From gagsl-py2 at yahoo.com.ar Mon Jan 28 13:54:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Jan 2008 10:54:05 -0800 (PST) Subject: PYS file References: Message-ID: On 28 ene, 13:05, azrael wrote: > A I Understood correctly, pyc files are compiled py scripts. Is it > possible to decomplite them. > I guess it's possible, but how hard is it. You want to get back the Python source? Look for the "decompyle" package. The last published release works for version 2.3; there is a paid service for newer versions (you send the .pyc, they give back the .py) At least you may use the dis module to disassemble the compiled .pyc into the correspoding VM instructions - if you are happy reading that... -- Gabriel Genellina From cokofreedom at gmail.com Tue Jan 15 05:45:18 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 15 Jan 2008 02:45:18 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> <478c868a$0$7040$426a34cc@news.free.fr> Message-ID: <5c0a472a-5ed6-4b34-9685-42f9a0a4145e@k39g2000hsf.googlegroups.com> A lecturer gave me the perfect answer to the question of speed. "You have two choices when it comes to programming. Fast code, or fast coders." From brochu121 at gmail.com Wed Jan 23 20:09:36 2008 From: brochu121 at gmail.com (David Brochu) Date: Wed, 23 Jan 2008 20:09:36 -0500 Subject: Increment Variable Name In-Reply-To: References: Message-ID: Basically what I am trying to do is pass each value from a list to the following line of code (where XXX is where I need to pass each value of the list tests = easygui.multchoicebox(message="Pick the test(s) you would like to run from the list below." , title="Validation Tests" ,choices=[XXX]) If i were to manually pass values to this line it would appear like : tests = easygui.multchoicebox(message="Pick the test(s) you would like to run from the list below." , title="Validation Tests" ,choices=["Test 1","Test 2", "Test 3"]) When I actually pass the list to the line of code, it works, however it doesn't really split the list by element. The desired output of this line of code would be a GUi that included a list consisting of each element from the passed list. Right now I can only get it to consist of a single element that contains every part of the list. Does this make sense? -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at marcher.name Wed Jan 9 04:02:57 2008 From: martin at marcher.name (Martin Marcher) Date: Wed, 09 Jan 2008 10:02:57 +0100 Subject: Collecting Rich Data Structures for students References: Message-ID: Paddy wrote: > On Jan 9, 2:19 am, "kirby.ur... at gmail.com" > wrote: >> Some have offered XML repositories, which I can well >> understand, but in this case we're looking specifically for >> legal Python modules (py files), although they don't have >> to be Latin-1 (e.g. the sushi types file might not have a >> lot of romanji). Are you asking for class SushiList(object): types = [sushi1, sushi2, sushi3, ...] I don't quite get that, any reference to the original discussion? /martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From gagsl-py2 at yahoo.com.ar Wed Jan 23 16:47:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 19:47:00 -0200 Subject: Trouble writing to database: RSS-reader References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> <4794e0f9$0$4429$426a74cc@news.free.fr> <739742b0-7d3d-4039-b793-ccefae4be721@1g2000hsl.googlegroups.com> Message-ID: En Wed, 23 Jan 2008 14:06:10 -0200, Arne escribi?: > On Jan 21, 11:25?pm, "Gabriel Genellina" > wrote: >> > On 21 Jan, 19:15, Bruno Desthuilliers > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> >> >> This should not prevent you from learning how to properly parse XML >> >> (hint: with an XML parser). XML is *not* a line-oriented format, so >> you >> >> just can't get nowhere trying to parse it this way. >> >> Try ElementTree instead; there is an implementation included with >> Python ? > > This look very interesting! But it looks like that no documents is > well-formed! I've tried several RSS-feeds, but they are eighter > "undefined entity" or "not well-formed". This is not how it should be, > right? :) Well, the RSS feed "should" be valid XML... Try a more forgiving parser like BeautifulStone, or preprocess the input with Tidy or a similar program before feeding it to ElementTree. -- Gabriel Genellina From apt.shansen at gmail.com Thu Jan 3 19:38:58 2008 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 3 Jan 2008 16:38:58 -0800 Subject: dictionary/hash and '1' versus 1 In-Reply-To: References: Message-ID: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> > As a Perl monkey in the process of learning Python, I just stepped on > the "'1' (string) is not the same as 1 (integer) in regards to keys for > dictionaries/hashes" landmine. Is there a good way to ensure that > numbers represented as strings or ints do not get mixed up as keys? > Well one important thing to learn while learning Python is that while the language is dynamically typed-- it is also /strongly/ typed. Every piece of data has an explicit type and it doesn't change unless you change it. It relies on duck typing a lot, and doesn't care if you mix and match (even partially) compatible types as long as the operations are there, but one type will always be distinct and remain that type until you explicitly convert it. A single integer is distinctly different from a sequence of characters in some encoding that may just happen to contain representations of a number.... so they'll hash differently :) One type will basically never implicitly convert into another type. To me, this sounds like the function should have converted the type explicitly on return. Or maybe you need to convert it explicitly on receipt. But if you are in a use-case where you really don't care and only want to hash strings, you can create a dict subclass easily that overrides __setitem__ to always str() the input. Check out the UserDict class. A similar method lets you make 'case-insensitive' dicts, for example. Were such a thing to happen automagically, you could get some weird situations, such as "assert (key in dict) == (key in dict.keys())" failing. Also, do 'if key in dict' instead of 'if dict.has_key(key)'. :) --Stephen -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Tue Jan 1 19:08:08 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 02 Jan 2008 01:08:08 +0100 Subject: Python Trajectory Module? In-Reply-To: <8ec8091e-8670-4d04-8198-c688c14576cf@p69g2000hsa.googlegroups.com> References: <8ec8091e-8670-4d04-8198-c688c14576cf@p69g2000hsa.googlegroups.com> Message-ID: <477AD5E8.3060007@gmail.com> squishywaffle at gmail.com wrote: > Greetings, > > I was wondering if there was a python Module/Library out there that > handles some trajectory/physics stuff like moving an object along a > straight path in an X,Y 2D (or 3D) plane or calculating parabolic > arcs. I'd really settle for just the moving of an object along a > straight line. > > I know it's not terribly difficult to implement this on your own, but > I'd rather not re-invent the wheel if someone else already did a good > job of it the first time. > > Thanks! > Depends on how detailed / graphical you've in mind. You might be interested in this: http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_animations_screenshots.html I've put a scanned version of my written notes about the trajectory example. No need for ODE in my very simple mind, because the functions describing the solution are already known. If you want to view the demos / animations, be sure to view the demo at the bottom first, because it explains the philosophy behind the program. Only 1 major feature is not described in this demo (because when I made the demo I had no solution for it, now I think I have) and that is : an integrated help / instruction / assignment / fill-in forms / judgement, specially for educational puposes. The program is not yet released, because I'm now cleaning it up and debugging it (by making demos ;-) cheers, Stef From lasses_weil at klapptsowieso.net Sun Jan 27 12:21:39 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 27 Jan 2008 18:21:39 +0100 Subject: Bash the Bush [WAS: Re: translating Python to Assembler] In-Reply-To: <13ppbnqcegh0993@corp.supernews.com> References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> <13pp2h2eugn8594@corp.supernews.com> <603npdF1oh17aU6@mid.uni-berlin.de> <13ppbnqcegh0993@corp.supernews.com> Message-ID: <479cbda4$0$9111$9b4e6d93@newsspool2.arcor-online.net> Grant Edwards wrote: > On 2008-01-27, Marc 'BlackJack' Rintsch wrote: >> The Dunning-Kruger effect is the phenomenon wherein people who have >> little knowledge think that they know more than others who have much >> more knowledge. >> [snip] > [snip as well] > ... must restist ... urge... to mention... Bush... > Well, I think that G.W. Bush knows perfectly well that he is not really up to the task. I still suspect that it never really was his decision to become president, if you follow me. /W (What do I care, he's not my president after all ... although, in a way ... YYAAAARRRGGGGHHHH!) From bignose+hates-spam at benfinney.id.au Thu Jan 31 15:51:56 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 01 Feb 2008 07:51:56 +1100 Subject: REALLY simple xml reader References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> <87tzkujeq6.fsf@benfinney.id.au> <13q3ri2707niqc6@corp.supernews.com> Message-ID: <87odb1k9ar.fsf@benfinney.id.au> 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: It's better to be as precise as possible so that failure can be unambiguous, than to have more-complex parsing rules that lead to ambiguity in implementation. 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. Given that, I think the choice of precise parsing rules that are simple to implement correctly (even if the rules themselves are necessarily complex) is a better one. -- \ "Those who will not reason, are bigots, those who cannot, are | `\ fools, and those who dare not, are slaves." ?"Lord" George | _o__) Gordon Noel Byron | Ben Finney From jimis at gmx.net Thu Jan 10 16:12:55 2008 From: jimis at gmx.net (Dimitrios Apostolou) Date: Thu, 10 Jan 2008 23:12:55 +0200 Subject: urllib2 rate limiting In-Reply-To: <87abndo1iz.fsf@merkury.smsnet.pl> References: <87abndo1iz.fsf@merkury.smsnet.pl> Message-ID: <200801102312.56680.jimis@gmx.net> On Thursday 10 January 2008 22:42:44 Rob Wolfe wrote: > Dimitrios Apostolou writes: > > On Thu, 10 Jan 2008, Rob Wolfe wrote: > >> Dimitrios Apostolou writes: > >>> P.S. And something simpler: How can I disallow urllib2 to follow > >>> redirections to foreign hosts? > >> > >> You need to subclass `urllib2.HTTPRedirectHandler`, override > >> `http_error_301` and `http_error_302` methods and throw > >> `urllib2.HTTPError` exception. > > > > Thanks! I think for my case it's better to override redirect_request > > method, and return a Request only in case the redirection goes to the > > same site. Just another question, because I can't find in the docs the > > meaning of (req, fp, code, msg, hdrs) parameters. To read the URL I > > get redirected to (the 'Location:' HTTP header?), should I check the > > hdrs parameter or there is a better way? > > Well, according to the documentation there is no better way. > But I looked into the source code of `urllib2` and it seems > that `redirect_request` method takes one more parameter > `newurl`, what is probably what you're looking for. ;) > > Regards, > Rob Cool! :-) Sometimes undocumented features provide superb solutions... I wonder if there is something similar for rate limiting :-s Thank you, Dimitris From gagsl-py2 at yahoo.com.ar Wed Jan 30 01:03:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jan 2008 22:03:34 -0800 (PST) Subject: Appropriate use of Property() References: <72c9d910-f19a-407d-91cf-5599fa3e73b3@h11g2000prf.googlegroups.com> Message-ID: On 29 ene, 23:17, noemailplease0... at gmail.com wrote: > Property() can be used to rid ourselves of the extra effort of using > two different methods (getAttrib() setAttrib()) for access of an > attribute without giving direct access to the attribute, thus making > it more elegant. So, the outsider using my module accesses the > attribute with the syntax 'Object.attrib', but since this syntax looks > as if he is accessing the attribute (rather than through a > descrtiptor), should we subscribe to this syntax only when the > attribute is both readable and writable? i.e., > if I have an attribute which I strongly believe would always be only > readable, should I go with the old style 'Object.getAttrib()'? > Would like to know different perspectives. I usually implement read only attributes using properties. Sometimes I may use getXXX() when it is slow to compute and I want to make explicit that it is a function call. Just my opinion. -- Gabriel Genellina From mr.cerutti at gmail.com Tue Jan 15 11:51:27 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Tue, 15 Jan 2008 11:51:27 -0500 Subject: Why this apparent assymetry in set operations? In-Reply-To: References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: <51302a8c0801150851k19cef902u1ce003e26dd26e83@mail.gmail.com> On Jan 15, 2008 11:07 AM, Skip Montanaro wrote: > > > Why is that? Doesn't the |= operator essentially map to an update() call? > > > > No, according to 3.7 Set Types, s | t maps to s.union(t). > > I was asking about the |= assignment operator which according to the > docs *does* map to the update method. Oops! You're right. That's surprising. This inconsistency is due to the c implementation. Internally, |= maps to the c function set_ior, while .update(...) maps to set_update. Both eventually call set_update_internal, which works fine when the operand is not a set. But set_ior specifically punts non-sets before calling set_update_internal. So this is a bug in set_update or in set_ior. They can't both be right. -- Neil Cerutti From mr.cerutti at gmail.com Fri Jan 4 11:34:26 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 4 Jan 2008 11:34:26 -0500 Subject: How Does This Static Variable Work? In-Reply-To: <4dc0cfea0801040717u9bc67ccr80447dc375502445@mail.gmail.com> References: <4dc0cfea0801040717u9bc67ccr80447dc375502445@mail.gmail.com> Message-ID: <51302a8c0801040834w6e9bf720l37d90a2884b19253@mail.gmail.com> On Jan 4, 2008 10:17 AM, Victor Subervi wrote: > Hi; > I read this example somewhere, but I don't understand it <:-) Can someone > please explain how static variables work? Or recommend a good how-to? > > > import random > > def randomwalk_static(last=[1]): # init the "static" var(s) > > rand = random.random() # init a candidate value > Simulating C's static local variables is the (in)famous application for this case of optimization in Python's design. Consult the following entry in the Python General Programming FAQ for further information. http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From hakim_ouaras at yahoo.com Sun Jan 13 15:54:03 2008 From: hakim_ouaras at yahoo.com (hakim ouaras) Date: Sun, 13 Jan 2008 12:54:03 -0800 (PST) Subject: NotImplimentedError Message-ID: <882739.52486.qm@web63705.mail.re1.yahoo.com> Hi, I am begining with python, I want to know what is the utility and how to use the expression "NotImplementedError". Thak you for your answers Hakim ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Wed Jan 30 17:59:55 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 30 Jan 2008 23:59:55 +0100 Subject: Dictionary Keys question In-Reply-To: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> Message-ID: FireNWater wrote: > I'm curious why the different outputs of this code. If I make the > dictionary with letters as the keys, they are not listed in the > dictionary in alphabetical order, but if I use the integers then the > keys are in numerical order. > > I know that the order of the keys is not important in a dictionary, > but I was just curious about what causes the differences. Thanks!! Currently the order of dict keys depend on the hash of the object. Try hash(1) and hash('a'). From gagsl-py2 at yahoo.com.ar Mon Jan 21 01:22:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 04:22:31 -0200 Subject: paging in python shell References: <31cb9b30-68f0-48ed-90f5-0e876fb08210@1g2000hsl.googlegroups.com> <87r6gkdn3x.fsf@benfinney.id.au> Message-ID: En Mon, 14 Jan 2008 21:05:38 -0200, Ben Finney escribi?: > To my knowledge there's nothing in the default Python shell that > enables what the OP is asking for. There are other Python shells, e.g. > Idle, ipython, or a Python window inside Emacs, that may be better > suited. Yes, there is. Thanks to Tim Roberts who menctioned that the builtin help system implements paging internally, I looked at it. It's easy to use (but maybe too late for the OP): Let Python determine the best pager available: import pydoc pydoc.pager(text) (it may pipe the text into an external program like less or more). Or explicitely use the builtin pager: import pydoc pydoc.ttypager(text) -- Gabriel Genellina From ganeshborse at gmail.com Tue Jan 29 22:58:26 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Tue, 29 Jan 2008 19:58:26 -0800 (PST) Subject: Replacing call to PyObject_CallObject with PyEval_CallFunction Message-ID: <5a99ab95-e225-4085-bce4-ea31da557d6d@j78g2000hsd.googlegroups.com> Hello Python Experts May you please help me on this change? I have following code: //================================================== typedef struct IOParams { char *ioString; long lionum; double dionum; float fionum; int nionum; } *pIOParams; // iterate thru list of variables, check if all req data is set int nCtr, ndtyp, ret = 0; IOParams inputVar; PyObject *pTuple = 0; pTuple = PyTuple_New(numofVars); for(nCtr = 0; nCtr < numofVars; nCtr++){ ndtyp = pEvalFunc->pExprVarsArray[nCtr].nDataType; switch(ndtyp){ case(INT_T): printf("%s=%d ",pEvalFunc- >pExprVarsArray[nCtr].szVarName,inputVar.nionum); PyTuple_SetItem(pTuple,nCtr,PyInt_FromLong(inputVar.nionum)); break; case(LONG_T): printf("%s=%ld ",pEvalFunc- >pExprVarsArray[nCtr].szVarName,inputVar.lionum); PyTuple_SetItem(pTuple,nCtr,PyLong_FromLong(inputVar.lionum)); break; case(FLOAT_T): printf("%s=%f ",pEvalFunc- >pExprVarsArray[nCtr].szVarName,inputVar.fionum); PyTuple_SetItem(pTuple,nCtr,PyFloat_FromDouble(inputVar.fionum)); break; case(DOUBLE_T): printf("%s=%f ",pEvalFunc- >pExprVarsArray[nCtr].szVarName,inputVar.dionum); PyTuple_SetItem(pTuple,nCtr,PyFloat_FromDouble(inputVar.dionum)); break; case(STRING_T): printf("%s=%s ",pEvalFunc- >pExprVarsArray[nCtr].szVarName,inputVar.ioString); PyTuple_SetItem(pTuple,nCtr,PyString_FromString(inputVar.ioString)); break; default: printf("\nUnknown data type [%d] for %s \n",ndtyp,pEvalFunc->pExprVarsArray[nCtr].szVarName); bUnknownDataType = true; break; } if(bUnknownDataType){ // got an unknown data type for a variable ret = -1; break; } } // all variables are set, call Python function if(ret == 0){ printf("\n"); PyObject *pResult = PyObject_CallObject(pEvalFunc- >pPyEvalFunction,pTuple); //================================================== In this, I am using IOParams struct to set values for the pTuple. The number & type of values to be set in pTuple change at runtime and therefore I had to put this for loop to set the value in this pTuple. Then I came to know about another function call PyEval_CallFunction(PyObject *obj, char *format, ...); This function call accepts variable number of arguments, like: PyEval_CallFunction(obj, "iii", a, b, c); Limitation with this is that "a", "b" and "c" are individual variables & are all known at compilation time. But, in may case, the variables with the values are in a vector of IOParams structs. How do I pass the elements populated in struct variables of this vector dynamically to PyEval_CallFunction, in the fashion somewhat like below? PyEval_CallFunction(obj, "iii", vector[0].ioparam- >nionum,vector[1].ioparam->nionum,vector[2].ioparam->nionum); PyEval_CallFunction(obj, "di", vector[0].ioparam- >fionum,vector[1].ioparam->nionum); PyEval_CallFunction(obj, "diiisis", vector[0].ioparam- >fionum,vector[1].ioparam->nionum,vector[2].ioparam- >nionum,vector[3].ioparam->nionum,vector[4].ioparam- >ioString,vector[5].ioparam->nionum,vector[6].ioparam->ioString); and so on..... These function calls are just few samples & not all of them. Any suggestions on this. Thanks & Regards. From steve at REMOVE-THIS-cybersource.com.au Thu Jan 17 18:36:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 17 Jan 2008 23:36:27 -0000 Subject: Creating unique combinations from lists References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> <478E6BA7.5030509@tim.thechases.com> <478F7471.9080909@tim.thechases.com> Message-ID: <13ovpjr8fl0bcd5@corp.supernews.com> On Thu, 17 Jan 2008 10:44:51 -0600, Reedick, Andrew wrote: >> -----Original Message----- >> From: Tim Chase [mailto:python.list at tim.thechases.com] Sent: Thursday, >> January 17, 2008 10:30 AM To: Reedick, Andrew >> Cc: breal; python-list at python.org; martin at v.loewis.de Subject: Re: >> Creating unique combinations from lists >> >> Yick...a nice demo of the power of eval, but definitely filed under the >> "Hack" heading > > You hurt my feeling. *sniffle* Given how late python > compiles/evaluates code blocks, I'm thinking that eval() is less hack > and more paradigm ..err.. pythonic. ;-) I see your smiley, but even so, do you have any idea how many times eval is used in the standard library? Not very often. $ pwd /usr/lib/python2.5 $ grep -r "eval(.*)" *.py | wc -l 20 Some of those twenty matches are false positives. I manually inspected them, and by my count there are just ten actual uses of eval: bdb.py: return eval(expr, globals, locals) dumbdbm.py: key, pos_and_siz_pair = eval(line) gettext.py: return eval('lambda n: int(%s)' % plural) gopherlib.py: _type_to_name_map[eval(name)] = name[2:] mhlib.py: def do(s): print s; print eval(s) os.py: eval(name) pdb.py: x = eval(arg, {}, {}) rexec.py: return eval(code, m.__dict__) rlcompleter.py: object = eval(expr, self.namespace) warnings.py: cat = eval(category) I haven't made any effort to determine how many of them are gaping great big security holes. -- Steven From grante at visi.com Wed Jan 30 20:30:40 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 31 Jan 2008 01:30:40 -0000 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> Message-ID: <13q2960err4db28@corp.supernews.com> On 2008-01-31, Daniel Fetchinson wrote: >> I do not understand why no one has answered the following question: >> >> Has anybody worked with Gene Expression Programming???? > > Hmmmmm, maybe because nobody did? Just a thought. It can also be that > everyone worked with it but everyone is part of a big conspiracy not > to answer any of your emails just to make you act weird. That's it then, now we're going to have to kill you... -- Grant Edwards grante Yow! Wait... is this a FUN at THING or the END of LIFE in visi.com Petticoat Junction?? From nagle at animats.com Sun Jan 6 11:06:35 2008 From: nagle at animats.com (John Nagle) Date: Sun, 06 Jan 2008 08:06:35 -0800 Subject: Cost of "unicode(s)" where s is Unicode Message-ID: <4780fb68$0$36341$742ec2ed@news.sonic.net> Does text = unicode(text) make a copy of a Unicode string, or is that essentially a free operation if the input is already Unicode? John Nagle From nytrokiss at gmail.com Sun Jan 13 05:38:26 2008 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 13 Jan 2008 11:38:26 +0100 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** In-Reply-To: <6a2ccd190801121107r7b728d09ve072909ba2863c04@mail.gmail.com> References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> <4788de48$0$26887$ecde5a14@news.coretel.net> <47890e3e$0$26886$ecde5a14@news.coretel.net> <6a2ccd190801121107r7b728d09ve072909ba2863c04@mail.gmail.com> Message-ID: <8a6b8e350801130238y1723cbcco37bdd8e7b60460ec@mail.gmail.com> When did this list become a politics dialog? Please keep on topic "Python"! Thanks James On Jan 12, 2008 8:07 PM, Joe Riopel wrote: > On Jan 12, 2008 2:00 PM, radiosrfun wrote: > > Whether we agree on "tactics" or not - if it come to a battlefield with the > > two of us - or any Americans there - we're still going to fight the same > > enemy - not each other. > > This is a good resource for starting Python > http://diveintopython.org/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com From siona at chiark.greenend.org.uk Thu Jan 17 07:55:17 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 17 Jan 2008 12:55:17 +0000 (GMT) Subject: Interesting Thread Gotcha References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >Of course start_new_thread could throw an error if it got nothing callable >as first argument. No idea why it doesn't. It does: >>> thread.start_new_thread(None, None) Traceback (most recent call last): File "", line 1, in ? TypeError: first arg must be callable -- \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 Rens.Duijsens at gmail.com Sat Jan 26 19:40:50 2008 From: Rens.Duijsens at gmail.com (Dox33) Date: Sat, 26 Jan 2008 16:40:50 -0800 (PST) Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> <87dd811e-3095-41d0-80fd-7312338e5254@i3g2000hsf.googlegroups.com> Message-ID: <489b6fc5-e871-425e-b242-45be618fc9f4@n20g2000hsh.googlegroups.com> Hello Mike, Thanks for your reply. Since I momentarily do not have the ability to build a new python executable, I would like to ask for your help in this case. Are you able to supply me with a corrected version? Friendly greetings Rens Duijsens On 26 jan, 16:50, Mike Kent wrote: > On Jan 26, 7:23 am, Dox33 wrote: > > > > > > > I ran into a very strange behaviour of raw_input(). > > I hope somebody can tell me how to fix this. > ===CUT=== > > *** Thirst, redirect stderr to file, STRANGE behaviour...... > > From the command prompt I run: > > python script.py 2> stderr_catch.txt > > This should redirect strerr to the file and stdout should stay on the > > screen. > > > But..... What happens? > > After a few 'enter' keys, on screen apears: > > 1: This is the print statement. > > 3: This is a possible solution. > > > WHERE IS THE SECOND LINE? > > It is in the file stderr_catch.txt!!! > > > **** See the problem? > > Please Tell me? Why is the prompt produced by raw_input() printed to > > the error channel? It should be stdout, just as the print statement > > does. > > I recently ran into this behaviour myself, and reported it both here > and to the python-dev mailing list. ?Seehttp://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > It turns out that *if* you don't have GNU readline installed, Python > falls back to its own implementation of readline, which is hard-coded > to send the prompt output to stderr. ?Guido agreed that this is wrong, > and a bug for it has been entered into the Python bug tracking > database. > > Your workaround until this bug is fixed is to install GNU readline, > and rebuild your python installation to use it rather than the fall- > back version.- Tekst uit oorspronkelijk bericht niet weergeven - > > - Tekst uit oorspronkelijk bericht weergeven - From over at thepond.com Sun Jan 27 06:23:20 2008 From: over at thepond.com (over at thepond.com) Date: Sun, 27 Jan 2008 11:23:20 GMT Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> Message-ID: >> >> >ajaksu at Belkar:~$ ndisasm error.txt >> >00000000 54 push sp >> >00000001 686973 push word 0x7369 >> >00000004 206973 and [bx+di+0x73],ch >> >00000007 206E6F and [bp+0x6f],ch >> >0000000A 7420 jz 0x2c >> >0000000C 61 popa >> >0000000D 7373 jnc 0x82 >> >0000000F 656D gs insw >> >00000011 626C65 bound bp,[si+0x65] >> >00000014 722E jc 0x44 >> >00000016 2E db 0x2E >> >00000017 2E db 0x2E >> >00000018 0A db 0x0A >> >> >:/ >> >> not sure what you're saying. Sure looks like assembler to me. Take the >> '54 push sp'. The 54 is an assembler opcode for push and the sp is >> the stack pointer, on which it is operating. > >go troll somewhere else (you obviously don't know anything about >assembler and don't want to learn anything about Python). > >-- bjorn before you start mouthing off, maybe you should learn assembler. If you're really serious, go to the Intel site and get it from the horses mouth. The Intel manual on assembler lists the mneumonics as well as the opcodes for each instruction. It's not called the Intel Machine Code and Assembler Language Manual. It's the bible on assembly language, written by Intel. If you're not so serious, here's a URL explaining it, along with an excerpt from the article: http://en.wikipedia.org/wiki/X86_assembly_language Each x86 assembly instruction is represented by a mnemonic, which in turn directly translates to a series of bytes which represent that instruction, called an opcode. For example, the NOP instruction translates to 0x90 and the HLT instruction translates to 0xF4. Some opcodes have no mnemonics named after them and are undocumented. However processors in the x86-family may interpret undocumented opcodes differently and hence might render a program useless. In some cases, invalid opcodes also generate processor exceptions. As far as this line from your code above: 00000001 686973 push word 0x7369 68 of 686973 is the opcode for PUSH. Go on, look it up. The 6973 is obviously the word address, 0x7369. Or, do you think that's coincidence? Don't fucking tell me about assembler, you asshole. I can read disassembled code in my sleep. From hnessenospam at yahoo.com Thu Jan 24 14:50:42 2008 From: hnessenospam at yahoo.com (hnessenospam at yahoo.com) Date: Thu, 24 Jan 2008 11:50:42 -0800 (PST) Subject: Duplicating a variable References: <1f5684fd-d8e6-4429-953f-b57362eeb4d1@s19g2000prg.googlegroups.com> Message-ID: On Jan 24, 9:55 am, bearophileH... at lycos.com wrote: > > If your variable contains a list, then you can copy it like this: > > >>> l1 = [1, 2, 3] > >>> l2 = l1[:] > >>> l2[1] = 4 > > As you can see now they are two distinct lists: > > >>> l1 > [1, 2, 3] > >>> l2 > > [1, 4, 3] > > If you want to copy any kind of object you can use the copy function > (instead of a simpler copy method that's absent): > > >>> d1 = {1:2, 3:4} > >>> from copy import copy > >>> d2 = copy(d1) > >>> d1[1] = 5 > >>> d1 > {1: 5, 3: 4} > >>> d2 > > {1: 2, 3: 4} > > But as you can see copy works only one level deep: > > >>> d3 = {1:[1], 3:4} > >>> d3 > {1: [1], 3: 4} > >>> d4 = copy(d3) > >>> d3[1][0] = 2 > >>> d3 > {1: [2], 3: 4} > >>> d4 > > {1: [2], 3: 4} > > To copy all levels you need deepcopy: > > >>> from copy import deepcopy > >>> d5 = deepcopy(d3) > >>> d3[1][0] = 5 > >>> d3 > {1: [5], 3: 4} > >>> d4 > {1: [5], 3: 4} > >>> d5 > > {1: [2], 3: 4} > > Bye, > bearophile Works great, it is exactly what I needed thanks! -Hans From aisaac at american.edu Fri Jan 25 13:46:40 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 25 Jan 2008 18:46:40 GMT Subject: find minimum associated values In-Reply-To: References: Message-ID: Steven Bethard wrote: > [3rd approach] Seems "pretty" enough to me. ;-) I find it most attractive of the lot. But its costs would rise if the number of values per object were large. Anyway, I basically agree. Thanks, Alan From mwm-keyword-python.b4bdba at mired.org Thu Jan 10 14:41:35 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 14:41:35 -0500 Subject: What is "lambda x=x : ... " ? In-Reply-To: References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> <20080110134335.37cf5377@mbook.mired.org> Message-ID: <20080110144135.20e55ec3@bhuda.mired.org> On Thu, 10 Jan 2008 19:59:23 +0100 Fredrik Lundh wrote: > Mike Meyer wrote: > >> What does "y=y" and "c=c" mean in the lambda function? > > > > Older versions of python didn't make variables in an outer scope > > visible in the inner scope. This was the standard idiom to work > > around that. > lexically scoped free variables and object binding are two different > things, and have different semantics. the former does not always > replace the latter. And? http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From grahn+nntp at snipabacken.dyndns.org Thu Jan 17 04:41:23 2008 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 17 Jan 2008 09:41:23 GMT Subject: Great Python books for the beginner References: Message-ID: On Sat, 12 Jan 2008 01:03:42 -0600, Landon wrote: > Hi, I'm a freshman in college and I'm going to be taking an intro to > programming course next semester which mainly uses Python, so I > thought it might be a good time to pick up Python beyond the scope of > the class as well. The text book for this class is Python for the > Absolute Beginner or something similar to that name. > > I was wondering if anyone had any opinions on what other titles I > could look into since this one seems from a glance at reviews to be > teaching mainly through game programming (a topic I'm not too > interested in) or if this one is a quality book by itself. I like Alex Martelli's book, published by O'Reilly a few years ago (I forget its name). It is not too thick -- books which are too thick to stay open are useless IMHO -- and it's not a beginner programmer's book. (You'll have a text book, so it will teach programming in general and simple Python programming, right?) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From peterbe at gmail.com Tue Jan 15 09:30:17 2008 From: peterbe at gmail.com (Peter Bengtsson) Date: Tue, 15 Jan 2008 06:30:17 -0800 (PST) Subject: ElementTree and namespaces in the header only Message-ID: <2c769fe0-8add-4aa1-9657-b8ee5f76cb91@k39g2000hsf.googlegroups.com> Here's my code (simplified): NS_URL = 'http://www.snapexpense.com/atom_ns#' ElementTree._namespace_map[NS_URL] = 'se' def SEN(tag): return "{%s}%s" % (NS_URL, tag) root = Element('feed', xmlns='http://www.w3.org/2005/Atom') root.set('xmlns:se', NS_URL) entry = SubElement(root, 'entry') SubElement(root, 'title').text = 'Title' SubElement(entry, SEN('category')).text = 'Category' And here's the generated XML string: Category Title But surely the xmlns:se attribute on the tag is excessive since the namespace (by the URI) is already defined in the tag. How do I set non-default namespace tags in elements without the automatic xmlns:se attribute repeated each time? From sjmachin at lexicon.net Wed Jan 2 04:44:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 2 Jan 2008 01:44:47 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> Message-ID: On Jan 2, 7:45 pm, mario wrote: > On Jan 2, 9:30 am, "Martin v. L?wis" wrote: > > > Use "mbcs" in the second call, not "mcbs". > > Ooops, sorry about that, when i switched to test it in the interpreter > I mistyped "mbcs" with "mcbs". But remark I did it consistently ;-) > I.e. it was still teh same encoding, even if maybe non-existant.. ? > > If I try again using "mbcs" consistently, I still get the same error: > > $ python > Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> unicode('', 'mbcs') > u'' > >>> unicode('', 'mbcs').encode('mbcs') > > Traceback (most recent call last): > File "", line 1, in > LookupError: unknown encoding: mbcs Two things for you to do: (1) Try these at the Python interactive prompt: unicode('', 'latin1') unicode('', 'mbcs') unicode('', 'raboof') unicode('abc', 'latin1') unicode('abc', 'mbcs') unicode('abc', 'raboof') (2) Read what the manual (Library Reference -> codecs module -> standard encodings) has to say about mbcs. From gagsl-py2 at yahoo.com.ar Wed Jan 30 23:35:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 31 Jan 2008 02:35:23 -0200 Subject: A design problem References: <5504f9ac0801301957l555d88d6m741c1cb2850cd53f@mail.gmail.com> Message-ID: En Thu, 31 Jan 2008 01:57:41 -0200, Dan Upton escribi?: > Or: How to write Python like a Python programmer, not a Java > programmer. This will be a little long-winded... > > So I just recently started picking up Python, mostly learning the new > bits I need via Google and otherwise cobbling together the functions > I've already written. It occurred to me though that one of my > programs was still probably written very much like I would in Java > (part of the reason I'm picking up Python is I'm tired of my coworkers > making fun of me for writing parsing/reformatting programs in Java). Maybe you've already read this, but I'll post the links anyway: http://dirtsimple.org/2004/12/python-is-not-java.html http://dirtsimple.org/2004/12/java-is-not-python-either.html > Anyway, basically here's the problem I have: > > -Fork off n copies of a program, where n is a command line parameter, > and save their PIDs. The way I've been accomplishing this is > basically: > > processes=[] > for i in range(numProcs): > pid=os.fork() > if pid == 0: > # do the forking > else: > processes.append(pid) Looks fine to me. > -Every so much time (say, every second), I want to ask the OS > something about that process from under /proc/pid (this is on Linux), > including what core it's on. > while 1: > for i in processes: > file = open("/proc/"+str(i)+"/stat") (I hope there is a time.sleep(1) after processing that) - don't use file as a variable name, you're shadowing the builtin file type. - "i" is very much overloaded as a variable name everywhere... I'd use pid instead - string interpolation looks better (and is faster, but that's not so relevant here) for pid in processes: statfile = open("/proc/%d/stat" % pid) >> From that, one of the pieces of data I'll get is which core it's > running on, which then will prompt me to open another file. > Ultimately, I want to have n files, that are a bunch of lines: > corenum data1 data2 ... > corenum data1 data2 ... > ... > > and so on. The way I was going to approach it was to every time > through the loop, read the data for one of the processes, open its > file, write out to it, and close it, then do the same for the next > process, and so on. Really though I don't need to be able to look at > the data until the processes are finished, and it would be less I/O, > at the expense of memory, to just save all of the lists of data as I > go along and then dump them out to disk at the end of the Python > program's execution. I feel like Python's lists or dictionaries > should be useful here, but I'm not really sure how to apply them, > particularly in a "Python-like" way. > > For anybody who made it all the way through that description ;) any > suggestions? The simplest solution would be to use a tuple to store a row of data. You know (implicitely) what every element contains: the first item is "corenum", the second item is "data1", the third item is "data2" and so on... (based on your example above). Collect those tuples (rows) into a list (one list per process), and collect all lists into a dictionary indexed by pid. That is, at the beginning, create an empty dictionary: info = {} After each forking, at the same time you save the pid, create the empty list: info[pid] = [] After you read and process the /proc file to obtain what you want, apend a new element to that list: info[pid].append((corenum, data1, data2, ...)) (notice the double parenthesis) At the end, write all that info on disk. The csv module looks like a good candidate: import csv for pid in processes: writer = csv.writer(open("process-%d.csv" % pid, "wb")) writer.writerows(info[pid]) That's all -- Gabriel Genellina From lloyd at paisite.com Sat Jan 5 13:41:02 2008 From: lloyd at paisite.com (lloyd at paisite.com) Date: Sat, 5 Jan 2008 13:41:02 -0500 (EST) Subject: Python web aps - A matter of security Message-ID: <53318.192.168.1.35.1199558462.webmail@192.168.1.35> Hello, I'm developing a Python-based web ap, but don't understand how to best organize the modules and set permissions for maximum security. Here's how the Python code for my ap is organized: 1) I have Python modules in a project directory. The path to that directory is in a *.pth file in the .*/pythonx-y/site-packages directory. Question: who should own these modules; what groups should have access, and how should permissions be set? 2) I have high-level modules that import the worker-bee modules in the web root directory tree that are called by the webserver. Questions: who should own these modules, what groups should have access, and how should permissions be set? 3) Is there a better way to organize my Python modules? Are there other security issues I should heed? Many thanks, Lloyd -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Fri Jan 11 06:15:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jan 2008 12:15:28 +0100 Subject: help for installing PIL In-Reply-To: <32600.51914.qm@web60520.mail.yahoo.com> References: <32600.51914.qm@web60520.mail.yahoo.com> Message-ID: Chan Kuang Lim wrote: > I'm using Window XP. How to install PIL 1.1.6? The Python i installed, > is come with Plone. So, is it ok? Thank you. Just run the appropriate installer for your Python version: http://www.pythonware.com/products/pil as the page says, "If the Windows installer cannot find a Python interpreter, you may have to register your interpreter", and links to this page: http://effbot.org/zone/python-register.htm From hakim_ouaras at yahoo.com Fri Jan 18 13:13:19 2008 From: hakim_ouaras at yahoo.com (hakim ouaras) Date: Fri, 18 Jan 2008 10:13:19 -0800 (PST) Subject: merge 2 arrays Message-ID: <199547.52014.qm@web63701.mail.re1.yahoo.com> Hi all, I have two dictionays like these: dict1={"id1":[1,2,3,4,5],"id2":[1,2,3,1,3], "var1":[10,11,12,13,14]} dict2={"id2":[1,2,3,4,], "var2":[20,21,22,23]} I want to replace the values of dict1["var1"] with those of dict["var2"] with taking count the correspondance between dict1["id1"] and dict2["id2"]. result that I want to have is like this: dict1={"id1":[1,2,3,4,5],"id2":[1,2,3,1,3], "var1":[20,21,22,20,22]} Thak you Hakim ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Fri Jan 25 15:01:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Jan 2008 20:01:31 GMT Subject: is possible to get order of keyword parameters ? References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> <5b6e2bc6-8136-4e3a-8bf2-bb6d689d6110@s8g2000prg.googlegroups.com> Message-ID: rndblnch wrote: > the following example should also > work: > size = Point(width=23, height=45) > w, h = size > So you want the unpacking to depend on how the Point was initialised! Aaargh! From bborcic at gmail.com Wed Jan 23 05:02:13 2008 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 23 Jan 2008 11:02:13 +0100 Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? In-Reply-To: References: Message-ID: I am surprised nobody pointed out explicitely that True==1 and False==0 so that for instance 5*(True+True)==10 and even (but implementation-dependent) : 5*(True+True) is 10 BB From goldtech at worldpost.com Fri Jan 25 08:48:24 2008 From: goldtech at worldpost.com (goldtech) Date: Fri, 25 Jan 2008 05:48:24 -0800 (PST) Subject: Python ADO Date Time database fields References: Message-ID: <30222931-7fa9-4dd5-bdc8-d1313c37a144@i3g2000hsf.googlegroups.com> snip > > try this: > > val = oRS.Fields(dt).Value > print type(val) this gives: > print float(val) yes, it gives 0.0 But there should be a way to print what is *actually in the field*. When I open the DB table in Access I see: 12:00:00 AM. That's what I want - the value, and the form of the value, exactly as seen in the field... As an aside, the roughly eqivalent code in Perl will print the "12:00:00 AM" - (the trick for the date types in Perl is to add: "use Win32::OLE::Variant;" There has to be a way:^) snip From mario at ruggier.org Thu Jan 3 09:52:15 2008 From: mario at ruggier.org (mario) Date: Thu, 3 Jan 2008 06:52:15 -0800 (PST) Subject: unicode(s, enc).encode(enc) == s ? References: <5e49e7e6-f2b3-4c9f-9dec-e5f01f12d59a@e4g2000hsg.googlegroups.com> <4773f0de$0$15825$9b622d9e@news.freenet.de> <7cb20641-ab33-4818-a911-80c684cb9792@q77g2000hsh.googlegroups.com> <4775AC6B.8070109@v.loewis.de> <1310677e-51ec-49f2-9709-196dcc4e1ac9@e4g2000hsg.googlegroups.com> <477BF54E.7090000@v.loewis.de> Message-ID: On Jan 2, 9:34 pm, "Martin v. L?wis" wrote: > > In any case, it goes well beyond the situation that triggered my > > original question in the first place, that basically was to provide a > > reasonable check on whether round-tripping a string is successful -- > > this is in the context of a small utility to guess an encoding and to > > use it to decode a byte string. This utility module was triggered by > > one that Skip Montanaro had written some time ago, but I wanted to add > > and combine several ideas and techniques (and support for my usage > > scenarios) for guessing a string's encoding in one convenient place. > > Notice that this algorithm is not capable of detecting the ISO-2022 > encodings - they look like ASCII to this algorithm. This is by design, > as the encoding was designed to only use 7-bit bytes, so that you can > safely transport them in Email and such (*) Well, one could specify decode_heuristically(s, enc="iso-2022-jp") and that encoding will be checked before ascii or any other encoding in the list. > If you want to add support for ISO-2022, you should look for escape > characters, and then check whether the escape sequences are among > the ISO-2022 ones: > - ESC ( - 94-character graphic character set, G0 > - ESC ) - 94-character graphic character set, G1 > - ESC * - 94-character graphic character set, G2 > - ESC + - 94-character graphic character set, G3 > - ESC - - 96-character graphic character set, G1 > - ESC . - 96-character graphic character set, G2 > - ESC / - 96-character graphic character set, G3 > - ESC $ - Multibyte > ( G0 > ) G1 > * G2 > + G3 > - ESC % - Non-ISO-2022 (e.g. UTF-8) > > If you see any of these, it should be ISO-2022; see > the Wiki page as to what subset may be in use. > > G0..G3 means what register the character set is loaded > into; when you have loaded a character set into a register, > you can switch between registers through ^N (to G1), > ^O (to G0), ESC n (to G2), ESC o (to G3) (*) OK, suppose we do not know the string is likely to be iso-2022, but we still want to detect it if it is. I have added a "may_do_better" mechanism to the algorithm, to add special checks on a *guessed* algorithm. I am not sure this will not however introduce more or other problems than the one it is addressing... I have re-instated checks for iso-8859-1 control chars (likely to be cp1252), for special symbols in iso-8859-15 when they occur in iso-8859-1 and cp1252, and for the iso-2022-jp escape sequences. To flesh out with other checks is mechanical work... If you could take a look at the updated page: > >http://gizmojo.org/code/decodeh/ I still have issues with what happens in situations when for example a file contains iso-2022 esc sequences but is anyway actally in ascii or utf-8? e.g. this mail message! I'll let this issue turn for a little while... > > I will be very interested in any remarks any of you may have! > > From a shallow inspection, it looks right. I would have spelled > "losses" as "loses". Yes, corrected. Thanks, mario From http Mon Jan 21 14:38:34 2008 From: http (Paul Rubin) Date: 21 Jan 2008 11:38:34 -0800 Subject: index of min element of sequence References: Message-ID: <7xfxwrt1dx.fsf@ruckus.brouhaha.com> Neal Becker writes: > What's a good/fast way to find the index of the minimum element of a > sequence? (I'm fairly sure sorting the sequence is not the fastest > approach) Python 2.5 (untested): from operator import itemgetter minindex = min(enumerate(seq), key=itemgetter(1))[1] From fredrik at pythonware.com Thu Jan 3 13:26:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 19:26:45 +0100 Subject: Treating a unicode string as latin-1 In-Reply-To: <5u4mutF1g0ccrU1@mid.uni-berlin.de> References: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> <5u4mutF1g0ccrU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> I would think it more likely that he wants to end up with u'Bob\u2019s >> Breakfast' rather than u'Bob\x92s Breakfast' although u'Dog\u2019s dinner' >> seems a probable consequence. > > If that's the case, he should read the file as string, de- and encode it > (probably into a StringIO) and then feed it to the parser. some alternatives: - clean up the offending strings: http://effbot.org/zone/unicode-gremlins.htm - turn the offending strings back to iso-8859-1, and decode them again: u = u'Bob\x92s Breakfast' u = u.encode("iso-8859-1").decode("cp1252") - upgrade to ET 1.3 (available in alpha) and use the parser's encoding option to override the file's encoding: parser = ET.XMLParser(encoding="cp1252") tree = ET.parse(source, parser) From joa at hrz.tu-chemnitz.de Wed Jan 16 03:34:33 2008 From: joa at hrz.tu-chemnitz.de (Andre) Date: Wed, 16 Jan 2008 09:34:33 +0100 Subject: Generic string import like in strptime? Message-ID: Hi there Is there a function like strptime, which takes a string and converts it into an array depending on a format string I provide. Like: >>> a = '3456\tblub-blib.0.9' >>> b = '%d\t%s-%s.%f' >>> c = mysticalfunction(a,b) >>> print c [3456,'blub','blib',0.9] Many thanks Andre From http Sat Jan 12 14:03:53 2008 From: http (Paul Rubin) Date: 12 Jan 2008 11:03:53 -0800 Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> <354c74f6-6e56-4e41-a686-56239aa4cea9@f47g2000hsd.googlegroups.com> <7x8x2uj3yb.fsf@ruckus.brouhaha.com> <0ad68aa8-735d-4cf0-b17a-d1f2be6af652@f47g2000hsd.googlegroups.com> Message-ID: <7x1w8mj27a.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > > Nothing else should have direct access to the list. > Impossible to guarantee in Python. If you do, the reference to you does. Well, ok. Nothing else should USE that access. From steve at REMOVE-THIS-cybersource.com.au Thu Jan 31 04:55:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 31 Jan 2008 09:55:15 -0000 Subject: list traversal and remove References: Message-ID: <13q36o3ir4p1bbb@corp.supernews.com> On Wed, 30 Jan 2008 23:49:46 -0800, digisatori at gmail.com wrote: > I supposed the below code will print seven 2 and generate the list li > without 2. > Strangely it only print four 2. If you change the number of 2 in the > list, the results are all beyond expectation. I know the other way to > achieve the expected goal, but why this is happening? Could somebody > enlight me? Do not modify a list at the same time that you are traversing it. If you look at the archives (say, on Google Groups, or any number of other places), this topic was just discussed yesterday and earlier today. See the thread with subject line: "Removal of element from list while traversing causes the next element to be skipped" As for why it is happening... you have code that looks like this: for x in li: if x == 2: print x li.remove(x) Consider that "under the hood", the for-loop looks something like this: i = 0 while i < the length of the list: set x equal to the item in the i-th position execute the loop block of code i += 1 If you start deleting or inserting items in the middle of the loop, the index won't be pointing where you expect. -- Steven From guptaabhishek1983 at gmail.com Wed Jan 23 06:29:02 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Wed, 23 Jan 2008 03:29:02 -0800 (PST) Subject: application error in python Message-ID: <75de8afc-4295-40b5-b9b7-af19ef5264e6@t1g2000pra.googlegroups.com> hello group i am working on a project where most of the code has been written in c++ but the web component is written in python. Initially we have been using python2.4 and vs.net2003 but recently we decided to move ahead with python2.5 and vs.net2005. the problem that has been haunting me for while now is when i am trying to access a few functions in c++ through python by building .pyd extension, python.exe crashes saying an application error has occured any clues why this happened as everythiing was working well in .net2003 and python2.4 thanks abhishek From hat at se-162.se.wtb.tue.nl Mon Jan 14 02:47:55 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 14 Jan 2008 08:47:55 +0100 Subject: where do my python files go in linux? References: Message-ID: On 2008-01-12, Jorgen Bodde wrote: > Question 1. Where do I put the bulk of python scripts in a normal > linux environment? > Question 2. Should I use *.pyc rather then *.py files to speed up > executing as the user cannot write to /usr/bin or any other dir in the > system and everytime my app runs it will recompile it > > Thanks for any advice or maybe a good tutorial how to set up files in > a linux environment Rather than re-inventing the wheel, please have a look at distutils: http://docs.python.org/lib/module-distutils.html It does most if not all of the things you want to do. If you want something more advanced, read about eggs. Sincerely, Albert From asmodai at in-nomine.org Sun Jan 13 05:43:11 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sun, 13 Jan 2008 11:43:11 +0100 Subject: Mailinglist/newsgroup gateway In-Reply-To: <5504f9ac0801121427k21137ecfvd9755b0a8b7a68e2@mail.gmail.com> References: <5504f9ac0801121427k21137ecfvd9755b0a8b7a68e2@mail.gmail.com> Message-ID: <20080113104311.GM75977@nexus.in-nomine.org> -On [20080112 23:30], Dan Upton (upton at virginia.edu) wrote: >Why was this ever on the Python list (I assume it started as spam), >and why on earth has it continued? The Python mailinglist is a gateway to/from comp.lang.python for all I know. So anything idiotic getting posted there might make its way unto the mailing list. I wonder what the ratio of newsgroup posters versus mailinglist posters is nowadays. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Faith, it seems, is not without irony... From sjmachin at lexicon.net Tue Jan 15 04:28:55 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 15 Jan 2008 01:28:55 -0800 (PST) Subject: Append zip files together, just get the binary data (in memory) References: <53f66038-ccc3-4c3d-97b2-fa5deb148809@d4g2000prg.googlegroups.com> <5v27oiF1kavhlU1@mid.uni-berlin.de> Message-ID: On Jan 15, 9:58 am, "Diez B. Roggisch" wrote: > Module StringIO is your friend. and cStringIO is your ....? From flossy at bobbsey_twins.com Sun Jan 13 22:13:06 2008 From: flossy at bobbsey_twins.com (MooJoo) Date: Sun, 13 Jan 2008 19:13:06 -0800 Subject: Great Python books for the beginner References: <2008011220494516807-generalcody@gmailcom> Message-ID: In article <2008011220494516807-generalcody at gmailcom>, GeneralCody wrote: > On 2008-01-12 08:03:42 +0100, Landon said: > > > Hi, I'm a freshman in college and I'm going to be taking an intro to > > programming course next semester which mainly uses Python, so I > > thought it might be a good time to pick up Python beyond the scope of > > the class as well. The text book for this class is Python for the > > Absolute Beginner or something similar to that name. > > > > I was wondering if anyone had any opinions on what other titles I > > could look into since this one seems from a glance at reviews to be > > teaching mainly through game programming (a topic I'm not too > > interested in) or if this one is a quality book by itself. > > I would definetly go for Learning Python first, maybe Apress "Python, > from novice to Professional" as well... > > Second those suggestions. Both are excellent books for the novice with details more experienced pythonistas can use. Although it is an excellent book, stay away from the Python Cookbook for now. Appreciating it requires a good working knowledge first. If you do get Learning Python, make sure its the 3rd edition that just became available. It covers the current 2.5 release. From celoserpa at gmail.com Thu Jan 24 06:29:07 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Thu, 24 Jan 2008 09:29:07 -0200 Subject: Navigating through python packages Message-ID: <1e5bcefd0801240329i51e54153xabf9e84a9f98756b@mail.gmail.com> Hello, I work with Zope and Plone, hence I deal with lots of eggs and python packages and modules. I'm always opening source files inside packages, closing them, opening again, searching through them... The main issue here is the level of directory nesting.. you need to write a lot (in emacs) or click too much (in Eclispe) to open python source file. Take the following dir structure for a particular package in my Plone buildout eggs/plone.app.portlets.portlets.1.0.5/plone/app/portlets/portlets/news ... this is insane! How do you guys deal with this issue so as to make life easier in this aspect? Thanks, Marcelo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.desthuilliers at gmail.com Sun Jan 13 13:03:53 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 13 Jan 2008 10:03:53 -0800 (PST) Subject: i am new guy for this discussion group References: Message-ID: <2c96a1ab-207c-4671-a529-358bdb51d4fc@f10g2000hsf.googlegroups.com> On Jan 13, 3:03 pm, "bill.wu" wrote: > i am new guy to learn python,also for this discussion group, i am > chinese. > nice to meet you, everyone. Hi and welcome onboard. If you're new to programming in general, you may want to join the tutor mailing-list. http://mail.python.org/mailman/listinfo/tutor If you're already a programmer, you may want to follow the offficial tutorial, then probably diveintopython: http://docs.python.org/tut/tut.html http://www.diveintopython.org/ HTH From vadivel59 at gmail.com Wed Jan 16 08:34:15 2008 From: vadivel59 at gmail.com (vadivel59 at gmail.com) Date: Wed, 16 Jan 2008 05:34:15 -0800 (PST) Subject: welcome to billa Message-ID: <66dd7663-d9c8-4579-87de-ecd9400123fa@i29g2000prf.googlegroups.com> welcome to billa ////////////////////////////////////////////////////////////// http://billaremix.blogspot.com/ ////////////////////////////////////////////////////////////// From bignose+hates-spam at benfinney.id.au Sun Jan 27 19:49:30 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 28 Jan 2008 11:49:30 +1100 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> Message-ID: <87d4rm93l1.fsf@benfinney.id.au> "Andr?" writes: > Personally, I like the idea you suggest, with the modification that I > would use "." instead of "@", as in > > class Server(object): > def __init__(self, .host, .port, .protocol, .bufsize, .timeout): > pass -1. That leading dot is too easy to miss when looking over the code. -- \ "Intellectual property is to the 21st century what the slave | `\ trade was to the 16th." ?David Mertz | _o__) | Ben Finney From piet at cs.uu.nl Wed Jan 2 08:25:48 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 02 Jan 2008 14:25:48 +0100 Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> Message-ID: >>>>> mario (M) wrote: >M> $ python >M> Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) >M> [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin >M> Type "help", "copyright", "credits" or "license" for more information. >>>>> unicode('', 'mbcs') >M> u'' >>>>> unicode('abc', 'mbcs') >M> Traceback (most recent call last): >M> File "", line 1, in >M> LookupError: unknown encoding: mbcs >>>>> >M> Hmmn, strange. Same behaviour for "raboof". Apparently for the empty string the encoding is irrelevant as it will not be used. I guess there is an early check for this special case in the code. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From bladedpenguin at gmail.com Sat Jan 26 17:02:09 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Sat, 26 Jan 2008 14:02:09 -0800 (PST) Subject: Doesn't know what it wants References: <13plo358k5rf059@corp.supernews.com> Message-ID: <8261dbc4-4858-45cc-9acf-f527482c2b59@e10g2000prf.googlegroups.com> On Jan 26, 2:52 am, John Machin wrote: > On Jan 26, 6:25 pm, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Fri, 25 Jan 2008 22:53:16 -0800, John Machin wrote: > > > On Jan 26, 5:32 pm, Jeroen Ruigrok van der Werven > > nomine.org> wrote: > > >> -On [20080126 06:26], Tim Rau (bladedpeng... at gmail.com) wrote: > > > >> >Line 147 reads: > > >> > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) > > > >> I think it expects something like: > > > >> # badly named variable, pick something better depending on context > > >> temp = vec2d(0, 0) > > >> cp.cpMomentForCircle(self.mass, .2, 0, temp) > > > > That *cannot* give a different result in Python. The called function > > > will be presented with *exactly* the same object as the OP's code does. > > > Not quite. Look carefully at the difference. > > > The OP's code calls vec2d with a single tuple argument (0,0). Jeroen's > > version calls vec2d with two int arguments, 0 and 0. > > > We don't know whether vec2d will treat those two things the same or not. > > That was Jeroen's 2nd problem; I was addressing his first problem > (thinking that introducing a temp variable would work some magic). > > Google is your friend: > """ > class vec2d(ctypes.Structure): > """2d vector class, supports vector and scalar operators, > and also provides a bunch of high level functions > """ > __slots__ = ['x', 'y'] > > def __init__(self, x_or_pair, y = None): > > if y == None: > self.x = x_or_pair[0] > self.y = x_or_pair[1] > else: > self.x = x_or_pair > self.y = y > """ Ok, so apparently, it needs a different vec2d, one which is specifically modified vec2d to work with the library Chipmunk, which is a c library, but with pindings binding(PyMunk) From mr.cerutti at gmail.com Tue Jan 8 07:07:15 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Tue, 8 Jan 2008 07:07:15 -0500 Subject: Open a List of Files In-Reply-To: References: Message-ID: <51302a8c0801080407n71ede5c9j3a05c5e5481b2db0@mail.gmail.com> On Jan 8, 2008 6:54 AM, BJ Swope wrote: > > > given a list such as > > > > > > ['messages', 'recipients', 'viruses'] > > > > > > how would I iterate over the list and use the values as variables and > > > open the variable names a files? > > > > > > I tried > > > > > > for outfile in ['messages', 'recipients', 'viruses']: > > > filename = os.path.join(Host_Path, outfile) > > > outfile = open(filename, 'w') > > > > > > But it's not working. > > Yep, defining "not working" is always helpful! :) > > I want to have all 3 files open at the same time. I will write to each of > the files later in my script but just the last file is open for writing. Your code successfully opened them all, but kept a reference only to the last one. Try something like: outfiles = [open(os.path.join(Host_Path, fname), 'w') for fname in fnames] -- Neil Cerutti From fredrik at pythonware.com Thu Jan 10 16:49:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 22:49:53 +0100 Subject: Elementtree 1.3 and xpath In-Reply-To: References: Message-ID: Andrew Lonie wrote: > Hi I noticed that the xpath functionality of elementtree has been > upgraded in version 1.3. However I can't seem to get the [postion] > predicate to function. All the other new functionality seems to be > working. ET 1.3 is only available in an early alpha yet, and the posted release only supports the [tag] form; from the CHANGES document: - Added new path engine, for "find", "findall", and "findtext". The new engine is a bit faster, and supports a number of predicates forms: [@attr], [@attr='value'], and [tag] (in the last case, only single tag names are supported). The engine also provides limited support for the ".." parent selector; you can use it inside the subtree, but it cannot go above the context element (the element you called "find" on). The next alpha will be out in February, and will do the right thing with your example: >>> from elementtree import ElementTree as ET >>> xml = ET.XML("""texttext2""") >>> ET.tostring(xml.find("tag[@att]")) 'text' >>> ET.tostring(xml.find("tag[@att]/..")) 'texttext2' >>> ET.tostring(xml.find("tag[1]")) 'text' From theller at ctypes.org Fri Jan 4 08:09:24 2008 From: theller at ctypes.org (Thomas Heller) Date: Fri, 04 Jan 2008 14:09:24 +0100 Subject: ctypes - pointer to array of structs? In-Reply-To: <18301.27496.174107.113205@montanaro.dyndns.org> References: <18301.27496.174107.113205@montanaro.dyndns.org> Message-ID: skip at pobox.com schrieb: > (Is this the right place to ask ctypes questions? There's a mailing list > but the last post to it seems to have been in November 2006.) You could use the ctypes-users mailing list: https://lists.sourceforge.net/lists/listinfo/ctypes-users It is also available via gmane. > Using ctypes I reference a structure which contains a pointer to an array of > another structure: > > class SYMBOL(Structure): > _fields_ = [("symbol", c_char_p), > ("num", c_int), > ("units", c_int), > ("baseprice", c_int), > ("active", c_int)] > SYMBOL_PTR = POINTER(SYMBOL) > > class TABLE(Structure): > _fields_ = [("map", SYMBOL_PTR), > ("nsymbols", c_uint), > ...] > > Effectively, TABLE.map is an array of TABLE.nsymbols SYMBOLS. How to I > reference elements in that array? In C I would just treat TABLE.map like an > array and index into it (for i=0; i< TABLE.nsymbols; i++) ...). This is > data returned from a C library, not something I'm building in Python to pass > into C. Assuming you got a pointer to TABLE from a function call like this: somefunction.restype = POINTER(TABLE) ptab = somefunction(...) then you should be able to use this code (C has the '*' operator to derefence pointers, Python does not so you have to use p[0] instead of *p): table = ptab[0] symp = table.map for i in range(table.nsymbols): sym = symp[0] print sym.symbol, sym.num, sym.units, sym.baseprice Thomas From k_vinoj at yahoo.com Wed Jan 2 02:04:21 2008 From: k_vinoj at yahoo.com (vinoj davis) Date: Wed, 2 Jan 2008 12:34:21 +0530 (IST) Subject: Using pexpect with cgi Message-ID: <752620.20123.qm@web94607.mail.in2.yahoo.com> An HTML attachment was scrubbed... URL: From jkugler at bigfoot.com Fri Jan 25 14:58:52 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Fri, 25 Jan 2008 10:58:52 -0900 Subject: Python and binary compatibility References: <083456aa-1ed1-4455-a8ca-4bbaaba1ce00@i29g2000prf.googlegroups.com> Message-ID: Christian Heimes wrote: > You can use MinGW32 to compile the extension, too. Or use the free > toolchain as described at > http://wiki.python.org/moin/Building_Python_with_the_free_MS_C_Toolkit That page has a link to the Microsoft Visual C++ Toolkit 2003 page, which then says it's been discontinued and to use Visual C++ 2005 Express Edition. Sigh... j From sjmachin at lexicon.net Fri Jan 25 06:03:14 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 03:03:14 -0800 (PST) Subject: The dimensions of a tuple References: Message-ID: <19d605ab-86de-44ec-8864-864554ffebc1@d21g2000prf.googlegroups.com> On Jan 25, 9:26 pm, bg... at yahoo.com wrote: > Hi, > > I wish to pass an argument to a function which will inset rows in a > db. I wish to have the follow possibilities - > > ("one","two") > (("one","two"),("three","four")) > > The first possibility would mean that one row is added with "one and > "two" being its column values. The second possibility means that two > rows are added. > > So to do this I need to establish the dimension of the duple. Is it a > one dimentional or two dimentional. How do I do this? isinstance(arg[0], tuple) ... but I wouldn't do it that way. I'd use a list of tuples, not a tuple of tuples, to allow for ease of building the sequence with list.append, and two functions: insert_one(("one", "two")) insert_many([("one", "two")]) insert_many([("one", "two"), ("three", "four")]) Which of those 2 functions calls the other depends on which you'd use more often. HTH, John From sjmachin at lexicon.net Sun Jan 27 06:04:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 27 Jan 2008 03:04:02 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <5vr1ekF1njt09U2@mid.uni-berlin.de> <84f39f37-4d18-47c1-9349-bf3f471b2bf5@s19g2000prg.googlegroups.com> Message-ID: <19efc1d4-d77d-4855-9647-7a4782b064eb@d21g2000prg.googlegroups.com> On Jan 27, 9:18 pm, glacier wrote: > On 1?24?, ??4?44?, Marc 'BlackJack' Rintsch wrote: > > > On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote: > > > My second question is: is there any one who has tested very long mbcs > > > decode? I tried to decode a long(20+MB) xml yesterday, which turns out > > > to be very strange and cause SAX fail to parse the decoded string. > > > That's because SAX wants bytes, not a decoded string. Don't decode it > > yourself. > > > > However, I use another text editor to convert the file to utf-8 and > > > SAX will parse the content successfully. > > > Because now you feed SAX with bytes instead of a unicode string. > > > Ciao, > > Marc 'BlackJack' Rintsch > > Yepp. I feed SAX with the unicode string since SAX didn't support my > encoding system(GBK). Let's go back to the beginning. What is "SAX"? Show us exactly what command or code you used. How did you let this SAX know that the file was encoded in GBK? An argument to SAX? An encoding declaration in the first few lines of the file? Some other method? ... precise answer please. Or did you expect that this SAX would guess correctly what the encoding was without being told? What does "didn't support my encoding system" mean? Have you actually tried pushing raw undecoded GBK at SAX using a suitable documented method of telling SAX that the file is in fact encoded in GBK? If so, what was the error message that you got? How do you know that it's GBK, anyway? Have you considered these possible scenarios: (1) It's GBK but you are telling SAX that it's GB2312 (2) It's GB18030 but you are telling SAX it's GBK HTH, John From hniksic at xemacs.org Tue Jan 8 06:52:46 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 08 Jan 2008 12:52:46 +0100 Subject: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> <5ugulaF1hqn2cU1@mid.uni-berlin.de> <5ugv5dF1i0edtU1@mid.dfncis.de> <87fxx8mycm.fsf@mulj.homelinux.net> <5uh0gcF1hoialU2@mid.dfncis.de> Message-ID: <87bq7wmt4h.fsf@mulj.homelinux.net> Robert Latest writes: >> If you see lines one by one, you are in luck, and you can fix things >> on the Python level simply by avoiding buffering in popen. If not, >> you will need to resort to more advanced hackery (e.g. fixing stdio >> using LD_PRELOAD). > > Do I really? After all, the shell itself doesn't hack stdio, does > it? Have you tried the "./slow | cat" test? It's not about the shell doing anything special, it's about slow's stdio choosing buffering "appropriate" for the output device. The hackery I referred to would be necessary to force slow's stdio to use line buffering over file/pipe output simply because there is no documented way to do that (that I know of). > Anyway, I'm taking this over to comp.unix.programmer since it really > isn't a python problem. It's still an often-encountered problem, so I believe a summary of the solution(s) would be appreciated. From duncan.booth at invalid.invalid Fri Jan 11 03:19:36 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Jan 2008 08:19:36 GMT Subject: Analyzing Python GC output - what is a "cell", and what information is available about it. References: <478707f2$0$36360$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > I'm printing out each entry in "gc.garbage" after a garbage collection in > DEBUG_LEAK mode, and I'm seeing many entries like > > > > That's the output of "repr". Are "cell" objects created only from > external C libraries, or can regular Python code generate them? Is there > any way to find out what the 'function object' is from within Python? > Cell objects are created whenever you have a function that references a variable in an outer scope. e.g. >>> def outer(): x = 42 def inner(): return x return inner >>> inner = outer() >>> inner.func_closure[0] >>> inner.func_closure[0].cell_contents 42 So in your case, cell.cell_contents.func_name might help. From donn.ingle at gmail.com Thu Jan 24 11:02:55 2008 From: donn.ingle at gmail.com (Donn Ingle) Date: Thu, 24 Jan 2008 18:02:55 +0200 Subject: piping into a python script References: Message-ID: > Try the fileinput module. I did give the fileinput module a go, but I can't find much info on it and the help is ... well, it's python help ;) > in goes to its stdin where it is processed if it has an argument of - > fileinput works that way Okay, I did think of the dash, but did not know how to handle it. Is it a bash thing or will that dash get passed into the args? (I am using getopt to parse the options and args) > which would work for ls and a python program using the fileinput > module. Any examples of fileinput (that do not open each file) would be great! (I'll go searching now anyway) Thanks, \d From bborcic at gmail.com Sun Jan 27 14:00:18 2008 From: bborcic at gmail.com (Boris Borcic) Date: Sun, 27 Jan 2008 20:00:18 +0100 Subject: Python self-evaluating strings In-Reply-To: References: Message-ID: <479cd4f5$1_2@news.bluewin.ch> Now there's always that style : >>> print x Traceback (most recent call last): File "", line 1, in eval(x) File "", line 2 Traceback (most recent call last): ^ SyntaxError: invalid syntax >>> eval(x) Traceback (most recent call last): File "", line 1, in eval(x) File "", line 2 Traceback (most recent call last): ^ SyntaxError: invalid syntax >>> Arnaud Delobelle wrote: > Hi all, > > An earlier post today got me thinking about "quines" (programs that > output themselves) in Python. I tried to find some on the web but > didn't find many ([1]). In particular I didn't find any that > corresponded to my instinctive (LISP-induced, probably) criterion: > > def self_evaluating(s): > "Return True if string s evaluates to itself" > return s == eval(s) > > Here is the result of my efforts so far: > > 1. Starting from the classic idea (lambda x:x%x)('lambda x:x%x') I got > the following > v=(lambda x:x%('"''""'+x+'"''""'))("""(lambda > x:x%%('"''""'+x+'"''""'))(%s)""") > > 2. (Given that if s is a nonempty string, s*2 is a longer string). > Starting from the idea "%s %s" % (("%s %s",)*2) I got the following > u="\"%s\" %% ((r\"%s\",)*2)" % ((r"\"%s\" %% ((r\"%s\",)*2)",)*2) > > Most of my problems in creating these 2 was with finding a suitable way > of quoting strings that propagates well. Both u and v are one-liners. > I'm hoping for no funky line wrapping here. > > Note: I'm not quoting the string as it makes no difference since they > evaluate to themselves:) > > I'd like to know if anyone on the list has indulged in this > time-bending/mind-wasting activity before. If so, it would be nice to > create a list of such expressions. > > Quining's-better-than-ironing'ly yours > > --Arnaud > > [1] http://www.nyx.net/~gthompso/self_pyth.txt > From cwitts at gmail.com Sat Jan 5 13:00:17 2008 From: cwitts at gmail.com (Chris) Date: Sat, 5 Jan 2008 10:00:17 -0800 (PST) Subject: Cursors in a Loop References: <3da337d8-2de0-4fdb-8c38-2f6fcd8348ac@i72g2000hsd.googlegroups.com> Message-ID: <7ea5ed8e-457c-4f93-985d-f7c5b8ad2436@t1g2000pra.googlegroups.com> On Jan 4, 4:32 pm, Carsten Haese wrote: > On Fri, 2008-01-04 at 00:03 -0800, Chris wrote: > > You should bind all variables to save the pool. > > > cursor = connection.cursor() > > cursor.executemany("""insert into as_siebel_hosts_temp > > values (:whole, :lot, :of, :bind, :variables) > > """ > > ,[(i,)[0] for i in hostlist] > > ) > > connection.commit() > > connection.close() > > Huh? In the OP's example, the table one has one column. I'll openly > admit that I don't know anything about Oracle, but that code doesn't > make sense to me. Maybe you're trying to execute a multi-row insert, but > that would be done with execute(), not executemany(), wouldn't it? > > Also, isn't "[(i,)[0] for i in hostlist]" exactly the same as "[i for i > in hostlist]" which in turn is exactly the same as "hostlist"? > > -- > Carsten Haesehttp://informixdb.sourceforge.net The OPs example has a formatted string, no idea what is in it... My example creates a tuple out of each of the records you want to insert and uses them in the bind variables. You can do a loop through hostlist and do a single execute on each one if you want. It won't make a large impact. The [(i,)[0] for i in hostlist] was mainly directed to you because your structure ends up being a tuple inside a list which doesn't work for cx_Oracle. You need a straight tuple to bind to the statement. My code creates a series of usable tuples for the executemany function. HTH, Chris From deets at nospam.web.de Mon Jan 7 08:17:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 Jan 2008 14:17:43 +0100 Subject: dictionary/hash and '1' versus 1 In-Reply-To: <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> Message-ID: <5uen3rF1f2vjrU1@mid.uni-berlin.de> bearophileHUGS at lycos.com schrieb: > Paddy: >> Not really, it seems to me to be going the exact opposite way with >> languages with automatic type conversions being seen as not suited for >> larger programs. > > In Java you can add the number 1 to a string, and have it > automatically converted to string before the string join... What do > you think of that feature? This isn't really what is happening. In fact, in Java the +-operator is overloaded for strings to invoke the mandatory toString()-method on all objects when concatenated with a string. So "" + 1 works internally as StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(new Integer(1).toString()); Or something like that, depending on how optimizing the compiler is. So you can also do "" + some_object However, some_object + "" or 1 + "" don't work - the operator is only overloaded on the left argument. Diez From rdrink at gmail.com Mon Jan 28 18:58:40 2008 From: rdrink at gmail.com (Robb Lane (SL name)) Date: Mon, 28 Jan 2008 15:58:40 -0800 (PST) Subject: file write question References: <62b96f11-1a81-4be8-9dcb-348ee38ebe16@f10g2000hsf.googlegroups.com> <5845751a-717e-4476-bdd5-4b7d09406fe4@j20g2000hsi.googlegroups.com> Message-ID: H - I am not familiar with flush(), will look into it. But an interesting note: I repeatedly and often start long running processes (one running right now: on about it's 14th hour), writing to open files, with few problems (on Mac OS X). Although of course I can't look at the results until the file closes...just have to hope it's right! LOL B - You are right about Sqlite, I'm a big fan (moved over from MySQL a few years ago). But the structure of the data for this project is much better suited to a 'flat file' format. Again, not that I am having problems, just thought I'd raise the topic. BTW PyCON is in Chicago this year (where I am), maybe I'll meet some of you there? RL From mnordhoff at mattnordhoff.com Wed Jan 9 17:54:32 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 09 Jan 2008 17:54:32 -0500 Subject: problem of converting a list to dict In-Reply-To: <49d262c8-492c-4f68-a145-27e84d3f7694@q39g2000hsf.googlegroups.com> References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> <49d262c8-492c-4f68-a145-27e84d3f7694@q39g2000hsf.googlegroups.com> Message-ID: <478550A8.1090006@mattnordhoff.com> bsneddon wrote: > This seemed to work for me if you are using 2.4 or greater and > like list comprehension. >>>> dict([ tuple(a.split("=")) for a in mylist[1:-1]]) > {'mike': 'manager', 'paul': 'employee', 'tom': 'boss'} > > should be faster than looping That's what he's doing (well, a generator expression, not a listcomp). It's just split across multiple lines (ew). -- From arkanes at gmail.com Tue Jan 29 11:00:04 2008 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 29 Jan 2008 10:00:04 -0600 Subject: optional static typing for Python In-Reply-To: <479e0225$0$36389$742ec2ed@news.sonic.net> References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> <479e0225$0$36389$742ec2ed@news.sonic.net> Message-ID: <4866bea60801290800r12af7b38ye9f060300ed7b55d@mail.gmail.com> On Jan 28, 2008 10:31 AM, John Nagle wrote: > Arnaud Delobelle wrote: > > On Jan 27, 11:00 pm, "Russ P." wrote: > >> On Jan 27, 2:49 pm, "Andr?" wrote: > >>> Perhaps this:http://www.python.org/dev/peps/pep-3107/mightbe > >>> relevant? > >>> Andr? > >> Thanks. If I read this correctly, this PEP is on track for Python 3.0. > >> Wonderful! > > > > Note that annotations do not provide explicit typing, AFAIK: > > > > def f(x:int) -> int: return x*2 > > > > is stricly equivalent to > > > > def f(x): return x*2 > > f.__annotations__ = {'x':int, 'return':int} > > > > You still need to write a type-checking wrapper. > > Unenforced static typing is somewhat pointless. If that > goes in, it should be enforced by implementations. Otherwise, > maintenance programmers can't trust the type information they see. > > Enforced, it makes it possible to start getting serious about > optimizing compilers for Python, like Shed Skin. Shed Skin > can usually figure out typing within a module, but across module > boundaries, some help is needed if you want to push optimization from > run time to compile time. > Given the difficulty of statically analyzing Python, and the limitations you need to add for either static typing or type inference to be practical, I think that the real future for faster Python code is JIT, not static optimizations. Languages which enforce static typing are, of course, not Python - that's why they have different names, like Pyrex or ShedSkin or RPython. I think static Python is pretty much a waste of time, really - if I'm going to write statically typed code using a traditional C/C++/Java style type system, I'll use a language designed for it, like D. If I want *real* strict typing - the kind where you can actually make a useful inference from the fact that the program is type-correct - I'll use Haskell or Ocaml. There is a lot of choice out there and there's no reason to try to make Python into whatever your favorite paradigm is. From jyoung79 at kc.rr.com Tue Jan 1 23:02:35 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Tue, 1 Jan 2008 22:02:35 -0600 Subject: os.tmpfile() Message-ID: <32714577.240331199246555557.JavaMail.root@hrndva-web18-z01> Can anyone elaborate on how 'os.tmpfile()' works? I was thinking it would create some sort of temporary file I could quickly add text too and then when I was finished would automatically get rid of it. Here's my questions: 1. Does it actually create a file somewhere? If so, where does it store it? Does it have to manually be deleted afterwards? 3. How do you use it? I tried the following, but it doesn't seem to work: >>> import os >>> c = os.tmpfile() >>> c.write('dude') >>> c.read() '' >>> os.path.exists(c) Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py", line 171, in exists TypeError: coercing to Unicode: need string or buffer, file found >>> type(c) >>> os.path.basename(c) Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py", line 112, in basename File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py", line 77, in split AttributeError: 'file' object has no attribute 'rfind' >>> for x in c: ... print x ... >>> Can you actually 'write' to this file? And if so, do you have to 'close()' it when you're done with it? Thanks for your help with this... I'm still learning Python and haven't been able to find out much about this in the documentation or on-line. Jay From fredrik at pythonware.com Thu Jan 10 14:36:19 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 20:36:19 +0100 Subject: Problem with Tkinter.PhotoImage In-Reply-To: <200801111548.34270.omer@no-log.org> References: <200801111548.34270.omer@no-log.org> Message-ID: C?dric Lucantis wrote: > I can only load gif images with Tkinter.PhotoImage and none with BitmapImage. > I tried png, jpg, bmp and xpm and always got this errors : > >>>> img = Tkinter.PhotoImage(file='/home/omer/fgfs/fgsync/map.xpm') > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 3206, in __init__ > Image.__init__(self, 'photo', name, cnf, master, **kw) > File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 3162, in __init__ > self.tk.call(('image', 'create', imgtype, name,) + options) > _tkinter.TclError: couldn't recognize data in image > file "/home/omer/fgfs/fgsync/map.xpm" to add to Kevin's reply, you seem to have a properly configured PIL on your machine: > python-imaging > python-imaging-tk which means that you could try replacing Tkinter.PhotoImage with from PIL import ImageTk img = ImageTk.PhotoImage(file='/home/omer/fgfs/fgsync/map.xpm') (PIL's XPM support isn't 100% perfect though; if it looks like crap, try using PNG or GIF or some other not quite as silly format...) From antroy at gmail.com Thu Jan 3 04:42:42 2008 From: antroy at gmail.com (Ant) Date: Thu, 3 Jan 2008 01:42:42 -0800 (PST) Subject: Extracting files from an ISO image? References: <34a84caa-5387-40a2-a808-5e7bd325023e@w47g2000hsa.googlegroups.com> Message-ID: <2fd70cf8-918a-4222-ac23-e08d5af06858@v4g2000hsf.googlegroups.com> On Jan 2, 7:07 pm, Rob Williscroft wrote: > Ant wrote in news:34a84caa-5387-40a2-a808- > > 1) Is there a module out there for extracting files from an ISO? > > There are command line programs that can do this: > > http://cdrecord.berlios.de/old/private/cdrecord.html ... > One problem you may have is daemon tools will mount cd images that > aren't iso images, where as isoinfo appears to handle only genuine > iso file systems. Cheers for the pointers. I'll try out the isoinfo tool, as my intention was to extract the images on the fly. If it turns out to be slow though (or problematic - I assume you mean that images in e.g. joliet format may not be parsed properly), I'll probably end up extracting the images and caching them on disk on the addition of new iso's by simply mounting the image as Grant pointed out. And it looks like wxPython may have support for icons in an img2py script, so that may sway me toward wxPython over TkInter. Cheers, -- Ant. From lasses_weil at klapptsowieso.net Tue Jan 8 06:53:37 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Tue, 08 Jan 2008 12:53:37 +0100 Subject: Look for a string on a file and get its line number In-Reply-To: References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> Message-ID: <47836440$0$27202$9b4e6d93@newsspool1.arcor-online.net> Jeroen Ruigrok van der Werven wrote: > line_nr = 0 > for line in big_file: > line_nr += 1 > has_match = line.find('my-string') > if has_match > 0: > print 'Found in line %d' % (line_nr) > Style note: May I suggest enumerate (I find the explicit counting somewhat clunky) and maybe turning it into a generator (I like generators): def lines(big_file, pattern="my string"): for n, line in enumerate(big_file): if pattern in line: print 'Found in line %d' % (n) yield n or for direct use, how about a simple list comprehension: lines = [n for (n, line) in enumerate(big_file) if "my string" in line] (If you're just going to iterate over the result, that is you do not need indexing, replace the brackets with parenthesis. That way you get a generator and don't have to build a complete list. This is especially useful if you expect many hits.) Just a note. regards /W From sjmachin at lexicon.net Fri Jan 25 15:58:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 12:58:09 -0800 (PST) Subject: Python ADO Date Time database fields References: <30222931-7fa9-4dd5-bdc8-d1313c37a144@i3g2000hsf.googlegroups.com> Message-ID: On Jan 26, 12:48 am, goldtech wrote: > snip > > > > > try this: > > > val = oRS.Fields(dt).Value > > print type(val) > > this gives: > > > print float(val) > > yes, it gives 0.0 > > But there should be a way to print what is *actually in the field*. What is "actually in the field" is a bunch of bits -- in this case all zero. What you *see* is quite another matter. > When I open the DB table in Access I see: 12:00:00 AM. And if you were to close Access, go Start / Control Panel / Regional and Language settings, change the Time display format to HH:mm:ss, and go back to look at your database, you'd see 00:00:00 ... send a copy of your database to someone in another country and they'd likely see something else again. > > That's what I want - the value, and the form of the value, exactly as > seen in the field... > > As an aside, the roughly eqivalent code in Perl will print the > "12:00:00 AM" - (the trick for the date types in Perl is to add: "use > Win32::OLE::Variant;" > > There has to be a way:^) C:\junk>type goldtech.py def time_format_12(day_fraction): assert 0.0 <= day_fraction < 1.0 seconds = int(day_fraction * 60 * 60 * 24) minutes, second = divmod(seconds, 60) hour, minute = divmod(minutes, 60) if hour >= 12: tag = 'PM' else: tag = 'AM' hour12 = (hour - 1) % 12 + 1 return '%02d:%02d:%02d %s' % (hour12, minute, second, tag) if __name__ == "__main__": import sys args = sys.argv[1:] if args: tests = map(float, args) else: tests = ( [0.0, 0.5, 0.9999999] + [(h + 0.99) / 24.0 for h in (0, 1, 11, 12, 13, 23)] ) for test in tests: print "%8.6f %s" % (test, time_format_12(test)) C:\junk>goldtech.py 0.000000 12:00:00 AM 0.500000 12:00:00 PM 1.000000 11:59:59 PM 0.041250 12:59:24 AM 0.082917 01:59:24 AM 0.499583 11:59:23 AM 0.541250 12:59:24 PM 0.582917 01:59:24 PM 0.999583 11:59:23 PM C:\junk>goldtech.py 0.1 0.01 0.001 0.100000 02:24:00 AM 0.010000 12:14:24 AM 0.001000 12:01:26 AM C:\junk> From basilisk96 at gmail.com Wed Jan 9 21:59:52 2008 From: basilisk96 at gmail.com (Basilisk96) Date: Wed, 9 Jan 2008 18:59:52 -0800 (PST) Subject: using super References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> <13niugpmvdls482@corp.supernews.com> <13nj1fp5m8u1i6f@corp.supernews.com> <13nj9oc1vo7j10@corp.supernews.com> <13njikdi21168e7@corp.supernews.com> Message-ID: On Jan 1, 12:11 am, Scott David Daniels wrote: > Steven D'Aprano wrote: > > On Mon, 31 Dec 2007 16:19:11 -0800, Scott David Daniels wrote: > > >> Steven D'Aprano wrote: > >>> On Mon, 31 Dec 2007 08:03:22 -0800, Scott David Daniels wrote: > >>>> Steven D'Aprano wrote: ... > >>>>> def chain(meth): # A decorator for calling super. > >>>>> def f(self, *args, **kwargs): > >>>>> result = meth(self, *args, **kwargs) > >>>>> S = super(self.__class__, self) > >>>> This line is the problem. The class parameter needs to be the class > >>>> (B in this case) in which the chaining method is defined, not that of > >>>> the object itself. > >>> One minor correction: the class parameter needs to be the class > >>> *itself*, not the class *name* (which would be the string "B"). > >> Point taken. > > >>> I don't quite understand your description though. What do you mean "the > >>> chaining method is defined"? chain() is defined outside of a class. > >> The class where f (the chaining method) is defined; equivalently, the > >> class in which the @chain is used. > > > So why doesn't self.__class__ work? That's the class in which @chain is > > used. > > OK, here's a simple 3-class example: > > class A(object): > def meth(self): print 'A.meth:', self.__class__, '---' > def pn(self): return '' > > class B(A): > def meth(self): > super(B, self).meth() > print 'B.meth:', self.__class__, super(B, self).pn() > def pn(self): return '' > > class C(B): > def meth(self): > super(C, self).meth() > print 'C.meth:', self.__class__, super(C, self).pn() > def pn(self): return '' > > c = C() > c.meth() > # Figure out why it printed what it did. > > # If not clear yet, how about this: > for class_ in C, B: > print class_.__name__, super(class_, c).pn() > > # And a bigger example (re-using A) to show why we > class B0(A): > def meth(self): > super(B0, self).meth() > print 'B0.meth:', self.__class__, super(B0, self).pn() > def pn(self): return '' > > class B1(B0): > def meth(self): > super(B1, self).meth() > print 'B1.meth:', self.__class__, super(B1, self).pn() > def pn(self): return '' > > class B2(B0): > def meth(self): > super(B2, self).meth() > print 'B2.meth:', self.__class__, super(B2, self).pn() > def pn(self): return '' > > class C1(B1, B2): > def meth(self): > super(C1, self).meth() > print 'C1.meth:', self.__class__, super(C1, self).pn() > def pn(self): return '' > > class D1(C1): > def meth(self): > super(D1, self).meth() > print 'D1.meth:', self.__class__, super(D1, self).pn() > def pn(self): return '' > > d = D1() > d.meth() > # Figure out why it printed what it did. > > for class_ in D1, C1, B1, B2, B0: > print class_.__name__, super(class_, d).pn() > # Now (after much cogitation) might that do it? > > # finally, just a fillip, predict this before you run it: > class E(D1, C): > def meth(self): > super(E, self).meth() > print 'E.meth:', self.__class__, super(E, self).pn() > def pn(self): return '' > > e = E() > e.meth() > for class_ in E, D1, C1, B1, B2, B0, C, B: > print class_.__name__, super(class_, e).pn() > > > I can clearly see that it doesn't work, I just don't understand why. I'd > > be inclined to chalk it up to super() being a mysterious black box that > > makes no sense *wink* .... > > super (and mro) work to get to all the superclasses in an order that > produces subtypes before their supertypes. The diamond inheritance > examples "show" why its needed. > > -Scott Cool, thanks for posting this example and clearing that up. Several times in the past I have used super(self.__class__, cls) instead of super(Klass_obj, cls), without a clue that it would wreck the subclasses. My beginner's thought at the time was that it would provide more flexibility.. Good thing I haven't had to subclass them..yet :) Cheers, -Basilisk96 From hniksic at xemacs.org Sat Jan 26 22:20:49 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 27 Jan 2008 04:20:49 +0100 Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> <87dd811e-3095-41d0-80fd-7312338e5254@i3g2000hsf.googlegroups.com> <489b6fc5-e871-425e-b242-45be618fc9f4@n20g2000hsh.googlegroups.com> Message-ID: <87r6g4q7hq.fsf@mulj.homelinux.net> Dox33 writes: > Thanks for your reply. Since I momentarily do not have the ability > to build a new python executable, I would like to ask for your help > in this case. Are you able to supply me with a corrected version? You can simply choose not to use raw_input, and use sys.stdin.readline instead. Or define your own corrected raw_input: def my_raw_input(msg): print msg, return raw_input() From asmodai at in-nomine.org Fri Jan 4 10:48:02 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jan 2008 16:48:02 +0100 Subject: problem in importing .pyd In-Reply-To: References: Message-ID: <20080104154802.GQ82115@nexus.in-nomine.org> -On [20080104 16:41], abhishek (guptaabhishek1983 at gmail.com) wrote: >What should i do to resolve this problem. Perhaps the hints/tips from http://blogs.msdn.com/nikolad/articles/427101.aspx might help? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ I realise that nothing's as it seems... From martin at v.loewis.de Wed Jan 23 04:17:54 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Jan 2008 10:17:54 +0100 Subject: Hebrew in idle ans eclipse (Windows) In-Reply-To: References: <478ee0c0$0$4589$9b622d9e@news.freenet.de> <86ea4c94-f4b3-4bc3-9b2a-bc9b5c182264@i12g2000prf.googlegroups.com> <478FBC1A.4080201@v.loewis.de> Message-ID: <47970642$0$13412$9b622d9e@news.freenet.de> > Recall: > When I read data using sql I got a sequence like this: > \x88\x89\x85 > But when I entered heberw words directly in the print statement (or as > a dictionary key) > I got this: > \xe8\xe9\xe5 > > Now, scanning the encoding module I discovered that cp1255 maps > '\u05d9' to \xe9 > while cp856 maps '\u05d9' to \x89, > so trasforming \x88\x89\x85 to \xe8\xe9\xe5 is done by Hebrew Windows apparently uses cp1255 (aka windows-1255) as the "ANSI code page", used in all GUI APIs, and cp856 as the "OEM code page", used in terminal window - and, for some reason, in MS SQL. > My qestion is, is there a way I can deduce cp856 and cp1255 from the > string itself? That's not possible. You have to know where the string comes from. to know what the encoding is. In the specific case, if the string comes out of MS SQL, it apparently has cp856 (but I'm sure you can specify the client encoding somewhere in SQL server, or in pymssql) > I don't know how IDLE guessed cp856, but it must have done it. I don't know why you think it did. You said you entered \xe9 directly into the source code in IDLE, so a) this is windows-1255, not cp856, and b) IDLE just *used* windows-1255 (i.e. the ANSI code page), it did not guess it. If you are claimaing that the program import pymssql con = pymssql.connect(host='192.168.13.122',user='sa',password='',database='tempdb') cur = con.cursor() cur.execute('select firstname, lastname from [users]') lines = cur.fetchall() print repr(lines[0]) does different things depending on whether it is run in IDLE or in a terminal window - I find that hard to believe. IDLE/Tk has nothing to do with that. It's the *repr* that you are printing, ie. all escaping has been done before IDLE/Tk even sees the text. So it must have been pymssql that returns different data in each case. It could be that the DB-API does such things, see http://msdn2.microsoft.com/en-us/library/aa937147(SQL.80).aspx Apparently, they do the OEMtoANSI conversion when you run a console application (i.e. python.exe), whereas they don't convert when running a GUI application (pythonw.exe). I'm not quite sure how they find out whether the program is a console application or not; the easiest thing to do might be to turn the autoconversion off on the server. Regards, Martin From mmanns at gmx.net Sun Jan 13 18:45:50 2008 From: mmanns at gmx.net (Martin Manns) Date: Mon, 14 Jan 2008 00:45:50 +0100 Subject: Slicing wrapped numpy arrays References: Message-ID: On Sun, 13 Jan 2008 16:03:16 -0600 Robert Kern wrote: > Martin Manns wrote: > > Hi, > > > > I have created a class that wraps a numpy array of custom objects. I > > would like to be able to slice respective objects (without copying > > the array if possible). > > > > I have browsed the doc and found some hints at __getitem__. > > However, I still do not grasp how to do it. How do I implement > > __getitem__ correctly? > > > mymap[10:20,15:20,:] # This line should work afterwards > > The first thing you should do is simply implement a very basic, > nonfunctional version just to see what objects come in: > > In [1]: class Sliceable(object): > ...: def __getitem__(self, arg): > ...: print arg > ...: I did that and got here: > (slice(None, None, 2), slice(10, None, 10)) However, I still do not see how I get a Map object that employs a slice of the array without creating a new Map object. Martin From tenax.raccoon at gmail.com Wed Jan 23 12:24:49 2008 From: tenax.raccoon at gmail.com (Jason) Date: Wed, 23 Jan 2008 09:24:49 -0800 (PST) Subject: get the size of a dynamically changing file fast ? References: <198fd91f-912b-4f56-a840-af96225125a7@c23g2000hsa.googlegroups.com> <197576d1-ab36-45f2-9648-3cfab6d3a814@j20g2000hsi.googlegroups.com> Message-ID: On Jan 22, 3:22 pm, Stef Mientki wrote: > Mike Driscoll wrote: > > On Jan 22, 3:35 pm, Stef Mientki wrote: > > >> Mike Driscoll wrote: > > >>> On Jan 17, 3:56 pm, Stef Mientki wrote: > > >>>> hello, > > >>>> I've a program (not written in Python) that generates a few thousands > >>>> bytes per second, > >>>> these files are dumped in 2 buffers (files), at in interval time of 50 msec, > >>>> the files can be read by another program, to do further processing. > > >>>> A program written in VB or delphi can handle the data in the 2 buffers > >>>> perfectly. > >>>> Sometimes Python is also able to process the data correctly, > >>>> but often it can't :-( > > >>>> I keep one of the files open en test the size of the open datafile each > >>>> 50 msec. > >>>> I have tried > >>>> os.stat ( ....) [ ST_SIZE] > >>>> os.path.getsize ( ... ) > >>>> but they both have the same behaviour, sometimes it works, and the data > >>>> is collected each 50 .. 100 msec, > >>>> sometimes 1 .. 1.5 seconds is needed to detect a change in filesize. > > >>>> I'm using python 2.4 on winXP. > > >>>> Is there a solution for this problem ? > > >>>> thanks, > >>>> Stef Mientki > > >>> Tim Golden has a method to watch for changes in a directory on his > >>> website: > > >>>http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_fo... > > >>> This old post also mentions something similar: > > >>>http://mail.python.org/pipermail/python-list/2007-October/463065.html > > >>> And here's a cookbook recipe that claims to do it as well using > >>> decorators: > > >>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/426620 > > >>> Hopefully that will get you going. > > >>> Mike > > >> thanks Mike, > >> sorry for the late reaction. > >> I've it working perfect now. > >> After all, os.stat works perfectly well, > >> the problem was in the program that generated the file with increasing > >> size, > >> by truncating it after each block write, it apperently garantees that > >> the file is flushed to disk and all problems are solved. > > >> cheers, > >> Stef Mientki > > > I almost asked if you were making sure you had flushed the data to the > > file...oh well. > > Yes, that's a small disadavantage of using a "high-level" language, > where there's no flush available, and you assume it'll done > automatically ;-) > > cheers, > Stef Uhm, there is a flush method for Python's files. From "http:// docs.python.org/lib/bltin-file-objects.html": flush() Flush the internal buffer, like stdio's fflush(). This may be a no-op on some file-like objects. As for an example: >>> import os >>> f = open('vikings.txt', 'wb') >>> os.stat('vikings.txt').st_size 0L >>> f.write('Spam, spam, spam, spam! ' * 1000) # Bloody vikings... >>> os.stat('vikings.txt').st_size 24576L >>> f.flush() >>> os.stat('vikings.txt').st_size 25000L >>> Is there something that I'm missing here? --Jason From browerg at verizon.net Fri Jan 11 10:19:05 2008 From: browerg at verizon.net (browerg at verizon.net) Date: Fri, 11 Jan 2008 09:19:05 -0600 (CST) Subject: scope question in a switch mixin Message-ID: <4132126.2363711200064745566.JavaMail.root@vms229.mailsrvcs.net> The code that follows is the result of noodling around with switches as a learning tool. I've played with python for a few years, but I'm self-taught, so . . . Class Switch builds a set of functions. Method switch executes one of them given a value of the switch variable. My question is, why are modules imported at the top of the program not visible to the functions Switch builds? There is no problem when the import is in the function, but I thought initially that imports at the top would be in its globals. The import that works is at line 111 in the code. Thanks in advance! George '''Mixin Switch provides function switch(key) that executes an appropriate function. Each instance can: use a different switch variable. be used as many places in a program as desirable. be changed in one place, no matte how many places it is used. Usage: inst = Switch(keys, vals, base) whose arguments are sequenes: keys has switch values ('su', 'mo', . . .), base has the shared fore and aft parts of instance functions, and vals has the individual parts of instane functions. Example: Suppose you want to switch on days of the week: keys = ('su', 'mo', 'tu', 'we', 'th', 'fr', 'sa', 'de') vals = ('Sunday is Comic-day.', 'Monday is Moan-day.', 'Tuesday is Twos-day.', 'Wednesday is Hump-day.', 'Thursday is Shop-day.', 'Friday is TGIF-day.', 'Saturday is Food-day.', 'Anything else is Party-day!') fore = "def %s(self, *args):\n\tprint '" aft = "'\\n" produces functions of the form: def su(self, *args):\\n\\tprint 'Sunday is Comic-day.'\\n or, for humans: def su(self, *args): print 'Sunday is Comic-day.' Test code (below) for this example produces: Sunday is Comic-day. Monday is Moan-day. . . . Anything else is Party-day! key {} keys must be hashable (immutable) objects. Example: Suppose you want to swith on a function and its argument. Test code (below) returns calculated values using functions like: def %s(self, *args):\\n\\timport math\\n\\ttmp = (args[0] / math.pi)\\n\\treturn tmp\\n or, for humans: def %s(self, *args): import math tmp = (args[0] / math.pi) return tmp that produce: In toplevel: circ.switch(dC, 10), d = 3.18309886184 In toplevel: circ.switch(Cd, 3.18), C = 9.99026463842 In toplevel: circ.switch(rC, 5), r = 0.795774715459 In toplevel: circ.switch(Cr, 0.796), C = 5.00141550451 In toplevel: circ.switch(A , 5), A = 78.5398163397 Thanks to Jean-Paul Calderone for his post at http://mail.python.org/pipermail/python-list/2007-June/446648.html in response to a question by vasudevrama t http://mail.python.org/pipermail/python-list/2007-June/446618.html ''' #import math class Switch(object): def __init__(self, keys, vals, base): self.dictionary = {} tmpd = {} for i in range(len(vals)): func = ''.join([base[0] % keys[i], vals[i], base[1]]) compile(func, '', 'exec') exec(func, tmpd) for k, v in tmpd.items(): if k in keys: self.dictionary[k] = v def switch(self, key, *args, **kwargs): try: result = self.dictionary[key](self, *args, **kwargs) except KeyError: result = self.dictionary['de'](self, *args, **kwargs) return result if '__main__' == __name__: '''Case 1: execute a statement. ''' keys = ('su', 'mo', 'tu', 'we', 'th', 'fr', 'sa', 'de') vals = ('Sunday is Comic-day.', 'Monday is Moan-day.', 'Tuesday is Twos-day.', 'Wednesday is Hump-day.', 'Thursday is Shop-day.', 'Friday is TGIF-day.', 'Saturday is Food-day.', 'Anything else is Party-day!') fore = "def %s(self, *args):\n\tprint '" aft = "'\n" base = (fore, aft) day = Switch(keys, vals, base) for k in keys: try: day.switch(k) except TypeError: print 'key %s %s keys must be hashable (immutable) objects.' % (k, type(k)) for k in ('xx', 1234, 12.3, {}): try: day.switch(k) except TypeError: print 'key %s %s keys must be hashable (immutable) objects.' % (k, type(k)) '''Case 2: execute an expression. ''' keys = ('dC', 'Cd', 'rC', 'Cr', 'A', 'de') vals = ("(args[0] / math.pi)", # diameter given Circumference "(math.pi * args[0])", # Circumferene given diameter "(args[0] / (2 * math.pi))", # radius given Circumference "(2 * math.pi * args[0])", # Circumference given radius "(math.pi * args[0]**2)", # Area given radius "False") # Why are modules imported at the top not found in these functions? fore = "def %s(self, *args):\n\timport math\n\ttmp = " aft = "\n\treturn tmp\n" base = (fore, aft) circ = Switch(keys, vals, base) vs = (10, 3.18, 5, 0.796, 5) kvs = zip(keys, vs) for k, v in kvs: result = circ.switch(k, v) print "In toplevel: circ.switch(%-2s, %5s), %s = %s" % (k, v, k[0], result) From kyosohma at gmail.com Thu Jan 10 11:57:49 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 10 Jan 2008 08:57:49 -0800 (PST) Subject: ISO Python example projects (like in Perl Cookbook) References: Message-ID: <67f0df0e-ac6a-491c-b141-11fe8dadf4de@i29g2000prf.googlegroups.com> On Jan 10, 10:13 am, kj wrote: > I'm looking for "example implementations" of small projects in > Python, similar to the ones given at the end of most chapters of > The Perl Cookbook (2nd edition, isbn: 0596003137). (Unfortunately, > the otherwise excellent Python Cookbook (2nd edition, isbn: > 0596007973), by the same publisher (O'Reilly), does not have this > great feature.) > > The subchapters devoted to these small projects (which are called > "Program"s in the book), each consists of a description of the > task, a discussion of the relevant design considerations, and one > or more illustrative implementations. As such, these programs are > larger and more complex than the typical "recipe" in the book, but > are still short enough to be read and understood in a few minutes. > > I find the study of such small programs invaluable when learning > a new language. > > Does anyone know of a source of similar material for Python? > > TIA! > > kynn > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. I know that Hetland's book, "Beginning Python" has some projects in the back. Zelle's book ("Python Programming: An Introduction to Computer Science") has exercises of sorts at the end of each of the chapters. Python Programming for the Absolute Beginner walks the reader through designing some games with the pygame module...and for some involved reading, I would recommend Lutz's tome, "Programming Python 3rd Ed.", which has various projects throughout that the author goes into in depth. I've seen tutorials of varying worth on devshed.com and good articles on IBM's site as well. Mike From tejovathi.p at gmail.com Tue Jan 8 05:33:25 2008 From: tejovathi.p at gmail.com (Teja) Date: Tue, 8 Jan 2008 02:33:25 -0800 (PST) Subject: COM server and EXE Message-ID: Hi All, I have a Python COM server. I need to deploy it on various sytems. When I run the COM server from python its showing an output " Registered : sample.lib" If I try to use the COM obj from a VB client like: obj = CreateObject("sample.lib") Its working fine without any errors Now I am trying to convert this COM server to an exe through py2exe and after I run the exe, I am getting the same output " Registered : sample.lib" But If I try to use the COM obj from a VB client like obj = CreateObject("sample.lib") A console pops up saying " Registered : sample.lib" and VB application hangs there. Its throwing a VB error that "ActiveX object cannot be created......etc etc" Any suggestions please....... Regards, Tejovathi From oinopion at gmail.com Fri Jan 25 17:52:22 2008 From: oinopion at gmail.com (Tomek Paczkowski) Date: Fri, 25 Jan 2008 23:52:22 +0100 Subject: Puzzled by behaviour of class with empty constructor References: <99b8e2ac-1c72-430a-9172-a809e169f96a@i12g2000prf.googlegroups.com> Message-ID: <479a6826$0$14672$f69f905@mamut2.aster.pl> dbaston at gmail.com wrote: > Hello, > > I have a class called 'Axis' that I use as a base class for several > types of axes that can be created by a grid generation program that I > have written: equally-spaced grids, logarithmic grids, etc. In any > case, if I use this base class by itself, I see some puzzling > behaviour: > ############# > class Axis: > ends = [] > N = None > def __init__(self): > pass > > x = Axis() > y = Axis() > z = Axis() > > x.ends.append((0,2)) > > print x.ends,y.ends,z.ends > ############# > Running the following code outputs: >>>> [(0, 2)] [(0, 2)] [(0, 2)] > > Can anyone explain this? Well, you are using a class variable - Axis.ends. It's shared among all instances of Axis class. To have it separate setup it in __init__ like: class Axix: def __init__(self): self.ends = [] self.N = None You see, code inside class, but outside methods is executed only once and any variables are then linked with class, and not instances (more/less). Take look at: http://docs.python.org/tut/node11.html ~TomekP -- Someone whom you reject today, will reject you tomorrow. From saluk64007 at gmail.com Wed Jan 23 04:08:54 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 23 Jan 2008 01:08:54 -0800 Subject: Removing objects In-Reply-To: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> Message-ID: On Jan 22, 2008 10:59 PM, wrote: > I am writing a game, and it must keep a list of objects. I've been > representing this as a list, but I need an object to be able to remove > itself. It doesn't know it's own index. If I tried to make each object > keep track of it's own index, it would be invalidated when any object > with a lower index was deleted. The error was that when I called > list.remove(self), it just removed the first thing in hte list with > the same type as what I wanted, rather than the object I wanted. The > objects have no identifying charachteristics, other than thier > location in memory > > So my question: How do I look something up in a list by it's location > in memory? does python even support pointers? > > Is there a better way? To put it simply, list.remove(self) ought to work. Are you sure it's not working? list.remove self doesn't delete the first matching type, it deletes the first object that IS what you passed, or failing that, it deletes the first object that == what you pass. I use an idiom often in my games, where rather than deleting objects on the fly, which is not very thread-safe in case you have something scanning through the objects, I set a property .kill on objects that are about to die, and then rebuild the list in the main loop with only objects that haven't been killed. I don't know if it's better, but it would probably work in your situation if list.remove(self) isn't working (which is strange). The other benefit of my idiom, is that objects don't need to have a reference to the object list, and any other function that wants to delete that object needs no other references besides the object itself. I have trouble with references a lot in complex games, and where I can I prefer not to have them. From mensanator at aol.com Tue Jan 22 09:30:38 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Tue, 22 Jan 2008 06:30:38 -0800 (PST) Subject: Max Long References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> Message-ID: <5eac4099-09c0-46a5-acf7-de14d902c43f@k39g2000hsf.googlegroups.com> On Jan 21, 7:42?pm, "Gabriel Genellina" wrote: > En Mon, 21 Jan 2008 22:02:34 -0200, mensana... at aol.com ? > escribi?: > > > > > > > On Jan 21, 5:36?pm, Gary Herron wrote: > >> tjhn... at gmail.com wrote: > >> > How can I figure out the largest long available? ?I was hoping for > > >> There is no explicit (defined) limit. ?The amount of available address > >> space forms a practical limit. > > > But not the only limitation: > > [...] > > Traceback (most recent call last): > > ? File "", line 2, in > > ? ? a = cf.Type12MH(k,1) > > ? File "C:\Program Files\PyGTK\Python\lib\collatz_functions.py", line > > 745, in Type12MH > > ? ? return TWO**(SIX*a - ONE) - ONE > > ValueError: mpz.pow outrageous exponent > > > The power function can't do exponents that have 32 or more bits > > even if the memory can hold the resulting number. > > Isn't it a limitation of the gmpy library, not of the builtin long type? Well, gmpy for sure. But as for Python's builtin longs, I wouldn't know as I've only got one lifetime. Python longs c:\python25\user>long_ago.py 1 2 0.0310001373291 2 9 0.0310001373291 3 74 0.0310001373291 4 659 0.0620000362396 5 5926 0.0620000362396 6 53328 0.219000101089 7 479940 63.5620000362 8 4319453 8983.07800007 9 GMPY longs c:\python25\user>long_ago.py 1 2 0.0 2 9 0.0160000324249 3 74 0.0160000324249 4 659 0.0160000324249 5 5926 0.0160000324249 6 53328 0.0160000324249 7 479940 0.0160000324249 8 4319453 0.0320000648499 9 38875064 0.15700006485 10 349875565 1.36000013351 > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - From hat at se-162.se.wtb.tue.nl Thu Jan 10 05:41:53 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 10 Jan 2008 11:41:53 +0100 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: On 2008-01-09, dongie.agnir at gmail.com wrote: > I'm pretty new to Python, and even newer to Image/Video processing, > and trying to get started on a project similar to GRL Vienna's laser > marker. I found some sample code here http://janto.blogspot.com/2006/01/motion-capture-in-python.html, > but after running the code with the included sample input file, it > seems quite slow (1-2 seconds from start to finish to do the 800 by > 600 gif image). > Is there a better way to do color tracking, or is Python just too slow > as an interpreted language to do any effective color tracking? People seem quite obsessed with execution speed of CPU's. I have come to believe that it is only one part of the equation, development time and ease of maintenance or modification is another one, which I believe is much more interesting to perform as fast as possible. 1-2 seconds may be slower than some alternative solution (you could in principle develop custom hardware for it, and do the trick in a few nano-seconds). The question that arises (for me at least) is, how fast can you write, maintain, and modify what you want in that other solution. Suppose you can do color-tracking in 0.5 seconds. So, you gained 1.5 seconds CPU time. Now the question you need to answer for yourself, is how much more worth is your own time compared to the gain in CPU time. If you think they are equal (ie the problem as a whole should be solved as fast as possible, thus the sum of development time + execution time should be as short as possible), you can spend an additional 1.5 seconds development in the alternative solution. Of course, if you do more color-tracking, the differences between alternative solutions become larger, and your custom hardware solution may become a feasible alternative.... :) In my experience however, differences in CPU execution time are usually meaningless compared to differences in development time. Albert From berteun at NO_SPAMdds.nl Tue Jan 29 12:03:33 2008 From: berteun at NO_SPAMdds.nl (Berteun Damman) Date: Tue, 29 Jan 2008 17:03:33 +0000 (UTC) Subject: Removal of element from list while traversing causes the next element to be skipped References: Message-ID: On Tue, 29 Jan 2008 16:34:17 GMT, William McBrine wrote: > Look at this -- from Python 2.5.1: > >>>> a = [1, 2, 3, 4, 5] >>>> for x in a: > ... if x == 3: > ... a.remove(x) > ... print x > ... > 1 > 2 > 3 > 5 >>>> a > [1, 2, 4, 5] You have to iterate over a copy of 'a', so for x in a[:]. Modifying a list while iterating over is a recipe for problems. (As it is in many other programming languages.) Berteun From mail at microcorp.co.za Thu Jan 17 02:36:11 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 17 Jan 2008 09:36:11 +0200 Subject: Interesting Thread Gotcha References: Message-ID: <001101c85929$9bb1a160$03000080@hendrik> "Duncan Booth" wrote: > Given that the start_new_thread function never actually got called, what > code exactly do you expect to complain about the absence of a tuple? I don't understand this assertion. I thought that start_new_thread was called with a missing comma in its argument list, which had the effect that I am complaining about. Putting the comma in place solved the problem, without any other changes, so why do you say that start_new_thread was not called? - Hendrik From deets at nospam.web.de Sun Jan 6 06:51:49 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 06 Jan 2008 12:51:49 +0100 Subject: list property fires get on append In-Reply-To: References: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com> Message-ID: <5ubtmpF1h6rimU1@mid.uni-berlin.de> Soviut schrieb: > On Jan 6, 3:03 am, Fredrik Lundh wrote: >> i... at neustyle.com wrote: >>> I've created a class that has a property which points at a private >>> list. When I try to use the append() function on this list property, >>> the fget method is fired rather than the fset method. If I directly >>> set my property to a literal list, the set method fires. >>> # this fires a get for some reason >>> hierarchy.children.append( Hierarchy.Hierarchy()) >> that's the expected behaviour: you're *fetching* the "children" >> attribute in order to modify it, you're not replacing it. >> >> reading up on Python's object model might be helpful. >> >> > > I figured that an append would be treated as a set since I'm adding to > the list. But what you say makes sense, although I can't say I'm > happy with the behaviour. Is there any way I can get the append to > fire a set? I'm thinking of properties from my C# background where i > believe that manipulation such this would be considered a set. No, it wouldn't. It's simply this: c = a.b Now what does that trigger? Obviously a get on a for the attribute b. But what you do with c afterwards is totally up to you. You can alter it, or you can leave it. Think of this example: c = a.b if random() > .5: c.append(1) else: print c[0] How should the interpreter or C# runtime know when a.b is executed how c will be treated? What you _can_ do is to not return the actual list-object in get, but instead a proxy that will notify the owner of the list of all methods called. Diez From grante at visi.com Sun Jan 27 05:00:45 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 27 Jan 2008 10:00:45 -0000 Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <690cb460-fa8a-49a1-a6fa-69cdf480a918@i3g2000hsf.googlegroups.com> <7xir1hznuu.fsf@ruckus.brouhaha.com> Message-ID: <13polidj792mi26@corp.supernews.com> On 2008-01-27, Stefan Behnel wrote: > Gabriel Genellina wrote: >> use the Windows sort command. It has been >> there since MS-DOS ages, there is no need to download and install other >> packages, and the documentation at >> http://technet.microsoft.com/en-us/library/bb491004.aspx says: >> >> Limits on file size: >> The sort command has no limit on file size. > > Sure, since no-one can ever try it with more than 640k, it's > easy to state that there is no limit. :) Huh? I used DOS sort to sort files much bigger than 640K. And I used the Unix sort command on a machine with 64K bytes of data space to sort files even larger than the ones under DOS. -- Grant From peng.kyo at gmail.com Wed Jan 16 00:59:03 2008 From: peng.kyo at gmail.com (J. Peng) Date: Wed, 16 Jan 2008 13:59:03 +0800 Subject: no pass-values calling? In-Reply-To: <13or6esikdrqa33@corp.supernews.com> References: <13or6esikdrqa33@corp.supernews.com> Message-ID: <18c1e5f20801152159o78b352absea6555b200161bd@mail.gmail.com> On Jan 16, 2008 1:45 PM, Dennis Lee Bieber wrote: > On Wed, 16 Jan 2008 11:09:09 +0800, "J. Peng" > > alist = [] > anint = 2 > astr = "Touch me" > > dummy(alist, anint, astr) > > "dummy" can only modify the contents of the first argument -- the > integer and string can not be mutated. Hi, How to modify the array passed to the function? I tried something like this: >>> a [1, 2, 3] >>> def mytest(x): ... x=[4,5,6] ... >>> mytest(a) >>> a [1, 2, 3] As you see, a was not modified. Thanks! From http Fri Jan 11 21:25:00 2008 From: http (Paul Rubin) Date: 11 Jan 2008 18:25:00 -0800 Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <7x7iifsrur.fsf@ruckus.brouhaha.com> George Sakkis writes: > from itertools import chain, izip, cycle > print ''.join(chain(*izip(s1.split('_'),cycle(':,'))))[:-1] from itertools import cycle a = cycle(':,') print re.sub('_', lambda x: a.next(), s1) From tommy.nordgren at comhem.se Thu Jan 17 19:30:47 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Fri, 18 Jan 2008 01:30:47 +0100 Subject: Downlod from FTP, pickle In-Reply-To: References: Message-ID: <75552DC8-480F-4217-BA61-A98A8EBA2D99@comhem.se> On 18 jan 2008, at 01.13, SMALLp wrote: > Hy! > > I have a little problem. I have to download file from FTP sp i use > ftplib. And then i have to pickle.load from that file. I make callback > function that saves line by line into temporary file and now i cant > read > from that file and when i close it i diapers. > > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list You need to rewind the temporary file before reading. ----------------------------------- See the amazing new SF reel: Invasion of the man eating cucumbers from outer space. On congratulations for a fantastic parody, the producer replies : "What parody?" Tommy Nordgren tommy.nordgren at comhem.se From vinay_sajip at yahoo.co.uk Mon Jan 14 16:31:38 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 14 Jan 2008 13:31:38 -0800 (PST) Subject: problem with logging exceptions with non-ASCII __str__ result References: Message-ID: <94bcb6ce-e42d-49cc-9d8e-2932e42b8028@j78g2000hsd.googlegroups.com> On Jan 14, 5:46 pm, Karsten Hilbert wrote: > Dear all, > > I have a problem withloggingan exception. > > environment: > > Python 2.4, Debian testing > > ${LANGUAGE} not set > ${LC_ALL} not set > ${LC_CTYPE} not set > ${LANG}=de_DE.UTF-8 > > activating user-default locale with returns: [de_DE.UTF-8] > > locale.getdefaultlocale() - default (user) locale: ('de_DE', 'utf-8') > encoding sanity check (also check "locale.nl_langinfo(CODESET)" below): > sys.getdefaultencoding(): [ascii] > locale.getpreferredencoding(): [UTF-8] > locale.getlocale()[1]: [utf-8] > sys.getfilesystemencoding(): [UTF-8] > > _logfile = codecs.open(filename = _logfile_name, mode = 'wb', encoding = 'utf8', errors = 'replace') > > logging.basicConfig ( > format = fmt, > datefmt = '%Y-%m-%d %H:%M:%S', > level =logging.DEBUG, > stream = _logfile > ) > > I am using psycopg2 which in turn uses libpq. When trying to > connect to the database and providing faulty authentication > information: > > try: > ... try to connect ... > except StandardError, e: > _log.error(u"login attempt %s/%s failed:", attempt+1, max_attempts) > > print "exception type :", type(e) > print "exception dir :", dir(e) > print "exception args :", e.args > msg = e.args[0] > print "msg type :", type(msg) > print "msg.decode(utf8):", msg.decode('utf8') > t,v,tb = sys.exc_info() > print "sys.exc_info() :", t, v > _log.exception(u'exception detected') > > the following output is generated: > > exception type : > exception dir : ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] > exception args : ('FATAL: Passwort-Authentifizierung f\xc3\xbcr Benutzer \xc2\xbbany-doc\xc2\xab fehlgeschlagen\n',) > msg type : > msg.decode(utf8): FATAL: Passwort-Authentifizierung f?r Benutzer ?any-doc? fehlgeschlagen > > sys.exc_info() : psycopg2.OperationalError FATAL: Passwort-Authentifizierung f?r Benutzer ?any-doc? fehlgeschlagen > > Traceback (most recent call last): > File "/usr/lib/python2.4/logging/__init__.py", line 739, in emit > self.stream.write(fs % msg.encode("UTF-8")) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 191: ordinal not in range(128) > > Now, the string "FATAL: Passwort-Auth..." comes from libpq > via psycopg2. It is translated to German via gettext within > libpq (at the C level). As we can see it is of type string. > I know from the environment that it is likely encoded in > utf8 manually applying which (see the decode call) succeeds. > > On _log.exception() theloggingmodule wants to output the > message as encoded as utf8 (that's what the log file is set > up as). So it'll look at the string, decide it is of type > "str" and decode with the *Python default encoding* to get > to type "unicode". Following which it'll re-encode with utf8 > to get back to type "str" ready for outputting to the log > file. > > However, since the Python default encoding is "ascii" that > conversion fails. > > Changing the Python default encoding isn't really an option > as it is advocated against and would have to be made to work > reliably on other users machines. > > One could, of course, write code to specifically check for > this condition and manually pre-convert the message string > to unicode but that seems not as things should be. > > How can I cleanly handle this situation ? > > Should theloggingmodule internally use an encoding gotten > from the locale module rather than the default string encoding ? > > Karsten > -- > GPG key ID E4071346 @ wwwkeys.pgp.net > E167 67FD A291 2BEA 73BD 4537 78B9 A9F9 E407 1346 Please reduce to a minimal program which demonstrates the issue and log an issue on bugs.python.org. Best regards, Vinay Sajip From alnilam at gmail.com Tue Jan 22 00:31:37 2008 From: alnilam at gmail.com (Alnilam) Date: Mon, 21 Jan 2008 21:31:37 -0800 (PST) Subject: HTML parsing confusion Message-ID: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> Sorry for the noob question, but I've gone through the documentation on python.org, tried some of the diveintopython and boddie's examples, and looked through some of the numerous posts in this group on the subject and I'm still rather confused. I know that there are some great tools out there for doing this (BeautifulSoup, lxml, etc.) but I am trying to accomplish a simple task with a minimal (as in nil) amount of adding in modules that aren't "stock" 2.5, and writing a huge class of my own (or copying one from diveintopython) seems overkill for what I want to do. Here's what I want to accomplish... I want to open a page, identify a specific point in the page, and turn the information there into plaintext. For example, on the www.diveintopython.org page, I want to turn the paragraph that starts "Translations are freely permitted" (and ends ..."let me know"), into a string variable. Opening the file seems pretty straightforward. >>> import urllib >>> page = urllib.urlopen("http://diveintopython.org/") >>> source = page.read() >>> page.close() gets me to a string variable consisting of the un-parsed contents of the page. Now things get confusing, though, since there appear to be several approaches. One that I read somewhere was: >>> from xml.dom.ext.reader import HtmlLib >>> reader = HtmlLib.Reader() >>> doc = reader.fromString(source) This gets me doc as >>> paragraphs = doc.getElementsByTagName('p') gets me all of the paragraph children, and the one I specifically want can then be referenced with: paragraphs[5] This method seems to be pretty straightforward, but what do I do with it to get it into a string cleanly? >>> from xml.dom.ext import PrettyPrint >>> PrettyPrint(paragraphs[5]) shows me the text, but still in html, and I can't seem to get it to turn into a string variable, and I think the PrettyPrint function is unnecessary for what I want to do. Formatter seems to do what I want, but I can't figure out how to link the "Element Node" at paragraphs[5] with the formatter functions to produce the string I want as output. I tried some of the htmllib.HTMLParser(formatter stuff) examples, but while I can supposedly get that to work with formatter a little easier, I can't figure out how to get HTMLParser to drill down specifically to the 6th paragraph's contents. Thanks in advance. - A. From ms at cerenity.org Wed Jan 2 10:06:22 2008 From: ms at cerenity.org (Michael Sparks) Date: Wed, 02 Jan 2008 15:06:22 +0000 Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> Message-ID: <13nn9k48n7ohr95@corp.supernews.com> Aaron Watters wrote: (from a gmail account) > So cloud computing is java diskless workstations warmed over but less > flexible? > > I'm having trouble understanding why people would want > to buy in to this. Why do you like gmail - since you appear to use it? (I can think of several possibilities) The reason I ask Gmail is a an example of computing in the cloud. Specifically it's an application in the cloud. You get several classes of things "in the cloud" - one possible break up: * Applications - gmail, amazon, hotmail, facebook widgets, writely, blogger, flickr, etc. * Components - YUI, EC2, S3 * Frameworks - open social, facebook etc. Each has benefits. Some examples: * gmail, hotmail, yahoomail - spam filtering, access your mail anywhere. You rent the application by paying with attention (or paying money - I think hotmail still do that) * S3 - scalable storage in the cloud WITH scalable serving. The trade off here is "how much does it cost you to run a colo box or dedicated server" vs "how much to rent the space". You rent capacity on demand. (a bit like "why buy storage at a self-storage place rather than buy a garage?" - there are good reasons both ways round :-) * EC2 - Similar, but to do with computing capacity. EC2 & S3 allow you to scale for example in line _and in time_ with the size of your userbase - assuming your business model (if you have one :-) matches * open social, facebook - rather than build your own social graph, you can attach yourself to an existing one to simplify take-up. I must admit I feel a hint of amusement though at your comment above, when it's sent from precisely the sort of setup you appear bemused by - since you appear to have already bought into it without realising ! :-D Have fun :-) Michael. From musiccomposition at gmail.com Mon Jan 21 22:11:15 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 21 Jan 2008 19:11:15 -0800 (PST) Subject: read files References: Message-ID: <60708436-2175-4551-9193-253ba6dcb5a0@s12g2000prg.googlegroups.com> On Jan 21, 9:08 pm, Mel wrote: > J. Peng wrote: > > first I know this is the correct method to read and print a file: > > > fd = open("/etc/sysctl.conf") > > done=0 > > while not done: > > line = fd.readline() > > if line == '': > > done = 1 > > else: > > print line, > > > fd.close() > > > I dont like that flag of "done",then I tried to re-write it as: > > > fd = open("/etc/sysctl.conf") > > while line = fd.readline(): > > print line, > > fd.close() > > > this can't work.why? > > Formally, because line = fd.readline() is a statement, not an > expression, and it can't be put into an if statement like that. > > The most idiomatic way is probably > > fd = open ("/etc/sysctl.conf") > for line in fd: > print line more idiomatic in Python 2.5+: from __future__ import with_statement with open("/my/file.conf") as fd: for line in fd: print line > > Mel. From duncan.booth at invalid.invalid Wed Jan 9 06:34:14 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jan 2008 11:34:14 GMT Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: cesco wrote: > Hi, > > say I have a string like the following: > s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... > Here's yet another answer: from itertools import islice, cycle def interleave(*iterators): iterators = [ iter(i) for i in iterators ] while 1: for i in iterators: yield i.next() def punctuate(s): parts = s.split('_') punctuation = islice(cycle(':,'), len(parts)-1) return ''.join(interleave(parts, punctuation)) s1 = 'hi_cat_bye_dog' print punctuate(s1) # Or as a one-liner (once you have interleave): print ''.join(list(interleave(s1.split('_'), cycle(':,')))[:-1]) From dblubaugh at belcan.com Mon Jan 21 16:33:30 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 21 Jan 2008 16:33:30 -0500 Subject: pygep Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38021A5AFD@AWMAIL04.belcan.com> To Anyone out there!!!!!!!!!! I was wondering if anyone out there has had any experience with pygep program. this program is an open source version for Gene Expression Programming, which I will need to utilize in order to complete my Master's Thesis. Thanks for any help!!!!!! David Blubaugh -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Wed Jan 23 18:30:19 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 15:30:19 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <7x8x2g8isi.fsf@ruckus.brouhaha.com> <13pfgdct573772d@corp.supernews.com> Message-ID: <04d0ed52-4b45-4c07-8ea6-ab3bb3f85225@e25g2000prg.googlegroups.com> On Jan 24, 9:50 am, ryan k wrote: > Steven D'Aprano, you are a prick. And your reasons for coming to that stridently expressed conclusion after reading a posting that was *not* addressed to you are .....? From dannox at gmail.com Sat Jan 12 05:10:00 2008 From: dannox at gmail.com (whatazor) Date: Sat, 12 Jan 2008 02:10:00 -0800 (PST) Subject: upload file and estimation time Message-ID: Hi all, unseccsefully, I try to analyze this problem. If I can only work on the client size, how can I create a module that calculate the upload time of a file, so the time for finish it? i can start with ftp protocol and after extend this logic for my requirements. thx w From Scott.Daniels at Acm.Org Tue Jan 15 20:45:31 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 15 Jan 2008 17:45:31 -0800 Subject: print >> to a derived file In-Reply-To: References: Message-ID: <13oqo4ndh91mvbb@corp.supernews.com> iu2 wrote: > Hi, > > I'm trying to write data to both a file and the console, so I did: > > class File_and_console(file): > def write(self, s): > file.write(self, s) > print s, >>>> f = File_and_console('1.txt', 'w') ... Always use the same method for writing, or you will get weird results. If you think the above works, try: for char in 'sample': f.write(char) class MultiWrite(object): def write(self, text): for dest in self._files: dest.write(text) def __init__(self, *files): self._files = files def close(self): for dest in self._files: dest.close() f1 = MultiWrite(open('1.txt', 'w'), sys.stdout) --Scott David Daniels Scott.Daniels at Acm.Org From bazwal at googlemail.com Mon Jan 7 14:21:28 2008 From: bazwal at googlemail.com (Baz Walter) Date: Mon, 7 Jan 2008 19:21:28 +0000 (UTC) Subject: Does Python cache the startup module? References: Message-ID: Guilherme Polo gmail.com> writes: > Uhm.. this didn't make much sense. If you say the module is cached, > then supposing you did a minor edit, and then supposing because it is > cached your application wouldn't detect the change, then I don't see > the connection with memory leak. > > Bring some concrete proof. Thanks for your reply. It's hard to supply an example for this, since it is local to the machine I am using. The startup module would look something like this: #!/usr/local/bin/python if __name__ == '__main__': import sys from qt import QApplication, QWidget application = QApplication(sys.argv) mainwindow = QWidget() application.setMainWidget(mainwindow) mainwindow.show() sys.exit(application.exec_loop()) If I change the name 'mainwindow' to 'mainwidget', the widget it refers to does not get destroyed; when I change it back again, it does get destroyed. Otherwise, the program runs completely normally. From ojeeves at gmail.com Fri Jan 11 11:33:25 2008 From: ojeeves at gmail.com (oj) Date: Fri, 11 Jan 2008 08:33:25 -0800 (PST) Subject: Using eggs Message-ID: <9a2575c7-5b62-4f00-a813-635a82e96b79@k39g2000hsf.googlegroups.com> Hi all! As is about to become apparent, I really don't know what I'm doing when it comes to using eggs. I'm writing some software that is going to be deployed on a machine as a number of eggs. Which is all well and good. These eggs all end up depending on each other; modules in egg A want to import modules in egg B etc. It's not really practical to add the path to each individual egg to the PYTHONPATH (although there's all in a directory that is in PYTHONPATH). Do I have to add boiler-plate code to the beginning of all the modules with these dependencies to check if modules are available and require the eggs if they aren't? Or is there a way I can have stuff 'just work' as it does in the development environment when the modules haven't been bundled up into eggs? On a similar note, I can't seem to get the automatic script creation stuff in setuptools to create scripts that have additional requirements. I tried defining extra requires giving the names of other eggs that will be required, and then specifying these as extras to the console_scripts, but the generated scripts were no different. Am I doing something wrong? Or am I just not understanding something? I'm muddling through getting this all working at the moment, but I get the distinct impression that there's a better (correct?) way that I'm not aware of. Sorry for such a vague posting. -Oli From gagsl-py2 at yahoo.com.ar Mon Jan 21 20:42:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 23:42:27 -0200 Subject: Max Long References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> Message-ID: En Mon, 21 Jan 2008 22:02:34 -0200, mensanator at aol.com escribi?: > On Jan 21, 5:36?pm, Gary Herron wrote: >> tjhn... at gmail.com wrote: >> > How can I figure out the largest long available? ?I was hoping for >> >> There is no explicit (defined) limit. ?The amount of available address >> space forms a practical limit. > > But not the only limitation: > [...] > Traceback (most recent call last): > File "", line 2, in > a = cf.Type12MH(k,1) > File "C:\Program Files\PyGTK\Python\lib\collatz_functions.py", line > 745, in Type12MH > return TWO**(SIX*a - ONE) - ONE > ValueError: mpz.pow outrageous exponent > > The power function can't do exponents that have 32 or more bits > even if the memory can hold the resulting number. Isn't it a limitation of the gmpy library, not of the builtin long type? -- Gabriel Genellina From israelu at elbit.co.il Tue Jan 1 08:52:33 2008 From: israelu at elbit.co.il (iu2) Date: Tue, 1 Jan 2008 05:52:33 -0800 (PST) Subject: using super References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> <13nk5l6oah7mh9b@corp.supernews.com> Message-ID: <4649f96c-10af-4dd1-864c-f0690cec1980@p69g2000hsa.googlegroups.com> On Jan 1, 12:32?pm, Steven D'Aprano wrote: > > import read_my_mind_and_do_what_I_want > > first. (Module expected in Python 9.7, due out in 2058.) That's because it seems to you like some esoteric feature. To me it seems natural with OO. > "Special cases aren't special enough to break the rules." I thought about this mechanism each time I had to call a base class method. Lisp has it, out of the box. May be it's not so special... > Since you have to call the superclass yourself, there's not that much > difference between reminding people to call the superclass by hand, and > reminding them to call some decorator. Not necessarily. Once a class is declared with chains, its deriveratives don't really need the decorator (Python will know about it). And even with a decorator, what if the class has 5 methods? That's one decorator against 5 superclass calls. > Admittedly, a decorator for the most common cases would be easier to use > than super(), but I don't think it would make enough of a difference that > it is worth changing Python's object model just to make it possible. As > ... > And as others have pointed out, if you really want this desperately > enough, you can create a metaclass to handle it. > That's right. From bjourne at gmail.com Thu Jan 24 13:33:13 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 24 Jan 2008 19:33:13 +0100 Subject: Can someone explain this unexpected raw_input behavior? In-Reply-To: References: Message-ID: <740c3aec0801241033g4da8008ua76625793f15a4bd@mail.gmail.com> On Jan 24, 2008 8:08 AM, Gabriel Genellina wrote: > En Thu, 24 Jan 2008 01:00:53 -0200, Mike Kent escribi?: > > > Gabriel, thank you for clarifying the source of this behavior. Still, > > I'm surprised it would be hard-coded into Python. Consider an > > interactive program, that asks the user several questions, and > > displays paragraphs of information based on those questions. The > > paragraphs are output using print, and the questions are asked via > > raw_input. You want to do some simple debugging of the program by > > printing some debugging statements via 'print >>sys.stderr', and you > > don't want the debug output mixed in with the normal output on the > > screen, so you try to route the debugging output to a file by adding > > '2>filename' to the end of the command line. > > > > Unfortunately, you will no longer see any of the questions being > > printed via raw_input. The rest of the output will be fine, but the > > questions disappear. Your program just stops, without asking > > anything... you have to guess what should be there. > > You have one console, two streams to output data (stdout and stderr), and > three data sources (program output, user prompt, and debugging messages). > Someone has to give. > I'm now convinced that the current behavior is rather reasonable... If it weren't for the documentation... "If the prompt argument is present, it is written to *standard output* without a trailing newline." -- mvh Bj?rn From python.list at tim.thechases.com Mon Jan 14 17:07:12 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 14 Jan 2008 16:07:12 -0600 Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) In-Reply-To: <13onli9dk7mu926@corp.supernews.com> References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> <7xsl105fvv.fsf@ruckus.brouhaha.com> <13onli9dk7mu926@corp.supernews.com> Message-ID: <478BDD10.60203@tim.thechases.com> > But how can Python determine when you want the result to be *the > callable* and when you want it to be *the result of calling the > callable*? > > Functions and other callables are first-class objects, and it is quite > reasonable to have something like this: > > map = {'a': Aclass, 'b': Bclass, 'c': Cclass} > class_ = map.get(astring, default=Zclass) > > The result I want is the class, not the result of calling the class > (which would be an instance). If I wanted the other semantics, I'd be > using defaultdict instead. For an example of the defaultdict usage without calling it the first time: from collections import defaultdict def f(): print "Doing some expensive calculation" return 42 d = defaultdict(f) d['hello'] = 3.14159 print 'Hello:', d['hello'] print 'World:', d['world'] print 'World (again):', d['world'] This results in the expensive calculation only being executed once and having the result stored in the defaultdict. This is a good thing. If you're doing as Steven suggests, you can pass and store function objects or class objects with the same ease: > map = {'a': Aclass, 'b': Bclass, 'c': Cclass} > class_ = map.get(astring, default=Zclass) Other than tromping on the "map" built-in, one can then instantiate the given class with my_instance = map.get(astring, default=Zclass)(params) Perfect for the factory pattern if you groove on that sort of thing. -tkc From grante at visi.com Mon Jan 21 11:07:55 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 21 Jan 2008 16:07:55 -0000 Subject: dynamic type variable References: Message-ID: <13p9gqrtiecd809@corp.supernews.com> On 2008-01-21, J. Peng wrote: > Python's variable is dynamic type,is it? > But why this can't work? > >>>> 3 + 'a' It can't work because the compiler has no way of knowing whether the correct answer is '3a', 0x0d, the color purple, or to reboot. > So I see the number 3 can't be converted to string type automacially. Because I wanted the string 'a' to be converted to an integer automatically. -- Grant Edwards grante Yow! A can of ASPARAGUS, at 73 pigeons, some LIVE ammo, visi.com and a FROZEN DAQUIRI!! From jpeng at block.duxieweb.com Sun Jan 20 21:37:36 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Mon, 21 Jan 2008 10:37:36 +0800 Subject: dynamic type variable Message-ID: <47940570.6080003@block.duxieweb.com> Python's variable is dynamic type,is it? But why this can't work? >>> 3 + 'a' Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'int' and 'str' So I see the number 3 can't be converted to string type automacially. From dongie.agnir at gmail.com Thu Jan 10 07:04:00 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Thu, 10 Jan 2008 04:04:00 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: For the most part, I agree with you, which is why I chose Python in the first place. I like quick development. Unfortunately, this is one of those cases where execution time is a factor. Who knows, maybe someone who's done camera vision with Python will come in and say it's just the algorithm in the example that needs work (I'm crossing my fingers that that's the case). From nodrogbrown at gmail.com Sat Jan 26 02:33:29 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Fri, 25 Jan 2008 23:33:29 -0800 (PST) Subject: getting values from cache References: <480b367b-e5c4-4018-a968-8c146555dbdd@v29g2000hsf.googlegroups.com> Message-ID: <863ee5ee-dae2-4596-8ce2-e49c7a87207c@u10g2000prn.googlegroups.com> also if i were to write unit test for this method ,how shd i do it? shd i be checking all values in the matrix created inside and so on? gordon From arnodel at googlemail.com Sat Jan 19 04:36:24 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 19 Jan 2008 01:36:24 -0800 (PST) Subject: Is this a bug, or is it me? References: <87myr4o3sg.fsf@mulj.homelinux.net> <8afa3779-6803-43ed-ae4d-d0a102eda00d@x69g2000hsx.googlegroups.com> Message-ID: <8dafa095-4d24-444b-ba60-e878b63564a6@c23g2000hsa.googlegroups.com> On Jan 18, 7:01?pm, cptnwill... at gmail.com wrote: > I filed a bug report, and here is the short answer to my question: > genexps are code blocks, and code blocks cannot see variables in class > scopes. Congrats to Neil Cerutti who figured it out. > > Now here is another one for your enjoyment: > > class C: > ? ? ? ? @staticmethod > ? ? ? ? def f1(): pass > ? ? ? ? F = { '1' : f1 } > > C().F['1']() > > >>> TypeError: 'staticmethod' object is not callable > > What do you think of this one? It's normal, the staticmethod decorator's role is to 'flag up' the method as static for further processing when type(C).__new__ is called. -- Arnaud From duncan.booth at invalid.invalid Wed Jan 23 13:31:18 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jan 2008 18:31:18 GMT Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? References: <13peapj5o7pis0e@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Wed, 23 Jan 2008 09:30:28 +0000, Duncan Booth wrote: > >> Kristian Domke wrote: >> >>> foo = (not f and 1) or 0 >>> >>> In this case f may be None or a string. >>> >>> If I am not wrong here, one could simply write >>> >>> foo = not f >>> >>> >> Yes, it sounds pretty silly, and not just on the level you spotted. >> >> The only difference between the two expressions is that the original >> sets foo to an integer whereas your version sets it to a bool. So the >> question of which is most appropriate actually comes down to what foo >> is being used for. > > > But since Python bools are subclasses from int, both of them are > actually ints. One happens to look like 1, and the other looks like > True. The twisted code isn't incorrect, just twisted. :) From terry at jon.es Mon Jan 21 04:16:14 2008 From: terry at jon.es (Terry Jones) Date: Mon, 21 Jan 2008 10:16:14 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 23:51:41 on , 20 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> Message-ID: <18324.25310.406219.893317@terry.local> >>>>> "Paul" == Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: Hi Paul Paul> Here's my latest, which I think is exhaustive, but it is very slow. Paul> It prints a progress message now and then just to give the user some Paul> sign of life. It should print a total of 256-8 = 248 of those Paul> messages and it takes around 20 minutes on my old 1 Ghz Pentium 3. Paul> It does find plenty of solutions for 234, e.g. Paul> 234 mul(9,sub(mul(mul(6,mul(3,1)),7),100)) Paul> There are some obvious clunky ways to speed it up through memoizing Paul> and symmetry folding but I can't help thinking there's a concise Paul> elegant way to do that too. The symmetry folding is important, you can cut off many recursive calls. My code runs in 0.5 seconds for the 234 problem, but I have a MacBook Pro :-) Terry From sjmachin at lexicon.net Tue Jan 8 03:46:56 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 8 Jan 2008 00:46:56 -0800 (PST) Subject: Look for a string on a file and get its line number References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> Message-ID: <9889cbd0-c19e-4b76-8c41-aa621a188661@e4g2000hsg.googlegroups.com> On Jan 8, 7:33 pm, Jeroen Ruigrok van der Werven wrote: > -On [20080108 09:21], Horacius ReX (horacius.... at gmail.com) wrote: > > >I have to search for a string on a big file. Once this string is > >found, I would need to get the number of the line in which the string > >is located on the file. Do you know how if this is possible to do in > >python ? > > (Assuming ASCII, otherwise check out codecs.open().) > > big_file = open('bigfile.txt', 'r') > > line_nr = 0 > for line in big_file: > line_nr += 1 > has_match = line.find('my-string') > if has_match > 0: Make that >= | >>> 'fubar'.find('fu') | 0 | >>> > print 'Found in line %d' % (line_nr) From eproust at gmail.com Sun Jan 20 06:03:41 2008 From: eproust at gmail.com (pythonewbie) Date: Sun, 20 Jan 2008 03:03:41 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt Message-ID: Hi all, I am newbie in Python, my wish would be to create python applications for both Linux/Win32. I am stucked on creating a function to get the Python install directory (and site-packages directory) with a 100% reliable method... My goal is to verify if an/several extension(s) are installed and to automatically install the missing ones on Linux or Win32. I have tested sys.executable and sys.path, but I am not sure to be able to get what I need on different versions of Python and different platforms. Google was not a good friend on this, so I am very interested on how you implement such a function. Cheers. From mag_dex at o2.pl Sat Jan 26 05:15:18 2008 From: mag_dex at o2.pl (mag_dex) Date: Sat, 26 Jan 2008 02:15:18 -0800 (PST) Subject: urllib + Microsoft VBScript Message-ID: <050632b0-68e6-4659-9bba-f148340b07ab@k2g2000hse.googlegroups.com> Hi, I have a problem, I wanna write script to get result from web tools http://202.120.37.186/bioinf/Gpos/index.htm I created script like this: #!/usr/bin/python import urllib def do_GposLoc(job_id,v=1): seqOfProtein = """>P46748""".strip() + '\r\n' seqOfProtein += """MKTLSILDTIIKIPEKIEIHPTTTEYIYTITGPLGSSSINLKKLDKNGIACINFDIQNKQ VLIRSLYPKYNGLYKKLIENKFLGVSRGFCVYLEIVGVGYRAALLSSSLQNSTKDTNDTI VLKLGHSHDIHYKVPNGVRVFLQSPSEICIFGVDLNQVTQVAHSIRNTRPPSVYKGKGIR YTNEKIVTKTGKRK """ # print seqOfProtein address= "http://202.120.37.186/bioinf/Gpos/Gpos-PSLPred- upload.asp?act=upload" params = urllib.urlencode( {'mode': 'string', 'S1':seqOfProtein, 'B1': 'Submit'}) # f = urllib.urlopen(address, params) content = f.read() if v:print content return 0 if '__main__'==__name__: job_id='f' do_GposLoc(job_id) and I got result like this:

Microsoft VBScript ?????????? ???? '800a03f6'

??? 'End'

/iisHelp/common/500-100.asp????242

Microsoft VBScript ????????? ???? '800a0005'

????????????????: 'right'

/bioinf/Gpos/Gpos-PSLPred-upload.asp????21 Yeah, I know these strange chars it's from wrong codding. But I can't get the same result as I would post it 'by hand' opening http://202.120.37.186/bioinf/Gpos/index.htm i submit the sequence: >P46748 MKTLSILDTIIKIPEKIEIHPTTTEYIYTITGPLGSSSINLKKLDKNGIACINFDIQNKQ VLIRSLYPKYNGLYKKLIENKFLGVSRGFCVYLEIVGVGYRAALLSSSLQNSTKDTNDTI VLKLGHSHDIHYKVPNGVRVFLQSPSEICIFGVDLNQVTQVAHSIRNTRPPSVYKGKGIR YTNEKIVTKTGKRK Maybe sb has idea how to solve this problem. Regards Marcin From pofuk at mzm.hr Wed Jan 2 08:04:47 2008 From: pofuk at mzm.hr (SMALLp) Date: Wed, 02 Jan 2008 14:04:47 +0100 Subject: Python events, panel with text In-Reply-To: References: Message-ID: SMALLp wrote: > Hy! > > I have many small panels with text and I want do bind wx.EVT_LEFT_DOWN > when clicked on panel, but i need to bind that in parent class. So I > have instance of that small panel and when i bind it efects only part of > small panel where is no text. > > > > import wx > > class RequestedFilesItems(wx.Panel): > def __init__(self, parent, id): > wx.Panel.__init__(self, parent, -1, style=wx.SUNKEN_BORDER) > sizer = wx.BoxSizer(wx.HORIZONTAL) > > upButton = PanelButton(self, -1, "Upload") > upButton.Bind(wx.EVT_LEFT_DOWN, self.upload) i did smothing like this nad it works but id doesn't look so good: upButton.text.Bind(wx.EVT_LEFT_DOWN, self.upload) > sizer.Add(upButton, 0, wx.LEFT, 15) > > > > self.SetSizer(sizer) > > def upload(self, event): > print "Please print this" > > > > class PanelButton(wx.Panel): > def __init__(self, parent, id, buttonName): > wx.Panel.__init__(self, parent, -1, style=wx.SUNKEN_BORDER) > self.SetBackgroundColour("GREY") > sizer = wx.BoxSizer(wx.HORIZONTAL) > self.text = wx.StaticText(self, -1, buttonName) > sizer.Add(self.text, -1, wx.EXPAND | wx.ALL, 1) > self.text.Bind(wx.EVT_LEFT_DOWN, self.OnClick) > self.SetSizer(sizer) > > def OnClick(self, event): > print "It only works for text, not for panel what I expected here" > > > if __name__ == '__main__': > app = wx.PySimpleApp() > frm = wx.Frame(None, wx.ID_ANY, 'Mouse-click test') > panel = RequestedFilesItems(frm, wx.ID_ANY) > frm.Show() > app.MainLoop() > > > > app.MainLoop() > > From cwitts at gmail.com Fri Jan 4 03:03:34 2008 From: cwitts at gmail.com (Chris) Date: Fri, 4 Jan 2008 00:03:34 -0800 (PST) Subject: Cursors in a Loop References: <3da337d8-2de0-4fdb-8c38-2f6fcd8348ac@i72g2000hsd.googlegroups.com> Message-ID: On Jan 4, 5:11 am, Carsten Haese wrote: > On Thu, 2008-01-03 at 17:25 -0800, t_rectenwald wrote: > > On Jan 3, 7:47 pm, t_rectenwald wrote: > > > I have a python script that uses the cx_Oracle module. I have a list > > > of values that I iterate through via a for loop and then insert into > > > the database. This works okay, but I'm not sure whether I can use one > > > cursor for all inserts, and define it outside of the loop, or > > > instantiate and close the cursor within the loop itself. For example, > > > I have: > > > > for i in hostlist: > > > cursor = connection.cursor() > > > sql= "insert into as_siebel_hosts_temp values('%s')" % (i) > > > cursor.execute(sql) > > > cursor.close() > > > > And I've also tried: > > > > cursor = connection.cursor() > > > for i in hostlist: > > > sql= "insert into as_siebel_hosts_temp values('%s')" % (i) > > > cursor.execute(sql) > > > cursor.close() > > > > Both work fine, and execute in the same amount of time. I'm just > > > trying to understand what is the "correct" approach to use. > > Even better would be to use executemany: > > cursor = connection.cursor() > cursor.executemany("insert into as_siebel_hosts_temp values(?)", > [(i,) for i in hostlist] ) > cursor.close() > > Depending on whether cx_Oracle allows this, the list comprehension in > that example could be replaced by the generator expression > ((i,) for i in hostlist), but I don't know if cx_Oracle allows > executemany with an arbitrary iterable. You should bind all variables to save the pool. cursor = connection.cursor() cursor.executemany("""insert into as_siebel_hosts_temp values (:whole, :lot, :of, :bind, :variables) """ ,[(i,)[0] for i in hostlist] ) connection.commit() connection.close() From henry.baxter at gmail.com Fri Jan 25 16:39:35 2008 From: henry.baxter at gmail.com (Henry Baxter) Date: Fri, 25 Jan 2008 13:39:35 -0800 Subject: Index of maximum element in list In-Reply-To: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> Message-ID: <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> Oops, gmail has keyboard shortcuts apparently, to continue: def maxi(l): m = max(l) for i, v in enumerate(l): if m == v: return i But it seems like something that should be built in - or at least I should be able to write a lambda function for it, but I'm not sure how to do that either...Suggestions are very much welcome! On Jan 25, 2008 1:37 PM, Henry Baxter wrote: > I apologize if this has already been discussed - funnily enough my > googling did bring up a previous thread about it on this mailing list, but > despite the promising subject line, seemed to mainly be concerned with > whether python-list should its own FAQ...so I assume this has been asked > many times before, but my apologies I cannot find the answer. Here is what I > have: > > def maxi(l): > > it > -- > Henry -- Henry -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Tue Jan 22 13:58:50 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 22 Jan 2008 13:58:50 -0500 Subject: printing escape character In-Reply-To: References: Message-ID: <16651e80801221058q615fd16dvc17c6eb4ac6e2d40@mail.gmail.com> On Jan 22, 2008 1:38 PM, hrochonwo wrote: > Hi, > > I want to print string without "decoding" escaped characters to > newline etc. > like print "a\nb" -> a\nb > is there a simple way to do it in python or should i somehow use > string.replace(..) function ? >>> print 'a\nb'.encode('string_escape') a\nb -- Jerry From bignose+hates-spam at benfinney.id.au Mon Jan 14 23:15:10 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 15:15:10 +1100 Subject: module naming conventions References: <7f39199a-3334-4bcc-a424-5102f042ed01@1g2000hsl.googlegroups.com> <87zlv8dnya.fsf@benfinney.id.au> <6a53a14a-8f7c-4b6b-986f-48c7698f679f@v29g2000hsf.googlegroups.com> <8763xwdj9c.fsf@benfinney.id.au> <972e17b4-2d1a-43d6-8382-21585b0fe786@v29g2000hsf.googlegroups.com> Message-ID: <87sl0zd8s1.fsf@benfinney.id.au> grackle writes: > On Jan 14, 6:28 pm, Ben Finney > wrote: > > Release your package as free software on the Cheeseshop > > . If the name you want is > > already taken, pick one that will help users distinguish yours > > from the existing one. > > Unfortunately, my company thinks it's their software and not mine :-) That's fine. Companies can release (and sell!) freely-licensed software too, and many of them do so. You, as someone who works there and is presumably responsible for this package, have leverage more than anyone else in this discussion to make it happen. -- \ "I spent a lot of money on wine and women, and like a fool I | `\ squandered the rest." -- Benny Hill | _o__) | Ben Finney From lists at cheimes.de Wed Jan 23 08:21:11 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 23 Jan 2008 14:21:11 +0100 Subject: translating Python to Assembler In-Reply-To: References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: Wim Vander Schelden wrote: > I didn't know that python uses a VM, I thought it still used an > interpretter! You > learn something new everyday :) still? I don't think Python ever used a different model. Most modern languages are using an interpreted byte code approach: http://en.wikipedia.org/wiki/Interpreted_language#Languages_usually_compiled_to_a_virtual_machine_code IMHO .NET/C# is missing from the list. Christian From jr9445 at ATT.COM Thu Jan 24 10:30:33 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 24 Jan 2008 09:30:33 -0600 Subject: Stripping whitespace In-Reply-To: <7920ea6d-fdb0-4c83-826d-3e5829a6ec0f@t1g2000pra.googlegroups.com> References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com><5vphe6F1njt09U1@mid.uni-berlin.de><12d19814-b7b9-44b0-aee3-299befac7279@i12g2000prf.googlegroups.com> <66446d1e-189c-4c24-bd7a-83cbd66deb60@i12g2000prf.googlegroups.com> <7920ea6d-fdb0-4c83-826d-3e5829a6ec0f@t1g2000pra.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 John Machin > Sent: Wednesday, January 23, 2008 5:48 PM > To: python-list at python.org > Subject: Re: Stripping whitespace > > On Jan 24, 7:57 am, "Reedick, Andrew" wrote: > > > > Why is it that so many Python people are regex adverse? Use the > dashed > > line as a regex. Convert the dashes to dots. Wrap the dots in > > parentheses. Convert the whitespace chars to '\s'. Presto! > Simpler, > > cleaner code. > > > pattern = re.sub(r'-', r'.', line) > > pattern = re.sub(r'\s', r'\\s', pattern) > > pattern = re.sub(r'([.]+)', r'(\1)', pattern) > > Consider this: > pattern = ' '.join('(.{%d})' % len(x) for x in line.split()) > Good. But the main drawback to using split+join is that it works if there is only one whitespace char acting as a column separator (split+join will compress multiple whitespace characters down to one char.) Normally, it's safe to assume a one character separator between columns, however since the input is supposed to be tab delimited (but wasn't) and tabs tend to get randomly converted to spaces depending on which butterfly is flapping its wings at any given instant, keeping the original whitespace column separators is probably a good idea. ***** 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. GA622 From bj_666 at gmx.net Wed Jan 30 07:38:31 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jan 2008 12:38:31 GMT Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> Message-ID: <60b9e7F1ps52dU4@mid.uni-berlin.de> On Tue, 29 Jan 2008 11:48:38 -0800, Tobiah wrote: > class genital: > > def pubic_hair(self): > pass > > def remove(self): > del(self.pubic_hair) I think `pubic_hair` is an attribute instead of a method. Oh, and ``del`` is a statement and not a function. So the way you wrote it with parentheses is a bit misleading. Ciao, Marc 'BlackJack' Rintsch From RobKapteyn at gmail.com Fri Jan 11 23:48:18 2008 From: RobKapteyn at gmail.com (Rob Kapteyn) Date: Fri, 11 Jan 2008 20:48:18 -0800 (PST) Subject: Persistent HTTP Connections with Python? References: Message-ID: <5c2898bb-a9a8-4b6f-8249-135b9cd3a015@k2g2000hse.googlegroups.com> On Jan 10, 12:46?pm, Scott Sharkey wrote: > Hello All, > > I am trying to write a python script to talk to an xml-based stock feed > service. ?They are telling me that I must connect and login, and then > "issue refresh requests" to fetch the data. ?This sounds a lot (to me) > like HTTP 1.1persistentconnections. ?Can I do that with the urllib > functions, or do I need to use the httplib functions for this kind of > work. ?Pointers and/or sample code would be much appreciated. > > Thanks! > > -scott I used to work in the financial industry and I have seen this. It is sort of like the XML RSS feed that web sites provide -- but like many financial protocols they created their own standard. Python httplib can be used to create a SERVER for persistent HTTP connections -- but want you want is a client. I think this is actually very simple. What happens when you open the data URL with a web browser ? Does the connection stay open and automatically update each time there is new data ? If so, just use urllib, leave the connection open and do a read() every so often to see if there is new data. Good luck! -Rob From electronixtar at gmail.com Wed Jan 2 07:52:09 2008 From: electronixtar at gmail.com (est) Date: Wed, 2 Jan 2008 04:52:09 -0800 (PST) Subject: dbus-python for windows References: <194e7fee-728a-48eb-9f51-1e272ecca838@j20g2000hsi.googlegroups.com> Message-ID: <318313d5-2ead-487c-a959-2bdfd3627db4@e50g2000hsh.googlegroups.com> I am not going to compile anything like that :) and I only need Windows library for dbus-python ps Windows source code is here https://windbus.svn.sourceforge.net/svnroot/windbus/trunk/ On Jan 2, 8:44 pm, Jeroen Ruigrok van der Werven wrote: > -On [20080102 13:41], est (electronix... at gmail.com) wrote: > > >I am trying to port Scribes to Windows, but I could not find a package > >named dbus-python for windows. There is a windbus >sourceforge.net/projects/windbus/> but it not for Python, so how could > >I install dbus module for Windows Python 2.5 ? > > Well, I assume using the source fromhttp://dbus.freedesktop.org/releases/dbus-python/and trying to build it > fails on Windows? (I readily admit I have little clue how much of dbus is > platform-specific.) > > -- > Jeroen Ruigrok van der Werven / asmodai > ????? ?????? ??? ?? ??????http://www.in-nomine.org/|http://www.rangaku.org/ > Resolve to find thyself; and to know that he who finds himself, loses > his misery... From sjmachin at lexicon.net Sat Jan 12 16:51:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 12 Jan 2008 13:51:18 -0800 (PST) Subject: Is unicode.lower() locale-independent? References: <871w8ni60t.fsf@physik.rwth-aachen.de> Message-ID: <8b781e43-c3c0-4113-a9a1-7351fb377d0d@i3g2000hsf.googlegroups.com> On Jan 12, 11:26 pm, Torsten Bronger wrote: > Hall?chen! > > > > Fredrik Lundh writes: > > Robert Kern wrote: > > >>> However it appears from your bug ticket that you have a much > >>> narrower problem (case-shifting a small known list of English > >>> words like VOID) and can work around it by writing your own > >>> locale-independent casing functions. Do you still need to find > >>> out whether Python unicode casings are locale-dependent? > > >> I would still like to know. There are other places where .lower() > >> is used in numpy, not to mention the rest of my code. > > > "lower" uses the informative case mappings provided by the Unicode > > character database; see > > > http://www.unicode.org/Public/4.1.0/ucd/UCD.html > > > afaik, changing the locale has no influence whatsoever on Python's > > Unicode subsystem. > > Slightly off-topic because it's not part of the Unicode subsystem, > but I was once irritated that the none-breaking space (codepoint xa0 > I think) was included into string.whitespace. I cannot reproduce it > on my current system anymore, but I was pretty sure it occured with > a fr_FR.UTF-8 locale. Is this possible? And who is to blame, or > must my program cope with such things? The NO-BREAK SPACE is treated as whitespace in the Python unicode subsystem. As for str objects, the default "C" locale doesn't know it exists; otherwise AFAIK if the character set for the locale has it, it will be treated as whitespace. You were irritated because non-break SPACE was included in string.whiteSPACE? Surely not! It seems eminently logical to me. Perhaps you were irritated because str.split() ignored the "no-break"? If like me you had been faced with removing trailing spaces from text columns in databases, you surely would have been delighted that str.rstrip() removed the trailing-padding-for-nicer-layout no-break spaces that the users had copy/pasted from some clown's website :-) What was the *real* cause of your irritation? From lasses_weil at klapptsowieso.net Sun Jan 27 13:05:15 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 27 Jan 2008 19:05:15 +0100 Subject: Exceptions on delete in pysqlite In-Reply-To: References: <479a7b0c$0$9119$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <479cc7dc$0$25378$9b4e6d93@newsspool4.arcor-online.net> Gabriel Genellina wrote: > En Fri, 25 Jan 2008 22:12:57 -0200, Wildemar Wildenburger > escribi?: > >> Using pysqlite, I'd like to check if some dataset that I removed has >> been in the database at all. Ideally I'd like pysqlite to raise an >> Exception if deleting does nothing. Is that possible? > > I don't think so. It isn't an error, like a SELECT which returns an > empty set isn't an error either. > Of course, but you know ... I was hoping. >> Codewise, I'd like the following, but without me checking for and >> raising the exception myself: >> >> cur = con.execute("""DELETE FROM SomeTable WHERE id=? AND name=?""", >> (ID, NAME)) >> if cur.rowcount == 0: >> raise Exception > > Write a function to do that. > Yeah well you see, I have several similar functions for inserting, updating and deleting on different tables. And I wanted them all to behave uniformly, raising some exception when the operation did not do quite right (in this case: delete something that is not there.). That way, all those functions would even have looked similar, and I would have liked that for readability. Or for my autism, you pick. :) Well, thanks anyway. :) /W From Shawn at Milochik.com Thu Jan 31 14:16:47 2008 From: Shawn at Milochik.com (Shawn Milochik) Date: Thu, 31 Jan 2008 14:16:47 -0500 Subject: Python for mobiles In-Reply-To: References: <03e0ad28-e72c-4582-8518-b5cb07d408df@e10g2000prf.googlegroups.com> Message-ID: <1201807007.31585.20.camel@smilochik-lin> A better solution would surely be to get a Nokia S60 'phone, for which there is a native Python implementation. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Steve: Do you know if the Nokia E60i phone has this capability? Also, is wxPython supported? Or are you just knowledgeable about the S60? Thanks, Shawn From Scott.Daniels at Acm.Org Wed Jan 9 09:06:40 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 09 Jan 2008 06:06:40 -0800 Subject: Converting a bidimensional list in a bidimensional array In-Reply-To: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> Message-ID: <13o9kupahavp952@corp.supernews.com> Santiago Romero wrote: > I'm trying to change my current working source code so that it works > with an array instead of using a list, but I'm not managing to do it. > ... > > This is how I create the tilemap (and the clipboard, a copy of my > tilemap): > > def __init__( self, bw, bh, tiles ): > self.width, self.height = bw, bh > self.tilemap = [] > self.clipboard = [] > (...) > for i in range(bh): > self.tilemap.append([0] * bw) > self.clipboard.append([0] * bw) def __init__( self, bw, bh, tiles ): self.width, self.height = bw, bh self.tilemap = array.array('b', [0]) * bw * bh self.clipboard = array.array('b', self.tilemap) Gives a pure linearization (you do the math for lines). def __init__( self, bw, bh, tiles ): self.width, self.height = bw, bh self.tilemap = [array.array('b', [0]) * bw for row in range(bh)] self.clipboard = [array.array('b', [0]) * bw for row in range(bh)] Gives a list of arrays. I punted on the type arg here; you should make a definite decision based on your data. --Scott David Daniels Scott.Daniels at Acm.Org From giles_brown at hotmail.com Tue Jan 8 14:21:19 2008 From: giles_brown at hotmail.com (Giles Brown) Date: Tue, 8 Jan 2008 11:21:19 -0800 (PST) Subject: COM server and EXE References: Message-ID: <0dcc9dfc-f789-4855-9c59-1de7fea54618@q39g2000hsf.googlegroups.com> On 8 Jan, 11:04, Teja wrote: > On Jan 8, 3:33 pm, Teja wrote: > > > > > Hi All, > > > I have a Python COM server. I need to deploy it on various sytems. > > When I run the COM server from > > python its showing an output " Registered : sample.lib" > > > If I try to use the COM obj from a VB client like: > > > obj = CreateObject("sample.lib") > > > Its working fine without any errors > > > Now I am trying to convert this COM server to an exe through py2exe > > and after I run the exe, I am > > getting the same output " Registered : sample.lib" > > > But If I try to use the COM obj from a VB client like > > > obj = CreateObject("sample.lib") > > > A console pops up saying " Registered : sample.lib" and VB application > > hangs there. > > Its throwing a VB error that "ActiveX object cannot be > > created......etc etc" > > > Any suggestions please....... > > > Regards, > > Tejovathi > > Here is my sample COM server and py2exe setup file > > testCOM.py > > import win32com.client > import os.path > import shutil > from win32api import Sleep > import string > import os > import sys > import pythoncom > > class FirstEx: > > _reg_clsid_ = "{A6DE9DF8-5EBF-48E6-889E-C71CB84CFF2C}" > pythoncom.frozen = 1 > if hasattr(sys, 'importers'): > # In the py2exe-packed version, specify the module.class > # to use. In the python script version, python is able > # to figure it out itself. > _reg_class_spec_ = "__main__.FirstEx" > _reg_desc_ = "My first COM server" > _reg_progid_ = "SAMPLE.Lib" > _public_methods_ = ['init', 'Version'] > _public_attrs_ = ['softspace', 'noCalls'] > _readonly_attrs_ = ['noCalls'] > _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER > > def __init__(self): > self.softspace = 1 > self.noCalls = 0 > > def Version(self): > self.noCalls = self.noCalls + 1 > > # insert "softspace" number of spaces > return "Version: 0.0.1" > > if __name__=='__main__': > import sys > if hasattr(sys, 'importers'): > # running as packed executable. > if '--register' in sys.argv[1:] or '--unregister' in > sys.argv[1:]: > # --register and --unregister work as usual > import win32com.server.register > win32com.server.register.UseCommandLine(FirstEx) > else: > # start the server. > from win32com.server import localserver > localserver.main() > else: > import win32com.server.register > win32com.server.register.UseCommandLine(FirstEx) > > Here is my setup file: > > #Start here > from distutils.core import setup > import py2exe > > setup(options = {"py2exe": {"compressed": 1, > "optimize": 2, > "ascii": 1, > "bundle_files": 1}}, > zipfile = None, > com_server = ["win32com.servers.interp"], > console = ["testCOM.py"]) > #End here > > Here is my VB code: > > Sub subRoutine() > Dim connection As Object > Dim returnvalue1 As String > Dim returnvalue2 As String > Dim flag3 As Boolean > > Set connection = CreateObject("SAMPLE.Lib") > returnvalue1 = connection.Version() > MsgBox (returnvalue1) > End Sub > > The non exe version of the COM server ie. directlly running the > testCOM.py registers the library properly and > > in the VB application, the message box displays the version as 0.0.1. > > But, after I create the EXE file using the setup.py file and run it, > it registers the library. > > When I run the VB application, it hangs at the line > > Set connection = CreateObject("SAMPLE.Lib") > > and displays. " ACTIVEX cannot create the object" > > Any suggestions please.... A quick suggestion (didn't read very carefully sorry). Make sure you register it with --debug and use the pythonwin tools- >trace collector debugging tool. See if you get any joy. It may be you missed some vital library in your py2exe that causes a start-up time failure. Giles From asmodai at in-nomine.org Sat Jan 5 05:35:17 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 5 Jan 2008 11:35:17 +0100 Subject: Fortran to Python In-Reply-To: <95d2fc8c-d95c-4f1f-8770-cd89c1295d3c@d21g2000prf.googlegroups.com> References: <95d2fc8c-d95c-4f1f-8770-cd89c1295d3c@d21g2000prf.googlegroups.com> Message-ID: <20080105103517.GS82115@nexus.in-nomine.org> -On [20080105 11:21], MartinRinehart at gmail.com (MartinRinehart at gmail.com) wrote: >Why convert? Modern Fortran is an object oriented, structured language >with the singular advantage that it can run old Fortran programs. With all due respect to Fortran but I find the syntax to be utterly horrendous. :) Furthermore, the code is not really heavy number crunching in that it seems to warrant explicit use in Fortran. At most it takes about 2 seconds on a current day PC to calculate some of these values. Furthermore it currently has a dependency on the Visual Numerics IMSL library. For just some calculations to warrant the cost of both this library and a Fortran compiler seems a bit excessive. Given we use Matlab in-house, next to C# (and perhaps F# in the future), and some Python it makes more sense to stick to your domain-specific knowledge rather than maintaining some relic from the past. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ For ever, brother, hail and farewell... From gagsl-py2 at yahoo.com.ar Tue Jan 29 16:44:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jan 2008 19:44:33 -0200 Subject: Fwd: Help! - Invoke setup.py file References: <7856b4e60801190232j3b1a18b5n3630ddf77aed9ee0@mail.gmail.com> <7856b4e60801210138w5e71a977w473db4bea0cba43c@mail.gmail.com> Message-ID: En Mon, 21 Jan 2008 07:38:15 -0200, Vikas Jadhav escribi?: > We have setup of SVGMath* 0.3.2 (Converter- Mathml 2.0 coding to SVG). > The > setup folder contains setup.py file but we are not able to initiate this > file. Kindly help us, resolution to this query will be appreciated. > Python version: Installed on PC- 2.5.1 and OS- Windows 2000. Unless the author provides more specific instructions to install the package, the usual way is: - Unpack the archive in any temporary directory - Open a console (CMD) and change to that temporary directory - Execute this command: python setup.py install - That's all If you get any error, post the whole error message here, but for specific help on that package it would be better to contact the author directly. -- Gabriel Genellina From jarausch at igpm.rwth-aachen.de Tue Jan 22 07:58:55 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 22 Jan 2008 13:58:55 +0100 Subject: ctypes CDLL - which paths are searched? In-Reply-To: References: <4794d573$0$2980$ba620e4c@news.skynet.be> Message-ID: <4795E88F.7050406@igpm.rwth-aachen.de> Thomas Heller wrote: > Helmut Jarausch schrieb: >> Hi, >> >> how can I specify the paths to be searched for a dynamic library >> to be loaded by ctypes' CDLL class on a Linux system. >> >> Do I have to set os.environment['LD_LIBRARY_PATH'] ? >> > > ctypes passes the argument given to CDLL(path) straight to > the dlopen(3) call, so your system documentation should tell you. > Thanks, but then it's difficult to use CDLL. Setting os.environ['LD_LIBRARY_PATH'] within the script which calls CDLL is too late. What other methods are possible rather than put an explicit export LD_LIBRARY_PATH=... before running the script, if I don't want to put the dynamic library into a standard system library. Many thanks, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From pavlovevidence at gmail.com Tue Jan 29 12:02:45 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jan 2008 09:02:45 -0800 (PST) Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> Message-ID: <0a285e6e-a3a9-4be9-ae59-4cb7547ffa3a@q21g2000hsa.googlegroups.com> On Jan 29, 7:48 am, Peter Schuller wrote: > > You can also put, in animal/__init__.py: > > from monkey import Monkey > > and now you can refer to it as org.lib.animal.Monkey, but keep the > > implementation of Monkey class and all related stuff into > > .../animal/monkey.py > > The problem is that we are now back to the identity problem. The class > won't actually *BE* org.lib.animal.Monkey. The usage is the same; it works in all cases once you redefine __module__. Who cares what it really is? > Perhaps manipulating > __module__ is enough; perhaps not (for example, what about > sys.modules?). It's enough. It satisfies the criteria you listed. sys.modules has nothing to do with it. Monkey is a class, not a module. If you set __module__, the only remaining discernable difference is that the global variables accessed from the Monkey class will be in org.lib.animal.monkey instead of org.lib.animal. This has no ill effects when unpickling or instantiating the class from org.lib.animal. > Looks like I'll just live with putting more than I > would like in the same file. Whatever. ISTM you came here looking for a particular means and not a particular end. Python already has the power to meet your stated needs, but you won't use that solution because it's "hacky". Apparently all you really wanted was the loosened file structure in the first place. Carl Banks From usenet at janc.be Tue Jan 15 12:53:56 2008 From: usenet at janc.be (Jan Claeys) Date: Tue, 15 Jan 2008 17:53:56 GMT Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: Op Mon, 07 Jan 2008 05:09:15 -0800, schreef MartinRinehart: > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is _______. > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > "grace" but I'm not sure I've done enough to choose. The best thing about Python is how it tries to find the "perfect" balance between elegance, practicality & clarity. -- JanC From hyperneato at gmail.com Fri Jan 4 05:19:50 2008 From: hyperneato at gmail.com (stuntgoat) Date: Fri, 4 Jan 2008 02:19:50 -0800 (PST) Subject: import zlib in 2.5 fails Message-ID: import zlib works in Python 2.4 (debian etch AMD64 - default python version for that distro) I built python 2.5 from source; zlib is not importable. I am trying to compile MySQLdb. any clues about how to get zlib able to be imported in 2.5? -sg From http Mon Jan 21 02:51:41 2008 From: http (Paul Rubin) Date: 20 Jan 2008 23:51:41 -0800 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> Message-ID: <7xlk6j7h0y.fsf@ruckus.brouhaha.com> Arnaud Delobelle writes: > After a quick glance at your code it seems to me that you can only > have solutions of the type: > (num, num, op, num, op, num, op, num, op, num, op) > this omits many possible solutions (see the one above). Here's my latest, which I think is exhaustive, but it is very slow. It prints a progress message now and then just to give the user some sign of life. It should print a total of 256-8 = 248 of those messages and it takes around 20 minutes on my old 1 Ghz Pentium 3. It does find plenty of solutions for 234, e.g. 234 mul(9,sub(mul(mul(6,mul(3,1)),7),100)) There are some obvious clunky ways to speed it up through memoizing and symmetry folding but I can't help thinking there's a concise elegant way to do that too. ================================================================ from operator import * from time import time, ctime start_time = time() def partition(k): for i in xrange(1, (1<', n0s, f, '%.3f'%(time()-start_time) for r0,t0 in countdown(n0s, trace, ams): for r1,t1 in countdown(n1s, trace, ams): if f != div or r1 != 0 and r0 % r1 == 0: yield f(r0, r1), \ '%s(%s,%s)'% (f.__name__, t0, t1) def find_repr(target, nums): for x,t in countdown(nums): if x == target: print x,t print ctime() find_repr(234, [100,9,7,6,3,1]) From vinay_sajip at yahoo.co.uk Thu Jan 17 10:49:32 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 17 Jan 2008 07:49:32 -0800 (PST) Subject: handlers.SocketHandler and exceptions References: <02de2e9c-331d-45c0-afaa-578ddad55664@j78g2000hsd.googlegroups.com> Message-ID: On Jan 17, 1:47 pm, writeson wrote: > Mark, > > > > > Check out the traceback module. It can translate the traceback into a > > variety of formats (such as a string) that can be pickled. > > > --Mark > > Thanks for the reply. I was looking at the traceback module and > thinking along the same lines you are. The problem I'm having with > that is how to modify the behavior of the SocketHandler code so it > would call the traceback module functions. The point at which the > handlers.SocketHandler code fails is in the method makePickle(), and > I'm not sure how to overload/override that method. I tried creating my > own class: > > class MySocketHandler(handlers.SocketHandler): > def makePickle(self, record): > # perform new code that transforms a Traceback object into a > string > > but so far I haven't figured out how to get theloggingmodule to use > my class. In myloggingconfiguration file I tried something like > this: > > [handler_local_server] > class=mydirectory.MySocketHandler > level=DEBUG > formatter=general > args=("localhost", handlers.DEFAULT_TCP_LOGGING_PORT + 1) > > but I can't seem to get theloggingmodule to include mydirectory in > its search path for modules. > > So that's where I'm stuck now. > > Again, thanks for your response, > Doug What version of Python are you running? Recent versions should have a fix for this. Here's the makePickle method of SocketHandler: def makePickle(self, record): """ Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket. """ ei = record.exc_info if ei: dummy = self.format(record) # just to get traceback text into record.exc_text record.exc_info = None # to avoid Unpickleable error s = cPickle.dumps(record.__dict__, 1) if ei: record.exc_info = ei # for next handler slen = struct.pack(">L", len(s)) return slen + s Notice the code to avoid the Unpickleable error. Best regards, Vinay Sajip From steve at REMOVE-THIS-cybersource.com.au Tue Jan 1 17:05:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 01 Jan 2008 22:05:36 -0000 Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> Message-ID: <13nle9g72fbtfce@corp.supernews.com> On Tue, 01 Jan 2008 13:55:10 -0800, PatrickMinnesota wrote: > The idea is that your data and applications are on the net, rather than > your local hard drive. Or, to put it another way, your data and applications are controlled by another company rather than you. Not that I wish to be cynical or anything like that. -- Steven From bearophileHUGS at lycos.com Wed Jan 9 07:29:06 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 9 Jan 2008 04:29:06 -0800 (PST) Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <5ujp0tF1ehvg2U1@mid.dfncis.de> Message-ID: Robert Latest: > Fredrik Lundh wrote: > > keywords = filter(None, keywords) # get "true" items only > > Makes seinse. BTW, where can I find all methods of the built-in types? > Section 3.6 only talks about strings and mentions the list append() method > only in an example. Am I too stupid to read the manual, or is this an > omission? filter isn't a method of list, it's a free function. For most situations that solution with filter(None,keywords) is good enough (but it filters away all false items, so it filters away None, 0, empty things, etc, too). The following one is an in-place version (it may be faster with Psyco), but you usually don't need it: def inplacefilter(pred, alist): """inplacefilter(pred, alist): filters the given list like filter(), but works inplace, minimizing the used memory. It returns None. >>> pr = lambda x: x > 2 >>> l = [] >>> inplacefilter(pr, l) >>> l [] >>> l = [1,2,2] >>> inplacefilter(pr, l) >>> l [] >>> l = [3] >>> inplacefilter(pr, l) >>> l [3] >>> l = [1,2,3,1,5,1,6,0] >>> r = filter(pr, l) # normal filter >>> r [3, 5, 6] >>> inplacefilter(pr, l) >>> r == l True """ slow = 0 for fast, item in enumerate(alist): if pred(item): if slow != fast: alist[slow] = alist[fast] slow += 1 del alist[slow:] You may want to avoid the enumerate() too if you use Psyco and you need max speed. Bye, bearophile From roger.miller at nova-sol.com Mon Jan 21 14:47:50 2008 From: roger.miller at nova-sol.com (Roger Miller) Date: Mon, 21 Jan 2008 11:47:50 -0800 (PST) Subject: index of min element of sequence References: Message-ID: <914f11c6-3f57-4468-8882-b3df84322e83@s13g2000prd.googlegroups.com> On Jan 21, 8:48 am, Peter Otten <__pete... at web.de> wrote: > Neal Becker wrote: > > What's a good/fast way to find the index of the minimum element of a > > sequence? ... > >>> min(xrange(len(items)), key=items.__getitem__) ... Or just items.index(min(items)) I found this to be significantly faster in a simple test (searching a list of 1000 ints with the minimum in the middle), despite the fact that it requires two passes. I'm sure that one could find cased where Peter's approach is faster, so you if you are concerned about speed you should measure with your own data. From kyosohma at gmail.com Wed Jan 23 11:30:24 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 23 Jan 2008 08:30:24 -0800 (PST) Subject: Processing XML that's embedded in HTML References: <1d163d82-db6b-4f43-8462-4359fb1f4b01@f47g2000hsd.googlegroups.com> Message-ID: On Jan 22, 5:31 pm, Paul McGuire wrote: > On Jan 22, 10:57 am, Mike Driscoll wrote:> Hi, > > > I need to parse a fairly complex HTML page that has XML embedded in > > it. I've done parsing before with the xml.dom.minidom module on just > > plain XML, but I cannot get it to work with this HTML page. > > > The XML looks like this: > > ... > > Once again (this IS HTML Day!), instead of parsing the HTML, pyparsing > can help lift the interesting bits and leave the rest alone. Try this > program out: > Happy post-HTML Day to you! > from pyparsing import > makeXMLTags,Word,nums,Combine,oneOf,SkipTo,withAttribute > > htmlWithEmbeddedXml = """ > > >

> Hey! this is really bold! > > > Owner > 1 > 07/16/2007 > No > Doe, John >

1905 S 3rd Ave , Hicksville IA 99999
> > > > Owner > 2 > 07/16/2007 > No > Doe, Jane >
1905 S 3rd Ave , Hicksville IA 99999
>
> > > > more HTML > blah blah blah... > """ > > # define pyparsing expressions for XML tags > rowStart,rowEnd = makeXMLTags("Row") > relationshipStart,relationshipEnd = makeXMLTags("Relationship") > priorityStart,priorityEnd = makeXMLTags("Priority") > startDateStart,startDateEnd = makeXMLTags("StartDate") > stopsExistStart,stopsExistEnd = makeXMLTags("StopsExist") > nameStart,nameEnd = makeXMLTags("Name") > addressStart,addressEnd = makeXMLTags("Address") > > # define some useful expressions for data of specific types > integer = Word(nums) > date = Combine(Word(nums,exact=2)+"/"+ > Word(nums,exact=2)+"/"+Word(nums,exact=4)) > yesOrNo = oneOf("Yes No") > > # conversion parse actions > integer.setParseAction(lambda t: int(t[0])) > yesOrNo.setParseAction(lambda t: t[0]=='Yes') > # could also define a conversion for date if you really wanted to > > # define format of a , plus assign results names for each data > field > rowRec = rowStart + \ > relationshipStart + SkipTo(relationshipEnd)("relationship") + > relationshipEnd + \ > priorityStart + integer("priority") + priorityEnd + \ > startDateStart + date("startdate") + startDateEnd + \ > stopsExistStart + yesOrNo("stopsexist") + stopsExistEnd + \ > nameStart + SkipTo(nameEnd)("name") + nameEnd + \ > addressStart + SkipTo(addressEnd)("address") + addressEnd + \ > rowEnd > > # set filtering parse action > rowRec.setParseAction(withAttribute(relationship="Owner",priority=1)) > > # find all matching rows, matching grammar and filtering parse action > rows = rowRec.searchString(htmlWithEmbeddedXml) > > # print the results (uncomment r.dump() statement to see full > # result for each row) > for r in rows: > # print r.dump() > print r.relationship > print r.priority > print r.startdate > print r.stopsexist > print r.name > print r.address > > This prints: > Owner > 1 > 07/16/2007 > False > Doe, John > 1905 S 3rd Ave , Hicksville IA 99999 > > In addition to parsing this data, some conversions were done at parse > time, too - "1" was converted to the value 1, and "No" was converted > to False. These were done by the conversion parse actions. The > filtering just for Row's containing Relationship="Owner" and > Priority=1 was done in a more global parse action, called > withAttribute. If you comment this line out, you will see that both > rows get retrieved. > > -- Paul > (Find out more about pyparsing athttp://pyparsing.wikispaces.com.) I've heard of this module, but never used it. Your code runs almost out of the box on my file and returns the correct result. That's pretty cool! It looks like the wiki you linked to has quite a few pieces of example code. I'll have to look this over. While I like lxml's very Object Oriented way of doing things, I tend to get overwhelmed by their tutorials for some reason. One more example of all those college OOP classes being a waste of money... Thank you for the help. Mike From mobiledreamers at gmail.com Tue Jan 8 20:02:28 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Tue, 8 Jan 2008 17:02:28 -0800 Subject: Pyflakes pre-commit hook in subversion Message-ID: http://tarekziade.wordpress.com/2006/11/01/protecting-a-python-svn-code-base-with-the-pre-commit-hook/ Is it possible to check code in python before committing to svn using pyflakes, pythontidy *Pyflakes and Subversion* Pyflakes is a nice little utility that checks your Python code for errors. The main advantage over PyChecker and PyLint is that it is much faster and gives almost no false positives. Today I wrote a little hack on top of the enforcerpre-commit script which forces the code you check in to pass pyflakes. Eg, the users of svn will see the following output if they try to check in code which has errors pyflakes can detect: $ svn ci -m "fix" completion.py Sending completion.py Transmitting file data .svn: Commit failed (details follow): svn: 'pre-commit' hook failed with error output: Pyflakes found 1 error(s)/warning(s): kiwi/trunk/examples/completion.py:1: undefined name 'test' The small "configuration" file for enforce can be found here. Can you share enforcer file? or a means to ensure safe code in python repo -------------- next part -------------- An HTML attachment was scrubbed... URL: From meesters at uni-mainz.de Tue Jan 29 07:48:31 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Tue, 29 Jan 2008 13:48:31 +0100 Subject: extending Python - passing nested lists References: Message-ID: Think, that I'm still at the wrong track. Point is that I cannot find any examples and don't know where to start here. Perhaps my problem boils down to two questions: I'd like to pass lists (in some cases nested ones) from Python to C and convert those Python-lists to C-arrays (e. g. of doubles). My second wish is to return a C-array of longs to a Python list. My approach so far: static PyObject *_foo(PyObject *self, PyObject *args) { double *v; if (!PyArg_Parse(args, "(d)", &v)) return NULL; // then I can't access v like v[1] ... // then return *v return with something like PyBuildValue (but didn't get so far) } Can somebody give me a hint here, please? Passing simple arguments to and fro (e. g. single integer values) is no problem, but lists of unknown size? TIA Christian From mwm-keyword-python.b4bdba at mired.org Fri Jan 11 17:37:30 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 17:37:30 -0500 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <20080111173730.3cd3a8b2@bhuda.mired.org> On Fri, 11 Jan 2008 22:18:22 GMT Neil Hodgson wrote: > Marty: > > I recently faced a similar issue doing something like this: > > data_out = [] > > for i in range(len(data_in)): > > data_out.append([]) > > Another way to write this is > data_out = [[]] * len(data_in) Not quite. All the other variants give you 23 empty lists. That one gives you 23 references to one list: >>> x = [[] for _ in range(23)] >>> x[1].append(23) >>> x [[], [23], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []] >>> x = [[]] * 23 >>> x[1].append(23) >>> x [[23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23]] http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From grflanagan at yahoo.co.uk Thu Jan 31 10:34:00 2008 From: grflanagan at yahoo.co.uk (grflanagan) Date: Thu, 31 Jan 2008 07:34:00 -0800 (PST) Subject: Python noob SOS (any [former?] Perlheads out there?) References: <6099ab30-390d-4b38-bc8e-81ecb52e03a6@e25g2000prg.googlegroups.com> Message-ID: <27f530a0-c955-43d7-93db-d907a1167d77@i29g2000prf.googlegroups.com> On Jan 31, 2:56 pm, "A.T.Hofkamp" wrote: > On 2008-01-30, grflanagan wrote: > > > > > On Jan 29, 5:39 pm, kj wrote: > > For command line options I get a long way with this: > > > [code python] > > def _getargs(): > > allargs = sys.argv[1:] > > args = [] > > kwargs = {} > > key = None > > while allargs: > > arg = allargs.pop(0) > > if arg.startswith('--'): > > key, arg = arg.split('=', 1) > > key = key[2:] > > elif arg.startswith('-'): > > key = arg[1:] > > if not allargs or allargs[0].startswith('-'): > > allargs.insert(0, 'yes') > > continue > > if key is None: > > args.append(arg) > > else: > > kwargs[key] = arg > > key = None > > return args, kwargs > > > ARGS, KWARGS = _getargs() > > [/code] > > Have a look at getopt (old) or optparse (newer) packages in the Python library > instead. > > Sincerely, > Albert Admittedly I haven't used either of them, but getopt and optparse have always looked like too much work to me. 90% of the time my '_getargs' does what I need, and when it's insufficient I go straight to a config file (ConfigParser or ConfigObj). Best Regards Gerard From steve at REMOVE-THIS-cybersource.com.au Fri Jan 18 17:39:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 18 Jan 2008 22:39:08 -0000 Subject: Is this a bug, or is it me? References: <87myr4o3sg.fsf@mulj.homelinux.net> <8afa3779-6803-43ed-ae4d-d0a102eda00d@x69g2000hsx.googlegroups.com> Message-ID: <13p2akcm9kmarce@corp.supernews.com> On Fri, 18 Jan 2008 11:01:29 -0800, cptnwillard wrote: > Now here is another one for your enjoyment: > > class C: > @staticmethod > def f1(): pass > F = { '1' : f1 } > > C().F['1']() > >>>> TypeError: 'staticmethod' object is not callable > > > What do you think of this one? The trick is to realise that the object stored in the dict is not the same object that you get back when you call C.f1(). >>> C().f1 is C().F['1'] False >>> C().f1 >>> C().F['1'] What you've done in inadvertently bypassed Python's method-access mechanism: >>> C.__dict__['f1'] is C().f1 False >>> C.__dict__['f1'] is C().F['1'] True Analogous results will occur without the decorator (although the error you get is different): >>> class D: ... def foo(self): pass ... F = {'oo': foo} ... >>> D().foo() >>> D.F['oo']() Traceback (most recent call last): File "", line 1, in TypeError: foo() takes exactly 1 argument (0 given) So... not a bug, a feature :) -- Steven From martin at v.loewis.de Thu Jan 3 16:47:22 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 03 Jan 2008 22:47:22 +0100 Subject: New-style objects are not instances, apparently In-Reply-To: <3c386519-8de3-4e50-8b96-e4c5f3cc8e78@d21g2000prf.googlegroups.com> References: <3c386519-8de3-4e50-8b96-e4c5f3cc8e78@d21g2000prf.googlegroups.com> Message-ID: <477D57EA.3040208@v.loewis.de> > Further experimentation showed that derivation from object was the > culprit; new-style objects are not considered "instances" in the above > sense. I wasn't able to figure out a workaround. Is there one, or is > the distinction between traditional classes and built-in types only > going to get more and more hazy? In the long run (ie. Python 3), the distinction is going to be very hazy, very dark: it will entirely disappear. There will be only one concept of type/class, not two, so there will be no point distinguishing between types and classes. Regards, Martin From max at alcyone.com Wed Jan 2 14:28:12 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 02 Jan 2008 11:28:12 -0800 Subject: os.tmpfile() In-Reply-To: References: Message-ID: jyoung79 at kc.rr.com wrote: > Erik, I am going to be displaying sections of text in the Terminal Window on OS X. > I wanted to format the text in a specific way and thought it might be quicker to > output all the text to a temporary file that I could quickly read sections from instead > of storing in memory. Not sure if this is the most efficient way to do this or not but > thought at least it'd be a good way to learn something new in Python. I was > assuming tmpfile() would automatically create some sort of temporary file that > would automatically delete itself when the code was finished. It is more likely that keeping it in a list will be more efficient, and easier to handle anyway. -- 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 When angry, count four; when very angry, swear. -- Mark Twain From Rens.Duijsens at gmail.com Sat Jan 26 07:23:36 2008 From: Rens.Duijsens at gmail.com (Dox33) Date: Sat, 26 Jan 2008 04:23:36 -0800 (PST) Subject: raw_input(), STRANGE behaviour Message-ID: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> I ran into a very strange behaviour of raw_input(). I hope somebody can tell me how to fix this. (Or is this a problem in the python source?) I will explain the problem by using 3 examples. (Sorry, long email) The first two examples are behaving normal, the thirth is strange....... I wrote the following flabbergasting code: #------------------------------------------------------------- print "1: This is the print statement." # Now halt the program until someone hits enter raw_input("2: This is the raw_input prompt.") import sys print "3: This is a possible solution. ", sys.stdout.flush() command = sys.stdin.readline() #------------------------------------------------------------- and saved it in the file 'script.py'. *** First, normal behaviour to stdout Now, I open a command line and run the following command: python script.py On screen appears, after a few 'enter' keys: 1: This is the print statement. 2: This is the raw_input prompt. 3: This is a possible solution. All works fine...... *** Second, redirected stdout to file, normal behaviour. >From the command prompt I run: python script.py > stdout_catch.txt The screen stays empty, and after a few 'enter' keys the prompt reapears. In the file 'stdout_catch.txt' are the lines: 1: This is the print statement. 2: This is the raw_input prompt. 3: This is a possible solution. And again, all works fine...... *** Thirst, redirect stderr to file, STRANGE behaviour...... >From the command prompt I run: python script.py 2> stderr_catch.txt This should redirect strerr to the file and stdout should stay on the screen. But..... What happens? After a few 'enter' keys, on screen apears: 1: This is the print statement. 3: This is a possible solution. WHERE IS THE SECOND LINE? It is in the file stderr_catch.txt!!! **** See the problem? Please Tell me? Why is the prompt produced by raw_input() printed to the error channel? It should be stdout, just as the print statement does. Looking at the python source code on http://svn.python.org/view/python/tags/r251/Python/bltinmodule.c?rev=54864&view=auto [found: 'builtin_raw_input(PyObject *self, PyObject *args)']. One thing that I notice is that the code checks whether stdin and stdout are connected to a terminal ("isatty" function), but I do not know why the prompt ends up on stderr then..... **** What is the solution? I have noticed this behaviour under DOS in Windows XP, Windows 2000, Windows 2003 Server, Windows vista, and Linux. How do I get raw_input() to send it's prompt to stdout? Friendly greetings Rens From mail at timgolden.me.uk Fri Jan 25 08:11:12 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 25 Jan 2008 13:11:12 +0000 Subject: Windows AVIFile problems In-Reply-To: References: Message-ID: <4799DFF0.1070007@timgolden.me.uk> c d saunter wrote: > I'm trying to access individual video frames of an AVI file from within > Python 2.4 or 2.5 under Windows XP. I thought that the recently-at-1.0 pyglet did that, only I can't now see it in their docs anywhere. Might be worth asking over there anyway [1] since it certainly comes close, is a much easier way of dealing with video images, and seems to have an active community. TJG [1] http://www.pyglet.org/ From lists at cheimes.de Wed Jan 16 02:11:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 16 Jan 2008 08:11:05 +0100 Subject: no pass-values calling? In-Reply-To: <873asyclo0.fsf@benfinney.id.au> References: <13or6esikdrqa33@corp.supernews.com> <873asyclo0.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > The term "reference" is fine, since that's exactly how it works. One > gets at an object via some reference, be it a name or some access into > a container object. When an object has no more references to itself, > it becomes a candidate for garbage collection. And so on. Thanks you, but I know exactly how Python works. I'm actually developing CPython and PythonDotNET. While your description of Python's memory management is technically, it's just an implementation detail of the CPython implementation. Jython and IronPython are using different approaches for GC. Anyway your message doesn't help a newbie and it gives most certainly the wrong impression. You are using words that have a different meaning in other languages. If you explain Python w/o the words variable, pointer, reference or call-by-value you have a much better chance to explain it right. Trust me :) Christian From charles_hans at yahoo.com Wed Jan 30 13:54:47 2008 From: charles_hans at yahoo.com (Charles_hans) Date: Wed, 30 Jan 2008 10:54:47 -0800 (PST) Subject: Q: paramiko/SSH/ how to get a remote host_key In-Reply-To: References: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> <9077ed27-e9b1-47ca-b30e-918e3b50d517@e4g2000hsg.googlegroups.com> Message-ID: <15189222.post@talk.nabble.com> I tried to get what host_key has been aquired after AutoPolicy is set. I added the following code just before client.close() in rosty's final code: try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print '*** Unable to open host keys file' I still got 'Unable to open host keys file'. Can you tell me how to get the remote host_key under this situation? Thanks! Charles 1/30/2008 by Guilherme Polo Jan 21, 2008; 09:08am : 2008/1/21, DHR : Very nice =) Just an advice, you dont need to import base64. Method decode of strings allows you to specify encoding as 'base64' to perform needed operations. by rosty Jan 21, 2008; 08:43am : Thank you! Now it works and the code looks like this: import paramiko import base64 from paramiko import AutoAddPolicy, SSHClient client = paramiko.SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect('hostIP', username='uname', password='pass') stdin, stdout, stderr = client.exec_command('ls') for line in stdout: print '... ' + line.strip('\n') client.close() -- View this message in context: http://www.nabble.com/Q%3A-paramiko-SSH--how-to-get-a-remote-host_key-tp14996119p15189222.html Sent from the Python - python-list mailing list archive at Nabble.com. From hniksic at xemacs.org Mon Jan 28 15:35:23 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 28 Jan 2008 21:35:23 +0100 Subject: post variable References: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> Message-ID: <87ir1dr8ms.fsf@mulj.homelinux.net> "pavloutefkros at gmail.com" writes: > so the output is always the POST retrieven at first. So the page > keeps on printing the POST variable retrieven at first even thought > i might have reloaded the page 1000 times. Is there any way to > "empty" the POST variable, so that at reload nothing would be the > same? Have test.py send a redirect to another page (or to itself, sans the params). Then reloading won't resend the POST params. From mccredie at gmail.com Fri Jan 18 16:12:49 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 18 Jan 2008 13:12:49 -0800 (PST) Subject: Bit Scan Forward and Reverse References: Message-ID: <4d0fa8e1-9fed-469d-9a70-ff07c8a88a79@t1g2000pra.googlegroups.com> On Jan 18, 12:01 pm, Thomas Dybdahl Ahle wrote: > Hi, I'm writing an app in python, and I'm storing some a lot of data in > bitmaps. > I need a way to find the first or latest set bit in a 64bit number, and > for that I've implemented a small routine. > > Thing is that this routine is not as fast as I'd wish. I know most > processors implement BSF and BSR calls to do this efficiently. > Is there anyway to access those calls from python? > > I'd still have my routine as a fallback on nonsupporting architectures. > > -- > Med venlig hilsen, > Best regards, > Thomas There isn't a simple way, but you have a couple of options: 1. put the code in a dll and call it from ctypes. 2. see extending and embedding in the documentation. Matt From socyl at 987jk.com.invalid Wed Jan 30 07:31:05 2008 From: socyl at 987jk.com.invalid (kj) Date: Wed, 30 Jan 2008 12:31:05 +0000 (UTC) Subject: Python noob SOS (any [former?] Perlheads out there?) References: Message-ID: In "Reedick, Andrew" writes: >> Be that as it may, the activation barrier to using Python for my >> scripting remains too high. >>=20 >> I'd written a Perl module to facilitate the writing of scripts. >> It contained all my boilerplate code for parsing and validating >> command-line options, generating of accessor functions for these >> options, printing of the help message and of the full documentation, >> testing, etc. >Bleh. Perl and Python have really good libraries. Why waste time >rolling your own when you can use Python's getopt or optparse, or Perl's >Getopt and Getopt::Long? No, no "bleh". My module in fact uses Getopt::Long behind the scenes, but customizes the heck out of it and adds a ton of functionality I wanted not available in Getopt::Long. kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From steven at REMOVE.THIS.cybersource.com.au Thu Jan 3 21:56:17 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 04 Jan 2008 02:56:17 -0000 Subject: problem with global var References: Message-ID: On Thu, 03 Jan 2008 11:38:48 -0300, Bruno Ferreira wrote: > Hi, > > I wrote a very simple python program to generate a sorted list of lines > from a squid access log file. > > Here is a simplified version: > > ################################## > 1 logfile = open ("squid_access.log", "r") > 2 topsquid = [["0", "0", "0", "0", "0", "0", "0"]] [snip] Others have already solved the immediate problem, but a much better design would be to avoid using a global variable in the first place. def add_sorted(alist, data): """Add figures from alist to collated data and return data.""" # do your processing here... return data topsquid=[["0", "0", "0", "0", "0", "0", "0"]] for line in logfile: linefields = logline.split() topsquid = add_sorted(linefields, topsquid) -- Steven From huisan.wang at gmail.com Wed Jan 2 20:15:06 2008 From: huisan.wang at gmail.com (huisan.wang at gmail.com) Date: Wed, 2 Jan 2008 17:15:06 -0800 (PST) Subject: A problem of twisted and dbus Message-ID: <87a3d1aa-f4e0-4cc0-a606-0cdaa172d5ef@e6g2000prf.googlegroups.com> Hello everyone, I am writing a program with twisted and dbus and got a such problem. If i run the code as $python local_proxy.py There is an error like this: Traceback (most recent call last): File "local_proxy.py", line 608, in reactor.listenTCP(143, factory) File "/usr/lib/python2.5/site-packages/twisted/internet/ posixbase.py", line 467, in listenTCP p.startListening() File "/usr/lib/python2.5/site-packages/twisted/internet/tcp.py", line 733, in startListening raise CannotListenError, (self.interface, self.port, le) twisted.internet.error.CannotListenError: Couldn't listen on any:143: (13, 'Permission denied'). So I tried to run the program as $sudo python local_proxy.py I got another error: Traceback (most recent call last): File "local_proxy.py", line 625, in session_bus = dbus.SessionBus() File "/var/lib/python-support/python2.5/dbus/_dbus.py", line 218, in __new__ mainloop=mainloop) File "/var/lib/python-support/python2.5/dbus/_dbus.py", line 107, in __new__ bus = BusConnection.__new__(subclass, bus_type, mainloop=mainloop) File "/var/lib/python-support/python2.5/dbus/bus.py", line 121, in __new__ bus = cls._new_for_bus(address_or_type, mainloop=mainloop) dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NoReply: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken. $sudo python local_porxy.py worked fine before I added the dbus into the program. And dbus has no problem for my other programs. How can I figure out this problem? Any helps will be appreciated. -Huisan From f.guerrieri at gmail.com Tue Jan 8 12:34:39 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Tue, 8 Jan 2008 18:34:39 +0100 Subject: copy a numpy array In-Reply-To: References: Message-ID: <79b79e730801080934x6f2403d2mc48ac0c1ca58680e@mail.gmail.com> On Jan 8, 2008 4:32 PM, jimgardener wrote: > hi, > (i posted this to numpy discussion grp couple of days back ..but it > fails to appear..)since it is needed for my work i would appreciate if > anyone can help me with this question > > > i have two ndarrays of 1000 elements each and want to copy all > elements from srcarray to destarray > > srcarray=numpy.array( [3973334.8381791776,........,382999.6748692277] ) > > arrsize=1000 > destarray=zeros(arrsize) > > i copied all items from src to dest by using > destarray[0:arrsize]=srcarray[0:arrsize] > > i don't know if this is the right way to do the copying. > is there a better(efficient?) way ? > jim If you want the array to share the data, just use destarray = numpy.array(srcarray) Otherwise you can set the copy flag to False: destarray = numpy.array(srcarray,copy=False) bye, Francesco From mr.cerutti at gmail.com Wed Jan 30 08:04:18 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 30 Jan 2008 08:04:18 -0500 Subject: Removal of element from list while traversing causes the next element to be skipped In-Reply-To: <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> Message-ID: <51302a8c0801300504i30c02ea3jfbf3228a62532720@mail.gmail.com> On Jan 30, 2008 6:57 AM, Arnaud Delobelle wrote: > Or one could use the trick of counting from the right (untested): > > n = len(a) > for i, x in enumerate(a): > if x == 99: del a[i-n] Or one can put on his bellbottoms, horn-rimmed glasses, and wear a mullet: i = 0 while i < len(a): if a[i] == 99: del a[i] else: i += 1 -- Neil Cerutti From sjmachin at lexicon.net Sun Jan 27 06:20:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 27 Jan 2008 03:20:36 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> Message-ID: On Jan 27, 9:17 pm, glacier wrote: > On 1?24?, ??3?29?, "Gabriel Genellina" wrote: > > > > > En Thu, 24 Jan 2008 04:52:22 -0200, glacier escribi?: > > > > According to your reply, what will happen if I try to decode a long > > > string seperately. > > > I mean: > > > ###################################### > > > a='???'*100000 > > > s1 = u'' > > > cur = 0 > > > while cur < len(a): > > > d = min(len(a)-i,1023) > > > s1 += a[cur:cur+d].decode('mbcs') > > > cur += d > > > ###################################### > > > > May the code above produce any bogus characters in s1? > > > Don't do that. You might be splitting the input string at a point that is > > not a character boundary. You won't get bogus output, decode will raise a > > UnicodeDecodeError instead. > > You can control how errors are handled, see http://docs.python.org/lib/string-methods.html#l2h-237 > > > -- > > Gabriel Genellina > > Thanks Gabriel, > > I guess I understand what will happen if I didn't split the string at > the character's boundry. > I'm not sure if the decode method will miss split the boundry. > Can you tell me then ? > > Thanks a lot. *IF* the file is well-formed GBK, then the codec will not mess up when decoding it to Unicode. The usual cause of mess is a combination of a human and a text editor :-) From peter.maas at somewhere.com Sat Jan 5 15:42:38 2008 From: peter.maas at somewhere.com (Peter Maas) Date: Sat, 05 Jan 2008 21:42:38 +0100 Subject: python interfaces In-Reply-To: References: Message-ID: Sion Arrowsmith wrote: > hyperboreean wrote: >> Why doesn't python provide interfaces trough its standard library? > > Because they're pointless. Wrong. I'm using Eclipse with the Java Development Tools (JDT) who do a wonderful job using interfaces to perform lots of checking, warning and code generation *nearly in real time while I am editing my code*. Because JDT knows interfaces it knows what to do and to suggest. > Java interfaces are a hack around the complexities of multiple > inheritence. A hack is something applied subsequently to solve a software problem while avoiding large changes. Java interfaces originate from careful language design. You are free to dislike Java interfaces but calling them a hack is just plain wrong. Once software becomes really big interfaces are very useful to handle complexity. Ever wondered why the Zope people introduced interfaces in their Python code? > Interfaces used purely with the idea of type safety provide > precious little gain for the added clutter and inconvenience. An interface is a software specification allowing you to use a software package without extensive code studies. This is a good thing. Interfaces have nothing to do with multiple inheritance and are not about type safety in the first place. They just tell you how to connect, how to plug in. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From caca at mailinator.com Sat Jan 5 11:07:35 2008 From: caca at mailinator.com (caca at mailinator.com) Date: Sat, 5 Jan 2008 08:07:35 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> Message-ID: <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> Hello, Paul and Arnaud. While I think about your answers: do you think there is any way to avoid shuffle? It may take unnecessary long on a long list most of whose elements have the property. From fredrik at pythonware.com Fri Jan 11 13:34:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jan 2008 19:34:35 +0100 Subject: Converting a bidimensional list in a bidimensional array In-Reply-To: <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> <005679e9-c355-4e0a-872c-e0dae3181fd0@x69g2000hsx.googlegroups.com> <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> Message-ID: Santiago Romero wrote: > My problem is that, in my game, each screen is 30x20, and I have > about 100 screens, so my tilemap contains 32*20*100 = 60000 python > objects (integers). > > If each integer-python-object takes 16 bytes, this makes 60000 * 16 = > almost 1MB of memory just for the tilemaps... or more likely, 240k for pointers to a few distinct integer objects, each of which occupies 16 bytes. if you're really running this on a machine with only a few megabytes free memory, maybe you could compress the screens you're not working with? zlib.compress(cPickle.dumps(screen)) should compress each 640-item list to say, 50 to 500 bytes, depending on the contents. From deets at nospam.web.de Wed Jan 16 13:33:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jan 2008 19:33:09 +0100 Subject: Interesting Thread Gotcha In-Reply-To: <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> Message-ID: <5v70v9F1kmtinU1@mid.uni-berlin.de> Dan schrieb: > On Jan 16, 11:06 am, "Diez B. Roggisch" wrote: >> Hendrik van Rooyen wrote: >>> "Dan" wrote: >>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) >>>> Needs to be >>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) >>>> Commas are important! >>>> -Dan >>> Absolutely! - well spotted! >>> As the first correct respondent, you win the freedom to spend a week in >>> Naboomspruit at your own expense. >>> It would have been nice, however, to have gotten something like: >>> TypeError - This routine needs a tuple. >>> instead of the silent in line calling of the routine in question, >>> while failing actually to start a new thread. >> You can't prevent the silent inline-calling - otherwise, how would you do >> this: >> >> def compute_thread_target(): >> def target(): >> pass >> return target >> >> thread.start_new_thread(compute_thread_target()) >> >> Of course start_new_thread could throw an error if it got nothing callable >> as first argument. No idea why it doesn't. >> >> Diez > > Of course, in his case, having start_new_thread throw an error > wouldn't have helped, since he went into an infinite loop while > evaluating the parameters for start_new_thread. > > Would it be possible to have pychecker (or some such) warn that there > is an insufficient parameter count to start_new_thread? I guess that > would require knowing the type of thread. . . What has this to do with the second argument? It's perfectly legal to have a function as thread-target that takes no arguments at all, so enforcing a second argument wouldn't be helpful - all it would do is to force all developers that don't need an argument tuple to pass the empty tuple. So there was no insufficient argument count. And none of these would solve the underlying problem that in python expressions are evaluated eagerly. Changing that would mean that you end up with a totally new language. the only thing that could help to a certain extend would be static types. Which we don't want here :) Diez From asmodai at in-nomine.org Tue Jan 8 03:55:28 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 09:55:28 +0100 Subject: Look for a string on a file and get its line number In-Reply-To: <9889cbd0-c19e-4b76-8c41-aa621a188661@e4g2000hsg.googlegroups.com> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <9889cbd0-c19e-4b76-8c41-aa621a188661@e4g2000hsg.googlegroups.com> Message-ID: <20080108085528.GF75977@nexus.in-nomine.org> -On [20080108 09:51], John Machin (sjmachin at lexicon.net) wrote: >Make that >= Right you are. Sorry, was doing it quickly from work. ;) And I guess the find will also be less precise if the word you are looking is a smaller part of a bigger word. E.g. find 'door' in a line that has 'doorway' in it. So 't is merely for inspiration. ;) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ >From morning to night I stayed out of sight / Didn't recognise I'd become No more than alive I'd barely survive / In a word, overrun... From DustanGroups at gmail.com Fri Jan 18 18:44:42 2008 From: DustanGroups at gmail.com (Dustan) Date: Fri, 18 Jan 2008 15:44:42 -0800 (PST) Subject: strange syntax rules on list comprehension conditions References: Message-ID: On Jan 18, 1:04 pm, "Chris Mellon" wrote: > On Jan 18, 2008 12:53 PM, Nicholas wrote: > > > I was quite delighted today, after extensive searches yielded nothing, to > > discover how to place an else condition in a list comprehension. > > Trivial mask example: > > >>> [True if i <5 else False for i in range(10)] # A > > [True, True, True, True, True, False, False, False, False, False] > > > I then experimented to drop the else statement which yields an error > > >>> [i if i>3 for i in range(10)] That would be: [i for i in range(10) if i>3] > > Traceback ( File "", line 1 > > this syntax works of course > > >>> [i if i>3 else i for i in range(10)] > > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] From martin at v.loewis.de Wed Jan 23 04:25:30 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Jan 2008 10:25:30 +0100 Subject: python2.4-dbg and C modules In-Reply-To: References: Message-ID: <4797080a$0$11374$9b622d9e@news.freenet.de> > please, when I try to run my code under python2.4-dbg > from Ubuntu, the interpreter complains that the Py_InitModule4 > symbol is undefined in a C module I'm using (PyOpenAL): > > ImportError: /var/lib/python-support/python2.4/_openal.so: undefined > symbol: Py_InitModule4 > > Google reveals that this problem is not specific just to PyOpenAL, > but I couldn't find out what is the essence of the problem and how > python-2.4dbg is different from python2.4 except for including > debugging symbols, because in plain python2.4 the module works > fine. The dbg version does not define Py_InitModule4, but Py_InitModule4TraceRefs. This is a safety-measure to prevent modules compiled for the nodebug version of Python to load into the debug version. There are major changes to the internal interpreter data structures in the debug version, so you have to recompile your module with the debug headers. HTH, Martin From hexamorph at gmx.net Fri Jan 25 15:52:24 2008 From: hexamorph at gmx.net (Hexamorph) Date: Fri, 25 Jan 2008 21:52:24 +0100 Subject: Operator overloading In-Reply-To: References: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com> <5vuob3F1nd2bhU1@mid.uni-berlin.de> <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> Message-ID: <479A4C08.3050400@gmx.net> MartinRinehart at gmail.com wrote: > > Hexamorph wrote: >> You mean you want the ability to change for example the + operator >> for ints to something like calculating the cosine instead of doing >> addition? > > Sure. Cosines are a monadic operation and the monadic '+' is a NOP, so > why shouldn't I define +45 to return cosine of 45, (presuming I needed > lots of cosines). I'd even let you define your own operators. Lots of > programmers really liked '++' and '--', for examples. Well, OK, the cosine example was badly chosen (it would still be very wired in terms of common syntax and semantics), but I think you got my point. Changing internal behaviour mostly causes more trouble as it's worth. In the end, you probably can access the parser to do this. From mrmakent at cox.net Sat Jan 26 10:50:15 2008 From: mrmakent at cox.net (Mike Kent) Date: Sat, 26 Jan 2008 07:50:15 -0800 (PST) Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> Message-ID: <87dd811e-3095-41d0-80fd-7312338e5254@i3g2000hsf.googlegroups.com> On Jan 26, 7:23 am, Dox33 wrote: > I ran into a very strange behaviour of raw_input(). > I hope somebody can tell me how to fix this. ===CUT=== > *** Thirst, redirect stderr to file, STRANGE behaviour...... > From the command prompt I run: > python script.py 2> stderr_catch.txt > This should redirect strerr to the file and stdout should stay on the > screen. > > But..... What happens? > After a few 'enter' keys, on screen apears: > 1: This is the print statement. > 3: This is a possible solution. > > WHERE IS THE SECOND LINE? > It is in the file stderr_catch.txt!!! > > **** See the problem? > Please Tell me? Why is the prompt produced by raw_input() printed to > the error channel? It should be stdout, just as the print statement > does. I recently ran into this behaviour myself, and reported it both here and to the python-dev mailing list. See http://groups.google.com/group/comp.lang.python/browse_thread/thread/1011238ac6b79292/6f8b7c47873a4a1e?lnk=gst&q=unexpected+behavior#6f8b7c47873a4a1e It turns out that *if* you don't have GNU readline installed, Python falls back to its own implementation of readline, which is hard-coded to send the prompt output to stderr. Guido agreed that this is wrong, and a bug for it has been entered into the Python bug tracking database. Your workaround until this bug is fixed is to install GNU readline, and rebuild your python installation to use it rather than the fall- back version. From steven at REMOVE.THIS.cybersource.com.au Wed Jan 16 23:20:14 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 17 Jan 2008 04:20:14 -0000 Subject: assigning values in python and perl References: <18c1e5f20801161934m69ff44edo1e35f5381f7d2928@mail.gmail.com> Message-ID: On Thu, 17 Jan 2008 11:40:59 +0800, J. Peng wrote: > May I ask, python's pass-by-reference is passing the object's reference > to functions, but perl, or C's pass-by-reference is passing the variable > itself's reference to functions. So althought they're all called > pass-by-reference,but will get different results.Is it? Python is not call by reference. Any book or person that says it is, is wrong to do so. Python's function call semantics are not the same as C, or Perl, or Pascal. They are, however, similar to those of Lisp, Scheme, Emerald and especially CLU. It is neither pass by reference, nor pass by value. Java also uses similar call-by-object (sometimes call-by-sharing) semantics, and just like Python, Java developers tie themselves in knots by using misleading names for it: http://codertricks.strainu.ro/java/2007/05/02/why-java-sends-parameters- by-value/ and http://codertricks.strainu.ro/java/2007/06/15/call-by-sharing/ Did you read the links I sent you yesterday, especially the second one? http://effbot.org/zone/python-objects.htm http://effbot.org/zone/call-by-object.htm -- Steven From hniksic at xemacs.org Wed Jan 30 08:52:47 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 30 Jan 2008 14:52:47 +0100 Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> <7xwsprxxe6.fsf@ruckus.brouhaha.com> Message-ID: <87ejbz774g.fsf@mulj.homelinux.net> Paul Rubin writes: > Quadratic time!! Yowch!! Back to the future: > > def rocket_science(xs): > for x in xs: > if x != 99: > yield x > > a[:] = list(rocket_science(a)) I call "useless use of list"! a[:] = rocket_science(a) :-) From alex at computronix.com Thu Jan 10 00:49:15 2008 From: alex at computronix.com (Alex VanderWoude) Date: Thu, 10 Jan 2008 05:49:15 GMT Subject: printing dots in simple program while waiting In-Reply-To: References: Message-ID: John wrote: > what i want to do is print a 'waiting' statement while a script is > working-- the multithreading aspect isn't an issue, the printing on > the same line is. i want to print something like: > > (1sec) working... > (2sec) working.... > (3sec) working..... > > > where the 'working' line isn't being printed each second, but the dots > are being added with time. When issuing output to stdout I have do something like this: print "working", # Note trailing comma while some_condition: do_something() print "\b.", # \b is backspace print # Finish the line of dots - Alex From grahn+nntp at snipabacken.dyndns.org Thu Jan 17 04:56:23 2008 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 17 Jan 2008 09:56:23 GMT Subject: module naming conventions References: <7f39199a-3334-4bcc-a424-5102f042ed01@1g2000hsl.googlegroups.com> <87zlv8dnya.fsf@benfinney.id.au> <6a53a14a-8f7c-4b6b-986f-48c7698f679f@v29g2000hsf.googlegroups.com> Message-ID: On Mon, 14 Jan 2008 15:58:49 -0800 (PST), grackle wrote: > On Jan 14, 4:47 pm, Ben Finney > wrote: >> I'm not sure, but it sounds as though you have yet to discover Python >> module packages . >> They allow a hierarchy of modules in directories. > > I do use packages. I mentioned the Java naming conventions because > they were my first thought for solving the problem of name clashes, > and they work well in some non-Java languages. They don't apply well > to Python, since every top-level module has a unique identity that can > only be specified on one source path. If two libraries use the same > top-level module name, they can't be used together in the same program > without modifying their source code. > > mycompany_mymodulename was just the first solution I thought of that > seemed practical. The mycompany_ prefix protects me from name clashes > with useful modules I might acquire from elsewhere. Seems to me that the Python community solves this as if you had released an executable program for Unix (where all executables end up in /usr/bin or /usr/local/bin, so they have to have unique names). In Linux, I am aware of very few name clashes. People tend to know what names are used and pick other ones. A suite of executables usually share a common prefix (like packages in Python). Some names are a bit far-fetched or silly, of course, but in practice it works reasonably well. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From loupgaroublond at gmail.com Mon Jan 7 08:33:23 2008 From: loupgaroublond at gmail.com (Yaakov Nemoy) Date: Mon, 7 Jan 2008 08:33:23 -0500 Subject: Memory Leaks and Heapy In-Reply-To: <47822129.4050500@egenix.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> <477E5A73.9070400@egenix.com> <7f692fec0801040823q14d16429y370ffceaf046a6f3@mail.gmail.com> <477E6525.3010805@egenix.com> <7f692fec0801041819r675e2137i293084baeae4954f@mail.gmail.com> <47822129.4050500@egenix.com> Message-ID: <7f692fec0801070533k5c7b3275i557a25c7d576c1c2@mail.gmail.com> On Jan 7, 2008 7:55 AM, M.-A. Lemburg wrote: > Fair enough. Just wanted to give some more details as to > where to look for things that look like leaks, but are in > fact just results of internal feature of the Python > interpreter. We have a hackfest coming up in the Fedora Community. I'll at least show some people a copy of this email, and see if we can peer debug things a bit, and maybe we'll come up with something. -Yaakov From george.sakkis at gmail.com Thu Jan 31 02:42:17 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 30 Jan 2008 23:42:17 -0800 (PST) Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> <60cai8F1qgh3aU1@mid.uni-berlin.de> <15d16017-3b43-45a8-86b9-93203972f813@u10g2000prn.googlegroups.com> <3c3d8f03-1a69-4fbe-8979-9aae458ab46c@u10g2000prn.googlegroups.com> Message-ID: On Jan 30, 9:27 pm, MRAB wrote: > On Jan 31, 1:09 am, George Sakkis wrote:> On Jan 30, 5:03 pm, Marc 'BlackJack' Rintsch wrote: > > > > On Wed, 30 Jan 2008 15:29:45 +0100, Wildemar Wildenburger wrote: > > > > Gerardo Herzig wrote: > > > >> I will use genital().extend(), thats for shure ^^ > > > > > Well, you never go wrong with apply(genital(), females), do you? > > > > `apply()` is deprecated. And ``genital(*females)`` looks a bit odd. :-) > > > Well, that use case alone is enough to convince anyone that apply > > should stay :-) > > The original had genital(), so that would be genital()(*females). But > what is genital() anyway? A factory? It actually implements several design patterns. Factory is just one of them; others include the Bridge and the Object Pool patterns. Some advanced instances of genital() may also implement the Visitor pattern while others less advanced implement primarily the Observer. George From arnodel at googlemail.com Wed Jan 23 16:56:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 13:56:27 -0800 (PST) Subject: Creating new types and invoking super References: Message-ID: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> On Jan 23, 8:55?pm, "Guilherme Polo" wrote: > Hello, Hi [...] > First I tried this: > > def init(func): > ? ? def _init(inst): > ? ? ? ? super(inst.__class__, inst).__init__() > ? ? ? ? func(inst) > > ? ? return _init > > class A(object): > ? ? @init > ? ? def __init__(self): pass This kind of approach can't work, you need to call super(A, obj). super(type(obj), obj) is pointless, it defeats the whole purpose of the mro! The only way I can think of would be to create a metaclass, but I don't think it's worth it. super(A, obj).__init__() isn't that bad! -- Arnaud From eproust at gmail.com Sun Jan 20 17:49:21 2008 From: eproust at gmail.com (pythonewbie) Date: Sun, 20 Jan 2008 14:49:21 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <4793C903.60201@v.loewis.de> Message-ID: On 20 jan, 23:19, "Martin v. L?wis" wrote: > > But for different reasons I also want to get the absolute path of > > Python install directory (not only the executable under Linux) and > > site-packages directory. > > The Python install directory is available as sys.prefix. The > site-packages directory is > sys.prefix+"lib/python"+x.y+"/site-packages (where x.y is from > sys.version_info). > > HTH, > Martin http://forum.ubuntu-fr.org/viewtopic.php?id=184199 >>> import distutils.sysconfig >>> distutils.sysconfig.get_python_lib() '/usr/lib/python2.5/site-packages' get_python_lib(plat_specific=0, standard_lib=0, prefix=None) Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure- Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. From rridge at caffeine.csclub.uwaterloo.ca Fri Jan 18 16:15:43 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 18 Jan 2008 16:15:43 -0500 Subject: Is this a bug, or is it me? References: <8afa3779-6803-43ed-ae4d-d0a102eda00d@x69g2000hsx.googlegroups.com> Message-ID: Neil Cerutti wrote: >The decoration is setting the class type's f1 attribute correctly, but >doing something strange in the local namespace. > >>>> class C: >... @staticmethod >... def f1(): pass >... print f1 >... > >>>> print C.f1 > It might help understand the problem if you do the something similar without using @staticmethod: class C: def f1(): pass print "f1", f1 print "C.f1", C.f1 print "C().f1", C().f1 You should see output something like: f1 C.f1 C().f1 > >The class statement's local namespace is pretty strange. I think I >mightl go back to pretending there isn't one. When class attributes are referenced, functions are turned into unbound methods and staticmethod objects get turned into functions. Something like the following should work: class C: def f1(): pass F = {'1': f1} f1 = staticmethod(f1) # if you need C.f1() to work as well If you don't need C.f1() to work you can replace the last line with "del f1". Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From berteun at NO_SPAMdds.nl Tue Jan 29 12:40:10 2008 From: berteun at NO_SPAMdds.nl (Berteun Damman) Date: Tue, 29 Jan 2008 17:40:10 +0000 (UTC) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> Message-ID: On Tue, 29 Jan 2008 09:23:16 -0800 (PST), attn.steven.kuo at gmail.com wrote: > If you're going to delete elements from > a list while iterating over it, then do > it in reverse order: Why so hard? Reversing it that way creates a copy, so you might as well do: >>> a = [ 98, 99, 100 ] >>> for i, x in enumerate(a[:]): ... if x == 99: del(a[i]) ... print x Berteun From ndbecker2 at gmail.com Tue Jan 29 14:06:05 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 29 Jan 2008 14:06:05 -0500 Subject: typename Message-ID: I want python code that given an instance of a type, prints the type name, like: typename (0) -> 'int' I know how to do this with the C-api, (o->tp_name), but how do I do it from python? type(0) prints "", not really what I wanted. From nodrogbrown at gmail.com Sat Jan 26 01:17:53 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Fri, 25 Jan 2008 22:17:53 -0800 (PST) Subject: eucledian dist calculations References: <87aff9a8-a9d8-4236-8a86-66aa58417792@i72g2000hsd.googlegroups.com> <13c59b0c-534a-4a4a-bad3-f6f51721ab78@n20g2000hsh.googlegroups.com> Message-ID: sorry..the last post didn't appear! > Are you sure? What happens if the vector with the smallest > sum(distance) is the first one? > initially i will set imgindex =0 so if the first one is of smallest sum..,the image will be reteived by imgindex 0 > (a) Can't you replace the inner loop with something like this: > distance = abs(input_weight - weights[image, :]) good suggestion ..was doing it java way! > (b) I doubt that you need the .copy() > 5. Lose the hard-wired numbers like 30 and 100 those nums were only for clarification.. > 6. Put it inside a function and *TEST* it > will do... thanx john ,your post really helped gordon From superwesman at gmail.com Wed Jan 16 01:24:28 2008 From: superwesman at gmail.com (superwesman) Date: Tue, 15 Jan 2008 22:24:28 -0800 (PST) Subject: can't find pyAntTasks.properties References: <3d1efa8c-ab6a-487d-abe6-63f227a895fc@i29g2000prf.googlegroups.com> Message-ID: <5bb081a5-f578-413f-87d2-fcfc845b7526@i7g2000prf.googlegroups.com> On Jan 15, 11:41 pm, superwesman wrote: > Hi - I'm trying to use pyAntTasks. I downloaded the jar and placed it > into ~/.ant/lib, put that directory into my CLASSPATH. I then created > a very simple build.xml and I'm getting a failure I can't explain. > > Here is my build.xml: > > > > > > Here is my CLASSPATH: > > > echo $CLASSPATH > > /home/wtorres/.ant/lib > > And here's what's in it: > > > ls -lrt $CLASSPATH > > total 24 > -rwxrwxr-x 1 wtorres staff 8563 Jan 15 18:34 pyAntTasks.jar > > When I run ant, here is the failure: > > (the 'ant' script I'm running here sets up ant 1.6.2 and runs it) > > > /vobs/jfw/ant > > ANT=/tools/ant/1.6.2 > Buildfile: build.xml > [taskdef] Could not load definitions from resource > pyAntTasks.properties. It could not be found. > > BUILD SUCCESSFUL > Total time: 1 second > > What the heck am I doing wrong? Where can I find > pyAntTasks.properties? I mean, it makes sense that "It could not be > found" because I can't find it either. Where do I get/put this? > Thanks > -w update: I downloaded a newer version on pyAntTasks and this file is included. Somebody should tell them to remove the bad build or at least mention that it won't work ;) From gagsl-py2 at yahoo.com.ar Sat Jan 26 19:20:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 26 Jan 2008 22:20:20 -0200 Subject: Text-based data inspector for Python? References: Message-ID: En Fri, 25 Jan 2008 12:28:08 -0200, kj escribi?: > The one thing I couldn't > find, and would greatly miss if not available, is the ability to > set breakpoints by inserting a particular indication right in the > code. In the Perl debugger one can insert something like the > following anywhere in the code: > > $DB::single = 1; > > When such a line executes, the debugger immediately switches to > single-step mode. It's a very flexible technique, and I like it I think that pdb.set_trace() does what you want. -- Gabriel Genellina From asmodai at in-nomine.org Mon Jan 14 06:21:09 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 14 Jan 2008 12:21:09 +0100 Subject: __init__ explanation please In-Reply-To: References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> Message-ID: <20080114112109.GV75977@nexus.in-nomine.org> -On [20080113 13:36], Fredrik Lundh (fredrik at pythonware.com) wrote: >given that they do different things, I'm not sure it's that helpful to >describe them *both* as constructors. I am still behind in my learning. ;) To restate it more correctly: __init__ is akin to a constructor. I am not entirely sure I fully understand __new__'s semantics though. The first read-through of http://docs.python.org/ref/customization.html makes it sound very similar to a call like: var = Object(arguments=...) I must not be understanding something and __new__'s documentation there is not that clear to me, to be honest. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ I think, therefore I am... From sturlamolden at yahoo.no Thu Jan 17 12:12:47 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 17 Jan 2008 09:12:47 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <3c05d0ad-3578-4976-bacb-8f5f9394c00a@i29g2000prf.googlegroups.com> On 17 Jan, 13:21, Sacred Heart wrote: > A push in the right direction, anyone? for number,letter in zip(array1,array2): print "%s %s" % (number,letter) From yantao at telus.com Sat Jan 26 23:06:45 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 04:06:45 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: References: Message-ID: I probably should mention that what I want is to make all parts of the string aligned, and look like table. I am not looking for other ways to make it table-alike, but only interested in making % work with unicode -counting characters not bytes... From kyosohma at gmail.com Mon Jan 21 09:17:45 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 21 Jan 2008 06:17:45 -0800 (PST) Subject: How to use py2exe ... References: Message-ID: On Jan 21, 1:45 am, Santiago Romero wrote: > Hi... > > I'm a Linux user, and I would like some windows-friends to test a > game I'm writing with python+pygame without they needing to install > python, pygame, and so on. > > I've heard about py2exe and pygame2exe, but I'm not sure on how to > use them to create: > > a.- standalone exe files with a single .py program. > Example: myprogram.py > > or > > b.- exe files containing all my source code + data directories (png > files, data files, and so). > Example: main.py, doc/README, src/*.py and data/* > > The problem is I'm not sure on how to use py2exe and pygame2exe to > build the executables... > > And finally, a question: if I want to provide source code > separately ... can I include .pyc files instead of .py files? You should also check out the py2exe website as it has a tutorial, a link to their mailing list, etc: http://www.py2exe.org/ Mike From pavlovevidence at gmail.com Sat Jan 12 16:10:28 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 12 Jan 2008 16:10:28 -0500 Subject: where do my python files go in linux? References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> <20080112113759.GJ75977@nexus.in-nomine.org> <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> Message-ID: <4cabmf.0g2.ln@127.0.0.1> On Sat, 12 Jan 2008 15:25:53 -0500, Mike Meyer wrote: > On Sat, 12 Jan 2008 16:13:08 +0100 "Jorgen Bodde" > wrote: >> > Normally you'd split up the bulk of the code into a module which gets >> > installed into site-packages and a piece of stand-alone front-end >> > code which imports the module and executes whatever you need to do >> > and gets installed into a typical PATH directory. >> I would agree but it is not a site package I am trying to distribute, >> but a wxPython application. I would not think my app belongs in the >> python site packages dir. > > I suspect that's because your app is "simple", in that it only has one > command. Many apps have multiple commands that share the same set of > libraries. So putting a package for that app in site-packages makes a > lot of sense. They should go into their own directory in /usr/local/lib (or whatever). > If your app-specific library is properly designed and > documented, users may be able to build further commands for the system > as well. Users can still add the /usr/local/lib/whatever to their path path and use it that way. I realize it's a fine line and a judgment call in some cases, but site- packages is really for libraries; applications should use their own directories. Carl Banks From graemeglass at gmail.com Sun Jan 13 15:15:54 2008 From: graemeglass at gmail.com (Graeme Glass) Date: Sun, 13 Jan 2008 12:15:54 -0800 (PST) Subject: Great Python books for the beginner References: Message-ID: <98cc988c-6efe-4861-a6e9-59e6764e3e89@s19g2000prg.googlegroups.com> On Jan 12, 9:03 am, Landon wrote: > Hi, I'm a freshman in college and I'm going to be taking an intro to > programming course next semester which mainly uses Python, so I > thought it might be a good time to pick up Python beyond the scope of > the class as well. The text book for this class is Python for the > Absolute Beginner or something similar to that name. > > I was wondering if anyone had any opinions on what other titles I > could look into since this one seems from a glance at reviews to be > teaching mainly through game programming (a topic I'm not too > interested in) or if this one is a quality book by itself. I found CORE PYTHON PROGRAMMING by Wesley Chun to be a great book with help on both novice and advanced topics. http://starship.python.net/crew/wesc/cpp/ The tuts and library reference on www.python.org are also really well written and layed out and you will find yourself frequenting them. From chris.monsanto at gmail.com Tue Jan 15 12:06:42 2008 From: chris.monsanto at gmail.com (Chris M) Date: Tue, 15 Jan 2008 09:06:42 -0800 (PST) Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: <5a3ace63-a8cf-4970-a95e-4243226fbac7@j20g2000hsi.googlegroups.com> On Jan 15, 11:51 am, "Neil Cerutti" wrote: > > So this is a bug in set_update or in set_ior. They can't both be > right. > It's not a bug. "Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') & 'cbs' in favor of the more readable set('abc').intersection('cbs')." From floris.bruynooghe at gmail.com Wed Jan 16 10:31:12 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Wed, 16 Jan 2008 07:31:12 -0800 (PST) Subject: MSI read support in msilib? Message-ID: <367e7e5e-6b63-4474-8704-b8af300f7bfb@e4g2000hsg.googlegroups.com> Hi The introduction from the msilib documentation in python 2.5 claims it supports reading an msi. However on the Record class there is only a GetFieldCount() method and some Set*() methods. I was expecting to see GetString() and GetInteger() methods to be able to read the values. Maybe I'm missing something? Is there an other way to read the data of a record? Regards Floris From Rens.Duijsens at gmail.com Sun Jan 27 09:51:51 2008 From: Rens.Duijsens at gmail.com (Dox33) Date: Sun, 27 Jan 2008 06:51:51 -0800 (PST) Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> <87dd811e-3095-41d0-80fd-7312338e5254@i3g2000hsf.googlegroups.com> <489b6fc5-e871-425e-b242-45be618fc9f4@n20g2000hsh.googlegroups.com> <87r6g4q7hq.fsf@mulj.homelinux.net> Message-ID: Yes, I know. There are several ways to work around the problem. (Look at the innitial code I provided in this discussion start) Fact is, every time I'm getting a script from somewhere or someone, I have to search and replace all the affected code. Not very conveniant. That's why I rather would have a correct working version. On 27 jan, 04:20, Hrvoje Niksic wrote: > Dox33 writes: > > Thanks for your reply. ?Since I momentarily do not have the ability > > to build a new python executable, I would like to ask for your help > > in this case. ?Are you able to supply me with a corrected version? > > You can simply choose not to use raw_input, and use sys.stdin.readline > instead. ?Or define your own corrected raw_input: > > def my_raw_input(msg): > ? ? print msg, > ? ? return raw_input() From princismo at gmail.com Mon Jan 21 23:34:01 2008 From: princismo at gmail.com (=?Big5?B?w0P4rw==?=) Date: Mon, 21 Jan 2008 20:34:01 -0800 (PST) Subject: How to solve "TypeError: list indices must be integers". References: <3f3ca8c6-b57c-43ff-bf80-11768e1a0f94@s8g2000prg.googlegroups.com> <13p9n6efmt4b95a@corp.supernews.com> Message-ID: <38cd97ae-dff8-4a29-9657-3db101c2f515@y5g2000hsf.googlegroups.com> On 1?22?, ??1?56?, Dennis Lee Bieber wrote: > On Mon, 21 Jan 2008 08:15:02 -0800 (PST), "?C??" > declaimed the following in comp.lang.python: > > > I was assigned dialog.colorDialog(self) return value to a result > > object, but I suspect that result.color is the attribute of the result > > object that can assign to a string variable. > > ? ? ? ? Showing the actual code would help... > > > There is a error prompt from python console "TypeError: list indices > > must be integers". > > Have any suggestion to solve this problem? > > ? ? ? ? Make sure you only have an integer when subscripting into a list? > > > When I print ?result.color, it is print out something like (255,0,0). > > ? ? ? ? Looks like a tuple -- probably > ? ? ? ? ? ? ? ? (red-level, green-level, blue-level) > where *-level is in the range 0..255 (x00..xFF); your example would be > (full red, no green, no blue) > > > How to covert result.color into a string? ?How to convert a string to > > result.color type? > > ? ? ? ? What type of string? > ? ? ? ? ? ? ? ? "0x%2.2X%2.2X%2.2X" % (r, g, b) > will produce a hex string of the form > ? ? ? ? ? ? ? ? 0xFF0000 > given your sample RGB > > ? ? ? ? If you want to get "Red", you'll need a look-up table and probably > some least-distance error function for items that don't directly match. > > (255, 0, 0) ? ? ? ? ? ? Red > (255, 255, 0) ? Yellow > (255, 0, 255) ? Magenta > (0, 255, 0) ? ? ? ? ? ? Green > (0, 255, 255) ? Cyan > (0, 0, 255) ? ? ? ? ? ? Blue > (0, 0, 0) ? ? ? ? ? ? ? Black > (255, 255, 255) White > > ? ? ? ? But where would you put: ? ? ? ?(127, 127, 63) ? ? ? ? ?[A half-black Yellow > with 1/4 blue added].. Is it closer to Yellow, or to Black: 255-127 => > 128, but 127 - 0 => 127... Shorter simplistic distance means map this to > (0, 0, 0)... But (128, 128, 64) simplistic shorter distance would map to > Yellow > > -- > ? ? ? ? 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/ Many thanks, Dennis Lee Bieber for your fast reply! Regards, Andreas From kyosohma at gmail.com Fri Jan 11 09:44:19 2008 From: kyosohma at gmail.com (Mike) Date: Fri, 11 Jan 2008 06:44:19 -0800 (PST) Subject: Help with Windows build of Yapgvb Python extension References: Message-ID: <4bfd40d3-61f5-4c88-b6b2-c8ebef1b13dc@m34g2000hsf.googlegroups.com> On Jan 11, 8:41 am, Lonnie Princehouse wrote: > I'm the author of Yapgvb, a Python binding for Graphviz. Yapgvb > enjoys modest success, but for some time it has been in dire need of a > Python 2.5 build for Windows. I'm posting this message in the hopes of > finding someone who is interested in making this build. > > This is a relatively quick task for someone who is comfortable with > building C extensions and has an operational Windows build environment > for Python 2.5 (which I don't). Alternately, it's a great way to > learn about these things, and to get involved with a small open source > project. > > Technologies used: > graphviz > distutils > boost.python > boost.graph > > See:http://yapgvb.sourceforge.net What do you need exactly? One of those executables created using bdist or are you going for the msi? I usually attempt to create these things doing python setup.py bdist_wininst ...for executable installers. If you can provide a valid setup.py, I can probably create the exe/ msi. Mike From pofuk at mzm.hr Tue Jan 1 18:55:28 2008 From: pofuk at mzm.hr (SMALLp) Date: Wed, 02 Jan 2008 00:55:28 +0100 Subject: Python events, panel with text Message-ID: Hy! I have many small panels with text and I want do bind wx.EVT_LEFT_DOWN when clicked on panel, but i need to bind that in parent class. So I have instance of that small panel and when i bind it efects only part of small panel where is no text. import wx class RequestedFilesItems(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, -1, style=wx.SUNKEN_BORDER) sizer = wx.BoxSizer(wx.HORIZONTAL) upButton = PanelButton(self, -1, "Upload") upButton.Bind(wx.EVT_LEFT_DOWN, self.upload) sizer.Add(upButton, 0, wx.LEFT, 15) self.SetSizer(sizer) def upload(self, event): print "Please print this" class PanelButton(wx.Panel): def __init__(self, parent, id, buttonName): wx.Panel.__init__(self, parent, -1, style=wx.SUNKEN_BORDER) self.SetBackgroundColour("GREY") sizer = wx.BoxSizer(wx.HORIZONTAL) self.text = wx.StaticText(self, -1, buttonName) sizer.Add(self.text, -1, wx.EXPAND | wx.ALL, 1) self.text.Bind(wx.EVT_LEFT_DOWN, self.OnClick) self.SetSizer(sizer) def OnClick(self, event): print "It only works for text, not for panel what I expected here" if __name__ == '__main__': app = wx.PySimpleApp() frm = wx.Frame(None, wx.ID_ANY, 'Mouse-click test') panel = RequestedFilesItems(frm, wx.ID_ANY) frm.Show() app.MainLoop() app.MainLoop() From yantao at telus.com Sun Jan 27 11:00:42 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 16:00:42 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: <6031q9F1oh17aU1@mid.uni-berlin.de> References: <13po55nc0q0s06@corp.supernews.com> <6031q9F1oh17aU1@mid.uni-berlin.de> Message-ID: "Marc 'BlackJack' Rintsch" wrote in message news:6031q9F1oh17aU1 at mid.uni-berlin.de... > On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: > >> You didn't understand my question, but thanks any way. >> >> Yes, it is true that %s already support unicode, and I did not contradict >> that. But it counts the number of bytes instead of characters, and makes >> things like %-20s out of alignment. If you don't understand my assertion, >> please don't argue back and I am only interested in answers from those >> who >> are qualified. > > I have the impression from your original post > > [?] because it is unicode, and one byte is not neccessary one character. > > that you confuse unicode and utf-8. Are you sure you are qualified to ask > such a question in the first place!? :-? so you are saying, with utf-8 encoding a byte is a character, shame on you. > > Ciao, > Marc 'BlackJack' Rintsch From tarun.kap at gmail.com Wed Jan 16 12:21:05 2008 From: tarun.kap at gmail.com (Tarun Kapoor) Date: Wed, 16 Jan 2008 09:21:05 -0800 (PST) Subject: paramiko References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> Message-ID: <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> # now, connect and use paramiko Transport to negotiate SSH2 across the connection sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) t = paramiko.Transport(sock) t.start_client() key = t.get_remote_server_key() event = threading.Event() t.auth_password(username=username, password=password, event=event) event.wait() if not t.is_authenticated(): print "not authenticated" output: not authenticated On Jan 16, 11:11 am, "Guilherme Polo" wrote: > 2008/1/16, Tarun Kapoor : > > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > > the remote server using an SFTP client I have just to make sure that > > username and password are working.. This is the code. > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > > connection > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > sock.connect((hostname, port)) > > > t = paramiko.Transport(sock) > > > event = threading.Event() > > > t.start_client(event) > > > event.wait(15) > > > if not t.is_active(): > > > print 'SSH negotiation failed.' > > > sys.exit(1) > > > else: > > > print "SSH negotiation sucessful" > > > event.clear() > > > t.auth_password(username=username, password=password,event=event) > > > if not t.is_authenticated(): > > > print "not authenticated" > > > output: > > > SSH negotiation successful > > > not authenticated > > > Tarun > > > Waterstone Capital Management > > > 2 Carlson Parkway, Suite 260 > > > Plymouth, MN 55447 > > > Direct: 952-697-4123 > > > Cell: 612-205-2587 > > Disclaimer This e-mail and any attachments is confidential and intended > > solely for the use of the individual(s) to whom it is addressed. Any views > > or opinions presented are solely those of the author and do not necessarily > > represent those of Waterstone Capital Management, L.P and affiliates. If you > > are not the intended recipient, be advised that you have received this > > e-mail in error and that any use, dissemination, printing, forwarding or > > copying of this email is strictly prohibited. Please contact the sender if > > you have received this e-mail in error. You should also be aware that > > e-mails are susceptible to interference and you should not assume that the > > contents of this e-mail originated from the sender above or that they have > > been accurately reproduced in their original form. Waterstone Capital > > Management, L.P. and affiliates accepts no responsibility for information, > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > > please verify the authenticity with the sender. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > You are missing an event.wait() after t.auth_password. > Also, why are you passing this magic value "15" to event.wait() ? That > parameter is passed to class _Verbose to indicate if debug messages > should be displayed or not, so typical values would be 0/1 or > False/True. > > -- > -- Guilherme H. Polo Goncalves From steven.bethard at gmail.com Tue Jan 1 14:59:44 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 01 Jan 2008 12:59:44 -0700 Subject: ElementTree should parse string and file in the same way In-Reply-To: <13nkkh6almg8o6b@corp.supernews.com> References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> <5tuqfaF1f8u9tU1@mid.uni-berlin.de> <13nkkh6almg8o6b@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Tue, 01 Jan 2008 13:36:57 +0100, Diez B. Roggisch wrote: > >> And codemonkeys know that in python >> >> doc = et.parse(StringIO(string)) >> >> is just one import away > > Yes, but to play devil's advocate for a moment, > > doc = et.parse(string_or_file) > > would be even simpler. I assume the problem with this is that it would be ambiguous. You can already use either a string or a file with ``et.parse``. A string is interpreted as a file name, while a file object is used directly. How would you differentiate between a string that's supposed to be a file name, and a string that's supposed to be XML? Steve From grflanagan at yahoo.co.uk Tue Jan 8 04:34:36 2008 From: grflanagan at yahoo.co.uk (grflanagan) Date: Tue, 8 Jan 2008 01:34:36 -0800 (PST) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> <1d895d6d-a649-439e-8223-0ae7d3a4eb40@l6g2000prm.googlegroups.com> Message-ID: On Jan 8, 3:08 am, ajaksu wrote: > On Jan 7, 11:25 am, MartinRineh... at gmail.com wrote: > > > Anything written somewhere that's thorough? Any code body that should > > serve as a reference? > > I've done this search before and it was very interesting, doing it > again gave me new results that also seem valuable. Here's most of them > (where PCG = Python Coding Guidelines). [...] > > Do you think this could be a valuable addition to the Python wiki? > +1, absolutely Here's the list in rest format: ------------------------------ FOSS Projects Style Guidelines ------------------------------ `Cogent project PCG`__ .. _Cogent PCG: http://jaynes.colorado.edu/PythonGuidelines.html __ `Cogent PCG`_ `Cogent project Python Idioms`__ .. _Cogent Idioms: http://jaynes.colorado.edu/PythonIdioms.html __ `Cogent Idioms`_ `Freevo Coding Standard`__ .. _Freevo PCG: http://doc.freevo.org/CodingStandard __ `Freevo PCG`_ `Mercurial Basic Coding Style`__ .. _Mercurial PCG: http://www.selenic.com/mercurial/wiki/index.cgi/Basic_Coding_Style __ `Mercurial PCG`_ `PyBlosxom Coding Style Guide`__ .. _PyBlosxom PCG: http://pyblosxom.sourceforge.net/blog/static/development#coding __ `PyBlosxom PCG`_ `MoinMoin Coding Style`__ .. _MoinMoin PCG: http://moinmoin.wikiwikiweb.de/CodingStyle __ `MoinMoin PCG`_ `Webware Style Guidelines`__ .. _Webware PCG: http://www.webwareforpython.org/Docs/StyleGuidelines.html __ `Webware PCG`_ `NOAA Enhanced Forecaster Tools PCG`__ .. _NOAA PCG: http://www-md.fsl.noaa.gov/eft/developer/PythonCodingStandards.html __ `NOAA PCG`_ `BioPython Coding Conventions`__ .. _BioPython PCG: http://biopython.org/wiki/Contributing#Coding_conventions __ `BioPython PCG`_ `Mnet PCG`__ .. _Mnet PCG: http://mnet.sourceforge.net/coding_standards.html __ `Mnet PCG`_ `Michael Foord's (aka Voidspace) PCG`__ .. _Michael PCG: http://www.voidspace.org.uk/python/weblog/arch_d7_2006_04_01.shtml#e296 __ `Michael PCG`_ `SQLObject Coding Style`__ .. _SQLObject PCG: http://www.sqlobject.org/DeveloperGuide.html#style-guide __ `SQLObject PCG`_ `WxPython PCG`__ .. _WxPython PCG: http://www.wxpython.org/codeguidelines.php __ `WxPython PCG`_ `Mailman PCG`__ .. _Mailman PCG: http://barry.warsaw.us/software/STYLEGUIDE.txt __ `Mailman PCG`_ `VoiceCode PCG`__ .. _VoiceCode PCG: http://voicecode.iit.nrc.ca/VoiceCode/uploads/codingGuidelines.html __ `VoiceCode PCG`_ `Bazaar Coding Style Guidelines`__ .. _Bazaar PCG: http://doc.bazaar-vcs.org/bzr.dev/en/developer-guide/HACKING.html#coding-style-guidlines __ `Bazaar PCG`_ `IPython Developer Guidelines`__ .. _IPython PCG: http://ipython.scipy.org/moin/Developer_Zone/Developer_Guidelines __ `IPython PCG`_ `OSAF Chandler PCG`__ .. _OSAF PCG: http://chandlerproject.org/Projects/ChandlerCodingStyleGuidelines __ `OSAF PCG`_ `OSAF Chandler Epydoc Style Guide`__ .. _OSAF Epydoc: http://chandlerproject.org/Projects/ChandlerEpydocStyleGuide __ `OSAF Epydoc`_ `Twisted Coding Standard`__ .. _Twisted PCG: http://twistedmatrix.com/trac/browser/trunk/doc/development/policy/coding-standard.xhtml?format=raw __ `Twisted PCG`_ `PyPy RPython and CPython Coding Guidelines`__ .. _PyPy PCG: http://codespeak.net/pypy/dist/pypy/doc/coding-guide.html __ `PyPy PCG`_ `Django PCG`__ .. _Django PCG: http://www.djangoproject.com/documentation/contributing/#coding-style __ `Django PCG`_ `Docutils PCG`__ .. _Docutils PCG: http://docutils.sourceforge.net/docs/dev/policies.html#python-coding-conventions __ `Docutils PCG`_ `Trac Coding Style`__ .. _Trac PCG: http://trac.edgewall.org/wiki/TracDev/CodingStyle __ `Trac PCG`_ `OLPC PCG`__ .. _OLPC PCG: http://wiki.laptop.org/go/Python_Style_Guide __ `OLPC PCG`_ `Skeletonz Coding and Naming Conventions`__ .. _Skeletonz PCG: http://orangoo.com/skeletonz/Developer_guide/Coding_convention/ __ `Skeletonz PCG`_ `CherryPy Code Conventions`__ .. _CherryPy PCG: http://www.cherrypy.org/wiki/CodeConventions __ `CherryPy PCG`_ `Software Carpentry on style`__ .. _Software Carpentry PCG: http://www.swc.scipy.org/lec/style.html __ `Software Carpentry PCG`_ `Zope's Coding Style`__ .. _Zope PCG: http://wiki.zope.org/zope3/CodingStyle __ `Zope PCG`_ `The docstrings PEP`__ .. _docstrings: http://www.python.org/dev/peps/pep-0257/ __ `docstrings`_ `Pyflakes`__ .. _Pyflakes: http://divmod.org/trac/wiki/DivmodPyflakes __ `Pyflakes`_ `PyChecker`__ .. _PyChecker: http://pychecker.sourceforge.net/ __ `PyChecker`_ `Pylint`__ .. _Pylint: http://www.logilab.org/857 __ `Pylint`_ From sunilkrghai at gmail.com Mon Jan 7 11:01:01 2008 From: sunilkrghai at gmail.com (Sunil Ghai) Date: Mon, 7 Jan 2008 21:31:01 +0530 Subject: PostgreSQL with Python Message-ID: <52da23100801070801o55c6ce8bva2e0a09be4ffa94e@mail.gmail.com> I am looking for an E-Book or some tutorial in which a good explanation about PostgreSQL/MySQL database, then about interacting with them using Python is explained. I want to start RDBMS, i have no idea about them. I have been doing Python, willing to do some good project in RDBMS. Thanks in advance :) Regards -- Sunil Ghai -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Tue Jan 22 16:42:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 22 Jan 2008 13:42:13 -0800 (PST) Subject: Processing XML that's embedded in HTML References: <6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> Message-ID: <25087d9b-ce63-4e9c-b83c-55e6043c49f9@v46g2000hsv.googlegroups.com> On Jan 23, 7:48 am, Mike Driscoll wrote: [snip] > I'm not sure what is wrong here...but I got lxml to create a tree from > by doing the following: > > > from lxml import etree > from StringIO import StringIO > > parser = etree.HTMLParser() > tree = etree.parse(filename, parser) > xml_string = etree.tostring(tree) > context = etree.iterparse(StringIO(xml_string)) > > > However, when I iterate over the contents of "context", I can't figure > out how to nab the row's contents: > > for action, elem in context: > if action == 'end' and elem.tag == 'relationship': > # do something...but what!? > # this if statement probably isn't even right > lxml allegedly supports the ElementTree interface so I would expect elem.text to refer to the contents. Sure enough: http://codespeak.net/lxml/tutorial.html#elements-contain-text Why do you want/need to use the iterparse technique on the 2nd pass instead of creating another tree and then using getiterator? From bertle at smoerz.org Fri Jan 25 11:46:13 2008 From: bertle at smoerz.org (Roman Bertle) Date: 25 Jan 2008 16:46:13 GMT Subject: grouping in module 'locale' Message-ID: Hello, I try to format monetary values using the locale module, python2.5: Python 2.5.2a0 (r251:54863, Jan 3 2008, 17:59:56) [GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_ALL, 'de_AT.utf8') 'de_AT.utf8' >>> locale.localeconv() {'mon_decimal_point': ',', 'int_frac_digits': 2, 'p_sep_by_space': 1, 'frac_digits': 2, 'thousands_sep': '', 'n_sign_posn': 1, 'decimal_point': ',', 'int_curr_symbol': 'EUR ', 'n_cs_precedes': 1, 'p_sign_posn': 1, 'mon_thousands_sep': ' ', 'negative_sign': '-', 'currency_symbol': '\xe2\x82\xac', 'n_sep_by_space': 1, 'mon_grouping': [3, 3, 0], 'p_cs_precedes': 1, 'positive_sign': '', 'grouping': []} >>> locale.currency(1234.5678, grouping=True, symbol=False) '1234,57' As you can see, the decimal point is correctly set to ','. But the grouping is not done, every 3 digits should be separated by space (' '). Using the 'de_DE.utf8' locale, ist works: >>> locale.setlocale(locale.LC_ALL, 'de_DE.utf8') 'de_DE.utf8' >>> locale.localeconv() {'mon_decimal_point': ',', 'int_frac_digits': 2, 'p_sep_by_space': 1, 'frac_digits': 2, 'thousands_sep': '.', 'n_sign_posn': 1, 'decimal_point': ',', 'int_curr_symbol': 'EUR ', 'n_cs_precedes': 0, 'p_sign_posn': 1, 'mon_thousands_sep': '.', 'negative_sign': '-', 'currency_symbol': '\xe2\x82\xac', 'n_sep_by_space': 1, 'mon_grouping': [3, 3, 0], 'p_cs_precedes': 0, 'positive_sign': '', 'grouping': [3, 3, 0]} >>> locale.currency(1234.5678, grouping=True, symbol=False) '1.234,57' The difference here is that thounds_sep is '.', not ' '. If we look at the code of locale.py, revision 55038, lines 157-161, the inserted spaces are later deleted again: while seps: sp = formatted.find(' ') if sp == -1: break formatted = formatted[:sp] + formatted[sp+1:] seps -= 1 This code is only called if numbers are formated as floating point, but not for integers. The following works: >>> locale.setlocale(locale.LC_ALL, 'de_AT.utf8') 'de_AT.utf8' >>> locale.format('%d',1234.5678, grouping=True, monetary=True) '1 234' The reason for the space removal is explained in an earlier version of locale.py, e.g. 42120: # If the number was formatted for a specific width, then it # might have been filled with spaces to the left or right. If # so, kill as much spaces as there where separators. # Leading zeroes as fillers are not yet dealt with, as it is # not clear how they should interact with grouping. But I don't know the why and how this code is necessary. Can anybody shed some light on this issue? Best Regards, Roman From max at alcyone.com Thu Jan 10 17:06:49 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 10 Jan 2008 14:06:49 -0800 Subject: Embedding python code into text document question. In-Reply-To: References: Message-ID: Thomas Troeger wrote: > I've written a program that parses a string or file for embedded python > commands, executes them and fills in the returned value. The input might > look like this: > > process id: $$return os.getpid()$$ > current date: $$return time.ctime()$$ > superuser: $$ > if os.geteuid(): > return "Yes" > else: > return "No"$$ > > I've tried several solutions using eval, execfile or compile, but none > of those would solve my problem. Does anyone have a solution that works? > Any suggestions? Any help will be appreciated :) What you're looking for is a templating system for Python. There are already many with varying degrees of complexity and emphasis, including one I've put together, EmPy: http://www.alcyone.com/software/empy/ For more, google around for Python templating. -- 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 If the sun comes up / And you're not home / I'll be strong -- India Arie From rong.xian at gmail.com Sun Jan 27 05:20:08 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 02:20:08 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <77a2d5cd-239f-4ce7-9fd1-3c935453180d@i29g2000prf.googlegroups.com> Message-ID: <64a9b332-c4e3-4bf3-b4f6-6c55c6161333@i12g2000prf.googlegroups.com> On 1?24?, ??5?51?, John Machin wrote: > On Jan 24, 2:49 pm, glacier wrote: > > > I use chinese charactors as an example here. > > > >>>s1='???' > > >>>repr(s1) > > > "'\\xc4\\xe3\\xba\\xc3\\xc2\\xf0'" > > > >>>b1=s1.decode('GBK') > > > My first question is : what strategy does 'decode' use to tell the way > > to seperate the words. I mean since s1 is an multi-bytes-char string, > > how did it determine to seperate the string every 2bytes or 1byte? > > The usual strategy for encodings like GBK is: > 1. If the current byte is less than 0x80, then it's a 1-byte > character. > 2. Current byte 0x81 to 0xFE inclusive: current byte and the next byte > make up a two-byte character. > 3. Current byte 0x80: undefined (or used e.g. in cp936 for the 1-byte > euro character) > 4: Current byte 0xFF: undefined > > Cheers, > John Thanks John, I will try to write a function to test if the strategy above caused the problem I described in the 1st post:) From rick.arnett at gmail.com Mon Jan 28 12:30:31 2008 From: rick.arnett at gmail.com (the_ricka) Date: Mon, 28 Jan 2008 09:30:31 -0800 (PST) Subject: SMTP Sending Mail Problem References: <9b00a5f5-277d-4d23-be82-60c2aafc4227@c23g2000hsa.googlegroups.com> Message-ID: <8d8a744f-f009-41b6-8a6a-001c6b1f0615@y5g2000hsf.googlegroups.com> I added a longer text file with vocabulary typically used in our office and the email sent successfully. The crazy thing is I had already checked all the spam filters and queues in Exchange, and the older messages seem to have disappeared. Sorry for the post, I thought I was going crazy for a bit! Thanks again for the sanity check. From khoard at gmail.com Fri Jan 18 14:50:27 2008 From: khoard at gmail.com (FireNWater) Date: Fri, 18 Jan 2008 11:50:27 -0800 (PST) Subject: Core Python Programming . . . Message-ID: I'm working my way thru the book "Core Python Programming" 2d Edition - Wesley Chun. . . Trying to figure out what he's looking for on Page 248, Exercise 6-11 (a). Is it supposed to be: 1) convert a 4-digit Integer (WXYZ) to an IP address (WWW.XXX.YYY.ZZZ) or 2) convert an 8-digit Integer (WWWXXXYYYZZZ) to (WWW.XXX.YYY.ZZZ) Thanks for anyone with the clue!!! From mwilson at the-wire.com Tue Jan 29 11:25:11 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 29 Jan 2008 11:25:11 -0500 Subject: extending Python - passing nested lists References: <3ddeaf07-3f4b-4d68-a176-9205fa4d234b@k39g2000hsf.googlegroups.com> Message-ID: Christian Meesters wrote: >> You didn't mention speed in your original post. > Sorry, perhaps I considered this self-evident - which it is, of course, not. > >> What about using >> array.array? Unless I am mistaken, these are just a thin wrapper >> around normal C arrays. > The algorithm I want to implement requires several million floating point > operations. Neither the array-modules nor numpy's thin layer seem thin > enough for me. ;-) > >> Anyway you could always convert your list >> into a c array, do lots and lots of fast calculations, then convert it >> back again to a list. > I guess I am too blind to see, but I couldn't discover a method description > like "double* PyList_toDouble". So, yes, my question is a C-API-newbie > question: What is the way to say "myCarray = SomePyMethod(InputPyList)"? Or > better, what should be here instead > static PyObject *_foo(PyObject *self, PyObject *args) { > double *v; > if (!PyArg_Parse(args, "(d)", &v)) > return NULL; > to get a list as an array of doubles into 'v' (and back to Python)? > > I did read the API-description, but still am lost at this point. I presume, > once I get to know the answer I'll bang my head on the table ... ;-) I haven't strictly tried this, but PyArg_ParseTuple and Py_BuildValue seem to be the orthodox ways to do Python->C and C->Python conversions. But if Numpy isn't fast enough, then any Python at all in the solution might be too much. Perhaps keeping your values in a file and reading them into the C programs will work. Mel. From mail at microcorp.co.za Thu Jan 17 09:22:26 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 17 Jan 2008 16:22:26 +0200 Subject: Interesting Thread Gotcha References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> Message-ID: <001301c85929$9cd82000$03000080@hendrik> "Diez B. Roggisch" wrote: > Hendrik van Rooyen wrote: > > It would have been nice, however, to have gotten something like: > > > > TypeError - This routine needs a tuple. > > > > instead of the silent in line calling of the routine in question, > > while failing actually to start a new thread. > > You can't prevent the silent inline-calling - otherwise, how would you do > this: > > def compute_thread_target(): > def target(): > pass > return target > > thread.start_new_thread(compute_thread_target()) > > > Of course start_new_thread could throw an error if it got nothing callable > as first argument. No idea why it doesn't. Thanks - got it, I think. Doesn't mean I like it, though: >>> a = 42 >>> b = 24 >>> def do_something(c,d): print c print d >>> do_something(a,b) 42 24 >>> def harmless(): return a >>> def evil(): while True: pass >>> do_something(a) Traceback (most recent call last): File "", line 1, in ? do_something(a) TypeError: do_something() takes exactly 2 arguments (1 given) >>> do_something(harmless()) Traceback (most recent call last): File "", line 1, in ? do_something(harmless()) TypeError: do_something() takes exactly 2 arguments (1 given) >>>do_something(evil()) This hangs and needs OS intervention to kill it - and there is also just one argument, not two. Looks like the arguments are handled one by one without validation till the end. Lets see: >>> do_something(a,b,harmless()) Traceback (most recent call last): File "", line 1, in ? do_something(a,b,harmless()) TypeError: do_something() takes exactly 2 arguments (3 given) So far, so good. >>>do_something(a,b,evil()) This also hangs - the third, extra argument is actually called! Are you all sure this is not a buglet? - Hendrik From mr.cerutti at gmail.com Tue Jan 15 08:24:47 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Tue, 15 Jan 2008 08:24:47 -0500 Subject: Append zip files together, just get the binary data (in memory) In-Reply-To: References: <53f66038-ccc3-4c3d-97b2-fa5deb148809@d4g2000prg.googlegroups.com> <5v27oiF1kavhlU1@mid.uni-berlin.de> Message-ID: <51302a8c0801150524u3020b402h31be2848b725fb87@mail.gmail.com> On Jan 15, 2008 4:28 AM, John Machin wrote: > On Jan 15, 9:58 am, "Diez B. Roggisch" wrote: > > > Module StringIO is your friend. > > and cStringIO is your ....? ... friend +1? -- Neil Cerutti From bignose+hates-spam at benfinney.id.au Mon Jan 14 17:20:17 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 09:20:17 +1100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> Message-ID: <87lk6sf3ry.fsf@benfinney.id.au> Hrvoje Niksic writes: > Wildemar Wildenburger writes: > > __init__() /initializes/ an instance (automatically after > > creation). It is called, /after/ the instance has been constructed > > I don't understand the purpose of this "correction". After all, > __init__ *is* the closest equivalent to what other languages would > call a constructor. No. That would be '__new__', which actually constructs the instance, and actually returns it to the caller. '__init__' does neither of those. It so happens that, in Python, one usually overrrides the initialiser and not the constructor. Thus, the confusion is understandable, but still regrettable and avoidable. -- \ "My, your, his, hers, ours, theirs, its. I'm, you're, he's, | `\ she's, we're, they're, it's." ?anonymous, | _o__) alt.sysadmin.recovery | Ben Finney From deets at nospam.web.de Thu Jan 3 10:05:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 16:05:07 +0100 Subject: problem with global var References: Message-ID: <5u4bt3F1ef265U1@mid.uni-berlin.de> Bruno Ferreira wrote: > Hi, > > I wrote a very simple python program to generate a sorted list of > lines from a squid access log file. > > Here is a simplified version: > > ################################## > 1 logfile = open ("squid_access.log", "r") > 2 topsquid = [["0", "0", "0", "0", "0", "0", "0"]] > 3 > 4 def add_sorted (list): > 5 for i in range(50): > 6 if int(list[4]) > int(topsquid[i][4]): > 7 topsquid.insert(i,list) > 8 break > 8 # Max len = 50 > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > 12 > 13 while True: > 14 logline = logfile.readline() > 15 linefields = logline.split() > 16 > 17 if logline != "": > 18 add_sorted (linefields) > 19 else: > 20 break > 21 > 22 for i in range (len(topsquid)): > 23 print topsquid[i][4] > #################################### > > When I execute the program _without_ the lines 10 and 11: > > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > > it runs perfectly. > > But if I execute the program _with_ those lines, this exception is thrown: > > bruno at ts:~$ python topsquid.py > Traceback (most recent call last): > File "topsquid.py", line 20, in > add_sorted (linefields) > File "topsquid.py", line 6, in add_sorted > if int(list[4]) > int(topsquid[i][4]): > UnboundLocalError: local variable 'topsquid' referenced before assignment > > > Note that now the error shown is not related with the lines 10 and 11, > but wiht a line prior to them. > > Any hints? Use def add_sorted(list): global topsquid ... to make topsquid a global variable to add_sorted. Otherwise python sees that it gets referred by in the if-statement before assigning to it, thus resulting in the error you see. The reason for this is that a (limited) static analysis of python-code is performed to determine which variables are local to a function and which not. The criteria essentially is the appearance on the left-hand-side of an expression makes a variable (or name) local to that function. Which makes it require the explicit global declaration. Apart from that there are quite a few things worth mentioning in your code: - don't shadow built-in names like list - it's superfluous to do for i in xrange(len(some_list)): .. some_list[i] .. as you do, unless you need the index. Instead do for element in some_list: ... element ... If you need an index, do for i, element in enumerate(some_list): ... - don't use range, use xrange if you don't need a list but rather want to enumerate indices. - the while-loop is superfluous as well, just do for line in logfile: ... or if your python is older do for line in logfile.xreadlines(): ... Diez From python.list at tim.thechases.com Mon Jan 28 12:01:46 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 28 Jan 2008 11:01:46 -0600 Subject: Get Available Functions In-Reply-To: <020501c861ca$d604dc70$820e9550$@rawlins@thinkbluemedia.co.uk> References: <020501c861ca$d604dc70$820e9550$@rawlins@thinkbluemedia.co.uk> Message-ID: <479E0A7A.9080305@tim.thechases.com> > I'm working with a python module which isn't part of the core > Python API and it also isn't very documented or supported, is > there any way that I can easily dump/view the available > classes and methods within the package from within python? Most of the time, the dir(), type() and help() functions can be your friend: >>> import somelib >>> dir(somelib) ['Foo', 'thing', 'whatever'] >>> type(somelib.Foo) >>> dir(somelib.Foo) ['method1', 'method2'] >>> type(somelib.thing) >>> print somelib.thing 'I didn't expect the Spanish Inquisition!' >>> type(somelib.whatever) >>> help(somelib.whatever) Help on function whatever in module somelib: whatever(param1, param2, *args, **kwargs) >>> I've had a couple cases where the underlying module was written in C (mod_python in particular...don't know if it still has this problem) where dir() wouldn't actually tell you about the object, but for most cases, dir() will get you pointed in the right dir-ection. :) -tkc From vriolk at gmail.com Fri Jan 18 04:20:40 2008 From: vriolk at gmail.com (coldpizza) Date: Fri, 18 Jan 2008 01:20:40 -0800 (PST) Subject: How to detect a remote webpage is accessible? (in HTTP) References: Message-ID: I suppose that if the file is really big and you don't need to read all of it then instead of f.readlines() you could use f.read(256) to read just the first 256 bytes. On Jan 18, 7:28?am, Astan Chee wrote: > How about: > > import socket, urllib2 > > timeout = 10 > socket.setdefaulttimeout(timeout) > try: > auth_handler = urllib2.HTTPBasicAuthHandler() > opener = urllib2.build_opener(auth_handler) #this used if we need > authentication > urllib2.install_opener(opener) > req = urllib2.Request('http://website.com') > f = urllib2.urlopen(req) > notes= f.readlines() > f.close() > print "Everything is ok" > except IOError, r: > p = str(r) > if re.search(r'urlopen error timed out',p): > print "Web page timed out" > > You'll need to set up the timeout to whatever duration your website > takes to load. > Cheers > Astan > > > > ?? wrote: > > Howdy, all, > > ? ? ?I want to use python to detect the accessibility of website. > > Currently, I use urllib > > to obtain the remote webpage, and see whether it fails. But the problem is that > > the webpage may be very large; it takes too long time. Certainly, it > > is no need to download > > the entire page. Could you give me a good and fast solution? > > ? ? Thank you. > > -- > > ShenLei From cyberco at gmail.com Mon Jan 7 06:53:40 2008 From: cyberco at gmail.com (Berco Beute) Date: Mon, 7 Jan 2008 03:53:40 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> Message-ID: <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Cool! We knew it would happen one day :) What could be the reason? Python 3? Jython 2.2? Java's loss of sexiness? What I would like to know is what it was that boosted Python's popularity in 2004 (see http://www.tiobe.com/tiobe_index/Python.html). Equally interesting is the question why it dropped shortly after. 2B From sjmachin at lexicon.net Sat Jan 12 20:12:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 12 Jan 2008 17:12:51 -0800 (PST) Subject: Is unicode.lower() locale-independent? References: <47894DD2.1080503@v.loewis.de> Message-ID: <99b941b9-ea25-46fd-bb9e-fd6998380c51@y5g2000hsf.googlegroups.com> On Jan 13, 10:31 am, "Martin v. L?wis" wrote: > > The Unicode standard says that case mappings are language-dependent. > > I think you are misreading it. Ummm well, it does say "normative" as opposed to Fredrik's "informative" ... > 5.18 "Implementation Guides" says > (talking about "most environments") "In such cases, the > language-specific mappings *must not* be used." (emphasis also > in the original spec). > Here is the paragraph from which you quote: """ In most environments, such as in file systems, text is not and cannot be tagged with language information. In such cases, the language- specific mappings /must not/ be used. Otherwise, data structures such as B-trees might be built based on one set of case foldings and used based on a different set of case foldings. This discrepancy would cause those data structures to become corrupt. For such environments, a constant, language-independent, default case folding is required. """ This is from the middle of a section titled "Caseless Matching"; this section starts: """ Caseless matching is implemented using case folding, which is the process of mapping strings to a canonical form where case differences are erased. Case folding allows for fast caseless matches in lookups because only binary comparison is required. It is more than just conversion to lowercase. For example, it correctly handles cases such as the Greek sigma, so that and will match. """ Python doesn't offer a foldedcase method, and the attitude of 99% of users would be YAGNI; use this: foldedcase = lambda x: x.lower() What the paragraph you quoted seems to be warning about is that people who do implement a fully-principled foldedcase using the Unicode CaseFolding.txt file should be careful about offering foldedcaseTurkic and foldedcaseLithuanianDictionary -- both dangerous and YAGNI**2. This topic seems to be quite different to the topic of whether the results of unicode.lower does/should depend on the locale or not. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 09:12:56 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 15:12:56 +0100 Subject: Unknown cause to error (new to python) In-Reply-To: References: Message-ID: <478e10bd$0$27280$426a34cc@news.free.fr> Brandon Perry a ?crit : > Hi, I am having to compile a standalone version of python for the web > server I use (they don't allow access to /usr/bin/python). I posted > earlier about a GLib error, but I have fixed that now. I am very close > to getting this to work, but I am getting some weird errors. > > File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", > line 41, in ? > File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", line 71, in ? > File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", line 4, in ? > File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", line 4, in ? > File "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", line 15, in ? Sorry but my crystal ball is broken. Please post the *whole* traceback. From tjreedy at udel.edu Mon Jan 7 20:40:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 Jan 2008 20:40:28 -0500 Subject: code doesn't reference immutables? References: <5e6d3674-fddb-402f-9e5c-19afcd7fcc22@i7g2000prf.googlegroups.com> Message-ID: wrote in message news:5e6d3674-fddb-402f-9e5c-19afcd7fcc22 at i7g2000prf.googlegroups.com... | >From the manual: | | "code objects are immutable and contain no references (directly or | indirectly) to mutable objects" (3.2) | | I thought my code worked with both mutable and immutable objects. | Whassup? Consider the following: >>> def g(): return (1,2), [1,2] >>> dis.dis(g) 1 0 LOAD_CONST 3 ((1, 2)) 3 LOAD_CONST 1 (1) 6 LOAD_CONST 2 (2) 9 BUILD_LIST 2 12 BUILD_TUPLE 2 15 RETURN_VALUE >>> g.func_code.co_consts (None, 1, 2, (1, 2)) The code object stores the immutables 1, 2, and (1,2) but not the mutable [1,2]. Rather it stores immutable code to create the mutable list. I tried to see if the addition of closures violated the stipulation, using >>> def f(): l = [] def _(x): l.append(x) return _ but the inner code object only knows the list by the (immutable) name 'l', which does not count as a reference. Such code objects cannot be directly exec'ed but only executed indirectly by calling the function that wraps it and that has the reference to the in-this-case mutable object. (The mapping from 'l' to that object appears to be hidden.) Terry Jan Reedy From ShekinaAngel at webtv.net Thu Jan 31 01:43:56 2008 From: ShekinaAngel at webtv.net (Eddie Davis) Date: Wed, 30 Jan 2008 22:43:56 -0800 Subject: Wo killed Benazir Bhutto of Pakistan = NEOCON/ZIOCON many layers of deception References: Message-ID: <47a16282$0$26005$88260bb3@free.teranews.com> A moron posting from google? How unusual! -- Posted via a free Usenet account from http://www.teranews.com From ppetrick at gmail.com Mon Jan 21 20:44:19 2008 From: ppetrick at gmail.com (p.) Date: Mon, 21 Jan 2008 17:44:19 -0800 (PST) Subject: Transforming ascii file (pseduo database) into proper database References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> <47952796$0$17606$426a74cc@news.free.fr> Message-ID: <531e2dd1-6044-4a33-8651-9fc578a73bde@q39g2000hsf.googlegroups.com> Thanks to all for the ideas. I am familiar with external sorting. Hadn't considered it though. Will definitely be giving that a go, and then merging. Again, thanks all. From cokofreedom at gmail.com Fri Jan 18 05:03:10 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 18 Jan 2008 02:03:10 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> <7xy7aong73.fsf@ruckus.brouhaha.com> <4eba552a-3f9f-4bc7-81e7-150f109013ad@c23g2000hsa.googlegroups.com> Message-ID: <27215072-005b-4979-a27c-d328a947487b@d4g2000prg.googlegroups.com> > Hehe.. I remember seeing a similar one for Java and "Hello world" > using more and more elaborate abstractions and design patterns but I > can't find the link. > > George This is not linked to Java but deals with Hello World http://www.ariel.com.au/jokes/The_Evolution_of_a_Programmer.html From paul.hankin at gmail.com Thu Jan 17 18:59:44 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 17 Jan 2008 15:59:44 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> Message-ID: <657961e1-44ce-4fef-b3b7-5662878f28d8@f47g2000hsd.googlegroups.com> On Jan 17, 7:02?pm, George Sakkis wrote: > On Jan 17, 12:25 pm, Paul Hankin wrote: > > > > > On Jan 17, 4:38 pm, Bruno Desthuilliers > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > > Now there are very certainly smart solutions using itertools, but the > > > one I cooked is way too ugly so I'll leave this to itertools masters !-) > > > Here's my effort: > > > from itertools import izip, islice, chain, repeat > > > def padzip(*xs, **kw): > > ? ? pad = kw.get('padding', None) > > ? ? maxlen = max(len(x) for x in xs) > > ? ? return islice(izip(*[chain(x, repeat(pad)) for x in xs]), maxlen) > > > -- > > Paul Hankin > > And if the iterables don't necessarily support len(), here's a more > general solution: > > from itertools import repeat > > def izippad(*iterables, **kw): > ? ? pad = kw.get('padding', None) > ? ? next_pad = repeat(pad).next > ? ? getnext = [iter(iterable).next for iterable in iterables] > ? ? pending = size = len(iterables) > ? ? while True: > ? ? ? ? slice = [None] * size > ? ? ? ? for i in xrange(size): > ? ? ? ? ? ? try: slice[i] = getnext[i]() > ? ? ? ? ? ? except StopIteration: > ? ? ? ? ? ? ? ? pending -= 1 > ? ? ? ? ? ? ? ? if not pending: return > ? ? ? ? ? ? ? ? getnext[i] = next_pad > ? ? ? ? ? ? ? ? slice[i] = pad > ? ? ? ? yield slice Instead of counting the exceptions, we can limit the padding iterables by using an iterator that returns len(iterables) - 1 padding generators, use a sort of lazy chain, and then just izip. from itertools import izip, repeat def chain_next(xs, yg): for x in xs: yield x for y in yg.next(): yield y def izippad(*xs, **kw): padder = repeat(kw.get('padding', None)) padder_gen = repeat(padder, len(xs) - 1) return izip(*[chain_next(x, padder_gen) for x in xs]) -- Paul Hankin From gnewsg at gmail.com Sat Jan 12 12:50:16 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 12 Jan 2008 09:50:16 -0800 (PST) Subject: How to get user home directory on Windows References: <0bb27916-5416-47b2-b58c-1eb82ccb6d3e@k2g2000hse.googlegroups.com> Message-ID: Update. I found a way for getting the home directory of the user but it requires to validate the user by providing username+password: def get_homedir(username, password): token = win32security.LogonUser( username, None, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT ) return win32profile.GetUserProfileDirectory(token) What I'd like to do is avoiding the requirement of the password, the same way as if I would on UNIX where it would be enough just using the pwd module: >>> import pwd >>> pwd.getpwnam('user').pw_dir '/home/user' From researchbase at gmail.com Tue Jan 22 13:57:15 2008 From: researchbase at gmail.com (krishnakant Mane) Date: Wed, 23 Jan 2008 00:27:15 +0530 Subject: difflib confusion Message-ID: hello all, I have a bit of a confusing question. firstly I wanted a library which can do an svn like diff with two files. let's say I have file1 and file2 where file2 contains some thing which file1 does not have. now if I do readlines() on both the files, I have a list of all the lines. I now want to do a diff and find out which word is added or deleted or changed. and that too on which character, if not at least want to know the word that has the change. any ideas please? kk From ajaksu at gmail.com Mon Jan 7 14:55:12 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 7 Jan 2008 11:55:12 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Message-ID: On Jan 7, 9:53 am, Berco Beute wrote: > Cool! We knew it would happen one day :) > What could be the reason? Python 3? Jython 2.2? Java's loss of > sexiness? > > What I would like to know is what it was that boosted Python's > popularity in 2004 (seehttp://www.tiobe.com/tiobe_index/Python.html). > Equally interesting is the question why it dropped shortly after. > > 2B >From http://www.tiobe.com/index.htm?tiobe_index(and http://www.tiobe.com/tiobe_index/images/tpci_trends.png ) # Q: What happened to Java in April 2004? Did you change your methodology? A: No, we did not change our methodology at that time. Google changed its methodology. They performed a general sweep action to get rid of all kinds of web sites that had been pushed up. As a consequence, there was a huge drop for languages such as Java and C++. In order to minimize such fluctuations in the future, we added two more search engines (MSN and Yahoo) a few months after this incident. From alonie at unimelb.edu.au Thu Jan 10 16:40:58 2008 From: alonie at unimelb.edu.au (Andrew Lonie) Date: Fri, 11 Jan 2008 08:40:58 +1100 Subject: Elementtree 1.3 and xpath Message-ID: Hi I noticed that the xpath functionality of elementtree has been upgraded in version 1.3. However I can't seem to get the [postion] predicate to function. All the other new functionality seems to be working. Maybe I'm getting the syntax wrong?: >>> xml = ET.XML("""texttext2""") >>> elem = xml.find("tag[@att]") #Works fine - returns first tag element >>> elem = xml.find("tag[@att]/..") #Works fine - returns entire doc >>> elem = xml.find("tag[1]") # FAILS - returns nothing. Should return first tag element. Any help appreciated! Andrew From steven at REMOVE.THIS.cybersource.com.au Wed Jan 23 00:50:44 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 05:50:44 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> Message-ID: On Wed, 23 Jan 2008 04:58:02 +0000, Grant Edwards wrote: > On 2008-01-22, over at thepond.com wrote: > >> My expertise, if any, is in assembler. I'm trying to understand Python >> scripts and modules by examining them after they have been disassembled >> in a Windows environment. > > You can't dissassemble them, since they aren't ever converted to > assembler and assembled. Python is compiled into bytecode for a virtual > machine (either the Java VM or the Python VM or the .NET VM). There is the Python disassembler, dis, which dissassembles the bytecode into something which might as well be "assembler" *cough* for the virtual machine. -- Steven From python.list at tim.thechases.com Wed Jan 16 09:55:36 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 16 Jan 2008 08:55:36 -0600 Subject: Python help for a C++ programmer In-Reply-To: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> References: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> Message-ID: <478E1AE8.9090207@tim.thechases.com> > I want something like (C++ code): > > struct Response > { > std::string name; > int age; > int iData[ 10 ]; > std::string sData; > }; > > // Prototype > void Process( const std::vector& ); > > int main() > { > std::vector responses; > > while( /* not end of file */ ) > { > Response r; > > // Fill struct from file > r.name = /* get the data from the file */; > r.age = /* ... */; > r.iData[0] = /* ... */; > // ... > r.sData = /* ... */; > responses.push_back( r ); > } > > // Do some processing on the responses > Process( responses ); > } > > What is the preferred way to do this sort of thing in Python? Without knowing more about the details involved with parsing the file, here's a first-pass whack at it: class Response(object): def __init__(self, name, age, iData, sData): self.name = name self.age = age self.iData = iData self.sData = sData def __repr__(self): return '%s (%s)' % self.name def parse_response_from_line(line): name, age, iData, sData = line.rstrip('\n').split('\t') return Response(name, age, iData, sData) def process(response): print 'Processing %r' % response responses = [parse_response_from_line(line) for line in file('input.txt')] for response in responses: process(response) That last pair might be condensed to just for line in file('input.txt'): process(parse_response_from_line(line)) Things get a bit hairier if your input is multi-line. You might have to do something like def getline(fp): return fp.readline().rstrip('\n') def response_generator(fp): name = None while name != '': name = getline(fp) age = getline(fp) iData = getline(fp) sData = getline(fp) if name and age and iData and sData: yield Response(name, age, iData, sData) fp = file('input.txt') for response in response_generator(fp): process(response) which you can modify accordingly. -tkc From dongie.agnir at gmail.com Sat Jan 12 14:52:13 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Sat, 12 Jan 2008 11:52:13 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: Oh.. it seems my naiveness has stirred quite a discussion >_<... I must admit though, I've learned a bit about Python reading through this topic. Thanks to everyone who pointed out the flaws in the code. I'll see if I can come up with my own color tracking solution in a few weeks and post back here. Thanks! From killerkiwi2005 at gmail.com Sun Jan 27 01:49:08 2008 From: killerkiwi2005 at gmail.com (Jason Taylor) Date: Sun, 27 Jan 2008 19:49:08 +1300 Subject: Klik2 Project, Python apps on linux Message-ID: <94dd8f6f0801262249v1c07cf3em2548c470a523291e@mail.gmail.com> Hi We've been working on klik2, http://code.google.com/p/klikclient/, which implements OSX like application files on linux (with applications working on all distros), In which every user desktop application is 1 file We've run into a bit of a problem with python apps, so while we can run a complicated application like openoffice.org on ubuntu, fedora and suse from a single file we cant run any python applications such as jokosher gnome-specimen angrydd gausssum pathological quodlibet webboard istanbul exaile ccsm bittornado pessulus labyrinth wammu accerciser We'd like to fix this in a clean way with out resorting to nasty hacks involving $PYTHON_PATH. If any one has any suggestions please email me or drop by #klik on freenode Issue http://code.google.com/p/klikclient/issues/detail?id=144 Cheers Jason Taylor -- "Why isn't my life like a situation comedy? Why don't I have a bunch of friends with nothing better to do but drop by and instigate wacky adventures? Why aren't my conversations peppered with spontaneous witticisms? Why don't my friends demonstrate heartfelt concern for my well being when I have problems? ...I gotta get my life some writers." - Calven -------------- next part -------------- An HTML attachment was scrubbed... URL: From Louis.Soninhu at gmail.com Wed Jan 9 14:57:07 2008 From: Louis.Soninhu at gmail.com (Louis.Soninhu at gmail.com) Date: Wed, 9 Jan 2008 11:57:07 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> <962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.googlegroups.com> Message-ID: oops, it seems there are other 'meaningless' item, which actually caused the problem Thanks for helps From steve at REMOVE-THIS-cybersource.com.au Thu Jan 31 17:39:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 31 Jan 2008 22:39:02 -0000 Subject: helper function in a class' namespace References: <47a226bb$0$2982$ba620e4c@news.skynet.be> <47a22a17$0$8306$9b622d9e@news.freenet.de> Message-ID: <13q4jg6edfvi970@corp.supernews.com> On Thu, 31 Jan 2008 20:05:44 +0000, Stargaming wrote: > String concatenation is generally considered unpythonic, better use > string interpolation:: > > 'H> %s' % (M,) String concatenation is significantly faster than string interpolation. >>> import timeit >>> timeit.Timer("'H> %s' % M", "M = 'abcdef'").repeat() [1.3407769203186035, 0.69128704071044922, 0.56362509727478027] >>> timeit.Timer("'H> ' + M", "M = 'abcdef'").repeat() [0.69647812843322754, 0.69620108604431152, 0.65643787384033203] The danger with string concatenation comes from building up a string piece by piece: even though a single + is faster than a single %, a dozen concats will likely be MUCH slower than a single &. Also, the tuple above is totally unnecessary. 'H> %s' % M will work fine. -- Steven From jimgardener at gmail.com Thu Jan 3 10:49:19 2008 From: jimgardener at gmail.com (jimgardener at gmail.com) Date: Thu, 3 Jan 2008 07:49:19 -0800 (PST) Subject: how to use bool Message-ID: hi, i have some code where i set a bool type variable and if the value is false i would like to return from the method with an error msg.. being a beginner I wd like some help here class myclass: ......... def mymethod(self): success=True msg="all validation OK" success=validateSthing() if(success==False): msg="sthing failed" return (success,msg) dosomeprocessing() ..... success=validateSthingelse() if(success==False): msg="sthingelse failed" return (success,msg) domoreprocessing() .... return(success,msg) i would like to know if this way of doing this is OK..I have need of many kinds of validations in this ..is there a better way of doing this ? thank you From mail at danielcuschieri.com Wed Jan 2 14:04:36 2008 From: mail at danielcuschieri.com (Daniel Cuschieri) Date: Wed, 2 Jan 2008 20:04:36 +0100 Subject: Pickle problem In-Reply-To: <267762840801021100j62f1c25o772a1f54625ecc43@mail.gmail.com> References: <267762840801021100j62f1c25o772a1f54625ecc43@mail.gmail.com> Message-ID: <267762840801021104v4560d4c0pd424212000ee0070@mail.gmail.com> Hi, I used code similar to the one at http://www.onlamp.com/pub/a/python/2006/02/09/ai_decision_trees.html in order to build an ID3 decision tree using python. I obviously do not want to rebuild this tree every time i need to use it! so i tried to save it using pickle, after building it: >from cPickle import dump >output = open(path, 'wb') >dump(self.tree, output, -1) >output.close() As soon as I do this, I get the following error: >dump(self.tree, output, -1) >cPickle.PicklingError: Can't pickle : attribute lookup __builtin__.function failed How on earth can I solve this!? Rebuilding the tree every time is dumb! I'm sure there is a work around somehow, but I honestly don't have a clue as to what this might be! Any ideas please!? I'm totally lost and stuck! Thanks! Daniel -------------- next part -------------- An HTML attachment was scrubbed... URL: From terry at jon.es Mon Jan 21 06:52:00 2008 From: terry at jon.es (Terry Jones) Date: Mon, 21 Jan 2008 12:52:00 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 02:52:59 on Monday, 21 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: <18324.34656.19567.943223@terry.local> >>>>> "cokofreedom" == cokofreedom writes: cokofreedom> Terry, your technique is efficient and pretty readable! All cokofreedom> that could be added now is a way to output the data in a more cokofreedom> user-friendly print. Yes, and a fix for the bug Arnaud just pointed out :-) Below is code to print things more nicely for you. Terry from operator import * from itertools import izip def countdown(target, nums, numsAvail, value, partialSolution, solutions, ops=(add, mul, sub, div)): if value == target or not any(numsAvail): # Add the solution, if we're right. if value == target: solutions.add(tuple(partialSolution)) elif value is None: # Use each distinct number as a starting value. used = set() for i, num in enumerate(nums): if num not in used: numsAvail[i] = False used.add(num) partialSolution.append(num) countdown(target, nums, numsAvail, num, partialSolution, solutions, ops) numsAvail[i] = True partialSolution.pop() else: for op in ops: for i, num in enumerate(nums): if numsAvail[i]: numsAvail[i] = False moreAvail = any(numsAvail) try: lastNum, lastOp = partialSolution[-2:] except ValueError: lastNum, lastOp = partialSolution[-1], None # Don't allow any of: if not ( # Div: after mul, by 1, by 0, producing a fraction. (op == div and (lastOp == 'mul' or num <= 1 or value % num != 0)) or # If initial mul/add, canonicalize to 2nd operator biggest. ((op == mul or op == add) and lastOp is None and num > lastNum) or # Don't allow add or sub of 0. ((op == add or op == sub) and num == 0) or # Don't allow mult by 1. (op == mul and num == 1) or # Don't allow sub after add (allow add after sub). (op == sub and lastOp == 'add') or # If same op twice in a row, canonicalize operand order. (lastOp == op.__name__ and num > lastNum) ): partialSolution.extend([num, op.__name__]) countdown(target, nums, numsAvail, op(value, num), partialSolution, solutions, ops) del partialSolution[-2:] numsAvail[i] = True op2sym = { 'add' : '+', 'sub' : '-', 'mul' : '*', 'div': '/', } def pretty(s): out = [str(s[0])] lastOp = None for value, op in izip(*(iter(s[1:]),) * 2): if (op == 'mul' or op == 'div') and (lastOp == 'add' or lastOp == 'sub'): out.insert(0, '(') out.append(')') out.append(op2sym[op]) out.append(str(value)) lastOp = op return ''.join(out) for nums, target in ( ((100, 9, 7, 6, 3, 1), 253), ((100, 9, 7, 6, 3, 1), 234), ((2, 3, 5), 21), ((7, 8, 50, 8, 1, 3), 923), ((8, 8), 16), ((8, 8, 8), 8), ((8, 0), 8), ((7,), 8), ((), 8), ((8, 8, 8, 8), 32), ((2, 4, 5, 8, 25), 758), ((2, 3, 4, 100), 406), ): solutions = set() countdown(target, nums, [True,] * len(nums), value=None, partialSolution=[], solutions=solutions) print "%d solutions to: target %d, numbers = %s" % (len(solutions), target, nums) for s in sorted(solutions, cmp=lambda a, b: cmp(len(a), len(b)) or cmp(a, b)): print '\t', pretty(s) Sample output: 8 solutions to: target 253, numbers = (100, 9, 7, 6, 3, 1) (6*3-1)*9+100 (7*6+9)*3+100 (9-3)*7*6+1 (100-9-7)*3+1 ((3+1)*6-7)*9+100 (7+1)*6*3+100+9 (7+6+3+1)*9+100 (100-7-6)*3-9+1 19 solutions to: target 234, numbers = (100, 9, 7, 6, 3, 1) (6*3+7+1)*9 ((7+1)*9+6)*3 (7*3-1+6)*9 (7*6*3-100)*9 ((100-1)/3-7)*9 ((100-1)*7+9)/3 (100*7*3+6)/9 (100-9)/7*6*3 (100-9-7-6)*3 ((6+1)*100-7+9)/3 ((6-9)*7-1+100)*3 (7*3-6)*9-1+100 7*6*3-1+100+9 (100-1)/3*7-6+9 ((100-1)*7-9)/3+6 (100*7-6-1+9)/3 ((100-7)/3-1+9)*6 ((100-7)/3-6+1)*9 (100+9+7+1)/3*6 From bearophileHUGS at lycos.com Sat Jan 26 17:12:37 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 26 Jan 2008 14:12:37 -0800 (PST) Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> <7xy7acsx2l.fsf@ruckus.brouhaha.com> <8ddebd68-43dc-4320-86e1-887aadff4af3@d70g2000hsb.googlegroups.com> <7xmyqs722t.fsf@ruckus.brouhaha.com> <13pnbp9l8lk1j8b@corp.supernews.com> Message-ID: Steven D'Aprano: > Much to my surprise, the fastest solution I've tried appears to be a pure > Python version not even using max() at all. That version is easy to translate to other languages and you can probably find that Psyco makes it much faster still. Bye, bearophile From ggpolo at gmail.com Mon Jan 21 09:08:11 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 21 Jan 2008 12:08:11 -0200 Subject: Q: paramiko/SSH/ how to get a remote host_key In-Reply-To: <9077ed27-e9b1-47ca-b30e-918e3b50d517@e4g2000hsg.googlegroups.com> References: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> <9077ed27-e9b1-47ca-b30e-918e3b50d517@e4g2000hsg.googlegroups.com> Message-ID: 2008/1/21, DHR : > Thank you! Now it works and the code looks like this: > > import paramiko > import base64 > from paramiko import AutoAddPolicy, SSHClient > > client = paramiko.SSHClient() > client.set_missing_host_key_policy(AutoAddPolicy()) > client.connect('hostIP', username='uname', password='pass') > stdin, stdout, stderr = client.exec_command('ls') > for line in stdout: > print '... ' + line.strip('\n') > > client.close() Very nice =) Just an advice, you dont need to import base64. Method decode of strings allows you to specify encoding as 'base64' to perform needed operations. > > On Jan 21, 3:10 pm, "Guilherme Polo" wrote: > > 2008/1/21, DHR : > > > > > > > > > I am connecting from a WindowsXP SP2 machine. When using Putty as an > > > SSH client, if you connect for the first time then you get somethign > > > like this: > > > > > ''' The server's host key is not cached in the registry. You > > > have no guarantee that the server is the computer you > > > think it is. > > > The server's rsa2 key fingerprint is: > > > ssh-rsa 1024 7b:e5:6f:a7:f4:f9:81:62:5c:e3:1f:bf:8b:57:6c:5a > > > If you trust this host, hit Yes to add the key to > > > PuTTY's cache and carry on connecting. > > > If you want to carry on connecting just once, without > > > adding the key to the cache, hit No. > > > If you do not trust this host, hit Cancel to abandon the > > > connection. ''' > > > > > If I get it correctly, Putty is using such a command to recieve the > > > host_key the first time it connects to a remote SSH server. Then it > > > stores it into the registry. The question is how can I do it from > > > Python? > > > > When you call method connect of SSHClient it checks if server's > > hostname is in system_hot_keys or any local host keys, if it is not, > > the missing host key policy is used. The default policy is to reject > > the key and raise an SSHException, but you can change that default > > policy to AutoAddPolicy > > > > > > > > > > > > > Guilherme Polo wrote: > > > > 2008/1/21, DHR : > > > > > I'm trying to run the simpliest example form paramiko readme(Homepage: > > > > >http://www.lag.net/paramiko/), and > > > > > cannot find out how to get the remote SSH server host_key. > > > > > > > This is the code. It is supposed to connect to a remote SSH host and > > > > > execute an 'ls' command: > > > > > > > import paramiko, base64 > > > > > > > key = paramiko.RSAKey(data=base64.decodestring('AAA...')) > > > > > client = paramiko.SSHClient() > > > > > client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key) > > > > > client.connect('227.112.168.273', username='uname', password='pass') > > > > > stdin, stdout, stderr = client.exec_command('ls') > > > > > for line in stdout: > > > > > print '... ' + line.strip('\n') > > > > > > > client.close() > > > > > > > Now, if I understand it correctly I need to get somehow the host_key > > > > > from the server and > > > > > write it insted of the 'AAA...' thing. Is there a command to get the > > > > > host_key from a remote SSH > > > > > server? > > > > > -- > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > You need a key to connect to that server, so you should want this: > > > > > > keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) > > > > > > Then keys[hostname] should contain a RSAKey object that you are looking for > > > > > > -- > > > > -- Guilherme H. Polo Goncalves > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > > -- > > -- Guilherme H. Polo Goncalves > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From lists at cheimes.de Wed Jan 23 02:54:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 23 Jan 2008 08:54:19 +0100 Subject: python24 symbol file...pyhon24.pdb In-Reply-To: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> References: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> Message-ID: over at thepond.com wrote: > I've seen a few references on the net to a python24.pdb file. I assume > it's a symbol file along the lines of the pdb files issued by > microsoft for their products. Maybe I'm wrong. .pdb files (program database) are created by MS' compiler, see http://en.wikipedia.org/wiki/Program_database. Python doesn't ship the files. You have to compile Python yourself to get the pdb files. Christian From paul.hankin at gmail.com Sun Jan 6 08:15:49 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sun, 6 Jan 2008 05:15:49 -0800 (PST) Subject: how to use bool References: Message-ID: <7db0fe1e-bbc0-4eb1-ac54-db6d0750bad7@s12g2000prg.googlegroups.com> On Jan 3, 3:49?pm, jimgarde... at gmail.com wrote: > hi, i have some code where i set a bool type variable and if the value > is false i would like to return from the method with an error msg.. > being a beginner I wd like some help here > > class myclass: > ? ? ?......... > ? ? def ?mymethod(self): > ? ? ? ? ? ? ?success=True > ? ? ? ? ? ? ?msg="all validation OK" > ? ? ? ? ? ? ?success=validateSthing() > ? ? ? ? ? ? ?if(success==False): > ? ? ? ? ? ? ? ? ? ?msg="sthing failed" > ? ? ? ? ? ? ? ? ? ?return (success,msg) > > ? ? ? ? ? ? ?dosomeprocessing() > ? ? ? ? ? ? ?..... > ? ? ? ? ? ? ?success=validateSthingelse() > ? ? ? ? ? ? ?if(success==False): > ? ? ? ? ? ? ? ? ? ?msg="sthingelse ?failed" > ? ? ? ? ? ? ? ? ? ?return (success,msg) > ? ? ? ? ? ? ?domoreprocessing() > ? ? ? ? ? ? ? .... > ? ? ? ? ? ? ? ?return(success,msg) > > i would like to know if this way of doing this is OK..I have need of > many kinds of validations in this ..is there a better way of doing > this ? As everyone's pointed out, you should use exceptions for this sort of thing. > def mymethod(self): > success=True > msg="all validation OK" > success=validateSthing() > if(success==False): > msg="sthing failed" > return (success,msg) > > dosomeprocessing() > ..... > success=validateSthingelse() > if(success==False): > msg="sthingelse failed" > return (success,msg) > domoreprocessing() > .... > return(success,msg) As everyone else has pointed out, you should use exceptions for this sort of thing. But even without exceptions, you can write your code a lot more cleanly by omitting all the temporary variables. That way, you don't have to search around to see where things are used (eg. seeing where "all validation OK" is used requires you to read every line of your method). def mymethod(self): if not validateSthing(): return (False, "sthing failed") dosomeprocessing() .... if not validateSthingelse(): return (False, "sthingelse failed") domoreprocessing() ... return (True, "all validation OK") Isn't that a lot more readable? -- Paul Hankin From steveo at syslang.net Thu Jan 10 16:04:23 2008 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 10 Jan 2008 16:04:23 -0500 (EST) Subject: Another dumb scope question for a closure. In-Reply-To: References: Message-ID: On Wednesday, Jan 9th 2008 at 14:01 -0000, quoth Fredrik Lundh: =>Steven W. Orr wrote: => =>> So sorry because I know I'm doing something wrong. =>> =>> 574 > cat c2.py =>> #! /usr/local/bin/python2.4 =>> =>> def inc(jj): =>> def dummy(): =>> jj = jj + 1 =>> return jj =>> return dummy =>> =>> h = inc(33) =>> print 'h() = ', h() =>> 575 > c2.py =>> h() = =>> Traceback (most recent call last): =>> File "./c2.py", line 10, in ? =>> print 'h() = ', h() =>> File "./c2.py", line 5, in dummy =>> jj = jj + 1 =>> UnboundLocalError: local variable 'jj' referenced before assignment => =>http://docs.python.org/ref/naming.html has the answer: => => "If a name binding operation occurs anywhere within a code block, => all uses of the name within the block are treated as references => to the current block." Thanks. This helps a little. But I still don't understand something. If it's a question of a legal reference or not, I could buy it. But what's really happening is that it works if it's a read-only ref but fails if it's a write: >>> def inc(jj): ... def dummy(): ... print jj ... return dummy ... >>> f = inc(44) >>> f() 44 >>> f() 44 >>> f() 44 >>> The problem only happens if I try to modify jj. What am I not understanding? From fetchinson at googlemail.com Sat Jan 5 22:58:39 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 5 Jan 2008 19:58:39 -0800 Subject: Python web aps - A matter of security In-Reply-To: <53318.192.168.1.35.1199558462.webmail@192.168.1.35> References: <53318.192.168.1.35.1199558462.webmail@192.168.1.35> Message-ID: On 1/5/08, lloyd at paisite.com wrote: > Hello, > > I'm developing a Python-based web ap, but don't understand how to best > organize the modules and set permissions for maximum security. > > Here's how the Python code for my ap is organized: > > 1) I have Python modules in a project directory. The path to that directory > is in a *.pth file in the .*/pythonx-y/site-packages directory. > > Question: who should own these modules; what groups should have access, and > how should permissions be set? > > 2) I have high-level modules that import the worker-bee modules in the web > root directory tree that are called by the webserver. > > Questions: who should own these modules, what groups should have access, and > how should permissions be set? > > 3) Is there a better way to organize my Python modules? Are there other > security issues I should heed? > > Many thanks, > > Lloyd Are you using any of the many available web frameworks like turbogears, django, etc? If so your best option is probably to use the authentication/authorization capabilities of these frameworks and then you won't have to worry about it too much. Cheers, Daniel From castironpi at gmail.com Sat Jan 12 17:41:14 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 14:41:14 -0800 (PST) Subject: removeall() in list References: <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> <354c74f6-6e56-4e41-a686-56239aa4cea9@f47g2000hsd.googlegroups.com> <7x8x2uj3yb.fsf@ruckus.brouhaha.com> <0ad68aa8-735d-4cf0-b17a-d1f2be6af652@f47g2000hsd.googlegroups.com> <7x1w8mj27a.fsf@ruckus.brouhaha.com> <7x7iie3ku2.fsf@ruckus.brouhaha.com> Message-ID: <94c5da6f-00df-4d9e-9ed6-d4a3b8d67eed@j78g2000hsd.googlegroups.com> On Jan 12, 1:28 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > Will you engage with me over e-mail to discuss the Locker > > implementation I'm developing? Aaron > > I really can't, sorry. I'm finding it hard enough to follow over the > newsgroup. If you just have a single one of these lists, it's > probably simplest to do what Frederik Lundh suggested. The other > stuff we've discussed is mostly about how to organize having a lot of > them. Highlight from the working solution: def onfulfill( self, func, *args, **kwargs ): '''decorator launches its function in separate thread upon completion of func. todo: cancel and reference check.''' locfunc= Ref() def honorth(): result= self.op( func, *args, **kwargs ) locfunc.val( result ) def prefulfill( func ): locfunc.val= func th= threading.Thread( target= honorth ) th.start() return prefulfill From tteststudent at gmail.com Sat Jan 5 11:04:42 2008 From: tteststudent at gmail.com (ttest) Date: Sat, 5 Jan 2008 08:04:42 -0800 (PST) Subject: Request for help with Image color space conversion References: <8586a895-f238-4a22-a1bb-31c39f22b4cc@n20g2000hsh.googlegroups.com> Message-ID: <37094242-5728-466f-a3b9-c5ae76a9f3c5@s12g2000prg.googlegroups.com> > Reimplement colorsys.rgb_to_hsv() such that it operates on arrays instead of > scalars. Only minor modifications are necessary. > > -- > Robert Kern Thanks! I'll try and see if a newcomer like me can get his head around the array-centric modifications to colorsys. From asmodai at in-nomine.org Sat Jan 5 05:36:44 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 5 Jan 2008 11:36:44 +0100 Subject: Fortran to Python In-Reply-To: <13nstth7a3km06c@corp.supernews.com> References: <13nstth7a3km06c@corp.supernews.com> Message-ID: <20080105103643.GT82115@nexus.in-nomine.org> -On [20080104 19:21], Dennis Lee Bieber (wlfraed at ix.netcom.com) wrote: > If the FORTRAN is using single precision reals, I'd expect a >slow-down in Python just on that alone, as Python uses doubles as the >only float type. There is also the overhead of object access for each. In this case it uses complex*16 and real*8. Is a real*8 a single precision real? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Everything has beauty, but not everyone sees it. - Confucius From gagsl-py2 at yahoo.com.ar Wed Jan 30 18:09:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jan 2008 21:09:36 -0200 Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> Message-ID: En Wed, 30 Jan 2008 20:47:36 -0200, FireNWater escribi?: > I'm curious why the different outputs of this code. If I make the > dictionary with letters as the keys, they are not listed in the > dictionary in alphabetical order, but if I use the integers then the > keys are in numerical order. > > I know that the order of the keys is not important in a dictionary, > but I was just curious about what causes the differences. Thanks!! > > list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] > list2 = [1,2,3,4,5,6,7,8] > > Dictionary = dict(zip(list1, list2)) > print Dictionary > > Dictionary1 = dict(zip(list2, list1)) > print Dictionary1 Dictionaries use the hash value of the keys to distribute them in "buckets". Compare these: for key in list1: print key, hash(key) for key in list2: print key, hash(key) -- Gabriel Genellina From rong.xian at gmail.com Sun Jan 27 05:17:05 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 02:17:05 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> Message-ID: <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> On 1?24?, ??3?29?, "Gabriel Genellina" wrote: > En Thu, 24 Jan 2008 04:52:22 -0200, glacier escribi?: > > > According to your reply, what will happen if I try to decode a long > > string seperately. > > I mean: > > ###################################### > > a='???'*100000 > > s1 = u'' > > cur = 0 > > while cur < len(a): > > d = min(len(a)-i,1023) > > s1 += a[cur:cur+d].decode('mbcs') > > cur += d > > ###################################### > > > May the code above produce any bogus characters in s1? > > Don't do that. You might be splitting the input string at a point that is > not a character boundary. You won't get bogus output, decode will raise a > UnicodeDecodeError instead. > You can control how errors are handled, see http://docs.python.org/lib/string-methods.html#l2h-237 > > -- > Gabriel Genellina Thanks Gabriel, I guess I understand what will happen if I didn't split the string at the character's boundry. I'm not sure if the decode method will miss split the boundry. Can you tell me then ? Thanks a lot. From asmodai at in-nomine.org Fri Jan 4 10:23:38 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jan 2008 16:23:38 +0100 Subject: Fortran to Python In-Reply-To: <477E48B4.1090809@chamonix.reportlab.co.uk> References: <20080104132119.GK82115@nexus.in-nomine.org> <20080104144712.GL82115@nexus.in-nomine.org> <477E48B4.1090809@chamonix.reportlab.co.uk> Message-ID: <20080104152338.GN82115@nexus.in-nomine.org> -On [20080104 15:56], Robin Becker (robin at reportlab.com) wrote: >you probably want to look at numpy an extension that handles lots of matrix >things with great ease. I think it now lives at http://scipy.org/ Yeah, I am aware of SciPy/NumPy, but aside from these two calls to do this inverse matrix calculation the rest is just stock mathematics, supported by Python. I am trying to avoid another external dependency if I can. :) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Time is merely a residue of Reality... From cbmeeks at gmail.com Wed Jan 16 14:51:46 2008 From: cbmeeks at gmail.com (cbmeeks) Date: Wed, 16 Jan 2008 11:51:46 -0800 (PST) Subject: Help with python shell References: <2706aa71-b072-4cbb-a7d9-abbfadd7d35a@c4g2000hsg.googlegroups.com> <5v7100F1kmtinU2@mid.uni-berlin.de> <5v74kaF1kt3a3U1@mid.uni-berlin.de> Message-ID: <93c924ff-f25a-48cf-ac1d-1b179bcaebf3@c4g2000hsg.googlegroups.com> On Jan 16, 2:35 pm, "Diez B. Roggisch" wrote: > cbmeeks schrieb: > > > > > On Jan 16, 1:33 pm, "Diez B. Roggisch" wrote: > >> cbmeeks schrieb: > > >>> I just upgraded my Python install up to version 2.5.1 (from 2.4.x) > >>> using source code and compiling. > >>> Everything went fine until I enter the command line mode and press any > >>> arrow keys. > >>> When I press UP arrow, I was getting my previous command as always but > >>> now I get: ^[[A > >>> What can I do to fix this?? > >> Compiling with readline support? I guess that's missing. > > >> Diez > > > I tried ./configure --enable-readline but that didn't do the trick. > > ARG!! This is annoying. > > You don't just need to enable it - the readline lib needs to be > installed, including the possible devel-package (If you are under linux) > for the headers. > > Diez That worked! I had to install readline-devel and rebuild with --enable-readline Thanks!!!!! cbmeeks http://codershangout.com From peng.kyo at gmail.com Thu Jan 17 02:20:36 2008 From: peng.kyo at gmail.com (J. Peng) Date: Thu, 17 Jan 2008 15:20:36 +0800 Subject: assigning values in python and perl In-Reply-To: <87tzlddjq6.fsf@mulj.homelinux.net> References: <87tzlddjq6.fsf@mulj.homelinux.net> Message-ID: <18c1e5f20801162320g6e25e4acw62fe08f451498051@mail.gmail.com> On Jan 17, 2008 2:55 PM, Hrvoje Niksic wrote: > > @$ref = (4, 5, 6) intentionally assigns to the same list pointed to by > the reference. That would be spelled as x[:] = [4, 5, 6] in Python. > What Python does in your example is assign the same as Perl's $ref = > [4, 5, 6]. So they're not so different after all. > Yup,you're so right.This test below in perl is the same as in python. So at before I may got mistaken by myself.Thanks all. $ cat t1.pl sub test { my $ref = shift; $ref = [4,5,6]; } my @a = (1,2,3); test(\@a); print "@a"; $ perl t1.pl 1 2 3 From mdfranz at gmail.com Tue Jan 1 17:31:30 2008 From: mdfranz at gmail.com (Matthew Franz) Date: Tue, 1 Jan 2008 16:31:30 -0600 Subject: Network Module In-Reply-To: <52da23100801010540s122337aci470e2ee4fa85fa1b@mail.gmail.com> References: <52da23100801010540s122337aci470e2ee4fa85fa1b@mail.gmail.com> Message-ID: <33acb3db0801011431h341e23f5mf6a1df91e3cc209f@mail.gmail.com> Why not just wrap netstat for what you need? or you might be able to get from /proc entries? Or look at http://www.psychofx.com/psi/trac/wiki/ (PSI Tools) If you want interface statistics you can process the CSV output of bwm-ng (http://www.gropp.org/?id=projects&sub=bwm-ng) - mdf On Jan 1, 2008 7:40 AM, Sunil Ghai wrote: > Hello people, > I am searching for a python module to interact with the network > connections/interfaces. For example the number of active TCP/IP connections > via eth0 interface and all that stuff. > I have done googling and search at pythonorg but couldn't find any. > > Thanks > Sunil Kumar Ghai > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matthew Franz http://www.threatmind.net/ From f.guerrieri at gmail.com Tue Jan 8 05:37:48 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Tue, 8 Jan 2008 11:37:48 +0100 Subject: Paid subscription Python magazines In-Reply-To: <13o6jthqrl90o2d@corp.supernews.com> References: <13o6jthqrl90o2d@corp.supernews.com> Message-ID: <79b79e730801080237s24235e6ap268af62bf3f255ba@mail.gmail.com> On Jan 8, 2008 11:17 AM, Jon Harrop wrote: > > Are there any Python magazines that you can pay to subscribe to? (either > paper or on-line). > Python Magazine comes to mind www.pythonmagazine.com I am subscribed and find it very good. Francesco From ganeshborse at gmail.com Thu Jan 10 05:07:34 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 10 Jan 2008 02:07:34 -0800 (PST) Subject: Import of cStringIO failing with "undefined symbol: PyObject_SelfIter" on python-2.3.3-88.9 Message-ID: <13cb45c0-5b5d-4151-9797-d851ed3ad544@i7g2000prf.googlegroups.com> I am importing cStringIO module in my PythonC++ embedded program. The import is failing with the following error: ImportError: /usr/lib/python2.3/lib-dynload/cStringIO.so: undefined symbol: PyObject_SelfIter I have python-2.3.3-88.9.x86 installed on my machine. Why is this error coming? how can I resolve this undefined symbol? Do I need to import anything before this? From azam.farooq3 at gmail.com Tue Jan 29 01:50:13 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Mon, 28 Jan 2008 22:50:13 -0800 (PST) Subject: Do You Want a GSM Mobile with Amazing Features? Please click here Message-ID: <8be6326a-f91c-431c-8c06-5a78a41ac20c@s8g2000prg.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 ganeshborse at gmail.com Tue Jan 15 06:01:49 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Tue, 15 Jan 2008 03:01:49 -0800 (PST) Subject: how to set sys.stderr to object of cStringIO type References: <45c94bc5-4bbe-491d-bcdd-3cb904cb552b@f47g2000hsd.googlegroups.com> Message-ID: <740646f5-f2e7-4b5f-a02d-aec8367e68b9@s8g2000prg.googlegroups.com> On Jan 15, 5:45?pm, grbgooglefan wrote: > I am in a perculiar situation. I want to use PyRun_SimpleString for > creating Python functions in embedded Python in C++. > But there could be cases when Python function code compilation could > fail & PyRun_SimpleString will return -1 as return status. At this > time, it prints the error message to sys.stderr. > So, we do not have any control or cannot use that message to show to > user to correct the errors in the function code. > I could assign an object of cStringIO type to sys.stderr at Python > command prompt as below: > > >>> import sys > >>> import cStringIO > >>> obj=cStringIO.StringIO() > >>> sys.stderr=obj > > And then using the obj.getvalue(), I could print exceptions printed to > sys.stderr. > > But, I am not able to figure out, how can I do this same thing in > Python/C API in my program using Py* functions? > > How do we set the "sys.stderr" to cStringIO object from Python > embedded in C++ or C? > > Should I be using PyFile_FromFile for convert the cStringIO object? > Please help. I have got a solution for this. Would like to know if this is the correct way or will it cause any problems if program runs for long time? /***************************************************/ /--1st stage is assign object of cStringIO to sys.stderr at initialization /-- once that is done, we can call getvalue() on that object on every error. /-----------------------------------------------------/ PyObject *_pPyobStringIO; PyObject *_pPyGetValFunc; _pPyobStringIO=NULL; _pPyGetValFunc=NULL; PyObject *obFuncStringIO = NULL; int ret1 = 0; // Import cStringIO module PyObject * modStringIO = PyImport_ImportModule("cStringIO"); if(PyErr_Occurred() || modStringIO == NULL){ printf("pyParserEvaluator::Init::PyImport cStringIO failed:"); PyErr_Print(); goto PY_INIT_ERR; } // get StringIO constructor obFuncStringIO = PyObject_GetAttrString(modStringIO, "StringIO"); if(PyErr_Occurred() || obFuncStringIO == NULL){ printf("pyParserEvaluator::Init: cant find cStringIO.StringIO:"); PyErr_Print(); goto PY_INIT_ERR; } // Construct cStringIO object _pPyobStringIO = PyObject_CallObject(obFuncStringIO, NULL); if(PyErr_Occurred() || _pPyobStringIO==NULL){ printf("pyParserEvaluator::Init: cStringIO.StringIO() failed:"); PyErr_Print(); goto PY_INIT_ERR; } // get the getvalue function ptr _pPyGetValFunc = PyObject_GetAttrString(_pPyobStringIO, "getvalue"); if(PyErr_Occurred() || _pPyGetValFunc==NULL){ printf("pyParserEvaluator::Init: cant find getvalue function:"); PyErr_Print(); goto PY_INIT_ERR; } // try assigning this object to sys.stderr ret1 = PySys_SetObject("stderr", _pPyobStringIO); if(ret1 != 0){ printf("failed to assign _pPyobStringIO to stderr\n"); } else printf("assigned _pPyobStringIO to stderr\n"); PY_INIT_ERR: printf("pyParseEvaluator::pyParseEvaluator failed\n"); / **********************************************************************/ int ret = PyRun_SimpleString(strFunction); if(ret != 0){ // call getvalue() method in StringIO instance PyObject *obResult=NULL; obResult = PyObject_CallObject(_pPyGetValFunc, NULL); if(PyErr_Occurred() || obResult==NULL){ printf("getvalue() failed\n"); return -1; } else printf("PyObject_CallObject on getvalue is ok\n"); // did getvalue return a string? if(!PyString_Check(obResult)){ printf("getvalue() did not return error string\n"); return -1; } else printf("getvalue returned string object\n"); // retrieve error message string from this object char *sresult = NULL; if(NULL != (sresult = PyString_AsString(obResult))){ printf("result string was [%s]\n",sresult); } } /**********************************************************/ From mattheww at chiark.greenend.org.uk Tue Jan 8 16:22:42 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 08 Jan 2008 21:22:42 +0000 (GMT) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> <0b11ce6b-3565-41b6-8e63-17cb941b8197@i7g2000prf.googlegroups.com> <105594e7-39bd-4e6a-9d21-71ba6b1fabfa@e10g2000prf.googlegroups.com> Message-ID: Paul McGuire wrote: > While not required by any means, you will also find it handy to follow > *every* entry in the list with a comma, even the last one in the list > (this is legal Python). That is, in your example: > > foo =3D [ > 'too long', > 'too long too', > 'too long too', > 'last item', > ] > > Later on when you want to reorder the items, then you can just copy/ > paste whole lines, even if moving to or from the bottom of the list. > This is also a good argument for putting the closing ']' on its own > line, instead of on the same line as the last item. The other good reason for doing these two things is that they fit better with the line-based rules that most source code management systems use for merging. -M- From timr at probo.com Thu Jan 31 02:35:50 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 31 Jan 2008 07:35:50 GMT Subject: Telnet Program References: <777d417c-6016-4a44-8d5e-8de6bf604e9a@e6g2000prf.googlegroups.com> <87zluo77qr.fsf@merkury.smsnet.pl> <13q026bb5f1i669@corp.supernews.com> Message-ID: <1fu2q3l0aeh6uj4s6duetlak6n2jovn42p@4ax.com> Dennis Lee Bieber wrote: >On Tue, 29 Jan 2008 16:23:28 -0800 (PST), "paul.zorn at gmail.com" > declaimed the following in comp.lang.python: > >> Telnet(192.168.2.75,5000): send '\n\n' > > Should that be "\r\n" (or, if two lines is intended, "\r\n\r\n") I don't think so. The RFC quote you provided talks about the physical manifestation of CR and LF on a terminal, and says that a Telnet server must be prepared to handle various combinations, but if you think about a real Telnet session, the user is going to press CR when its through with a line. Thus, I would think he needs either \r\r or \n\n. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From castironpi at gmail.com Sat Jan 12 03:37:25 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 00:37:25 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> Message-ID: <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> On Jan 11, 8:04 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > Could you: > > > lockerA= Locker( listA, listB ) > > lockerA.op( listB.reverse ) > > lockerA.op( listA.pop ) > > > Where lockerA ops acquire the locks on all its threads? > > I don't understand that question. The main thing to understand is > that multi-threaded programming is complicated (especially if you're > after high performance), and very difficult to get right without > knowing exactly what you're doing. The generally preferred approach > in Python is to keep things simple at some performance cost. > > Your Locker approach above looks sort of reasonable if you can be > absolutely sure that nothing else can mess with listA or listB > concurrently with those locker operations. Normally you would put > listA and listB into a single object along with a lock, then do > operations on that object. > > You might check the Python Cookbook for some specific recipes and > sample code for this stuff. If you've used Java, Python's general > threading mechanisms are similar, but they are in the library rather > than built into the language (i.e. there is no "synchronized" > keyword, you have to do that locking explicitly). > > What is the actual application, if you don't mind saying? Are you > sure that you really need concurrency? I'm writing an NxN observer pattern, mostly for my own personal exploration. Two threads -might- be calling 'Disconnect' at the same time, and I can't even guarantee that the function runs properly. for emelem in [ e for e in emlist if e.func is func ]: try: emlist.remove( emelem ) except ValueError: pass From stefan.behnel-n05pAM at web.de Sun Jan 27 04:05:24 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 27 Jan 2008 10:05:24 +0100 Subject: how to make format operator % work with unicode as expected In-Reply-To: References: <13po55nc0q0s06@corp.supernews.com> Message-ID: <479C4954.6030400@web.de> Ever heard the word "PLONK"? Peter Pei harshly top-posted: > You didn't understand my question, but thanks any way. > > Yes, it is true that %s already support unicode, and I did not > contradict that. But it counts the number of bytes instead of > characters, and makes things like %-20s out of alignment. If you don't > understand my assertion, please don't argue back and I am only > interested in answers from those who are qualified. > ============================================================== > > "Steven D'Aprano" wrote [pretty qualifying response stripped] From nagle at animats.com Mon Jan 21 15:36:33 2008 From: nagle at animats.com (John Nagle) Date: Mon, 21 Jan 2008 12:36:33 -0800 Subject: Is there a portable way to tell if data is available on a pipe? In-Reply-To: <13p9le6nu1u9l4d@corp.supernews.com> References: <47941112$0$36375$742ec2ed@news.sonic.net> <13p9le6nu1u9l4d@corp.supernews.com> Message-ID: <47950101$0$36322$742ec2ed@news.sonic.net> Scott David Daniels wrote: > John Nagle wrote: >> I need some way to find out if a pipe has data available for >> a read without blocking if it does not. > ... >> I'd like to avoid having a thread to manage each pipe, but if I >> have to, so be it. > > Well, without granting your wish, put a Queue.Queue "in front" of > each pipe. The per-pipe thread ... That's what I thought. Oh, well. John Nagle From fredrik at pythonware.com Wed Jan 9 15:55:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 21:55:15 +0100 Subject: Another dumb scope question for a closure. In-Reply-To: <741fd030801091246h491ffbccp4cbbb3f947aeac63@mail.gmail.com> References: <20080109152403.433b113a@bhuda.mired.org> <741fd030801091246h491ffbccp4cbbb3f947aeac63@mail.gmail.com> Message-ID: Ben Fisher wrote: > One way to get this to work is: > > def inc(jj): > def dummy(jj = jj): > jj = jj + 1 > return jj > return dummy > > h = inc(33) > print h() > > It's not very pretty though, especially when you have many variables > you want to have in the inner scope. Default argument binding allows you to bind to an outer object rather than a name, but it doesn't help if you want to update the object: >>> def inc(jj): ... def dummy(jj = jj): ... jj = jj + 1 ... return jj ... return dummy ... >>> h = inc(33) >>> print h() 34 >>> print h() 34 >>> print h() 34 >>> print h() 34 From ivanlan9 at gmail.com Tue Jan 29 10:46:09 2008 From: ivanlan9 at gmail.com (Ivan Van Laningham) Date: Tue, 29 Jan 2008 08:46:09 -0700 Subject: Problem with Tkinter scrollbar callback In-Reply-To: References: Message-ID: Nope: 'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '300'), And even after I set it, it looks funny: 'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '1000'), And when I try it with the new repeatdelay (1000), the only thing that has changed is that it waits 1000 milliseconds before exhibiting the same uncontrolled growth as before. Metta, Ivan On Jan 25, 2008 5:49 PM, Russell E. Owen wrote: > In article , > "Ivan Van Laningham" wrote: > > > Hi All-- > > That helps. Doing a get() on the scrollbar before a set(0.0,0.0) > > returns a 4-tuple: (0.0, 0.0, 0.0, 0.0) ! I did the set(0.0,0.0) > > and now the callback gets the correct number of arguments. > > > > However, I'm still getting the weird behaviour when clicking the > > arrowheads--and the heads are all I want. They act like they've been > > set to a keybounce timeout of about a millisecond. ... The arrow > > click increments the number of cells in a table row (effectively), and > > it shoots up from 5 to 26 columns almost instantly (that's the > > internal max I set). > > Is the scroll bar's repeatinterval set to a reasonable value? > > -- Russell > > -- > 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 gregturn at mindspring.com Fri Jan 11 15:44:16 2008 From: gregturn at mindspring.com (Goldfish) Date: Fri, 11 Jan 2008 12:44:16 -0800 (PST) Subject: virtualpython / workingenv / virtualenv ... shouldn't this be part of python References: <4787981c$0$90268$14726298@news.sunsite.dk> Message-ID: On Jan 11, 11:45 am, Christian Heimes wrote: > Damjan wrote: > > My question is, shoudn't it be enough to set PYTHONPATH and everything > > automagically to work then? Is there some work done on this for python 3.0 > > or 2.6 perhaps? > > I'm working on a PEP for a per user site dir for 2.6 and 3.0 > > Christian What about security holes, like a malicious version of socket getting downloaded into a user's directory, and overriding the default, safe version? Don't forget that in your PEP. From cokofreedom at gmail.com Mon Jan 21 05:52:59 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 21 Jan 2008 02:52:59 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: On Jan 21, 11:29 am, Terry Jones wrote: > >>>>> "dg" == dg google groups writes: > > dg> It's great how many different sorts of solutions (or almost solutions) > dg> this puzzle has generated. Speedwise, for reference my solution posted > dg> above takes about 40 seconds on my 1.8GHz laptop, and the less elegant > dg> version (on my webpage linked to in the original post) takes about 15 > dg> seconds. It seems to me like surely this problem can be more > dg> efficiently solved than that? > > dg> Paul: 758 = 8+(5*((2+4)*25)) > > For this I get: > > 2 solutions to: target 758, numbers = (2, 4, 5, 8, 25) > (4, 2, 'add', 25, 'mul', 5, 'mul', 8, 'add') > (25, 4, 'mul', 5, 'sub', 8, 'mul', 2, 'sub') > > real 0m0.118s > user 0m0.074s > sys 0m0.044s > > Terry Terry, your technique is efficient and pretty readable! All that could be added now is a way to output the data in a more user-friendly print. (it currently reminds me of Lisp operands done backwards :) ) Also perhaps the creation of a random generator for the 6 numbers and the target :) I do not remember if countdown enforced that it must be possible to actually get the target, you could also get close to it. (I believe you would get different points depending on this) Will have to read up on how many large numbers you can have, as well as small. Currently I think it is you can take up to 4 large numbers, and up to 6 small numbers to a total of 6. (you must always have 6 numbers to work with) From alejandro.valdez at gmail.com Fri Jan 25 17:59:41 2008 From: alejandro.valdez at gmail.com (alejandro.valdez at gmail.com) Date: Fri, 25 Jan 2008 14:59:41 -0800 (PST) Subject: How to modify the content of an email Message-ID: <3f39a8c3-7e47-4971-84db-f26f03e0abae@d70g2000hsb.googlegroups.com> Hello, I'm trying to make a python script that take an email in (raw) text format, and add a footer to the text (or html) body of the email. I'm aware of the email and email.mime modules, but I can't figure out how to identify 'the main text (or html) content' from the email, and how to be sure that I don't incorrectly identify a txt (or html) attach as the main content of the email. By 'main text (or html) content' I mean the text (or html) that is showed by a Mail User Agent when it display the email to the recipient. Thanks in advance. From mail at timgolden.me.uk Wed Jan 23 11:42:45 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Jan 2008 16:42:45 +0000 Subject: Python printing! In-Reply-To: References: Message-ID: <47976E85.9080208@timgolden.me.uk> SMALLp wrote: > Hy. How to use printer in python. I goggled little i I found only some > win32 package which doesn't look processing for cross platform > application. (I'm using USB printer and I tried to f=open("dev/...") usb > port but i couldn't fond where printer is! You perhaps want to look at something like wxPython where someone's already done the dirty work for you: http://wiki.wxpython.org/Printing I assume other x-platform toolkits like Qt have similar facilities. Python itself is a bit lower-level than that and as far as I know no-one's put together a x-platform printing module, so you could be the first. TJG From minger at gmail.com Sat Jan 5 21:59:59 2008 From: minger at gmail.com (Ming) Date: Sat, 5 Jan 2008 18:59:59 -0800 (PST) Subject: MRO Error on Multiple Inheritance? References: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> <87prwhp4l8.fsf@benfinney.id.au> Message-ID: <9b389f23-c8c4-461e-ba09-031e12397c59@l1g2000hsa.googlegroups.com> Thanks for the all the replies. CPP2e is the Second Edition of the book "Core Python Programming." On Jan 4, 6:13 pm, Ben Finney wrote: > Ming writes: > > I'm working through Wesley Chun's CPP2e and got this error on 13.11.1, > > pp 548 where his interpreter snippet shows no problems: > > I don't know what a "CPP2e" is. Is it a book? Can you give the ISBN? > > > > > ActivePython 2.5.1.1 (ActiveState Software Inc.) b > > Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [ > > win32 > > Type "help", "copyright", "credits" or "license" f > > >>> class A(object): pass > > ... > > >>> class B(A): pass > > ... > > >>> class C(B): pass > > ... > > >>> class D(A, B): pass > > ... > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: Error when calling the metaclass bases > > Cannot create a consistent method resolution > > order (MRO) for bases A, B > > > (I submitted the problem to the author but I'm not sure I'll ever hear > > back.) I'm guessing that this kind of diamond inheritance is > > prohibited by the interpreter, and that his lack of error messages > > from the interpretation is due to actually leaving out the "class > > B(A): pass" Can someone shed light? Thanks. > > That's not an example of diamond inheritance > because classes A > and B are not distinct classes with a *common* base. Instead, they're > in a direct parent-child relationship. > > So there's no sense in defining class D to inherit from both A *and* > B. To get a descendent of both those classes, inheriting from B is > sufficient. It should rather be:: > > class D(B): pass > > -- > \ "Pinky, are you pondering what I'm pondering?" "Uh, I think so, | > `\ Brain, but we'll never get a monkey to use dental floss." -- | > _o__) _Pinky and The Brain_ | > Ben Finney From steve at REMOVE-THIS-cybersource.com.au Wed Jan 30 09:06:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 30 Jan 2008 14:06:26 -0000 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> Message-ID: <13q1132200cf537@corp.supernews.com> On Tue, 29 Jan 2008 06:48:59 -0600, Peter Schuller wrote: >> You can also put, in animal/__init__.py: >> from monkey import Monkey >> and now you can refer to it as org.lib.animal.Monkey, but keep the >> implementation of Monkey class and all related stuff into >> .../animal/monkey.py > > The problem is that we are now back to the identity problem. The class > won't actually *BE* org.lib.animal.Monkey. It what sense will it not be? Why do you care so much about where the source code for Monkey is defined? If you actually want to read the source, you might need to follow the chain from "animal", see that Monkey is imported from "monkey", and go look at that. But the rest of the time, why would you care? There is a very good reason to care *in practice*: if there is code out there that assumes that the source code from Monkey is in the file it was found in. In practice, you might be stuck needing to work around that. But that's not a good reason to care *in principle*. In principle, the actual location of the source code should be an implementation detail of which we care nothing. It's possible that the source for Monkey doesn't exist *anywhere*. It is important to deal with buggy tools. But the correct way to do so is to fix the bugs, not to throw away perfectly good abstractions. -- Steven From sergio at invalid.invalid Sun Jan 20 07:00:18 2008 From: sergio at invalid.invalid (Sergio) Date: Sun, 20 Jan 2008 13:00:18 +0100 Subject: convivenza In-Reply-To: <1ib0fd9.i462gwrkkb06N%riko@despammed.com> References: <0690b38a-d587-45f5-95e9-fc1216da4b93@l1g2000hsa.googlegroups.com> <1i9np5k.uxildouuzt58N%riko@despammed.com> <477608c1$0$17940$4fafbaef@reader1.news.tin.it> <1iaktue.wi85ml1ro93ycN%riko@despammed.com> <1ib0fd9.i462gwrkkb06N%riko@despammed.com> Message-ID: crxor 666 wrote: > >> Evidentemente equivocher? sul termine "potenza di un linguaggio", ma >> dubito che io possa scrivere un device driver in Python, >> indipendentemente dalla potenza processore o dall'esistenza di un >> compilatore Python (ho preso per esempio il Python ma potevo usare molti >> altri linguaggi). > E perch?? In particolare questa ? una questione di libreria pi? che di > linguaggio. Questo oggetto per dire ti fa scrivere driver per oggetti > USB in Python: > Per prima cosa non ? scritta in Python ma in C, ma in ogni caso mi pare una libreria per l'accesso a dispositivi USB, non una libreria per scrivere driver in Python, che sono due cose ben diverse. Il fatto che le librerie Python (come quelle di altri linguaggi) siano scritte per la maggior parte in un linguaggio diverso non dipende solo da questioni prestazionali, ma anche dal fatto che certe cose sono impossibili in Python. > Come sopra, il kernel non ? in Python. Ciao. From thermostat at gmail.com Tue Jan 15 10:50:42 2008 From: thermostat at gmail.com (Dan) Date: Tue, 15 Jan 2008 07:50:42 -0800 (PST) Subject: Interesting Thread Gotcha References: Message-ID: On Jan 15, 10:07 am, "Hendrik van Rooyen" wrote: > I thought I would share this nasty little gotcha with the group. > > Consider the following code fragment: > > > print 'starting kbd thread' > keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) > print 'starting main loop' > error = Mainloop(s,port_q,active_q_list) > > > It produces, as output, the following: > > starting kbd thread > we get here - a > > It does not print 'starting main loop', the Mainloop routine > is never executed, and no exceptions are raised. > > Here is the offending routine that seems to capture the control: > > > def kbd_driver(out_q,in_q): > """ > thread to look for keyboard input and to put it on the queue out_q > also looks for replies on in_q and prints them > """ > > kbdname = '/dev/stdin' > > kbd = open(kbdname,'r+',1) # Reading, line buffered > > unblock(kbd) # Call the magic to unblock keyboard > print 'we get here - a' > while True: > > try: > d = kbd.readline() # see if any kbd input > except: > IOError > try: > msg=in_q.get(block=False) > except Queue.Empty: > time.sleep(0.1) > continue > print msg > time.sleep(0.1) > continue > d = d.rstrip() # get rid of line feed > out_q.put([d + '\r',in_q]) # add a carriage return and return q and send > to port > > > The unblock is a routine that unblocks a port using fcntl - it > is not the problem. In case you don't believe me, here it is: > > def unblock(f): > """Given file 'f', sets its unblock flag to true.""" > > fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) > > I will post the solution tomorrow when I read my mail, > if no one has spotted it by then. > > - Hendrik >>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) Needs to be >>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) Commas are important! -Dan From MartinRinehart at gmail.com Mon Jan 7 08:25:55 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Mon, 7 Jan 2008 05:25:55 -0800 (PST) Subject: I'm searching for Python style guidelines Message-ID: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> There's a lot of dumb stuff out there. "Algorithms should be coded efficiently ..." Thanks, I'll keep that in mind. van Rossum's guidelines tend toward "pick something and stick to it" which is OK if you have enough experience to pick something Pythonic. I'm a relative newbie, not qualified to pick. Anything written somewhere that's thorough? Any code body that should serve as a reference? From alnilam at gmail.com Tue Jan 22 08:44:45 2008 From: alnilam at gmail.com (Alnilam) Date: Tue, 22 Jan 2008 05:44:45 -0800 (PST) Subject: HTML parsing confusion References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> Message-ID: <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> > Pardon me, but the standard issue Python 2.n (for n in range(5, 2, > -1)) doesn't have an xml.dom.ext ... you must have the mega-monstrous > 200-modules PyXML package installed. And you don't want the 75Kb > BeautifulSoup? I wasn't aware that I had PyXML installed, and can't find a reference to having it installed in pydocs. And that highlights the problem I have at the moment with using other modules. I move from computer to computer regularly, and while all have a recent copy of Python, each has different (or no) extra modules, and I don't always have the luxury of downloading extras. That being said, if there's a simple way of doing it with BeautifulSoup, please show me an example. Maybe I can figure out a way to carry the extra modules I need around with me. From omer at no-log.org Fri Jan 11 09:48:34 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Fri, 11 Jan 2008 15:48:34 +0100 Subject: Problem with Tkinter.PhotoImage Message-ID: <200801111548.34270.omer@no-log.org> Hi, I can only load gif images with Tkinter.PhotoImage and none with BitmapImage. I tried png, jpg, bmp and xpm and always got this errors : >>> img = Tkinter.PhotoImage(file='/home/omer/fgfs/fgsync/map.xpm') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 3206, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 3162, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't recognize data in image file "/home/omer/fgfs/fgsync/map.xpm" (or _tkinter.TclError: format error in bitmap data with BitmapImage) I also tried the imageview demo with the bitmaps in Demo/tix/bitmaps and same result (only works with tix.gif). Sounds weird that tkinter only supports a non-free format... Am I lacking some packages or config ? I'm on a debian sid and have the following python packages installed : libboost-python1.34.1 python python-central python-doc python-imaging python-imaging-tk python-minimal python-mode python-newt python-selinux python-semanage python-support python-tk python2.4 python2.4-doc python2.4-minimal thanks, -- C?dric Lucantis From lists at cheimes.de Fri Jan 25 22:54:37 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 26 Jan 2008 04:54:37 +0100 Subject: "just like Java" (was :Re: translating Python to Assembler) In-Reply-To: <7f6f3a93-4301-4a75-83d3-13d9a7c57cda@h11g2000prf.googlegroups.com> References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <4799de28$0$12358$426a74cc@news.free.fr> <7f6f3a93-4301-4a75-83d3-13d9a7c57cda@h11g2000prf.googlegroups.com> Message-ID: Paul Boddie wrote: > Well, it is important to make distinctions when people are wondering, > "If Python is 'so slow' and yet everyone tells me that the way it is > executed is 'just like Java', where does the difference in performance > come from?" Your responses seemed to focus more on waving that issue > away and leaving the whole topic in the realm of mystery. The result: > "Python is just like Java apparently, but it's slower and I don't know > why." Short answer: Python doesn't have a Just In Time (JIT) compiler. While Java's JIT optimizes the code at run time Python executes the byte code without additional optimizations. Christian From google at mrabarnett.plus.com Mon Jan 7 18:29:36 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 7 Jan 2008 15:29:36 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: On Jan 7, 5:40 pm, Martin Marcher wrote: > MartinRineh... at gmail.com wrote: > > The best thing about Python is _______. > > it's pythonicness. > I think it sounds better as "its pythonicity". From david.hotham at blueyonder.co.uk Tue Jan 29 04:02:34 2008 From: david.hotham at blueyonder.co.uk (david.hotham at blueyonder.co.uk) Date: Tue, 29 Jan 2008 01:02:34 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <92b67efe-c437-40bc-89fc-bbdd85d6e718@s19g2000prg.googlegroups.com> <816442e1-be46-4543-88dc-1b328ced7231@j20g2000hsi.googlegroups.com> Message-ID: On Jan 28, 10:11 pm, Arnaud Delobelle wrote: > My strategy was to walk through each solution "only once" (for a > certain definition of "only once :), thus I was hoping not to need a > hashtable. Yes, that seems like it should be preferable (and indeed necessary for a more general problem with larger numbers of seeds). But I wasn't smart enough to figure out how to do it ;-) > Did you pick these numbers at random? Interestingly, the solution is > unique: Not at random - this particular puzzle came out of the first post in this thread. > Mine is faster on this example, but one example is not representative! If you've found an efficient way to walk through the possible solutions only once, then - I expect that yours will be faster - and well done! I guess I should try to understand your code... > -- > Arnaud From terry at jon.es Thu Jan 24 20:00:55 2008 From: terry at jon.es (Terry Jones) Date: Fri, 25 Jan 2008 02:00:55 +0100 Subject: Text-based data inspector for Python? In-Reply-To: Your message at 00:36:16 on Friday, 25 January 2008 References: Message-ID: <18329.13511.152371.434938@jon.es> >>>>> "kj" == kj writes: kj> I've only recently started programming in Python, trying to wean kj> myself from Perl. One of the things I *really* miss from Perl is kj> a 100% mouse-free data inspector, affectionally known as the Perl kj> debugger, PerlDB, or just perl -d. With it I can examine the most kj> elaborate data structures with ease: You actually liked the perl debugger... gasp! OK, I used it too, but it left a few things to be desired (the mouse was not one). kj> And, since it's text-based, I can run it within a shell in Emacs, and kj> transfer anything I want between it and an editing buffer without even kj> a THOUGHT of touching the filthy mouse! If there's a greater joy in kj> life I have yet to find it. I use M-x pydb to debug python from inside emacs. I like it more than the straight pdb as it's a bit more like gdb. In pydb (and pdb) there's p and pp to print and pretty print a python object. They work pretty well & there's no need for the mouse. kj> NOTE: In my address everything before the first period is backwards; kj> and the last period, and everything after it, should be discarded. Nice. See http://www.fluidinfo.com/terry/2007/10/31/stagnant-email-address-arms-race/ Terry From zentraders at gmail.com Wed Jan 16 15:50:17 2008 From: zentraders at gmail.com (Zentrader) Date: Wed, 16 Jan 2008 12:50:17 -0800 (PST) Subject: error/warning color customization in interactive console? References: Message-ID: <0cb7044d-4f20-4cf8-b08c-5a99543853bd@i29g2000prf.googlegroups.com> On Jan 15, 5:44?pm, yhvh wrote: > Is it possible to output error messages in a different color? > I'm using Terminal on Gnome. For the few times that I want to do this, this simple form works with xterm. for j in range(1,10): os.system("tput setaf "+str(j)) print "test for ", j From boblatest at yahoo.com Mon Jan 14 06:33:34 2008 From: boblatest at yahoo.com (Robert Latest) Date: 14 Jan 2008 11:33:34 GMT Subject: encrypting python modules References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <5v0mquF1jhm3dU7@mid.dfncis.de> <478b4043$0$85785$e4fe514c@news.xs4all.nl> Message-ID: <5v0vkeF1kgr8fU5@mid.dfncis.de> Paul Sijben wrote: >> >> You could check the MD5 hashes of your files. > > indeed but I still need to hook into import to do that reliably, right? Depends. In a job I once had I just supplied a shell script that spat out the MD5 sums of my sources. When I got a support request I had the customer run the script and email the result to me so I could check if anything had changed. (A malicious person could of course have stored the good MD5 sums, then done his changes, and then made his request, sending me the old sums.) If your customer is cooperative and trustworthy, this is a good way to find stupid mistakes. If he ain't, drop him ;-) robert From fredrik at pythonware.com Wed Jan 9 09:57:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 15:57:51 +0100 Subject: How to get memory size/usage of python object In-Reply-To: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> References: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> Message-ID: Santiago Romero wrote: > Is there a way to check the REAL size in memory of a python object? in standard Python, without reading the interpreter source code carefully, no. to get an approximate value, create a thousand (or a million) objects and check how much the interpreter grows when you do that. From arkanes at gmail.com Fri Jan 25 22:33:22 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 25 Jan 2008 21:33:22 -0600 Subject: translating Python to Assembler In-Reply-To: <13pl92h3um45rc1@corp.supernews.com> References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pl92h3um45rc1@corp.supernews.com> Message-ID: <4866bea60801251933u38b89eedte105098ca0437e62@mail.gmail.com> On Jan 25, 2008 9:09 PM, Steven D'Aprano wrote: > On Wed, 23 Jan 2008 08:49:20 +0100, Christian Heimes wrote: > > > It's even > > possible to write code with Python assembly and compile the Python > > assembly into byte code. > > Really? How do you do that? > > I thought it might be compile(), but apparently not. > There are tools for it in the undocumented compiler.pyassem module. You have to pretty much know what you're doing already to use it - I spent a fun (but unproductive) week figuring out how to use it and generated customized bytecode for certain list comps. Malformed hand-generated bytecode stuffed into code objects is one of the few ways I know of to crash the interpreter without resorting to calling C code, too. From goldspin at gmail.com Mon Jan 7 12:27:40 2008 From: goldspin at gmail.com (Henry Chang) Date: Mon, 7 Jan 2008 09:27:40 -0800 Subject: Python's great, in a word In-Reply-To: <08f0c528-0619-432a-80a1-569cd9183e09@s12g2000prg.googlegroups.com> References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <08f0c528-0619-432a-80a1-569cd9183e09@s12g2000prg.googlegroups.com> Message-ID: What exactly does it mean "a bycycle for the mind"?? (assuming s/bycycle/bicycle) On Jan 7, 2008 5:41 AM, alain wrote: > On Jan 7, 2:09pm, MartinRineh... at gmail.com wrote: > > I'm a Java guy who's been doing Python for a month now and I'm > > convinced that > > > > 1) a multi-paradigm language is inherently better than a mono-paradigm > > language > > > > 2) Python writes like a talented figure skater skates. > > > > Would you Python old-timers try to agree on a word or two that > > completes: > > > > The best thing about Python is _______. > > > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > > "grace" but I'm not sure I've done enough to choose. > > Paraphrasing Steve Jobs but in this context: > PYTHON = a bycycle for the mind > > Best regards > > Alain > > -- > http://mail.python.org/mailman/listinfo/python-list > From robert.kern at gmail.com Fri Jan 4 17:21:21 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 04 Jan 2008 16:21:21 -0600 Subject: Fortran to Python In-Reply-To: <20080104132119.GK82115@nexus.in-nomine.org> References: <20080104132119.GK82115@nexus.in-nomine.org> Message-ID: Jeroen Ruigrok van der Werven wrote: > I got someone who asked me to make changes in an old Fortran program she is > using for some calculations. > The calculations are pretty standard aside from 2 calls to DLINCG (an IMSL > numerical_libraries function to calculate an inverse matrix). > > What I wonder about, does anybody have a Fortran to Python conversion page > somewhere to map some of the basic types to Python equivalents? > What kind of speed difference should I expect? Fairly large, if you insist on avoiding numpy. However, if your inputs are small enough, it may not matter a whole lot. You may want to use Raymond Hettinger's Matfunc.py module to implement the inverse matrices (or preferably, reformulate the problem to use a solver instead of inverting matrices explicitly): http://users.rcn.com/python/download/python.htm -- 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 pataphor at gmail.com Tue Jan 29 15:55:13 2008 From: pataphor at gmail.com (pataphor) Date: Tue, 29 Jan 2008 21:55:13 +0100 Subject: breaking out of outer loops References: Message-ID: <20080129215513.3352a90d@hyperspace> On Tue, 29 Jan 2008 11:51:04 -0800 (PST) noemailplease0001 at gmail.com wrote: > Any elegant way of breaking out of the outer for loop than below, I > seem to have come across something, but it escapes me > > for i in outerLoop: > for j in innerLoop: > if condition: > break > else: > continue > break Ha! Think outside the box to begin with ... P. def cross(args): ans = [[]] for arg in args: ans = [x+[y] for x in ans for y in arg] return ans def test(): L = [[0,1,2]]*3 for a,b,c in cross(L): print a,b,c if __name__=='__main__': test() From devnew at gmail.com Sat Jan 12 11:53:30 2008 From: devnew at gmail.com (devnew at gmail.com) Date: Sat, 12 Jan 2008 08:53:30 -0800 (PST) Subject: a problem with py2exe Message-ID: <76ba6371-abb9-4e1c-9019-711d1582adb6@s12g2000prg.googlegroups.com> I wrote an app that uses some Tix widgets and wanted to make an exe using py2exe .i used the setup script as given in http://www.py2exe.org/index.cgi/TixSetup and it copies the dlls into the dist directory created by py2exe. But then the application works only if i create a directory named 'DLLs ' and copy the tix84.dll alone into that directory. it seems silly to have tix84.dll in that dir and all other dlls in the dist directory.can anyone advise me if i can run the app with all dlls in one directory. the setup script i used is below import glob,os,sys from distutils.core import setup import py2exe def files(folder): for path in glob.glob(folder+'/*'): if os.path.isfile(path): yield path data_files=[ ('.', glob.glob(sys.prefix+'/DLLs/tix84.dll')), ('tcl/tix8.4', files(sys.prefix+'/tcl/tix8.4')), ('tcl/tix8.4/bitmaps', files(sys.prefix+'/tcl/tix8.4/bitmaps')), ('tcl/tix8.4/pref', files(sys.prefix+'/tcl/tix8.4/pref')), ] setup( script_args=['py2exe'], windows=['pyfaces.py'], data_files=data_files ) thanx in adv dn From hnessenospam at yahoo.com Tue Jan 22 13:53:27 2008 From: hnessenospam at yahoo.com (hnessenospam at yahoo.com) Date: Tue, 22 Jan 2008 10:53:27 -0800 (PST) Subject: rpy registry Message-ID: <12d6367e-4e8f-4286-8ad1-dd5f02ff0803@s12g2000prg.googlegroups.com> Howdy, I've been using rpy (1.0.1) and python (2.5.1) on my office computer with great success. When I went to put rpy on my laptop, however, I get an error trying to load rpy. "Unable to determine R version from the registry. Trying another method." followed by a few lines of the usual error message style (ending with "NameError: global name 'RuntimeExecError' is not defined." I have reinstalled R (now 2.6.1), rpy, and python without any luck (being sure to check the "include in registry" on the installation of R). Everything else I have used thus far works perfectly. Any thoughts on what might be causing problems? Thanks, -Hans From timr at probo.com Tue Jan 22 01:03:54 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 22 Jan 2008 06:03:54 GMT Subject: I don't understand what is happening in this threading code References: Message-ID: Matthew Wilson wrote: >In this code, I tried to kill my thread object by setting a variable on it >to False. > >Inside the run method of my thread object, it checks a different >variable. > >I've already rewritten this code to use semaphores, but I'm just curious >what is going on. >... >The memory address of should_keep_running seems to change when I set it >from True to False, and inside the run method, I keep checking the old >location. You misunderstand what "id(a)" does. "id" doesn't tell you anything about the name "a" or the address of "a". What it tells you is the unique identifier of the object that "a" is bound to. Any time you change "a", "id(a)" will also change. Note, for example: C:\tmp>python Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> id(True) 504958236 >>> a = True >>> id(a) 504958236 >>> id(False) 504958224 >>> a = False >>> b = False >>> id(a) 504958224 >>> id(b) 504958224 >>> 504958236 is the id of "True", not of "a". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From hniksic at xemacs.org Tue Jan 15 05:15:18 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 15 Jan 2008 11:15:18 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> <87ir1wf1wi.fsf@mulj.homelinux.net> <478c8594$0$31498$426a34cc@news.free.fr> Message-ID: <87ejcjbdjd.fsf@mulj.homelinux.net> Bruno Desthuilliers writes: > So while it's true that __init__ is the closest equivalent to what > C++ and Java (and possibly a couple "other languages") call a > constructor, it doesn't imply that you should refer to it as "the > constructor". As Neil Cerutti points out, there's in fact nothing > like a 'constructor method' in Python : there are a "__new__" > method, an "__init__" method, and "constructor expressions" which > may invoke them !-) I agree with this. The poster I was responding to called __init__ "akin to a constructor", which (to me) implied connection to other languages, not aspiration to define __init__ as THE constructor. From PatrickMinnesota at gmail.com Tue Jan 1 20:46:14 2008 From: PatrickMinnesota at gmail.com (PatrickMinnesota) Date: Tue, 1 Jan 2008 17:46:14 -0800 (PST) Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <7yBej.30029$CN4.18224@news-server.bigpond.net.au> Message-ID: <3693eb2d-9034-4f30-8d8f-84376bc6d521@e25g2000prg.googlegroups.com> On Jan 1, 7:12 pm, Neil Hodgson wrote: > Cloud computing is mostly about scalability. You do not need to be > concerned so much about low level infrastructure details such as > purchasing servers, configuring and maintaining them, hiring space in > data centres, linking up data centres, etc. It converts a lot of fixed > costs into lower recurring costs so makes it easier for a start up with > limited capital to start operating. > > There are Python libraries for accessing some of the cloud computing > services and you can also host Python application code on some services > that allow code execution. This includes services that can run arbitrary > code on virtual machines such as EC2 and more restricted computational > services like Hadoop which can run Jython. > > Neil I would say that cloud computing to an implementor or company providing cloud computing is all about scalability and stuff like S3 and EC3. There are other options for this BTW. But to the end user, it's about having your data and applications on a disk served by a network and server that is somewhere out there on the net and accessible from anywhere that you have connectivity. You might travel with a laptop, but generally, when in Hong Kong, you'll be screwed if a chunk of data is sitting on a disk inside a desktop in your home office and isn't on your laptop. With the 'cloud' concept, it wouldn't matter where you are, as long as you have a connection to the internet, you can run the apps and access the data. Issues: and yes, they are big, who has control over the data, is it being backed up and protected, and is your private data being mined without your approval. Oh, and what happens if you use Zoho's system and they go out of business? From lists at cheimes.de Sat Jan 26 17:14:23 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 26 Jan 2008 23:14:23 +0100 Subject: Python and binary compatibility In-Reply-To: References: <083456aa-1ed1-4455-a8ca-4bbaaba1ce00@i29g2000prf.googlegroups.com> Message-ID: Joshua Kugler wrote: > That page has a link to the Microsoft Visual C++ Toolkit 2003 page, which > then says it's been discontinued and to use Visual C++ 2005 Express > Edition. Sigh... You can still find some copies of the free toolkit on the internet. Christian From mmazur at gmail.com Tue Jan 8 20:16:38 2008 From: mmazur at gmail.com (Mike Mazur) Date: Wed, 9 Jan 2008 10:16:38 +0900 Subject: 'Borg' and multiple threads. In-Reply-To: <47829a95$0$26035$88260bb3@free.teranews.com> References: <47829a95$0$26035$88260bb3@free.teranews.com> Message-ID: <184110a70801081716v19d4136du24a0cb3c6951ab61@mail.gmail.com> Hi, On Jan 8, 2008 7:24 AM, Tobiah wrote: > I have a class that I call Borg that starts like this: > > class Borg(dict): > > static_state = {} > def __init__(self): > self.__dict__ = self.static_state > > > so that I can access the same data from anywhere within > any module or function just by instantiating one. > > This is used in a cherrypy web app. I got to thinking > about whether there would be confusion when multiple > users are eventually hitting the site at the same time. > Everything seems ok. Each time I hit the app and examine > the Borg() at the beginning, it seems to have no attributes. > This is what I want. > > My question is why this seems to work. I had the idea that > there was a class object that is created when the file containing > the definition is read, which actually contains the static > information that is later accessed by instances. Isn't this > done when the cherrypy app first loads, rather than each time > a browser hits the app? Otherwise, where is the individual data > stored for each of two simultaneous hits of the web page? Maybe a silly question, but are you changing the values in the dict before hitting it again and getting the empty dict? Mike From no_one at here Thu Jan 31 01:54:56 2008 From: no_one at here (Iain Mackay) Date: Thu, 31 Jan 2008 06:54:56 -0000 Subject: Sine Wave Curve Fit Question References: <7eOdnXVrB-fQFD3anZ2dnUVZ8hednZ2d@giganews.com> Message-ID: Thanks folks - I'll have a think about both of these options. From elind at spamcop.net Wed Jan 16 13:45:50 2008 From: elind at spamcop.net (Erik Lind) Date: Wed, 16 Jan 2008 13:45:50 -0500 Subject: A question about event handlers with wxPython References: <478c3bb2$0$5150$4c368faf@roadrunner.com> <2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com> <478ccbc3$0$11000$4c368faf@roadrunner.com> <478d15b4$0$18437$4c368faf@roadrunner.com> <0571a7cd-f7f6-44b4-a4d5-e427de93590a@c4g2000hsg.googlegroups.com> Message-ID: <478e5251$0$22656$4c368faf@roadrunner.com> "Mike Driscoll" wrote in message news:0571a7cd-f7f6-44b4-a4d5-e427de93590a at c4g2000hsg.googlegroups.com... > On Jan 15, 2:20 pm, "Erik Lind" wrote: >> That all looks cool. I will experiment more. I'm a bit slow on this as >> only >> two weeks old so far. >> >> Thanks for the patience > > No problem. I'm pretty slow with some toolkits too...such as > SQLAlchemy. Ugh. > > Mike BTW, The wxPython group that you mentioned....is that http://wxforum.shadonet.com/ ? From bearophileHUGS at lycos.com Sun Jan 27 05:49:25 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 27 Jan 2008 02:49:25 -0800 (PST) Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> <7xy7acsx2l.fsf@ruckus.brouhaha.com> <8ddebd68-43dc-4320-86e1-887aadff4af3@d70g2000hsb.googlegroups.com> <7xmyqs722t.fsf@ruckus.brouhaha.com> <13pnbp9l8lk1j8b@corp.supernews.com> Message-ID: <8a699886-24f7-485e-a87f-90518e9ff536@l32g2000hse.googlegroups.com> bearophile: > That version is easy to translate to other languages and you can > probably find that Psyco makes it much faster still. That operation is quite common, so it deserves a bit more work: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/543271 (I can show you the D/C code if you want it. The C code is just for testing, while the D code is usable). The final sum: the Psyco version is almost 40 times faster than the Python version, and just 2.8 times slower than the D version, and 3.4 times slower than a C version (that doesn't use too many pointer tricks). I think this is good enough. Bye, bearophile From gagsl-py2 at yahoo.com.ar Sun Jan 27 12:45:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 15:45:24 -0200 Subject: Exceptions on delete in pysqlite References: <479a7b0c$0$9119$9b4e6d93@newsspool2.arcor-online.net> Message-ID: En Fri, 25 Jan 2008 22:12:57 -0200, Wildemar Wildenburger escribi?: > Using pysqlite, I'd like to check if some dataset that I removed has > been in the database at all. Ideally I'd like pysqlite to raise an > Exception if deleting does nothing. Is that possible? I don't think so. It isn't an error, like a SELECT which returns an empty set isn't an error either. > Codewise, I'd like the following, but without me checking for and > raising the exception myself: > > cur = con.execute("""DELETE FROM SomeTable WHERE id=? AND name=?""", > (ID, NAME)) > if cur.rowcount == 0: > raise Exception Write a function to do that. -- Gabriel Genellina From arnlen at mac.com Mon Jan 28 04:43:36 2008 From: arnlen at mac.com (Jumping Arne) Date: Mon, 28 Jan 2008 10:43:36 +0100 Subject: Serving images Message-ID: <0001HW.C3C3625800224F8DB04379AF@news.individual.de> I'm no web programmer so please be kind. I'm just going to start writing a small "web app", it's very small and will only do one thing so I'm not going to use some kind of web framework. The purpose of the script is to do some custom markup of markdown formatted pages, render them and send them back to the browser. This is fairly simple and I've done similar things before but this time I'm going to add support for handling images. Before I've just placed the images on a server where the script didn't need to bother about it. Now I'm considering to let the script handle the images also, that is serve them to the browser when requested. I've tried two different approaches in other scripts: + Put them somewhere outside the scope of the script and link to them. + In my own code open the images, read the data and send it back (is there a library for this?). Before deciding on how to handle this for this script I would like to ask: how is this best done? Is there a better way? From thelanguageofcities at gmail.com Sun Jan 27 19:21:34 2008 From: thelanguageofcities at gmail.com (Max) Date: Sun, 27 Jan 2008 16:21:34 -0800 (PST) Subject: Python Genetic Algorithm References: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <2a0f06c6-4fad-4c41-ac67-ce87aaae89cd@u10g2000prn.googlegroups.com> On Jan 27, 7:01 pm, "Steven Clark" wrote: > Why not make chromosome itself a class? > > class BasicChromosome(object): > def __init__(self, data): > self.data = data > > def crossover(self): > [stuff here] > > You can subclass this as needed, altering the crossover method as necessary. > > ...perhaps I didn't understand your question. > -Steven > > On Jan 27, 2008 6:35 PM, Wildemar Wildenburger > > wrote: > > Max wrote: > > > In GAs, you operate on a Population of solutions. Each Individual from > > > the Population is a potential solution to the problem you're > > > optimizing, and Individuals have what's called a chromosome - a > > > specification of what it contains. For example, common chromosomes are > > > bit strings, lists of ints/floats, permutations...etc. I'm stuck on > > > how to implement the different chromosomes. I have a Population class, > > > which is going to contain a list of Individuals. Each individual will > > > be of a certain chromosome. I envision the chromosomes as subclasses > > > of an abstract Individual class, perhaps all in the same module. I'm > > > just having trouble envisioning how this would be coded at the > > > population level. Presumably, when a population is created, a > > > parameter to its __init__ would be the chromosome type, but I don't > > > know how to take that in Python and use it to specify a certain class. > > > I'm not sure I'm following you here. So a "chromosome" is bit of > > functionality, right? So basically it is a function. So my advice would > > be to write these functions and store it to the "indivuals"-list like so: > > > class Population(object): > > def __init__(self, *individuals): > > self.individuals = list(individuals) > > > Then you can say: > > p = Population(indiv1, indiv2, indiv3) > > for individual in p.individual: > > individual(whatever_your_problem) > > > (Don't know if this is the way GA's are supposed to work) > > > You can also create callable classes (that is, classes that implement > > the __call__ method), and use instances of these as the individuals. For > > example you can create a Permutation class that returns a permutation > > (defined in it's __init__()) when it's __call__ method is called. (Am I > > making sense?) > > > This is just generic advice, maybe this helps and maybe it doesn't at > > all. :) > > > > I'm doing something similar with my crossover methods, by specifying > > > them as functions in a module called Crossover, importing that, and > > > defining > > > > crossover_function = getattr(Crossover, "%s_crossover" % xover) > > > > Where xover is a parameter defining the type of crossover to be used. > > > I'm hoping there's some similar trick to accomplish what I want to do > > > with chromosomes - or maybe I'm going about this completely the wrong > > > way, trying to get Python to do something it's not made for. Any help/ > > > feedback would be wonderful. > > > This isn't too bad, but for such things dictionaries are your Go-To > > datatype. Just have a dictionary of xover-functions handy and call the > > thusly: > > > crossover_function = Crossover.function[xover] > > > > Thanks, > > > Max Martin > > If that helps :) > > > regards > > /W > > > -- > >http://mail.python.org/mailman/listinfo/python-list This is sort of what I'm trying to do. The super class would be Individual, and subclasses would be BitStringIndividual, IntIndividual, PermutationIndividual...etc. I just am feeling lost as to how I'm going to implement my Population class, because when a Population is initially created, it's going to fill itself up with individuals by creating them, so it's going to need to know which class it's creating instances of (which will be input when creating the population somehow; I'm just not sure how to implement this). From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 30 04:15:55 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 30 Jan 2008 10:15:55 +0100 Subject: Appropriate use of Property() In-Reply-To: <72c9d910-f19a-407d-91cf-5599fa3e73b3@h11g2000prf.googlegroups.com> References: <72c9d910-f19a-407d-91cf-5599fa3e73b3@h11g2000prf.googlegroups.com> Message-ID: <47a0403f$0$15926$426a74cc@news.free.fr> noemailplease0001 at gmail.com a ?crit : > Property() can be used to rid ourselves of the extra effort of using > two different methods (getAttrib() setAttrib()) for access of an > attribute without giving direct access to the attribute, NB : properties are for computed attributes, not to "avoid giving direct acces to (an) attribute". If what you need is really a public attribute, then use a plain attribute - knowing you'll be able to switch to a property if and when the need arises. > thus making > it more elegant. So, the outsider using my module accesses the > attribute with the syntax 'Object.attrib', but since this syntax looks > as if he is accessing the attribute (rather than through a > descrtiptor), should we subscribe to this syntax only when the > attribute is both readable and writable? i.e., > if I have an attribute which I strongly believe would always be only > readable, should I go with the old style 'Object.getAttrib()'? > Would like to know different perspectives. I just can second Gabriel on this: as long as it's not computation intensive, I use a read-only attribute (ie: fset and fdel raising AttributeError('attribute XXX is read-only')). From vimfefv at gmail.com Tue Jan 1 04:19:22 2008 From: vimfefv at gmail.com (vimfefv at gmail.com) Date: Tue, 1 Jan 2008 09:19:22 +0000 (UTC) Subject: M'I-5 Persecutio n , Capita l R adio - Chri s Tarran t Message-ID: -=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-= -=. Capital Radio - Chris Tarrant -= -=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-= Capital Radio DJs have been "in on it". from the start. One of the first things I heard in the summer of 1990 was from a Capital DJ who said,. "If he listens to Capital then he. can't be all bad" (supportive, you see. We're not bastards). Much of. what came over the radio in 1990 is now so far away the precise details have. been obliterated by time. No diary was kept of the details, and although archives if they exist may give. pointers, the ambiguity of what broadcasters said would leave that. open to re-interpretation. In spring 1994,. Chris Tarrant on his Capital morning show made an aside to someone else in the studio, about a person. he didn't identify. He said, "You know this. bloke? He says we're trying to kill him. We should be done for attempted. manslaughter". That mirrored something I had said a day. or two before. What Tarrant said was understood by the staff member in the. studio he was saying it to; they said, "Oh no, don't say that" to Tarrant. If any archives. exist of the morning show (probably unlikely) then it. could be found there; what he said was so out of context that he would be very hard. put to find an explanation. A couple of days. later, someone at the site where I was working repeated the remark although in a. different way; they said there had been people in a computer room when automatic fire extinguishers. went off and those people were. "thinking of suing for attempted manslaughter". Finally, this isn't confined. to the established radio stations. In 1990 after I. had listened to a pirate radio station in South London for about half an. hour, there was an audible phone call in the background, followed by total. silence for a few moments, then shrieks of laughter. "So what are we supposed to say now? Deadly torture? He's. going to talk to us now, isn't he?", which meant that they could hear what I would say in my. room. 5203 From steve at REMOVE-THIS-cybersource.com.au Tue Jan 1 17:01:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 01 Jan 2008 22:01:55 -0000 Subject: ElementTree should parse string and file in the same way References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> <5tuqfaF1f8u9tU1@mid.uni-berlin.de> <13nkkh6almg8o6b@corp.supernews.com> Message-ID: <13nle2jp4lh1g9a@corp.supernews.com> On Tue, 01 Jan 2008 12:59:44 -0700, Steven Bethard wrote: > Steven D'Aprano wrote: >> On Tue, 01 Jan 2008 13:36:57 +0100, Diez B. Roggisch wrote: >> >>> And codemonkeys know that in python >>> >>> doc = et.parse(StringIO(string)) >>> >>> is just one import away >> >> Yes, but to play devil's advocate for a moment, >> >> doc = et.parse(string_or_file) >> >> would be even simpler. > > I assume the problem with this is that it would be ambiguous. You can > already use either a string or a file with ``et.parse``. A string is > interpreted as a file name, while a file object is used directly. Ah! I wasn't aware that parse() operated on either an open file object or a string file name. That's an excellent reason for not treating strings the same as files in ElementTree. > How would you differentiate between a string that's supposed to be a > file name, and a string that's supposed to be XML? Well, naturally I wouldn't. I *could*, if I assumed that a multi-line string that started with "<" was XML, and a single-line string with the path separator character or ending in ".xml" was a file name, but that sort of Do What I Mean coding is foolish in a library function that can't afford to occasionally Do The Wrong Thing. -- Steven From pavlovevidence at gmail.com Mon Jan 7 18:27:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 7 Jan 2008 15:27:39 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: On Jan 7, 8:09 am, MartinRineh... at gmail.com wrote: > I'm a Java guy who's been doing Python for a month now and I'm > convinced that > > 1) a multi-paradigm language is inherently better than a mono-paradigm > language > > 2) Python writes like a talented figure skater skates. > > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is _______. > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > "grace" but I'm not sure I've done enough to choose. "it doesn't suck". (Really. All programming languages have good, useful features. Even Perl. Python is unique in having no very bad ones.) Carl Banks From gagsl-py2 at yahoo.com.ar Fri Jan 25 15:00:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 Jan 2008 18:00:02 -0200 Subject: Increment Variable Name References: Message-ID: En Wed, 23 Jan 2008 23:09:36 -0200, David Brochu escribi?: > Basically what I am trying to do is pass each value from a list to > the following line of code (where XXX is where I need to pass each > value of the list > > tests = easygui.multchoicebox(message="Pick the test(s) you would > like to run from the list below." > , title="Validation Tests" > ,choices=[XXX]) > > If i were to manually pass values to this line it would appear like : > tests = easygui.multchoicebox(message="Pick the test(s) you would > like to run from the list below." > , title="Validation Tests" > ,choices=["Test 1","Test 2", "Test 3"]) > > When I actually pass the list to the line of code, it works, however > it doesn't really split the list by element. The desired output of > this line of code would be a GUi that included a list consisting of > each element from the passed list. Right now I can only get it to > consist of a single element that contains every part of the list. You should have posted this in the first place! No answer to your previous specific question would have helped you in this case. See http://catb.org/~esr/faqs/smart-questions.html#goal Ok, you have a list containing all the possible choices. It doesn't matter how did you build that list. Then, just pass *that* *list* as the choices parameter to the function. By example: all_tests = ["Test 1","Test 2", "Test 3"] tests = easygui.multchoicebox(message="Pick the test(s) you would like to run from the list below.", title="Validation Tests", choices=all_tests) (If you use [items] you are building a new list with a single element which itself is the list of choices, and that's not what multchoicebox expects). -- Gabriel Genellina From deets at nospam.web.de Wed Jan 9 17:59:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Jan 2008 23:59:10 +0100 Subject: for loop without variable In-Reply-To: References: Message-ID: <5ul1tuF1i0qr1U1@mid.uni-berlin.de> erik gartz schrieb: > Hi. I'd like to be able to write a loop such as: > for i in range(10): > pass > but without the i variable. The reason for this is I'm using pylint > and it complains about the unused variable i. I can achieve the above > with more lines of code like: > i = 0 > while (i != 10): > i += 1 > Is there a concise way to accomplish this without adding extra lines > of codes? Thanks in advance for your help. The underscore is used as "discarded" identifier. So maybe for _ in xrange(10): ... works. Diez From paul.hankin at gmail.com Wed Jan 9 04:21:25 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 9 Jan 2008 01:21:25 -0800 (PST) Subject: Open a List of Files References: <874pdomrrd.fsf@mulj.homelinux.net> Message-ID: <4f67337a-14ea-4552-8a5a-6de9703e58ff@d70g2000hsb.googlegroups.com> On Jan 9, 2:41?am, Tim Chase wrote: > > I decided that I was just trying to be "too smooth by 1/2" so I fell back to > > > messages = open(os.path.join(host_path,'messages.txt'), 'wb') > > deliveries = open(os.path.join(host_path,'deliveries.txt'), 'wb') > > actions = open(os.path.join(host_path,'actions.txt'), 'wb') > > parts = open(os.path.join(host_path,'parts.txt'), 'wb') > > recipients = open(os.path.join(host_path,'recipients.txt'), 'wb') > > viruses = open(os.path.join(host_path,'viruses.txt'), 'wb') > > esp_scores = open(os.path.join(host_path,'esp_scores.txt'), 'wb') > > Another way to write this which reduces some of the code would be > > ? filenames = ['messages', 'deliveries', 'actions', 'parts', > ? ? 'recipients', 'viruses', 'esp_scores'] > > ? (messages, deliveries, actions, parts, > ? ? recipients, viruses, esp_scores) = [ > ? ? open(os.path.join(host_path, '%s.txt' % fn), 'wb') > ? ? for fn in filenames > ? ? ] > > It becomes even more clear if you make an intermediate "opener" > function such as > > ? binwriter = lambda fname: open( > ? ? ? os.path.join(host_path, '%s.txt' % fname), 'wb') > > ? (messages, deliveries, actions, parts, > ? ? recipients, viruses, esp_scores) = [ > ? ? binwriter(fn) for fn in filenames] This can be more cleanly written using locals() for fn in filenames: locals()[fn] = open(os.path.join(host_path, fname + '.txt', 'wb') -- Paul Hankin From hyperneato at gmail.com Fri Jan 4 05:40:08 2008 From: hyperneato at gmail.com (stuntgoat) Date: Fri, 4 Jan 2008 02:40:08 -0800 (PST) Subject: import zlib in 2.5 fails References: Message-ID: <1b0cd0c2-8e13-46df-8463-ac452f170940@t1g2000pra.googlegroups.com> Modules/main.c:186: warning: function declaration isn't a prototype /home/name/Desktop/webdl/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ ffi64.c:45: warning: function declaration isn't a prototype /home/name/Desktop/webdl/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ ffi64.c:342: warning: function declaration isn't a prototype /usr/bin/ld: /usr/local/lib/libz.a(adler32.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC /usr/local/lib/libz.a: could not read symbols: Bad value collect2: ld returned 1 exit status this error occurred at one point during a compilation of Python 2.5. It seems related to my inability to import zlib now. On Jan 4, 10:19 am, stuntgoat wrote: > import zlib works in Python 2.4 (debian etch AMD64 - default python > version for that distro) > > I built python 2.5 from source; zlib is not importable. > > I am trying to compile MySQLdb. > > any clues about how to get zlib able to be imported in 2.5? > > -sg From arkanes at gmail.com Mon Jan 14 13:49:57 2008 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 14 Jan 2008 12:49:57 -0600 Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) In-Reply-To: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> Message-ID: <4866bea60801141049xcaab6d7vac5b42d75c141a6e@mail.gmail.com> On Jan 14, 2008 12:39 PM, aspineux wrote: > > This append in both case > > dict(a=1).get('a', f()) > dict(a=1).setdefault('a', f()) > > This should be nice if f() was called only if required. > Think about the change to Python semantics that would be required for this to be true, and then use collections.defaultdict instead. From peng.kyo at gmail.com Tue Jan 15 22:09:09 2008 From: peng.kyo at gmail.com (J. Peng) Date: Wed, 16 Jan 2008 11:09:09 +0800 Subject: no pass-values calling? Message-ID: <18c1e5f20801151909u4cdd227ah685741ea21734491@mail.gmail.com> Hello, I saw this statement in Core Python Programming book, All arguments of function calls are made by reference, meaning that any changes to these parameters within the function affect the original objects in the calling function. Does this mean there is not pass-values calling to a function in python? only pass-reference calling? Thanks! From asmodai at in-nomine.org Thu Jan 10 05:56:58 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 10 Jan 2008 11:56:58 +0100 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <20080110105658.GW75977@nexus.in-nomine.org> -On [20080110 11:46], A.T.Hofkamp (hat at se-162.se.wtb.tue.nl) wrote: >In my experience however, differences in CPU execution time are usually >meaningless compared to differences in development time. I have to disagree with you to a point. Yes, maintenance of code is important, no denying that. However, if I can calculate N variations of a certain material's properties in an hour and using Python will cut that in half, the number of calculated variations per hour, I will be concerned. This is especially so for people designing, say, optics. If you look at the amount of optimizing designs and calculating the resulting properties and doing this for X iterations in a day it becomes quite painfully obvious that raw CPU execution time *does* matter. 't All varies with what you want, of course... -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ When you have eliminated the impossible, whatever remains, however improbable, must be the truth... From grante at visi.com Sun Jan 20 10:16:53 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 20 Jan 2008 15:16:53 -0000 Subject: Memory errors with imaplib References: <6012daff-0fd3-4835-a9ca-c18d2a2ac53c@v29g2000hsf.googlegroups.com> Message-ID: <13p6pf5he8am89e@corp.supernews.com> On 2008-01-20, Fredrik Lundh wrote: > looks like a known bug in imaplib: > > http://bugs.python.org/issue1389051 > > "In a worst case scenario, you'll need some 13 gigabytes of > virtual memory to read a 15 megabyte message..." The problem and the one-line soulution have been known for over two years and it's still an open bug? -- Grant Edwards grante Yow! Yow! Is my fallout at shelter termite proof? visi.com From joejacob21 at gmail.com Wed Jan 23 06:31:20 2008 From: joejacob21 at gmail.com (joe jacob) Date: Wed, 23 Jan 2008 03:31:20 -0800 (PST) Subject: wxpython Message-ID: <77cc3d61-5dd0-4878-b436-b6d07e40de4d@i7g2000prf.googlegroups.com> I am trying to open a file containing non displayable characters like contents an exe file. The is is with the below mentioned code: self.text_ctrl_1.SetValue(file_content) If the file_content contains non displayable characters I am getting an error like this: Traceback (most recent call last): File "C:\Documents and Settings\joe_jacob\Desktop\notepad.py", line 102, in open_file self.text_ctrl_1.SetValue(file_content) File "D:\softwares\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx \_controls.py", line 1708, in SetValue return _controls_.TextCtrl_SetValue(*args, **kwargs) File "D:\softwares\Python25\lib\encodings\cp1252.py", line 15, in decode return codecs.charmap_decode(input,errors,decoding_table) UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to I am trying to create an encryption program so if I open any file even if it is an exe file it should display in text ctrl. What is this problem with this ? How can I rectify this? From asmodai at in-nomine.org Fri Jan 4 09:47:12 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jan 2008 15:47:12 +0100 Subject: Fortran to Python In-Reply-To: <20080104132119.GK82115@nexus.in-nomine.org> References: <20080104132119.GK82115@nexus.in-nomine.org> Message-ID: <20080104144712.GL82115@nexus.in-nomine.org> -On [20080104 14:22], Jeroen Ruigrok van der Werven (asmodai at in-nomine.org) wrote: >What I wonder about, does anybody have a Fortran to Python conversion page >somewhere to map some of the basic types to Python equivalents? Just to share my own ideas: Seems COMPLEX*16/complex*16 ~= complex REAL*8/real*8 ~= float INTEGER/integer ~= int/long -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Necessity is the mother of invention... From eproust at gmail.com Mon Jan 21 04:12:59 2008 From: eproust at gmail.com (pythonewbie) Date: Mon, 21 Jan 2008 01:12:59 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <13p8803epubo92b@corp.supernews.com> Message-ID: <14dc1431-909b-4702-a695-846a683ef345@q77g2000hsh.googlegroups.com> On 21 jan, 09:53, pythonewbie wrote: > On 21 jan, 05:31, Dennis Lee Bieber wrote: > > > > > On Sun, 20 Jan 2008 13:58:13 -0800 (PST), pythonewbie > > declaimed the following in comp.lang.python: > > > > I just would like to know if I would ALWAYS find the install directory > > > in sys.path[6] and site-packages directory in sys.path[7] on any Win32 > > > platform and sys.path[2] and site-packages directory in sys.path[6] on > > > any Linux platform. > > > Unlikely... > > > >>> sys.path[6] > > > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg'>>> sys.path[2] > > > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg'>>> sys.path > > > ['', 'E:\\Python24\\lib\\site-packages\\pyopengl-3.0.0a5-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg', > > 'E:\\Python24\\lib\\site-packages\\sqlobject-0.7.6-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\celementtree-1.0.5_20051216-py2.4-win32.egg', > > 'E:\\Python24\\lib\\site-packages\\configobj-4.4.0-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\ruledispatch-0.5a0.dev_r2306-py2.4-win32.egg', > > 'E:\\Python24\\lib\\site-packages\\formencode-0.7.1-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\pastescript-1.3.4-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\elementtree-1.2.6_20050316-py2.4-win32.egg', > > 'E:\\Python24\\lib\\site-packages\\simplejson-1.7.1-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\cherrypy-2.2.1-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\turbocheetah-0.9.5-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\turbojson-1.0-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\pyprotocols-1.0a0dev_r2302-py2.4-win32.egg', > > 'E:\\Python24\\lib\\site-packages\\pastedeploy-1.3-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\paste-1.3-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\cheetah-2.0rc8-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\setuptools-0.6c6-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\turbogears-1.0.3.2-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\turbokid-1.0.2-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\kid-0.9.6-py2.4.egg', > > 'e:\\python24\\lib\\site-packages\\scipy', > > 'C:\\WINDOWS\\system32\\python24.zip', 'e:\\UserData\\Dennis Lee > > Bieber\\My Documents', 'E:\\Python24\\DLLs', 'E:\\Python24\\lib', > > 'E:\\Python24\\lib\\plat-win', 'E:\\Python24\\lib\\lib-tk', > > 'E:\\Python24\\Lib\\site-packages\\pythonwin', 'E:\\Python24', > > 'E:\\Python24\\lib\\site-packages', > > 'E:\\Python24\\lib\\site-packages\\Numeric', > > 'E:\\Python24\\lib\\site-packages\\PIL', > > 'E:\\Python24\\lib\\site-packages\\win32', > > 'E:\\Python24\\lib\\site-packages\\win32\\lib', > > 'E:\\Python24\\lib\\site-packages\\wx-2.8-msw-unicode'] > > > >>> os.environ["PATH"] > > > 'E:\\Python24\\;C:\\GNAT\\bin;C:\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\PROGRA~1\\MySQL\\MySQL > > Server 5.0\\bin;C:\\Program Files\\SciTE;C:\\Program > > Files\\Java\\jre1.6.0_03\\bin;C:\\Program > > Files\\Java\\jdk1.6.0_03\\bin;C:\\Program Files\\Common > > Files\\Adobe\\AGL;C:\\MSSQL7\\BINN;c:\\PROGRA~1\\sdb\\programs\\bin;c:\\PROGRA~1\\sdb\\programs\\pgm;C:\\Tcl\\bin;C:\\Program > > Files\\Common Files\\Roxio Shared\\DLLShared\\;C:\\Program Files\\Common > > Files\\Roxio Shared\\9.0\\DLLShared\\;e:\\Python24\\Scripts;c:\\Regina' > > > -- > > 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/ > > OK Denis Lee, I see now. I appreciate your clear and simple to > understand reply. > > All posts on this topic, have been appreciated a lot... Thanks to all > helpers. > > Cheers Hi John Machin, Your code : >>> import sys, re >>> for p in sys.path: ... m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p) ... if m: ... print m.group(1, 0) ... break ... else: ... raise Exception('Huh?') ... Does not work on my PC : Traceback (most recent call last): File "/home/eproust/john-machin_recup_rep_site-packages.py", line 9, in raise Exception('Huh?') Exception: Huh? Even if I remove all code below the else: part of the script... - Thanks for your advice to read : http://www.python.org/community/sigs/current/distutils-sig/ Cheers From http Wed Jan 23 14:05:01 2008 From: http (Paul Rubin) Date: 23 Jan 2008 11:05:01 -0800 Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> Message-ID: <7x8x2g8isi.fsf@ruckus.brouhaha.com> ryan k writes: > Hello. I have a string like 'LNAME > PASTA ZONE'. I want to create a list of those words and > basically replace all the whitespace between them with one space so i > could just do lala.split(). Thank you! import re s = 'LNAME PASTA ZONE' re.split('\s+', s) From nagle at animats.com Thu Jan 24 19:13:30 2008 From: nagle at animats.com (John Nagle) Date: Thu, 24 Jan 2008 16:13:30 -0800 Subject: Sorting Large File (Code/Performance) In-Reply-To: References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> Message-ID: <4799285d$0$36346$742ec2ed@news.sonic.net> Ira.Kovac at gmail.com wrote: > Thanks to all who replied. It's very appreciated. > > Yes, I had to double check line counts and the number of lines is ~16 > million (instead of stated 1.6B). OK, that's not bad at all. You have a few options: - Get enough memory to do the sort with an in-memory sort, like UNIX "sort" or Python's "sort" function. - Thrash; in-memory sorts do very badly with virtual memory, but eventually they finish. Might take many hours. - Get a serious disk-to-disk sort program. (See "http://www.ordinal.com/". There's a free 30-day trial. It can probably sort your data in about a minute.) - Load the data into a database like MySQL and let it do the work. This is slow if done wrong, but OK if done right. - Write a distribution sort yourself. Fan out the incoming file into one file for each first letter, sort each subfile, merge the results. With DRAM at $64 for 4GB, I'd suggest just getting more memory and using a standard in-memory sort. John Nagle From aspineux at gmail.com Sat Jan 5 05:01:18 2008 From: aspineux at gmail.com (aspineux) Date: Sat, 5 Jan 2008 02:01:18 -0800 (PST) Subject: How a smart editor could make "Postfix type declarations PEP3117" in Python3000 more readable References: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> Message-ID: <27358cb1-7e7d-42c2-91d3-00e003ecb6d8@z17g2000hsg.googlegroups.com> On Jan 5, 4:39 am, aspineux wrote: > Hi > > I read the PEP 3117 about the new "Postfix type declarations" in > Python3000. > THIS PEP as been REJECTED ! But ... > > The notation in the PEP is very ugly ! This make python code more > difficult to read! > > Anyway when I switched to python (from C, C++, ..), I suffered a lot > of the > untyped python variables. And I think this is a good idea to include > typing in python. > > Then I get this idea: The editor could hide the typing notation, just > displaying hint ! > It could also auto-complete the type of any variable having already a > type in > the current function, and underline untyped variable or variable > having multiple type inside the function. > > Just an idea ! And to go further the editor could do all the job of type checking, using formatted comment to specify type, like in some existing embedded documentation. But then we are losing the brevity provided by the PEP. Pydev (and certainly other) already does some interesting work to find mistyped (typed like in "I made a typo") variable name. TO ALL "NEW IDEA" RESISTANT : Hopefully, in 1990 nobody said to someone that inventing a language where bloc definition is based on indentation was a s.... Regards > > Alain Spineux > > Happy new year. From mattheww at chiark.greenend.org.uk Tue Jan 8 16:19:10 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 08 Jan 2008 21:19:10 +0000 (GMT) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> <1d895d6d-a649-439e-8223-0ae7d3a4eb40@l6g2000prm.googlegroups.com> <4fb7129f-3887-4e3b-a827-3255344047f3@c23g2000hsa.googlegroups.com> Message-ID: wrote: > A quick look (thorough analysis still required) shows that OLPC and > PyPy are, indeed, extensive standards. > one-laptop-per-child.html (olpc),74.3,,http://wiki.laptop.org/go/Python_Style_Guide I think that's mostly PEP 8, with some notes added. -M- From lasses_weil at klapptsowieso.net Tue Jan 22 15:48:01 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Tue, 22 Jan 2008 21:48:01 +0100 Subject: question In-Reply-To: References: Message-ID: <47965686$0$5955$9b4e6d93@newsspool3.arcor-online.net> Hi there :) A little tip upfront: In the future you might want to come up with a more descriptive subject line. This will help readers decide early if they can possibly help or not. jyoung79 at kc.rr.com wrote: > def albumInfo(theBand): > def Rush(): > return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > > def Enchant(): > return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > > ... > Yuck! ;) > The only problem with the code above though is that I don't know how to call it, especially since if the user is entering a string, how would I convert that string into a function name? While this is relatively easy, it is *waaayyy* too complicated an approach here, because . . . > def albumInfo(theBand): > if theBand == 'Rush': > return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > elif theBand == 'Enchant': > return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > ... > . . . this is a lot more fitting for this problem. You could also have used a dictionary here, but the above is better if you have a lot of lists, because only the one you use is created (I think . . .). You might also want to consider preparing a textfile and reading it into a list (via lines = open("somefile.txt").readlines()) and then work with that so you don't have to hardcode it into the program. This however is somewhat advanced (if you're just starting out), so don't sweat it. > I'm not familiar with how 'classes' work yet (still reading through my 'Core Python' book) but was curious if using a 'class' would be better suited for something like this? Since the user could possibly choose from 100 or more choices, I'd like to come up with something that's efficient as well as easy to read in the code. If anyone has time I'd love to hear your thoughts. > Think of classes as "models of things and their behavior" (like an animal, a car or a robot). What you want is a simple "request->answer" style functionality, hence a function. Hope that helps. Happy coding :) /W From vivfvfifi at gmail.com Tue Jan 1 06:41:56 2008 From: vivfvfifi at gmail.com (vivfvfifi at gmail.com) Date: Tue, 1 Jan 2008 11:41:56 +0000 (UTC) Subject: M,I-5,Persecu tion w ho kn ows abou t it? Message-ID: -=-=-=-=-=-=-=-=-=-=-=-=- -= who knows about it?. =- -=-=-=-=-=-=-=-=-=-=-=-=- Many people know, both in the establishment and media, and. among the general. public. Despite an absence of its target from the UK for more than two years, the echoes of paranoia can still. be heard loud and clear from across the water. When it started in 1990, the only. people who knew were those in BBC television who were. spying on my home, and a few radio broadcasters. There were a few cases of public harassment, but. very little compared to the situation that developed a couple of years. later. The list today includes BBC. TV staff (newsreaders such as Martyn Lewis, Michael Buerk, Nicholas. Witchell), people from radio stations such as Chris Tarrant of Capital and. Radio 1 DJs, people in the print media, but also many. people in the general public. All united in a conspiracy which breaks the laws which the UK does have regarding. harassment, and all completely uncaring for any semblance. of decency or elementary respect for. individual rights. The British police (obviously) do know the nature of the. harassment and in all probability the identity of those behind. it. Some time ago I made a complaint to my local police station in London, without positive. result. The UK police are failing in their. duty to see the law enforced in not checking the. abuse. 2773 From DustanGroups at gmail.com Wed Jan 30 18:08:52 2008 From: DustanGroups at gmail.com (Dustan) Date: Wed, 30 Jan 2008 15:08:52 -0800 (PST) Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> Message-ID: <6047713b-c963-404d-af92-7e31053a06c8@v46g2000hsv.googlegroups.com> On Jan 30, 4:47 pm, FireNWater wrote: > I'm curious why the different outputs of this code. If I make the > dictionary with letters as the keys, they are not listed in the > dictionary in alphabetical order, but if I use the integers then the > keys are in numerical order. > > I know that the order of the keys is not important in a dictionary, > but I was just curious about what causes the differences. Thanks!! > > list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] > list2 = [1,2,3,4,5,6,7,8] > > Dictionary = dict(zip(list1, list2)) > print Dictionary > > Dictionary1 = dict(zip(list2, list1)) > print Dictionary1 The underlying order is a result, in part, of the key's hash codes*. Integers are hash coded by their integer values, therefore, they appear in numeric order. Strings, however, use an algorithm that ensures as unique hash codes as possible. Notice the difference: >>> map(hash, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 1, 2, 3, 4, 5, 6, 7, 8]) [-468864544, -340864157, -212863774, -84863387, 43136996, 171137383, 299137766, 427138153, 1, 2, 3, 4, 5, 6, 7, 8] * emphasis on the "in part". Other factors include the amount of memory space available, order added, the current size of the underlying hash table, etc. From deets at nospam.web.de Wed Jan 16 08:54:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jan 2008 14:54:56 +0100 Subject: Unknown cause to error (new to python) References: Message-ID: <5v6glgF1kpndqU1@mid.uni-berlin.de> Brandon Perry wrote: > Hi, I am having to compile a standalone version of python for the web > server I use (they don't allow access to /usr/bin/python). I posted > earlier about a GLib error, but I have fixed that now. I am very close > to getting this to work, but I am getting some weird errors. > > File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", > line 41, in ? > File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", > line 71, in ? File > "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", > line 4, in ? File > "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", > line 4, in ? File > "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", line > 15, in ? > > I am using 2.2 for compatibility purposes. I don't see no error - is that all stacktrace you get? Diez From robert.kern at gmail.com Sat Jan 12 06:39:17 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 12 Jan 2008 05:39:17 -0600 Subject: Is unicode.lower() locale-independent? In-Reply-To: References: Message-ID: John Machin wrote: > On Jan 12, 8:25 pm, Robert Kern wrote: >> The section on "String Methods"[1] in the Python documentation states that for >> the case conversion methods like str.lower(), "For 8-bit strings, this method is >> locale-dependent." Is there a guarantee that unicode.lower() is >> locale-*in*dependent? >> >> The section on "Case Conversion" in PEP 100 suggests this, but the code itself >> looks like to may call the C function towlower() if it is available. On OS X >> Leopard, the manpage for towlower(3) states that it "uses the current locale" >> though it doesn't say exactly *how* it uses it. >> >> This is the bug I'm trying to fix: >> >> http://scipy.org/scipy/numpy/ticket/643 >> http://dev.laptop.org/ticket/5559 >> >> [1]http://docs.python.org/lib/string-methods.html >> [2]http://www.python.org/dev/peps/pep-0100/ > > The Unicode standard says that case mappings are language-dependent. > It gives the example of the Turkish dotted capital letter I and > dotless small letter i that "caused" the numpy problem. See > http://www.unicode.org/versions/Unicode4.0.0/ch05.pdf#G21180 That doesn't determine the behavior of unicode.lower(), I don't think. That specifies semantics for when one is dealing with a given language in the abstract. That doesn't specify concrete behavior with respect to a given locale setting on a real computer. For example, my strings 'VOID', 'INT', etc. are all English, and I want English case behavior. The language of the data and the transformations I want to apply to the data is English even though the user may have set the locale to something else. > Here is what the Python 2.5.1 unicode implementation does in an > English-language locale: > >>>> import unicodedata as ucd >>>> eyes = u"Ii\u0130\u0131" >>>> for eye in eyes: > ... print repr(eye), ucd.name(eye) > ... > u'I' LATIN CAPITAL LETTER I > u'i' LATIN SMALL LETTER I > u'\u0130' LATIN CAPITAL LETTER I WITH DOT ABOVE > u'\u0131' LATIN SMALL LETTER DOTLESS I >>>> for eye in eyes: > ... print "%r %r %r %r" % (eye, eye.upper(), eye.lower(), > eye.capitalize()) > ... > u'I' u'I' u'i' u'I' > u'i' u'I' u'i' u'I' > u'\u0130' u'\u0130' u'i' u'\u0130' > u'\u0131' u'I' u'\u0131' u'I' > > The conversions for I and i are not correct for a Turkish locale. > > I don't know how to repeat the above in a Turkish locale. If you have the correct locale data in your operating system, this should be sufficient, I believe: $ LANG=tr_TR python Python 2.4.3 (#1, Mar 14 2007, 19:01:42) [GCC 4.1.1 20070105 (Red Hat 4.1.1-52)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_ALL, '') 'tr_TR' >>> 'VOID'.lower() 'vo\xfdd' >>> 'VOID'.lower().decode('iso-8859-9') u'vo\u0131d' >>> u'VOID'.lower() u'void' >>> > However it appears from your bug ticket that you have a much narrower > problem (case-shifting a small known list of English words like VOID) > and can work around it by writing your own locale-independent casing > functions. Do you still need to find out whether Python unicode > casings are locale-dependent? I would still like to know. There are other places where .lower() is used in numpy, not to mention the rest of my code. -- 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 paddy3118 at googlemail.com Tue Jan 22 00:15:06 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 21 Jan 2008 21:15:06 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> Message-ID: On Jan 22, 3:20 am, Alan Isaac wrote: > I want to generate sequential pairs from a list. <> > What is the fastest way? (Ignore the import time.) 1) How fast is the method you have? 2) How much faster does it need to be for your application? 3) Are their any other bottlenecks in your application? 4) Is this the routine whose smallest % speed-up would give the largest overall speed up of your application? - Paddy. From sjmachin at lexicon.net Thu Jan 31 17:11:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 31 Jan 2008 14:11:27 -0800 (PST) Subject: pyExcelerator - Can I read and modify an existing Excel-WorkBook? References: Message-ID: On Feb 1, 4:37 am, Stephen Brown wrote: > Yes indeed, pyExcelerator does support reading data from excel > spreadsheets. I presume this is an orphaned and belated reply to the 3-message thread in July 2006 with the same subject. > An example of how to do this is included in the file > xls2csv-gerry.py under the directory ... pyExcelerator/examples/tools > Syntax is pretty straight forward. extract_all = parse_xls(filename, CP > = None) where CP is the encoding format used within tht file. The OP was aware of pyExcelerator's parse_xls, but required formatting information: """ To me it seems, that pyExcelerator does not support the reading for modification of an Excel-sheet. It allows only the "parse_xls" but I would like to keep the "formatting" in the template. """ > Uses > same codes that xlrd uses, ie 'cp437' = US English. An interesting way of describing it. It is *not* restricted to being a "codepage". The arg can be any Python-supported encoding that can be passed to str.decode to convert internal 8-bit strings to unicode. > > All you need is the "parse_xls" command and simply let it iterate > through your spreadsheet file. [snip] Current situation: I am (sporadically) maintaining xlwt, a fork of pyExcelerator which among other things fixes bugs and enables use with Python 2.3. It is available from https://secure.simplistix.co.uk/svn/xlwt/trunk xlwt.parse_xls is the same as pyExcelerator.parse_xls and thus has the same deficiencies e.g. it reports a date as a floating-point number of days since some more-or-less-fixed epoch and provides no indication that the item should be interpreted as a date. It will not be maintained, and is severely deprecated -- use xlrd instead. HTH, John From fredrik at pythonware.com Wed Jan 9 08:03:05 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 14:03:05 +0100 Subject: PIL question In-Reply-To: References: Message-ID: Alex K wrote: > Would anyone know how to generate thumbnails with rounded corners > using PIL? I'm also considering imagemagick if PIL turns out not to be > appropriate for the task. create a mask image with round corners (either with your favourite image editor or using ImageDraw/aggdraw or some such). in your program, load the mask image, and cut out the four corners using "crop". then, for each image, create a thumbnail as usual, and use the corner masks on the corners of the thumbnail. - if you want transparent corners, create an "L" image with the same size as the thumbnail, use "paste" to add the corner masks in that image, and then use "putalpha" to attach the alpha layer it to the thumbnail. - if you want solid corners, use "paste" on the thumbnail instead, using a solid color as the source. From sjmachin at lexicon.net Mon Jan 21 16:47:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jan 2008 13:47:06 -0800 (PST) Subject: index of min element of sequence References: <7xfxwrt1dx.fsf@ruckus.brouhaha.com> <6243b2e3-e2eb-41fb-bb7c-88b40ffcef60@e25g2000prg.googlegroups.com> <7xabmyyk29.fsf@ruckus.brouhaha.com> Message-ID: On Jan 22, 7:56 am, Paul Rubin wrote: > John Machin writes: > > s/[1]/[0]/ or more generally: > > Oops, got two spellings confused. Originally was going to use > > from itertools import count, izip > min(izip(seq, count()))[1] > > but did it with enumerate instead. I don't know which is actually > faster. > > > minindex, minvalue = min(enumerate(seq), key=itemgetter(1)) > > Cool, I like this best of all. Or alternatively, > > minindex, minvalue = min(izip(seq, count())) Bzzzt #2! >>> from itertools import count, izip >>> min(izip(seq, count())) (7, 3) From Russ.Paielli at gmail.com Tue Jan 8 01:08:54 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 7 Jan 2008 22:08:54 -0800 (PST) Subject: use fileinput to read a specific line References: <6f2db44c-2641-47cb-ab24-4177ccc96d6e@m77g2000hsc.googlegroups.com> <13o637afk4mql0c@corp.supernews.com> Message-ID: <44c28069-12bf-43c2-96f6-06b4c3923188@41g2000hsy.googlegroups.com> > Given that the OP is talking 2000 files to be processed, I think I'd > recommend explicit open() and close() calls to avoid having lots of I/O > structures floating around... Good point. I didn't think of that. It could also be done as follows: for fileN in files: lnum = 0 # line number input = file(fileN) for line in input: lnum += 1 if lnum >= 4: break input.close() # do something with "line" Six of one or half a dozen of the other, I suppose. From arkanes at gmail.com Thu Jan 3 14:06:07 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 3 Jan 2008 13:06:07 -0600 Subject: reassign to builtin possible !? In-Reply-To: <477CEB93.8000706@tim.thechases.com> References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> <477CEB93.8000706@tim.thechases.com> Message-ID: <4866bea60801031106j70d496caw8e1a60e6931ab4fc@mail.gmail.com> On Jan 3, 2008 8:05 AM, Tim Chase wrote: > >> But you can't alter the values for True/False globally with this. > > > > Are you sure ? what about the following example ? > > Is this also shadowing ? > > > >>>> import __builtin__ > >>>> __builtin__.True = False > >>>> __builtin__.True > > False > > It doesn't seem to screw things up globally > > >>> import __builtin__ > >>> t = __builtin__.True > >>> __builtin__.True = False > >>> __builtin__.False = t > >>> True > False > >>> False > True > >>> 1 == 1 > True > >>> import os > >>> os.path.isdir('.') > True > >>> #if they were globally redefined, this would be False > >>> #you'd have to actually reference __builtin__.True > > My thought would be if you do something as daft as > redefining/shadowing True and False, you get the headaches that > ensue. Fortunately, since Python is explicit, you can trace back > through the code and see where the inanity occurred. > Additionally, any scoping rules mean that programmer stupidity > can't leak too badly outside the scope of the block containing > the stupidity. > > It's the old "DIHWIDT! WDDT!" ("Doctor, it hurts when I do > this!", "well don't do that!") syndrome. > In Py3k this will be a syntax error, like assigning to None is now. Possibly also in 2.6. From jo at durchholz.org Thu Jan 3 10:13:55 2008 From: jo at durchholz.org (Joachim Durchholz) Date: Thu, 03 Jan 2008 16:13:55 +0100 Subject: Choosing a new language In-Reply-To: References: <20071228162351.f29a3ce4.coolzone@it.dk> Message-ID: Tim Roberts schrieb: > Joachim Durchholz wrote: > >>> Xah Lee wrote: >>>> [...] PHP and Perl are practically identical in their >>>> high-levelness or expressiveness or field of application (and >>>> syntax), >> That must have been a very, very distant point of view with narrowly >> squinted eyes. > > Do you really think so? It seems clear to me that the syntax of PHP was > heavily influenced by Perl. PHP lacks the @array and %hash weirdnesses, > but most PHP code will work just fine as Perl. Quite unlikely. It won't even parse. PHP code starts with and the next Do I have to install something extra to use the new look? Robert From steven at REMOVE.THIS.cybersource.com.au Tue Jan 15 23:36:27 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Jan 2008 04:36:27 -0000 Subject: no pass-values calling? References: Message-ID: On Wed, 16 Jan 2008 11:09:09 +0800, J. Peng wrote: > Hello, > > I saw this statement in Core Python Programming book, > > All arguments of function calls are made by reference, meaning that any > changes to these parameters within the function affect the original > objects in the calling function. > > > Does this mean there is not pass-values calling to a function in python? > only pass-reference calling? Thanks! No, Python does not use either pass by reference or pass by value. It uses pass by object. (Sometimes called "pass by object reference".) See: http://effbot.org/zone/call-by-object.htm for further details. -- Steven From grante at visi.com Sat Jan 5 09:40:06 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 05 Jan 2008 14:40:06 -0000 Subject: Question on os.tempnam() vulnerability References: <13nt81gftkfa32d@corp.supernews.com> Message-ID: <13nv5m68qeknk1f@corp.supernews.com> On 2008-01-05, Jarek Zgoda wrote: >> Under Windows, is there a "safe" way to create a temp file >> that has a name that can be passed to a program which will >> then open it? I never figured out a way to do that and had to >> fall back on the "unsafe" tmpnam method. > > I think it's all impossible to get only file name and feel > safe. You have to have both file name and a file object opened > exclusively for you. Any other way you'll get a possible race > condition. I know. That's the point of my question: how do you do that under Windows? -- Grant Edwards grante Yow! HAIR TONICS, please!! at visi.com From over at thepond.com Wed Jan 23 13:47:37 2008 From: over at thepond.com (over at thepond.com) Date: Wed, 23 Jan 2008 18:47:37 GMT Subject: python24 symbol file...pyhon24.pdb References: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> <479706a0$0$13412$9b622d9e@news.freenet.de> Message-ID: <3u2fp3ht1cr9avj68qvf26qqsh0jiqh9co@4ax.com> On Wed, 23 Jan 2008 10:19:28 +0100, "Martin v. L?wis" wrote: >> Also, is there source code available for python24 for Windoze? I have >> seen reference to source code but not in a package for Windows. > >It's available from > >http://www.python.org/ftp/python/2.4/Python-2.4.tgz > >Regards, >Martin thanks you kindly. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 30 17:09:03 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 30 Jan 2008 23:09:03 +0100 Subject: Events in Python References: <2b005569-3dbc-41c1-aebf-8b6fd8d2175e@v46g2000hsv.googlegroups.com> Message-ID: <60carvF1q0a0rU1@mid.individual.net> Ivan Illarionov wrote: > Note that all those signals/events are very slow in Python. Compared to what, did you measure something? Regards, Bj?rn -- BOFH excuse #38: secretary plugged hairdryer into UPS From ajaksu at gmail.com Sat Jan 19 18:22:01 2008 From: ajaksu at gmail.com (ajaksu) Date: Sat, 19 Jan 2008 15:22:01 -0800 (PST) Subject: Python 3000 and import __hello__ References: Message-ID: <952a1ed8-638b-4c78-abd7-1dc62fdc837d@z17g2000hsg.googlegroups.com> On Jan 19, 7:54 pm, Brad wrote: > Just playing around with Python3000 a2 release on Windows XP 32-bit x86. > > import __hello__ > > doesn't print 'hello world...' as it does on 2.5 Thanks for spoiling this easter egg for me! ;) From brkict at gmail.com Mon Jan 21 12:25:57 2008 From: brkict at gmail.com (glomde) Date: Mon, 21 Jan 2008 09:25:57 -0800 (PST) Subject: is it possible to set namespace to an object. Message-ID: <27529efd-b8d8-4a8e-b72d-379a607366b7@i7g2000prf.googlegroups.com> Hi, is it somehow possible to set the current namespace so that is in an object. Somthing like. class Test(): .... testObj = Test() set namespace testObj Name = "Test" Name would set testObj.Name to "Test". I was thinking this could be done with the with statement somehow (without using as) in the __enter__ function. Is the above possible? /T From http Thu Jan 10 21:22:35 2008 From: http (Paul Rubin) Date: 10 Jan 2008 18:22:35 -0800 Subject: Best way to merge/sort two sorted lists?... References: <1230064b-603d-4386-b68c-a913c5cf80d3@s12g2000prg.googlegroups.com> <60572417-9e83-4d0c-80da-2c99a9bd19e4@b40g2000prf.googlegroups.com> <232c569b-783a-43b8-bdb0-2d578bac037b@s8g2000prg.googlegroups.com> Message-ID: <7xfxx5cd90.fsf@ruckus.brouhaha.com> Aaron Watters writes: > The second one is! That's why it works so fast. > Tim Peters optimized this case! > Gotta hand it to Tim Peters. The first one should > win some sort of obfuscated code contest, imho. > It also seems to be 5 times slower than any of the others. The heapq method is the right way to do it when you want to merge n lists instead of two lists. Each selection takes O(log n) operations. From superwesman at gmail.com Wed Jan 16 00:41:01 2008 From: superwesman at gmail.com (superwesman) Date: Tue, 15 Jan 2008 21:41:01 -0800 (PST) Subject: can't find pyAntTasks.properties Message-ID: <3d1efa8c-ab6a-487d-abe6-63f227a895fc@i29g2000prf.googlegroups.com> Hi - I'm trying to use pyAntTasks. I downloaded the jar and placed it into ~/.ant/lib, put that directory into my CLASSPATH. I then created a very simple build.xml and I'm getting a failure I can't explain. Here is my build.xml: Here is my CLASSPATH: > echo $CLASSPATH /home/wtorres/.ant/lib And here's what's in it: > ls -lrt $CLASSPATH total 24 -rwxrwxr-x 1 wtorres staff 8563 Jan 15 18:34 pyAntTasks.jar When I run ant, here is the failure: (the 'ant' script I'm running here sets up ant 1.6.2 and runs it) > /vobs/jfw/ant ANT=/tools/ant/1.6.2 Buildfile: build.xml [taskdef] Could not load definitions from resource pyAntTasks.properties. It could not be found. BUILD SUCCESSFUL Total time: 1 second What the heck am I doing wrong? Where can I find pyAntTasks.properties? I mean, it makes sense that "It could not be found" because I can't find it either. Where do I get/put this? Thanks -w From deets at nospam.web.de Fri Jan 25 09:19:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jan 2008 15:19:50 +0100 Subject: Terse Syntax through External Methods In-Reply-To: References: Message-ID: <5vu9gaF1no9i1U1@mid.uni-berlin.de> Jens schrieb: > Hello Everyone > > I'm newbie to Zope and i have a few questions regarding external > methods. What i wan't to do > is provide a terse syntax for converting urls to special tracking > urls: > > > > turns the provided url into something like > > http://host/tracking?url=http%3A%2F%2Fmyurl%2F > > in the output. > > i've been trying to use a external procedure like this. > > ## Script (Python) "track_link" > ##bind container=container > ##bind context=context > ##bind namespace=_ > ##bind script=script > ##bind subpath=traverse_subpath > ##parameters=self,url > ##title=track link > ## > return "%s%s" % (self.tracking_prefix, url_quote(url)) > > This doesn't work because because the method doesn't have access to > the environment. Obviously I don't wan't to pass everything explicitly > into the function as this would defeat the purpose of the exercise, > namely to provide a terse syntax. > > I have a background in other languages so I might be missing something > conceptually with regard Zope and DTML.. Is there a better was of > doing this, perhaps without using external methods? Currently im doing > the following which isn't very elegant: > > in content document > tracking>">link > ... > tracking: > > > Appreciate any input you might have on this- Is it really needed to use an external method for this, or isn't a "normal" python script enough already? If it has to be an External method, you can't access such a context AFAIK. But then you can create a python script that _has_ this context, and passese it to the external method. Not the nicest solution, but should work. Diez From shriphanip at gmail.com Tue Jan 1 07:21:29 2008 From: shriphanip at gmail.com (Shriphani) Date: Tue, 1 Jan 2008 04:21:29 -0800 (PST) Subject: pdf library. References: <133097f4-de83-4e13-93f1-1404213333a4@l6g2000prm.googlegroups.com> Message-ID: <3b429178-8c07-4dcb-8034-1912c0597830@d21g2000prf.googlegroups.com> On Jan 1, 4:28 pm, Piet van Oostrum wrote: > >>>>>Shriphani (S) wrote: > >S> I tried pyPdf for this and decided to get the pagelinks. The trouble > >S> is that I don't know how to determine whether a particular page is the > >S> first page of a chapter. Can someone tell me how to do this ? > > AFAIK PDF doesn't have the concept of "Chapter". If the document has an > outline, you could try to use the first level of that hierarchy as the > chapter starting points. But you don't have a guarantee that they really > are chapters. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org How would a pdf to html conversion work ? I've seen Google's search engine do it loads of times. Just that running a 500odd page ebook through one of those scripts might not be such a good idea. From robert.kern at gmail.com Fri Jan 4 21:45:32 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 04 Jan 2008 20:45:32 -0600 Subject: vim newb - indenting python comments In-Reply-To: <477EE677.1030908@tim.thechases.com> References: <477EE677.1030908@tim.thechases.com> Message-ID: Tim Chase wrote: >> One problem I have is that the >> indent in normal mode doesn't work >> when a line starts with the # character. Any idea what I'm doing >> wrong? > > In short, ">>" *does* indent in normal mode (I presume you > accurately mean "Normal" mode, rather than "Insert" mode). The > question becomes why doesn't it work in your particular copy of Vim? > > To evidence this, start vim with > > vim -u NONE myfile.py > > (which bypasses startup files) and you'll see that >> does indeed > shift commented lines. > > To track down the problem, you'll need to provide a little more > info. Starting Vim the way you normally do, pointed at a > problematic python file, what is the output of > > :scriptnames > > What mappings do you have defined: > > :nmap > > (particularly any mappings for ">" and its kin). > > What are your filetype settings: > > :filetype > > What are your settings for 'indentkeys', 'indentexpr', > 'shiftwidth', 'tabstop', 'expandtab' and 'filetype' > > :set indentkeys? indentexpr? sw? ts? et? ft? :set cindent? Having this set (in the absence of anything else) will replicate the behavior for me (vim 7.1 OS X). :filetype plugin on :filetype indent on Fixes it. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From nospam at invalid.com Sat Jan 12 01:07:07 2008 From: nospam at invalid.com (Jack) Date: Sat, 12 Jan 2008 06:07:07 GMT Subject: Using a proxy with urllib2 References: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> <87ir21o8sj.fsf@merkury.smsnet.pl> Message-ID: >> I'm trying to use a proxy server with urllib2. >> So I have managed to get it to work by setting the environment >> variable: >> export HTTP_PROXY=127.0.0.1:8081 >> >> But I wanted to set it from the code. However, this does not set the >> proxy: >> httpproxy = '127.0.0.1:3129' >> proxy_support = urllib2.ProxyHandler({"http":"http://" + httpproxy}) >> opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) >> urllib2.install_opener(opener) I find out why it doesn't work in my code but I don't have a solution - somewhere else in the code calls these two lines: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) and they override the proxy opener. Could anyone tell me how to use both openers? From pofuk at mzm.hr Thu Jan 17 19:13:56 2008 From: pofuk at mzm.hr (SMALLp) Date: Fri, 18 Jan 2008 01:13:56 +0100 Subject: Downlod from FTP, pickle Message-ID: Hy! I have a little problem. I have to download file from FTP sp i use ftplib. And then i have to pickle.load from that file. I make callback function that saves line by line into temporary file and now i cant read from that file and when i close it i diapers. Thanks! From rw at smsnet.pl Thu Jan 10 13:28:11 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 10 Jan 2008 19:28:11 +0100 Subject: urllib2 rate limiting References: Message-ID: <87ejcpo7r8.fsf@merkury.smsnet.pl> Dimitrios Apostolou writes: > P.S. And something simpler: How can I disallow urllib2 to follow > redirections to foreign hosts? You need to subclass `urllib2.HTTPRedirectHandler`, override `http_error_301` and `http_error_302` methods and throw `urllib2.HTTPError` exception. http://diveintopython.org/http_web_services/redirects.html HTH, Rob From martin at marcher.name Mon Jan 21 08:57:31 2008 From: martin at marcher.name (Martin Marcher) Date: Mon, 21 Jan 2008 14:57:31 +0100 Subject: [OT] Valid Mail addresses modifications (WAS: Re: Looping through the gmail dot trick) References: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> Message-ID: Martin Vilcans wrote: > Try the SMTP spec. IIRC there's a passage there that says that the > server should try to make sense of addresses that don't map directly > to a user name. Specifically, it says that firstname.lastname should > be mapped to the user with those first and last names. Short story long: there aren't any! FYI: https://mail.google.com/support/bin/answer.py?answer=10313&topic=1564 that was the only reference i found, http://www.ietf.org/rfc/rfc0821.txt doesn't mention anything beside EXPN which still treats the localpart literally and checks for a mailbox (or alias) as literally found in the localpart. Personally I think google's doing wrong here. Just don't do it anywhere else, as it's unlikely your mail will reach the person you intended to send it. -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From fredrik at pythonware.com Sun Jan 6 05:01:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 06 Jan 2008 11:01:11 +0100 Subject: python interfaces In-Reply-To: <96b70141-f872-413a-a433-08b217cecb27@e4g2000hsg.googlegroups.com> References: <96b70141-f872-413a-a433-08b217cecb27@e4g2000hsg.googlegroups.com> Message-ID: r.grimm at science-computing.de wrote: > Interfaces are a extremly smart Design Principle in static typed > languages like Java and C++. that's somewhat questionable in itself, and even more questionable as an argument for interfaces in Python. I'd recommend anyone who thinks that they cannot program without formal interfaces to try using Python as Python for a while, before they try using it as something else. you might be surprised over how easy it is to build robust stuff without having to add lots of extra constraints to your code. From marduk at python.invalid Mon Jan 21 02:00:11 2008 From: marduk at python.invalid (Albert Hopkins) Date: Mon, 21 Jan 2008 01:00:11 -0600 Subject: When is min(a, b) != min(b, a)? References: Message-ID: On Sun, 20 Jan 2008 20:16:18 -0800, Paddy wrote: > I am definitely NOT a floating point expert, but I did find this: > http://en.wikipedia.org/wiki/IEEE_754r#min_and_max > > P.S. What platform /Compiler are you using for Python? Linux with GCC 4 -a From grahn+nntp at snipabacken.dyndns.org Sun Jan 20 09:59:43 2008 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 20 Jan 2008 14:59:43 GMT Subject: Core Python Programming . . . References: <7xir1q29j5.fsf@ruckus.brouhaha.com> <0005f532-409b-4c4e-8483-b2e32bbc724a@q77g2000hsh.googlegroups.com> Message-ID: On Sat, 19 Jan 2008 08:57:24 -0500, Yu-Xi Lim wrote: > FireNWater wrote: > >> I guess I'm not fully up to speed on what constitutes an IP address. >> Does the term 'octet' refer to an 8-bit (xFF) number? > > Yes, it somewhat archaic though. It's more precise than byte, like you say. I don't think its archaic though; it's a fairly common term when you are talking data communication in general and IP-based protocols in particular. > It's used when "byte" is ambiguous. On > some ancient (by computing standards) computers, the size of a byte may > be as small as 6 bits or as big as 9. On ancient computers and in some embedded processors. I have a Texas Instruments DSP in my cellphone with 16-bit words. A C "char" is 16 bits in that environment. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From http Fri Jan 11 09:00:13 2008 From: http (Paul Rubin) Date: 11 Jan 2008 06:00:13 -0800 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <7xir21lzmo.fsf@ruckus.brouhaha.com> Message-ID: <7xprw8xy1e.fsf@ruckus.brouhaha.com> Fredrik Lundh writes: > (and if you use sane naming conventions, the risk for collisions is > near zero as well). I haven't felt that way, I'm always worried about clobbering something by leaking a variable. Maybe collisions don't really happen much, but it's always seemed cleaner to me to use the most restricted scopes possible just to minimize or eliminate the possibility. This is especially attractie in a language like Python, with no declarations and no compile-time type safety. From goon12 at gmail.com Tue Jan 29 14:02:29 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 29 Jan 2008 14:02:29 -0500 Subject: noob stuck on reading double In-Reply-To: <6a2ccd190801291059q1a18c70co8e9db881c6994f63@mail.gmail.com> References: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk> <6a2ccd190801291059q1a18c70co8e9db881c6994f63@mail.gmail.com> Message-ID: <6a2ccd190801291102m457f1fb9odca04ef24fb47ac3@mail.gmail.com> On Jan 29, 2008 1:59 PM, Joe Riopel wrote: > When reading the file, try using > file = open('data.bin', 'rb') > file.seek(0) > raw = file.read() > > Do the unpack on "raw". Ignore this, sorry for the confusion. From fredrik at pythonware.com Thu Jan 10 14:52:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 20:52:07 +0100 Subject: What is "lambda x=x : ... " ? In-Reply-To: <20080110144135.20e55ec3@bhuda.mired.org> References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> <20080110134335.37cf5377@mbook.mired.org> <20080110144135.20e55ec3@bhuda.mired.org> Message-ID: Mike Meyer wrote: >>>> What does "y=y" and "c=c" mean in the lambda function? >>> >>> Older versions of python didn't make variables in an outer scope >>> visible in the inner scope. This was the standard idiom to work >>> around that. >>> >> lexically scoped free variables and object binding are two different >> things, and have different semantics. the former does not always >> replace the latter. > > And? and what? it's not the same thing. the "newer" idiom only replaces the "older" idiom under certain circumstances (such as in the OP's first example, but *not* in his second example). From arnodel at googlemail.com Tue Jan 22 09:19:24 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 06:19:24 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: On Jan 22, 1:19?pm, Alan Isaac wrote: [...] > PS My understanding is that the behavior > of the last is implementation dependent > and not guaranteed. [...] > def pairs4(x): > ? ? xiter = iter(x) > ? ? for x12 in izip(xiter,xiter): > ? ? ? ? yield x12 According to the docs [1], izip is defined to be equivalent to: def izip(*iterables): iterables = map(iter, iterables) while iterables: result = [it.next() for it in iterables] yield tuple(result) This guarantees that it.next() will be performed from left to right, so there is no risk that e.g. pairs4([1, 2, 3, 4]) returns [(2, 1), (4, 3)]. Is there anything else that I am overlooking? [1] http://docs.python.org/lib/itertools-functions.html -- Arnaud From sjmachin at lexicon.net Tue Jan 29 15:29:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 30 Jan 2008 07:29:31 +1100 Subject: noob stuck on reading double In-Reply-To: References: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk> <6a2ccd190801291059q1a18c70co8e9db881c6994f63@mail.gmail.com> <6a2ccd190801291102m457f1fb9odca04ef24fb47ac3@mail.gmail.com> Message-ID: <479F8CAB.7060203@lexicon.net> [I can't see Hannah's posting(s) with my news client (Thunderbird), nor with Google Groups] Joe Riopel wrote: > Since you're unpacking it with the 'd' format character I am assuming > a "doubleword" field is a double. Given Hannah has sensibly stated up front that she is a noob, I would assume nothing from her code. Given "doubleword" is Intel/MS-speak for "32-bit quantity", and following the strong hint of repeat-every-4-bytes from the printed gibberish (e.g. "Q???Q???Q???Q???Q?") I'd *guess* that a "doubleword" is a signed or unsigned 32-bit integer. Now let's check the guess: > You said you had 113 of them in the > binary file. There are about 170 bytes of gibberish, that I saw in Joe's second reply. Hannah, don't do: print gibberish do: print len(gibberish), repr(gibberish) What is the size of the file? 4 * 113 -> 452, 8 * 113 = 904 > You should be doing something like this: > > file = open('data.bin', 'rb') don't shadow the 'file' built-in function > file.seek(0) where else would it be positioned??? > raw = file.read() > unpacked = unpack('113d', raw) > for i in range(0,113): > print unpacked[i] > file.close() I suggest that Hannah try something like this: from struct import unpack f = open('data.bin', 'rb') raw = f.read() nbytes = len(raw) print 'nbytes', nbytes print '32-bit signed integer', unpack('<%di' % (nbytes // 4), raw) print '32-bit unsigned integer', unpack('<%dI' % (nbytes // 4), raw) print '64-bit floating point', unpack('<%dd' % (nbytes // 8), raw) and choose depending on what output best meets her expectations. Note: the "<" in the above is another guess based on "doubleword" -> Intel -> little-endian. If struct.unpack is unhappy or if all three results look like rubbish, change the "<" to a ">" and try again ... if in doubt, come back for more advice. If you do, please include the output from starting Python at the shell prompt and peeking at sys.byteorder -- this i swhat that produces on my machine: C:\junk>python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys; sys.byteorder 'little' >>> HTH, John From asmodai at in-nomine.org Thu Jan 10 03:13:37 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 10 Jan 2008 09:13:37 +0100 Subject: Conventions for dummy name (was: for loop without variable) In-Reply-To: <873at6k2qt.fsf_-_@benfinney.id.au> References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de> <873at6k2qt.fsf_-_@benfinney.id.au> Message-ID: <20080110081337.GU75977@nexus.in-nomine.org> -On [20080110 00:21], Ben Finney (bignose+hates-spam at benfinney.id.au) wrote: >The problem with the '_' name is that it is already well-known and >long-used existing convention for an entirely unrelated purpose: in >the 'gettext' i18n library, the '_' function to get the >locally-translated version of a text string. The same applies for Babel (http://babel.edgewall.org/) where we have _() in similar vein to the gettext implementation. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ With a nuclear fire of Love in our Hearts, rest easy baby, rest easy... From brian at briansmith.org Thu Jan 17 07:29:05 2008 From: brian at briansmith.org (Brian Smith) Date: Thu, 17 Jan 2008 04:29:05 -0800 Subject: Some Berkeley DB questions (being maintained? queries?) In-Reply-To: <0ba30836-8e2d-4061-94ea-ccddb24bc290@s19g2000prg.googlegroups.com> References: <0ba30836-8e2d-4061-94ea-ccddb24bc290@s19g2000prg.googlegroups.com> Message-ID: <003601c85904$904150c0$0401a8c0@T60> HerbAsher at googlemail.com wrote: > 1. Now that Berkeley DB is part of Oracle, is it still being > maintained? Is it free? Berkeley DB is owned by Oracle, but it is seperate from the Oracle RDBMS product. Yes, it is free. > 2. Are there good python libraries for bdb available, that > are being maintained? I would like to know the answer to this question too--if you have used the pybsddb/bsddb.db module, please share your experience. > 3. Is it possible to query a berkeley db database? Just > simple queries like: find me all items where key "name" = "John" That is basically the only kind of query that a Berkeley DB database can do: key [<|=|>] value. > 4. What are good, stable alternatives? That depends soley on your requirements. Berkeley DB is actually one of the most complicated persistence solutions. It is more complex than SQLite, and WAY more complex than gdbm, for example. If you don't need all its functionality, especially its multi-user capabilities, then I recommend using something simpler. However, if you DO need its multi-user cabailities or its advanced features like secondary indexes, then it is better to use Berkeley DB than to re-invent it. - Brian From rrr at ronadam.com Sun Jan 13 23:08:39 2008 From: rrr at ronadam.com (Ron Adam) Date: Sun, 13 Jan 2008 22:08:39 -0600 Subject: time.time or time.clock In-Reply-To: References: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> Message-ID: <478AE047.8070306@ronadam.com> Fredrik Lundh wrote: > John Machin wrote: > >> AFAICT that was enough indication for most people to use time.clock on >> all platforms ... > > which was unfortunate, given that time.clock() isn't even a proper clock > on most Unix systems; it's a low-resolution sample counter that can > happily assign all time to a process that uses, say, 2% CPU and zero > time to one that uses 98% CPU. > > > before the introduction of the timeit module; have you considered it? > > whether or not "timeit" suites his requirements, he can at least replace > his code with > > clock = timeit.default_timer > > which returns a good wall-time clock (which happens to be time.time() on > Unix and time.clock() on Windows). Thanks for the suggestion Fredrik, I looked at timeit and it does the following. import sys import time if sys.platform == "win32": # On Windows, the best timer is time.clock() default_timer = time.clock else: # On most other platforms the best timer is time.time() default_timer = time.time I was hoping I could determine which to use by the values returned. But maybe that isn't as easy as it seems it would be. Ron From tjreedy at udel.edu Mon Jan 28 22:48:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jan 2008 22:48:11 -0500 Subject: Python self-evaluating strings References: <1BEEBF03-1A38-4745-B08B-DCA3106D1CC5@gmail.com> Message-ID: "Arnaud Delobelle" wrote in message news:a04ca850-fe63-4b7e-abff-cdacab3bcc0f at i29g2000prf.googlegroups.com... | I found this: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a1316cb4e216eba4/0cda739385abd03c?lnk=gst&q=Self-Reproducing+Program#0cda739385abd03c Exactly the one I meant. | It contains a lambda-solution similar to mine, only more concise: | (lambda x:x%`x`)('(lambda x:x%%`x`)(%s)') Being a Lisp novice, I was rather proud of that translation | I have been using python for 7 years, and it the first time ever that | I see the `...` construct being used! It is going away in 3.0, so the above would need revision to work with repr(), if indeed it will. | Thanks You're welcome Terry From mobiledreamers at gmail.com Mon Jan 14 00:51:20 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Sun, 13 Jan 2008 21:51:20 -0800 Subject: Recieving emails in python Message-ID: I m trying to create something simple a mailing list similar to yahoo groups I m stumbling at the part where the python recieves messages via say python at yahoogroups.com how to make python recieve emails and process it after that it is straight forward processing in python inserting in db etc -------------- next part -------------- An HTML attachment was scrubbed... URL: From buzzard at urubu.freeserve.co.uk Sat Jan 19 11:30:41 2008 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Sat, 19 Jan 2008 16:30:41 +0000 Subject: TopSort in Python? In-Reply-To: <12f0f54e-5d30-40bc-9135-2c59b8a5acc2@i3g2000hsf.googlegroups.com> References: <0000161d@bossar.com.pl> <358cc5a3-300f-49ba-9857-2f0cd629a4df@i12g2000prf.googlegroups.com> <12f0f54e-5d30-40bc-9135-2c59b8a5acc2@i3g2000hsf.googlegroups.com> Message-ID: Carl Banks wrote: > On Jan 18, 7:01 pm, Paddy wrote: >> On Jan 18, 9:47 pm, startec... at gmail.com wrote:> Tim, >> >>> Thanks for the topsort code. It would be useful in a project I'm >>> working on. Can I use the code for free under public domain? Thanks! >> When I needed one I didn't know the name. I'm curious, how did you >> know to look for the topological sort algorithm by name? > > I spent quite a bit of time looking for this one myself. It was quite > a stumper. Sometimes Google gets us in the habit of just firing > random search terms when we ought to be thinking it out. > > After quite of bit of dead end searching--like a week--I stepped back, > thought about what I was looking for. I wanted a sort of dependency > system: A must happen before B. What other programs do that? make, > of course. I looked at the documents for make and found the term > "directed acyclic graph", and pretty much instantly knew I had it. Searching for "precedence diagram" might throw up some relevant results; but you've probably already discovered that. I have some basic precedence diagram code (no warranty etc.) somewhere if anyone is interested. Duncan From rw at smsnet.pl Thu Jan 10 09:09:56 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 10 Jan 2008 06:09:56 -0800 (PST) Subject: New Tk look (aka Ttk or Tile widgets) References: Message-ID: <89e08cf4-a815-412b-b575-ccd770a7f0d3@v4g2000hsf.googlegroups.com> Robert Hicks napisa?(a): > Do I have to install something extra to use the new look? I managed to use Tile with Tk 8.4 and Python 2.5. After installing Tile I followed these advices: http://tkinter.unpythonic.net/wiki/UsingTile and used this code: http://tkinter.unpythonic.net/wiki/TileWrapper Actually, I wanted to use Treeview, so I needed to tweak a little bit this code, but it's very simple to do. HTH, Rob From rw at smsnet.pl Sat Jan 12 07:16:02 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Sat, 12 Jan 2008 13:16:02 +0100 Subject: Using a proxy with urllib2 References: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> <87ir21o8sj.fsf@merkury.smsnet.pl> Message-ID: <874pdjck8t.fsf@merkury.smsnet.pl> "Jack" writes: >>> I'm trying to use a proxy server with urllib2. >>> So I have managed to get it to work by setting the environment >>> variable: >>> export HTTP_PROXY=127.0.0.1:8081 >>> >>> But I wanted to set it from the code. However, this does not set the >>> proxy: >>> httpproxy = '127.0.0.1:3129' >>> proxy_support = urllib2.ProxyHandler({"http":"http://" + httpproxy}) >>> opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) >>> urllib2.install_opener(opener) > > I find out why it doesn't work in my code but I don't have a solution - > somewhere > else in the code calls these two lines: > > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > urllib2.install_opener(opener) > > and they override the proxy opener. Could anyone tell me how to use both > openers? > You don't have to create another opener if you only want to add some handler. You can use `add_handler` method, e.g.: opener.add_handler(urllib2.HTTPCookieProcessor(cj)) HTH, Rob From wuhrrr at gmail.com Thu Jan 17 04:47:20 2008 From: wuhrrr at gmail.com (Hai Vu) Date: Thu, 17 Jan 2008 01:47:20 -0800 (PST) Subject: reading a specific column from file References: Message-ID: <3149e879-b94d-443c-b056-d6cf5bad2688@h11g2000prf.googlegroups.com> Here is another suggestion: col = 2 # third column filename = '4columns.txt' third_column = [line[:-1].split('\t')[col] for line in open(filename, 'r')] third_column now contains a list of items in the third column. This solution is great for small files (up to a couple of thousand of lines). For larger file, performance could be a problem, so you might need a different solution. From papilonv at gmail.com Sat Jan 19 05:32:28 2008 From: papilonv at gmail.com (Vikas Jadhav) Date: Sat, 19 Jan 2008 16:02:28 +0530 Subject: Help! - Invoke setup.py file Message-ID: <7856b4e60801190232j3b1a18b5n3630ddf77aed9ee0@mail.gmail.com> Hi, We have setup of SVGMath* 0.3.2 (Converter- Mathml 2.0 coding to SVG). The setup folder contains setup.py file but we are not able to initiate this file. Kindly help us, resolution to this query will be appreciated. Python version: Installed on PC- 2.5.1 and OS- Windows 2000. * *SVGMath* is a *command*-line utility to convert MathML expressions to SVG, written entirely in Python. Note: Attached file contains SVGMath installation components. Cheers, Vikas -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: SVGMath-0.3.2.zip Type: application/zip Size: 77473 bytes Desc: not available URL: From stefan.behnel-n05pAM at web.de Thu Jan 3 03:08:36 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 03 Jan 2008 09:08:36 +0100 Subject: ElementTree should parse string and file in the same way In-Reply-To: References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> Message-ID: <477C9804.40003@web.de> Hi, Chris Mellon wrote: > On that note, I really don't like APIs that take either a file name or > a file object - I can open my own files, thanks. ... and HTTP URLs, and FTP URLs. In lxml, there is a performance difference between passing an open file (which is read in Python space using the read() method) and passing a file name or URL, which is passed on to libxml2 (and thus doesn't require the GIL at parse time). That's only one reason why I like APIs that allow me to pass anything that points to a file - be it an open file object, a local file path or a URL - and they just Do The Right Thing with it. I find that totally pythonic. > open(fname) is even shorter than StringIO(somedata). It doesn't serve the same purpose, though. > My take on the API decision in question was always that a file is > inherently an XML *document*, while a string is inherently an XML > *fragment*. Not inherently, no. I know some people who do web processing with an XML document coming in as a string (from an HTTP request) and a result XML document going out as a string. I don't think that's an uncommon use case. Stefan From johnthawk at excite.com Sat Jan 12 22:14:57 2008 From: johnthawk at excite.com (johnthawk at excite.com) Date: Sat, 12 Jan 2008 22:14:57 -0500 (EST) Subject: pygtk dnd woes Message-ID: <20080113031457.1DA4C2F5E7@xprdmxin.myway.com> Hi all, DND has just about got me going bonkers. I want to process the dnd drop to main window and then process the dnd_list to ship to open_arg. Resulting in individual editor panes opening the files. The problem: TypeError: dnd_drop() takes exactly 6 arguments (8 given) or TypeError: dnd_drop() takes exactly 8 arguments (6 given) Seems I'm in a catch 22 here. The code: # read notes self.on_read_notes() # dnd # self.TARGET_TYPE_URI_LIST = 80 self.window.dnd_list = [ ( 'text/plain', 0, self.TARGET_TYPE_URI_LIST ) ] self.window.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_HIGHLIGHT, self.window.dnd_list, gtk.gdk.ACTION_COPY) self.window.connect('drag_data_received', self.dnd_drop) self.window.drag_dest_set(gtk.DEST_DEFAULT_ALL, [ ( 'text/uri-list', 0, self.TARGET_TYPE_URI_LIST ) ], gtk.gdk.ACTION_COPY) self.window.connect('drag_drop', self.dnd_drop) # # show all self.window.show_all() self.window.set_title('GEd:') self.window.show() # welcome self.set_status('Welcome to GEd-V-0.1 :-) ...') # #-------------------------------------------------------------------------- def dnd_drop(self, widget, context, x, y, times): # (self, widget, context, x, y, selection, target_type, time): # process list and and ship to open_arg print 'data received' context.finish(True, False, time) return True # #-------------------------------------------------------------------------- def on_blank(self, widget): pass Thanks john _______________________________________________ Join Excite! - http://www.excite.com The most personalized portal on the Web! From grante at visi.com Wed Jan 23 18:54:13 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 23 Jan 2008 23:54:13 -0000 Subject: Increment Variable Name References: <5vq0rjF1o724kU1@mid.uni-berlin.de> Message-ID: <13pfkt53kq7jo7c@corp.supernews.com> On 2008-01-23, Diez B. Roggisch wrote: > David Brochu schrieb: >> This is probably really trivial but I'm stumped.... :-( >> >> Does anyone know how to increment a variable name? >> >> For example: >> >> I know the length of a list and I want to pass each element of a list to >> a unique variable, thus I want to increment variable names. If the list >> length = 4, i want to have the following variables: var1, var2, var3, var4. >> > > Use a dictionary > > value_dict = {} > > for i, value in values: > value_dict["var%i" % i] = value That assumes that the OPs "list" is actually a list of tumples: [(1,firstvalue),(2,secondvalue), (3, thirdvalue), ...] I'd adjust my thinking (regarding 0/1 based counting) and just use a list or a tuple: var = list(values) or var = tuple(values) In either case, you now have var[0], var[1], var[2], var[3], ... If you insist on numbers starting at 1, then a dict would work: var = {} for i,value in itertools.enumerate(itertools.count(1), values): var[i] = value now you have var[1], var[2], var[3], var[4], ... -- Grant Edwards grante Yow! I'm continually AMAZED at at th'breathtaking effects visi.com of WIND EROSION!! From lists at cheimes.de Sat Jan 19 10:14:26 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 19 Jan 2008 16:14:26 +0100 Subject: finding memory leak in edgewall trac 0.11 In-Reply-To: References: Message-ID: <479213D2.2020701@cheimes.de> rupert.thurner wrote: > what would be a good means of finding where the 0.11 version of > edgewall trac uses excessive memory. see > http://groups.google.com/group/trac-dev/browse_thread/thread/116e519da54f16b > for some details, where jonas suggested > http://wingolog.org/archives/2007/11/27/reducing-the-footprint-of-python-applications > as reading. > > tiran already gave some hints on http://bugs.python.org/issue1871, but > also suggested to ask the general mailing list: > > Do you have classes with a __del__ method which may create reference > cycles? The GC can't break cycles when a __del__ method is involved. > > Are you keeping references to tracebacks, exception objects (except > Exception, err) or frames (sys._getframe()) I forgot one important point in my reply. The GC module contains some useful methods for debugging. Check gc.garbage. It should be empty. http://docs.python.org/lib/module-gc.html Christian From lasses_weil at klapptsowieso.net Mon Jan 28 07:23:54 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 28 Jan 2008 13:23:54 +0100 Subject: Python Genetic Algorithm In-Reply-To: <13pqbvn8ckilnfc@corp.supernews.com> References: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> <13pqbvn8ckilnfc@corp.supernews.com> Message-ID: <479dc95e$0$9103$9b4e6d93@newsspool2.arcor-online.net> Steven D'Aprano wrote: >> I'm not sure I'm following you here. So a "chromosome" is bit of >> functionality, right? So basically it is a function. So my advice would >> be to write these functions and store it to the "indivuals"-list like >> so: > > No, a chromosome is a bit of *data*: a noun, not a verb. Read these bits > again: > > "Individuals HAVE what's called a chromosome - a SPECIFICATION of what it > contains. For example, common chromosomes are BIT STRINGS, ..." > Oh, OK. I *sort of* got this. Sort of. My reasoning was that these functions would return their associated "representation" upon being called. Which makes not much sense, especially after your explanation. > Some background which may help you understand what the OP is asking for. > > [snip little GA-intro] > Thanks Steven, that sure was useful. I think I now have a new toy hammer. I'm sure I'll see myself looking for toy nails everywhere over the next few weeks. :) /W From sjmachin at lexicon.net Sat Jan 19 06:38:49 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jan 2008 03:38:49 -0800 (PST) Subject: Excess whitespace in my soup Message-ID: <48eb8853-91b3-4c43-8014-a0c624e4c6e7@t1g2000pra.googlegroups.com> I'm trying to recover the original data from some HTML written by a well-known application. Here are three original data items, in Python repr() format, with spaces changed to tildes for clarity: u'Saturday,~19~January~2008' u'Line1\nLine2\nLine3' u'foonly~frabjous\xa0farnarklingliness' Here is the HTML, with spaces changed to tildes, angle brackets changed to square brackets, omitting \r\n from the end of each line, and stripping a large number of attributes from the [td] tags. ~~[td]Saturday,~19 ~~January~2008[/td] ~~[td]Line1[br] ~~~~Line2[br] ~~~~Line3[/td] ~~[td]foonly ~~frabjous farnarklingliness[/td] Here are the results of feeding it to ElementSoup: >>> import ElementSoup as ES >>> elem = ES.parse('ws_soup1.htm') >>> from pprint import pprint as pp >>> pp([(e.tag, e.text, e.tail) for e in elem.getiterator()]) [snip] (u'td', u'Saturday, 19\n January 2008', u'\n'), (u'td', u'Line1', u'\n'), (u'br', None, u'\n Line2'), (u'br', None, u'\n Line3'), (u'td', u'foonly\n frabjous\xa0farnarklingliness', u'\n')] I'm happy enough with reassembling the second item. The problem is in reliably and correctly collapsing the whitespace in each of the above five elements. The standard Python idiom of u' '.join(text.split()) won't work because the text is Unicode and u'\xa0' is whitespace and would be converted to a space. Should whitespace collapsing be done earlier? Note that BeautifulSoup leaves it as   -- ES does the conversion to \xa0 ... Does anyone know of an html_collapse_whitespace() for Python? Am I missing something obvious? Thanks in advance, John From steve at REMOVE-THIS-cybersource.com.au Fri Jan 25 06:09:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 25 Jan 2008 11:09:39 -0000 Subject: When is min(a, b) != min(b, a)? References: <13pi8fiiqgljdb5@corp.supernews.com> Message-ID: <13pjgrj540qt98a@corp.supernews.com> On Fri, 25 Jan 2008 07:57:13 +0000, Antoon Pardon wrote: >> But if you consider that having "x is not smaller than y" be equivalent >> to "x is greater than or equal to y" is more important than forcing a >> boolean answer in the first place, then you need something to signal >> Undefined, and an exception is the right solution unless you have >> multi- valued logic system (True, False, Maybe, Undefined, ...) > > Why should we consider that? It's a value judgement. Ask the Apple and IBM engineers and mathematicians. Personally, I think it is more useful to be able to assume that if x is not less than y, it must be greater or equal to instead ("completeness"), than it is to have a guarantee that x < y will never raise an exception. Having said that, I think the opposite holds for sorting and calculating the min() and max() of floats. Sorting should push the NaNs to one end of the list (I don't care which) while min() and max() should ignore NaNs and only raise an exception if all the arguments are NaNs. > The world is full of partial orders. In > python we have sets and a partial order is perfectly mathematically > sound. Sure, we could define floats to have any sort of order we want. We could define them to be ordered by their English spelling so that "five million point three" would be less than "zero point one". But is it useful? Putting aside sorting and max/min, what is the use-case for having comparisons with NaN succeed? What benefit will it give you? -- Steven From martin at v.loewis.de Fri Jan 25 02:20:47 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 25 Jan 2008 08:20:47 +0100 Subject: Python and binary compatibility In-Reply-To: <083456aa-1ed1-4455-a8ca-4bbaaba1ce00@i29g2000prf.googlegroups.com> References: <083456aa-1ed1-4455-a8ca-4bbaaba1ce00@i29g2000prf.googlegroups.com> Message-ID: <47998dcf$0$15586$9b622d9e@news.freenet.de> > All my troubles could apparently be fixed if I > could acquire a copy of VS 2003, but Microsoft has made it incredibly > difficult to find the download for it (I don't think it exists). > > Any suggestions? You can get copies of VS 2003 from ebay fairly easily. Regards, Martin From cokofreedom at gmail.com Mon Jan 28 05:49:58 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 28 Jan 2008 02:49:58 -0800 (PST) Subject: optional static typing for Python References: <479da584$0$25625$426a74cc@news.free.fr> <69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com> Message-ID: <6d586b84-743b-475b-90be-944fddb1941e@v46g2000hsv.googlegroups.com> On Jan 28, 11:42 am, "Russ P." wrote: > On Jan 28, 1:51 am, Bruno Desthuilliers > > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > Russ P. a ?crit :> A while back I came across a tentative proposal from way back in 2000 > > > for optional static typing in Python: > > > (snip) > > > > In any case, optional static typing in Python would help tremendously > > > here. The hardest part of automated conversion of Python to a > > > statically typed language is the problem of type inference. If the > > > types are explicitly declared, that problem obviously goes away. > > > (snip) > > > > Note also that, while "static" type checking would be ideal, > > > "explicit" typing would be a major step in the right direction > > > Lord have mercy(tm). > > What is that supposed to mean? > > Oh, I almost forgot. I'm supposed to sit here and be polite while > clueless dolts make wise cracks. Sorry, but I haven't yet mastered > that level of self-control. > > I would just like to thank you for reminding me about what losers hang > out perpetually on sites like this one, thinking they are in some kind > of real "community." Being reminded of that will help prevent me from > becoming such a loser myself. No, I didn't say that all the "regulars" > here are losers, but you most certainly are. > > Do you have a job? How about a life? Have you ever been "with" a > woman? How in the world is it that every time I come to this site, I > see your sorry ass hanging around yet again? I can't even imagine how > "pointless" your life must be if you have that much time to spend > "hanging around" on comp.lang.python -- and being an a--hole to boot. > > Yeah, Lord have mercy -- on losers like you. > > And thanks for reminding me to quit wasting so much time here. I've > been doing way too much of that lately. Why is it everyone has to resort to name calling and instantly being offended by everyone. If you don't think he reply has merit, then either simply ask him what he meant or ignore the post altogether. Your reply just flames the issue. I never get the reason why people feel the need to insult someone they feel has insulted them. That somehow by the re-doing the act they will solve the issue? Just move on. From dg.google.groups at thesamovar.net Sun Jan 20 12:41:32 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Sun, 20 Jan 2008 09:41:32 -0800 (PST) Subject: Just for fun: Countdown numbers game solver Message-ID: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Ever since I learnt to program I've always loved writing solvers for the Countdown numbers game problem in different languages, and so now I'm wondering what the most elegant solution in Python is. If you don't know the game, it's simple: you're given six randomly chosen positive integers, and a target (another randomly chosen positive integer), and you have to make the target using only the numbers you're given, and +,-,* and / (and any number of brackets you like). You're not allowed fractions as intermediate values. So, given 2, 3 and 5 say, and a target of 21, you could do (2+5)*3 = 21. So what's the best algorithm? And, what's the most elegant way to code it in Python? I've posted my most elegant version below (I have a faster version which is slightly less elegant). Can anyone do better? Refs: * This academic paper describes an implementation of an algorithm to solve the problem in Haskell. I found it after I'd written mine but it uses a very similar algorithm. http://www.cs.nott.ac.uk/~gmh/countdown.pdf * My web page where I put both versions of my code: http://thesamovar.net/countdownnumbers * The web page of the TV show the problem is based on: http://www.channel4.com/entertainment/tv/microsites/C/countdown/index.html My version: class InvalidExpressionError(ValueError): pass subtract = lambda x,y: x-y def add(x,y): if x<=y: return x+y raise InvalidExpressionError def multiply(x,y): if x<=y or x==1 or y==1: return x*y raise InvalidExpressionError def divide(x,y): if not y or x%y or y==1: raise InvalidExpressionError return x/y add.display_string = '+' multiply.display_string = '*' subtract.display_string = '-' divide.display_string = '/' standard_operators = [ add, subtract, multiply, divide ] class Expression(object): pass class TerminalExpression(Expression): def __init__(self,value,remaining_sources): self.value = value self.remaining_sources = remaining_sources def __str__(self): return str(self.value) def __repr__(self): return str(self.value) class BranchedExpression(Expression): def __init__(self,operator,lhs,rhs,remaining_sources): self.operator = operator self.lhs = lhs self.rhs = rhs self.value = operator(lhs.value,rhs.value) self.remaining_sources = remaining_sources def __str__(self): return '('+str(self.lhs)+self.operator.display_string +str(self.rhs)+')' def __repr__(self): return self.__str__() def ValidExpressions(sources,operators=standard_operators,minimal_remaining_sources=0): for value, i in zip(sources,range(len(sources))): yield TerminalExpression(value=value, remaining_sources=sources[:i]+sources[i+1:]) if len(sources)>=2+minimal_remaining_sources: for lhs in ValidExpressions(sources,operators,minimal_remaining_sources+1): for rhs in ValidExpressions(lhs.remaining_sources, operators, minimal_remaining_sources): for f in operators: try: yield BranchedExpression(operator=f, lhs=lhs, rhs=rhs, remaining_sources=rhs.remaining_sources) except InvalidExpressionError: pass def TargetExpressions(target,sources,operators=standard_operators): for expression in ValidExpressions(sources,operators): if expression.value==target: yield expression def FindFirstTarget(target,sources,operators=standard_operators): for expression in ValidExpressions(sources,operators): if expression.value==target: return expression raise IndexError, "No matching expressions found" if __name__=='__main__': import time start_time = time.time() target_expressions = list(TargetExpressions(923,[7,8,50,8,1,3])) target_expressions.sort(lambda x,y:len(str(x))-len(str(y))) print "Found",len(target_expressions),"solutions, minimal string length was:" print target_expressions[0],'=',target_expressions[0].value print print "Took",time.time()-start_time,"seconds." From thomas.pani at gmail.com Thu Jan 31 06:39:50 2008 From: thomas.pani at gmail.com (Thomas Pani) Date: Thu, 31 Jan 2008 12:39:50 +0100 Subject: dl module In-Reply-To: <11ed47ab0801310303w44b173a1sacfb317bb2737b3@mail.gmail.com> References: <11ed47ab0801310303w44b173a1sacfb317bb2737b3@mail.gmail.com> Message-ID: <47A1B386.8030504@gmail.com> There's a Debian bug for python2.2 at [1]. You can't use dl on a 64bit machine anyway, because sizeof(int) != sizeof(long). Cheers Thomas Pani [1] http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=141681 Nicola Jean wrote: > Hi everyone, > I'm having a problem compiling Python2.4.4 on a 64 bits machine. It > looks like I cannot compile the dl module. > When I run test_dl.py I get the following error message: > SystemError: module dl requires sizeof(int) == sizeof(long) == sizeof(char*) > > Do I need to put any special flag when I run the configure script? > Cheers > N.Jean From steve at REMOVE-THIS-cybersource.com.au Thu Jan 24 19:09:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 25 Jan 2008 00:09:58 -0000 Subject: When is min(a, b) != min(b, a)? References: Message-ID: <13pia6m7phe2n22@corp.supernews.com> On Thu, 24 Jan 2008 16:51:16 +0000, Pete Forman wrote: > Christian Heimes writes: > > > Antoon Pardon wrote: >>> That doesn't follow. The problem is not that x < nan returns False >>> because that is correct since x isn't smaller than nan. The problem is >>> cmp(x, nan) returning 1, because that indicates that x is greater than >>> nan and that isn't true. >> > > Please report the problem. cmp(), min() and max() don't treat NaNs > > right. I don't think that x < nan == False is the correct answer, > > too. But I've to check the IEEE 754 specs. IMHO < nan and > nan > > should raise an exception. > > I disagree with your last sentence. We are dealing with quiet NaNs > which should not raise exceptions. x < nan is well defined in IEEE, it > is false. I question that. The IEEE standard states that comparisons involving NaNs are unordered and should signal INVALID. What that means at the high level of x < NAN (etc.) isn't clear. I'm having a lot of trouble finding the canonical IEEE-754 standard, so I'm forced to judge by implementations and third party accounts. For example, this is what IBM says: http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/ com.ibm.xlf101l.doc/xlfopg/fpieee.htm [quote] The IEEE standard defines several exception conditions that can occur: ... INVALID Operations are performed on values for which the results are not defined. These include: Operations on signaling NaN values ... Comparisons involving NaN values [end quote] Note that *only* sNaNs signal invalid on arithmetic operations, but *both* types of NaNs signal invalid on comparisons. The same page also lists a table showing the result of such signals. I won't reproduce the whole table, but it states that the INVALID signal results in a NaN if exceptions are disabled, and no result (naturally) if exceptions are enabled. SANE (Standard Apple Numerics Environment) and Apple's PowerPC Numerics also do the same. See for example: http://developer.apple.com/documentation/mac/PPCNumerics/ PPCNumerics-37.html [quote] ...when x or y is a NaN, x < y being false might tempt you to conclude that x >= y, so PowerPC Numerics signals invalid to help you avoid the pitfall. [end quote] Regardless of deep philosophical questions about truth, that's a great example of Practicality Beats Purity. And some of us think that raising an exception would not only be more practical, but also more pure as well. -- Steven From dickinsm at gmail.com Mon Jan 28 10:07:08 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 28 Jan 2008 07:07:08 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: <13pi8fiiqgljdb5@corp.supernews.com> <13pjgrj540qt98a@corp.supernews.com> Message-ID: <5633527c-579b-4978-acfd-20dfff7d852c@n20g2000hsh.googlegroups.com> On Jan 28, 6:50 am, Antoon Pardon wrote: > People who somehow made it clear they know how to work with inf, and > NaN results, would get silent NaN where no exceptions would be thrown. One other thing: there's an excellent starting point for considering how things should work, in the form of the Decimal type. This does exactly what you suggest: by default, users get Python exceptions instead of NaNs and/or infinities, but the user can override the defaults to switch off the various traps (Overflow, Invalid, etc.) and work directly with NaNs and infinities if (s)he prefers. Note also that decimal.py runs to over 5000 lines of (Python) code! And that's without having to deal with the vagaries of the C-compiler/ library/OS/hardware, since everything's implemented directly in Python. A surprisingly small amount of that code is actually 'real' mathematics: most of it is devoted to dealing correctly with infinities, NaNs, signed zeros, subnormals, `ideal' exponents, traps, flags, etc. Mark From cybergrind at gmail.com Mon Jan 14 06:11:41 2008 From: cybergrind at gmail.com (cybergrind at gmail.com) Date: Mon, 14 Jan 2008 03:11:41 -0800 (PST) Subject: (bit)torrent source code help References: Message-ID: Hi, Try to use ABC. it based on bittornado Thnx From musiccomposition at gmail.com Fri Jan 18 20:41:47 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 18 Jan 2008 17:41:47 -0800 (PST) Subject: Unique thread ID References: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> Message-ID: <97c1bc57-5caf-4fa5-96d7-f6847db9e18c@f10g2000hsf.googlegroups.com> On Jan 18, 2:31 am, Christian Heimes wrote: > Benjamin wrote: > > Is there a way to obtain a unique ID for the current thread? I have an > > object that I need to store local thread data in, and I don't want to > > use threading.local because each thread might have multiple instances > > of my object. > > threading.get_ident() but please use threading.local. Nobody is going to > stop you if you use a list or dict in threading.local. then, I have to figure out how to represent an instance of my object in threading.local. (The data also won't be garbage collect when my object is, will it?) I think the unique id is elegant in this case. > > Christian From Ira.Kovac at gmail.com Thu Jan 24 14:18:45 2008 From: Ira.Kovac at gmail.com (Ira.Kovac at gmail.com) Date: Thu, 24 Jan 2008 11:18:45 -0800 (PST) Subject: Sorting Large File (Code/Performance) Message-ID: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> Hello all, I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like to sort based on first two characters. I'd greatly appreciate if someone can post sample code that can help me do this. Also, any ideas on approximately how long is the sort process going to take (XP, Dual Core 2.0GHz w/2GB RAM). Cheers, Ira From pavlovevidence at gmail.com Sat Jan 26 03:19:12 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 26 Jan 2008 00:19:12 -0800 (PST) Subject: Generational Interfaces References: <1b7b3b47-72f0-4a5d-9185-4903e75dba47@d70g2000hsb.googlegroups.com> Message-ID: <87dfcd78-13ce-4c91-a6a8-8fcdb1edc07b@s8g2000prg.googlegroups.com> On Jan 26, 3:04 am, Paddy wrote: > I thought a major use of an interface is to allow separate development > that comes together at the interface. If so then such fluid interface > changing would scupper separate development. Yes, this wouldn't be appropriate for that particular use. Carl Banks From gagsl-py2 at yahoo.com.ar Mon Jan 21 16:19:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 19:19:14 -0200 Subject: problem deriving form type long References: <47950186.1040707@vtxmail.ch> Message-ID: En Mon, 21 Jan 2008 18:33:10 -0200, Frederic Rentsch escribi?: > Hi, here's something that puzzles me: > > >>> class Fix_Point (long): > def __init__ (self, l): > long.__init__ (self, l * 0x10000): > > >>> fp = Fix_Point (99) > >>> fp > 99 You have to override __new__, not __init__. Immutable types like numbers and tuples don't use __init__. See http://docs.python.org/ref/customization.html > (P.S. I am not currently a subscriber. I was and had to bail out when I > couldn't handle the volume anymore. To subscribe just to post one > question doesn't seem practical at all. So, I don't even know if this > message goes through. In case it does, I would appreciate a CC directly > to my address, as I don't think I can receive the list. Thanks a > million.) You can read this thru the Google Groups interfase: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ade1fdc42c5380b8/ or using Gmane: http://thread.gmane.org/gmane.comp.python.general/555822 -- Gabriel Genellina From greg.johnston at gmail.com Mon Jan 21 17:44:09 2008 From: greg.johnston at gmail.com (Greg Johnston) Date: Mon, 21 Jan 2008 14:44:09 -0800 (PST) Subject: PyGTK, Glade, and ComboBoxEntry.append_text() Message-ID: <4066a33f-6293-48e3-a48c-66af699d0eb9@i29g2000prf.googlegroups.com> Hey all, I'm a relative newbie to Python (switched over from Scheme fairly recently) but I've been using PyGTK and Glade to create an interface, which is a combo I'm very impressed with. There is, however, one thing I've been wondering about. It doesn't seem possible to modify ComboBoxEntry choice options on the fly--at least with append_text(), etc--because they were not created with gtk.combo_box_entry_new_text(). Basically, I'm wondering if there's any way around this. Thank you, Greg Johnston From asmodai at in-nomine.org Sat Jan 12 03:58:21 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 12 Jan 2008 09:58:21 +0100 Subject: converting JSON to string In-Reply-To: References: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> <13og5g06rvrtefa@corp.supernews.com> Message-ID: <20080112085821.GI75977@nexus.in-nomine.org> -On [20080112 08:38], Gowri (gowricp at gmail.com) wrote: >Actually, I have one other problem after all this. I see that if I try >to construct JSON output as above, it is of the form >[{'isbn': u'1-56592-724-9', 'title': u'The Cathedral & the Bazaar'}, >{'isbn': u'1-56592-051-1', 'title': u'Making TeX Work'}] >The extra 'u' seems to causing syntax error in JavaScript which is not >able to parse this response string. Any idea how I can fix this? JSON does not support Unicode in the sense of allowing raw Unicode codepoints. Instead JSON uses a \uNNNN scheme to encode Unicode characters (a bit flawed to limit it to four hexadecimal digits though, it leaves the whole CJK Unified Ideographs Extension B out of scope.). I use simplejson along with lxml/ElementTree for my JSON<>XML needs. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Any road leads to the end of the world... From guyon.moree at gmail.com Thu Jan 31 08:32:38 2008 From: guyon.moree at gmail.com (=?ISO-8859-1?Q?Guyon_Mor=E9e?=) Date: Thu, 31 Jan 2008 05:32:38 -0800 (PST) Subject: Executing other python code References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: <1451cb46-b3c0-4250-8137-62d2b39d69c0@s13g2000prd.googlegroups.com> > One simple solution would be to forbid import statements in the > scripts, to import the scripts as modules and inject whatever > functions you want them to be able to use in the module's namespace. how do you 'forbid' imports? Guyon http://gumuz.nl From donn.ingle at gmail.com Sun Jan 13 12:28:54 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 19:28:54 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A4408.2090805@v.loewis.de> References: <200801131550.50119.donn.ingle@gmail.com> <478A4408.2090805@v.loewis.de> Message-ID: <200801131928.54459.donn.ingle@gmail.com> > No. It may use replacement characters (i.e. a question mark, or an empty > square box), but if you don't see such characters, then the terminal has > successfully decoded the file names. Whether it also correctly decoded > them is something for you to check (i.e. do they look right?) Okay. So, the picture I get is: *If* my locale *happens* to be the right one then the filename will appear properly. If it does not cover that file, then that filename will appear with ? marks in the name. Because I use en_ZA.utf8 it's doing a very good job of decoding a wide variety of filenames and therefore I rarely see ? characters. What happens if there is a filename that cannot be represented in it's entirety? i.e. every character is 'replaced'. Does it simply vanish, or does it appear as "?????????" ? :) I spent an hour trying to find a single file on the web that did *not* have (what seemed like) ascii characters in it and failed. Even urls on Japanese websites use western characters ( a tcp/ip issue I suspect). I was hoping to find a filename in Kanji (?) ending in .jpg or something so that I could download it and see what my system (and Python) made of it. Thanks again, \d -- "Life results from the non-random survival of randomly varying replicators." -- Richard Dawkins Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From hniksic at xemacs.org Tue Jan 8 09:42:40 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 08 Jan 2008 15:42:40 +0100 Subject: use fileinput to read a specific line References: <6f2db44c-2641-47cb-ab24-4177ccc96d6e@m77g2000hsc.googlegroups.com> <13o637afk4mql0c@corp.supernews.com> <36e49a53-8e56-4847-a792-5032ea204a8e@l6g2000prm.googlegroups.com> <13o6tldft8suj83@corp.supernews.com> Message-ID: <87ve64l6ov.fsf@mulj.homelinux.net> Fredrik Lundh writes: > From what I can tell, Java's GC automatically closes file streams, > so Jython will behave pretty much like CPython in most cases. The finalizer does close the reclaimed streams, but since it is triggered by GC, you have to wait for GC to occur for the stream to get closed. That means that something like: open('foo', 'w').write(some_contents) may leave 'foo' empty until the next GC. Fortunately this pattern is much rarer than open('foo').read(), but both work equally well in CPython, and will continue to work, despite many people's dislike for them. (For the record, I don't use them in production code, but open(...).read() is great for throwaway scripts and one-liners.) > I sure haven't been able to make Jython run out by file handles by > opening tons of files and discarding the file objects without > closing them. Java's generational GC is supposed to be quick to reclaim recently discarded objects. That might lead to swift finalization of open files similar to what CPython's reference counting does in practice. It could also be that Jython internally allocates so many Java objects that the GC is triggered frequently, again resulting in swift reclamation of file objects. It would be interesting to monitor (at the OS level) the number of open files maintained by the process at any given time during the execution of such a loop. From Lie.1296 at gmail.com Sun Jan 13 09:14:08 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 13 Jan 2008 06:14:08 -0800 (PST) Subject: Exceptions - How do you make it work like built-in exceptions? Message-ID: <7888e20f-0775-46c4-a6e2-3fc3825c5145@e23g2000prf.googlegroups.com> A built-in exceptions, when raised, would print traceback that points out the offending code, like this: Traceback (most recent call last): File "F:\dir\code.py", line 43, in a = 1/0 <<<--- ZeroDivisionError: integer division or modulo by zero a user-made exception, when raised, would print traceback that points out the code that raises the exception Traceback (most recent call last): File "F:\dir\code.py", line 48, in raise SomeException('Some Exception Message') <<<--- SomeException: Some Exception Message which is generally of little use (yeah, it's possible to trace the code from the line number, but sometimes it might not be that easy, cause the line number is (again) the line number for the raising code instead of the offending code) The sample exception was generated from this code: #### class SomeException(Exception): pass try: a = 1/0 except: raise SomeException('Some Exception Message') #### Is it possible to make the user-made exception points out the offending code? From socyl at 987jk.com.invalid Thu Jan 10 10:22:37 2008 From: socyl at 987jk.com.invalid (kj) Date: Thu, 10 Jan 2008 15:22:37 +0000 (UTC) Subject: ISO books of official Python docs References: fm38qu$6c7$1@reader2.panix.com <966c993a-2aa6-4724-852a-49d8da686675@k2g2000hse.googlegroups.com> Message-ID: In <966c993a-2aa6-4724-852a-49d8da686675 at k2g2000hse.googlegroups.com> gordyt writes: >Howdy kynnjo, >> Is it possible to buy the official Python docs in book form? If >> so, I'd very much appreciate the name(s) and author(s) of the >> book(s). >I haven't seen them in print form, but you can download PDF's from >here: >http://docs.python.org/download.html Thanks for the link. With the name of the manual on hand I was able to find a printed version of it (ISBN: 0954161785). A mere 144 pages, and for under $15. Sweeeeet! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From danebarney at gmail.com Tue Jan 1 17:35:14 2008 From: danebarney at gmail.com (Jugdish) Date: Tue, 1 Jan 2008 14:35:14 -0800 (PST) Subject: confusion about package/module imports References: <13nlc7fecs63099@corp.supernews.com> Message-ID: Thanks very much for your helpful response! > You'll see that b is executed (making module __main__), > (1) it imports pkg.subpkg.a, > (2) which is accomplished by importing pkg (successfully), > (3) then by importing pkg.subpkg > (4) which imports pkg.subpkg.a (successfully) > (5) and then imports pkg.subpkg.b > (6) which then attempts to import pkg.subpkg.a What I'm not really understanding here is why this fails at lines (5) and (6). If pkg.subpkg.a has already been successfully imported at line (4), then (6) should be detected as a duplicate import and just be skipped, right? So the import at line (5) should succeed. From paul at boddie.org.uk Thu Jan 31 11:21:07 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 31 Jan 2008 08:21:07 -0800 (PST) Subject: Problems installing Python on server References: Message-ID: On 28 Jan, 22:28, Yansky wrote: > I asked my hosting company if they would upgrade Python on my server > to the latest version. They responded with: > > "Sorry no. We tend to stick with what comes packaged with the unix > distribution to ease maintenance issues. Which version are they running, by the way? > There is nothing stopping you from running your own version of python > from within your own account. Download the source and compile it and > install it into your own space. Adjust the fist line of your python > scripts to reflect the location of YOUR python binary: > > #! /home/youraccount/yourlibs/python > > and you should be all set." This sounds like reasonable advice, I suppose. > The build instructions for Python are: > To start building right away (on UNIX): type "./configure" in the > current directory and when it finishes, type "make". This creates an > executable "./python"; to install in usr/local, first do "su root" and > then "make install". > > The problem is, I don't have root access to the server so I can't do > the "make install". I think that the "su root" stuff is just there in anticipation of people trying to configure, build and install Python without thinking too hard about it and then finding that they get lots of errors about installing into places they don't have permissions for. If you're installing into a different location, you only need to have permissions to write to that location. > I have ubuntu on my computer, but from what I understand I can't > compile it on that and upload it because the server > runs Red Had and the ./configure would have made it incompatible > right? If you have shell access on the hosting service and they have compilers available, you can just do the build and install there. Building on your own computer and having the executable work on the server is likely to be more difficult due to the usual library versioning issues that arise between distributions - it'd be interesting to see if anyone can suggest a solution for this involving the LSB tools. > So how can I build Python without root access? Something like this: mkdir /home/youraccount/apps # optional - see below ./configure --prefix=/home/youraccount/apps make make install Here, the apps directory in your home directory will contain the usual UNIX directory structure that you would otherwise see in /usr: directories such as bin, lib, share (probably), and so on. You'll find the python executable as /home/youraccount/apps/bin/python. Some people like to mimic the full UNIX structure and have a usr directory (either underneath or instead of the apps directory employed above); others prefer to have the bin, lib (and other directories) in their home directory (thus omitting the apps directory); you get to choose. ;-) I hope this helps! Paul From donn.ingle at gmail.com Sun Jan 13 06:51:58 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 13:51:58 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <4789F559.1090703@v.loewis.de> References: <200801131224.10263.donn.ingle@gmail.com> <4789F559.1090703@v.loewis.de> Message-ID: <200801131351.59005.donn.ingle@gmail.com> Martin, > Yes. It does so when it fails to decode the byte string according to the > file system encoding (which, in turn, bases on the locale). That's at least one way I can weed-out filenames that are going to give me trouble; if Python itself can't figure out how to decode it, then I can also fail with honour. > > I will try the technique given > > on:http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html > >#guessing-the-encoding Perhaps that will help. > I would advise against such a strategy. Instead, you should first > understand what the encodings of the file names actually *are*, on > a real system, and draw conclusions from that. I don't follow you here. The encoding of file names *on* a real system are (for Linux) byte strings of potentially *any* encoding. os.listdir() may even fail to grok some of them. So, I will have a few elements in a list that are not unicode, I can't ask the O/S for any help and therefore I should be able to pass that byte string to a function as suggested in the article to at least take one last stab at identifying it. Or is that a waste of time because os.listdir() has already tried something similar (and prob. better)? > I notice that this doesn't include "to allow the user to enter file > names", so it seems there is no input of file names, only output. I forgot to mention the command-line interface... I actually had trouble with that too. The user can start the app like this: fontypython /some/folder/ or fontypython SomeFileName And that introduces input in some kind of encoding. I hope that locale.getprefferedencoding() will be the right one to handle that. Is such input (passed-in via sys.argv) in byte-strings or unicode? I can find out with type() I guess. As to the rest, no, there's no other keyboard input for filenames. There *is* a 'filter' which is used as a regex to filter 'bold', 'italic' or whatever. I fully expect that to give me a hard time too. > Then I suggest this technique of keeping bytestring/unicode string > pairs. Use the Unicode string for display, and the byte string for > accessing the disc. Thanks, that's a good idea - I think I'll implement a dictionary to keep both and work things that way. > I see no problem with that: > >>> u"M\xd6gul".encode("ascii","ignore") > 'Mgul' > >>> u"M\xd6gul".encode("ascii","replace") > 'M?gul' Well, that was what I expected to see too. I must have been doing something stupid. \d From kyosohma at gmail.com Fri Jan 11 16:51:37 2008 From: kyosohma at gmail.com (Mike) Date: Fri, 11 Jan 2008 13:51:37 -0800 (PST) Subject: Graphics Module References: Message-ID: On Jan 11, 3:31 pm, "Gabriel" wrote: > Hi all ! > > I'm developing a math program that shows graphics of functions. > I would hear suggestions about the way of drawing 2D . > > Thanks a lot for your answers. > > - Gabriel - That's not a very descriptive question, however most people talk about matplotlib for graphing and 2D drawings. Here's a few links on graphing in Python: http://matplotlib.sourceforge.net/ http://wiki.python.org/moin/PythonGraphApi http://alpha-leonis.lids.mit.edu/nlp/pygraph/ http://boost.org/libs/graph/doc/python.html http://www.python.org/doc/essays/graphs.html Some of these may have dependencies, such as numpy or scipy. Be sure to read the docs for full details either way. Mike From fredrik at pythonware.com Fri Jan 4 15:09:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 21:09:49 +0100 Subject: Question on os.tempnam() vulnerability In-Reply-To: References: Message-ID: cameronwong88 at gmail.com wrote: > Does any one know what kind of security risk these message are > suggesting? > >>>> f = os.tempnam() > __main__:1: RuntimeWarning: tempnam is a potential security risk to > your program >>>> f > '/tmp/filed4cJNX' > >>>> g = os.tmpnam() > __main__:1: RuntimeWarning: tmpnam is a potential security risk to > your program >>>> g > '/tmp/fileENAuNw' you get a name instead of a file, so someone else can create that file after you've called tempnam/tmpnam, but before you've actually gotten around to create the file yourself. which means that anyone on the machine might be able to mess with your application's data. use the functions marked as "safe" in the tempfile module instead. From wdraxinger at darkstargames.de Sun Jan 20 13:09:39 2008 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sun, 20 Jan 2008 19:09:39 +0100 Subject: HTTP POST uploading large files References: <7xwsq4zahb.fsf@ruckus.brouhaha.com> Message-ID: <3cfc65-ohe.ln1@darkstargames.dnsalias.net> Paul Rubin wrote: > Wolfgang Draxinger writes: >> Am I just blind for some urllib2/httplib feature, or some >> other library? Or do I really have to fiddle around with >> sockets myself (I hope not...). > > I did something like that by just opening a socket and writing > the > stuff with socket.sendall. It's only about 5 lines of code and > it's pretty straightforward. Well, for YouTube you've to fiddle around with cookies, form/multipart data and stuff like that. It's a bit more than just opening a socket, there's some serious HTTP going on. However I found a solution: The curl program, that comes with libcurl and can be found on most *nix systems allows to do pretty sophisticated HTTP requests, among them also sending files by POST. So instead of using urllib2 or sockets from Python, now my program just generates the appropriate calls to curl, provides the in memory storage of cookies and does the neccesary HTML parsing*. Wolfgang Draxinger *) YouTube uploads videos in a two part process: First you set the various video options, in return you get a form with some hidden input fields, some of them providing a handle to the already sent video information. That data has to be extracted from the form and be put into the POST that also transfers the video file. -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From faber at linuxnj.com Fri Jan 11 22:32:28 2008 From: faber at linuxnj.com (Faber J. Fedor) Date: Fri, 11 Jan 2008 22:32:28 -0500 Subject: Newbie Q: modifying SQL statements In-Reply-To: <20080111182956.64466688@bhuda.mired.org> References: <20080111013206.GA18259@neptune.faber.nom> <20080110225352.2c112555@bhuda.mired.org> <20080111231141.GA24213@neptune.faber.nom> <20080111182956.64466688@bhuda.mired.org> Message-ID: <20080112033228.GB24213@neptune.faber.nom> On 11/01/08 18:29 -0500, Mike Meyer wrote: > It is a 2.5 feature, though. I was beginning to wonder of that was the case. > I converted all my clients to 2.5.1, > shortly after it was available, and haven't used anything older > since. Sorry 'bout that. No prob. -- Regards, Faber Fedor -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From kyosohma at gmail.com Tue Jan 15 10:21:50 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 15 Jan 2008 07:21:50 -0800 (PST) Subject: A question about event handlers with wxPython References: <478c3bb2$0$5150$4c368faf@roadrunner.com> <2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com> <478ccbc3$0$11000$4c368faf@roadrunner.com> Message-ID: <965596ac-466b-4ff7-a6c5-53b929c56376@i29g2000prf.googlegroups.com> On Jan 15, 9:04 am, "Erik Lind" wrote: > > def HandleSomething(self, event): > > generating_control = event.GetEventObject() > > print generating_control > > > HTH, > > Thank you.That is what I was looking for, but as often seems the case, one > thing exposes another. Is there any way to listen for events without > specifically binding to a handler (it seems one cannot bind an event to two > handlers?)? One could do so with globals, but I'm trying to avoid that. > > For example, "press any button to stop" > > def HandleSomething(self, event): > ................. > while generating_control: == something: > run > else > stop There are a number of ways to handle this. You could just bind the parent to the handler. Something like this: self.Bind(wx.EVT_BUTTON, self.onStop) This will bind all button presses to the onStop handler. You could also do something like this: self.Bind(wx.EVT_BUTTON, self.onBtnStop) def onBtnStop(self, event): #do something event.Skip() By calling the Skip() method, it will propagate the event and look for another handler, which in this case would be the onStop handler. On Windows, you will most likely need to make a wx.Panel be the parent of the rest of the widgets to have this effect. My complete test code is below. import wx class Closer(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, title='Test Frame') panel = wx.Panel(self, -1) sizer = wx.BoxSizer(wx.VERTICAL) btn1 = wx.Button(panel, wx.ID_ANY, 'Button 1') btn2 = wx.Button(panel, wx.ID_ANY, 'Button 2') btn3 = wx.Button(panel, wx.ID_ANY, 'Button 3') sizer.Add(btn1) sizer.Add(btn2) sizer.Add(btn3) self.Bind(wx.EVT_BUTTON, self.onDone) self.Bind(wx.EVT_BUTTON, self.onStop, btn1) panel.SetSizer(sizer) def onStop(self, event): print 'Stop!' event.Skip() def onDone(self, event): print 'Done!' if __name__ == '__main__': app = wx.PySimpleApp() Closer().Show() app.MainLoop() FYI: There is an excellent wxPython group that you can join over on the wxPython.org website. Mike From asmodai at in-nomine.org Tue Jan 8 04:03:56 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 10:03:56 +0100 Subject: python syntax:urgent In-Reply-To: <645055.89441.qm@web45511.mail.sp1.yahoo.com> References: <645055.89441.qm@web45511.mail.sp1.yahoo.com> Message-ID: <20080108090356.GI75977@nexus.in-nomine.org> -On [20080108 09:42], mpho raborife (mraborife at yahoo.com) wrote: >subprocess.Popen(["gmmscore", "-i", Input, "-l", List, "-t", > modeltype, "-m", str(mixture), "-d", str(dimension), "-v", str(vfloor), > "-n", str(number), "-r", str(results)]) "gmmscore", "-i" seems a bit silly, why not just "gmmscore -i"? You can always do something like (assuming all arguments are strings, adjust accordingly): s = "gmmscore -i %s -l %s -t %s -m %s -d %s -v %s -n %s -r %s" % (Input, List, modeltype, str(mixture), str(dimension), str(vfloor), str(number), str(results)) subprocess.Popen([s]) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Few are those who see with their own eyes and feel with their own hearts... From george.sakkis at gmail.com Fri Jan 11 17:05:11 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 14:05:11 -0800 (PST) Subject: Import and execfile() Message-ID: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> I maintain a few configuration files in Python syntax (mainly nested dicts of ints and strings) and use execfile() to read them back to Python. This has been working great; it combines the convenience of pickle with the readability of Python. So far each configuration is contained in a single standalone file; different configurations are completely separate files. Now I'd like to factor out the commonalities of the different configurations in a master config and specify only the necessary modifications and additions in each concrete config file. I tried the simplest thing that could possibly work: ====================== # some_config.py # master_config.py is in the same directory as some_config.py from master_config import * # override non-default options foo['bar']['baz] = 1 ... ====================== # trying to set the configuration: CFG = {} execfile('path/to/some_config.py', CFG) Traceback (most recent call last): ... ImportError: No module named master_config I understand why this fails but I'm not sure how to tell execfile() to set the path accordingly. Any ideas ? George From stefan.behnel-n05pAM at web.de Thu Jan 24 16:39:57 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 24 Jan 2008 22:39:57 +0100 Subject: Sorting Large File (Code/Performance) In-Reply-To: <479904BD.9090400@web.de> References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <479904BD.9090400@web.de> Message-ID: <479905AD.6040802@web.de> Stefan Behnel wrote: > Ira.Kovac at gmail.com wrote: >>> What are you going to do with it after it's sorted? >> I need to isolate all lines that start with two characters (zz to be >> particular) > > "Isolate" as in "extract"? Remove the rest? > > Then why don't you extract the lines first, without sorting the file? (or sort > it afterwards if you still need to). That would heavily cut down your memory > footprint. Just for fun, this is what I meant: for utf8_line in open(filename, 'rb'): if utf8_line.startswith('zz'): print utf8_line Stefan From lists at cheimes.de Fri Jan 18 12:20:28 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 18 Jan 2008 18:20:28 +0100 Subject: Bug in __init__? In-Reply-To: References: Message-ID: Zbigniew Braniecki wrote: > Any clue on what's going on here, and/if where I should report it? Congratulations! You've stumbled over a well known gotcha. Most newbies fall for the trap. class A: def __init__ (self, val=[]): print val self.lst = val val is created only *once* and shared across all instaces of A. Christian From washakie at gmail.com Tue Jan 15 15:15:05 2008 From: washakie at gmail.com (washakie) Date: Tue, 15 Jan 2008 12:15:05 -0800 (PST) Subject: MySQL-python-1.2.2 install with no mysql In-Reply-To: <14837853.post@talk.nabble.com> References: <14836669.post@talk.nabble.com> <14837853.post@talk.nabble.com> Message-ID: <14845579.post@talk.nabble.com> Thank you... after: %yum install mysql* I was able to build and install mysql-python -- View this message in context: http://www.nabble.com/MySQL-python-1.2.2-install-with-no-mysql-tp14836669p14845579.html Sent from the Python - python-list mailing list archive at Nabble.com. From thudfoo at opensuse.us Wed Jan 23 19:01:59 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Wed, 23 Jan 2008 16:01:59 -0800 Subject: Trouble writing to database: RSS-reader In-Reply-To: References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> <4794e0f9$0$4429$426a74cc@news.free.fr> <739742b0-7d3d-4039-b793-ccefae4be721@1g2000hsl.googlegroups.com> Message-ID: <3d881a310801231601w4dd08b95s62b1ba6b98c128ba@mail.gmail.com> On 1/23/08, Arne wrote: > On Jan 21, 11:25pm, "Gabriel Genellina" > wrote: > > En Mon, 21 Jan 2008 18:38:48 -0200, Arne escribi?: > > [...] > > This look very interesting! But it looks like that no documents is > well-formed! I've tried several RSS-feeds, but they are eighter > "undefined entity" or "not well-formed". This is not how it should be, > right? :) > Go to http://www.feedparser.org Download feedparser.py Read the documentation, at least.: you will find out a lot about working with rss. > -- > http://mail.python.org/mailman/listinfo/python-list From tavares at fe.up.pt Sun Jan 27 10:59:18 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Sun, 27 Jan 2008 07:59:18 -0800 (PST) Subject: Workshop "Medical Imaging Systems" within EUROMEDIA 2008 - Last Call for Papers Message-ID: <70c8b903-bd4e-4122-a823-dcbd39bed34a@s13g2000prd.googlegroups.com> ----------------------------------------------------------------------------------------------------------------------------------------- (Apologies for cross-posting) Workshop "Medical Imaging Systems" within EUROSIS EUROMEDIA 2008 April 9-11, 2008, University of Porto, Porto, Portugal http://www.eurosis.org/cms/index.php?q=node/461 We would appreciate if you could distribute this information by your colleagues and co-workers. ----------------------------------------------------------------------------------------------------------------------------------------- Dear Colleague, In recent years, extensive research has been performed to develop more and more efficient and powerful medical imaging systems. Such systems are crucial for medical specialists, allowing a deeper analysis and to understand what is going inside the human body, and therefore they play an essential role for adequate medical diagnosis and treatments. To accomplish efficient and powerful medical imaging systems, many research works have being done in many domains, like the ones related with medical image devices, signal processing, image processing and analysis, biomechanical simulation and data visualization. The main goal of the Workshop "Medical Imaging Systems" is to bring together researchers involved in the related domains, in order to set the major lines of development for the near future. Therefore, the proposed Workshop will consist of researchers representing various fields related to Medical Devices, Signal Processing, Computational Vision, Computer Graphics, Computational Mechanics, Scientific Visualization, Mathematics and Medical Imaging. The Workshop endeavours to contribute to obtain better solutions for more efficient and powerful medical imaging systems, and attempts to establish a bridge between clinicians and researchers from these diverse fields. The proposed Workshop will cover topics related with medical imaging systems, such as: image acquisition, signal processing, image processing and analysis, modelling and simulation, computer aided diagnosis, surgery, therapy, and treatment, computational bioimaging and visualization, software development, virtual reality and telemedicine systems and their applications. Due to your research activities in the field, we would like to invite you to submit a contributed paper. Your contribution is mostly welcomed and we would be honoured if you could participate in EUROMEDIA 2008. DEADLINE FOR PAPERS SUBMISSION: February 5, 2008 SCIENTIFIC COMMITTEE: Alberto De Santis, Universit? degli Studi di Roma "La Sapienza", Italy Ana Mafalda Reis, Instituto de Ci?ncias Biom?dicas Abel Salazar, Portugal Arrate Mu?oz Barrutia, University of Navarra, Spain Behnam Heidari, University College Dublin, Ireland Bernard Gosselin, Faculte Polytechnique de Mons, Belgium Chandrajit Bajaj, University of Texas, USA Christos E. Constantinou, Stanford University School of Medicine, USA Daniela Iacoviello, Universit? degli Studi di Roma "La Sapienza", Italy Dinggang Shen, University of Pennsylvania, USA Djemel Ziou, University of Sherbrooke, Canada Gerald Schaefer, Aston University, UK Jo?o Krug Noronha, Dr. Krug Noronha Clinic, Portugal Jo?o Manuel R. S. Tavares, Faculty of Engineering of University of Porto, Portugal Jo?o Paulo Costeira, Instituto Superior T?cnico, Portugal Jorge M. G. Barbosa, Faculty of Engineering of University of Porto, Portugal Lyuba Alboul, Sheffield Hallam University, UK Manuel Gonz?lez Hidalgo, Balearic Islands University, Spain Maria Elizete Kunkel, Universit?t Ulm, Germany M?rio Forjaz Secca, Universidade Nova de Lisboa, Portugal Miguel Angel L?pez, Faculty University of Ciego de Avila, Cuba Miguel Velhote Correia, Faculty of Engineering of University of Porto, Portugal Patrick Dubois, Institut de Technologie M?dicale, France Reneta Barneva, State University of New York, USA Renato M. Natal Jorge, Faculty of Engineering of University of Porto, Portugal Sabina Tangaro, University of Bari, Italy Valentin Brimkov, State University of New York, USA Yongjie Zhan, Carnegie Mellon University, USA For further details please see the conference website at: http://www.eurosis.org/cms/index.php?q=node/461 We are looking forward to see you in Porto next April. Kind regards, Jo?o Manuel R. S. Tavares University of Porto tavares at fe.up.pt www.fe.up.pt/~tavares From stef.mientki at gmail.com Tue Jan 1 15:07:12 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 01 Jan 2008 21:07:12 +0100 Subject: Some specific exec behavior ? In-Reply-To: References: <477A88D9.4090708@gmail.com> Message-ID: <477A9D70.1040103@gmail.com> Gabriel Genellina wrote: > En Tue, 01 Jan 2008 16:39:21 -0200, Stef Mientki > escribi?: > > >> I find 2 strange behaviors in exec-function, >> and I can't find anything in the documentation. >> (Python 2.4.3 Enthought edition) >> >> 1. A function definition may not span more than 1 line, e.g. >> This generates an exception: >> def _func (x,y): >> return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) >> >> while this works correct: >> def _func (x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) >> >> 2. an emtpy line at the end also generates an exception >> >> Is this behavior correct ? >> where should I find information about it ? >> > > It's correct; source lines must be separated by '\n' only (NOT '\r\n' as > in a Windows text file) and the last line must end in '\n'. > It's documented, but under the compile() built-in function: > http://docs.python.org/lib/built-in-funcs.html; perhaps the docs for exec > should refer there. > > Thanks Gabriel, that explains everything ! cheers, Stef From Lie.1296 at gmail.com Wed Jan 16 07:38:10 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 16 Jan 2008 04:38:10 -0800 (PST) Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> Message-ID: <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> On Jan 15, 9:00?pm, Bruno Desthuilliers wrote: > Lie a ?crit : > > > > > On Jan 7, 2:46 am, Bruno Desthuilliers > > wrote: > >> Lie a ?crit : > > >>> On Jan 5, 5:40 pm, MartinRineh... at gmail.com wrote: > >>>> Jeroen Ruigrok van der Werven wrote: > >>>>> Shouldn't this be: > >>>>> self.startLoc = start > >>>>> self.stopLoc = stop > >>>> Thanks! Of course it should. Old Java habits die slowly. > >>> No, seriously it isn't Java habits only, most other languages wouldn't > >>> need explicit calling of class name. > >> Where is the "explicit calling of class name" exactly ? > > > Perhaps I was a bit tired when writing that (I wouldn't understand > > what I wrote if I were you)... what I meant is most other languages > > doesn't usually enforce us to explicitly state the containing class > > name, which in python is generally called "self". > > 'self' (or whatever you name it) is not the "containing class name", Current instance is what I meant, thanks for pointing out the incorrect term I used. > it's the first argument of the function - which usually happens to be > the current instance when the function is used as a method. And that's the point, self (or anything you name it) is almost always the current instance and that makes it functionally the same as Me and this in VB and Java. > > Most other languages > > 1) automatically assign the containing class' object > > s/containing class' object/current instance/ > > > in a keyword > > (Java: this, VB: Me) behind the screen, > > That's not very far from what a Python method object does - > automatically assign the current instance to something. The difference > is that Python uses functions to implement methods (instead of having > two distinct contructs), so the only reliable way to "inject" the > reference to the current instance is to pass it as an argument to the > function (instead of making it pop from pure air). It isn't very far, but Python makes it obvious about the assignment (not behind the screen). > There are some benefits to this solution. One of them is the ability to > ? dynamically assign functions as methods. So if you do have some > function taking an object as first argument, you can easily turn it into > a method. Indeed, many languages doesn't allow dynamic assignment of function which makes having an automatic assignment of current instance to Me/ this possible and with minimal harm. > > and 2) automatically searches > > variable name in both the local variable table and the containing > > class variable table ?(so to refer to a class variable named var from a > > method inside the class, we only need to write var, not self.var as in > > python). > > This - as you know - cannot work well with Python's scoping rules and > dynamicity. Anyway, implicit object reference is definitively a > BadThing(tm) wrt/ readbility, specially with multiparadigm languages > (like Python or C++). Why do you think soooo many C++ shops impose the > m_something naming scheme ? Implicit object reference for the containing class has little harm, if a class is so complex that there are more than 10 class-level variable, then it is obvious that that class needs to be fragmented to smaller classes. Remembering less than 10 variable and avoiding naming collision among just 10 variable is not hard (and 10 is really too many, most classes should only use 2-4 variables), especially if you have a good IDE that employs Intellisense-like technology (IDLE has it). And it is always a Bad Thing(tm) to use the same name for two variable in the class and in function (which is the main and only source of possible ambiguity) in ANY language, even in Python. > Anyway, I actually know 3 languages (4 if C# works the same) that has > this implicit 'this' (or whatever the name) 'feature', and at least 5 > that don't. So I'm not sure that the "most other languages" qualifier > really applies to point 2 !-) What's this 5 languages? Are they a mainstream, high-level languages or lesser known, low-level languages? C-family, Java, and Basic are the Big Three of high-level programming language. > > In VB, Me is extremely rarely used, > > I used to systematically use it - like I've always systematically used > 'this' in C++ ?and Java. And that is what reduces readability. A proficient VB/C/Java programmer would frown upon the extra, unneeded garbage as they thought it was clear already that the variable refers to a class-level variable. It is a different story if, like Python, the use of self is enforced by the language, the self wouldn't be viewed as extra unnecessary garbage. > > in Python, self is all > > over the place. Well, there is positive and negative to both sides, > > convenience in VB, and flexibility in Python. > > As far as I'm concerned, there's *no* positive point in implicit object > reference, and there has never been (and before some paranoid nutcase > around accuse me of overzealous biggotry : I already held this very same > opinion years before I discovered Python). There is one major positive point: convenience and shorter code. (isn't that two?) As I've pointed out, there is little harm in class-level variable's implicit reference. > > Compare the following codes: > > VB.NET: > > Public Class A > > ? ? Dim var > > ? ? Public Function aFunction() > > ? ? ? ? return var > > Add three levels of inheritence and a couple globals and you'll find out > that readability count !-) It's the mental model that have to be adapted here, if the current class is inheriting from another class, you've got to think it as names from parent class as it is a native names, so you don't actually need to know where the variable comes from since knowing where it comes from is breaking the encapsulation (which, in Python is very weakly implemented, which favors flexibility in many cases[1]). [1] In Python, it is impossible to create a completely private variable, which is the reason why the mental model of these other languages doesn't fit Python. > In any non-trivial piece of C++ code, and unless the author either used > the explicit 'this' reference or the 'm_xxx' naming convention, you'll > have hard time figuring out where a given name comes from when browsing > a function's code. If you're used to the implicit naming scheme it's easy to know where a variable came from, if not the current scope, it's the class' scope and searching two short variable tables (SHORT! Creating complex classes is for stupid programmers[2]) at the same time isn't an expensive operation for human-being, especially if memoization is implemented. [2] I used to create an extremely complex classes when I was still green in programming, and that hits me back many times. Small, simple class is A Good Thing(tm). Class should use less than 10 variables, although the recommended number is 2-3 variables. Function names should be as little as possible, the use of overloading and overriding should be maximized. As a final note: I don't think implicit class reference is superior to explicit class reference, neither do I think explicit class reference is superior to implicit class reference. I think both have their own +s and -s. I only pointed out that implicit do have its benefits, depending on the language used (obviously Python wouldn't benefit from using implicit behavior, due to it being extremely dynamic). From grflanagan at yahoo.co.uk Wed Jan 30 11:37:41 2008 From: grflanagan at yahoo.co.uk (grflanagan) Date: Wed, 30 Jan 2008 08:37:41 -0800 (PST) Subject: Python noob SOS (any [former?] Perlheads out there?) References: Message-ID: <6099ab30-390d-4b38-bc8e-81ecb52e03a6@e25g2000prg.googlegroups.com> On Jan 29, 5:39 pm, kj wrote: [...] > It's not the Python syntax that I'm having problems with, but rather > with larger scale issues such as the structuring of packages, > techniques for code reuse, test suites, the structure of > distributions,... Python and Perl seem to come from different > galaxies altogether... > [...] > > I'd written a Perl module to facilitate the writing of scripts. > It contained all my boilerplate code for parsing and validating > command-line options, generating of accessor functions for these > options, printing of the help message and of the full documentation, > testing, etc. > > Of course, for Python now I don't have any of this, so I must write > it all from scratch, and the thing is *I don't even know where to > begin*! And meanwhile works needs to get done, projects finished, > etc. So naturally I revert to Perl, yadda-yadda-yadda, and the > Python project gets pushed back another week... > > In a way it's the usual story with learning a new language, but > I've taught myself new languages before. (After all, there was a > time when I didn't know Perl.) It's harder this time, somehow... > The journey of a thousand miles etc. For command line options I get a long way with this: [code python] def _getargs(): allargs = sys.argv[1:] args = [] kwargs = {} key = None while allargs: arg = allargs.pop(0) if arg.startswith('--'): key, arg = arg.split('=', 1) key = key[2:] elif arg.startswith('-'): key = arg[1:] if not allargs or allargs[0].startswith('-'): allargs.insert(0, 'yes') continue if key is None: args.append(arg) else: kwargs[key] = arg key = None return args, kwargs ARGS, KWARGS = _getargs() [/code] though obviously there's no validation. For testing see doctest module. For file and directory manipulation see os and shutil modules. The following is an abuse of docstrings, but shows some OO techniques: [code python] import inspect linesep = '\n' class TemplateBase(object): factory = None template = None verb = 'substitute' @classmethod def render(cls, **kws): if cls.template is None: cls.template = cls.factory(inspect.getdoc(cls)) return getattr(cls.template, cls.verb)(**kws) @classmethod def write(cls, fd, **kws): fd.write(linesep) fd.write(cls.render(**kws)) fd.write(linesep) @classmethod def writeiter(cls, fd, seq): for context in seq: cls.write(fd, **context) class StringTemplate(TemplateBase): import string factory = string.Template class SafeStringTemplate(StringTemplate): verb = 'safe_substitute' try: class TempitaTemplate(TemplateBase): import tempita factory = tempita.Template except ImportError: pass try: class MakoTemplate(TemplateBase): from mako.template import Template factory = Template verb = 'render' except ImportError: pass class StartJythonUnix(SafeStringTemplate): r""" #!/usr/bin/ksh java \ -Dpython.home=$jythonhome \ -classpath $jythonhome/jython.jar:$CLASSPATH \ org.python.util.jython.class """ class DefineLocalQueue(StringTemplate): """ DEFINE QLOCAL($qname) + DEFPSIST(YES) + DESCR('$descr') + STGCLASS('$stgclass') + MAXDEPTH ($maxdepth) """ class DeleteLocalQueue(TempitaTemplate): """ DELETE QLOCAL({{qname}}) """ import sys StartJythonUnix.write(sys.stdout, jythonhome="/home/dev/jython/ jython-2.1") from cStringIO import StringIO s = StringIO() DefineLocalQueue.write(s, name="AAA", descr="AAA", stgclass="AAA", maxdepth=100) DeleteLocalQueue.write(s, name="BBB", descr="BBB", stgclass="BBB", maxdepth=100) print s.getvalue() [/code] HTH Gerard From f.guerrieri at gmail.com Mon Jan 14 10:01:40 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Mon, 14 Jan 2008 16:01:40 +0100 Subject: csv add lines In-Reply-To: References: Message-ID: <79b79e730801140701p4df29f20g186c6840970cb8aa@mail.gmail.com> On Jan 14, 2008 3:52 PM, Alexandru Dumitrescu wrote: > > > Hi, > I'm new to this list and to python. > > I am wondering, am I able to make my program read the *.txt files from a > directory and > > to add, at the top of the file, three new lines which are stored in a *.csv > file? Maybe you are still not able to do it :-) But if you give a look at the csv module you probably will be in a short time. Just read http://docs.python.org/lib/module-csv.html where you will learn how to parse a csv file. bye, Francesco From Arao44 at gmail.com Tue Jan 22 01:38:16 2008 From: Arao44 at gmail.com (AK444) Date: Mon, 21 Jan 2008 22:38:16 -0800 (PST) Subject: Electronic and Computer Science video courses, No login, No fee Message-ID: Hi Guys Good news is 23 Electronic and Computer Science video courses are free, No login, No fee. All you need to have is real player installed on your PC. Electronics is at http://freevideolectures.com/electronics/circuits_and_electronics.php Computer Science is at http://freevideolectures.com/ComputerScience/Computer_System_Engineering.php Keep Learning.......... Bye From pavloutefkros at gmail.com Thu Jan 31 12:46:03 2008 From: pavloutefkros at gmail.com (pavloutefkros at gmail.com) Date: Thu, 31 Jan 2008 09:46:03 -0800 (PST) Subject: Python for mobiles Message-ID: <03e0ad28-e72c-4582-8518-b5cb07d408df@e10g2000prf.googlegroups.com> Hello, Is there any chance that i could compile python programs to java (.jar [java bytecode]) so that i could run them with full support (no interpreter) in a wireless device (talking about mobiles eg. nokia, ericsson). I am aware of jython, however i am not elegible of finding a proper article claiming wheather this ability is provided or not. Thanks in advance! From steve at REMOVE-THIS-cybersource.com.au Sat Jan 12 18:56:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 23:56:21 -0000 Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> Message-ID: <13oikt5eoorace6@corp.supernews.com> On Sat, 12 Jan 2008 15:47:05 -0500, Mike Meyer wrote: > There's an apparently common bug here: you don't want to pass super > self.__class__, but the class that the method is bound to. Given an instance method, is it possible to easily determine what class it is defined in? I thought the im_class attribute might do it, but it apparently just points to self.__class__. >>> class Foo(object): ... def foo(self): ... pass ... >>> class Bar(Foo): ... def bar(self): ... pass ... >>> Bar().bar.im_class # expecting Bar >>> Bar().foo.im_class # hoping for Foo -- Steven From over at thepond.com Sun Jan 27 06:53:25 2008 From: over at thepond.com (over at thepond.com) Date: Sun, 27 Jan 2008 11:53:25 GMT Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <60357uF1perd0U1@mid.individual.net> Message-ID: > >> That's not the point, however. I'm trying to say that a processor >> cannot read a Python script, and since the Python interpreter as >> stored on disk is essentially an assembler file, > >It isn't; it's an executable. I appreciated the intelligent response I received from you earlier, now we're splitting hairs. :-) Assembler, like any other higher level language is written as a source file and is compiled to a binary. An executable is one form of a binary, as is a dll. When you view the disassembly of a binary, there is a distinct difference between C, C++, Delphi, Visual Basic, DOS, or even between the different file types like PE, NE, MZ, etc. But they all decompile to assembler. While they are in the binary format, they are exactly that...binary. Who would want to interpret a long string of 1's and 0's. Binaries are not stored in hexadecimal on disk nor are they in hexadecimal in memory. But, all the 1's and 0's are in codes when they are instructions or ASCII strings. No other high level language has the one to one relationship that assembler has to machine code, the actual language of the computer. Dissassemblers can easily convert a binary to assembler due to the one to one relationship between them. That can't be said for any other higher level language. Converting back to C or Python would be a nightmare, although it's becoming a reality. Converting a compiled binary back to hexadecimal is basically a matter of converting the binary to hexadecimal, as in a hex editor. There are exceptions to that, of course, especially with compound assembler statements that use extensions to differentiate between registers. > >> any Python script must be sooner or later be converted to >> assembler form in order to be read by its own interpreter. > >This "assembler form" is commonly referred to as "Python byte code". > thanks for pointing that out. It lead me to this page: http://docs.python.org/lib/module-dis.html where it is explained that the opcodes are in Include/opcode.h. I'll take a look at that. The light goes on. From opcode.h: #define PRINT_NEWLINE_TO 74 All the ASCIi strings end with 0x74 in the disassembly. I have noted that Python uses a newline as a line feed/carriage return. Now I'm getting it. It could all be disassembled with a hex editor, but a disassembler is better for getting things in order. OK. So the pyc files use those defs...that's cool. From http Fri Jan 25 14:56:11 2008 From: http (Paul Rubin) Date: 25 Jan 2008 11:56:11 -0800 Subject: find minimum associated values References: Message-ID: <7xd4rpznl0.fsf@ruckus.brouhaha.com> Alan Isaac writes: > print "method 2: groupby" > t=time.clock() > d = dict() > kv_sorted = sorted(kv, key=lambda x: id(x[0])) How about something like: kv_sorted = sorted(kv, key=lambda x: (id(x[0]), x[1])) Now do your groupby and the first element of each group is the minimum for that group. From asmodai at in-nomine.org Mon Jan 14 06:24:18 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 14 Jan 2008 12:24:18 +0100 Subject: __init__ explanation please In-Reply-To: <87tzlhg9vu.fsf@benfinney.id.au> References: <47895d25$0$30708$4c368faf@roadrunner.com> <87tzlhg9vu.fsf@benfinney.id.au> Message-ID: <20080114112418.GW75977@nexus.in-nomine.org> -On [20080113 14:03], Ben Finney (bignose+hates-spam at benfinney.id.au) wrote: >That's getting the two of them confused. __new__ is a constructor, >__init__ is not. And there I just sent an email stating the wrong thing. I'll dig into it again, because I am really confusing something here (and jumping between 4 languages on the same day is not helping much to be honest). -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ If slavery is not wrong, nothing is wrong... From bj_666 at gmx.net Thu Jan 24 03:44:04 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Jan 2008 08:44:04 GMT Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> Message-ID: <5vr1ekF1njt09U2@mid.uni-berlin.de> On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote: > My second question is: is there any one who has tested very long mbcs > decode? I tried to decode a long(20+MB) xml yesterday, which turns out > to be very strange and cause SAX fail to parse the decoded string. That's because SAX wants bytes, not a decoded string. Don't decode it yourself. > However, I use another text editor to convert the file to utf-8 and > SAX will parse the content successfully. Because now you feed SAX with bytes instead of a unicode string. Ciao, Marc 'BlackJack' Rintsch From bbxx789_05ss at yahoo.com Thu Jan 24 13:52:59 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 24 Jan 2008 10:52:59 -0800 (PST) Subject: Problems getting Python scripts to run on server References: <83ae0f82-e9af-433e-936d-d5b5600a315e@j20g2000hsi.googlegroups.com> Message-ID: <196f3fac-c8a4-417d-ae5d-6a8d458a99cd@v67g2000hse.googlegroups.com> On Jan 23, 11:30?pm, 7stud wrote: I just wanted to point out that the tag below would go in the httpd.conf file(a config file for apache), which you apparently do not have access to. I was suggesting that you check with your host to make sure they have the right AllowOverride line. > > 3) "What you can put in <.htaccess> files is determined by the > AllowOverride directive." > > e.g. > > > ? ? AllowOverride FileInfo > ? ? Options None > ? ? Order allow,deny > ? ? Allow from all > > > "Note: you must have "AllowOverride Options" in effect to permit the > use of the "Options" directive in .htaccess files." > > So, in the above example the line starting with AllowOverride would > need to have "Options" instead of FileInfo(or maybe in addition to?). > > More info fromhttp://httpd.apache.org/docs/2.0/howto/htaccess.html: > ------- > Finally, you may wish to use a .htaccess file to permit the execution > of CGI programs in a particular directory. This may be implemented > with the following configuration: > > Options +ExecCGI > AddHandler cgi-script cgi pl > > Alternately, if you wish to have all files in the given directory be > considered to be CGI programs, this may be done with the following > configuration: > > Options +ExecCGI > SetHandler cgi-script > > Note that AllowOverride Options and AllowOverride FileInfo must both > be in effect for these directives to have any effect. > > Please see the CGI tutorial for a more complete discussion of CGI > programming and configuration. > ----- > > According to that passage, you should have the extension 'py' not > '.py' in the AddHandler part. ?I don't know if that makes a > difference. ?Go to that web page and click the link to the CGI > tutorial, and maybe you can find some clues on how to configure your > directories with .htacesss files. From steve at REMOVE-THIS-cybersource.com.au Wed Jan 30 09:00:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 30 Jan 2008 14:00:19 -0000 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> <0a285e6e-a3a9-4be9-ae59-4cb7547ffa3a@q21g2000hsa.googlegroups.com> Message-ID: <13q10njnbffkceb@corp.supernews.com> On Tue, 29 Jan 2008 13:44:33 -0600, Robert Kern wrote: > Carl Banks wrote: >> On Jan 29, 7:48 am, Peter Schuller wrote: >>>> You can also put, in animal/__init__.py: >>>> from monkey import Monkey >>>> and now you can refer to it as org.lib.animal.Monkey, but keep the >>>> implementation of Monkey class and all related stuff into >>>> .../animal/monkey.py >>> The problem is that we are now back to the identity problem. The class >>> won't actually *BE* org.lib.animal.Monkey. >> >> The usage is the same; it works in all cases once you redefine >> __module__. Who cares what it really is? > > The inspect module. [snip example] I call that a bug in the inspect module. In fact, looking at the source for the findsource() function, I can see no fewer than two bugs, just in the way it handles classes: (1) it assumes that the only way to create a class is with a class statement, which is wrong; and (2) it assumes that the first occurrence of "class " must be the correct definition, which is also wrong. It isn't hard to break the inspect module. Here's an example: >>> import broken >>> import inspect >>> lines, lineno = inspect.findsource(broken.Parrot) >>> lines[lineno] 'class Parrot which will be defined later.\n' >>> >>> lines, lineno = inspect.findsource(broken.Wensleydale) >>> lines[lineno] 'class Wensleydale: # THIS IS GONE\n' Here's the source of broken.py: $ cat broken.py """Here is a doc string, where I happen to discuss the class Parrot which will be defined later. """ class Parrot: pass class Wensleydale: # THIS IS GONE pass del Wensleydale class Wensleydale(object): # but this exists pass It isn't often that I would come right out and say that part of the Python standard library is buggy, but this is one of those cases. -- Steven From paddy3118 at googlemail.com Thu Jan 24 20:35:16 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 17:35:16 -0800 (PST) Subject: Text-based data inspector for Python? References: Message-ID: <6398ab68-da01-408e-902b-0b488310e9b0@e10g2000prf.googlegroups.com> On 25 Jan, 00:36, kj wrote: > I've only recently started programming in Python, trying to wean > myself from Perl. One of the things I *really* miss from Perl is > a 100% mouse-free data inspector, affectionally known as the Perl > debugger, PerlDB, or just perl -d. With it I can examine the most > elaborate data structures with ease: > > DB<234> |x %one_most_elaborate_data_structure > > ...and miles of data, paged for leisurely browsing, lie at my feet. > > And, since it's text-based, I can run it within a shell in Emacs, > and transfer anything I want between it and an editing buffer > without even a THOUGHT of touching the filthy mouse! If there's > a greater joy in life I have yet to find it. > > Now, I have NO DOUBT in my mind WHATSOEVER that a plethora of simply > amazing GRAPHICAL data inspectors (or the equivalent) exist for > Python, with exquisite features, animation, sound effects, > scratch-and-sniff, massage, built-in spiritual advisor, you-name-it. > Beautiful stuff, no doubt. > > But an old geezer like me likes to keep his knobby hands on the > keyboard at all times, so that his arthritic shoulder keeps quiet... > > So. Can I hope to find a text-based data inspector for Python? > > kynn > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. I tend to do the following at the python prompt: from pprint import pprint as pp Then I can: pp(my_data) - Paddy. From paddy3118 at googlemail.com Fri Jan 18 03:06:41 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 18 Jan 2008 00:06:41 -0800 (PST) Subject: array and list References: Message-ID: <24f854eb-93a8-414d-a518-842bb2d185fb@s13g2000prd.googlegroups.com> On Jan 18, 3:23 am, "J. Peng" wrote: > what's the difference between an array and a list in python? > I see list has all features of array in C or perl. > so please tell me.thanks. If you are new to Python, then where other languages may reach for an 'array', Python programs might organise data as lists. Lists are used much more than arrays in Python. you should find that is the case in tutorials/books too. P.S. if you know Perl then try: http://wiki.python.org/moin/PerlPhrasebook?highlight=%28perl%29 - Paddy. From bret.wortman at gmail.com Thu Jan 24 10:49:40 2008 From: bret.wortman at gmail.com (Bret) Date: Thu, 24 Jan 2008 07:49:40 -0800 (PST) Subject: A global or module-level variable? References: <7637fd0b-961e-4730-abd8-96e85c907082@i72g2000hsd.googlegroups.com> <7xwsq1tyts.fsf@ruckus.brouhaha.com> <63002d69-7738-4cae-bfb5-b933f16591b8@t1g2000pra.googlegroups.com> Message-ID: On Jan 23, 2:27 pm, "Gabriel Genellina" wrote: > En Wed, 23 Jan 2008 11:58:05 -0200, Bret escribi?: > > > On Jan 22, 1:00 pm, Paul Rubin wrote: > > >> If you have to do it that way, use: > > > Is there a better way? A more Pythonic way? > > It's simple, clear and works fine, why make it more complicated? > Unless you have additional requirements, like a multithreaded program. > > -- > Gabriel Genellina Ultimately, it will be multithreaded -- and I had intended to wrap the access to the global member in a lock to ensure only one thread could get a value at any point. It might also become multiprocess (ugh!) and so might need to live in its own SocketServer some day. But for now, I agree. Simple is good. I just wanted to be sure I wasn't oversimplifying, you know? Thanks! From MartinRinehart at gmail.com Sat Jan 5 05:15:23 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Sat, 5 Jan 2008 02:15:23 -0800 (PST) Subject: Fortran to Python References: Message-ID: <95d2fc8c-d95c-4f1f-8770-cd89c1295d3c@d21g2000prf.googlegroups.com> Jeroen Ruigrok van der Werven wrote: > I got someone who asked me to make changes in an old Fortran program she is > using for some calculations. Why convert? Modern Fortran is an object oriented, structured language with the singular advantage that it can run old Fortran programs. From nagle at animats.com Fri Jan 25 00:03:06 2008 From: nagle at animats.com (John Nagle) Date: Thu, 24 Jan 2008 21:03:06 -0800 Subject: Sorting Large File (Code/Performance) In-Reply-To: <7x3asmep73.fsf@ruckus.brouhaha.com> References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <4799285d$0$36346$742ec2ed@news.sonic.net> <7x3asmep73.fsf@ruckus.brouhaha.com> Message-ID: <47996c3c$0$36337$742ec2ed@news.sonic.net> Paul Rubin wrote: > John Nagle writes: >> - Get enough memory to do the sort with an in-memory sort, like >> UNIX "sort" or Python's "sort" function. > > Unix sort does external sorting when needed. Ah, someone finally put that in. Good. I hadn't looked at "sort"'s manual page in many years. John Nagle From odysseus1479-at at yahoo-dot.ca Sun Jan 13 04:43:13 2008 From: odysseus1479-at at yahoo-dot.ca (Odysseus) Date: Sun, 13 Jan 2008 09:43:13 GMT Subject: Elementary string-formatting References: Message-ID: In article , Roberto Bonvallet wrote: > Put this at the beginning of your program: > > from __future__ import division > > This forces all divisions to yield floating points values: Thanks for the tip. May I assume the div operator will still behave as usual? -- Odysseus From stefan.behnel-n05pAM at web.de Tue Jan 29 09:17:55 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 29 Jan 2008 15:17:55 +0100 Subject: REALLY simple xml reader In-Reply-To: References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> Message-ID: <479F3593.1080005@web.de> Hi, Ricardo Ar?oz wrote: > I don't know zit about xml, but I might need to, and I am saving the > thread for when I need it. So I looked around and found some 'real' > XML document (see below). The question is, how to access s from > s (any category) but not s. > > doc = """ > > > expenses: january 2002 > > > 31.19 > 200213 > Walking Store > shoes > > > > 1549.58 > 200217 > Bob's Bolts > [...] > > """ Sure, no problem. Just use the XPath expression "//debit/amount", or maybe "/checkbook/credit/amount", if you prefer. This is basically tree traversal, so you can check the parents and the children as you see fit. Stefan From nagle at animats.com Tue Jan 15 02:43:29 2008 From: nagle at animats.com (John Nagle) Date: Mon, 14 Jan 2008 23:43:29 -0800 Subject: Is there some Python function that searches "sys.path" for a module? In-Reply-To: <6c9fb69f-04fb-460e-b78e-9b342e6f83ed@d21g2000prf.googlegroups.com> References: <478c5755$0$36354$742ec2ed@news.sonic.net> <6c9fb69f-04fb-460e-b78e-9b342e6f83ed@d21g2000prf.googlegroups.com> Message-ID: <478C6421.2030603@animats.com> Miki wrote: > http://docs.python.org/lib/module-imp.html Ah. "imp.find_module". I was looking in "sys" and path-related places. Thanks. John Nagle From steve at REMOVE-THIS-cybersource.com.au Sat Jan 5 19:00:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 06 Jan 2008 00:00:53 -0000 Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> Message-ID: <13o06hleh4dkj45@corp.supernews.com> On Sat, 05 Jan 2008 15:07:10 -0800, bearophileHUGS wrote: > Paddy: >> Not really, it seems to me to be going the exact opposite way with >> languages with automatic type conversions being seen as not suited for >> larger programs. > > In Java you can add the number 1 to a string, and have it automatically > converted to string before the string join... What do you think of that > feature? You mean special-casing the int 1 so that this works? # Faked! >>> x = "spam spam spam" >>> x = x + 1 >>> x 'spam spam spam1' but not this? >>> x = "spam spam spam" >>> x = x + 2 TypeError: automatic conversion between strings and ints only works for the int 1 How bizarre. The problem with automatic conversions between strings and integers is that it isn't clear what the user wants when they do something like this: >>> x = '1' + 1 Should x be the string '11' or the int 2? Please justify your answer. On the other hand, if the language includes separate operators for addition and concatenation (say, + and &) then that sort of auto- conversion is no longer ambiguous: >>> '2' + 3 5 >>> '2' & 3 '23' -- Steven From jura.grozni at gmail.com Sun Jan 20 14:55:19 2008 From: jura.grozni at gmail.com (azrael) Date: Sun, 20 Jan 2008 11:55:19 -0800 (PST) Subject: py2exe and modules question Message-ID: I'm working on an application and i'm having some questions. I am working with python 2.5, numpy and PIL. does anyone know if there are some problems while compiling the source because of the modules.. It has to be closed source. I didn't try Py2exe but I heard about it. Is there any other and better way to compile the source. Thnx From gagsl-py2 at yahoo.com.ar Wed Jan 30 22:49:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 31 Jan 2008 01:49:33 -0200 Subject: small problem with re.sub References: <47A13A0A.3010607@al.com.au> Message-ID: En Thu, 31 Jan 2008 01:01:30 -0200, Astan Chee escribi?: > I have a html text stored as a string. Now I want to go through this > string and find all 6 digit numbers and make links from them. > Im using re.sub and for some reason its not picking up the previously > matched condition. Am I doing something wrong? This is what my code > looks like: > htmlStr = re.sub('(?P\d{6})',' href=\"http://linky.com/(?P=id).html\">(?P=id)',htmlStr) > It seems that it replaces it alright, but it replaces it literally. Am I > not escaping certain characters? Two errors: - use raw strings r"..." to write regular expressions (or quote every backslash...) - if you want to *substitute* a named group, the syntax is "\g"; you have used the syntax to *match* a named group. re.sub(r'(?P\d{6})',r'\g',htmlStr) In simple cases like this, may be easier to just use a number: re.sub(r'(\d{6})',r'\1',htmlStr) -- Gabriel Genellina From ryan at ryankaskel.com Wed Jan 23 14:57:12 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 11:57:12 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> <12d19814-b7b9-44b0-aee3-299befac7279@i12g2000prf.googlegroups.com> Message-ID: On Jan 23, 2:53 pm, John Machin wrote: > On Jan 24, 6:17 am, ryan k wrote: > > > I am taking a database class so I'm not asking for specific answers. > > Well I have this text tile: > > >http://www.cs.tufts.edu/comp/115/projects/proj0/customer.txt > > Uh-huh, "column-aligned" output. > > > > > And this code: > > [snip] > > > > > Because the addresses contain spaces, this won't work because there > > are too many values being unpacked in row's __init__'s for loop. Any > > suggestions for a better way to parse this file? > > Tedious (and dumb) way: > field0 = line[start0:end0+1].rstrip() > field1 = line[start1:end1+1].rstrip() > etc > > Why dumb: if the column sizes change, you have to suffer the tedium > again. While your sample appears to pad out each field to some > predetermined width, some reporting software (e.g. the Query Analyzer > that comes with MS SQL Server) will tailor the widths to the maximum > size actually observed in the data in each run of the report ... so > you write your program based on some tiny test output and next day you > run it for real and there's a customer whose name is Marmaduke > Rubberduckovitch-Featherstonehaugh or somesuch and your name is mud. > > Smart way: note that the second line (the one with all the dashes) > gives you all the information you need to build lists of start and end > positions. Thank you for your detailed response Mr. Machin. The teacher *said* that the columns were supposed to be tab delimited but they aren't. So yea i will just have to count dashes. Thank you! From donn.ingle at gmail.com Thu Jan 24 11:12:39 2008 From: donn.ingle at gmail.com (Donn Ingle) Date: Thu, 24 Jan 2008 18:12:39 +0200 Subject: piping into a python script References: <5vrovvF1njt09U6@mid.uni-berlin.de> <77bf0ea2-5e7d-4cd0-8692-319b85a97d65@v17g2000hsa.googlegroups.com> Message-ID: Paddy wrote: > ls *.a | ./fui.py -f - *.b To be sure I grok this: I am seeing the single dash as a placeholder for where all the piped filenames will go, so *.b happens after *.a has been expanded and they all get fed to -f, right? I'm also guessing you mean that I should detect the single dash and then go look for stdin at that point. How do I detect a lack of stdin? Thanks, \d From cwitts at gmail.com Fri Jan 18 04:37:59 2008 From: cwitts at gmail.com (Chris) Date: Fri, 18 Jan 2008 01:37:59 -0800 (PST) Subject: Filtering two files with uncommon column References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> Message-ID: <5084371c-dba0-4d11-be95-a01d1b439de6@s12g2000prg.googlegroups.com> On Jan 18, 11:23 am, Madhur wrote: > I would like to know the best way of generating filter of two files > based upon the following condition > > I have two files. Contents of the first file is > > File 1 > abc def hij > asd sss lmn > hig pqr mno > > File 2 > > jih def asd > poi iuu wer > wer pqr jjj > > I would like have the output as > Output > > File1 > asd sss lmn > File2 > poi iuu wer > > Basically I want to compare the two files based on second column. If > the second > column matches on both the files do not print anything, else if there > is no matc > h in for the second column for first file in second file then print it > under Fil > e1 header, else if there is no match for the second column for second > file in fi > rst file print it under File2 header. > > Thankyou > Madhur file1 = open('file1.txt','rb') file2 = open('file2.txt','rb') file1_line = file1.next() file2_line = file2.next() while file1_line and file2_line: try: f1_col2 = file1_line.split(' ')[1] except IndexError: print 'Not enough delimiters in line.' try: f2_col2 = file2_line.split(' ')[2] except IndexError: print 'Not enough delimiters in line.' if f1_col2 != f2_col2: outfile_data_to_relevant_files() file1_line = file1.next() file2_line = file2.next() HTH Chris From deets at nospam.web.de Sat Jan 19 21:14:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 20 Jan 2008 03:14:25 +0100 Subject: Naming a file In-Reply-To: References: <89bb0095-429f-404c-b7f6-ff0a554b07cc@i72g2000hsd.googlegroups.com> Message-ID: <5vfp46F1meva4U1@mid.uni-berlin.de> Matthias Bl?sing schrieb: > Am Sat, 19 Jan 2008 14:14:30 -0800 schrieb snoylr: > >> For example if the variable is 105Markum >> >> What statement do I need to create a file name 105Markum.txt? > > filename_base = '105Markum' > filename = '%s.txt' % filename_base > f = open(filename, 'w') > f.write( f.close You missed the cruicial parentheses here: f.close() Diez From vladimir at greenmice.info Fri Jan 25 06:30:43 2008 From: vladimir at greenmice.info (Vladimir Rusinov) Date: Fri, 25 Jan 2008 14:30:43 +0300 Subject: problem with gethostbyaddr with intranet addresses on MAC In-Reply-To: References: Message-ID: On 1/25/08, shailesh wrote: > > apples-computer:~ apple$ ping 192.168.4.123 > PING 192.168.4.123 (192.168.4.123): 56 data bytes > 64 bytes from 192.168.4.123: icmp_seq=0 ttl=64 time=0.328 ms > 64 bytes from 192.168.4.123: icmp_seq=1 ttl=64 time=0.236 ms > 64 bytes from 192.168.4.123: icmp_seq=2 ttl=64 time= 0.255 ms > ^C > --- 192.168.4.123 ping statistics --- > 3 packets transmitted, 3 packets received, 0% packet loss > round-trip min/avg/max/stddev = 0.236/0.273/0.328/0.040 ms > apples-computer:~ apple$ python2.4 > Python 2.4.4 (#1, Oct 18 2006, 10:34:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> from socket import * > >>> x = gethostbyname('google.com') > >>> x > '64.233.167.99' > >>> gethostbyaddr(x) > ('py-in-f99.google.com', [], ['64.233.167.99']) > >>> e = '192.168.4.123' > >>> gethostbyaddr(e) > Traceback (most recent call last): > File "", line 1, in ? > socket.herror: (1, 'Unknown host') > >>> > I'm sure your dns server have no reverse records for ' 192.168.4.123'. So, it can't resolve it (123.4.168.192.in-addr.arpa). -- Vladimir Rusinov GreenMice Solutions: IT-??????? ?? ???? Linux http://greenmice.info/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.stuart.risney at gmail.com Sat Jan 12 14:13:22 2008 From: marc.stuart.risney at gmail.com (marcstuart) Date: Sat, 12 Jan 2008 11:13:22 -0800 (PST) Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> Message-ID: <3df4a0f9-6dfd-4dfd-b6bb-53ff434c65e8@s12g2000prg.googlegroups.com> I have gotten a little further, but not in the order of the original list def divide_list(lst, n): return [lst[i::n] for i in range(n)] x = [1,2,3,4,5,6,7,8,9,10] y = 3 z = divide_list(x,y) print z[0] print z[1] print z[2] this prints: [1, 4, 7, 10] [2, 5, 8] [3, 6, 9] closer, but I would like to maintain the original order of the list. From arnodel at googlemail.com Sun Jan 27 20:56:31 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 27 Jan 2008 17:56:31 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> Message-ID: On Jan 28, 1:47?am, Steven D'Aprano wrote: [...] > As nice as this feature would be, and I vote +2 on the functionality, I > wonder whether the amount of line noise in method definitions now will be > approaching Perlish levels? We've got default values, type annotations > (in Python3), *args and **kwargs, _ private names, and now we want to add > auto-assignment. Don't forget keyword only arguments! I find signatures too complicated already, please let's not clutter them even more. -- Arnaud From justinrob at gmail.com Fri Jan 25 06:50:25 2008 From: justinrob at gmail.com (justinrob at gmail.com) Date: Fri, 25 Jan 2008 03:50:25 -0800 (PST) Subject: Minimum Requirements for Python Message-ID: Can someone tell me the minimum requitements for Python as I can't find it anwhere on the site. I have 3 PC's which are only 256mb RAM, wanted to know if this was sufficenent. Thanks From musiccomposition at gmail.com Thu Jan 17 22:45:43 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 17 Jan 2008 19:45:43 -0800 (PST) Subject: Unique thread ID Message-ID: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> Is there a way to obtain a unique ID for the current thread? I have an object that I need to store local thread data in, and I don't want to use threading.local because each thread might have multiple instances of my object. From guyrutenberg at gmail.com Fri Jan 18 07:58:02 2008 From: guyrutenberg at gmail.com (Guy Rutenberg) Date: Fri, 18 Jan 2008 04:58:02 -0800 (PST) Subject: "Code Friendly" Blog? References: Message-ID: <0e3de274-1200-4268-b0ae-e3e56645ba49@s19g2000prg.googlegroups.com> On Jan 18, 8:56 am, Jeroen Ruigrok van der Werven wrote: > I personally use a Wordpress installation on my own machine with an additional > plugin for syntax highlighting.http://wordpress.org/extend/plugins/wp-syntax/ > I use the same configuration (Wordpress + wp-syntax) too. I can say I'm pretty satisfied with it. I had no problem posting python code. IIRC Wordpresss will automatically escape < and > for you (if it's no part of tag). Regards, Guy http://www.guyrutenberg.com/ From skip at pobox.com Tue Jan 15 11:05:43 2008 From: skip at pobox.com (Skip Montanaro) Date: Tue, 15 Jan 2008 16:05:43 +0000 (UTC) Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: > If the RHS is a set then it works OK: Yup, I understand that. Would be kind of bad if it didn't. ;-) > It could be modifies to handle any > iterable on the RHS. That's my question. Why does it work in one place but not everywhere? Skip From marek.rocki at wp.pl Sat Jan 26 08:20:15 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sat, 26 Jan 2008 05:20:15 -0800 (PST) Subject: Doesn't know what it wants References: <13plo358k5rf059@corp.supernews.com> Message-ID: <7909cb2e-33da-47aa-be05-38ca333d2cde@c23g2000hsa.googlegroups.com> > class vec2d(ctypes.Structure): > """2d vector class, supports vector and scalar operators, > and also provides a bunch of high level functions > """ > __slots__ = ['x', 'y'] > > def __init__(self, x_or_pair, y = None): > > if y == None: > self.x = x_or_pair[0] > self.y = x_or_pair[1] > else: > self.x = x_or_pair > self.y = y I may be way off here, but why does vec2d inherit from ctypes.Structure if it doesn't observe the protocol for Structures (they're supposed to have _fields_, not __slots__)? From rrr at ronadam.com Sun Jan 13 23:08:39 2008 From: rrr at ronadam.com (Ron Adam) Date: Sun, 13 Jan 2008 22:08:39 -0600 Subject: time.time or time.clock In-Reply-To: References: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> Message-ID: <478AE047.8070306@ronadam.com> Fredrik Lundh wrote: > John Machin wrote: > >> AFAICT that was enough indication for most people to use time.clock on >> all platforms ... > > which was unfortunate, given that time.clock() isn't even a proper clock > on most Unix systems; it's a low-resolution sample counter that can > happily assign all time to a process that uses, say, 2% CPU and zero > time to one that uses 98% CPU. > > > before the introduction of the timeit module; have you considered it? > > whether or not "timeit" suites his requirements, he can at least replace > his code with > > clock = timeit.default_timer > > which returns a good wall-time clock (which happens to be time.time() on > Unix and time.clock() on Windows). Thanks for the suggestion Fredrik, I looked at timeit and it does the following. import sys import time if sys.platform == "win32": # On Windows, the best timer is time.clock() default_timer = time.clock else: # On most other platforms the best timer is time.time() default_timer = time.time I was hoping I could determine which to use by the values returned. But maybe that isn't as easy as it seems it would be. Ron From JAMoore84 at gmail.com Sat Jan 26 15:15:59 2008 From: JAMoore84 at gmail.com (JAMoore84 at gmail.com) Date: Sat, 26 Jan 2008 12:15:59 -0800 (PST) Subject: Beginner String formatting question References: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> Message-ID: <8e13cb51-5268-419d-99d2-eba8226f4358@z17g2000hsg.googlegroups.com> I apologize for the lack of details in my last post. This time formatting program is a piece of a larger program I am trying to write to de-clutter GPS transmission. I have a GPS receiver that transmits its readings via bluetooth. I've been able to use pySerial and store X number of bytes, then write that to a file (the next step will be finding a way to write the stream to a file directly). The raw GPS data is tranmitted in the NMEA format (http://vancouver-webpages.com/ peter/nmeafaq.txt): $GPRMC,024830,V,,N,,E,,,260108,,,N*58 $GPVTG,,T,,M,,N,,K,N*2C $GPGGA,024831,LAT_GOES_HERE,N,LONG_GOES_HERE,E,0,00,,,M,,M,,*61 $GPGSA,A,1,,,,,,,,,,,,,,,*1E $GPGSV,3,1,09,09,,,37,13,,,00,18,,,00,23,,,00*75 $GPGSV,3,2,09,01,,,00,29,,,00,14,,,00,26,,,00*7A $GPGSV,3,3,09,12,,,00,,,,,,,,,,,,*73 $GPRMC,024831,V,LAT_GOES_HERE,N,LONG_GOES_HERE,E,,,260108,,,N*59 $GPVTG,,T,,M,,N,,K,N*2C the "$GPGGA" and "$GPRMC" lines are the ones that will give you your Latitude and Longitude data --or the would if I had a signal. All the entries are comma delimited, so I used the split(',') function to parse the appropriate statements. Here's the code for that: ============================= input = open('c:\sample_readout.txt','r') #location of the Raw GPS data output = open('c:\GPSout.txt', 'w') output.write("Timestamp \t Latitude \t Longitude \t Velocity") s = input.readlines() for line in s: if line.startswith('$GPGGA'): InputTuple = line.split(',') time = InputTuple[1] lat = InputTuple[2]+' '+InputTuple[3] long = InputTuple[4]+' '+InputTuple[5] out = '\n '+ time + '\t\t' + lat + '\t\t\t' + long output.writelines(out) elif line.startswith('$GPRMC'): InputTuple = line.split(',') time = InputTuple[1] lat = InputTuple[3]+' '+InputTuple[4] long = InputTuple[5]+' '+InputTuple[6] out = '\n '+ time + '\t\t' + lat + '\t\t\t' + long output.writelines(out) elif line.startswith('$GPVTG'): #this will give grounp speed in knts and [7] gives kmph InputTuple = line.split(',') out = '\n ' + '\t\t' + InputTuple[5] output.writelines(out) input.close() output.close() ======================== The time stamp for both the GPRMC and GPGGA lines will be stored in InputTuple[1]. Right now, this program will read the GPS data file and pull out the necessary information. I wanted the Format.py program to function as a module so that I could call Format.FormatTime(time) to change the HHMMSS GPS data to HH:MM:SS, for readability. The next step was to write a FormatCoord function (within the Format module) to do the same for lat/long data. Now that I've explained the structure, the argument of Format.FormatTime() will be InputTuple[1] (the timestamp). I want to be able to call that function in the GPS program to read the contents of InputTuple[1] and write the HH:MM:SS data to the file. I've incorporated some of your recommendations into my program already and it looks much better. Thanks to everyone for your suggestions. Jimmy From bill.wws at gmail.com Sun Jan 13 10:03:15 2008 From: bill.wws at gmail.com (bill.wu) Date: Sun, 13 Jan 2008 07:03:15 -0800 (PST) Subject: i am new guy for this discussion group Message-ID: i am new guy to learn python,also for this discussion group, i am chinese. nice to meet you, everyone. From cokofreedom at gmail.com Thu Jan 17 10:14:08 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 17 Jan 2008 07:14:08 -0800 (PST) Subject: Is this a bug, or is it me? References: Message-ID: <4044206c-9fd8-4dc1-8fe9-61edb314b9f5@k39g2000hsf.googlegroups.com> On Jan 17, 4:05 pm, cptnwill... at gmail.com wrote: > Hello all, > For some reason, the following does not work : > > class C: > TYPES = [None] > DICT = {} > for Type in TYPES: > DICT.update((E,Type) for E in [1]) > > >>> NameError: global name 'Type' is not defined > > What do you think? Is this a bug? Do not use those names...really poor choice... thingydingy = [None] my = {} for dingaling in thingydingy: my.update([(E,dingaling ) for E in [1]]) print my From siona at chiark.greenend.org.uk Mon Jan 28 13:02:53 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Jan 2008 18:02:53 +0000 (GMT) Subject: problem with gethostbyaddr with intranet addresses on MAC References: Message-ID: shailesh wrote: >Python 2.4.4 (#1, Oct 18 2006, 10:34:39) >[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin >Type "help", "copyright", "credits" or "license" for more information. >>>> from socket import * >>>> x = gethostbyname('google.com') >>>> x >'64.233.167.99' >>>> gethostbyaddr(x) >('py-in-f99.google.com', [], ['64.233.167.99']) >>>> e = '192.168.4.123' >>>> gethostbyaddr(e) >Traceback (most recent call last): > File "", line 1, in ? >socket.herror: (1, 'Unknown host') >>>> So what are you expecting it to return? Or, to put it another way, what would you feed to gethostbyname() to get 192.168.4.123 back? Can you get the "right" answer from host or some other command- line tool? Can you get an answer from gethostbyaddr() on one of the other machines on the network? How do they do their name resolution? -- \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 gh at ghaering.de Fri Jan 18 11:42:21 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 18 Jan 2008 17:42:21 +0100 Subject: how to resolve Windows pathnames into cygwin ones In-Reply-To: References: Message-ID: <5vc35eF1lsgcjU1@mid.uni-berlin.de> mgierdal at gmail.com wrote: > I am looking for a function to resolve 'F:/foo/bar' into '/cygdrive/f/ > foo/bar'. I get the original dirpath from tkFileDialog.askdirectory in > a Windows form and none of os.path.* functions seem to resolve it to a > cygwin form. Rather they _append_ it to the current directory, > resulting at best in a monster '/cygdrive/c/whatever/f/foo/bar'. > It's all being developed under cygwin currently (so it is a kind of > mixed environment), but I would like the fix to work correctly in any > environment. You can call the cygpath utility: >>> import commands >>> commands.getoutput("cygpath c:/windows") '/c/windows' -- Gerhard From steve at mhomer.au Thu Jan 10 05:31:18 2008 From: steve at mhomer.au (Steve Brown) Date: Thu, 10 Jan 2008 21:31:18 +1100 Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: <13obsvnqrhqvk34@corp.supernews.com> "Russ P." wrote in message news:d2a08eac-3ae7-4710-9b49-cdbe365a25ef at d21g2000prf.googlegroups.com... > On Jan 9, 11:51 pm, Fredrik Lundh wrote: >> Steve Brown wrote: >> > I've got a series of modules which look like this: >> >> > #************ >> > # >> > # Temperature Sense Test >> > # >> > #************ >> > class Test3(ar_test.AR_TEST): >> > """Temperature Sense Test""" >> >> > I don't like the duplicated information: But the comment is attractive, >> > and >> > the docstring self.__doc__ is already in use in the test log. I've read >> > that >> > all modules and classes should have docstrings, but I don't really have >> > anything else to say, and each module contains only one class. I don't >> > think >> > that >> >> > """Temperature Sense Test""" >> > class Test3(ar_test.AR_TEST): >> > """Temperature Sense Test""" >> >> > would be a real improvement. >> >> > What do you think? >> >> since you already seem to cater to your audience (clearly marked >> comments for people browsing the code, brief docstrings for the test >> log), I don't really see why you should change anything. >> >> > I've read that all modules and classes should have docstrings >> >> if nobody's going to read them, there's no reason to add them. don't >> treat generic style advice as dogma. >> >> > > Well, trivial modules certainly don't need much documentation, but he > didn't say they were trivial. I assumed there was more to them then he > showed. All of the complexity is in the test framework. I've been working on paring back the tests to make them simple to understand, create and modify, which is how I've come to this: I'm still trying to remove lines. The test itself is a now a linear script of 20-40 lines, and I'm still working on them. However, it is relatively important to make the documentation right for these simple scripts. The docstring/comment does need to show some embedded dependancies, I just chose one without any. I realise from reading Jeroen Ruigrok van der Werven's comment that I should probably also care what epydoc makes of my doc strings, -- that's an additional constraint. From steve at REMOVE-THIS-cybersource.com.au Mon Jan 14 16:21:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 14 Jan 2008 21:21:43 -0000 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <87prw4fyej.fsf@benfinney.id.au> Message-ID: <13onkj7ra3i0p75@corp.supernews.com> On Mon, 14 Jan 2008 22:18:44 +1100, Ben Finney wrote: > What one is "in reality" calling is the '__new__' method of the Person > class. That function, in turn, is creating a new Person instance, and > calling the '__init__' method of the newly-created instance. Finally, > the '__new__' method returns that instance back to the caller. But not if Person is an old-style class. -- Steven From george.sakkis at gmail.com Thu Jan 31 20:34:45 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 31 Jan 2008 17:34:45 -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> <7xzlula8z4.fsf@ruckus.brouhaha.com> <7xhcgtv8m0.fsf@ruckus.brouhaha.com> Message-ID: On Jan 31, 7:11 pm, Paul Rubin wrote: > "attn.steven.... at gmail.com" writes: > > True... Any lighter-weight implementation of > > sets out there? That is, one that would defer > > use of resources until actually needed -- > > somewhat akin to the distinction between > > range and xrange, and so on. > > Don't even think of doing it that way, that solves the space problem > but leaves a speed problem. You probably want to use something like > sort the intervals and then use the bisect module to find the > intervals intersecting a given one. I haven't actually used it but from the short description this package seems to fit the bill: http://pypi.python.org/pypi/interval/1.0.0 George From kyosohma at gmail.com Thu Jan 24 09:15:15 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 24 Jan 2008 06:15:15 -0800 (PST) Subject: wxpython References: <77cc3d61-5dd0-4878-b436-b6d07e40de4d@i7g2000prf.googlegroups.com> <0d5fbbaf-aff3-46eb-a8ff-ef0247262fcc@i29g2000prf.googlegroups.com> Message-ID: <8789c20d-4c2a-4c68-a9cb-9b68b0a3f16d@u10g2000prn.googlegroups.com> On Jan 24, 5:37 am, Tim Golden wrote: > [... snip stuff from TJG ...] > > joe jacob wrote: > > Thanks for the information. I'll try to manage it some how. > > If you haven't already, try posting to a wxPython or wxWidgets > mailing list; maybe someone's already done this kind of thing? > > TJG I'm not able to think of anything offhand that's in wxPython, but I seem to recall someone trying to display a language even if the language wasn't installed on the PC. The OP might find the internationalization techniques useful for this application. Here's some wiki entries on that topic: http://wiki.wxpython.org/RecipesI18n http://wiki.wxpython.org/Internationalization The newest version of wxPython comes with Editra, which is a fairly advanced text editor written with wxPython. It won't open exes or pictures, but most files that are in plain text it opens with no problem. Editra has its own site: http://editra.org/ The mailing list for wxPython can be found here: http://wxpython.org/maillist.php Mike From stefan.behnel-n05pAM at web.de Thu Jan 3 02:55:26 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 03 Jan 2008 08:55:26 +0100 Subject: XML-XSD Processing/Creation. In-Reply-To: References: Message-ID: <477C94EE.7080806@web.de> paul wrote: >> Can i create python classes based off the XSD files? What else can I >> do with the XSD files? > This might be worth looking at: http://www.rexx.com/~dkuhlman/#generateDS If it's really such a complex XML language, the tool above might or might not be of any help, as it doesn't support the whole XSD standard (and XML Schema is very complex). It's worth a try, but don't expect too much. The lxml way of dealing with XML languages is namespace implementation: http://codespeak.net/lxml/dev/element_classes.html#id1 However, there isn't currently a way to automatically bootstrap an implementation, especially not in XSD, so it depends on the language how much work it will be to get this to a usable state. Stefan From tteststudent at gmail.com Fri Jan 4 18:17:49 2008 From: tteststudent at gmail.com (ttest) Date: Fri, 4 Jan 2008 15:17:49 -0800 (PST) Subject: Request for help with Image color space conversion Message-ID: <8586a895-f238-4a22-a1bb-31c39f22b4cc@n20g2000hsh.googlegroups.com> Hello, I'm working on an image processing project using the Python Imaging Library along with numpy. Right now, I'm trying to build a speedy script for converting whole images between the RGB and the HSV (a.k.a. HSB) color spaces. Unfortunately, the code I've made so far runs dreadfully slow with even moderate-sized images. I'm under the impression that the crux of the problem is the fact that PIL's point method operates on only one band at a time, and to do a proper color space conversion, you need information about all three bands in a particular problem. This has forced me to do an awkward work-around where the image data is loaded into a numpy array (1600x1200x3), and a dinky for-loop run runs through the array picking up RGB values, converting to HSV, and dumping the results back into another array. How can I make this more efficient? -------- from PIL import Image from PIL import TiffImagePlugin from scipy.misc import pilutil import numpy import colorsys def myrgbtohsv(r,g,b): '''A wrapper for the colorsys function rgb_to_hsv that takes r,g,b values between 0 and 255 (standard pixel value range in most of my single-band imaging operations) and returns the corresponding 255-scaled h,s,v values''' tr = r/255.0 tg = g/255.0 tb = b/255.0 ur,ug,ub = colorsys.rgb_to_hsv(tr,tg,tb) pr = int(round(ur,0))*255 pg = int(round(ug,0))*255 pb = int(round(ub,0))*255 return pr,pg,pb def rgbarrtohsvarr(pilarray): '''Takes an 3d numpy ndarray loaded with a RGB PIL image and converts a copy of the contents to 255-scaled HSV array. Returns the converted copy of the array. ''' arrt = pilarray.copy() r,c,d = arrt.shape hsvarray = numpy.zeros((r,c,d)) print out for i in range(0,r): for j in range(0,c): localrgb = (arrt[i,j,0],arrt[i,j,1],arrt[i,j,2]) (lh,ls,lv) = rgbtohsv(localrgb) hsvarray[i,j,0],hsvarray[i,j,1],hsvarray[i,j,2]= lh,ls,lv return hsvarray im = Image.open(r'C:\test.tif') arr = pilutil.fromimage(im) out = rgbarrtohsvarr(arr) -------- From brunoacf at gmail.com Thu Jan 3 09:38:48 2008 From: brunoacf at gmail.com (Bruno Ferreira) Date: Thu, 3 Jan 2008 11:38:48 -0300 Subject: problem with global var Message-ID: <3448388f0801030638sd285c7dh78b9ea9f7b911139@mail.gmail.com> Hi, I wrote a very simple python program to generate a sorted list of lines from a squid access log file. Here is a simplified version: ################################## 1 logfile = open ("squid_access.log", "r") 2 topsquid = [["0", "0", "0", "0", "0", "0", "0"]] 3 4 def add_sorted (list): 5 for i in range(50): 6 if int(list[4]) > int(topsquid[i][4]): 7 topsquid.insert(i,list) 8 break 8 # Max len = 50 10 if len(topsquid) > 50: 11 topsquid = topsquid[0:50] 12 13 while True: 14 logline = logfile.readline() 15 linefields = logline.split() 16 17 if logline != "": 18 add_sorted (linefields) 19 else: 20 break 21 22 for i in range (len(topsquid)): 23 print topsquid[i][4] #################################### When I execute the program _without_ the lines 10 and 11: 10 if len(topsquid) > 50: 11 topsquid = topsquid[0:50] it runs perfectly. But if I execute the program _with_ those lines, this exception is thrown: bruno at ts:~$ python topsquid.py Traceback (most recent call last): File "topsquid.py", line 20, in add_sorted (linefields) File "topsquid.py", line 6, in add_sorted if int(list[4]) > int(topsquid[i][4]): UnboundLocalError: local variable 'topsquid' referenced before assignment Note that now the error shown is not related with the lines 10 and 11, but wiht a line prior to them. Any hints? -- Bruno A. C. Ferreira Linux Registered User #181386 From eduardo.padoan at gmail.com Wed Jan 23 07:32:55 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Wed, 23 Jan 2008 10:32:55 -0200 Subject: Removing objects In-Reply-To: <13peaovbkqd3202@corp.supernews.com> References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> <13peaovbkqd3202@corp.supernews.com> Message-ID: On Jan 23, 2008 9:55 AM, Steven D'Aprano wrote: > For that to work, you need to give your class an __eq__ method, and have > it match by name: > > # put this in MyClass > def __eq__(self, other): > return self.name == self.other Do you mean: # put this in MyClass def __eq__(self, other): return self.name == other.name ? -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From siona at chiark.greenend.org.uk Mon Jan 7 10:50:59 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Jan 2008 15:50:59 +0000 (GMT) Subject: dictionary/hash and '1' versus 1 References: <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> Message-ID: wrote: >In Java you can add the number 1 to a string, and have it >automatically converted to string before the string join... What do >you think of that feature? "-%s" % 1 -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From over at thepond.com Tue Jan 22 17:45:08 2008 From: over at thepond.com (over at thepond.com) Date: Tue, 22 Jan 2008 22:45:08 GMT Subject: translating Python to Assembler...sorry if this is duplicated...it's unintentional Message-ID: My expertise, if any, is in assembler. I'm trying to understand Python scripts and modules by examining them after they have been disassembled in a Windows environment. I'm wondering if a Python symbols file is available. In the Windows environment, a symbol file normally has a PDB extension. It's a little unfortunate that Python also uses PDB for its debugger. Google, for whatever reason, wont accept queries with dots, hyphens, etc., in the query line. For example a Google for "python.pdb" returns +python +pdb, so I get a ridiculous number of returns referring to the python debugger. I have mentioned this to Google several times, but I guess logic isn't one of their strong points. :-) If there's dupicates of this post it's because it wouldn't send for some reason. From python at rcn.com Tue Jan 22 15:21:54 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 22 Jan 2008 12:21:54 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: [Peter Otten] > You can be bolder here as the izip() docs explicitly state > > """ > Note, the left-to-right evaluation order of the iterables is > guaranteed. This makes possible an idiom for clustering a data series into > n-length groups using "izip(*[iter(s)]*n)". > """ . . . > is about zip(), not izip(). FWIW, I just added a similar guarantee for zip(). Raymond From http Thu Jan 24 14:41:46 2008 From: http (Paul Rubin) Date: 24 Jan 2008 11:41:46 -0800 Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> Message-ID: <7xhch380zp.fsf@ruckus.brouhaha.com> Ira.Kovac at gmail.com writes: > I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like > to sort based on first two characters. > > I'd greatly appreciate if someone can post sample code that can help > me do this. Use the unix sort command: sort inputfile -o outputfile I think there is a cygwin port. > Also, any ideas on approximately how long is the sort process going to > take (XP, Dual Core 2.0GHz w/2GB RAM). Eh, unix sort would probably take a while, somewhere between 15 minutes and an hour. If you only have to do it once it's not worth writing special purpose code. If you have to do it a lot, get some more ram for that box, suck the file into memory and do a radix sort. From mark.dufour at gmail.com Wed Jan 16 06:15:56 2008 From: mark.dufour at gmail.com (Mark Dufour) Date: Wed, 16 Jan 2008 12:15:56 +0100 Subject: Shed Skin (restricted) Python-to-C++ Compiler 0.0.26 Message-ID: <8180ef690801160315i3a2b1b30m403a02ad121f8dca@mail.gmail.com> Hi all, I have just released Shed Skin 0.0.26, with the following goodies: -Almost complete support for os.path (bootstrapped using Shed Skin) -Support for collections.defaultdict (completing collections) -Much improved support for the os module (though many methods remain) -Support for 5 of 7 last missing str methods -Added support for getopt.gnu_getopt (bootstrapped) -Improved support for locales -Optimized string addition (a+b+c..) -Much better documentation (tutorial) -Added a Debian package -Squashed many bugs -Moved to Google code hosting Please have a look at my latest blog entry for more details about the release, or visit the new Google code hosting site: http://shed-skin.blogspot.com http://shedskin.googlecode.com Thanks, Mark Dufour. -- "One of my most productive days was throwing away 1000 lines of code" - Ken Thompson From upton at virginia.edu Thu Jan 31 21:00:07 2008 From: upton at virginia.edu (Dan Upton) Date: Thu, 31 Jan 2008 21:00:07 -0500 Subject: Will Python on day replace MATLAB????????????????????????????????????????????????????? In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380239F7FC@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F7FC@AWMAIL04.belcan.com> Message-ID: <5504f9ac0801311800x6179d86ah30f8229e6d42021@mail.gmail.com> > with ImpulseC and the graphing capabilities of GNU Plot and SciPy in http://gnuplot-py.sourceforge.net/ From george.sakkis at gmail.com Mon Jan 14 21:02:36 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 14 Jan 2008 18:02:36 -0800 (PST) Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> <874pdgf2wo.fsf@benfinney.id.au> Message-ID: <44c962f1-184c-4f79-9ce8-84bd69f9ef64@f47g2000hsd.googlegroups.com> On Jan 14, 5:39 pm, Ben Finney wrote: > I think of NotImplemented as equivalent to None; it's useful as a > sentinel value to set an attribute to in (e.g.) an abstract class. My guess would be that it is more of an implementation performance decision than semantic. Checking 'if result is NotImplemented' is much faster than guarding the call with a try/except NotImplementedError block, and since the motivation for NotImplemented was AFAIK rich comparisons, the potential overhead could be substantial (e.g. a tight 'while i References: <20080109152403.433b113a@bhuda.mired.org> Message-ID: <741fd030801091246h491ffbccp4cbbb3f947aeac63@mail.gmail.com> One way to get this to work is: def inc(jj): def dummy(jj = jj): jj = jj + 1 return jj return dummy h = inc(33) print h() It's not very pretty though, especially when you have many variables you want to have in the inner scope. -Ben On 1/9/08, Mike Meyer wrote: > On Wed, 9 Jan 2008 13:47:30 -0500 (EST) "Steven W. Orr" wrote: > > > So sorry because I know I'm doing something wrong. > > > > 574 > cat c2.py > > #! /usr/local/bin/python2.4 > > > > def inc(jj): > > def dummy(): > > jj = jj + 1 > > return jj > > return dummy > > > > h = inc(33) > > print 'h() = ', h() > > 575 > c2.py > > h() = > > Traceback (most recent call last): > > File "./c2.py", line 10, in ? > > print 'h() = ', h() > > File "./c2.py", line 5, in dummy > > jj = jj + 1 > > UnboundLocalError: local variable 'jj' referenced before assignment > > > > I could have sworn I was allowed to do this. How do I fix it? > > Nope. This is one of the things that makes lisper's complain that > Python doesn't have "real closures": you can't rebind names outside > your own scope (except via global, which won't work here). > > Using a class is the canonical way to hold state. However, any of the > standard hacks for working around binding issues work. For instance: > > >>> def inc(jj): > ... def dummy(): > ... box[0] = box[0] + 1 > ... return box[0] > ... box = [jj] > ... return dummy > ... > >>> h = inc(33) > >>> h() > 34 > > > -- > Mike Meyer http://www.mired.org/consulting.html > Independent Network/Unix/Perforce consultant, email for more information. > -- > http://mail.python.org/mailman/listinfo/python-list > From http Fri Jan 18 05:56:13 2008 From: http (Paul Rubin) Date: 18 Jan 2008 02:56:13 -0800 Subject: Filtering two files with uncommon column References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> <5084371c-dba0-4d11-be95-a01d1b439de6@s12g2000prg.googlegroups.com> Message-ID: <7x1w8f2yia.fsf@ruckus.brouhaha.com> Madhur writes: > If the files2 is unordered, then the above logic does not work. How to > takle it? This sounds like a homework problem. Also, you are trying to reimplement the unix "comm" command. From gagsl-py2 at yahoo.com.ar Mon Jan 21 13:41:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 16:41:50 -0200 Subject: Trouble writing to database: RSS-reader References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> Message-ID: En Mon, 21 Jan 2008 14:12:43 -0200, Arne escribi?: > I try to make a rss-reader in python just for fun, and I'm almost > finished. I don't have any syntax-errors, but when i run my program, > nothing happends. > > This program is supposed to download a .xml-file, save the contents in > a buffer-file(buffer.txt) and parse the file looking for start-tags. > When it has found a start tag, it asumes that the content (between the > start-tag and the end-tag) is on the same line, so then it removes the > start-tag and the end-tag and saves the content and put it into a > database. That's a gratuitous assumption and may not hold on many sources; you should use a proper XML parser instead (using ElementTree, by example, is even easier than your sequence of find and replace) > The problem is that i cant find the data in the database! If i watch > my program while im running it, i can see that it sucsessfuly > downloads the .xml-file from the web and saves it in the buffer. Ok. So the problem should be either when you read the buffer again, when processing it, or when saving in the database. It's very strange to create the table each time you want to save anything, but this gives you another clue: the table is created and remains empty, else the select statement in print_rss would have failed. So you know that those lines are executed. Now, the print statement is your friend: self.buffer = file('buffer.txt') for line in self.buffer.readline(): print "line=",line # add this and see what you get Once you get your code working, it's time to analyze it. I think someone told you "in Python, you have to use self. everywhere" and you read it literally. Let's see: def update_buffer(self): self.buffer = file('buffer.txt', 'w') self.temp_buffer = urllib2.urlopen(self.rssurl).read() self.buffer.write(self.temp_buffer) self.buffer.close() All those "self." are unneeded and wrong. You *can*, and *should*, use local variables. Perhaps it's a bit hard to grasp at first, but local variables, instance attributes and global variables are different things used for different purposes. I'll try an example: you [an object] have a diary, where you record things that you have to remember [your instance attributes, or "data members" as they are called on other languages]. You also carry a tiny notepad in your pocket, where you make a few notes when you are doing something, but you always throw away the page once the job is finished [local variables]. Your brothers, sisters and parents [other objects] use the same schema, but there is a whiteboard on the kitchen where important things that all of you have to know are recorded [global variables] (anybody can read and write on the board). Now, back to the code, why "self." everywhere? Let's see, self.buffer is a file: opened, written, and closed, all inside the same function. Once it's closed, there is no need to keep a reference to the file elsewhere. It's discardable, as your notepad pages: use a local variable instead. In fact, *all* your variables should be locals, the *only* things you should keep inside your object are rssurl and the database location, and perhaps temp_buffer (with another, more meaningful name, rssdata by example). Other -more or less random- remarks: if self.titleStored == True and self.linkStored == True and descriptionStored == True: Don't compare against True/False. Just use their boolean value: if titleStored and linkStored and descriptionStored: Your code resets those flags at *every* line read, and since a line contains at most one tag, they will never be True at the same time. You should reset the flags only after you got the three items and wrote them onto the database. The rss feed, after being read, is available into self.temp_buffer; why do you read it again from the buffer file? If you want to iterate over the individual lines, use: for line in self.temp_buffer.splitlines(): -- Gabriel Genellina From fredrik at pythonware.com Wed Jan 9 16:25:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 22:25:25 +0100 Subject: ISO books of official Python docs In-Reply-To: References: Message-ID: Doug Morse wrote: > I'm terribly confused. You want me to apologize for recommending that someone > buy your books? To apologize for noting that they are a quality reference > sources for Python? for implying that the material in them is copied from the python.org handbooks. at least that's what "reproduce" means in my dictionary. From terry at jon.es Sun Jan 20 22:39:44 2008 From: terry at jon.es (Terry Jones) Date: Mon, 21 Jan 2008 04:39:44 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 04:19:51 on Monday, 21 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <18324.3927.640023.70736@terry.local> Message-ID: <18324.5120.406872.662872@terry.local> My output looks better sorted. I.e., for s in sorted(solutions)... Giving the easier to read/compare: Target 234, numbers = (100, 9, 7, 6, 3, 1) (6, 1, 'add', 100, 'mul', 7, 'sub', 9, 'add', 3, 'div') (6, 9, 'sub', 7, 'mul', 1, 'sub', 100, 'add', 3, 'mul') (7, 3, 'mul', 6, 'sub', 9, 'mul', 1, 'sub', 100, 'add') (7, 6, 'mul', 3, 'mul', 1, 'sub', 100, 'add', 9, 'add') (7, 6, 'mul', 3, 'mul', 100, 'sub', 9, 'mul', 1, 'mul') (100, 1, 'sub', 3, 'div', 7, 'mul', 6, 'sub', 9, 'add') (100, 1, 'sub', 7, 'mul', 9, 'sub', 3, 'div', 6, 'add') (100, 7, 'mul', 3, 'mul', 6, 'add', 9, 'div', 1, 'mul') * (100, 7, 'mul', 6, 'sub', 1, 'sub', 9, 'add', 3, 'div') (100, 7, 'sub', 3, 'div', 1, 'sub', 9, 'add', 6, 'mul') (100, 7, 'sub', 3, 'div', 6, 'sub', 1, 'add', 9, 'mul') (100, 9, 'add', 7, 'add', 1, 'add', 3, 'div', 6, 'mul') (100, 9, 'sub', 7, 'div', 6, 'mul', 3, 'mul', 1, 'mul') (100, 9, 'sub', 7, 'sub', 6, 'sub', 3, 'mul', 1, 'mul') Terry From mario at ruggier.org Wed Jan 2 03:24:59 2008 From: mario at ruggier.org (mario) Date: Wed, 2 Jan 2008 00:24:59 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? Message-ID: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> Hello! i stumbled on this situation, that is if I decode some string, below just the empty string, using the mcbs encoding, it succeeds, but if I try to encode it back with the same encoding it surprisingly fails with a LookupError. This seems like something to be corrected? $ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> s = '' >>> unicode(s, 'mcbs') u'' >>> unicode(s, 'mcbs').encode('mcbs') Traceback (most recent call last): File "", line 1, in LookupError: unknown encoding: mcbs Best wishes to everyone for 2008! mario From jim.hefferon at gmail.com Mon Jan 28 07:27:52 2008 From: jim.hefferon at gmail.com (Jim) Date: Mon, 28 Jan 2008 04:27:52 -0800 (PST) Subject: Can xml.sax NOT process the DTD? References: Message-ID: On Jan 28, 6:48 am, marek jedlinski wrote: > I've noticed that I can eliminate the error if I create 0-byte dtd files > and put them where the parser expects to find them, but this is a little > tedious, since there are plenty of different DTDs expected at different > locations. How about overriding the entity resolver in some way like this: class xResolver(EntityResolver): def resolveEntity(self, publicId, systemId): return "dummy.dtd" and then calling .setEntityResolver(xResolver()) ? That will always look in the same dtd file, which you say works for you. Jim From kyosohma at gmail.com Wed Jan 2 09:33:36 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 2 Jan 2008 06:33:36 -0800 (PST) Subject: Bind mouse over event for panel (or Static text) wxPython References: Message-ID: <4441d83a-9de8-4c06-902b-3dd267c3d199@s12g2000prg.googlegroups.com> On Jan 2, 6:55 am, SMALLp wrote: > How to? > > I couldn't find anything except EVT_ENTER_WINDOW that didn't work. I use wx.EVT_MOTION, which you would have found had you googled for "wxpython mouse events". The first result is: http://www.wxpython.org/docs/api/wx.MouseEvent-class.html which details all the mouse events in wxPython. As I have mentioned to you before, wxPython questions really ought to be addressed to the wxPython users group, which you can join here: http://wxpython.org/maillist.php Mike From george.sakkis at gmail.com Wed Jan 23 17:39:08 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 23 Jan 2008 14:39:08 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> <13pfdh31k2bp8eb@corp.supernews.com> Message-ID: <8f2a164c-5516-487f-802b-5651cb15b404@h11g2000prf.googlegroups.com> On Jan 23, 4:48 pm, Steven D'Aprano wrote: > As for your other points, I think we're actually very much in agreement, > except for your tolerance of random posters asking what I believe is an > incoherent question: "what's the fastest way to do ...?". It seems to me > you're willing to give them the benefit of the doubt that they've done > their profiling and considered their trade-offs, or at the very worst are > asking from purely intellectual curiosity. It depends on the specific problem and the context. For small well- defined algorithmic type problems, I just assume it's intellectual curiosity or that performance really matters. If the same question was asked in the context of, say, a typical web application fetching data from a database and rendering dynamic pages, I might have dismissed it as YAGNI. George From levilista at gmail.com Thu Jan 10 13:25:27 2008 From: levilista at gmail.com (zslevi@gmail.com) Date: Thu, 10 Jan 2008 10:25:27 -0800 (PST) Subject: What is "lambda x=x : ... " ? Message-ID: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> I'm reading this page: http://www.ps.uni-sb.de/~duchier/python/continuations.html and I've found a strange usage of lambda: #################### Now, CPS would transform the baz function above into: def baz(x,y,c): mul(2,x,lambda v,y=y,c=c: add(v,y,c)) ################### What does "y=y" and "c=c" mean in the lambda function? I thought it bounds the outer variables, so I experimented a little bit: ################# x = 3 y = lambda x=x : x+10 print y(2) ################## It prints 12, so it doesn't bind the variable in the outer scope. From ricaraoz at gmail.com Tue Jan 29 09:53:44 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 29 Jan 2008 11:53:44 -0300 Subject: REALLY simple xml reader In-Reply-To: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> Message-ID: <479F3DF8.4070308@bigfoot.com> > What about : > > doc = """ > > 99 > > > 42 > > """ That's not an XML document, so what about it? Stefan ---------------------------------------------- Ok Stefan, I will pretend it was meant in good will. I don't know zit about xml, but I might need to, and I am saving the thread for when I need it. So I looked around and found some 'real' XML document (see below). The question is, how to access s from s (any category) but not s. Probably my previous example was not properly stated, what I meant to convey is two substructures (namespaces, or whatever you call them in XML) which have the same 'properties' is not the same as as is not the same as . The examples given by Diez and Mark, though useful, don't seem to address the problem. Thanks for your help. doc = """ expenses: january 2002 31.19 200213 Walking Store shoes 1549.58 200217 Bob's Bolts 40 200218 pocket money 25 200218 188.20 200218 Boston Endodontics cavity 10.58 2002110 Exxon Saugus gasoline 909.56 2002114 Honda North car repairs 24.30 2002115 Johnny Rockets lunch """ From bill.wws at gmail.com Sun Jan 13 21:20:34 2008 From: bill.wws at gmail.com (bill.wu) Date: Sun, 13 Jan 2008 18:20:34 -0800 (PST) Subject: i am new guy for this discussion group References: <2c96a1ab-207c-4671-a529-358bdb51d4fc@f10g2000hsf.googlegroups.com> Message-ID: <9cf6638e-41ed-4c78-9d1b-aff6547f8ae3@e6g2000prf.googlegroups.com> On Jan 14, 2:03?am, "bruno.desthuilli... at gmail.com" wrote: > On Jan 13, 3:03 pm, "bill.wu" wrote: > > > i am new guy to learn python,also for this discussion group, i am > > chinese. > > nice to meet you, everyone. > > Hi and welcome onboard. > > If you're new to programming in general, you may want to join the > tutor mailing-list.http://mail.python.org/mailman/listinfo/tutor > > If you're already a programmer, you may want to follow the offficial > tutorial, then probably diveintopython:http://docs.python.org/tut/tut.htmlhttp://www.diveintopython.org/ > > HTH thank you very much. From steve at REMOVE-THIS-cybersource.com.au Thu Jan 24 19:58:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 25 Jan 2008 00:58:14 -0000 Subject: Terminology: "script" versus "program" References: <1666950d-e9a5-4b7c-a614-5bba90e5b4ca@y5g2000hsf.googlegroups.com> <87ir1j7r9k.fsf_-_@benfinney.id.au> Message-ID: <13pid16l607s065@corp.supernews.com> On Thu, 24 Jan 2008 12:22:04 +0000, samwyse wrote: >> The term "script" has the strong connotation of a limited-purpose >> program designed to solve a problem expressed almost entirely as a >> simple series of steps. Languages that are often used to write such >> scripts are usually referred to as "scripting languages", which becomes >> a denigration because such a language need not have support for much >> else. > > I strongly disagree with your interpretation. Scritping languages > provide high-level facilites for process control. Historically, they > were purely interpretive but now they tend to compile to some sort of > byte code. Examples include the various shells, Rexx, and various > languages whose names start with "P". Do you have a source for your claim that the shells (e.g. Linux/Unix shells bash, ksh, zsh, etc. or Windows shells cmd.exe, command.com) are compiled to byte code? I don't believe this is the case, I understand that they are typically "immediate interpreted" languages, that is, each line in interpreted from source code immediately before being executed, as often as it takes. Note to purists: yes, I know that being interpreted or compiled is a property of the implementation, not the language. But when all the implementations of a language (where "all" might mean "the only one"), I think it is reasonable to blur the lines. > Languages which only express a > "series of steps" are generally called batch languages. Maybe in the Windows/DOS world, but not typically in the Linux/Unix world, where they are called scripting languages. > I've never > heard anyone refer to a .BAT file as a script. Linux/Unix/Mac admins may be excused for saying that they've never come across a .BAT file at all. $ locate .bat | wc -l 14 Oh well, what do you know! I've got fourteen of the beggars. Hmmm... two are in the Python standard lib, two are in wxPython, six seem to be in the game Abuse, a couple of false positives, and a few odd files. $ locate .sh | wc -l 606 -- Steven From dongie.agnir at gmail.com Wed Jan 9 02:25:18 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Tue, 8 Jan 2008 23:25:18 -0800 (PST) Subject: Tracking colors Message-ID: I'm just getting started with Python, and I want to do a bit of color tracking using VideoCapture. However, I've never worked with video or images, so I'm a little at a loss. How would I use VideoCapture to track a specified color, and its coordinates? From ndbecker2 at gmail.com Mon Jan 14 07:56:05 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 14 Jan 2008 07:56:05 -0500 Subject: ucs2 or ucs4? Message-ID: How do I tell if my python-2.5 is build with ucs2 or ucs4? From james.pye at gmail.com Tue Jan 22 11:14:13 2008 From: james.pye at gmail.com (james.pye at gmail.com) Date: Tue, 22 Jan 2008 08:14:13 -0800 (PST) Subject: isgenerator(...) - anywhere to be found? References: <5vm8t3F1m1797U1@mid.uni-berlin.de> Message-ID: <0336d6a4-9dac-4a64-a189-2d8384046934@e10g2000prf.googlegroups.com> On Jan 22, 6:20?am, "Diez B. Roggisch" wrote: > For a simple greenlet/tasklet/microthreading experiment I found myself in > the need to ask the question > > isgenerator(v) > > but didn't find any implementation in the usual suspects - builtins or > inspect. types.GeneratorType exists in newer Pythons, but I'd suggest just checking for a send method. ;) That way, you can use something that emulates the interface without being forced to use a generator. hasattr(ob, 'send').. From stefan.behnel-n05pAM at web.de Mon Jan 7 03:43:55 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 07 Jan 2008 09:43:55 +0100 Subject: Patches to Python 2.5.1 In-Reply-To: References: Message-ID: <4781E64B.9050700@web.de> Brad wrote: > I was just looking through the 2.5.1 source code. I noticed a few > mis-spellings in the comments. No big deal really. Can patches be > submitted that correct the spelling errors or should they just be > pointed out to some mailing list? Funny you ask, if there were so few, you could already have added the patch anyway. :) However, I'd just submit it to Python's bug tracker. Broken documentation is something that should be fixed. Stefan From donn.ingle at gmail.com Mon Jan 14 17:55:07 2008 From: donn.ingle at gmail.com (Donn) Date: Tue, 15 Jan 2008 00:55:07 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478BD8AC.6050404@v.loewis.de> References: <200801141802.56353.donn.ingle@gmail.com> <478BD8AC.6050404@v.loewis.de> Message-ID: <200801150055.07699.donn.ingle@gmail.com> > You get the full locale name with locale.setlocale(category) (i.e. > without the second argument) Ah. Can one call it after the full call has been done: locale.setlocale(locale.LC_ALL,'') locale.setlocale(locale.LC_ALL) Without any issues? > > I need that two-letter code that's hidden in a > > typical locale like en_ZA.utf8 -- I want that 'en' part. Okay, I need it because I have a tree of dirs: en, it, fr and so on for the help files -- it's to help build a path to the right html file for the language being supported. > Not sure why you want that. Notice that the locale name is fairly system > specific, in particular on non-POSIX systems. It may be > "English_SouthAfrica" on some systems. Wow, another thing I had no idea about. So far all I've seen are the xx_yy.utf8 shaped ones. I will have some trouble then, with the help system. Thanks, \d -- "There may be fairies at the bottom of the garden. There is no evidence for it, but you can't prove that there aren't any, so shouldn't we be agnostic with respect to fairies?" -- Richard Dawkins Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From salgerman at gmail.com Thu Jan 3 23:44:33 2008 From: salgerman at gmail.com (gsal) Date: Thu, 3 Jan 2008 20:44:33 -0800 (PST) Subject: Problem reading csv files References: <1788604d-5fed-435a-a9f3-f7e9f652b5a3@s12g2000prg.googlegroups.com> Message-ID: <9e78ef2f-7532-41dd-935e-c1eea4b1bc58@j78g2000hsd.googlegroups.com> Well, I don't know much python, yet, but I know a csv file when I see one...and an Excel files in not a csv file. As far as I know, an Excel file is stored probably in binary and in a propriatery format...I doubt very much csv.reader would read that just like that; then again, I know nothing about cvs.reader. A csv file is a comma-separated-file and it is plain text file that humans can read with a simple editor... I think I would skip that part where you make OpenOffice store the file in Excel format and simply save it to plain text. Hope this helps. gsal From stefan.behnel-n05pAM at web.de Wed Jan 23 10:18:01 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 16:18:01 +0100 Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? In-Reply-To: References: Message-ID: <47975AA9.9010103@web.de> Hi, kliu wrote: > what I really need is the mapping between each DOM nodes and > the corresponding original source segment. I don't think that will be easy to achieve. You could get away with a parser that provides access to the position of an element in the source, and then map changes back into the document. But that won't work well in the case where the parser inserts or deletes content to fix up the structure. Anyway, the normal focus of broken HTML parsing is in fixing the source document, not in writing out a broken document. Maybe we could help you better if you explained what your actual intention is? Stefan From http Fri Jan 11 15:54:09 2008 From: http (Paul Rubin) Date: 11 Jan 2008 12:54:09 -0800 Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> Message-ID: <7xprw8w0b2.fsf@ruckus.brouhaha.com> dg.google.groups at thesamovar.net writes: > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > run() > > The idea is that the run() function inspects the stack, and looks for > object which are instances of class Obj, creates a Bigobj with those > objects and calls its run() method. > > So, any comments on that approach? Bleeearrrrrggggh!!!! Just make the object initializer remember where the instances are. Or, write something like: newobj = Bigobj() # give Bigobj a __call__ method to create and record an object obj1 = newobj(params1) obj2 = newobj(params2) ... newobj.run() From http Fri Jan 11 00:06:39 2008 From: http (Paul Rubin) Date: 10 Jan 2008 21:06:39 -0800 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> Message-ID: <7xir21lzmo.fsf@ruckus.brouhaha.com> erik gartz writes: > The loop performs some actions with web services. The particular > iteration I'm on isn't important to me. It is only important that I > attempt the web services that number of times. If I succeed I > obviously break out of the loop and the containing function (the > function which has the loop in it) returns True. If all attempts fail > the containing loop returns False. This uses an index var, but doesn't leak it outside the genexp, so I don't know what pylint would say (untested): def f(): return any(attempt_service() for i in xrange(10)) I think the above is pretty natural. If you really insist on not using any variables, the below might work (untested): from itertools import imap, repeat def f(): return any(imap(apply, repeat(attempt_service, 10))) it just seems way too obscure though. Python style seems to favor spewing extra variables around. From sjmachin at lexicon.net Wed Jan 23 17:50:21 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 14:50:21 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <7x8x2g8isi.fsf@ruckus.brouhaha.com> <13pfgdct573772d@corp.supernews.com> Message-ID: <416d70d4-35e5-457d-ad01-38725ded6ac7@s8g2000prg.googlegroups.com> On Jan 24, 9:47 am, ryan k wrote: > On Jan 23, 5:37 pm, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Wed, 23 Jan 2008 11:05:01 -0800, Paul Rubin wrote: > > > ryan k writes: > > >> Hello. I have a string like 'LNAME > > >> PASTA ZONE'. I want to create a list of those words and > > >> basically replace all the whitespace between them with one space so i > > >> could just do lala.split(). Thank you! > > > > import re > > > s = 'LNAME PASTA ZONE' > > > re.split('\s+', s) > > > Please tell me you're making fun of the poor newbie and didn't mean to > > seriously suggest using a regex merely to split on whitespace? > > > >>> import timeit > > >>> timeit.Timer("s.split()", "s = 'one two three four'").repeat() > > > [1.4074358940124512, 1.3505148887634277, 1.3469438552856445]>>> timeit.Timer("re.split('\s+', s)", "import re;s = 'one two > > > three four'").repeat() > > [7.9205508232116699, 7.8833441734313965, 7.9301259517669678] > > > -- > > Steven > > The main topic is not an issue anymore. We know that. This thread will continue with biffo and brickbats long after your assignment has been submitted :-) From gagsl-py2 at yahoo.com.ar Sat Jan 26 13:33:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 26 Jan 2008 16:33:50 -0200 Subject: Anybody has ported talib to Python via SWIG References: <6fa2a3e3-ab77-41dc-a01e-55770a764b0e@k39g2000hsf.googlegroups.com> Message-ID: En Thu, 24 Jan 2008 20:49:33 -0200, Aldo Ceccarelli escribi?: > Hi Everybody, > TaLib (technical analysis package with function indicators coded in C/C > ++, http://www.ta-lib.org ) has a complete library with source in C/C+ > +. > > I am new to SWIG (wrapper interface generator) and would really > appreciate any Python (.py) port of TaLib to be able to call and test > TaLib's functions (f.i. MACD, Parabolic SAR and so on) in some Python > (2.5) script. > > Do you have idea whether TaLib Python package has already been > generated and can be eventually downloaded anywhere? If Talib has a C API (not C++), the ctypes module can be used to call those C functions, so there is no need to write a special SWIG wrapper. In fact it may be much easier to do that way. ctypes is a standard module on Python 2.5, and is documented here: http://docs.python.org/lib/module-ctypes.html -- Gabriel Genellina From nagle at animats.com Fri Jan 18 12:54:46 2008 From: nagle at animats.com (John Nagle) Date: Fri, 18 Jan 2008 09:54:46 -0800 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. In-Reply-To: <479046a5$0$36403$742ec2ed@news.sonic.net> References: <478FAC5A.50206@animats.com> <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> <479046a5$0$36403$742ec2ed@news.sonic.net> Message-ID: <4790e693$0$36362$742ec2ed@news.sonic.net> John Nagle wrote: > Irmen de Jong wrote: >> Christian Heimes wrote: >>> John Nagle wrote: >>>> It's possible to use "pickle" for interprocess communication over >>>> pipes, but it's not straightforward. Another "gotcha". The "pickle" module seems to be OK with the translations of "universal newlines" on Windows, but the "cPickle" module is not. If I pickle Exception("Test") send it across the Windows pipe to the parent in universal newlines mode, and read it with cPickle's load() function, I get ImportError: No module named exceptions If I read it with "pickle"'s "load()", it works. And if I read the input one character at a time until I see ".", then feed that to cPickle's "loads()", that works. So cPickle doesn't read the same thing Python does in "universal newline" mode. Is there any way within Python to get the pipe from a child process to the parent to be completely transparent under Windows? John Nagle From vedrandekovic at gmail.com Wed Jan 23 11:37:15 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Wed, 23 Jan 2008 08:37:15 -0800 (PST) Subject: py2exe: python modules and applicaation Message-ID: Hello again, I'am working a simple application with wxpython, py2exe and directpython.After I write python code in my wxpython textctrl, then my application must save that code and create ( pgssetup2.py script ), and then with py2exe create (.exe) of the code. ( my application is builded with py2exe too ). Here is example of code the converts from .py to .exe: try: process2=subprocess.Popen(["python","pgssetup2.py","py2exe","- d","exe"],shell=True, stdout=subprocess.PIPE) stdout_value = process2.communicate()[0] except NameError,e: print e When I run this code before converting to exe it works fine but in .exe there is no error but It wont work. I think it's problem with modules py2exe and directpython how can I "append" that modules to my application? Regards, Vedran From wuwei23 at gmail.com Thu Jan 24 19:49:40 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jan 2008 16:49:40 -0800 (PST) Subject: Test driven development References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> <53bae618-0a57-470e-b698-3f936ef7c0e7@s12g2000prg.googlegroups.com> <98f3ca4c-a7f0-4707-b09d-8012b86de96b@x69g2000hsx.googlegroups.com> Message-ID: <273268bb-421f-4228-a16b-a64ea38869b8@m34g2000hsf.googlegroups.com> On Jan 25, 5:44 am, Roel Schroeven wrote: > I guess I just need to try somewhat harder to use TDD in my daily > coding. Apart from books, are there other resources that can help > beginners with TDD? Mailing lists, forums, newsgroups possibly? There's the Testing-in-Python mailing list. It's pretty low traffic but generally relevant: http://lists.idyll.org/listinfo/testing-in-python -alex23 From sromero at gmail.com Wed Jan 9 09:26:05 2008 From: sromero at gmail.com (Santiago Romero) Date: Wed, 9 Jan 2008 06:26:05 -0800 (PST) Subject: Converting a bidimensional list in a bidimensional array References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> Message-ID: <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> > > This is how I create the tilemap (and the clipboard, a copy of my > > tilemap): > > > def __init__( self, bw, bh, tiles ): > > self.tilemap = [] > > (...) > > for i in range(bh): > > self.tilemap.append([0] * bw) > def __init__( self, bw, bh, tiles ): > self.width, self.height = bw, bh > self.tilemap = array.array('b', [0]) * bw * bh > > Gives a pure linearization (you do the math for lines). Do you mean : tilemap[(width*y)+x] ? > def __init__( self, bw, bh, tiles ): > self.width, self.height = bw, bh > self.tilemap = [array.array('b', [0]) * bw for row in range(bh)] > > Gives a list of arrays. I punted on the type arg here; you should make > a definite decision based on your data. What do you think about: - Memory Performance: Of course, my maps will take ( 16 bytes / 2-4 bytes ) = 8 or 4 times less memory (32 / 64 bit processores) ... right? - Speed Performance: Do you think that changing from list to Array() would improve speed? I'm going to do lots of tilemap[y][x] checks (I mean, player jumping around the screen, checking if it's falling over a non-zero tile, and so). And thanks a lot for your answer :-) From sjmachin at lexicon.net Thu Jan 17 06:28:58 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 17 Jan 2008 03:28:58 -0800 (PST) Subject: reading a specific column from file References: <3149e879-b94d-443c-b056-d6cf5bad2688@h11g2000prf.googlegroups.com> Message-ID: On Jan 17, 8:47 pm, Hai Vu wrote: > Here is another suggestion: > > col = 2 # third column > filename = '4columns.txt' > third_column = [line[:-1].split('\t')[col] for line in open(filename, > 'r')] > > third_column now contains a list of items in the third column. > > This solution is great for small files (up to a couple of thousand of > lines). For larger file, performance could be a problem, so you might > need a different solution. Using the maxsplit arg could speed it up a little: line[:-1].split('\t', col+1)[col] From lars at larsjohansen.org Tue Jan 29 03:42:28 2008 From: lars at larsjohansen.org (Lars Johansen) Date: Tue, 29 Jan 2008 09:42:28 +0100 Subject: [HELP] SMTPlib not sending my mail In-Reply-To: References: Message-ID: <1201596148.7850.2.camel@lars-laptop.ez.no> have you checked your mail server logs ? tir, 29.01.2008 kl. 00.24 -0800, skrev ashok.raavi: > Hi, > > I am also facing the same problem, smtplib used to send mail a while > back but it stopped sending mails. > > when i run this in interpreter > >>> import smtplib > >>> s = smtplib.SMTP("localhost") > >>> s.sendmail(from, to, "message") > {} > >>> > > though it is not giving any error, it is not sending mail. > > Any help is appreciated. > > ornto wrote: > > Hi, I'm trying to create an application which checks a > > dynamic web site and on certain events sends an email to me. > > My problem though is with the email task. By now I made this > > simple test code: > > > > #prova invio email > > smtpserver = smtplib.SMTP(mailserver) > > messaggio= "Messaggio di prova" > > print mail > > print messaggio > > smtpresult=smtpserver.sendmail("Watcher",mail,messaggio) > > if smtpresult: > > print smtpresult > > smtpserver.quit() > > > > "mailserver" and "mail" values are loaded from a ini file > > and they're correct. > > The call to smtpserver gives back no errors (smtpresult > > remains empty). > > The running enviroment gives no error. > > So, it looks like that the program works alloright, sending > > the mail- BUT, I receive no mail! I've tried to change the > > smtp server with another one which still works with my isp, > > with no luck. If I try a smtp which doesn't give me access, > > I correctly receive an error from the program. > > What might be the problem? From pablo at decode.com.ar Wed Jan 9 09:08:31 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Wed, 09 Jan 2008 12:08:31 -0200 Subject: alternating string replace In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <4784D55F.9070004@decode.com.ar> cesco wrote: > Hi, > > say I have a string like the following: > s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... What about: >>> import re >>> s1 = 'hi_cat_bye_dog' >>> print re.sub(r'([^_]+)_([^_]+)_?', r'\1:\2;', s1) hi:cat;bye:dog; it still works for a longer string: >>> s1 = 'hi_cat_bye_dog_' + s1 >>> s1 'hi_cat_bye_dog_hi_cat_bye_dog' >>> print re.sub(r'([^_]+)_([^_]+)_?', r'\1:\2;', s1) hi:cat;bye:dog;hi:cat;bye:dog; From jgardner at jonathangardner.net Thu Jan 24 16:13:49 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 24 Jan 2008 13:13:49 -0800 (PST) Subject: object vs class oriented -- xotcl References: Message-ID: <2dc601fc-38de-4cf6-bed0-5bf8be06b29b@e6g2000prf.googlegroups.com> On Jan 24, 12:35 pm, William Pursell wrote: > I'm not sure that describes the method well. Basically, you can > instantiate an object A of class Foo, and later change A to be an > object of class Bar. Does Python support this type of flexibility? > As I stated above, I've been away from Python for awhile now, and am a > bit rusty, but it seems that slots or "new style" objects might > provide this type of behavior. The ability to have an object change > class is certainly (to me) a novel idea. Can I do it in Python? Short answer: yes, easily. Long answer: observe. >>> class Foo(object): ... def foo(self): print "Foo.foo" ... >>> class Bar(object): ... def foo(self): print "Bar.foo" ... >>> a = Foo() >>> a.__class__ = Bar >>> a.foo() Bar.foo From steve at REMOVE-THIS-cybersource.com.au Tue Jan 1 05:32:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 01 Jan 2008 10:32:06 -0000 Subject: using super References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> Message-ID: <13nk5l6oah7mh9b@corp.supernews.com> On Mon, 31 Dec 2007 22:56:41 -0800, iu2 wrote: > Indeed I might want to chain methods in all sort of ways: > @chain_call_before - call the parent's method before the derived method > @chain_call_after - call the parent's method after the derived method > @chain_call_sum - sum the result of the parent's method with the result > of the derived method > @chain_call_list - make a list from the result of the parent's method > and the result of the derived method Indeed there are all sorts of ways you might want to call the parent class' method. How about a @chain_call__multiply_by_seven_and_append_to_list decorator? [snip] >>simply remind people to call >> A.foo(self, ) within the definition of foo in B. > > Sorry, I can't agree to this (although there is nothing else I can do.. > . Reminding is not "simply" at all. Why REMIND people do stuff and not > let Python handle it automatically? But Python can't handle it automatically, not unless you do import read_my_mind_and_do_what_I_want first. (Module expected in Python 9.7, due out in 2058.) Since you have to call the superclass yourself, there's not that much difference between reminding people to call the superclass by hand, and reminding them to call some decorator. Admittedly, a decorator for the most common cases would be easier to use than super(), but I don't think it would make enough of a difference that it is worth changing Python's object model just to make it possible. As the Zen of Python says: "Special cases aren't special enough to break the rules." (or in this case, to change the rules). And as others have pointed out, if you really want this desperately enough, you can create a metaclass to handle it. -- Steven From MartinRinehart at gmail.com Mon Jan 7 08:09:15 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Mon, 7 Jan 2008 05:09:15 -0800 (PST) Subject: Python's great, in a word Message-ID: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> I'm a Java guy who's been doing Python for a month now and I'm convinced that 1) a multi-paradigm language is inherently better than a mono-paradigm language 2) Python writes like a talented figure skater skates. Would you Python old-timers try to agree on a word or two that completes: The best thing about Python is _______. Please, no laundry lists, just a word or two. I'm thinking "fluid" or "grace" but I'm not sure I've done enough to choose. From martyb1 at earthlink.net Fri Jan 11 01:48:43 2008 From: martyb1 at earthlink.net (Marty) Date: Fri, 11 Jan 2008 01:48:43 -0500 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: Mike Meyer wrote: > On Thu, 10 Jan 2008 22:36:56 -0500 Marty wrote: >> I recently faced a similar issue doing something like this: >> >> data_out = [] >> for i in range(len(data_in)): >> data_out.append([]) > > More succinctly: > > data_out = [] > for _ in data_in: > data_out.append([]) > > Or, as has already been pointed out: > > data_out = [[] for _ in data_in] That's nice. > >> This caused me to wonder why Python does not have a "foreach" statement (and >> also why has it not come up in this thread)? I realize the topic has probably >> been beaten to death in earlier thread(s), but does anyone have the short answer? > > But I'm curious - what's the difference between the "foreach" you have > in mind and the standard python "for"? > > <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> Message-ID: <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> On Jan 10, 3:37 am, Bruno Desthuilliers wrote: > I fail to see how the existence of JIT compilers in some Java VM changes > anything to the fact that both Java (by language specification) and > CPython use the byte-code/VM scheme. Because these "some Java VMs" with JIT compilers are the de facto standard used by millions; the spec is pretty much irrelevant (unless you're a compiler writer or language theorist). George From steve at REMOVE-THIS-cybersource.com.au Wed Jan 16 06:33:47 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Jan 2008 11:33:47 -0000 Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> <873asyclo0.fsf@benfinney.id.au> Message-ID: <13orqsrlp81ep71@corp.supernews.com> On Wed, 16 Jan 2008 17:46:39 +1100, Ben Finney wrote: > Christian Heimes writes: > >> Dennis Lee Bieber wrote: >> > Since all "variable" names in Python are references to objects, >> > anything accessed using a name is accessed by reference. >> >> Anybody using the terms variable, reference or call-by-value is most >> likely explaining Python the wrong way. > > The term "reference" is fine, since that's exactly how it works. One > gets at an object via some reference, be it a name or some access into a > container object. When an object has no more references to itself, it > becomes a candidate for garbage collection. And so on. The term "reference" *by itself* is fine, so long as there is no possibility of confusion with the very common concept of "call by reference" (or "pass by reference"). But since the Original Poster himself raised the question of whether Python is call by reference or call by value, that should be a great big warning flag to avoid the term "reference" until he's reset his brain. Python is not C, and if you talk about Python using C terminology without making it absolutely crystal clear that the semantics of that terminology is different in Python, then you'll just reinforce the O.P.'s misunderstandings. Python might have "references" in the generic sense, but in the specific sense that it is understood by most people with C/Pascal/Java/Perl experience, Python does not. -- Steven From jpeng at block.duxieweb.com Sun Jan 20 23:02:50 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Mon, 21 Jan 2008 12:02:50 +0800 Subject: object scope Message-ID: <4794196A.2020901@block.duxieweb.com> Please see the code below,what's the scope for object "name"? I thought it should be located in the while block, but it seems not really,it can be accessed out of while (the db[name] statement).Thanks in advance. db = {} def newuser(): prompt = 'login desired: ' while 1: name = raw_input(prompt) if db.has_key(name): prompt = 'name taken, try another: ' continue else: break pwd = raw_input('passwd: ') db[name] = pwd From stefan.behnel-n05pAM at web.de Sun Jan 27 04:30:42 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 27 Jan 2008 10:30:42 +0100 Subject: Sorting Large File (Code/Performance) In-Reply-To: References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <690cb460-fa8a-49a1-a6fa-69cdf480a918@i3g2000hsf.googlegroups.com> <7xir1hznuu.fsf@ruckus.brouhaha.com> Message-ID: <479C4F42.3010500@web.de> Gabriel Genellina wrote: > use the Windows sort command. It has been > there since MS-DOS ages, there is no need to download and install other > packages, and the documentation at > http://technet.microsoft.com/en-us/library/bb491004.aspx says: > > Limits on file size: > The sort command has no limit on file size. Sure, since no-one can ever try it with more than 640k, it's easy to state that there is no limit. :) Stefan From robert.kern at gmail.com Sat Jan 12 04:25:52 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 12 Jan 2008 03:25:52 -0600 Subject: Is unicode.lower() locale-independent? Message-ID: The section on "String Methods"[1] in the Python documentation states that for the case conversion methods like str.lower(), "For 8-bit strings, this method is locale-dependent." Is there a guarantee that unicode.lower() is locale-*in*dependent? The section on "Case Conversion" in PEP 100 suggests this, but the code itself looks like to may call the C function towlower() if it is available. On OS X Leopard, the manpage for towlower(3) states that it "uses the current locale" though it doesn't say exactly *how* it uses it. This is the bug I'm trying to fix: http://scipy.org/scipy/numpy/ticket/643 http://dev.laptop.org/ticket/5559 [1] http://docs.python.org/lib/string-methods.html [2] http://www.python.org/dev/peps/pep-0100/ Thanks. -- 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 ganeshborse at gmail.com Thu Jan 3 06:37:08 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 3 Jan 2008 03:37:08 -0800 (PST) Subject: PyObject_CallObject code dump after calling 4 times Message-ID: I have a following C++ code which uses PyObject_CallObject to evaluate expressions dynamically. This code sets the input parameters for the function also dynamically. After calling this function 4 times (with these shown values), PyObject_CallObject causes application to crash in frame_dealloc. 1) Can some one please help me understand why is this crash happening in frame_dealloc & how to solve it? 2) Is there anything wrong I am doing about incrementing or decrementing the reference counts of the object passed to PyObject_CallObject? 3) Is it because of the big value (2299265.500000) I am trying to convert from double to float using PyFloat_FromDouble? //========================= code reduced for readability =============== switch(ndtyp){ case(INT_T): { printf("PyInt_FromLong val %d, var %s \n",inputVar.nionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); val = PyInt_FromLong(inputVar.nionum); break; } case(LONG_T): { printf("PyLong_FromLong val %ld, var %s \n",inputVar.lionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); val = PyLong_FromLong(inputVar.lionum); break; } case(FLOAT_T): { printf("PyFloat_FromDouble val %f, var %s \n",inputVar.fionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); val = PyFloat_FromDouble(inputVar.fionum); break; } case(DOUBLE_T): { printf("PyFloat_FromDouble val %f, var %s \n",inputVar.dionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); val = PyFloat_FromDouble(inputVar.dionum); break; } case(STRING_T): { printf("PyString_FromString val %s, var %s \n",inputVar.ioString,pEvalFunc->pExprVarsArray[nCtr].szVarName); val = PyString_FromString(inputVar.ioString); break; } default: printf("Unknown data type [%d] for %s\n",ndtyp,pEvalFunc- >pExprVarsArray[nCtr].szVarName); } if(!val){ ret = -1; printf("Failed to convert %d %s to PyObject\n",ndtyp,pEvalFunc- >pExprVarsArray[nCtr].szVarName); fflush(stdout); Py_XDECREF(pTuple); break; } PyTuple_SetItem(pTuple, nCtr, val); Py_XDECREF(val); } // all variables are set, call Python function Py_XINCREF(pTuple); PyObject *pResult = PyObject_CallObject(pEvalFunc- >pPyEvalFunction,pTuple); Py_XDECREF(pTuple); if(PyErr_Occurred()){ PyErr_Print(); } else { char* plevel = NULL; if(NULL != (plevel = PyString_AsString(pResult))){ ret = 0; sprintf(szEvalResult,"%s",plevel); } } Py_XDECREF(pResult); ================================================ Following crash (back trace) appears when I run this in GDB. The expression that was getting evaluated at this time is: def DangerousQuantity(size,maxvol,adv): if((size<1000 and (maxvol<10000) and (size<0.001*adv))): return "Dangerous" else: return "FAIL" //--------------- Crash dump information & values of variables passed to this expression Categorizing the order pyParserEvaluator evaluating category function DangerousTactic PyString_FromString val R, var aestactic PyLong_FromLong val 1139, var endtime PyLong_FromLong val 599, var starttime PyLong_FromLong val 23, var Aggr PyObject_CallObject done, do Py_XDECREF-pTuple Final result FAIL doing Py_XDECREF(pResult pyParserEvaluator evaluating category function MediumTactic PyString_FromString val R, var aestactic PyLong_FromLong val 1139, var endtime PyLong_FromLong val 599, var starttime PyLong_FromLong val 23, var Aggr PyObject_CallObject done, do Py_XDECREF-pTuple Final result FAIL doing Py_XDECREF(pResult pyParserEvaluator evaluating category function SafeTactic PyString_FromString val R, var aestactic PyLong_FromLong val 1139, var endtime PyLong_FromLong val 599, var starttime PyLong_FromLong val 23, var Aggr PyObject_CallObject done, do Py_XDECREF-pTuple Final result FAIL doing Py_XDECREF(pResult pyParserEvaluator evaluating category function DangerousQuantity PyLong_FromLong val 1, var size PyLong_FromLong val 0, var maxvol PyFloat_FromDouble val 2299265.500000, var adv Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 82336688 (LWP 27652)] 0xc0000000 in ?? () (gdb) where #0 0xc0000000 in ?? () #1 0x0285e59e in frame_dealloc (f=0xf5a2f68c) at Objects/ frameobject.c:106 #2 0x0281a4b1 in PyEval_EvalCodeEx (co=0xf5a69990, globals=0x2884120, locals=0x0, args=0x288bca0, argcount=3, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2609 #3 0x0285f551 in function_call (func=0xf5a694c4, arg=0xf5a47c3c, kw=0x0) at Objects/funcobject.c:476 #4 0x027e1e04 in PyObject_Call (func=0xf5a2003c, arg=0xf5a47c3c, kw=0x0) at Objects/abstract.c:1688 #5 0x0281b3eb in PyEval_CallObjectWithKeywords (func=0xf5a694c4, arg=0xf5a47c3c, kw=0x0) at Python/ceval.c:3058 #6 0x027e1de3 in PyObject_CallObject (o=0xf5a694c4, a=0xf5a47c3c) at Objects/abstract.c:1679 #7 0x027dd6fd in pyParserEvaluator::EvaluateCategory (this=0xf5a08df0, nCatLevelId=1, pOrdData=0x4e84f40, szEvalResult=0x4e84b70 "Dangerous") at pyEvaluator.cpp:342 #8 0x0070da71 in ParseEvalDriver::categorizeOrder (this=0xf5a0cf20, pcatRuleCache=0xfeff4e20, pOrdData=0x4e84f40, szLevelResult=0x9876180) at IEvaluatorInterface.cpp:102 #9 0x0807e812 in HandleCheck (szTopic=0x96d0439 "CE/REQ_3_EX/NEW", szReplyTopic=0x96d0639 "CE/RES_3_EX/njl36a-7003_401", pBuff=0x9875688 "4056029121", nBuffLen=195, pUsr=0xfeff4e18) at cerule.cpp:4859 #10 0x0032130d in CMiTssSub::OnRecvMsg (this=0xf5aaf0b0, pszTopic=0x96d0439 "CE/REQ_3_EX/NEW", pszReplyTopic=0x96d0639 "CE/RES_3_EX/njl36a-7003_401", pmsg=0x98754e8) at src/mitss.cpp:1810 #11 0x0031dc01 in CMiTss::OnRecvMsg (pszTopic=0x96d0438 "/CE/REQ_3_EX/ NEW", pszReplyTopic=0x96d0638 "/CE/RES_3_EX/njl36a-7003_401", pszMsg=0x98755e8 "?T\207\t?T\207\t", nMsgLen=4, pUsr=0xf5aaf0b0) at src/mitss.cpp:466 #12 0x0032296c in CMiHelper::_worker (arg=0x96cfc44) at mihelper.cpp: 390 #13 0x00339701 in _vmt_proc (thread_arg=0x96d0250) at vmt.c:347 #14 0x002afdec in start_thread () from /lib/tls/libpthread.so.0 #15 0x00603a2a in clone () from /lib/tls/libc.so.6 =================================================================== From phd at phd.pp.ru Thu Jan 10 07:32:38 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 10 Jan 2008 15:32:38 +0300 Subject: SQLObject 0.8.7 Message-ID: <20080110123238.GF3070@phd.pp.ru> Hello! I'm pleased to announce the 0.8.7 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.8.7 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.8.6 ---------------- * With PySQLite2 do not use encode()/decode() from PySQLite1 - always use base64 for BLOBs. * MySQLConnection doesn't convert query strings to unicode (but allows to pass unicode query strings if the user build ones). DB URI parameter sqlobject_encoding is no longer used. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From duncan.booth at invalid.invalid Tue Jan 15 04:08:06 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Jan 2008 09:08:06 GMT Subject: import from question References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> Message-ID: iu2 wrote: > file a3.py: >======== > from a1 import the_number > import a2 > ... > > Why doesn't it work in the first version of a3.py? > Think of 'import a2' as being the same as: a2 = __import__('a2') and 'from a1 import the_number' as roughly the same as: the_number = __import__('a1').the_number In other words think of them as assignments and it should all make sense. From thomas.troeger.ext at siemens.com Fri Jan 11 05:11:51 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Fri, 11 Jan 2008 11:11:51 +0100 Subject: Embedding python code into text document question. References: Message-ID: Thanks guys, you've helped me very much :) Cheers & happy new year! From arnodel at googlemail.com Sun Jan 27 20:51:28 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 27 Jan 2008 17:51:28 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> Message-ID: On Jan 27, 6:32?pm, "Diez B. Roggisch" wrote: > Wildemar Wildenburger schrieb: > > > Andr? wrote: > >> Personally, I like the idea you suggest, with the modification that I > >> would use "." instead of "@", as in > > >> class Server(object): > >> ? ? def __init__(self, .host, .port, .protocol, .bufsize, .timeout): > >> ? ? ? ? pass > > > I like :) > > > However, you can probably cook up a decorator for this (not certain, I'm > > not a decorator Guru), which is not that much worse. > > > Still, I'd support that syntax (and the general idea.). > > Just for the fun of it, I implemented a decorator: > > from functools import * > from inspect import * > > def autoassign(_init_): > ? ? ?@wraps(_init_) > ? ? ?def _autoassign(self, *args, **kwargs): > ? ? ? ? ?argnames, _, _, _ = getargspec(_init_) > ? ? ? ? ?for name, value in zip(argnames[1:], args): > ? ? ? ? ? ? ?setattr(self, name, value) > ? ? ? ? ?_init_(self, *args, **kwargs) > > ? ? ?return _autoassign Nice! I've got a slight variation without magic argument names: def autoassign(*names): def decorator(f): def decorated(self, *args, **kwargs): for name in names: setattr(self, name, kwargs.pop(name)) return f(self, *args, **kwargs) return decorated return decorator class Test(object): @autoassign('foo', 'bar') def __init__(self, baz): print 'baz =', baz t = Test(foo=1, bar=2, baz=6) # or Test(6, foo=1, bar=2) print t.foo print t.bar print t.baz -- Arnaud From Russ.Paielli at gmail.com Mon Jan 28 01:31:08 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 22:31:08 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> <8763xe8vzd.fsf@benfinney.id.au> Message-ID: On Jan 27, 7:33 pm, Ben Finney wrote: > "Russ P." writes: > > On Jan 27, 5:13 pm, Wildemar Wildenburger > > wrote: > > > class Server(object): > > > def __init__(self, self.host, self.port, > > > self.protocol, self.bufsize, self.timeout): > > > pass > > > > ? > > > That makes sense to me. > > Not to me. 'self' is a name that doesn't exist until *after* that > 'def' statement is completed; in any other statement, that would mean > 'self.foo' in the same statement would raise a NameError. > > Special-casing it for a function declaration complicates the language > for little gain: the rules of what is valid when become more > complicated. Special cases aren't special enough to break the rules. > > -- > \ "I took a course in speed waiting. Now I can wait an hour in | > `\ only ten minutes." -- Steven Wright | > _o__) | > Ben Finney OK, then how about a special function that could be called from inside the constructor (or anywhere else for that matter) to initialize a list of data members. For example, self.__set__(host, port, protocol, bufsize, timeout) This would be equivalent to self.host = host self.port = port # etc. I'm not sure if that is technically feasible, but it would cut down on repetition of names. From ryan at ryankaskel.com Wed Jan 23 17:47:37 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 14:47:37 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <7x8x2g8isi.fsf@ruckus.brouhaha.com> <13pfgdct573772d@corp.supernews.com> Message-ID: On Jan 23, 5:37 pm, Steven D'Aprano wrote: > On Wed, 23 Jan 2008 11:05:01 -0800, Paul Rubin wrote: > > ryan k writes: > >> Hello. I have a string like 'LNAME > >> PASTA ZONE'. I want to create a list of those words and > >> basically replace all the whitespace between them with one space so i > >> could just do lala.split(). Thank you! > > > import re > > s = 'LNAME PASTA ZONE' > > re.split('\s+', s) > > Please tell me you're making fun of the poor newbie and didn't mean to > seriously suggest using a regex merely to split on whitespace? > > >>> import timeit > >>> timeit.Timer("s.split()", "s = 'one two three four'").repeat() > > [1.4074358940124512, 1.3505148887634277, 1.3469438552856445]>>> timeit.Timer("re.split('\s+', s)", "import re;s = 'one two > > three four'").repeat() > [7.9205508232116699, 7.8833441734313965, 7.9301259517669678] > > -- > Steven The main topic is not an issue anymore. From duncan.booth at invalid.invalid Wed Jan 9 03:59:17 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jan 2008 08:59:17 GMT Subject: stupid/style/list question References: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Giampaolo Rodola' wrote: > >> To flush a list it is better doing "del mylist[:]" or "mylist = []"? >> Is there a preferred way? If yes, why? > > The latter creates a new list object, the former modifies an existing > list in place. > > The latter is shorter, reads better, and is probably a bit faster in > most cases. > > The former should be used when it's important to clear a specific list > object (e.g. if there are multiple references to the list). I tried to measure this with timeit, and it looks like the 'del' is actually quite a bit faster (which I find suprising). C:\Python25\Lib>timeit.py -s "lista=range(10000)" "mylist=list(lista)" 10000 loops, best of 3: 81.1 usec per loop C:\Python25\Lib>timeit.py -s "lista=range(10000)" "mylist=list(lista)" "del mylist[:]" 10000 loops, best of 3: 61.7 usec per loop C:\Python25\Lib>timeit.py -s "lista=range(10000)" "mylist=list(lista)" "mylist=[]" 10000 loops, best of 3: 80.9 usec per loop In the first test the local variable 'mylist' is simply allowed to go out of scope, so the list is destroyed as its reference count drops to 0. In the third case again the list is destroyed when no longer referenced, but an empty list is also created and destroyed. Evidently the empty list takes virtually no time to process compared with the long list. The second case clears the list before destroying it, and appears to be significantly faster. Increasing the list length by a factor of 10 and it becomes clear that not only is #2 always fastest, but #3 always comes in second. Only when the lists are quite short (e.g. 10 elements) does #1 win (and even at 10 elements #2 beats #3). Unless I've missed something, it looks like there may be an avoidable bottleneck in the list code: whatever the slice delete is doing should also be done by the deletion code (at least if the list is longer than some minimum length). The most obvious thing I can see is that list_dealloc: if (op->ob_item != NULL) { /* Do it backwards, for Christian Tismer. There's a simple test case where somehow this reduces thrashing when a *very* large list is created and immediately deleted. */ i = Py_Size(op); while (--i >= 0) { Py_XDECREF(op->ob_item[i]); } PyMem_FREE(op->ob_item); } would be better written as a copy of (or even call to) list_clear which picks up op->ob_item once instead of every time through the loop. From no_one at here Wed Jan 30 09:25:54 2008 From: no_one at here (Iain Mackay) Date: Wed, 30 Jan 2008 14:25:54 -0000 Subject: Sine Wave Curve Fit Question Message-ID: <7eOdnXVrB-fQFD3anZ2dnUVZ8hednZ2d@giganews.com> Python Folks I'm a newbie to Python and am looking for a library / function that can help me fit a 1D data vector to a sine wave. I know the frequency of the wave, so its really only phase and amplitude information I need. I can't find anything in the most widely known libraries (they seem to be strong on polynomial fitting, but not, apparently, on trig functions) and I wondered if any one here had recommendations? Something that implemented IEEE 1057 , or similar, would be perfect. TIA Iain From paul.hankin at gmail.com Thu Jan 3 08:40:25 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 3 Jan 2008 05:40:25 -0800 (PST) Subject: Treating a unicode string as latin-1 References: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Message-ID: <319bb5ab-8a38-4892-9832-2b171c81c4ec@s12g2000prg.googlegroups.com> On Jan 3, 1:31 pm, Simon Willison wrote: > How can I tell Python "I know this says it's a unicode string, but I > need you to treat it like a bytestring"? u'Bob\x92s Breakfast'.encode('latin-1') -- Paul Hankin From boblatest at yahoo.com Tue Jan 22 03:45:36 2008 From: boblatest at yahoo.com (Robert Latest) Date: 22 Jan 2008 08:45:36 GMT Subject: Question on sort() key function Message-ID: <5vlopgF1mv4ekU1@mid.dfncis.de> Hello, I have this class: class File: def __init__(self): self.name = '' self.path = '' self.date = 0 self.mod_date = 0 self.keywords = [] self.url = '' ...and after creating a list of File objects called flist, I'd like to sort it like thus: flist.sort(key=File.mod_date.toordinal) However, Python says: AttributeError: class File has no attribute 'mod_date' Well if you ask me, there are many things that may be said about my File class, but the absence of the attribute 'mod_date' ain't one of them. What do you think? And yes, this loop works fine: for f in flist: print f.mod_date.isoformat() (which IMO proves that all mod_date members are properly initialized as datetime objects). robert From siona at chiark.greenend.org.uk Fri Jan 4 12:01:28 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 04 Jan 2008 17:01:28 +0000 (GMT) Subject: python interfaces References: Message-ID: hyperboreean wrote: >Why doesn't python provide interfaces trough its standard library? Because they're pointless. Java interfaces are a hack around the complexities of multiple inheritence. Python does multiple inheritence Just Fine (give or take the subtleties of super()) so does not need them. Interfaces used purely with the idea of type safety provide precious little gain for the added clutter and inconvenience. Compare them to Java's requirement for explicit declaration of exceptions thrown in a method signature, if you will. -- \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 gnewsg at gmail.com Tue Jan 8 10:34:06 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 8 Jan 2008 07:34:06 -0800 (PST) Subject: stupid/style/list question Message-ID: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> I was wondering... To flush a list it is better doing "del mylist[:]" or "mylist = []"? Is there a preferred way? If yes, why? From bruno.desthuilliers at gmail.com Tue Jan 29 18:34:23 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 29 Jan 2008 15:34:23 -0800 (PST) Subject: Decision (if, else) routine is not working as intended with CGI module References: <9dc9f5d3-2392-48d6-8cb4-8b31c1ce4af9@e6g2000prf.googlegroups.com> Message-ID: <597dcd4e-8e0d-4df7-9f2f-6fcd8d3963bc@e6g2000prf.googlegroups.com> On 29 jan, 21:23, epsilon wrote: > All: > > I'm running into trouble figuring this one out. It seems that my > decision routine is not working as intended. Does anyone know why my > output continues to utilize the "else" portion of the routine. Probably because the test expression 'tag_form["fse00"] == ""' evals to false ? Hint: try printing out tag_form["fse00"] before the test, ie: (snip) > > #!/usr/bin/python > > import cgi > > print "Content-type: text/plain\n" > tag_form = cgi.FieldStorage(keep_blank_values=True) > print "tag_form[\"fse00\"] is actually: %s" % tag_form["fse00"] print "tag_form[\"fse00\"] == '' evals to: %s" % (tag_form["fse00"] == '') > if tag_form["fse00"] == "": > fse000 = {"fse00": "0"} > tag_form.update(fse000) > print "Printing fse000: ", tag_form["fse00"] > else: > print "Printing fse00: ", tag_form["fse00"] HTH From duncan.booth at invalid.invalid Thu Jan 10 07:03:39 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Jan 2008 12:03:39 GMT Subject: for loop without variable References: Message-ID: erik gartz wrote: > Hi. I'd like to be able to write a loop such as: > for i in range(10): > pass > but without the i variable. The reason for this is I'm using pylint > and it complains about the unused variable i. I can achieve the above > with more lines of code like: > i = 0 > while (i != 10): > i += 1 > Is there a concise way to accomplish this without adding extra lines > of codes? Thanks in advance for your help. Google for: pylint unused It pointed me at: > Question: > I've a function / method which is a callback where I do not have any > control on received argument, and pylint is complaining about unused > arguments. What can I do to avoid those warnings ? > > Answer: > prefix (ui) the callback's name by cb_, as in cb_onclick(...). By doing > so arguments usage won't be checked. Another solution is to use one of > the name defined in the "dummy-variables" configuration variable for > unused argument ("_" and "dummy" by default). http://www.iaeste.or.at/doc/python2.3-pylint/html/FAQ.html So it looks like you can use 'dummy' or add any other names you want to the configuration. From jpeng at block.duxieweb.com Tue Jan 22 00:37:43 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Tue, 22 Jan 2008 13:37:43 +0800 Subject: read files In-Reply-To: References: <7xbq7e5wxt.fsf@ruckus.brouhaha.com> Message-ID: <47958127.8050208@block.duxieweb.com> Gabriel Genellina ??: > En Tue, 22 Jan 2008 02:03:10 -0200, Paul Rubin > <"http://phr.cx"@NOSPAM.invalid> escribi?: > >> "J. Peng" writes: >>> print line, >> Do you really want all the lines crunched together like that? If not, >> leave off the comma. > > Remember that Python *keeps* the end-of-line charater at the end of each > line; if you leave out the comma, you'll print them doubly spaced. > Most languages (AFAIK) keep the newline character at the end of lines when reading from a file.But python's difference is its 'print' built-in function add a newline automatically for you. So without that ',' we will get double newlines. From steve at holdenweb.com Fri Jan 25 10:33:58 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 Jan 2008 10:33:58 -0500 Subject: read and readline hanging In-Reply-To: References: Message-ID: Olivier Lefevre wrote: > I am calling subprocess.Popen with > p = Popen(args, bufsize=-1, stdin=PIPE, stdout=PIPE, stderr=PIPE) > and after sending come command to the process, I try to read > from p.stdout but after a few calls I hang. What is the correct > way to do this, i.e., to read everything w/o getting stuck? I am > not familiar with all these low-level functions and their annoying > blocking behaviour. Note that I don't want to close the process > because I want to send more commands to it after that, read the > results, and so on and on. > While I realise it isn't easy to determine what's going on in a hung program, I might ask what you have tried already? I can think of at least two reasons why your program might hang: 1. The subprocess has stopped producing output. If you are only reading its standard output, are you sure that the subprocess is flushing its buffers so you can recognize it's time to provide more input? Are you simply failing to provide more input? 2. The subprocess has blocked because it has filled its stderr buffer and is waiting for something (i.e. your program) to read it. To eliminate the second possibility use stderr=STDOUT, which will then have both streams written to standard output. In general subprocess management is much tricker and subtler than most people expect when they first dive into it, and I suspect your problem is a manifestation of that fact. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From celoserpa at gmail.com Tue Jan 29 12:52:58 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Tue, 29 Jan 2008 15:52:58 -0200 Subject: Implementation of IBuyable or Interface? Message-ID: <1e5bcefd0801290952n9e3bffdre30cff32be5b2072@mail.gmail.com> Hello! It's more a design question than anything python specific. If anyone could help me, I would be grateful. If it's not the right place for this subject, please advise. I've got a IBuyable interface. The app can sell both Products and Services (Both "Buyables"). I'm not sure if Product and Service should also be represented as interfaces (inherited from IBuyable) or if they are actually directly implementations of IBuyable. What do you think? Thanks, Marcelo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From xng at xs4all.nl Sun Jan 13 20:21:28 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Mon, 14 Jan 2008 02:21:28 +0100 Subject: How to get user home directory on Windows In-Reply-To: References: Message-ID: <478ab8a1$0$20930$e4fe514c@dreader19.news.xs4all.nl> Giampaolo Rodola' wrote: > Hi all, > I'm trying to use the pywin32 extension to find out the user's home > directory but currently I didn't find a solution yet. > What I'd need to do is not getting the home directory of the currently > logged in user but something like: > >>>> get_homedir("frank") > "C:\home\users\frank" >>>> get_homedir("josh") > "C:\home\users\josh" > > Is there a way to do that? > I tried to search through the Pywin32 documentation with no luck. > In addition I'm not practiced with the Windows API at all. Well, windows, to my knowledge, uses the same base path for all profiles (this is not true for the My Documents folder which can differ). So what you could do is get the location from the ALLUSERPROFILE environment variable, go one folder higher and iterate through that. Ignoring the folders for the 'pseudo' users: 'All Users', 'Default User', 'LocalService' and 'NetworkService'. hth -- mph From sromero at gmail.com Wed Jan 9 09:48:35 2008 From: sromero at gmail.com (Santiago Romero) Date: Wed, 9 Jan 2008 06:48:35 -0800 (PST) Subject: How to get memory size/usage of python object Message-ID: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> Is there a way to check the REAL size in memory of a python object? Something like > print sizeof(mylist) or > print sizeof(myclass_object) or something like that ... Thanks. From deets at nospam.web.de Tue Jan 22 03:42:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 09:42:48 +0100 Subject: Calculate net transfer rate without dummy file In-Reply-To: References: Message-ID: <5vlokaF1nbp4iU1@mid.uni-berlin.de> whatazor schrieb: > Hi, > how can I calulate transfer rate to a host , without using a file ? > can ping module (written by Jeremy Hylton) be useful ? You can't measure without transmitting data. It's not only the network connection between the two hosts that is important, but also the sending and receiving processes, if they can cope with the amount of data or not and so forth. Diez From jpeng at block.duxieweb.com Wed Jan 30 20:51:45 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Thu, 31 Jan 2008 09:51:45 +0800 Subject: python modules collection Message-ID: <47A129B1.6000301@block.duxieweb.com> Hello, Is there a site for python,which collects most kinds of python modules? like CPAN for Perl. Sometime I want to use a module,like the time/date modules,don't know where I should search from. Sorry if I have repeated this question on the list. Thanks! From sromero at gmail.com Mon Jan 21 05:17:37 2008 From: sromero at gmail.com (Santiago Romero) Date: Mon, 21 Jan 2008 02:17:37 -0800 (PST) Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> <479451D9.3060207@block.duxieweb.com> Message-ID: Thanks all for the answers ... I'll use a tuple as you said :) Anyway, is interesting to know how to sort 2 lists when you dont want to use tuples, so thanks also to Peter :) > Then one have to split the list twice.Given the list is large,it's maybe > not good for performance.Is it a more effective split way? Well, I just use: rows = i.split(' ') a = rows[3] b = rows[5] X-D From mr.cerutti at gmail.com Thu Jan 17 10:23:05 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 17 Jan 2008 10:23:05 -0500 Subject: Is this a bug, or is it me? In-Reply-To: References: Message-ID: <51302a8c0801170723p35097f2avcb1b19964ef28dd9@mail.gmail.com> On Jan 17, 2008 10:05 AM, wrote: > Hello all, > For some reason, the following does not work : > > > class C: > TYPES = [None] > DICT = {} > for Type in TYPES: > DICT.update((E,Type) for E in [1]) > > >>> NameError: global name 'Type' is not defined > > > What do you think? Is this a bug? You cannot access a class's class variables in it's class-statement scope, since the name of the type is not bound until after the class statement is completed. Try: class C: TYPES = [None] DICT = {} for Type in C.TYPES: C.DICT.update((E, Type) for E in [1]) -- Neil Cerutti From steve at REMOVE-THIS-cybersource.com.au Thu Jan 31 10:50:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 31 Jan 2008 15:50:26 -0000 Subject: REALLY simple xml reader References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> <87tzkujeq6.fsf@benfinney.id.au> Message-ID: <13q3ri2707niqc6@corp.supernews.com> 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. "You know Bob, XML just isn't hostile enough to anyone silly enough to believe it's 'human-readable'. What can we do to make it more hostile?" "Well Fred, how about making the XML declaration completely optional, so you can leave it out and still be vald XML, but if you include it, you're not allowed to precede it with semantically neutral whitespace?" "I take my hat off to you." This is legal XML: """ Hello, world!""" and so is this: """ Hello, world!""" but not this: """ Hello, world!""" You can't get this sort of stuff except out of a committee. -- Steven From azam.farooq3 at gmail.com Sat Jan 12 06:59:46 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Sat, 12 Jan 2008 03:59:46 -0800 (PST) Subject: Looking for GSM Mobile Phone www.enmac.com.hk Message-ID: <7da8882a-aee7-486f-a8e3-81431fb4cbfc@q77g2000hsh.googlegroups.com> ENMAC Digital Quran Mobile includes Full Quran with Text and Translation in different languages, Tafaseer books, Ahadees Books, Universal Qibla Direction, Prayer Timing and much more at good price, please contact us for best prices and visit our website http://www.enmac.com.hk for more information. From mwm-keyword-python.b4bdba at mired.org Sat Jan 12 15:47:05 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Sat, 12 Jan 2008 15:47:05 -0500 Subject: super, decorators and gettattribute In-Reply-To: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> Message-ID: <20080112154705.347fa23e@bhuda.mired.org> On Sat, 12 Jan 2008 10:45:25 -0800 (PST) Richard Szopa wrote: > Hello all, > > I am playing around w/ Python's object system and decorators and I > decided to write (as an exercise) a decorator that (if applied to a > method) would call the superclass' method of the same name before > doing anything (initially I wanted to do something like CLOS > [1] :before and :end methods, but that turned out to be too > difficult). > > However, I cannot get it right (specially, get rid of the eval). I > suspect that I may be misunderstanding something happening between > super objects and __getattribute__ methods. > > Here's my code: > > def endmethod(fun): > """Decorator to call a superclass' fun first. > > If the classes child and parent are defined as below, it should > work like: > > >>> x = child() > >>> x.foo() > I am parent's foo > I am child's foo. > """ > name = fun.__name__ > def decorated(self, *args, **kwargs): > try: > super_object = super(self.__class__, self) There's an apparently common bug here: you don't want to pass super self.__class__, but the class that the method is bound to. The two aren't the same, as an instance of a subclass will have the subclass as self.__class__, and not the current class. So super will return the current class or a subclass of it, meaning (since you invoked this method from self) you'll wind up invoking this method recursively. All of which means your decorator is probably going to have to take the class as an argument. > # now I want to achieve something equivalent to calling > # parent.foo(*args, **kwargs) > # if I wanted to limit it only to this example > > # this doesn't work: in the example, it calls child's foo, > # entering in an eternal loop (instead of calling parent's > # foo, as I would expect). > > # super_object.__getattribute__(name)(*args, **kwargs) > > # this does work, but I feel it's ugly > eval('super_object.%s(*args, **kwargs)' % name) > except AttributeError: > pass # if parent doesn't implement fun, we don't care > # about it > return fun(self, *args, **kwargs) # hopefully none > > decorated.__name__ = name > return decorated > > > class parent(object): > def foo(self): > print 'I am parent\'s foo' > > class child(parent): > @endmethod > def foo(self): > print "I am foo\'s foo." > > if __name__=='__main__': > x = child() > x.foo() > > Can anybody tell me how to call a superclass method knowing its name? The same way you call any object's methods if you know it's name": getattr(super_object, name)(*args, **kwargs) The code seems to work the way you want: >>> x.foo() I am parent's foo I am foo's foo. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From halcyon1981 at gmail.com Fri Jan 25 19:46:59 2008 From: halcyon1981 at gmail.com (David Erickson) Date: Fri, 25 Jan 2008 16:46:59 -0800 (PST) Subject: Email module, how to add header to the top of an email? References: <97c04812-3b66-4d84-9e92-21de72a3ca56@c23g2000hsa.googlegroups.com> <088eeaff-8251-49a4-9202-a9481f5e8aaa@x69g2000hsx.googlegroups.com> Message-ID: <476b67e8-ce42-4357-ba2a-90ed757e6c6a@y5g2000hsf.googlegroups.com> On Jan 25, 5:04 am, "Karlheinz Klingbeil" wrote: > Am 25.01.2008, 06:21 Uhr, schrieb David Erickson : > > > Bottom of the headers... but I am looking to insert at the top, and re- > > ordering/inserting does matter depending on what type of header you > > are, received headers for example must be inserted at the top of the > > header list so you can watch the progression of the email. I was > > unable to find a clean way to do this via the API which seems very > > strange to me.. but perhaps I am just missing something? > > I think your are really missing something. First, Email-headers are > unordered > and every relay can, and probably will, rearrange them, add or delete > headers. > You therefore most definitely should not add any headers which are > position-dependent. > If you want to track mails somehow, add headers with timestamps. > This way you can watch the progression of an email without being > dependend on "sorted" headerlines. This is incorrect, quoting directly from RFC 2822: It is important to note that the header fields are not guaranteed to be in a particular order. They may appear in any order, and they have been known to be reordered occasionally when transported over the Internet. However, for the purposes of this standard, header fields SHOULD NOT be reordered when a message is transported or transformed. More importantly, the trace header fields and resent header fields MUST NOT be reordered, and SHOULD be kept in blocks prepended to the message. See sections 3.6.6 and 3.6.7 for more information. Trace header fields are not to be ordered, and should be prepended when added to a message. Now that said I am not trying to track anything, I simply want to prepend my additional headers onto the top of the email, and seem to be unable to do that via the API, which I think ought to be possible. If for example I was writing some kind of an SMTP server with Python and needed to add said trace headers they would need to be prepended, and currently cannot be (without doing it by hand). -David From Russ.Paielli at gmail.com Thu Jan 24 13:57:15 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 24 Jan 2008 10:57:15 -0800 (PST) Subject: Linux Journal Survey References: <1666950d-e9a5-4b7c-a614-5bba90e5b4ca@y5g2000hsf.googlegroups.com> Message-ID: <56eb736f-5ba3-417a-a4c1-3a310a67c3d3@s12g2000prg.googlegroups.com> 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. From gagsl-py2 at yahoo.com.ar Wed Jan 30 00:58:35 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jan 2008 21:58:35 -0800 (PST) Subject: Replacing call to PyObject_CallObject with PyEval_CallFunction References: <5a99ab95-e225-4085-bce4-ea31da557d6d@j78g2000hsd.googlegroups.com> Message-ID: <740a5e65-64c3-45dc-95bf-691978fb4290@f47g2000hsd.googlegroups.com> On 30 ene, 01:58, grbgooglefan wrote: > How do I pass the elements populated in struct variables of this > vector dynamically to PyEval_CallFunction, in the fashion somewhat > like below? > PyEval_CallFunction(obj, "iii", vector[0].ioparam->nionum,vector[1].ioparam->nionum,vector[2].ioparam->nionum); > > PyEval_CallFunction(obj, "di", vector[0].ioparam->fionum,vector[1].ioparam->nionum); > > PyEval_CallFunction(obj, "diiisis", vector[0].ioparam->fionum,vector[1].ioparam->nionum,vector[2].ioparam- > >nionum,vector[3].ioparam->nionum,vector[4].ioparam- > >ioString,vector[5].ioparam->nionum,vector[6].ioparam->ioString); I didn't know of PyEval_CallFunction until now, but aparently the lines above are OK. Can't you use it that way? What's your problem? -- Gabriel Genellina From dima.hristov at gmail.com Mon Jan 21 06:57:12 2008 From: dima.hristov at gmail.com (DHR) Date: Mon, 21 Jan 2008 03:57:12 -0800 (PST) Subject: How to use py2exe ... References: Message-ID: Here is how I am creating my win32 exe with py2exe: 1. create a setup.py file with the following: from distutils.core import setup import py2exe #setup(console=['main_script.py']) setup(windows=['main_script.py'] ) 2. run the following command from console: 'python setup.py py2exe' Hope this helps. On Jan 21, 9:45 am, Santiago Romero wrote: > Hi... > > I'm a Linux user, and I would like some windows-friends to test a > game I'm writing with python+pygame without they needing to install > python, pygame, and so on. > > I've heard about py2exe and pygame2exe, but I'm not sure on how to > use them to create: > > a.- standalone exe files with a single .py program. > Example: myprogram.py > > or > > b.- exe files containing all my source code + data directories (png > files, data files, and so). > Example: main.py, doc/README, src/*.py and data/* > > The problem is I'm not sure on how to use py2exe and pygame2exe to > build the executables... > > And finally, a question: if I want to provide source code > separately ... can I include .pyc files instead of .py files? From yann.le_boulanger at u-paris10.fr Fri Jan 25 11:27:17 2008 From: yann.le_boulanger at u-paris10.fr (Yann Leboulanger) Date: Fri, 25 Jan 2008 17:27:17 +0100 Subject: Icon in a gtk.Entry In-Reply-To: References: Message-ID: <479a0dd4$0$1229$426a74cc@news.free.fr> johnthawk at excite.com wrote: > > Hello all, > > I have two thing I wish to accomplish, First, put an icon in a gtk.Entry as in many search boxes. Second put a gtk.Checkbox in a gtk.ComboboxEntry. On the later I thought I could get a handle to the Combobox tree and then add a column and then column span column 1 back into column 0 , thus a gtk.ToggelRender would be visible in column 0. But I had no luck getting a handle to the Combobox tree. For the first one, look at libsexy: http://www.chipx86.com/wiki/Libsexy For using a ToggleRenderer, look at pygtk tuto: http://pygtk.org/pygtk2tutorial/sec-CellRenderers.html#sec-ActivatableToggleCells -- Yann From mani.sabri at gmail.com Mon Jan 28 13:27:16 2008 From: mani.sabri at gmail.com (mani) Date: Mon, 28 Jan 2008 10:27:16 -0800 (PST) Subject: Embeding python with mingw on win32 and python 2.4.4 Message-ID: <43e347ca-1c61-4527-aa47-14f93cef3179@y5g2000hsf.googlegroups.com> Hi I'm bringing up an old story once more! I'm on win32 (winxp sp2) python 2.4.4. mingw gcc version is 3.4.5. msys is in c:\msys. mingw is in c:\mingw and python is in c:\pyton24. there is also python24.lib and libpython24.a in c:\python24\libs. when I try to compile this sample code [1] from with command [2] in msys shell I get the results [3]. this subject was discussed a few times over these years and I tried everything in the posts and forums that I found and google could translate with no success. I realy need your suggestion! Regards, Mani [1] Sample code: #include int main(int argc, char *argv[]) { Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } [2] Command: $ g++ -I/c/python24/include -I/c/MinGW/include -L/c/python24/libs -L/c/ mingw/lib -lpython24 -shared -mwin32 -o p1 p1.o [3] Results: p1.o:p1.cpp:(.text+0x2b): undefined reference to `_imp__Py_Initialize' p1.o:p1.cpp:(.text+0x39): undefined reference to `_imp__PyRun_SimpleString' p1.o:p1.cpp:(.text+0x40): undefined reference to `_imp__Py_Finalize' collect2: ld returned 1 exit status From domma at procoders.net Fri Jan 4 09:54:21 2008 From: domma at procoders.net (Achim Domma) Date: Fri, 4 Jan 2008 06:54:21 -0800 (PST) Subject: Details about pythons set implementation Message-ID: Hi, I'm interested in details about how sets are implemented in python. They seem to be quite fast and I found some remarks who state, that the implementation is highly optimized. I need to implemented sets in C/C++ and need a starting point on how to do it right. Could somebody give me a starting point? regards, Achim From mal at egenix.com Fri Jan 4 11:56:05 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 04 Jan 2008 17:56:05 +0100 Subject: Memory Leaks and Heapy In-Reply-To: <7f692fec0801040823q14d16429y370ffceaf046a6f3@mail.gmail.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> <477E5A73.9070400@egenix.com> <7f692fec0801040823q14d16429y370ffceaf046a6f3@mail.gmail.com> Message-ID: <477E6525.3010805@egenix.com> On 2008-01-04 17:23, Yaakov Nemoy wrote: > On Jan 4, 2008 11:10 AM, M.-A. Lemburg wrote: >> If you're using lots of small objects, you may be running into a >> problem with the Python memory allocation mechanism, pymalloc. It used >> to not return memory to the system. In Python 2.5 (IIRC, could be >> 2.6) this was changed to at least return completely empty blocks >> back to the OS. For details, see Objects/obmalloc.c > > The most common answer I heard was possible fragmentation, meaning > there are no or few completely empty blocks to be found. If there are > no 'leaks' in the VM, then it's probably related to how memory is > freed. You can check for this by using a special build of Python with disabled PyMalloc - Python will then use the standard OS malloc for all object allocations. It still uses free lists for a couple of object types, but those won't cause major leak problems. Alternatively, try to tune the PyMalloc implementation (see objmalloc.c), e.g. enable WITH_MEMORY_LIMITS. >> This could be caused by interned strings which are kept in a special >> pool dictionary to speed up string comparisons. > > That's quite possible, a majority of the code is a huge number of SQL > connections and code. All string based. Note that strings are normally *not* interned. However, you can write code in a way that causes Python to intern more strings than needed, e.g. if you dynamically compile code in your app, which then causes all identifiers in the compiled code to be interned. The interned dictionary is not exposed in Python, but you can access it using a debugger via Objects/stringobject.c:interned. >> However, the first thing to check is whether any of the C extension >> modules you are using is leaking memory. Python itself is usually >> well tested for memory leaks, but this is less so for C extension >> modules and it's easy to mis a few Py_DECREFs (decrementing a >> Python object's reference count), causing objects to live forever. > > I'll try to track it down, but AFAIK, most of the code is python, and > the only C code there would be is the MySQL container. How can I > debug the VM though, to determine where the leak lies? Heapy wasn't > able to tell me this, and this is the important aspect. I'm wondering > how most people go about determining the causes of leaks like these, > so I can provide some accurate bug information. Building Python in debug mode provides some help with this. You can then detect whether objects get properly freed. Doing explicit garbage collection via the gc module also helps in narrowing down the leak. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jan 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From python at rcn.com Wed Jan 9 15:56:46 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 9 Jan 2008 12:56:46 -0800 (PST) Subject: Structure of packages References: Message-ID: <49bc33e0-7980-41f1-aef6-788c54d53df6@e10g2000prf.googlegroups.com> [Ben Fisher] > I am trying to learn the best way to do intra-package references. IMO, the email package is a stellar example of best practices using packages. > I have layered the dependencies so that a depends on b, >b depends on c, and c depends on d. For the most part, I think packages tend to be over-used and can create more problems than they solve. They were added as tool for managing *very* large code bases and for helping resolve namespace collisions between tools with similiar APIs. Your layering application may also be a good use but I haven't seen packages used that way before. Raymond From rw at smsnet.pl Thu Jan 17 14:46:58 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 17 Jan 2008 20:46:58 +0100 Subject: examples of logger using smtp References: Message-ID: <87wsq85j65.fsf@merkury.smsnet.pl> DwBear75 writes: > I am hoping to find some simple examples of how to create a logger > instance using smtphandler. I don't want to create a separate ini > file. I just want to sent the smtphost, from, to right in the code > when I instantiate the logger. I can't seem to find simple code on how > to do this. Any pointers ? If you need to use smtp authentication there is a small problem with `SMTPHandler`. Actually, you need to subclass `SMTPHandler` and override `emit` method, e.g.: from logging import getLogger, Formatter, DEBUG from logging.handlers import SMTPHandler class SMTPAuthHandler(SMTPHandler): def __init__(self, mailhost, fromaddr, toaddrs, subject, user=None, password=None): SMTPHandler.__init__(self, mailhost, fromaddr, toaddrs, subject) self.user = user self.password= password def emit(self, record): import smtplib from email.Utils import formatdate smtp = smtplib.SMTP(self.mailhost, smtplib.SMTP_PORT) if self.user and self.password: smtp.login(self.user, self.password) msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, ','.join(self.toaddrs), self.getSubject(record), formatdate(), msg) smtp.sendmail(self.fromaddr, self.toaddrs, msg) smtp.quit() def smtp_logger(level, mailhost, fromaddr, toaddr, subject, user=None, password=None): logger = getLogger('AppName') logger.setLevel(level) hdlr = SMTPAuthHandler(mailhost, fromaddr, toaddr, subject, user, password) fmt = Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s', '%Y-%m-%d %H:%M:%S') hdlr.setFormatter(fmt) logger.addHandler(hdlr) hdlr.setLevel(level) return logger logger = smtp_logger(DEBUG, 'mailhost', 'fromaddr', 'toaddr', 'DEBUG: AppName', 'user', 'password') logger.debug('some message') HTH, Rob From steven.bethard at gmail.com Wed Jan 23 00:53:20 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 22 Jan 2008 22:53:20 -0700 Subject: subprocess and & (ampersand) Message-ID: I'm having trouble using the subprocess module on Windows when my command line includes special characters like "&" (ampersand):: >>> command = 'lynx.bat', '-dump', 'http://www.example.com/?x=1&y=2' >>> kwargs = dict(stdin=subprocess.PIPE, ... stdout=subprocess.PIPE, ... stderr=subprocess.PIPE) >>> proc = subprocess.Popen(command, **kwargs) >>> proc.stderr.read() "'y' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n" As you can see, Windows is interpreting that "&" as separating two commands, instead of being part of the single argument as I intend it to be above. Is there any workaround for this? How do I get "&" treated like a regular character using the subprocess module? Thanks, STeVe From deets at nospam.web.de Thu Jan 3 08:50:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 14:50:27 +0100 Subject: reassign to builtin possible !? References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> Message-ID: <5u47h3F1gbcngU1@mid.uni-berlin.de> Bernhard Merkle wrote: > On Jan 3, 2:07 pm, "Diez B. Roggisch" wrote: >> This hal always been possible. But it's not reassigning, it's shadowing - >> which is a totally different beast. Shadowing builtins is bad style, but >> lokal to your context. Which can get nasty of course, if you do the above >> on e.g. module level. >> >> But you can't alter the values for True/False globally with this. > > Are you sure ? what about the following example ? > Is this also shadowing ? > > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import __builtin__ >>>> __builtin__.True = False >>>> __builtin__.True > False >>>> True > False I'm not entirely sure what happens there, but that seems to only work in the interactive prompt. --------- test.py ------------ print True if __builtins__.True == 10: print "I'm reassigned globally" --------- test.py ------------- Then, in the interpreter do: droggisch at ganesha:/tmp$ 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. Welcome to rlcompleter2 0.96 for nice experiences hit multiple times >>> __builtins__.True = 10 >>> import test 10 Traceback (most recent call last): File "", line 1, in File "test.py", line 5, in if __builtins__.True == 10: AttributeError: 'dict' object has no attribute 'True' >>> Diez From castironpi at gmail.com Fri Jan 11 18:43:36 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 11 Jan 2008 15:43:36 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> Message-ID: <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> On Jan 11, 5:26 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > This function just wants X out of the list. It doesn't matter if this > > happens before, during, or after something else; so long as it happens. > > 2. Associate a lock with the list. Anything wanting to access the > list should acquire the lock, do its stuff, then release the lock. > This gets confusing after a while. To keep it generic, how about: listA.op( insert, x ) listA.op( remove, x ) From theCodeMaiden at gmail.com Thu Jan 3 12:50:08 2008 From: theCodeMaiden at gmail.com (Adeola Bannis) Date: Thu, 3 Jan 2008 09:50:08 -0800 (PST) Subject: PyOpenGL, wxPython weird behaviour Message-ID: <71ae5a6b-31e9-41e9-a39e-919138dc4a03@l6g2000prm.googlegroups.com> Hi everyone, I'm doing a project using wxPython and pyopengl, and I seem to have a problem rendering textures. This is code that worked before my hard drive had a meltdown, but not since I re-installed everything. I've determined the problem is in the OpenGL part of my program. I do some calculations to generate a 2D numpy array that holds the image data, and pylab.imshow() shows me the image as it is meant to be. I used the same algorithm in Octave and MATLAB, and all are giving me the right picture. However, using pyOpenGL and the numpyhandler functions (http://cours- info.iut-bm.univ-fcomte.fr/docs/python/OpenGL/ OpenGL.arrays.numpymodule.NumpyHandler-class.html) doesn't seem to work. I get a garbled screen pocked with black pixels. I am including my openGL code below. What am I doing wrong? And yes, I did make the dtype of my array 'float32'. -------code snippets------ import wx from wx.glcanvas import GLCanvas from OpenGL.GLU import * from OpenGL.GL import * from OpenGL.arrays.numpymodule import NumpyHandler PC = 1 RI = 0 class myGLCanvas(GLCanvas): def __init__(self, parent): GLCanvas.__init__(self, parent,-1) wx.EVT_PAINT(self, self.OnPaint) self.init = 0 self.mode = -1 # making a texture for the range image self.texture = glGenTextures(1) # making a spot for the point cloud points self.cloud = None return def OnPaint(self,event): dc = wx.PaintDC(self) self.SetCurrent() if not self.init: self.InitGL() self.init = 1 self.OnDraw() return def OnDraw(self): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if self.mode == RI: self.drawRange() elif self.mode == PC: self.drawCloud() def InitGL(self): glClearColor(0.0, 0.0, 0.0, 0.0); glClearDepth(1.0) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) glClear(GL_COLOR_BUFFER_BIT) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glPixelStorei(GL_PACK_ALIGNMENT, 1) #NTSC colour scales... glPixelTransferf(GL_RED_SCALE, 0.299); glPixelTransferf(GL_GREEN_SCALE, 0.587); glPixelTransferf(GL_BLUE_SCALE, 0.114); glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0,1.0,0,1.0,-1.0,1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() return def rangeImage(self, image): glBindTexture(GL_TEXTURE_2D, self.texture) glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # flatten it into a list so the OpenGL calls work n = NumpyHandler() fI = image.flatten() flatImage = n.dataPointer(n.contiguous(fI)) print n.contiguous(fI) gluBuild2DMipmaps(GL_TEXTURE_2D, 1, image.shape[0]+1, image.shape[1]+1, GL_LUMINANCE, GL_FLOAT, flatImage) self.mode = RI self.OnDraw() def drawRange(self): ''' Controls the actual drawing of the range image''' glMatrixMode(GL_MODELVIEW) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColor3f(1.0,1.0,1.0) glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.texture) glBegin(GL_TRIANGLE_FAN) glTexCoord2d(1,1); glVertex3f(0.0, 0.0, 0.0) glTexCoord2d(1,0); glVertex3f(0.0, 1.0, 0.0) glTexCoord2d(0,0); glVertex3f(1.0, 1.0, 0.0) glTexCoord2d(0,1); glVertex3f(1.0, 0.0, 0.0) glEnd() self.SwapBuffers() --------end snippet----------- From scrdhrt at gmail.com Thu Jan 17 08:38:38 2008 From: scrdhrt at gmail.com (Sacred Heart) Date: Thu, 17 Jan 2008 05:38:38 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: On Jan 17, 1:35 pm, cokofree... at gmail.com wrote: > for i in zip(array1, array2): > print i > > Although I take it you meant four d, the issue with this method is > that once you hit the end of one array the rest of the other one is > ignored. Yes, small typo there. Okey, so if my array1 is has 4 elements, and array2 has 6, it won't loop trough the last 2 in array2? How do I make it do that? R, SH From python.list at tim.thechases.com Wed Jan 9 18:00:53 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 09 Jan 2008 17:00:53 -0600 Subject: for loop without variable In-Reply-To: References: Message-ID: <47855225.90605@tim.thechases.com> >> Hi. I'd like to be able to write a loop such as: >> for i in range(10): >> pass >> but without the i variable. The reason for this is I'm using pylint >> and it complains about the unused variable i. > > if a computer tells you to do something stupid, it's often better to > find a way to tell the computer to shut up than to actually do some- > thing stupid. > > (pylint's online documentation is remarkably unreadable, so I cannot > help you with the details, but surely there's a way to disable that > test, either globally, or for a specific region of code?). That documentation on PyLint[1] is atrocious! From my reading of it, at the beginning of your file, you put a comment something like # pylint: disable-msg=W0612 which should disable that particular message. Totally untested. I don't know if PyLint is smart enough, but if you don't use "i", you might use the common "throwaway" variable of "_": for _ in xrange(10): do_something() in which case it _might_ recognize that it's a throwaway variable and not warn you about it. At least that would be nice of it. But given the abusive nature of the documenation, I'm not sure that's the case ;) -tkc [1]http://www.logilab.org/card/pylintfeatures From guptaabhishek1983 at gmail.com Fri Jan 11 03:04:00 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Fri, 11 Jan 2008 00:04:00 -0800 (PST) Subject: Why Python.exe is breaking with memory dump?? Message-ID: Hi group i have created a simple .pyd using which i m able call C function from python code. There are around 6 such functions. 4 of them work great. But when i try to run other two python's exe breaks giving memory dump. Any pros or cons on what led to such a situation.. Is it a problem in my c code?? Thank you. From lutz.horn at fastmail.fm Wed Jan 16 09:39:26 2008 From: lutz.horn at fastmail.fm (Lutz Horn) Date: Wed, 16 Jan 2008 15:39:26 +0100 Subject: Python help for a C++ programmer In-Reply-To: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> References: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> Message-ID: <1200494366.9118.1231561231@webmail.messagingengine.com> Hi, On Wed, 16 Jan 2008 06:23:10 -0800 (PST), "mlimber" said: > I'm writing a text processing program to process some survey results. > I'm familiar with C++ and could write it in that, but I thought I'd > try out Python. I've got a handle on the file I/O and regular > expression processing, but I'm wondering about building my array of > classes (I'd probably use a struct in C++ since there are no methods, > just data). You could try something like this. #!/usr/bin/env python class Response: def __init__(self, name, age, iData, sData): self.name = name self.age = age self.iData = iData self.sData = sData def sourceOfResponses(): return [["you", 42, [1, 2, 3], ["foo", "bar", "baz"]], ["me", 23, [1, 2, 3], ["ham", "spam", "eggs"]]] if __name__ == "__main__": responses = [] for input in sourceOfResponses: response = Response(input.name, input.age, input.iData, input.sData) reponses.append(response) Lutz -- GnuPG Key: 1024D/6EBDA359 1999-09-20 Key fingerprint = 438D 31FC 9300 CED0 1CDE A19D CD0F 9CA2 6EBD A359 http://dev-random.dnsalias.net/0x6EBDA35.asc http://pgp.cs.uu.nl/stats/6EBDA359.html From tim.peters at gmail.com Sun Jan 20 20:44:06 2008 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 20 Jan 2008 17:44:06 -0800 (PST) Subject: TopSort in Python? References: <0000161d@bossar.com.pl> Message-ID: <81cb9a15-4f34-4cba-9542-adaa82ca3ec6@c4g2000hsg.googlegroups.com> [startec... at gmail.com] > Thanks for the topsort code. It would be useful in a project I'm > working on. Can I use the code for free under public domain? Thanks! If I ran the world, everything I posted to a public place would be public domain. Alas, the last lawyer who typed at me about this insisted that an individual in the USA cannot meaningfully disclaim copyright, so perhaps you're required to pay me millions of dollars instead ;-) To keep him happy and you solvent, I hereby license the code under the MIT license: http://www.opensource.org/licenses/mit-license.php Copyright (c) 1999-2008 Tim Peters Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. From workitharder at gmail.com Sat Jan 5 17:09:09 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 5 Jan 2008 14:09:09 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> <13ntbv51tqcm7c@corp.supernews.com> Message-ID: <83b78deb-b7c4-4fa3-b9ad-1a40be4f9231@n22g2000prh.googlegroups.com> On Jan 4, 2:15 pm, Steven D'Aprano wrote: > On Fri, 04 Jan 2008 09:29:50 -0800, bukzor wrote: > > Why cant you implement < for complex numbers? Maybe I'm being naive, but > > isn't this the normal definition? > > a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) > > No, it is not. Ordered comparisons are not defined for complex numbers. > Which is bigger, 4+2j or 2+4j? > > > How do you implement a set without sorting? > > With a hash table. > > Or if you are willing to limit yourself to sets of small integers, you > can implement it using bit flipping. E.g. 5 is an element of the set if > bit 5 is on. > > > Are you expecting better than O(log n)? > > Sure. > > -- > Steven Good Answers! From peanut.sam at googlemail.com Sat Jan 5 18:54:55 2008 From: peanut.sam at googlemail.com (Sam Garson) Date: Sat, 5 Jan 2008 23:54:55 +0000 Subject: Taskbar/System Tray Message-ID: <4e1ac4910801051554n5927c45ejb62d77b48eedd645@mail.gmail.com> hello group, Using tkinter, is there any way to have the program not showing on the taskbar, and even better showin in the system tray? I realise tkinter does not have that much OS specific stuff but maybe there is a way? Thanks, Sam -- I intend to live forever - so far, so good. SaM -------------- next part -------------- An HTML attachment was scrubbed... URL: From jr9445 at ATT.COM Thu Jan 17 11:44:51 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 17 Jan 2008 10:44:51 -0600 Subject: Creating unique combinations from lists In-Reply-To: <478F7471.9080909@tim.thechases.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> <478E6BA7.5030509@tim.thechases.com> <478F7471.9080909@tim.thechases.com> Message-ID: > -----Original Message----- > From: Tim Chase [mailto:python.list at tim.thechases.com] > Sent: Thursday, January 17, 2008 10:30 AM > To: Reedick, Andrew > Cc: breal; python-list at python.org; martin at v.loewis.de > Subject: Re: Creating unique combinations from lists > > Yick...a nice demo of the power of eval, but definitely filed > under the "Hack" heading :) You hurt my feeling. *sniffle* Given how late python compiles/evaluates code blocks, I'm thinking that eval() is less hack and more paradigm ..err.. pythonic. ;-) > > I think Martin's solution/recommendation[1] is better > (readability-wise, and "less apt to shoot yourself in the foot > with some bogus generated code"-wise) if you don't mind building > the whole result set in memory which your eval() solution does as > well. I'm curious to see the timing results from adding that > recipe to your test-suite. Cookbook is relatively decent. 5 deep, 100 iterations: list comprehension: 11.02 nested for loop : 13.16 +19% cookbook : 18.85 +71% recursion : 69.00 +526% eval : 13.30 +20% > > The advantage to the recursive-generator solution is that it > should really only keep your initial input and the current result > in memory as the generated item, so you can reasonably iterate > over millions of rows without having gigs of RAM. I don't > believe the recursion will go deeper than the number of lists > you're iterating over, so the stack shouldn't explode. Excellent point about memory usage. However, since we're dealing with exponential algorithms, will you run out of time or memory first? Here's the test code if anyone wants to play with it. It will let you specify the levels of nested loops and display the generated code. Usage: foo.py num_nested_loops num_iterations import sys from timeit import Timer def CreateComprehension(lists): out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in range(len(lists))]) return '[ ' + out + comp + ' ]' num_loops = int(sys.argv[1]) iterations = int(sys.argv[2]) results = [] lists = '''lists = [] for i in range(%d): lists.append(range(i, i+10)) ''' % (num_loops) print "################################################" print lists print print "################################################" code = 'r = ' + CreateComprehension(range(num_loops)) t = Timer(code, lists) results.append("list comprehension: %4.2f" % t.timeit(iterations)) print results[-1:][0] print code print print "################################################" code = 'r = []\n' for i in range(num_loops): code += " " * i code += "for v%d in lists[%d]:\n" % (i, i) code += ' ' * num_loops code += 'r.append([' code += ','.join( ['v%d' % i for i in range(num_loops)]) code += '])' t = Timer(code, lists) results.append("nested for loop : %4.2f" % t.timeit(iterations)) print results[-1:][0] print code print print "################################################" code = '''r=[[]] for x in lists: t = [] for y in x: for i in r: t.append(i+[y]) r = t ''' t = Timer(code, lists) results.append("cookbook : %4.2f" % t.timeit(iterations)) print results[-1:][0] print code print print "################################################" code = ''' r = [] def iterall(*iterables): if iterables: for head in iterables[0]: for remainder in iterall(*iterables[1:]): yield [head] + remainder else: yield [] for thing in iterall(%s): r.append(thing) ''' % ( ','.join([ 'lists[%d]' % i for i in range(num_loops) ]) ) t = Timer(code, lists) results.append("recursion : %4.2f" % t.timeit(iterations)) print results[-1:][0] print code print print "################################################" code = ''' def gen(lists): out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in range(len(lists))]) return eval('[ ' + out + comp + ' ]') gen(lists) ''' t = Timer(code, lists) results.append("eval : %4.2f" % t.timeit(iterations)) print results[-1:][0] print code print print '\n'.join(results) ***** 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. GA622 From martin at v.loewis.de Sun Jan 13 15:43:28 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 13 Jan 2008 21:43:28 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801132048.08966.donn.ingle@gmail.com> References: <200801131928.54459.donn.ingle@gmail.com> <478A4F8A.5010108@v.loewis.de> <200801132048.08966.donn.ingle@gmail.com> Message-ID: <478A77F0.4000502@v.loewis.de> > Now, I want to open that file from Python, and I create a path with > os.path.join() and an os.listdir() which results in this byte string: > paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] > > I *think* that the situation is impossible because the system cannot resolve > the correct filename (due the locale being ANSI and the filename being other) > but I am not 100% sure. Not at all. The string you pass is a *byte* string, not a character string. You may think that the first letter of it is an aitch, but that's just your interpretation - it really is the byte 104. The operating system does not interpret the file names as characters at all, with the exception of treating byte 47 as the path separator (typically interpreted by people as "slash"). Your locale becomes only relevant when displaying file names, and having to chose what glyphs to use. > So, I have been trying combinations of open: > 1. f = codecs.open( paf, "r", "utf8" ) > I had hopes for this one. > 2. f = codecs.open( paf, "r", locale.getpreferredencoding()) > 3. f = open( paf, "r") Now you are mixing two important concepts - the *contents* of the file with the *name* of the file. These are entirely independent, and the file name may be in one encoding and the file contents in another, or the file contents may not represent character data at all. All these three APIs try to get to the *contents* of the file, by opening it. The name is already a byte string (as a character string, it would have started with u'...'), so there is no need to encode it. What the content of a .pog file is, I don't know, so I can't tell you what encoding it is encoded it. > But none will open it - all get a UnicodeDecodeError. This aligns with my > suspicions, but I wanted to bounce it off you to be sure. Option three should have worked if paf was a string, but above, I see it as a *list* of strings. So try f = open(paf[0], "r")# where paf[0] should be '/home/donn/.fontypython/M\xc3\x96gul.pog', as paf is ['/home/donn/.fontypython/M\xc3\x96gul.pog'] Still, I question that you *really* got a UnicodeDecodeError for three: I get TypeError: coercing to Unicode: need string or buffer, list found Can you please type paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] f = open(paf, "r") at the interactive prompt, and report the *complete* shell output? > Also, this codecs.open(filename, "r", ) function: > 1. Does it imply that the filename will be opened (with the name as it's > type : i.e. bytestring or unicode ) and written *into* as > 2. Imply that filename will be encoded via and written into as > > It's fuzzy, how is the filename handled? See above. The encoding in codecs.open has no effect at all on the file name; it only talks about the file content. Regards, Martin From fetchinson at googlemail.com Tue Jan 8 20:19:02 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 8 Jan 2008 17:19:02 -0800 Subject: user friendly datetime features Message-ID: Many times a more user friendly date format is convenient than the pure date and time. For example for a date that is yesterday I would like to see "yesterday" instead of the date itself. And for a date that was 2 days ago I would like to see "2 days ago" but for something that was 4 days ago I would like to see the actual date. This is often seen in web applications, I'm sure you all know what I'm talking about. I'm guessing this feature is needed so often in so many projects that it has been implemented already by several people. Does anyone know of such a stand alone module? From max at alcyone.com Thu Jan 10 17:10:08 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 10 Jan 2008 14:10:08 -0800 Subject: Newbie question on Classes In-Reply-To: References: Message-ID: Adrian Wood wrote: > I can call man.state() and then woman.state() or Person.state(man) and > Person.state(woman) to print the status of each. This takes time and > space however, and becomes unmanageable if we start talking about a > large number of objects, and unworkable if there is an unknown number. > What I'm after is a way to call the status of every instance of Man, > without knowing their exact names or number. > > I've gone through the relevant parts of the online docs, tried to find > information elsewhere online, and looked for code samples, but the > ionformation either isn't there, or just isn't clicking with me. I've > tried tracking the names of each object in a list, and even creating > each object within a list, but don't seem to be able to find the right > syntax to make it all work. You'll have to retain a list of all extant Person objects, and then a function which calls the relevant method on every element of that list and returns the result however you wish. You can easily encapsulate that list into a class attribute of Person, and the function into a static method of the class for elegance, but it's not required to get the proper functionality. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Life is a gamble so I should / Live life more carefully -- TLC From hannah.drayson at plymouth.ac.uk Tue Jan 29 13:35:30 2008 From: hannah.drayson at plymouth.ac.uk (Hannah Drayson) Date: Tue, 29 Jan 2008 18:35:30 +0000 Subject: noob stuck on reading double Message-ID: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk> Hi all, I have a .bin file which python just won't play ball with- Does anyone know what I'm doing wrong- is it simply incompatible? I've read it fine using a C program - its 113 doubleword fields- apparently its possible to handle these in python in a very similar way to C. I can provide the c code and have attached .bin if anyone is interested... Thank you all. It imports as a string of rubbish... i.e. >>> text = f.read() >>> print text ?F?C??y??>? @??I at g[??B8~??????Q???Q???Q???Q???Q???Q???Q???Q???Q???Q????=N@???????????????????/???8@@@@?Q at E??/??T at N#????S@?????Q???Q???Q???Q???Q???????????R[???Q??????? It won't unpack using struct... >>> unpack('d', text) Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/struct.py", line 87, in unpack return o.unpack(s) struct.error: unpack requires a string argument of length 8 Using str and repr gets me something that looks like unicode... >>> str(text) '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \xa0F\xa2C\xc0\xd2y\xf9\xf8>\xd2\n@\x00\x00\x00\xc0\xd3\x9cI@\x00\x00\x00\x 00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00g[\xa0?B8~\xd4\x00\x00\x00 \x00\x00\x00\xf8\xff\x00\x00\x00\x00\x00\x00\xf8\xff\x00\x00\x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x00\x00\x00\ etc..... Tried formatting it... >>> str(text) % ('Python', 'g') Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting Tried converting it to unicode... >>> unicode(text, 'utf8', 'strict') Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0xa0 in position 19: unexpected code byte I even tried chopping it up into 8 character pieces and then converting it into a float, but I think I'm just being stupid by this point... >>> the_list=[] >>> index = 0 >>> second_dig = 7 >>> while index < (len(bum))/8: ... new_bit = bum[index:second_dig] ... the_list.append(new_bit) ... index += 8 ... second_dig += 8 ... >>> print the_list [u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\ufffdF\ufffdC', u'y\ufffd@\x00\x00\x00\ufffd', u'I@\x00\x00\x00\x00\x00', u'\x00\x00\x00\x01\x00\x00\x00', u'\x00\x00g[\ufffd?B', u'~\ufffd\x00\x00\x00\x00\x00', u'\x00\x00\x00\ufffd\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00'] >>> the_list[1] u'\x00\x00\x00\x00\x00\x00\x00' >>> float(the_list[1]) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'decimal' codec can't encode character u'\x00' in position 0: invalid decimal Unicode string Any ideas? -------------- next part -------------- A non-text attachment was scrubbed... Name: data.bin Type: application/macbinary Size: 904 bytes Desc: data.bin URL: From stef.mientki at gmail.com Wed Jan 9 16:22:52 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 09 Jan 2008 22:22:52 +0100 Subject: getting absolute path ? Message-ID: <47853B2C.9020403@gmail.com> hello, I'm trying to convert the links in html pages to absolute links, these pages can either be webpages or files on local harddisk (winXP). Now I've struggling for a while, and this code works a lilttle: i = line.find ( 'href=' ) if i < 0 : i = line.find ( ' src=' ) if i >= 0 : ii = line.find ( '"', i+6 ) file = line [ i+6 : ii ] #print urlparse.urljoin ( p, file ) if file.find ( 'http:' ) < 0 : abspath = os.path.normpath ( os.path.join ( p, file ) ) line = line.replace ( file, abspath ) print line but it only covers files on local disk and just 1 link per line, so I guess it's a lot of trouble to catch all cases. Isn't there a convenient function for (OS independent preferable) ? Googled for it, but can't find it. thanks, Stef Mientki From bignose+hates-spam at benfinney.id.au Mon Jan 14 17:39:03 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 09:39:03 +1100 Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> Message-ID: <874pdgf2wo.fsf@benfinney.id.au> George Sakkis writes: > By the way, why do we need both NotImplementedError and the > NotImplemented singleton object ? Couldn't we have just one of them ? One of them is an exception class, the other is not. They have rather different semantics. I think of NotImplemented as equivalent to None; it's useful as a sentinel value to set an attribute to in (e.g.) an abstract class. For a function that is (or has a flow branch which is) not (yet?) implemented, I don't want to return at all. Instead, I want to raise an instance of NotImplementedError. I think it's desirable to keep them both distinct as is. -- \ "If you get invited to your first orgy, don't just show up | `\ nude. That's a common mistake. You have to let nudity | _o__) 'happen.'" -- Jack Handey | Ben Finney From kar1107 at gmail.com Sat Jan 12 19:50:23 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Sat, 12 Jan 2008 16:50:23 -0800 (PST) Subject: executing newgrp from python in current shell possible? References: <755e7fd2-5e4a-4a4b-b848-a5e4ca756087@l6g2000prm.googlegroups.com> Message-ID: <73c6fb57-caa7-4676-8e5e-31c78f882531@t1g2000pra.googlegroups.com> On Jan 12, 6:19 am, Svenn Are Bjerkem wrote: > On Jan 9, 9:18 pm, Zentrader wrote: > > > On Jan 9, 5:56 am, Svenn Are Bjerkem > > wrote: > > > >I have been looking for a way to execute this command > > > as a part of a script, but it seems that the changes are only valid in > > > the context of the script and when the script exits, the current shell > > > still have the original "users" group setting. > > > I don't think you would want it any other way. Would you want a user > > to be able to change the group and have it remain permanently? Who's > > going to remember whether they were last in "A" or "B", and it opens > > up oportunities for the practical joker when you go to the restroom > > and leave the terminal on. Put the "change the group" code into a > > separate function in a separate file (with only you as the owner) and > > call it whenever you want to change groups. > > I am trying to create a script that make it easy for users in a design > team to create files that belong to the same group, but retain the > users uid. In order to make it visible that the user is creating files > with a different gid, the script will change the prompt to indicate > so. In a tcl solution I have now, the users home is changed to the > design area as some tools are reading and writing setup files into > $HOME. I have not found a way to change the gid in tcl so I turned to > python in hope that this scripting language could do so. > > The tcl solution spawns a new tcsh after setting several environment > variables and works quite well except for not being able to change > gid. And it is also a wish from my side to port this script to python. > > Is your suggestion to put "newgrp design" into a new file and then > exec this file in my python script? What happens to the group id of > the shell that called the python script in this case? I would try to > avoid spawning a new tcsh as this make execution of tools on a remote > computer difficult as the handover of command line arguments does not > seem to be handed over to the newly spawned shell. I may be > understanding something wrongly here. When you fork a process in unix/linux, the child inherits all of parents settings; *but* any future changes that is made in child process will not get reflected in the parent. So there is no way you can fire a process and some how get its setting back to the invoking shell (which could be anything btw, say bash/tcsh/ csh). Thus what you really want is start a wrapper python script, say setup_design.py In setup_design.py, call necessary os routines like setegid(egid); this will update the process settings of the process running setup_design.py. At the end of setup_design.py, do an exec call[1] to fire the user's shell (note that even if you use popen or other ways of forking a new process, things will work just fine) Whatever changes you made to the process environment will get propagated to the new shell. User must explicitly finish the new shell (say typing 'exit' on shell prompt) Karthik [1]. e.g. import os os.execvp(cmd_run[0], cmd_run) # cmd_run is probably ['/bin/bash'] > > -- > Svenn From mwm at mired.org Thu Jan 10 13:43:35 2008 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 13:43:35 -0500 Subject: What is "lambda x=x : ... " ? In-Reply-To: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> Message-ID: <20080110134335.37cf5377@mbook.mired.org> On Thu, 10 Jan 2008 10:25:27 -0800 (PST) "zslevi at gmail.com" wrote: > I'm reading this page: http://www.ps.uni-sb.de/~duchier/python/continuations.html > and I've found a strange usage of lambda: > > #################### > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ################### > > What does "y=y" and "c=c" mean in the lambda function? Older versions of python didn't make variables in an outer scope visible in the inner scope. This was the standard idiom to work around that. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From tjreedy at udel.edu Wed Jan 30 21:26:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jan 2008 21:26:20 -0500 Subject: booleans, hash() and objects having the same value References: <9cdb261f-b81b-4eca-955a-a9b516eba9d2@s13g2000prd.googlegroups.com> Message-ID: "Ryszard Szopa" wrote in message news:9cdb261f-b81b-4eca-955a-a9b516eba9d2 at s13g2000prd.googlegroups.com... | | (Also, it is not completely clear what it means for two Python objects | to "have the same value". Objects of different types compare unequal unless provision is made otherwise. See http://docs.python.org/ref/comparisons.html for more From tjreedy at udel.edu Sat Jan 26 22:20:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jan 2008 22:20:20 -0500 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu><120eok46fkf0j2b@corp.supernews.com> <15114746.post@talk.nabble.com> Message-ID: To answer the OP's question: GOF design patterns that solve problems due to static typing (and there are some) are not needed with Python. Others do apply and can be useful. There have been various mentions in c.l.p over the years. From gherron at islandtraining.com Sun Jan 6 21:33:45 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 06 Jan 2008 18:33:45 -0800 Subject: ctypes In-Reply-To: <5bc0722e-efe7-4067-9bf4-afee3f1c9a03@f3g2000hsg.googlegroups.com> References: <5bc0722e-efe7-4067-9bf4-afee3f1c9a03@f3g2000hsg.googlegroups.com> Message-ID: <47818F89.7090001@islandtraining.com> hkimball at eti-web.com wrote: > I am having trouble with ctypes: i can load the third party dll, and > gain access to the function but the function calls do not actually > perform their intended purpose. I have tried this in both interactive > mode and from a saved script. I know that is a somewhat vague > description but any help would be greatly appreciated. > > thanks > harold kimball > It is too vague to give any help other than: Read the documentation, and search for and follow examples. That worked for me in my recent (and first) attempt a accessing a dll via ctypes. If you can be more specific about your problem and how it fails, then perhaps you'll get more specific answers. Also, please read this: http://www.catb.org/~esr/faqs/smart-questions.html Gary Herron From grante at visi.com Mon Jan 21 11:17:58 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 21 Jan 2008 16:17:58 -0000 Subject: When is min(a, b) != min(b, a)? References: Message-ID: <13p9hdmh7c08abe@corp.supernews.com> On 2008-01-21, Jason wrote: > Infinite values are also problematic. In almost all cases, it is far > better to avoid infinite and NaN values. In many applications (e.g. process control) propogating NaN values are way too useful to avoid. Avoiding NaN would make a lot of code far more complicated than would using them. -- Grant Edwards grante Yow! How's the wife? at Is she at home enjoying visi.com capitalism? From george.sakkis at gmail.com Thu Jan 17 00:42:00 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 16 Jan 2008 21:42:00 -0800 (PST) Subject: next line (data parsing) References: <13otnvakq8kc6a3@corp.supernews.com> Message-ID: On Jan 17, 12:01 am, Scott David Daniels wrote: > robleac... at gmail.com wrote: > > Hi there, > > I'm struggling to find a sensible way to process a large chuck of > > data--line by line, but also having the ability to move to subsequent > > 'next' lines within a for loop. I was hoping someone would be willing > > to share some insights to help point me in the right direction. This > > is not a file, so any file modules or methods available for files > > parsing wouldn't apply. > > > I can iterate over each line by setting a for loop on the data object; > > no problem. But basically my intension is to locate the line "Schedule > > HOST" and progressively move on to the 'next' line, parsing out the > > pieces I care about, until I then hit "Total", then I resume to the > > start of the for loop which locates the next "Schedule HOST". > > if you can do: > > for line in whatever: > ... > > then you can do: > > source = iter(whatever) > for intro in source: > if intro.startswith('Schedule '): > for line in source: > if line.startswith('Total'): > break > process(intro, line) > > --Scott David Daniels > Scott.Dani... at Acm.Org Or if you use this pattern often, you may extract it to a general grouping function such as http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877: import re for line in iterblocks(source, start = lambda line: line.startswith('Schedule HOST'), end = lambda line: re.search(r'^ \s*Total',line), skip_delim=False): process(line) George From gbacon at hiwaay.net Mon Jan 28 13:53:42 2008 From: gbacon at hiwaay.net (Greg Bacon) Date: Mon, 28 Jan 2008 18:53:42 -0000 Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> Message-ID: <13ps95mg8am3l37@corp.supernews.com> The code below at least passes your tests. Hope it helps, Greg #! /usr/bin/perl use warnings; use strict; use constant { MATCH => 1, NO_MATCH => 0, }; my @tests = ( [ "winter tire", => MATCH ], [ "tire", => MATCH ], [ "retire", => MATCH ], [ "tired", => MATCH ], [ "snowbird tire", => MATCH ], [ "tired on a snow day", => MATCH ], [ "snow tire and regular tire", => MATCH ], [ " tire" => MATCH ], [ "snow tire" => NO_MATCH ], [ "snow tire" => NO_MATCH ], [ "some snowtires" => NO_MATCH ], ); my $not_snow_tire = qr/ ^ \s* tire | ([^w\s]|[^o]w|[^n]ow|[^s]now)\s*tire /xi; my $fail; for (@tests) { my($str,$want) = @$_; my $got = $str =~ /$not_snow_tire/; my $pass = !!$want == !!$got; print "$str: ", ($pass ? "PASS" : "FAIL"), "\n"; ++$fail unless $pass; } print "\n", (!$fail ? "PASS" : "FAIL"), "\n"; __END__ -- ... all these cries of having 'abolished slavery,' of having 'preserved the union,' of establishing a 'government by consent,' and of 'maintaining the national honor' are all gross, shameless, transparent cheats -- so trans- parent that they ought to deceive no one. -- Lysander Spooner, "No Treason" From kw at codebykevin.com Thu Jan 10 17:06:27 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 10 Jan 2008 17:06:27 -0500 Subject: Wrap Tk widget using a class Message-ID: I'm trying to wrap a subset of a Tcl/Tk widget set called tclmacbag (see http://tclmacbag.autons.net/) for use in my Tkinter application, using a "macnotebook" class. I'm having some difficulty getting things configured correctly. Here is my class code: from Tkinter import * class Macnotebook: def __init__(self, master): self.master = master self.master.call('package', 'require', 'tclmacbag') def notebook(self): self.master.call('::tclmacbag::pnb', self) def add(self, child): self.master.call('::tclmacbag::pnb', 'add', child) Here is an example of how I'm calling this in my code: from Macnotebook import Macnotebook self.prefbook = Macnotebook.notebook(self.prefframe) self.prefbook.pack(fill=BOTH, expand=YES, side=TOP) This returns the following error in my console: Traceback (most recent call last): self.prefbook = Macnotebook.notebook(self.prefframe) TypeError: unbound method notebook() must be called with Macnotebook instance as first argument (got Frame instance instead) Can anyone suggest how I might better structure the class so that this works? I'm a bit of a newbie with OO, so any pointers are appreciated. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From gnewsg at gmail.com Fri Jan 4 06:25:28 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 4 Jan 2008 03:25:28 -0800 (PST) Subject: choosing random dynamic port number References: <32e43bb70801031409o5d1dcd2at5a159339cd43ae52@mail.gmail.com> Message-ID: <3e6cca84-f8cf-4947-931c-18d6af748f13@l6g2000prm.googlegroups.com> On 3 Gen, 23:21, Fredrik Lundh wrote: > Emin.shopper Martinian.shopper wrote: > > Is there a good way to choose/assign random dynamic port numbers in python? > > > I had in mind something like the following, but if multiple programs are > > generating random port numbers, is there a way to check if a given port > > number is already taken? > > > ? ? def GenerateDynamicPortNumber(): > > ? ? ? ? "Generate a random dynamic port number and return it." > > ? ? ? ? # port numbers between 49152 to 65535 are dynamic port numbers > > ? ? ? ? return 49152 + random.randrange(15000) > > ? ? def GenerateDynamicPortNumber(): > ? ? ? ? return 0 > > (to get the actual number, use getsockname() on the socket after you've > called "bind" on it) > > By using 0 as port number value you let kernel choose a free unprivileged random port: >>> import socket >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s.bind(('', 0)) >>> s.getsockname() ('0.0.0.0', 3070) From ajaksu at gmail.com Sun Jan 27 18:28:37 2008 From: ajaksu at gmail.com (ajaksu) Date: Sun, 27 Jan 2008 15:28:37 -0800 (PST) Subject: optional static typing for Python References: <23f7c55a-949f-41a4-b558-81861ede258f@f10g2000hsf.googlegroups.com> Message-ID: On Jan 27, 9:13 pm, "Russ P." wrote: > On Jan 27, 3:08 pm, Jarek Zgoda wrote: > > > Russ P. pisze: > > > >>> I noticed that Guido has expressed further interest in static typing > > >>> three or four years ago on his blog. Does anyone know the current > > >>> status of this project? Thanks. > > >> I thought it was april fools joke? > > > > On January 21, 2000? Which calendar do you use? > > > Static typing in Python is usual theme of april fools jokes. > > I hope Guido doesn't find out about that! He does know, follow http://mail.python.org/pipermail/python-dev/2007-April/072419.html and get a laugh too! :) On a more serious note, I suggest you look up ShedSkin, Pyrex and Cython, where the static typing is used for better performance. And with Psyco, you get dynamic typing with JIT specialization. In core CPython, little is being done AFAIK to support static typing per-se, but annotations can (and probably will) be used for that end. However, I don't think it'll interfere in how CPython executes the program. Daniel From mauriceling at gmail.com Tue Jan 8 06:09:26 2008 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Tue, 8 Jan 2008 03:09:26 -0800 (PST) Subject: Paid subscription Python magazines References: <13o6jthqrl90o2d@corp.supernews.com> Message-ID: On Jan 8, 6:17 pm, Jon Harrop wrote: > Are there any Python magazines that you can pay to subscribe to? (either > paper or on-line). The Python Papers (www.pythonpapers.org) is a free e-journal, including industry and academic articles. maurice From bruno.desthuilliers at gmail.com Sat Jan 12 11:42:19 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jan 2008 08:42:19 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> <478732db$0$19250$426a74cc@news.free.fr> <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> <4787762b$0$18777$426a74cc@news.free.fr> Message-ID: <2b12e762-a5ca-4e86-b95a-ef6823ed8603@j78g2000hsd.googlegroups.com> On 11 jan, 16:10, George Sakkis wrote: > On Jan 11, 8:59 am, Bruno Desthuilliers > But I *still* fail to see how it could be "misleading", and > > *you* still fail to explain in which way it could be misleading. > > > If your point is that saying that CPython uses a byte-code/VM scheme > > "just like Java" necessarily implies JIT compilation just because some > > JVM support this feature, then it would be time you pay more attention > > to what is effectively written. > > What three different people in this thread have been trying to tell > you but you seem to miss is that claiming CPython's VM "is just like > Java" George, *please*, re-read what I wrote. I *never* claimed that CPython's VM is just like a JVM, I just stated that both CPython and Java use a byte-code/VM execution model. Can't you understand that ? From ssharkey at linuxunlimited.com Thu Jan 10 13:46:47 2008 From: ssharkey at linuxunlimited.com (Scott Sharkey) Date: Thu, 10 Jan 2008 13:46:47 -0500 Subject: Persistent HTTP Connections with Python? Message-ID: <47866817.7050207@linuxunlimited.com> Hello All, I am trying to write a python script to talk to an xml-based stock feed service. They are telling me that I must connect and login, and then "issue refresh requests" to fetch the data. This sounds a lot (to me) like HTTP 1.1 persistent connections. Can I do that with the urllib functions, or do I need to use the httplib functions for this kind of work. Pointers and/or sample code would be much appreciated. Thanks! -scott From kyosohma at gmail.com Mon Jan 7 11:20:19 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 7 Jan 2008 08:20:19 -0800 (PST) Subject: Killing worker threads References: Message-ID: On Jan 6, 7:48 am, Fredrik Lundh wrote: > tarun wrote: > > Can anyone help me with a simple code through which the main thread can > > kill the worker thread it started. > > it cannot. threads cannot be killed from the "outside". > > The only way to "kill" a thread is to have the spawned thread have some kind of passed in argument which will trigger it to shut down. You could have the thread read a file or file-like object periodically (like a timer) and if it meets some condition, have the thread quit. It's kind of like a subscription process. The thread subscribes to the main program and can accept signals. I suggest that the OP read the docs on threads: http://docs.python.org/lib/module-threading.html Of special interest to this user: http://docs.python.org/lib/condition-objects.html I have messed with KillProcName, a PyWin32 script with limited success. There's also the following snippet which is Windows only and works for some processes and not others (i.e. unreliable): subprocess.Popen('taskkill /s %s /im %s' % (computer_id, proc)) Hopefully I didn't muddy the waters or write something too off the mark. Mike From ram.rachum at gmail.com Wed Jan 23 10:37:35 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Wed, 23 Jan 2008 07:37:35 -0800 (PST) Subject: A GUI framework for running simulations References: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com> <657f0$47975960$83aef404$1819@news1.tudelft.nl> Message-ID: <76254c7d-7e69-4270-a10d-bf88acdae10d@f47g2000hsd.googlegroups.com> On Jan 23, 5:12?pm, Stef Mientki wrote: > ram.rac... at gmail.com wrote: > > Hello! I am currently working on writing a simulation engine for > > special relativity physics. I'm writing it in Python, of course. I'm > > doing fine with the engine, but I want a GUI framework in which I > > could use it conveniently, and test different setups on it. I'm not so > > strong with GUI programming. I looked at Tkinter, I looked at > > WxPython, I looked at PythonCard. It all looks pretty daunting. > > > My question is, does there exist a GUI package that is intended > > specifically for simulations? I saw a program called Golly, which is a > > simulation for Conway's Game of Life. Its GUI had most of the features > > I needed. For example, you can load a setup, there are "play" and > > "stop" buttons, you can change a setup and save it, etc. > > > So does anyone know of a general GUI framework for running > > simulations? > > although quit premature, > PyLab_Works might be of interest, > see some demos here (watch the demo at the bottom first):http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_animations_sc... > > (you can contact me offline if PyLab_Works looks interesting to you). > > cheers, > Stef Mientki Thank you, Stef and Guilherme. I'll be checking those things out. If anyone else who has an idea for something that can help me, I'll be happy to hear it! Ram. From sjmachin at lexicon.net Mon Jan 28 01:31:17 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 27 Jan 2008 22:31:17 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> <72a03212-7cf3-486d-ac70-c97a002d90c7@n20g2000hsh.googlegroups.com> Message-ID: <70b77205-e870-43d2-89d0-7f0d37bd056d@s8g2000prg.googlegroups.com> On Jan 28, 2:53 pm, glacier wrote: > > Thanks,John. > It's no doubt that you proved SAX didn't support GBK encoding. > But can you give some suggestion on how to make SAX parse some GBK > string? Yes, the same suggestion as was given to you by others very early in this thread, the same as I demonstrated in the middle of proving that SAX doesn't support a GBK-encoded input file. Suggestion: Recode your input from GBK to UTF-8. Ensure that the XML declaration doesn't have an unsupported encoding. Your handler will get data encoded as UTF-8. Recode that to GBK if needed. Here's a cut down version of the previous script, focussed on demonstrating that the recoding strategy works. C:\junk>type gbksax2.py import xml.sax, xml.sax.saxutils import cStringIO unistr = u''.join(unichr(0x4E00+i) + unichr(ord('W')+i) for i in range(4)) gbkstr = unistr.encode('gbk') print 'This is a GBK-encoded string: %r' % gbkstr utf8str = gbkstr.decode('gbk').encode('utf8') print 'Now recoded as UTF-8 to be fed to a SAX parser: %r' % utf8str xml_template = """%s""" utf8doc = xml_template % ('utf-8', unistr.encode('utf8')) f = cStringIO.StringIO() handler = xml.sax.saxutils.XMLGenerator(f, encoding='utf8') xml.sax.parseString(utf8doc, handler) result = f.getvalue() f.close() start = result.find('') + 6 end = result.find('') mydata = result[start:end] print "SAX output (UTF-8): %r" % mydata print "SAX output recoded to GBK: %r" % mydata.decode('utf8').encode('gbk') C:\junk>gbksax2.py This is a GBK-encoded string: '\xd2\xbbW\xb6\xa1X\x81 at Y\xc6\xdfZ' Now recoded as UTF-8 to be fed to a SAX parser: '\xe4\xb8\x80W \xe4\xb8\x81X\xe4\xb8\x82Y\xe4\xb8\x83Z' SAX output (UTF-8): '\xe4\xb8\x80W\xe4\xb8\x81X\xe4\xb8\x82Y \xe4\xb8\x83Z' SAX output recoded to GBK: '\xd2\xbbW\xb6\xa1X\x81 at Y\xc6\xdfZ' HTH, John From duncan.booth at invalid.invalid Mon Jan 14 05:39:26 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Jan 2008 10:39:26 GMT Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> Message-ID: Gary Herron wrote: > hakim ouaras wrote: >> Hi, >> >> I am begining with python, I want to know what is the utility and how >> to use the expression "NotImplementedError". >> >> Thak you for your answers >> Hakim >> > > It's meant to be used to mark a procedure that you intend to write, > but have not yet done so. More often it is used to mark a method which is some part of a class interface but is not implemented in that specific class. Typically you do this when writing an abstract base class: whoever uses it must implement particular methods, and if they forget then you raise NotImplementedError. For examples just grep the Python lib sources. e.g. optparse has an abstract class HelpFormatter which has a couple of methods that must be implemented in subclasses: class HelpFormatter: ... def format_usage(self, usage): raise NotImplementedError, "subclasses must implement" def format_heading(self, heading): raise NotImplementedError, "subclasses must implement" ... class IndentedHelpFormatter (HelpFormatter): """Format help with indented section bodies. """ ... def format_usage(self, usage): return _("Usage: %s\n") % usage def format_heading(self, heading): return "%*s%s:\n" % (self.current_indent, "", heading) and so on. From syahreza.octadian at gmail.com Sun Jan 13 21:26:33 2008 From: syahreza.octadian at gmail.com (syahreza.octadian) Date: Sun, 13 Jan 2008 18:26:33 -0800 (PST) Subject: import gzip error (please help) References: Message-ID: <84c2aba9-19cb-4ded-8332-10cf16032127@m77g2000hsc.googlegroups.com> On Jan 11, 7:14 pm, Fredrik Lundh wrote: > the core zlib library (libz.so) isn't installed on your machine. but in my machine there is file -rwxr-xr-x 1 bin bin 48576 Sep 20 2006 /usr/local/lib/ python2.5/lib-dynload/zlib.so if i have to install zlib library core, where i can found it for solaris 10 sparcv. From ppetrick at gmail.com Mon Jan 21 17:41:18 2008 From: ppetrick at gmail.com (p.) Date: Mon, 21 Jan 2008 14:41:18 -0800 (PST) Subject: Transforming ascii file (pseduo database) into proper database References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> <051e9305-6f9a-4d95-91cb-641c04b97b79@e10g2000prf.googlegroups.com> Message-ID: So in answer to some of the questions: - There are about 15 files, each roughly representing a table. - Within the files, each line represents a record. - The formatting for the lines is like so: File1: somval1|ID|someval2|someval3|etc. File2: ID|someval1|someval2|somewal3|etc. Where ID is the one and only value linking "records" from one file to "records" in another file - moreover, as far as I can tell, the relationships are all 1:1 (or 1:0) (I don't have the full dataset yet, just a sampling, so I'm flying a bit in the dark). - I believe that individual "records" within each of the files is unique with respect to the identifier (again, not certain because I'm only working with sample data). - As the example shows, the position of the ID is not the same for all files. - I don't know how big N is since I only have a sample to work with, and probably won't get the full dataset anytime soon. (Lets just take it as a given that I won't get that information until AFTER a first implementation...politics.) - I don't know how many identifiers either, although it has to be at least as large as the number of lines in the largest file (again, I don't have the actual data yet). So as an exercise, lets assume 800MB file, each line of data taking up roughly 150B (guesstimate - based on examination of sample data)...so roughly 5.3 million unique IDs. With that size, I'll have to load them into temp db. I just can't see holding that much data in memory... From Lie.1296 at gmail.com Fri Jan 11 05:52:25 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 11 Jan 2008 02:52:25 -0800 (PST) Subject: Property with Arguments Message-ID: <3b8f3359-2889-42d5-9a5f-db2ee4268e8c@l1g2000hsa.googlegroups.com> Is there a way to create a property with arguments? Or an index value like a list? To be used in the form like: someClass.someProperty['arguments'] = 'some value' or someClass.someProperty('argument1', 'argument2') = 'some value' From gherzig at fmed.uba.ar Mon Jan 14 06:59:32 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Mon, 14 Jan 2008 08:59:32 -0300 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** In-Reply-To: <8a6b8e350801130238y1723cbcco37bdd8e7b60460ec@mail.gmail.com> References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> <4788de48$0$26887$ecde5a14@news.coretel.net> <47890e3e$0$26886$ecde5a14@news.coretel.net> <6a2ccd190801121107r7b728d09ve072909ba2863c04@mail.gmail.com> <8a6b8e350801130238y1723cbcco37bdd8e7b60460ec@mail.gmail.com> Message-ID: <478B4EA4.9070207@fmed.uba.ar> James Matthews wrote: >When did this list become a politics dialog? Please keep on topic "Python"! > >Thanks >James > >On Jan 12, 2008 8:07 PM, Joe Riopel wrote: > > >>On Jan 12, 2008 2:00 PM, radiosrfun wrote: >> >> >>>Whether we agree on "tactics" or not - if it come to a battlefield with the >>>two of us - or any Americans there - we're still going to fight the same >>>enemy - not each other. >>> >>> >>This is a good resource for starting Python >>http://diveintopython.org/ >> >>-- >>http://mail.python.org/mailman/listinfo/python-lis >> >> >> >> indian = CreeIndian() indian.setVoice("lugubrious") indian.says("When the last tree is cut down, the last fish eaten and the last stream poisoned, you will realize that you cannot eat money.") :) From deets at nospam.web.de Thu Jan 31 11:35:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jan 2008 17:35:39 +0100 Subject: REALLY simple xml reader In-Reply-To: <13q3ri2707niqc6@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> Message-ID: <60ebn3F1q0eaeU1@mid.uni-berlin.de> Steven D'Aprano schrieb: > 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. > > "You know Bob, XML just isn't hostile enough to anyone silly enough to > believe it's 'human-readable'. What can we do to make it more hostile?" > > "Well Fred, how about making the XML declaration completely optional, so > you can leave it out and still be vald XML, but if you include it, you're > not allowed to precede it with semantically neutral whitespace?" > > "I take my hat off to you." > > > This is legal XML: > > """ > Hello, world!""" > > and so is this: > > """ > Hello, world!""" > > > but not this: > > """ > Hello, world!""" > > > You can't get this sort of stuff except out of a committee. do not forget to mention that trailing whitespace is evil as well!!! And that for some reason some characters below \x20 aren't allowed in XML even if it's legal utf-8 - for what reason I'd really like to know... Diez From mr.cerutti at gmail.com Sun Jan 6 19:22:17 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Sun, 6 Jan 2008 19:22:17 -0500 Subject: Basic inheritance question In-Reply-To: <42aeef02-a0a9-4e29-9a5d-7a0785997666@v67g2000hse.googlegroups.com> References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <5u95sjF1etf0nU1@mid.individual.net> <42aeef02-a0a9-4e29-9a5d-7a0785997666@v67g2000hse.googlegroups.com> Message-ID: <51302a8c0801061622m50732b01pb948a332cfd63590@mail.gmail.com> On Jan 6, 2008 6:59 PM, Dan Bishop wrote: > > My employer has us use the "m_" convention. > > I wonder why Bjarne made "this->" optional in the first place. > -- > http://mail.python.org/mailman/listinfo/python-list > I think implicit this-> is somewhat more defensible. If 'this' were not a pointer, perhaps C++ wouldn't have chosen impliciticity.. -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sat Jan 26 02:40:28 2008 From: http (Paul Rubin) Date: 25 Jan 2008 23:40:28 -0800 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <479A58F9.4090805@gmx.net> <8d04436f0801251519g482a697dn625223b6d46e8f2c@mail.gmail.com> Message-ID: <7x8x2d11cj.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > | > What's about l.index(max(l)) ? > > Both of these methods scan the list twice. The two given by RH and SDD do > so just once. Both of those will give the index of the of the last maximum > value. If you want the index of the first max value (you did not specify > ;-), write an explicit loop. How about (corrected but still untested): -max((v,-i) for i,v in enumerate(l))[1] I may have still missed something. From jorgen.maillist at gmail.com Wed Jan 16 04:02:56 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Wed, 16 Jan 2008 10:02:56 +0100 Subject: where do my python files go in linux? In-Reply-To: References: <32650267-3c38-4eee-ac18-fbb3b7ae907f@d21g2000prf.googlegroups.com> Message-ID: <11e49df10801160102r18e86c0re6671a770ea3f9fa@mail.gmail.com> Hi All, Sorry for the late reply back, I had a busy weekend ... it seems there is no clear way to do it and maybe that is why I was / am so confused. Eventually I searched for *.py files, and like I said most apps seem to install in /usr/share/{app} I believe that location is for data only that is shared between users. But for simplicity's sake I put my whole python application in there. It saves me setting a lot of paths differently. I made a symbolic link in /usr/bin that points to /usr/share/{app}/{app}.py This all seems to work fine. When I am getting more experienced with Debian / Ubuntu and linux overall, I will re-evaluate this and see if I can improve it. Thanks all for your answer, - Jorgen On Jan 14, 2008 4:30 PM, Nick Craig-Wood wrote: > Paul Boddie wrote: > > On 14 Jan, 08:47, "A.T.Hofkamp" wrote: > > > > > > Rather than re-inventing the wheel, please have a look at distutils: > > > http://docs.python.org/lib/module-distutils.html > > > > > > It does most if not all of the things you want to do. > > > If you want something more advanced, read about eggs. > > > > Although distutils does some of the work needed by the inquirer, it > > falls far short of what is needed to make a Debian package - that's > > why you have the "new" Debian Python policy and why the authors > > specifically refer to both distutils and setuptools in that document. > > It would be nice to have an equivalent to dh-make-perl which takes a > CPAN module and makes a .deb directly. > > http://packages.debian.org/stable/devel/dh-make-perl > > What I usually do is > > python setup.py bdist_rpm > > Then use alien to convert the resulting .rpm into a .deb > > I don't think these create particularly policy compliant .debs but > they are good enough for local usage. > > > Meanwhile, even stdeb [1] doesn't appear to completely automate the > > production of Debian packages using distutils. > > Looks interesting though! > > > [1] http://stdeb.python-hosting.com/ > > -- > Nick Craig-Wood -- http://www.craig-wood.com/nick > -- > > http://mail.python.org/mailman/listinfo/python-list > From nospam at invalid.com Fri Jan 11 12:39:00 2008 From: nospam at invalid.com (Jack) Date: Fri, 11 Jan 2008 17:39:00 GMT Subject: Using a proxy with urllib2 References: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> <87ir21o8sj.fsf@merkury.smsnet.pl> Message-ID: > Works for me. > How do you know that the proxy is not set? The proxy drops some URLs and the URLs were not being dropped when I did this :) > Try this: Thank you. I'll give it a try. From andre.roberge at gmail.com Sun Jan 27 17:49:46 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 27 Jan 2008 14:49:46 -0800 (PST) Subject: optional static typing for Python References: Message-ID: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> On Jan 27, 6:19 pm, "Russ P." wrote: > A while back I came across a tentative proposal from way back in 2000 > for optional static typing in Python: > > http://www.python.org/~guido/static-typing > > Two motivations were given: > > -- faster code > -- better compile-time error detection > > I'd like to suggest a third, which could help extend Python into the > safety-critical domain: > > -- facilitates automated source-code analysis > > There has been much heated debate in the past about whether Python is > appropriate for safety-critical software. Some argue that, with > thorough testing, Python code can be as reliable as code in any > language. Well, maybe. But then, a famous computer scientist once > remarked that, > > "Program testing can be used to show the presence of bugs, but never > to show their absence!" --Edsger Dijkstra > > The next step beyond extensive testing is automated, "static" analysis > of source-code ("static" in the sense of analyzing it without actually > running it). For example, Spark Ada is a subset of Ada with > programming by contract, and in some cases it can formally prove the > correctness of a program by static analysis. > > Then there is Java Pathfinder (http://javapathfinder.sourceforge.net), > an "explicit state software model checker." The developers of JPF > wanted > to use it on a prototype safety-critical application that I wrote in > Python, but JPF only works on Java code. We considered somehow using > Jython and Jythonc, but neither did the trick. So they ended up having > someone manually convert my Python code to Java! (The problem is that > my code was still in flux, and the Java and Python versions have now > diverged.) > > In any case, optional static typing in Python would help tremendously > here. The hardest part of automated conversion of Python to a > statically typed language is the problem of type inference. If the > types are explicitly declared, that problem obviously goes away. > Explicit typing would also greatly facilitate the development of a > "Python Pathfinder," so the conversion would perhaps not even be > necessary in the first place. > > Note also that, while "static" type checking would be ideal, > "explicit" typing would be a major step in the right direction and > would probably be much easier to implement. That is, provide a syntax > to explicitly declare types, then just check them at run time. A > relatively simple pre-processor could be implemented to convert the > explicit type declarations into "isinstance" checks or some such > thing. (A pre-processor command-line argument could be provided to > disable the type checks for more efficient production runs if > desired.) > > I noticed that Guido has expressed further interest in static typing > three or four years ago on his blog. Does anyone know the current > status of this project? Thanks. Perhaps this: http://www.python.org/dev/peps/pep-3107/ might be relevant? Andr? From madhurrajn at gmail.com Fri Jan 18 05:08:27 2008 From: madhurrajn at gmail.com (Madhur) Date: Fri, 18 Jan 2008 02:08:27 -0800 (PST) Subject: Filtering two files with uncommon column References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> <5084371c-dba0-4d11-be95-a01d1b439de6@s12g2000prg.googlegroups.com> Message-ID: On Jan 18, 2:37 pm, Chris wrote: > On Jan 18, 11:23 am, Madhur wrote: > > > > > I would like to know the best way of generating filter of two files > > based upon the following condition > > > I have two files. Contents of the first file is > > > File 1 > > abc def hij > > asd sss lmn > > hig pqr mno > > > File 2 > > > jih def asd > > poi iuu wer > > wer pqr jjj > > > I would like have the output as > > Output > > > File1 > > asd sss lmn > > File2 > > poi iuu wer > > > Basically I want to compare the two files based on second column. If > > the second > > column matches on both the files do not print anything, else if there > > is no matc > > h in for the second column for first file in second file then print it > > under Fil > > e1 header, else if there is no match for the second column for second > > file in fi > > rst file print it under File2 header. > > > Thankyou > > Madhur > > file1 = open('file1.txt','rb') > file2 = open('file2.txt','rb') > > file1_line = file1.next() > file2_line = file2.next() > > while file1_line and file2_line: > try: > f1_col2 = file1_line.split(' ')[1] > except IndexError: > print 'Not enough delimiters in line.' > try: > f2_col2 = file2_line.split(' ')[2] > except IndexError: > print 'Not enough delimiters in line.' > > if f1_col2 != f2_col2: > outfile_data_to_relevant_files() > > file1_line = file1.next() > file2_line = file2.next() > > HTH > Chris If the files2 is unordered, then the above logic does not work. How to takle it? From sjmachin at lexicon.net Thu Jan 10 17:38:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 10 Jan 2008 14:38:53 -0800 (PST) Subject: Newbie question on Classes References: Message-ID: <8f91961f-4d41-48a2-b541-c0604d0fae78@21g2000hsj.googlegroups.com> On Jan 11, 8:46 am, "Adrian Wood" wrote: > Hi al! I'm new to the list, and reasonably new to Python, so be gentle. > > Long story short, I'm having a hard time finding a way to call a > function on every object of a class at once. A class is a factory that creates objects. It keeps no records of what it has created -- it will never have to recall them for remediation. The customer needs to keep track of them. [snip] >I've > tried tracking the names of each object in a list In general, objects have 0, 1, or many "names" ... "tracking the names" is not a very meaningful concept hence not a very useful concept. At your application level, a person's name is what they call themselves and can vary over time and with the purpose for which it is used, and what is actually recorded in databases is subject to a non- trivial error rate -- hence using person's name as a key is not a very good idea. > and even creating > each object within a list, but don't seem to be able to find the right > syntax to make it all work. "creating each object in a list" sounds like it's going down the right path -- you need to keep a collection of objects somehow if you want to perform some operations on all objects, and a list is a reasonable start. Here's a very basic simple skeleton toy demonstration: >>> class Person(object): ... def __init__(self, name, hair): ... self.name = name ... self.hair = hair ... def show(self): ... print 'name=%r hair=%r' % (self.name, self.hair) ... >>> plist = [] >>> obj1 = Person(name='Bluey', hair='red') >>> plist.append(obj1) >>> obj2 = Person(name='John', hair='grey') >>> plist.append(obj2) >>> >>> for obj in plist: ... obj.show() ... name='Bluey' hair='red' name='John' hair='grey' >>> Does this help? From cjw at sympatico.ca Tue Jan 15 11:25:25 2008 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 15 Jan 2008 11:25:25 -0500 Subject: Why this apparent assymetry in set operations? In-Reply-To: References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: Colin J. Williams wrote: > Neil Cerutti wrote: >> On Jan 15, 2008 10:10 AM, wrote: >>> I've noticed that I can update() a set with a list but I can't extend a set >>> with a list using the |= assignment operator. >>> >>> >>> s = set() >>> >>> s.update([1,2,3]) >>> >>> s >>> set([1, 2, 3]) >>> >>> s |= [4,5,6] >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: unsupported operand type(s) for |=: 'set' and 'list' >>> >>> s |= set([4,5,6]) >>> >>> s >>> set([1, 2, 3, 4, 5, 6]) >>> >>> Why is that? Doesn't the |= operator essentially map to an update() call? >> No, according to 3.7 Set Types, s | t maps to s.union(t). >> > If the RHS is a set then it works OK: > > *** Python 2.5.1 (r251:54863, Apr 18 > 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32. *** >>>> import sets >>>> s1= sets.Set([2, 4, 5]) > Set([2, 4, 5]) >>>> s1= sets.Set([2, 4, 5]) >>>> s2= sets.Set([4, 5, 6]) >>>> s1|s2 > Set([2, 4, 5, 6]) >>>> s1|=s2 >>>> s1 > Set([2, 4, 5, 6]) > > It could be modified to handle any > iterable on the RHS. > > Colin W. > I'm sorry, there appears to be a bug: # tSet.py import sets s1= sets.Set([1, 2, 3]) s1.union_update([3, 4,5]) print(s1) s2= sets.Set([6, 7, 8]) s1 |+ s2 # This fails: exceptions.TypeError: bad operand type for unary +: 'Set' print s1 Colin W. From dbr517 at gmail.com Tue Jan 29 08:12:46 2008 From: dbr517 at gmail.com (dbr517 at gmail.com) Date: Tue, 29 Jan 2008 05:12:46 -0800 (PST) Subject: Extending the import mechanism - what is recommended? Message-ID: I need to extend the import mechanism to support another file type. I've already written the necessary C library to read the file and return a python code object. I found one example which just sub-classed imputil.ImportManager like this: from myLib import pye_code as pye_code class MyImporter(imputil.ImportManager): def __init__(self): imputil.ImportManager.__init__(self) self.add_suffix('.pye', self.import_pye) self.install() def import_pye(self, filepath, fileinfo, filename): data = pye_code(filepath) return 0, data, {} This actually works fine if the module is just a few lines of code, but it won't chain to the "built-in" importers; if the module that I'm importing does something as simple as 'import re', it fails. It may be that my confusion here is because (even after reading the code), I'm not clear on the purposes of imputil.ImportManager vs. imputil.Importer :-( What is the "preferred" way to do this type of extension? One other note; at this time, I just need to import individual module files with this extension; I don't need to import packages. Thanks! Dan From lists at cheimes.de Wed Jan 2 03:41:00 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 02 Jan 2008 09:41:00 +0100 Subject: os.tmpfile() In-Reply-To: <32714577.240331199246555557.JavaMail.root@hrndva-web18-z01> References: <32714577.240331199246555557.JavaMail.root@hrndva-web18-z01> Message-ID: <477B4E1C.7040401@cheimes.de> jyoung79 at kc.rr.com wrote: > Can anyone elaborate on how 'os.tmpfile()' works? I was thinking it would create some sort of temporary file I could quickly add text too and then when I was finished would automatically get rid of it. Here's my questions: Please don't use os.tmpfile(). It's not safe and exists only for legacy reasons. The tempfile module contains methods to create safe temporary files and directories. Christian From PurpleServerMonkey at gmail.com Wed Jan 30 15:17:58 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Wed, 30 Jan 2008 12:17:58 -0800 (PST) Subject: Web Interface Recommendations References: <45040839-8b1f-40af-9ef5-1be274c6e95f@z17g2000hsg.googlegroups.com> <80d6ce9f-6c8b-412d-a261-cfe480bd0c3b@e10g2000prf.googlegroups.com> <47a03e68$0$5443$426a34cc@news.free.fr> Message-ID: On Jan 30, 8:08 pm, Bruno Desthuilliers wrote: > PurpleServerMonkey a ?crit : > (snip) > > > Out of the major frameworks is there one that stands out as being > > particularly well suited for what I'm trying to do? > > > Django and CherryPy are on the short list so I'll give them a detailed > > look although Pylons does sound rather interesting as well. > > I guess you'll have to try them out to find the one that best match your > needs and personal preferences. Mostly: > > - CherryPy is more of a web application server than a framework per-se: > it's it's own HTTP server - which might or not be a good thing -, and > only deals with the "controler" part of the MVC triad. > > - Django is by now a mostly mature MVC framework, with more than a > couple years of production use on quite a lot of sites and applications, > good documentation and a somewhat large and active community. OTHO, it's > a very opiniated (and somewhat monolithic) framework, with most parts of > the stack (ORM, forms validation, template system etc) built > specifically for this framework (which was probably the sensible thing > to do by the time), so it's perhaps the less flexible of the three. > > - Pylons is IMHO very promising: wsgi from bottom to top, very flexible, > good default components choice (paste / Routes / SQLAlchemy / Mako / > FormEncode) but let you swap what you want in and out, and FWIW I've > seen so far a very sound architecture. FWIW, next Turbogears major > version will switch from CherryPy to Pylons. OTHO, it's still far from > being as mature and documented as Django. > > My 2 cents... Thanks Bruno, that's just the sort of info I was after. After reading more on the subject recently I'll be installing and testing Pylons and Turbogears first, think it will be a good fit for the project and if not there's no shortage of other offerings. From steve at mhomer.au Thu Jan 10 21:02:23 2008 From: steve at mhomer.au (Steve Brown) Date: Fri, 11 Jan 2008 13:02:23 +1100 Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: <13odjhgshnchjd4@corp.supernews.com> "Neil Cerutti" wrote in message news:mailman.408.1199973821.896.python-list at python.org... > On Jan 10, 2008 12:47 AM, Steve Brown wrote: >> I've got a series of modules which look like this: >> >> #************ >> # >> # Temperature Sense Test >> # >> #************ >> class Test3(ar_test.AR_TEST): >> """Temperature Sense Test""" >> >> >> I don't like the duplicated information: But the comment is attractive, >> and >> the docstring self.__doc__ is already in use in the test log. I've read >> that >> all modules and classes should have docstrings, but I don't really have >> anything else to say, and each module contains only one class. I don't >> think >> that >> >> """Temperature Sense Test""" >> class Test3(ar_test.AR_TEST): >> """Temperature Sense Test""" >> >> would be a real improvement. >> >> What do you think? > > I recommend a careful reading of PEP 257. > > You shouldn't waste your time creating (at best) decorative comments, > like: > #************ > # > # Temperature Sense Test > # > #************ > class Test3(ar_test.AR_TEST): > """Temperature Sense Test"" > > Remember that comments have to maintained along with the rest of the > code, so unnecessary ones just create more work for you. Any time you > can replace a comment with self-explanatory code, you should. > > Here's a vast improvement: > > class TemperatureSenseTester(ar_test.AR_TEST): > > -- > Neil Cerutti Yes, I'm working in that direction. At present there is still code that parses the test sequence to get the class name, but I'm rebuilding that. However, there will still be sufficient information for some of the tests to justify one doc string or comment as well as the class name. Is it possible to get from an object to a class module doc string? Something like self.class.module.__doc__ ? I'm not able to do an assignment inside the test class, because I have to keep that clean, but I can do assignments inside the parent test class. Steve From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 16 09:10:45 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 16 Jan 2008 15:10:45 +0100 Subject: Interesting Thread Gotcha References: Message-ID: <5v6hj5F1k6gi5U1@mid.individual.net> Hendrik van Rooyen wrote: > Absolutely! - well spotted! This is no threading problem at all; not even a syntax problem. If you don't know exactly what start_new_thread and kbd_driver functions do it's impossible to tell if your code does what is intended. > It would have been nice, however, to have gotten something like: > > TypeError - This routine needs a tuple. > > instead of the silent in line calling of the routine in question, > while failing actually to start a new thread. Exactly which part of the code should give you this warning? > Is it worth the trouble of learning how to submit a bug report? For your problem not, IMHO, as a bug report for it will be closed quickly. Regards, Bj?rn -- BOFH excuse #330: quantum decoherence From fredrik at pythonware.com Thu Jan 3 07:00:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 13:00:08 +0100 Subject: PyObject_CallObject code dump after calling 4 times In-Reply-To: References: Message-ID: grbgooglefan wrote: > I have a following C++ code which uses PyObject_CallObject to evaluate > expressions dynamically. This code sets the input parameters for the > function also dynamically. After calling this function 4 times (with > these shown values), PyObject_CallObject causes application to crash > in frame_dealloc. > 1) Can some one please help me understand why is this crash happening > in frame_dealloc & how to solve it? > 2) Is there anything wrong I am doing about incrementing or > decrementing the reference counts of the object passed to > PyObject_CallObject? if something crashes after a while, it's almost always a reference count error. > default: > printf("Unknown data type [%d] for %s\n",ndtyp,pEvalFunc- >> pExprVarsArray[nCtr].szVarName); > } what's val set to if this happens? > if(!val){ > ret = -1; > printf("Failed to convert %d %s to PyObject\n",ndtyp,pEvalFunc- >> pExprVarsArray[nCtr].szVarName); fflush(stdout); > Py_XDECREF(pTuple); > break; > } > PyTuple_SetItem(pTuple, nCtr, val); > Py_XDECREF(val); > } PyTuple_SetItem "steals" a reference http://docs.python.org/api/refcountDetails.html so you shouldn't DECREF val yourself. > // all variables are set, call Python function > Py_XINCREF(pTuple); this isn't necessary, and will (most likely) result in a leak. > PyObject *pResult = PyObject_CallObject(pEvalFunc- >> pPyEvalFunction,pTuple); > Py_XDECREF(pTuple); > > if(PyErr_Occurred()){ > PyErr_Print(); > } else { > char* plevel = NULL; > if(NULL != (plevel = PyString_AsString(pResult))){ > ret = 0; > sprintf(szEvalResult,"%s",plevel); shouldn't you check the size of plevel here, before copying it to szEvalResult? (and what's wrong with using strcpy to do the copy, btw?) From ask at me Thu Jan 17 14:25:20 2008 From: ask at me (alf) Date: Thu, 17 Jan 2008 13:25:20 -0600 Subject: how django discovers changed sources Message-ID: <18udndZmKMfMNhLanZ2dnUVZ_rzinZ2d@comcast.com> hi, I started playing with django and accidentally discovered that it restarts the server once a source file is touched. does it use some python's feature or just scans for changs on its one? sources? any idea? A. From paddy3118 at googlemail.com Tue Jan 22 13:34:08 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 22 Jan 2008 10:34:08 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Jan 22, 5:34 am, George Sakkis wrote: > On Jan 22, 12:15 am, Paddy wrote: > > > On Jan 22, 3:20 am, Alan Isaac wrote:> I want to generate sequential pairs from a list. > > <> > > > What is the fastest way? (Ignore the import time.) > > > 1) How fast is the method you have? > > 2) How much faster does it need to be for your application? > > 3) Are their any other bottlenecks in your application? > > 4) Is this the routine whose smallest % speed-up would give the > > largest overall speed up of your application? > > I believe the "what is the fastest way" question for such small well- > defined tasks is worth asking on its own, regardless of whether it > makes a difference in the application (or even if there is no > application to begin with). Hi George, You need to 'get it right' first. Micro optimizations for speed without thought of the wider context is a bad habit to form and a time waster. If the routine is all that needs to be delivered and it does not perform at an acceptable speed then find out what is acceptable and optimise towards that goal. My questions were set to get posters to think more about the need for speed optimizations and where they should be applied, (if at all). A bit of forethought might justify leaving the routine alone, or optimising for readability instead. - Paddy. From jitender001001 at gmail.com Wed Jan 16 08:29:08 2008 From: jitender001001 at gmail.com (jitender001001 at gmail.com) Date: Wed, 16 Jan 2008 05:29:08 -0800 (PST) Subject: plz help how to print python variable using os.system() Message-ID: <78444c3a-17dc-4912-aac7-39253648d86f@u10g2000prn.googlegroups.com> hi all i m new to python and i have a problem of printing python variable using os.system() in bash !/usr/bin/env python var = "/home/anonymous" os.system("echo $var) it is not working.. i want to print string using os.system() ....plz help From luca.colombi.it at gmail.com Thu Jan 17 07:32:32 2008 From: luca.colombi.it at gmail.com (Luca) Date: Thu, 17 Jan 2008 04:32:32 -0800 (PST) Subject: zip function for python Message-ID: <7cec1575-12d6-458c-9507-296e7d1ff330@e6g2000prf.googlegroups.com> Hi, Ive written this easy and fast function cause there it was impossible for me to find one that zip a directory without external libraries: import zipfile import sys import os def zipdir(zipPath,directory="./"): """Store the cdontent of directory to a zipPath file, if directory is not given stores the content of the current dir ( luca.colombi.it at gmail.com )""" directory=os.path.realpath(directory) zipObject = zipfile.ZipFile(zipPath, 'w') for root, dirs, files in os.walk(directory): for file in files: arcfile=root[len(os.path.commonprefix((directory, root))) +1:]+"/"+file #retrieves the inner relative file path filepath=os.path.join(root,file) zipObject.write(filepath,arcfile) zipObject.close() return zipObject #for optional further elaborations From steven.bethard at gmail.com Tue Jan 8 17:04:15 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 08 Jan 2008 15:04:15 -0700 Subject: Modules and descriptors In-Reply-To: References: Message-ID: Chris Leary wrote: > As I understand it, the appeal of properties (and descriptors in > general) in new-style classes is that they provide a way to > "intercept" direct attribute accesses. This lets us write more clear > and concise code that accesses members directly without fear of future > API changes. > > I love this feature of the language, but find that I still have to > call getter/setter methods of module instances. Since module > attributes are accessed by way of __dict__ and the module type has a > valid __mro__, why doesn't the descriptor protocol apply to module > instances? Because it doesn't apply to class *instances*. Module-level code gets executed roughly like this:: mod = ModuleType(...) exec module_code in mod.__dict__ So consider the similar code:: >>> class C(object): ... pass ... >>> c = C() >>> exec ''' ... def foo(self, *args): ... print self, args ... ''' in c.__dict__ A function ``foo`` has been added to the ``C`` instance. But *instances* don't invoke the descriptor protocol, so we the ``self`` parameter is not bound to the ``C`` instance:: >>> c.foo() Traceback (most recent call last): File "", line 1, in TypeError: foo() takes at least 1 argument (0 given) So the straightforward answer to your question is that module instances don't invoke the descriptor protocol because instances in general don't invoke the protocol (only classes do). The follow-up question is usually something like "well, can't we make module instances special and have them invoke the descriptor protocol?" Yes, in theory it would be possible, but it would break backwards compatibility in very bad ways. For example, every pure function you define at the module level would then become a bound method whenever it was accessed. Consider a simple module ``mod`` like:: def foo(bar): return 'baz(%s)' % bar If I try to use this module, and module instances invoke the descriptor protocol, then ``bar`` will always be bound to the module instance. That means we'd have to totally change how we right module level functions, and they'd have to start looking like this:: def foo(mod, bar): return 'baz(%s)' % bar That, of course, would break *tons* of existing code. STeVe From rewonka at gmail.com Tue Jan 15 19:24:02 2008 From: rewonka at gmail.com (rewonka at gmail.com) Date: Tue, 15 Jan 2008 16:24:02 -0800 (PST) Subject: Memory problem with threading Message-ID: <55f016fb-42f9-47d6-903a-a068f846b795@e10g2000prf.googlegroups.com> Hi! I made a string parser program, it has a main function and a working thread class. When it is running in 24h non-stop, the memory run out. I dont Know why. Do anybody know somekind of debugger that can i see what is eating the memory? Maybe there is a list or value or dictionary that is growing continually but i dont know which one. Maybe there is a program for that kind of debugging, what can monitoring the memory and values size in the memory. Or it is a sience fiction :) p.s.: sorry for my english Rew From sturlamolden at yahoo.no Fri Jan 11 13:40:54 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 11 Jan 2008 10:40:54 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <64a5ee48-cc7f-4e19-be34-012b68c537ae@v67g2000hse.googlegroups.com> On 9 Jan, 20:11, "dongie.ag... at gmail.com" wrote: > Is there a better way to do color tracking, or is Python just too slow > as an interpreted language to do any effective color tracking? The slowness stems from the use of k-means clustering on each frame. SciPy's clustering module used for the purpose is written in plain C. It is not Python that is slow. From bignose+hates-spam at benfinney.id.au Mon Jan 14 23:24:52 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 15:24:52 +1100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> <87ir1wf1wi.fsf@mulj.homelinux.net> Message-ID: <87k5mbd8bv.fsf@benfinney.id.au> Hrvoje Niksic writes: > Ben Finney writes: > > > Hrvoje Niksic writes: > >> __init__ *is* the closest equivalent to what other languages > >> would call a constructor. > > > > No. That would be '__new__', which actually constructs the > > instance, > > That's not what other OO languages (C++, Java) actually call a > constructor More fool them, then. It seems that the best referent for the term "constructor" is the thing that does the constructing and returns the result. -- \ "Imagine a world without hypothetical situations." -- Anonymous | `\ | _o__) | Ben Finney From tim at rileyphotographic.com Sat Jan 26 13:48:38 2008 From: tim at rileyphotographic.com (tim at rileyphotographic.com) Date: Sat, 26 Jan 2008 10:48:38 -0800 (PST) Subject: Programmer Need Message-ID: Hi, I have a program of about 300 lines of code that I wrote in AutoHotKeys. I am looking for someone who might be interested in making a little $ to help me bring this program into a mac compatable language. I can be reached at tim at rileyphotographic dot come From B.Ogryczak at addr.in.reply-to.invalid Sat Jan 19 09:01:44 2008 From: B.Ogryczak at addr.in.reply-to.invalid (Bart Ogryczak) Date: Sat, 19 Jan 2008 14:01:44 +0000 (UTC) Subject: SPARQL server in Python? Message-ID: Hi, I'm trying to migrate some R&D I've done with PHP and RAP[1] to Python. But I've got hard time finding Python RDF/SPARQL server. Most things I find are SPARQL clients. Do you know of a Python library, that could do the job? [1] http://sites.wiwiss.fu-berlin.de/suhl/bizer/rdfapi/ bart -- Set phasers on kill, fire at will. http://candajon.azorragarse.info/ http://azorragarse.candajon.info/ From antonio.chay at gmail.com Thu Jan 31 17:05:00 2008 From: antonio.chay at gmail.com (Antonio Chay) Date: Thu, 31 Jan 2008 14:05:00 -0800 (PST) Subject: char string 2 hex string Message-ID: Hello! I need to transform a string from a file into a hexadecimal representation, for example: "AAA" should be "414141" With perl I do this with: unpack("H*","AAA") And with python I got this: "".join([str(hex(ord(x)))[2:] for x in "AAA"]) But seems a little "weird" for me. Is there another way? Thanks in advance! From fetchinson at googlemail.com Sun Jan 13 03:08:45 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 13 Jan 2008 00:08:45 -0800 Subject: __init__ explanation please In-Reply-To: <00b801c8558e$13765be0$6701a8c0@hpinm> References: <47895d25$0$30708$4c368faf@roadrunner.com> <00b801c8558e$13765be0$6701a8c0@hpinm> Message-ID: Please keep discussion on the list...... > > I'm not sure if I understand your question correctly but maybe this will > > help: > > > > If you want code to be run upon creating an instance of your class you > > would use __init__. Most common examples include setting attributes on > > the instance and doing some checks, e.g. > > > > class Person: > > def __init__( self, first, last ): > > if len( first ) > 50 or len( last ) > 50: > > raise Exception( 'The names are too long.' ) > > self.first = first > > self.last = last > > > > And you would use your class like so, > > > > p1 = Person( 'John', 'Smith' ) > > p2 = Person( "Some long fake name that you don't really want to > > except, I don't know if it's really longer than 50 but let's assume it > > is", "Smith" ) > > # This last one would raise an exception so you know that something is not > > okay > > > > HTH, > > Daniel > > Is not the code run when I create an instance by assignement somewhere else? > > I take the point that one might want to check for potential exceptions > immediately, but most examples in the literature aren't doing that and don't > seem to be doing anything that would not be done when creating an instance > by assignment later somewhere. I'm missing something basic here. What do you mean by "create an instance by asignment somewhere else"? From service at metamodul.com Fri Jan 11 09:03:30 2008 From: service at metamodul.com (HajoEhlers) Date: Fri, 11 Jan 2008 06:03:30 -0800 (PST) Subject: Define installation directory for python Message-ID: Task: build and install python 2.5.1 on AIX 5.3 to /opt/python2.5 with the subdirectories: ./lib ./bin ./include ./man ./info a.s.o The ./bin ./man are created fine but for ./lib & ./include the structure is /opt/python2.5/lib/python2.5 /opt/python2.5/include/python2.5 where i would like to have only /opt/python2.5/lib and /opt/ python2.5/include Looking at the make install output i see that setup.py is using a option called --install-platlib but how do i set this option during configure ? Or do i have to patch the setup.py ? Any hints tia Hajo From lipun4u at gmail.com Fri Jan 25 07:28:43 2008 From: lipun4u at gmail.com (asit) Date: Fri, 25 Jan 2008 04:28:43 -0800 (PST) Subject: inode number in windows XP Message-ID: <3331a284-b786-42d5-bbe8-a764d59af920@c4g2000hsg.googlegroups.com> why this program shows ambiguous behavior ?? import os import stat import time #import types file_name=raw_input("Enter file name : ") print file_name, "information" st=os.stat(file_name) print "mode", "=>", oct(stat.S_IMODE(st[stat.ST_MODE])) print "type","=>", if stat.S_ISDIR(st[stat.ST_MODE]): print "DIReCTORY" elif stat.S_ISREG(st[stat.ST_MODE]): print "REGULAR" elif stat.S_ISLINK(st[stat.ST_MODE]): print "LINK" print "file size", "=>",st[stat.ST_SIZE] print "inode number", "=>",st[stat.ST_INO] print "device inode resides on", "=>",st[stat.ST_DEV] print "number of links to this inode", "=>",st[stat.ST_NLINK] print "last accessed", "=>", time.ctime(st[stat.ST_ATIME]) print "last modified", "=>", time.ctime(st[stat.ST_MTIME]) print "inode changed", "=>", time.ctime(st[stat.ST_CTIME]) i ran this program in Winows XP SP2 in python 2.5. From bg_ie at yahoo.com Thu Jan 24 11:28:47 2008 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Thu, 24 Jan 2008 08:28:47 -0800 (PST) Subject: Connecting to Sql Server from Python References: <56f14ea0-defb-445b-b957-7f379a000add@x69g2000hsx.googlegroups.com> <00bb6a7c-7e92-4ddf-af79-4ed6827f2a6b@s13g2000prd.googlegroups.com> Message-ID: <6c436619-0898-43ea-8320-0a2f4d9f610d@v46g2000hsv.googlegroups.com> On 24 Jan, 17:16, Mike Driscoll wrote: > On Jan 24, 9:44 am, bg... at yahoo.com wrote: > > > > > > > Hi, > > > I have an sql server from which I'd like to read and write to. The > > connection string is as follows - > > > "Data Source=localhost\SQLExpress;Initial Catalog=Test;Integrated > > Security=True;Pooling=False" > > > Other properties as they appear in Visual Studio 2005 include - > > > Data Provider: .NET Framework Data Provider for SQL Server > > State: Open > > Type: Microsoft SQL Server > > > So my question is, how might I connect to my Test Catalog and update > > data within its tables via perl, > > > Thanks, > > > Barry. > > If you want to do this in Perl, then why are you asking on a Python > list? In Python, there are many ways to accomplish this task. Take a > look at SQLAlchemy, SQLObject, pymssql or the adodb package. > > http://pymssql.sourceforge.net/www.sqlalchemy.orghttp://www.sqlobject.org/http://phplens.com/lens/adodb/adodb-py-docs.htm > > Mike- D?lj citerad text - > > - Visa citerad text - Woops, I ment Python... From asmodai at in-nomine.org Fri Jan 4 10:34:41 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jan 2008 16:34:41 +0100 Subject: Memory Leaks and Heapy In-Reply-To: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> Message-ID: <20080104153441.GO82115@nexus.in-nomine.org> -On [20080104 16:11], Yaakov Nemoy (loupgaroublond at gmail.com) wrote: >I'm trying to plug some memory leaks in a TurboGears program. We (the >Fedora Project) have a few apps in Turbogears in infrastructure that >all seem to be running into the same issues in a variety of >configurations. Hopefully when I get to the cause of this in one app, >Smolt, we can fix the others too. [snip] >A couple of developers have mentioned that python might be fragmenting >its memory space, and is unable to free up those pages. How can I go >about testing for this, and are there any known problems like this? >If not, what else can I do to look for leaks? As various people pointed out to me: http://wingolog.org/archives/2007/11/27/reducing-the-footprint-of-python-applications That might help. Aside from that (rant), I seriously dislike Python's memory management and even more the fairly arcane ways people have to go about debugging/troubleshooting some 600 MB to 2-3 GB(!) of resident memory use by Python. Personally I consider this the weakest point of Python. Given the fact there is a garbage collector this sort of keeping track of memory seems a bit contradictory to the concept of garbage collection. (And yes, I am investigating this and also how to get it leaner and better.) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Speak the sweet truth... From hardcoded.software at gmail.com Thu Jan 24 13:55:35 2008 From: hardcoded.software at gmail.com (Virgil Dupras) Date: Thu, 24 Jan 2008 10:55:35 -0800 (PST) Subject: Test driven development References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> <53bae618-0a57-470e-b698-3f936ef7c0e7@s12g2000prg.googlegroups.com> Message-ID: <98f3ca4c-a7f0-4707-b09d-8012b86de96b@x69g2000hsx.googlegroups.com> On Jan 24, 1:30?pm, Roel Schroeven wrote: > Virgil Dupras schreef: > > > I know what you mean by top-down vs. bottom-up and I used to have the > > same dilemma, but now I would tend to agree with Albert. Your issue > > with top-down or bottom-up is not relevant in TDD. The only thing that > > is relevant is to reach your current milestone as soon as possible, > > without caring about what you're going to do in the milestone after > > that. > > > Not so long ago, I took the "bottom-up" approach to TDD, which was a > > mistake because it leads to over-engineering (the end result is not so > > bad since it's over-engineering that has good test coverage :) ) > > I don't regularly use TDD yet, and one of the reasons is that in many > cases I'm unsure exactly how to use it in practice. I read "Test-driven > development - A practical guide" (and I should re-read), but I feel it > doesn't help my much in everyday situations. Somehow the examples in the > book don't match very well with how I code (and I admit that perhaps the > problem is more with me than with the book). > > One of the problems I have is something like what Andy describes: I need > a function spam(), so I write tests for it. Then I start implementing > the function and see that I need to write functions ham() and eggs(). > Should I write unit tests for ham() and eggs(), or do I rely on the > tests for spam()? If I don't write them, doesn't that make it more > difficult to find out why the tests for spam() fail? > > Speaking about over-engineering, when I do TDD along the lines of the > book I mentioned, I always feel that I'm over-engineering the tests. It > all feels very unnatural though I'm convinced it shouldn't be like that. > > Can someone suggest other books to read about the subject, ideally > something more focused on Python or C++ rather than Java? > > -- > The saddest aspect of life right now is that science gathers knowledge > faster than society gathers wisdom. > ? ?-- Isaac Asimov > > Roel Schroeven I also have a book about TDD and it never was of much help either. All techniques come from the initial workflow: Red - Green - Refactor. The problem you describe is a tricky problem. The way I feel it should be solved is: - Write spam() (and its tests, of course). - Then, at some point, in the re-factor phase, you split extract the function ham() from spam(). Alright, do it and keep the tests as is (all on spam()). - Then at some other point, you extract eggs(). same thing. - After a while (I don't know, 3 or 4 milestones), when it becomes clear that ham() and eggs() are there to stay, start moving your tests away from spam() by just mocking ham() and eggs() and just make sure that spam() call them with the right arguments. The tests you had on spam() that were relevant to ham() and eggs() are just performed directly on them now. What I've been saying in my other message is: Don't do that too early, because if it turns out that ham() and eggs() is not the optimal way to do it, but foo() bar() and baz() is, it is *much* easier to do a safe re-factoring with high level tests. From george.sakkis at gmail.com Wed Jan 23 14:06:44 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 23 Jan 2008 11:06:44 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: <90cfc1f7-8792-4e28-9466-6a1bf77c87c5@q77g2000hsh.googlegroups.com> On Jan 23, 1:30 pm, Paddy wrote: > I've heard quality expressed as "meeting requirements", which I think > is apt. Falling short of requirements everyone knows doesn't give a > quality result, but equally 'exceeding' requirements also detracts > from quality (as does not knowing your requirements). > It is good to learn optimization techniques, which may be part of what > you are saying, but part of that is learning when it pays to apply > them and/or search for them; and when it does not. The OP wanted an answer to a simple question, not a lecture on good software engineering principles. This whole subthread reminds of a movie (can't remember which) where someone asks his buddy in the stadium "what do you want?". His buddy gets it wrong and embarks in a long diatribe of what he wants in life now, what he wanted as a child, what's the meaning of one's life and so on. After a couple of minutes the guy cuts him and asks again: - "Man, what do you want, burger or hot dog?" - "Oh, a hot dog". Sometimes you want to see the tree right in front of you, not the whole damn forest. George From BjornSteinarFjeldPettersen at gmail.com Mon Jan 14 17:05:21 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Mon, 14 Jan 2008 14:05:21 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> Message-ID: On Jan 14, 1:41 pm, Richard Szopa wrote: > On Jan 13, 3:31 pm, thebjorn > wrote: > > > They do, except for when it comes to what super(..) returns. It isn't > > really an object in the sense that they're presented in the tutorial, > > but rather a sort of proxy to the methods in the ancestor classes of > > the concrete object (self), relative to the current method's class. I > > can't imagine that sentence would ease any confusion however, suffice > > it to say that you have to call getattr(super(..), 'name') instead of > > super(..).__getattr__('name') and you have to call super(..).__len__() > > instead of len(super(..)) -- I can't imagine that lessens any > > confusion either :-/ > > Surprisingly, I think your first sentence *does* make something more > clear. Let me check if I understand it right: when we call a method on > super(Foo, self) it is as if we were calling call-next-method in > Common Lisp or Dylan I don't remember if CLOS was changed to use C3 Linearization also, but the concept came from Dylan (http://www.webcom.com/haahr/dylan/ linearization-oopsla96.html) and that's what is implemented in Python. [...] > However, there's one piece that doesn't completely fit to the puzzle: > why does getattr work? The help says: > > getattr(...) > getattr(object, name[, default]) -> value > > Get a named attribute from an object; getattr(x, 'y') is > equivalent to x.y. When a default argument is given, it > is returned when the attribute doesn't exist; without it, > an exception is raised in that case. > > Does it work on the basis that "getattr(x, 'y') is equivalent to x.y"? > What is then a "named attribute for an object" in Python? It seems not > to be equivalent to the value of the item whose name is 'y' in the > object's class __dict__... Conceptually, x.y is always "get the y attribute of x" and the same as getattr(x, 'y'). Depending on the type of x and y, and your familiarity with Python internals, what actually happens during a lookup might be surprising. In the vast majority of cases however, x.y is equivalent to one of x.__dict__['y'] type(x).__dict__['y'] but if you're a language geek like me, you might be excited that in some cases it is type(x).__dict__['y'].__get__(x, type(x)) which says you get the value of x.y by calling y and passing x as an argument -- if you know CLOS you'll recognize that it's a primitive multi-method call. (there are some other special cases too, although not as exciting ;-) Much more detail can be found in Raymond's paper on descriptors (http://users.rcn.com/python/download/Descriptor.htm) and Michele's paper on super (http://www.phyast.pitt.edu/~micheles/python/ super.html). -- bjorn From http Thu Jan 17 19:13:52 2008 From: http (Paul Rubin) Date: 17 Jan 2008 16:13:52 -0800 Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> Message-ID: <7xy7aong73.fsf@ruckus.brouhaha.com> George Sakkis writes: > And if the iterables don't necessarily support len(), here's a more > general solution: Not trying to pick on you personally but there's this disease when a newbie comes with a basically simple question (in this case, how to solve the problem with ordinary lists) and gets back a lot of complex, overly general "graduate level" solutions. There's a humorous set of Haskell examples that takes this to extremes: http://www.willamette.edu/~fruehr/haskell/evolution.html From nospam at invalid.com Fri Jan 11 12:57:18 2008 From: nospam at invalid.com (Jack) Date: Fri, 11 Jan 2008 17:57:18 GMT Subject: Using a proxy with urllib2 References: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> <87ir21o8sj.fsf@merkury.smsnet.pl> Message-ID: <26Ohj.3530$jJ5.1972@newssvr11.news.prodigy.net> Rob, I tried your code snippet and it worked great. I'm just wondering if getopener( ) call is lightweight so I can just call it in every call to fetchurl( )? Or I should try to share the opener object among fetchurl( ) calls? Thanks, Jack "Rob Wolfe" wrote in message news:87ir21o8sj.fsf at merkury.smsnet.pl... > Try this: > > > import urllib2 > > def getopener(proxy=None): > opener = urllib2.build_opener(urllib2.HTTPHandler) > if proxy: > proxy_support = urllib2.ProxyHandler({"http": "http://" + proxy}) > opener.add_handler(proxy_support) > return opener > > def fetchurl(url, opener): > f = opener.open(url) > data = f.read() > f.close() > return data > > print fetchurl('http://www.python.org', getopener('127.0.0.1:8081')) > > > HTH, > Rob From kyosohma at gmail.com Tue Jan 8 17:14:28 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 8 Jan 2008 14:14:28 -0800 (PST) Subject: Newbie question: Classes References: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com> Message-ID: <061b53ed-7e89-4afb-96f8-bb4d28320b47@v67g2000hse.googlegroups.com> On Jan 8, 3:31 pm, "Daniel Fetchinson" wrote: > > Basically, I have created a program using tkinter without using any class > > structure, simply creating widgets and functions (and finding ways around > > passing variables from function to function, using global variables etc). > > The program has become rather large ( lines?) I am trying to now put it into > > a class structure, because I hear it is easier to handle. > > > So basically, I put all the stuff into a class, making the widgets in the > > "def __init__(self, root)" (root being my Tk() ) and then I have had to put > > a "self." in front of any instance of any variable or widget. Is this right? > > it seems like nothing is any easier (except having variables locally). Is > > this right? Should I be creating more classes for different things or what? > > Use the method that works best for you. If you like the procedural > approach more then don't worry about being object oriented. The good > thing is that python is multi-paradigm so if custom objects don't make > your life easier then just forget about them :) One great benefit to classes is the ability to take a generic class and then subclass it. Or the ability to instantiate various objects from one class. Say you have a dog class. If you pass in the correct data, you can instantiate a dalmatian, a Labrador or a mutt. They're all dogs, but their all different too. Enough of my babbling. Check out the following links for more info: http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm http://www.diveintopython.org/object_oriented_framework/defining_classes.html http://docs.python.org/tut/node11.html Mike From yantao at telus.com Sun Jan 27 00:32:40 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 05:32:40 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: <13po55nc0q0s06@corp.supernews.com> References: <13po55nc0q0s06@corp.supernews.com> Message-ID: You didn't understand my question, but thanks any way. Yes, it is true that %s already support unicode, and I did not contradict that. But it counts the number of bytes instead of characters, and makes things like %-20s out of alignment. If you don't understand my assertion, please don't argue back and I am only interested in answers from those who are qualified. ============================================================== "Steven D'Aprano" wrote in message news:13po55nc0q0s06 at corp.supernews.com... > On Sun, 27 Jan 2008 04:06:45 +0000, Peter Pei wrote: > >> I probably should mention that what I want is to make all parts of the >> string aligned, and look like table. I am not looking for other ways to >> make it table-alike, but only interested in making % work with unicode >> -counting characters not bytes... > > % already works with unicode. Just give it unicode arguments: > > >>>> print u"x y z %s 1 2 3" % u"Les mis?rables" > x y z Les mis?rables 1 2 3 > > > -- > Steven From laurent.pointal at laposte.net Thu Jan 17 15:23:48 2008 From: laurent.pointal at laposte.net (Laurent Pointal) Date: 17 Jan 2008 20:23:48 GMT Subject: Importing java within python References: Message-ID: <478fb953$0$874$ba4acef3@news.orange.fr> Le Thu, 17 Jan 2008 08:36:59 -0800, Henry Chang a ?crit?: > www.jython.org > > On Jan 17, 2008 8:06 AM, Osthaus, Christopher (Mission Systems) > wrote: >> >> >> Hi All, >> >> This is an easy one - I'm new to Python and working on a script where I >> need to use some java swing classes. I'm running Python on Windows. >> >> I've got an import statement that looks something like: >> >> from java.lang import System >> from javax.swing import JPasswordField from javax.swing import >> JOptionPane >> >> >> How do I get Python to recognize the java module? I assume I need to >> set one of my environment variables? I realize this is probably very >> obvious but I can't seem to figure it out :) >> >> Thanks everyone... >> -- >> http://mail.python.org/mailman/listinfo/python-list >> To complement Henry Chang reply, you can also take a look at: http://jpype.sourceforge.net/ (Java To Python Integration) http://jepp.sourceforge.net/ (Java Embeded Python) See my other Python/Java links at http://www.limsi.fr/Individu/pointal/python.html#liens-intautlang-java A+ Laurent. -- Laurent POINTAL - laurent.pointal at laposte.net From davidhuebel at gmail.com Mon Jan 14 20:03:43 2008 From: davidhuebel at gmail.com (grackle) Date: Mon, 14 Jan 2008 17:03:43 -0800 (PST) Subject: module naming conventions References: <7f39199a-3334-4bcc-a424-5102f042ed01@1g2000hsl.googlegroups.com> <87zlv8dnya.fsf@benfinney.id.au> <6a53a14a-8f7c-4b6b-986f-48c7698f679f@v29g2000hsf.googlegroups.com> <8763xwdj9c.fsf@benfinney.id.au> Message-ID: <972e17b4-2d1a-43d6-8382-21585b0fe786@v29g2000hsf.googlegroups.com> On Jan 14, 6:28 pm, Ben Finney wrote: > grackle writes: > What do you mean by "top-level module", and "the same top-level name"? > Do you mean "the same fully-qualified name"? If two modules are in > separate places in the hierarchy, they will have different > fully-qualified names. I mean that if I worked at Google (which I don't) and developed google.search and google.officeapps, they would share the same top- level name "google". Because of this, if I wanted to use the two in the same program, they would have to be deployed at the same point in the source path: if I deployed one set of source at src1/google/ search/etc. and the other at src2/google/officeapps/etc. and added src1/ and src2/ to my application's Python source path, one of them would be found and the other not. (Essentially I'd be trying to create two different modules, both named "google", which is nonsense.) I would have to put them in the same source directory and merge the two google/__init__.py files together. I might as well admit that I already made the same mistake in reverse, using a single top-level module for my application, which I now want to split into a group of core application modules and one or more optional, separately-deployed packages. Since I screwed up the first time, I figured I'd get advice before attempting to rectify the situation. My next (slightly more considered, possibly just as naive) impulse is to turn google.search and google.officeapps into google_search and google_officeapps, thereby avoiding name clashes with internal or external projects. (It feels dangerous, not to mention presumptuous, to put generic names like "search" and "officeapps" in the global namespace.) > Release your package as free software on the Cheeseshop > . If the name you want is already > taken, pick one that will help users distinguish yours from the > existing one. Unfortunately, my company thinks it's their software and not mine :-) -David From elind at spamcop.net Mon Jan 14 23:50:00 2008 From: elind at spamcop.net (Erik Lind) Date: Mon, 14 Jan 2008 23:50:00 -0500 Subject: A question about event handlers with wxPython Message-ID: <478c3bb2$0$5150$4c368faf@roadrunner.com> I'd appreciate any pointer on a simple way to tell within an event handler where the event came from. I want to have "while" condition in a handler to stop or change processing if an event occurs from some other button click. Trying to bind more than one event to the same handler still doesn't tell me where the event came from in a basic bind. Is there an argument I can put in the bind so as to identify the source of the event in the event argument? . From thermostat at gmail.com Wed Jan 16 13:07:59 2008 From: thermostat at gmail.com (Dan) Date: Wed, 16 Jan 2008 10:07:59 -0800 (PST) Subject: Interesting Thread Gotcha References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> Message-ID: <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> On Jan 16, 11:06 am, "Diez B. Roggisch" wrote: > Hendrik van Rooyen wrote: > > "Dan" wrote: > > >> >>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) > > >> Needs to be > >> >>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) > > >> Commas are important! > > >> -Dan > > > Absolutely! - well spotted! > > > As the first correct respondent, you win the freedom to spend a week in > > Naboomspruit at your own expense. > > > It would have been nice, however, to have gotten something like: > > > TypeError - This routine needs a tuple. > > > instead of the silent in line calling of the routine in question, > > while failing actually to start a new thread. > > You can't prevent the silent inline-calling - otherwise, how would you do > this: > > def compute_thread_target(): > def target(): > pass > return target > > thread.start_new_thread(compute_thread_target()) > > Of course start_new_thread could throw an error if it got nothing callable > as first argument. No idea why it doesn't. > > Diez Of course, in his case, having start_new_thread throw an error wouldn't have helped, since he went into an infinite loop while evaluating the parameters for start_new_thread. Would it be possible to have pychecker (or some such) warn that there is an insufficient parameter count to start_new_thread? I guess that would require knowing the type of thread. . . -Dan From google at mrabarnett.plus.com Wed Jan 30 21:27:06 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 30 Jan 2008 18:27:06 -0800 (PST) Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> <60cai8F1qgh3aU1@mid.uni-berlin.de> <15d16017-3b43-45a8-86b9-93203972f813@u10g2000prn.googlegroups.com> Message-ID: <3c3d8f03-1a69-4fbe-8979-9aae458ab46c@u10g2000prn.googlegroups.com> On Jan 31, 1:09 am, George Sakkis wrote: > On Jan 30, 5:03 pm, Marc 'BlackJack' Rintsch wrote: > > > On Wed, 30 Jan 2008 15:29:45 +0100, Wildemar Wildenburger wrote: > > > Gerardo Herzig wrote: > > >> I will use genital().extend(), thats for shure ^^ > > > > Well, you never go wrong with apply(genital(), females), do you? > > > `apply()` is deprecated. And ``genital(*females)`` looks a bit odd. :-) > > Well, that use case alone is enough to convince anyone that apply > should stay :-) > The original had genital(), so that would be genital()(*females). But what is genital() anyway? A factory? From paddy3118 at googlemail.com Sat Jan 5 01:37:16 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 4 Jan 2008 22:37:16 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> Message-ID: <33417662-8246-4950-9b86-265aa1c63c69@c23g2000hsa.googlegroups.com> On Jan 4, 7:55 pm, c... at mailinator.com wrote: > Hello, > This is a question for the best method (in terms of performance > only) to choose a random element from a list among those that satisfy > a certain property. > > This is the setting: I need to pick from a list a random element > that satisfies a given property. All or none of the elements may have > the property. Most of the time, many of the elements will satisfy the > property, and the property is a bit expensive to evaluate. Chance of > having the property are uniform among elements. > > A simple approach is: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > > Returns None if no element has the property > ''' > random.shuffle(a_list) > for i in a_list: > if property(i): return i > > but that requires to shuffle the list every time. > > A second approach, that works if we know that at least one element of > the list has the property, is: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > > Loops forever if no element has the property > ''' > while 1: > i=random.choice(a_list) > if property(i): return i > > which is more efficient (on average) if many elements of the list have > the property and less efficient if only few elements of the list has > the property (and goes crazy if no element has the property) > > Yet another one: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > ''' > b_list=[x for x in a_list if property(x)] > try: > return random.choice(b_list) > finally: return None > > but this one checks the property on all the elements, which is no > good. > > I don't need strong random numbers, so a simple solution like: > import random > globalRNG=random.Random() > > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > > Works only if len(a_list)+1 is prime: uses Fermat's little theorem > ''' > a=globalRNG(1,len(a_list)) > ind=a > for i in xrange(len(a_list)): > x=a_list[a-1] > if property(x):return x > ind*=a > > but this works only if len(a_list)+1 is prime!!! Now this one could be > saved if there were an efficient method to find a prime number given > than a number n but not very much greater... > > Any other ideas? Thanks everybody Caching might help. If random_pick is called several times with the same list(s) then cache the result of [property(i) for i in a_list] against a_list. If random_pick is called several times with list(s) whith multiple instances of list items then cache property(i) against i for i in a_list . You could do both. You might investigate wether property(i) could be implemented using a faster algorithm, maybe table lookup, or interpolation from initial table lookup. - Paddy. From aspineux at gmail.com Fri Jan 4 22:39:13 2008 From: aspineux at gmail.com (aspineux) Date: Fri, 4 Jan 2008 19:39:13 -0800 (PST) Subject: How a smart editor could make "Postfix type declarations PEP3117" in Python3000 more readable Message-ID: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> Hi I read the PEP 3117 about the new "Postfix type declarations" in Python3000. THIS PEP as been REJECTED ! But ... The notation in the PEP is very ugly ! This make python code more difficult to read! Anyway when I switched to python (from C, C++, ..), I suffered a lot of the untyped python variables. And I think this is a good idea to include typing in python. Then I get this idea: The editor could hide the typing notation, just displaying hint ! It could also auto-complete the type of any variable having already a type in the current function, and underline untyped variable or variable having multiple type inside the function. Just an idea ! Alain Spineux Happy new year. From gagsl-py2 at yahoo.com.ar Tue Jan 1 13:58:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Jan 2008 16:58:45 -0200 Subject: Some specific exec behavior ? References: <477A88D9.4090708@gmail.com> Message-ID: En Tue, 01 Jan 2008 16:39:21 -0200, Stef Mientki escribi?: > I find 2 strange behaviors in exec-function, > and I can't find anything in the documentation. > (Python 2.4.3 Enthought edition) > > 1. A function definition may not span more than 1 line, e.g. > This generates an exception: > def _func (x,y): > return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) > > while this works correct: > def _func (x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) > > 2. an emtpy line at the end also generates an exception > > Is this behavior correct ? > where should I find information about it ? It's correct; source lines must be separated by '\n' only (NOT '\r\n' as in a Windows text file) and the last line must end in '\n'. It's documented, but under the compile() built-in function: http://docs.python.org/lib/built-in-funcs.html; perhaps the docs for exec should refer there. -- Gabriel Genellina From http Sun Jan 27 06:01:05 2008 From: http (Paul Rubin) Date: 27 Jan 2008 03:01:05 -0800 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> <7xy7acsx2l.fsf@ruckus.brouhaha.com> <8ddebd68-43dc-4320-86e1-887aadff4af3@d70g2000hsb.googlegroups.com> <7xmyqs722t.fsf@ruckus.brouhaha.com> <13pnbp9l8lk1j8b@corp.supernews.com> <8a699886-24f7-485e-a87f-90518e9ff536@l32g2000hse.googlegroups.com> Message-ID: <7xzlur353i.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > The final sum: the Psyco version is almost 40 times faster than the > Python version, and just 2.8 times slower than the D version, and 3.4 > times slower than a C version (that doesn't use too many pointer > tricks). I think this is good enough. I can't help wishing that psyco could do as good a job with the simpler expressions of that function. I'll have to see what JHC does. From bruno.desthuilliers at gmail.com Sat Jan 12 11:57:35 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jan 2008 08:57:35 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <13of60ikspqhh06@corp.supernews.com> Message-ID: <8ad434bb-4213-417c-8be1-b84faf62c7ed@q39g2000hsf.googlegroups.com> On 11 jan, 17:23, Ed Jensen wrote: > Bruno Desthuilliers wrote: > > fact 1: CPython compiles source code to byte-code. > > fact 2: CPython executes this byte-code. > > fact 3: Sun's JDK compiles source code to byte-code. > > fact 4: Sun's JDK executes this byte-code. > > > Care to prove me wrong on any of these points ? Don't bother: you can't. > > So my first assertion that "CPython is compiled to byte-code, which is > > then executed by a VM" is true, and since the same assertion also stands > > for Java (ie: sun's JDK), then the "just like" qualifier is true too. > > Period. > > #2 and #4 are wrong (or, at best, misleading). Here, I'll fix them > for you: > > Fact 2: CPython interprets the bytecode. > > Fact 4: Sun's JVM does some interpretation of the bytecode, but also > compiles some of the bytecode to native code and executes the > resulting native code. > > These distinctions can be important and it's intellectually dishonest > to gloss over them. These distinctions are important if the context is the VM implementation, which is *obviously* not the case here. FWIW, I you had spent a bit more time reading the remaining of the discussion with the OP, I do clearly mention this distinction. So please get a life and keep your comment about "intellectual dishonesty" where they belong. From arnodel at googlemail.com Tue Jan 22 11:09:01 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 08:09:01 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: On Jan 22, 1:19?pm, Alan Isaac wrote: > I suppose my question should have been, > is there an obviously faster way? > Anyway, of the four ways below, the > first is substantially fastest. ?Is > there an obvious reason why? Can you post your results? I get different ones (pairs1 and pairs2 rewritten slightly to avoid unnecessary indirection). ====== pairs.py =========== from itertools import * def pairs1(x): return izip(islice(x,0,None,2),islice(x,1,None,2)) def pairs2(x): xiter = iter(x) while True: yield xiter.next(), xiter.next() def pairs3(x): for i in range( len(x)//2 ): yield x[2*i], x[2*i+1], def pairs4(x): xiter = iter(x) return izip(xiter,xiter) def compare(): import timeit for i in '1234': t = timeit.Timer('list(pairs.pairs%s(l))' % i, 'import pairs; l=range(1000)') print 'pairs%s: %s' % (i, t.timeit(10000)) if __name__ == '__main__': compare() ===================== marigold:python arno$ python pairs.py pairs1: 0.789824962616 pairs2: 4.08462786674 pairs3: 2.90438890457 pairs4: 0.536775827408 pairs4 wins. -- Arnaud From tjreedy at udel.edu Wed Jan 16 15:12:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Jan 2008 15:12:53 -0500 Subject: import from question References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com><478d04d4$0$26042$88260bb3@free.teranews.com> <87tzleb2st.fsf@benfinney.id.au> Message-ID: "Ben Finney" wrote in message news:87tzleb2st.fsf at benfinney.id.au... | Tobiah writes: | | > This is a little surprising. So "from mod import *" really copies | > all of the scalars into new variables in the local namespace. 'Scalar' is not a Python term. Neither is 'object pointer' really, except in respect to the CPython implementation. | No. Nothing is copied. All the objects (remembering that in Python, | *everything* is an object) created by the code in module 'mod' are | given names in the current namespace. To amplify, 'from mod import *' is, I believe, more or less equivalent to import mod for name in mod.__all__ exec "%s = mod.%s" % name,name del mod except, of course, that the imported module would not actually be bound to 'mod' (and need deleting) so that there is no conflict with mod containing the name 'mod'. From beema.shafreen at gmail.com Thu Jan 3 09:09:06 2008 From: beema.shafreen at gmail.com (Beema shafreen) Date: Thu, 3 Jan 2008 19:39:06 +0530 Subject: CSV Message-ID: Hi all, I have written a script to parse a CSV file: import csv def get_lines(fname): fhandle = csv.reader(open(fname,"rb")) for line in fhandle: while fhandle.next()[0] == "prot_hit_num": continue for row in fhandle: print row result = get_lines("file.csv") print result I need to print the data from "prot_hit_num" and before the line "peptide sequence". I am able to print the whole from "prot_hit_num" to the end of the file but I need to break before line "peptide sequence........". How should i do this. -------------- next part -------------- An HTML attachment was scrubbed... URL: From neumann at wu-wien.ac.at Thu Jan 31 19:00:47 2008 From: neumann at wu-wien.ac.at (neumann at wu-wien.ac.at) Date: Thu, 31 Jan 2008 16:00:47 -0800 (PST) Subject: object vs class oriented -- xotcl References: <2dfb6cd3-921a-4692-9627-d35bda40a93e@v29g2000hsf.googlegroups.com> Message-ID: <63fecd10-4d04-40b3-9de4-139a87dcae90@q39g2000hsf.googlegroups.com> On 29 Jan., 19:22, William Pursell wrote: > I > believe "per object mixin" is the correct > term for such an animal. The first several google > hits on that phrase all reference xotcl, so I'm > not sure if that is an xotcl inspired vocabulary > that isn't really standard. well, it depends, what you mean by "standard" when it comes to mixins. We coined the term to distinguish between per object and per class mixins, where the per objects mixins have much in common with the decorator design pattern (see e.g. http://nm.wu-wien.ac.at/research/publications/xotcl-objpattern.pdf) We have as well a paper showing that the approach based on intersection classes does not scale well, especially when multiple supplemental classes should be mixed in, and some of the behavior should be as well mixed out (see e.g. section 3.3 in http://nm.wu-wien.ac.at/research/publications/xotcl-mixin.pdf) If you are interested in the matter, we have as well a recent paper http://nm.wu-wien.ac.at/research/publications/b613.pdf providing declarative semantics for mixins, and there is many more related papers in the publications section of media.wu-wien.ac.at From asmodai at in-nomine.org Tue Jan 8 03:33:02 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 09:33:02 +0100 Subject: Look for a string on a file and get its line number In-Reply-To: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> Message-ID: <20080108083302.GD75977@nexus.in-nomine.org> -On [20080108 09:21], Horacius ReX (horacius.rex at gmail.com) wrote: >I have to search for a string on a big file. Once this string is >found, I would need to get the number of the line in which the string >is located on the file. Do you know how if this is possible to do in >python ? (Assuming ASCII, otherwise check out codecs.open().) big_file = open('bigfile.txt', 'r') line_nr = 0 for line in big_file: line_nr += 1 has_match = line.find('my-string') if has_match > 0: print 'Found in line %d' % (line_nr) Something to this effect. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ If you think that you know much, you know little... From ryszard.szopa at gmail.com Mon Jan 14 18:53:48 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Mon, 14 Jan 2008 15:53:48 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> Message-ID: On Jan 14, 11:05 pm, thebjorn wrote: > I don't remember if CLOS was changed to use C3 Linearization also, but > the concept came from Dylan (http://www.webcom.com/haahr/dylan/ > linearization-oopsla96.html) and that's what is implemented in Python. The Common Lisp ANSI standard is from 1994, and the article you cite is from 1996, which strongly suggests C3 linearization wasn't included in CLOS. The most important difference between CLOS and C3 linearization AFAIK is that the latter enforces monotonicity, while the former doesn't. Of course, it shouldn't be very difficult to implement the C3 behavior in Common Lisp using the de facto standard MetaObject Protocol. (Nb. Dylan was such a nice language... It's a pity it is practically dead right now.) > but if you're a language geek like me, you might be excited that in > some cases it is > > type(x).__dict__['y'].__get__(x, type(x)) > > which says you get the value of x.y by calling y and passing x as an > argument -- if you know CLOS you'll recognize that it's a primitive > multi-method call. (there are some other special cases too, although > not as exciting ;-) Yeah, I also feel the excitement, so probably I am a language geek too ;-). However, this is still quite far away from full fledged multimethods. (OTOH trying to get something more from these primitive multimethods by abusing __get__ looks kind of tempting ;-)) Regards, -- Richard From sipickles at hotmail.com Fri Jan 18 13:51:19 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Fri, 18 Jan 2008 18:51:19 +0000 Subject: Pythonland documentation Message-ID: Hi I am new to python (fairly) but can't stop pythonning. c++ seems so far away now.... from here it looks like a horrid scribble :) Anyway.... my question is really about doc tools. I've been used to doxygen in c++ land, and although it makes a reasonable stab with a python project in java mode, the output is a bit messy. Can any one suggest a more tailored tool? or do I risk a flamewar? :) Thanks SiPi -- Linux user #458601 - http://counter.li.org. From sromero at gmail.com Thu Jan 10 03:07:35 2008 From: sromero at gmail.com (Santiago Romero) Date: Thu, 10 Jan 2008 00:07:35 -0800 (PST) Subject: Converting a bidimensional list in a bidimensional array References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> <13obak214p9h8cc@corp.supernews.com> Message-ID: > C:\> \python25\python -m -s :-) Thanks a lot :-) From paddy3118 at googlemail.com Wed Jan 23 13:30:04 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 23 Jan 2008 10:30:04 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Jan 23, 2:32 am, George Sakkis wrote: > On Jan 22, 1:34 pm, Paddy wrote: > > > > > On Jan 22, 5:34 am, George Sakkis wrote: > > > > On Jan 22, 12:15 am, Paddy wrote: > > > > > On Jan 22, 3:20 am, Alan Isaac wrote:> I want to generate sequential pairs from a list. > > > > <> > > > > > What is the fastest way? (Ignore the import time.) > > > > > 1) How fast is the method you have? > > > > 2) How much faster does it need to be for your application? > > > > 3) Are their any other bottlenecks in your application? > > > > 4) Is this the routine whose smallest % speed-up would give the > > > > largest overall speed up of your application? > > > > I believe the "what is the fastest way" question for such small well- > > > defined tasks is worth asking on its own, regardless of whether it > > > makes a difference in the application (or even if there is no > > > application to begin with). > > > Hi George, > > You need to 'get it right' first. > > For such trivial problems, getting it right alone isn't a particularly > high expectation. Hi George, not 'alone' but 'first'. And it is the ultimate expectation. Who wants to recieve wrong software? > > > Micro optimizations for speed > > without thought of the wider context is a bad habit to form and a time > > waster. > > The OP didn't mention anything about the context; for all we know, > this might be a homework problem or the body of a tight inner loop. Thats why I thought to ask about the context. > There is this tendency on c.l.py to assume that every optimization > question is about a tiny subproblem of a 100 KLOC application. Without > further context, we just don't know. Again, I did not assume; I asked about the wider context. I too don't believe your statement about c.l.p. > > > If the routine is all that needs to be delivered and it does not > > perform at an acceptable speed then find out what is acceptable > > and optimise towards that goal. My questions were set to get > > posters to think more about the need for speed optimizations and > > where they should be applied, (if at all). > > I don't agree with this logic in general. But you don't defend yourself well by such a far-fetched example. I've heard quality expressed as "meeting requirements", which I think is apt. Falling short of requirements everyone knows doesn't give a quality result, but equally 'exceeding' requirements also detracts from quality (as does not knowing your requirements). It is good to learn optimization techniques, which may be part of what you are saying, but part of that is learning when it pays to apply them and/or search for them; and when it does not. - Paddy. > Just because one can solve a > problem by throwing a quick and dirty hack with quadratic complexity > that happens to do well enough on current typical input, it doesn't > mean he shouldn't spend ten or thirty minutes more to write a proper > linear time solution, all else being equal or at least comparable > (elegance, conciseness, readability, etc.). Of course it's a tradeoff; > spending a week to save a few milliseconds on average is usually a > waste for most applications, but being a lazy keyboard banger writing > the first thing that pops into mind is not that good either. > > George From martin at v.loewis.de Sun Jan 20 17:19:47 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 20 Jan 2008 23:19:47 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt In-Reply-To: References: Message-ID: <4793C903.60201@v.loewis.de> > But for different reasons I also want to get the absolute path of > Python install directory (not only the executable under Linux) and > site-packages directory. The Python install directory is available as sys.prefix. The site-packages directory is sys.prefix+"lib/python"+x.y+"/site-packages (where x.y is from sys.version_info). HTH, Martin From hyugaricdeau at gmail.com Fri Jan 11 09:56:03 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Fri, 11 Jan 2008 06:56:03 -0800 (PST) Subject: Help with Scons References: Message-ID: <22fde803-0583-458e-a817-3087cbb21edc@f47g2000hsd.googlegroups.com> On Jan 11, 5:20 am, anush wrote: > Can anybody tell how I could go about running python scripts with > scons. Have you tried reading the SCons user guide (http://www.scons.org/doc/ production/HTML/scons-user.html)? It's actually pretty good. I'm not too clear on what you're asking though. SCons scripts are written in Python (as is SCons itself)... Hyuga From bignose+hates-spam at benfinney.id.au Sun Jan 13 07:58:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 13 Jan 2008 23:58:29 +1100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: <87tzlhg9vu.fsf@benfinney.id.au> Jeroen Ruigrok van der Werven writes: > -On [20080113 01:41], Erik Lind (elind at spamcop.net) wrote: > >I'm new to Python, and OOP. I've read most of Mark Lutz's book and > >more online and can write simple modules, but I still don't get > >when __init__ needs to be used as opposed to creating a class > >instance by assignment. > > I personally tend to see __init__ or __new__ as equivalent to what > other languages call a constructor. That's getting the two of them confused. __new__ is a constructor, __init__ is not. > (And I am sure some people might disagree with that. ;)) It isn't really a matter for much debate. __new__ is the constructor: it creates the instance and returns it. Along the way, it calls __init__ on the *already-created* instance, to ask it to initialise itself ready for use. So, __init__ is an "initialiser" for the instance. Python, unlike many other OO languages, fortunately has these two areas of functionality separate. It's far more common to need to customise instance initialisation than to customise creation of the instance. I override __init__ for just about every class I write; I can count the number of times I've needed to override __new__ on the fingers of one foot. -- \ "Reichel's Law: A body on vacation tends to remain on vacation | `\ unless acted upon by an outside force." -- Carol Reichel | _o__) | Ben Finney From d.l.goldsmith at gmail.com Mon Jan 7 18:08:01 2008 From: d.l.goldsmith at gmail.com (dgoldsmith_89) Date: Mon, 7 Jan 2008 15:08:01 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python References: Message-ID: On Jan 7, 2:47 pm, Fredrik Lundh wrote: > dgoldsmith_89 wrote: > > Can anyone point me to a downloadable open source English dictionary > > suitable for programmatic use with python: I'm programming a puzzle > > generator, and I need to be able to generate more or less complete > > lists of English words, alphabetized. Thanks! DG > > here's one: > > http://www.dcs.shef.ac.uk/research/ilash/Moby/ > > Excellent, that'll do nicely! Thanks!!! DG From safealattar at gmail.com Wed Jan 30 03:36:09 2008 From: safealattar at gmail.com (Safe Alattar) Date: Wed, 30 Jan 2008 00:36:09 -0800 Subject: help using python on Vista Message-ID: I have no issues using python on XP. However on Vista I cant get the python gui (IDLE) to open! I did some research and found out that I need to unhide .idlerc but I cannot find any hidden files by that name whatsoever. Please help me. Im fairly new to python but I want to get this going. User friendly instructions would be much appreciated. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Jan 23 13:32:01 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Jan 2008 19:32:01 +0100 Subject: pairs from a list References: Message-ID: Matthew_WARREN wrote: > I'm just fiddling with this, am no great expert, but I added > > def pairs5(x): > o=[] > for n in zip(x[::2],x[1:2]): The second argument should be x[1::2]. > o.append(n) > return o > > I dont know if that breaks any constraints placed on the problem, but I It breaks the constraints unless the above is not cut-n-paste ;) Also note that your pairs5() offers no advantage over def pairs6(x): return zip(x[::2], x[1::2]) Peter From mark.e.tolonen at mailinator.com Sun Jan 27 15:58:10 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Sun, 27 Jan 2008 12:58:10 -0800 Subject: strftime return value encoding (mbcs, locale, etc.) References: <%D5nj.2630$Xg7.935@tornado.fastwebnet.it> Message-ID: <7oudne7Kqp3DbQHanZ2dnUVZ_tadnZ2d@comcast.com> "Giovanni Bajo" wrote in message news:%D5nj.2630$Xg7.935 at tornado.fastwebnet.it... > Hello, > > I am trying to find a good way to portably get the output of strftime() > and put it onto a dialog (I'm using PyQt, but it doesn't really matter). > The problem is that I need to decode the byte stream returned by strftime > () into Unicode. > > This old bug: > http://mail.python.org/pipermail/python-bugs-list/2003- > November/020983.html > > (last comment) mentions that it is "byte string in the locale's encoding". > > The comment also suggests to use "mbcs" in Windows (which, AFAIK, it's > sort of an "alias" encoding for the current Windows codepage), and to > find out the exact encoding using locale.getpreferredencoding(). > > Thus, I was hoping that something like: > > strftime("%#c", localtime()).decode(locale.getpreferredencoding()) > > would work... but alas I was reported this exception: > > LookupError: unknown encoding: cp932 > > So: what is the correct code to achieve this? Will something like this > work: > > data = strftime("%#c", localtime()) > if os.name == "nt": > data = data.decode("mbcs") > else: > data = dada.decode(locale.getpreferredencoding()) > > Is this the correct way of doing it? (Yes, it sucks). > > Shouldn't Python automatically alias whatever is returned by > locale.getpreferredencoding() to "mbcs", so that my original code works > portably? > > Thanks in advance! > -- > Giovanni Bajo Odd, what version of Python are you using? Python 2.5 works: >>> import time,locale >>> time.strftime('%#c').decode(locale.getpreferredencoding()) # cp1252 on >>> my system u'Sunday, January 27, 2008 12:56:30' >>> time.strftime('%#c').decode('cp932') u'Sunday, January 27, 2008 12:56:40' >>> time.strftime('%#c').decode('mbcs') u'Sunday, January 27, 2008 12:56:48' --Mark From terry at jon.es Wed Jan 9 09:32:39 2008 From: terry at jon.es (Terry Jones) Date: Wed, 9 Jan 2008 15:32:39 +0100 Subject: Open a List of Files In-Reply-To: Your message at 00:40:56 on Wednesday, 9 January 2008 References: <874pdomrrd.fsf@mulj.homelinux.net> <18308.12959.742868.758136@terry.local> Message-ID: <18308.56071.859777.102224@terry.local> >>>>> "BJ" == BJ Swope writes: I (at least) think the code looks much nicer. BJ> #Referring to files to write in various places... BJ> open_files['deliveries'].write(flat_line) BJ> open_files['deliveries'].write('\n') If you were doing a lot with the deliveries file at some point, you could put the file descriptor into a local variable deliveries = open_files['deliveries'] deliveries.write(flat_line) deliveries.write('\n') BJ> #And finally to close the opened files BJ> for fn in open_files.keys(): BJ> open_files[fn].close() You don't need "for fn in open_files.keys():", you can just use "for fn in open_files:", but simpler than that is to just use the dictionary values: for fn in open_files.values(): fn.close() Regards, Terry From bill.mill at gmail.com Sun Jan 27 11:18:19 2008 From: bill.mill at gmail.com (Bill Mill) Date: Sun, 27 Jan 2008 11:18:19 -0500 Subject: Klik2 Project, Python apps on linux In-Reply-To: <94dd8f6f0801262249v1c07cf3em2548c470a523291e@mail.gmail.com> References: <94dd8f6f0801262249v1c07cf3em2548c470a523291e@mail.gmail.com> Message-ID: <797fe3d40801270818n3c34c5f5lda0d6b6eab6d9261@mail.gmail.com> Jason, Can you give a little more detail on the problem? What's the directory structure of a Klik package that's failing look like? What program is trying to import what module from where that's failing? -Bill Mill On Jan 27, 2008 1:49 AM, Jason Taylor wrote: > Hi > > We've been working on klik2, http://code.google.com/p/klikclient/, which > implements OSX like application files on linux (with applications working on > all distros), In which every user desktop application is 1 file > > We've run into a bit of a problem with python apps, so while we can run a > complicated application like openoffice.org on ubuntu, fedora and suse from > a single file we cant run any python applications such as > jokosher > gnome-specimen > angrydd > gausssum > pathological > quodlibet > webboard > istanbul > exaile > ccsm > bittornado > pessulus > labyrinth > wammu > accerciser > > We'd like to fix this in a clean way with out resorting to nasty hacks > involving $PYTHON_PATH. > > If any one has any suggestions please email me or drop by #klik on freenode > > Issue http://code.google.com/p/klikclient/issues/detail?id=144 > > Cheers > > Jason Taylor > > -- > "Why isn't my life like a situation comedy? Why don't I have a bunch of > friends with nothing better to do but drop by and instigate wacky > adventures? Why aren't my conversations peppered with spontaneous > witticisms? Why don't my friends demonstrate heartfelt concern for my well > being when I have problems? ...I gotta get my life some writers." - Calven > -- > http://mail.python.org/mailman/listinfo/python-list > From cokofreedom at gmail.com Wed Jan 9 05:40:41 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jan 2008 02:40:41 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <8089de25-76c7-426a-a9c7-9ac0a3641e30@f3g2000hsg.googlegroups.com> On Jan 9, 11:34 am, cesco wrote: > Hi, > > say I have a string like the following: > s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... > > Thanks in advance > Cesco For replacing every other one, I tend to use the modulo, with a counter. count = (if u want even start with 0 else do 1) while/for replacing /in lalastring: if count % 2 == 0: do even else: do odd count += 1 This is a rather basic way of doing it, and I am sure people will sure much more efficient ways, but it generally works for me. Though I am now wondering if count % 2 when count == 2 is true or false as it returns 0 Of course you still need to do your replace but you should be able to do that. From paddy3118 at googlemail.com Thu Jan 17 01:10:55 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 16 Jan 2008 22:10:55 -0800 (PST) Subject: assigning values in python and perl References: Message-ID: On Jan 17, 3:34 am, "J. Peng" wrote: > I just thought python's way of assigning value to a variable is really > different to other language like C,perl. :) > > Below two ways (python and perl) are called "pass by reference", but > they get different results. > Yes I'm reading 'Core python programming', I know what happened, but > just a little confused about it. > > $ cat t1.py > def test(x): > x = [4,5,6] > Hi J, Unlike C or Perl , there is hardly ever any good reason for functions to act by purposefully modifying their arguments. Don't do it. Stick a return in your function and use that result. It is much more maintainable and readable. (It will also work, and look a lot more like, the same function written in other languages :-) - Paddy. From stef.mientki at gmail.com Thu Jan 10 18:31:17 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 11 Jan 2008 00:31:17 +0100 Subject: getting absolute path ? In-Reply-To: References: Message-ID: <4786AAC5.3030905@gmail.com> thanks Mike, with your links I managed to write some code that seems to work well. Still I stay surprised that these kind of functions are not available ;-) cheers, Stef kyosohma at gmail.com wrote: > On Jan 9, 3:22 pm, Stef Mientki wrote: > >> hello, >> >> I'm trying to convert the links in html pages to absolute links, >> these pages can either be webpages or files on local harddisk (winXP). >> Now I've struggling for a while, and this code works a lilttle: >> >> i = line.find ( 'href=' ) >> if i < 0 : >> i = line.find ( ' src=' ) >> if i >= 0 : >> ii = line.find ( '"', i+6 ) >> file = line [ i+6 : ii ] >> #print urlparse.urljoin ( p, file ) >> if file.find ( 'http:' ) < 0 : >> abspath = os.path.normpath ( os.path.join ( p, file ) ) >> line = line.replace ( file, abspath ) >> print line >> >> but it only covers files on local disk and just 1 link per line, >> so I guess it's a lot of trouble to catch all cases. >> Isn't there a convenient function for (OS independent preferable) ? >> Googled for it, but can't find it. >> >> thanks, >> Stef Mientki >> > > I googled a bit too. The Perl forums talk about using a regular > expression. You can probably take that and translate it into the > Python equivalent: > > http://forums.devshed.com/perl-programming-6/how-to-parse-relatives-links-to-absolute-links-8173.html > > I also found this, which appears to be an old c.l.py thread: > > http://www.dbforums.com/archive/index.php/t-320359.html > > You might have more luck if you google for "relative to absolute > links". I would also take a look at how django or cherrypy creates > their URLs. > > Mike > From thelanguageofcities at gmail.com Sun Jan 27 18:09:52 2008 From: thelanguageofcities at gmail.com (Max) Date: Sun, 27 Jan 2008 15:09:52 -0800 (PST) Subject: Python Genetic Algorithm Message-ID: Hi all. I'm just getting introduced to Python (mostly through Dive Into Python), and I've decided to use it for a project where I have to write my own Genetic Algorithm. Even if you don't know about GAs, you might be able to help with an issue I'm having. I'm just starting the project off, so I'm still in the conceptual phase, and I'm stuck on how I'm going to be able to implement something. In GAs, you operate on a Population of solutions. Each Individual from the Population is a potential solution to the problem you're optimizing, and Individuals have what's called a chromosome - a specification of what it contains. For example, common chromosomes are bit strings, lists of ints/floats, permutations...etc. I'm stuck on how to implement the different chromosomes. I have a Population class, which is going to contain a list of Individuals. Each individual will be of a certain chromosome. I envision the chromosomes as subclasses of an abstract Individual class, perhaps all in the same module. I'm just having trouble envisioning how this would be coded at the population level. Presumably, when a population is created, a parameter to its __init__ would be the chromosome type, but I don't know how to take that in Python and use it to specify a certain class. I'm doing something similar with my crossover methods, by specifying them as functions in a module called Crossover, importing that, and defining crossover_function = getattr(Crossover, "%s_crossover" % xover) Where xover is a parameter defining the type of crossover to be used. I'm hoping there's some similar trick to accomplish what I want to do with chromosomes - or maybe I'm going about this completely the wrong way, trying to get Python to do something it's not made for. Any help/ feedback would be wonderful. Thanks, Max Martin From yantao at telus.com Sun Jan 27 00:48:48 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 05:48:48 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: References: Message-ID: <4XUmj.43653$fj2.34204@edtnps82> For sure I can calculate the number of characters and do the padding myself, but what's the point, and i surely hope that python does it for me. ============ "Peter Pei" wrote in message news:cjTmj.43610$fj2.37903 at edtnps82... >I am using things like "%-20s%-60s%-10s" in tkinter listbox to make it look >like a table, with mono sized font like lucie system. But this does not >work with data contains "Les mis?rables", because it is unicode, and one >byte is not neccessary one character. Now how can I resolve this issue? > > My issue is "how to make format operator % work with unicode as expected", > and has nothing to do with tkinter. If I want to use a table widget or > something, I can. But that's not the question. From mail at timgolden.me.uk Wed Jan 23 06:06:34 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Jan 2008 11:06:34 +0000 Subject: subprocess and & (ampersand) In-Reply-To: References: Message-ID: <47971FBA.8080104@timgolden.me.uk> Steven Bethard wrote: > I'm having trouble using the subprocess module on Windows when my > command line includes special characters like "&" (ampersand):: > > >>> command = 'lynx.bat', '-dump', 'http://www.example.com/?x=1&y=2' > >>> kwargs = dict(stdin=subprocess.PIPE, > ... stdout=subprocess.PIPE, > ... stderr=subprocess.PIPE) > >>> proc = subprocess.Popen(command, **kwargs) > >>> proc.stderr.read() > "'y' is not recognized as an internal or external command,\r\noperable > program or batch file.\r\n" > > As you can see, Windows is interpreting that "&" as separating two > commands, instead of being part of the single argument as I intend it to > be above. Is there any workaround for this? How do I get "&" treated > like a regular character using the subprocess module? A little experimentation suggests that the problem's somehow tied up with the .bat file. ie this works for me (doubly complicated because of the long firefox path: import subprocess cmd = [ r"c:\Program Files\Mozilla Firefox\firefox.exe", "http://local.goodtoread.org/search?word=tim&cached=0" ] subprocess.Popen (cmd) but this doesn't: "c:\Program Files\Mozilla Firefox\firefox.exe" "%*" import subprocess cmd = [ r"c:\temp\firefox.bat", "http://local.goodtoread.org/search?word=tim&cached=0" ] subprocess.Popen (cmd) although, interestingly, it seems to cut off at the "=" before the "&". Not sure how significant that is. So, even assuming we're looking at the same situation, I suppose one solution for you is to break out the .bat file. But that may not be a possibility. TJG From nick.fabry at coredump.us Tue Jan 29 00:10:23 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Tue, 29 Jan 2008 00:10:23 -0500 Subject: ISO with timezone In-Reply-To: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> References: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Message-ID: Hello, nik. On Jan 28, 2008, at 21:03, nik wrote: > Hi, > > How does one express the time in ISO format with the timezone > designator? > > what I want is YYYY-MM-DDThh:mm:ss.sTZD > >> From the documentation I see: >>>> from datetime import tzinfo, timedelta, datetime >>>> class TZ(tzinfo): > ... def utcoffset(self, dt): return timedelta(minutes=-399) > ... >>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') > '2002-12-25 00:00:00-06:39' > > and I've also figured out: >>>> datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3] > '2008-01-23T11:22:54.130' > > But can't figure out how to fit them together. > There is nothing there to 'fit together' - in the first example given, the datetime object has no time component specified, so it fills in default vaules of zero. The following should make this clear: >>> your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ()) >>> print your_time 2008-02-29 15:30:11-05:00 >>> print your_time.isoformat('T') 2008-02-29T15:30:11-05:00 If you wish to append the NAME of the tzinfo object instead of its offset, that requires a bit more playing around (along with a properly defined tzinfo object - check out dateutil or pytz for a concrete implementation of tzinfo subclasses (i.e. timezones)), but the following would work: >>> print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z') 2008-02-29T15:30:11 EST For details on how the .strftime method works, see Python Standard Library, Section 14.2. I hope this helps! Nick Fabry > Thank you, > Nik > -- > http://mail.python.org/mailman/listinfo/python-list From hakim_ouaras at yahoo.com Sun Jan 20 11:35:52 2008 From: hakim_ouaras at yahoo.com (hakim ouaras) Date: Sun, 20 Jan 2008 08:35:52 -0800 (PST) Subject: change values of array in dictionary Message-ID: <321201.92447.qm@web63707.mail.re1.yahoo.com> Hi all, I have two dictionays like these: dict1={"id1":[1,2,3,4,5],"id2":[1,2,3,1,3], "var1":[10,11,12,13,14]} dict2={"id2":[1,2,3,4,], "var2":[20,21,22,23]} I want to replace the values of dict1["var1"] with those of dict["var2"] with taking count the correspondance between dict1["id1"] and dict2["id2"]. result that I want to have is like this: dict1={"id1":[1,2,3,4,5],"id2":[1,2,3,1,3], "var1":[20,21,22,20,22]} Are there any predefined python function to do this. Thak you for your answers Hakim ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Fri Jan 4 18:36:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 4 Jan 2008 15:36:27 -0800 (PST) Subject: Questions about subclassing an int References: Message-ID: <38614926-19fe-49f8-aa08-fe68449aae70@f3g2000hsg.googlegroups.com> On Jan 4, 10:55?pm, "Steven W. Orr" wrote: > class S(int): > ? ? ?def __init__(self, value): > ? ? ? ? self.value = value > ? ? ?def addStr(self, str): > ? ? ? ? self.doc = str > > s = S(44) > s.addStr('Hello') > > print 's = ', s > print 's.doc = ', s.doc > > class T(int): > ? ? ?def __init__(self, value, str): > ? ? ? ? self.value = value > ? ? ? ? self.doc = str > > t = T(44, 'Goodbye') > > print 't = ', t > print 't.doc = ', t.doc > > It works ok with S but it fails when I try to instantiate T with a syntax > error. Why? > > Also, I don't understand why S works. If I change the name of value and > use something else, the print of s still works by printing the integer > value out. How does it know what value to use? Also, in S.__init__, should > I be calling super(S, self).__init__(value) or is there a difference? I suggest you read http://www.python.org/download/releases/2.2.3/descrintro/ Briefly, S(44) calls first S.__new__(S, 44) which does not exist, so falls back to int.__new__(S, 44) which creates the new object s which is 44 as an integer. Then *only*, s.__init__(44) is called and your code is executed. Try changing self.value=value to self.value='SPAM', you will see that 'print s' still returns 44. As for T(44, 'Goodbye'), the same happens. First T.__new__ does not exist, so int.__new__(T, 44, 'Goodbye') is executed and this is where the error comes from (shouldn't it be a TypeError?) as this means "create the integer whose representation in base 'Goodbye' is 44". As for calling int.__init__, there is no point: integers don't have an __init__() since they are immutable. > And just for fun: > > class R(int): > ? ? ?def __init__(self, value, doc): > ? ? ? ? ?super(R, self).__init__(value) > ? ? ? ? ?self.doc = doc > > r = R(66,'GGG') > Traceback (most recent call last): > ? ?File "", line 1, in ? > TypeError: an integer is required > > Now it's no longer a syntax error but I don't see why it's different? Same as above, though I don't understand why you get a SyntaxError for T and a TypeError for R. AFAICT both shoult give a TypeError. -- Arnaud From eefacm at gmail.com Thu Jan 3 16:15:15 2008 From: eefacm at gmail.com (eefacm at gmail.com) Date: Thu, 3 Jan 2008 13:15:15 -0800 (PST) Subject: New-style objects are not instances, apparently Message-ID: <3c386519-8de3-4e50-8b96-e4c5f3cc8e78@d21g2000prf.googlegroups.com> I have a class that derives from Exception. In Python 2.4, isinstance(MyClass(), types.InstanceType) was True. In 2.5, it's False. Further experimentation showed that derivation from object was the culprit; new-style objects are not considered "instances" in the above sense. I wasn't able to figure out a workaround. Is there one, or is the distinction between traditional classes and built-in types only going to get more and more hazy? From sjmachin at lexicon.net Thu Jan 24 15:44:00 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 24 Jan 2008 12:44:00 -0800 (PST) Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> Message-ID: <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> On Jan 25, 6:18 am, Ira.Ko... at gmail.com wrote: > Hello all, > > I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like > to sort based on first two characters. If you mean 1.6 American billion i.e. 1.6 * 1000 ** 3 lines, and 2 * 1024 ** 3 bytes of data, that's 1.34 bytes per line. If you mean other definitions of "billion" and/or "GB", the result is even fewer bytes per line. What is a "Unicode text file"? How is it encoded: utf8, utf16, utf16le, utf16be, ??? If you don't know, do this: print repr(open('the_file', 'rb').read(100)) and show us the results. What does "based on [the] first two characters" mean? Do you mean raw order based on the ordinal of each character i.e. no fancy language- specific collating sequence? Do the first two characters always belong to the ASCII subset? You'd like to sort a large file? Why? Sorting a file is just a means to an end, and often another means is more appropriate. What are you going to do with it after it's sorted? > I'd greatly appreciate if someone can post sample code that can help > me do this. I'm sure you would. However it would benefit you even more if instead of sitting on the beach next to the big arrow pointing to the drop zone, you were to read the manual and work out how to do it yourself. Here's a start: http://docs.python.org/lib/typesseq-mutable.html > Also, any ideas on approximately how long is the sort process going to > take (XP, Dual Core 2.0GHz w/2GB RAM). If you really have a 2GB file and only 2GB of RAM, I suggest that you don't hold your breath. Instead of writing Python code, you are probably better off doing an external sort. You might consider looking for a Windows port of a Unicode-capable Unix sort utility. Google "GnuWin32" and see if their sort does what you want. From jeba.ride at gmail.com Wed Jan 16 02:47:10 2008 From: jeba.ride at gmail.com (Clement) Date: Tue, 15 Jan 2008 23:47:10 -0800 (PST) Subject: Memory problem with threading References: <55f016fb-42f9-47d6-903a-a068f846b795@e10g2000prf.googlegroups.com> Message-ID: On Jan 16, 5:24 am, "rewo... at gmail.com" wrote: > Hi! > > I made a string parser program, it has a main function and a working > thread class. When it is running in 24h non-stop, the memory run out. > I dont Know why. Do anybody know somekind of debugger that can i see > what is eating the memory? Maybe there is a list or value or > dictionary that is growing continually but i dont know which one. > Maybe there is a program for that kind of debugging, what can > monitoring the memory and values size in the memory. Or it is a sience > fiction :) > > p.s.: sorry for my english > Rew Hi I got the same problem when i did my crawler..... the simple soloution what i did is... created one therad at the start up time of my program.. it will run all the time of the life of the program... it's duty is frequently calling gc.college() function in garbage collector package of python http://arctrix.com/nas/python/gc/ i used it as temporary solution.... if any other way please share........... ...... Thanking you... Clement http://www.squzer.com/ From bignose+hates-spam at benfinney.id.au Tue Jan 29 17:14:30 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jan 2008 09:14:30 +1100 Subject: Removing Pubic Hair Methods References: Message-ID: <878x28e0u1.fsf@benfinney.id.au> xikom01 at yahoo.com.tw writes: > Shaving is the most common removing pubic hair method. However, it > is not the only one. Clearly you haven't done the Python tutorial, otherwise you'd realise there's no distinction between pubic methods and privy methods. Also, there's one, and preferably only one, obvious way to do it:: >>> del foo.hair -- \ "A man's only as old as the woman he feels." -- Groucho Marx | `\ | _o__) | Ben Finney From remco at gerlich.nl Mon Jan 28 12:22:24 2008 From: remco at gerlich.nl (Remco Gerlich) Date: Mon, 28 Jan 2008 18:22:24 +0100 Subject: validate string is valid maths In-Reply-To: References: Message-ID: <7ae3ca10801280922r7463a725ye52b872a45af6aff@mail.gmail.com> Hi, It seems that for every group of 2 or more +-/* signs, one of the following holds: - The group starts with '-', everything after it should be dropped, otherwise - The second character is '-', everything after it should be dropped, otherwise - Drop everything after the first. That should turn into one short regex. Did I miss something? Remco On Jan 28, 2008 4:10 PM, wrote: > Hi pythoners. > > I am generating strings of length n, randomly from the symbols > > +-/*0123456789 > > What would be the 'sensible' way of transforming the string, for example > changing '3++++++8' into 3+8 > or '3++--*-9' into '3+-9' such that eval(string) will always return a > number? > > in cases where multiple symbols conflict in meaning (as '3++--*-9' the > earliest valid symbols in the sequence should be preserved > > so for example, > > '3++*/-9' = 3+-9 > '45--/**/+7' = 45-+7 > '55/-**+-6**' = 55/-6 > > ...that is, unless there is a canonical method for doing this that does > something else instead.. > > > this sounds like homework. It's not. I like making problems up and it's a > slow work day. So, as an aside, there is no real reason I want to do this, > nor other problem to solve, nor other background to what I'm trying to > achieve ;) other than twiddling with python. > > 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. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Fri Jan 4 04:17:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 10:17:01 +0100 Subject: PyObject_CallObject code dump after calling 4 times In-Reply-To: <0d763f52-6845-4822-807a-130c9c46c327@i12g2000prf.googlegroups.com> References: <938001bf-33d2-4071-9b08-f7bb041505b1@s19g2000prg.googlegroups.com> <0d763f52-6845-4822-807a-130c9c46c327@i12g2000prf.googlegroups.com> Message-ID: grbgooglefan wrote: > char* plevel = NULL; > if(NULL != (plevel = PyString_AsString(pResult))){ > ret = 0; > strncpy(szEvalResult,plevel,strlen(plevel)); strncpy doesn't check the size of the target buffer, so that's no different from just doing strcpy(szEvalResult, plevel). or in other words, it's still trivial to crash your program simply by returning too much data from the Python code. From arnodel at googlemail.com Wed Jan 23 16:23:46 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 13:23:46 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> <457550e3-f5e1-4fad-b553-c3e5e400dbb1@u10g2000prn.googlegroups.com> Message-ID: On Jan 23, 8:40?pm, Terry Jones wrote: > >>>>> "Arnaud" == Arnaud Delobelle writes: > > Arnaud> FWIW, I have a clear idea of what the space of solutions is, and > Arnaud> which solutions I consider to be equivalent. ?I'll explain it > Arnaud> below. ?I'm not saying it's the right model, but it's the one > Arnaud> within which I'm thinking. > > OK. This reinforces why I'm not going to work on it anymore, the solution > is subjective (once you start pruning). > > Arnaud> I think it's best to forbid negatives. ?Solutions always be written > Arnaud> without any negative intermediate answer. ?E.g. 1-7*6*(3-9) can be > Arnaud> done as 1+7*6*(9-3). > > That's a good optimization, and I think it's easy to prove that it's > correct supposing the target is positive and the inputs are all positive. > > If you consider the intermediate results in a solution, then if you ever go > negative it's because of an operation X (must be a sub or a div) and when > you next become positive it's due to an operation Y (must be add or > mul). So you can "reflect" that part of the computation by doing the > opposite operations for that formerly sub-zero intermediate sequence. > > Arnaud> I don't consider these to be equivalent, because their equivalence > Arnaud> depends on understanding the meaning of subtraction and addition. > > Ha - you can't have it both ways Arnaud! You don't want the computation to > go negative... doesn't that (and my "proof") have something to do with the > inverse nature of add and sub? :-) I think I can have it both ways, here's why: the "big then small" and "no negatives" rules are applied indiscriminately by the algorithm: it doesn't need to know about the history of operations in order to make a decision depending on their nature. OTOH, identifying (a + b) - c and a + (b - c) for example, requires inspection of the stack/tree/ calculation history. It is an *informed* decision made by the algorithm > Arnaud> (I've also applied the 'big then small' rule explained below) > > And now you're taking advantage of your knowledge of > and < ... Again, *I* have the knowledge, the algorithm does it indiscriminately... [...] > Arnaud> To be perfectly honest (and expose my approach a little to your > Arnaud> argument) I added a three additional rules: > > Arnaud> * Don't allow x - x > Arnaud> * Don't allow x * 1 > Arnaud> * Don't allow x / 1 > > Yes, I do these too, including not allowing a zero intermediate (which is a > useless calculation that simply could not have been done - see, I have deep > knowledge of zero!). Note that disallowing 0 and disallowing x - x are equivalent, as the only way to get your first 0 is by doing x - x. Thanks for the discussion, it's made me realise more clearly what I was doing. -- Arnaud From cokofreedom at gmail.com Wed Jan 30 04:06:38 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 30 Jan 2008 01:06:38 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <7xabmnbxh7.fsf@ruckus.brouhaha.com> <98e4151d-2253-4872-aa79-b391ddb7af77@k39g2000hsf.googlegroups.com> Message-ID: On Jan 30, 9:50 am, Santiago Romero wrote: > On 30 ene, 08:09, Paul Rubin wrote: > > > Santiago Romero writes: > > > > > >>> li = [1,2,3,4,5] > > > > >>> filter(lambda x: x != 3, li) > > > > [1, 2, 4, 5] > > > > I haven't measured it, but this should be the fast solution in all > > > the thread ... > > > li.remove(3) is probably faster. > > But that only removes the first ocurrence of item==3. > > In a = [1, 2, 3, 3, 3, 4, 3, 3, 2, 3], the filter solution will > efectively remove all items with value == 3 while li.remove(3) will > only remove the first ocurrence. > > Bye! from itertools import ifilter print [x for x in ifilter(lambda x: x != 99, li)] Will this one be faster or slower than filter? From lists at cheimes.de Tue Jan 22 10:06:47 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 22 Jan 2008 16:06:47 +0100 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <4795F398.2050306@strank.info> References: <5vm8t3F1m1797U1@mid.uni-berlin.de> <4795F398.2050306@strank.info> Message-ID: Stefan Rank wrote: > on 22.01.2008 14:20 Diez B. Roggisch said the following: >> def isgenerator(v): >> def _g(): yield >> return type(v) == type(_g()) >> >> But I wonder why there is no such method already available? > > > This tests for generator objects, and you could also use:: > > return type(v) is types.GeneratorType > > I think that this is pretty direct already. > > I also need to test for generator functions from time to time for which > I use:: > > def _isaGeneratorFunction(func): > '''Check the bitmask of `func` for the magic generator flag.''' > return bool(func.func_code.co_flags & CO_GENERATOR) Can you please write a function for the inspect module + docs + a small unit tests and submit a patch? The inspect module is missing the isgenerator function. Christian From MartinRinehart at gmail.com Sat Jan 5 05:31:15 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Sat, 5 Jan 2008 02:31:15 -0800 (PST) Subject: Basic inheritance question Message-ID: Working on parser for my language, I see that all classes (Token, Production, Statement, ...) have one thing in common. They all maintain start and stop positions in the source text. So it seems logical to have them all inherit from a base class that defines those, but this doesn't work: import tok class code: def __init__( self, start, stop ): startLoc = start stopLoc = stop class token(code): pass x = token( tok.Loc(0, 0), tok.Loc(3, 4) ) print x.startLoc.repr(), x.stopLoc.repr() AttributeError: token instance has no attribute 'startLoc' 1) Is my design thinking good, or hopelessly unPythonic? 2) If it's good, how do you access base class data attributes? (The doc is rich in method access info, impoverished when it comes to other attributes.) From paddy3118 at googlemail.com Wed Jan 9 16:29:10 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 13:29:10 -0800 (PST) Subject: alternating string replace: Extended input (Long). References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: On Jan 9, 8:56 pm, Fredrik Lundh wrote: > Donald 'Paddy' McCarthy wrote: > > I created some more test strings and ran posters solutions against them. > > the point being? > > To see how they act against 'corner cases' and an exercise for me in trying to create corner cases. (I'm in to functional testing at the mo'). - Paddy. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 18 04:16:26 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 18 Jan 2008 10:16:26 +0100 Subject: Loop in a loop? In-Reply-To: References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <47906e35$0$16946$426a74cc@news.free.fr> Roel Schroeven a ?crit : > Sacred Heart schreef: >> On Jan 17, 1:35 pm, cokofree... at gmail.com wrote: >>> for i in zip(array1, array2): >>> print i >>> >>> Although I take it you meant four d, the issue with this method is >>> that once you hit the end of one array the rest of the other one is >>> ignored. >> >> Yes, small typo there. >> >> Okey, so if my array1 is has 4 elements, and array2 has 6, it won't >> loop trough the last 2 in array2? How do I make it do that? > > One solution is with map() instead if zip(). map() with None as the > first argument works much like zip(), but it keeps looping if one of the > lists is exhausted. When that happens, it uses None for those values: Yek ! Should have read the doc more carefully. Height years of Python, and I didn't knew this one :( From travis.jensen at gmail.com Thu Jan 24 18:26:31 2008 From: travis.jensen at gmail.com (Travis Jensen) Date: Thu, 24 Jan 2008 16:26:31 -0700 Subject: OS X, Python, and Emacs Message-ID: Honestly, I don't know if this is a python problem or an emacs problem; I'm leaning towards something to do with python, but I'm hoping somebody here might know the answer. The problem is that whenever I start python inside of emacs (both emacs.app and aquamacs), anything I type gets echoed back to the buffer before being processed. For example: >>> 'a' 'a' 'a' >>> for x in xrange(5): for x in xrange(5): ... print x print x ... 0 1 2 3 4 Any ideas on what is causing this or how I can fix it? Thanks. tj Travis Jensen travis.jensen at gmail.com http://softwaremaven.innerbrane.com/ You should read my blog; it is more interesting than my signature. -------------- next part -------------- An HTML attachment was scrubbed... URL: From MrJean1 at gmail.com Fri Jan 11 12:53:12 2008 From: MrJean1 at gmail.com (MrJean1) Date: Fri, 11 Jan 2008 09:53:12 -0800 (PST) Subject: Detecting OS platform in Python References: Message-ID: <0524f8e0-e0b0-43a4-84c0-aa7d92f173e7@v46g2000hsv.googlegroups.com> On Jan 10, 7:53?pm, Benjamin wrote: > On Jan 10, 8:37 pm, Devraj wrote:> Hi everyone, > > > My Python program needs reliably detect which Operating System its > > being run on, infact it even needs to know which distribution of say > > Linux its running on. The reason being its a GTK application that > > needs to adapt itself to be a Hildon application if run on devices > > like the N800. > > platform.dist might help you. It's not very complete at all, though. > (This is supposed to improve in 2.6, though) > Better yet, first use sys.platform. If that is 'linux2', then use platform.dist(). /Jean Brouwers > > I have been searching around for an answer to this, and did find some > > messages on a lists that suggested the use of sys.platform to detect > > platform, with counter posts saying that it didn't work on Windows > > etc. > > > Can anyone please shed some light on this? > > > Thanks a lot. From mccredie at gmail.com Wed Jan 16 16:25:12 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 16 Jan 2008 13:25:12 -0800 (PST) Subject: Creating unique combinations from lists References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> Message-ID: On Jan 16, 11:15 am, breal wrote: > I have three lists... for instance > > a = ['big', 'small', 'medium']; > b = ['old', 'new']; > c = ['blue', 'green']; > > I want to take those and end up with all of the combinations they > create like the following lists > ['big', 'old', 'blue'] > ['small', 'old', 'blue'] > ['medium', 'old', 'blue'] > ['big', 'old', 'green'] > ['small', 'old', 'green'] > ['medium', 'small', 'green'] > ['big', 'new', 'blue'] > ['small', 'new', 'blue'] > ['medium', 'new', 'blue'] > ['big', 'new', 'green'] > ['small', 'new', 'green'] > ['medium', 'new', 'green' ] > > I could do nested for ... in loops, but was looking for a Pythonic way > to do this. Ideas? I would probably just create a generator: def permute(a,b,c): for x in a: for y in b: for z in c: yield [x,y,z] all_combos = list(permute( ['big', 'small', 'medium'], ['old', 'new'], ['blue', 'green'])) print all_combos I'm using nested for loops, but I sure find it easy to read that way. Though, using list comprehension does pretty much the same thing. It appears that Tim Chase has posted a more generic version of the above. Matt From wmcbrine at users.sf.net Tue Jan 29 11:34:17 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Tue, 29 Jan 2008 16:34:17 GMT Subject: Removal of element from list while traversing causes the next element to be skipped Message-ID: Look at this -- from Python 2.5.1: >>> a = [1, 2, 3, 4, 5] >>> for x in a: ... if x == 3: ... a.remove(x) ... print x ... 1 2 3 5 >>> a [1, 2, 4, 5] >>> Sure, the resulting list is correct. But 4 is never printed during the loop! What I was really trying to do was this: apps = [name for name in os.listdir(ROOT) if os.path.isdir(os.path.join(ROOT, name))] apptitles = {} for name in apps: try: app = __import__(name) except: apps.remove(name) else: apptitles[name] = getattr(app, 'TITLE', name.title()) which worked fine, until I actually had a directory with no module in it. Then that directory was correctly removed from the list, but the _next_ one was skipped, so its title was never assigned, which caused problems later in the program. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From bruno.desthuilliers at gmail.com Thu Jan 31 18:28:31 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 31 Jan 2008 15:28:31 -0800 (PST) Subject: python modules collection References: <47A129B1.6000301@block.duxieweb.com> Message-ID: <39945886-aaf9-4255-a636-c38198158bba@h11g2000prf.googlegroups.com> On 31 jan, 02:57, "Guilherme Polo" wrote: > 2008/1/30, J. Peng : > > > Hello, > > > Is there a site for python,which collects most kinds of python modules? > > like CPAN for Perl. > > Sometime I want to use a module,like the time/date modules,don't know > > where I should search from. > > Sorry if I have repeated this question on the list. > > Thanks! > > There ishttp://pypi.python.org/pypi > > And the module index for the standard lib, of course: http://docs.python.org/modindex.html From finite.automaton at gmail.com Fri Jan 11 12:14:59 2008 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: Fri, 11 Jan 2008 09:14:59 -0800 (PST) Subject: Help with Windows build of Yapgvb Python extension References: <4bfd40d3-61f5-4c88-b6b2-c8ebef1b13dc@m34g2000hsf.googlegroups.com> Message-ID: <161c71e8-274c-4e96-a14f-b790f69809e6@q39g2000hsf.googlegroups.com> On Jan 11, 9:44 am, Mike wrote: > On Jan 11, 8:41 am, Lonnie Princehouse > wrote: > > > > > I'm the author of Yapgvb, a Python binding for Graphviz. Yapgvb > > enjoys modest success, but for some time it has been in dire need of a > > Python 2.5 build for Windows. I'm posting this message in the hopes of > > finding someone who is interested in making this build. > > > This is a relatively quick task for someone who is comfortable with > > building C extensions and has an operational Windows build environment > > for Python 2.5 (which I don't). Alternately, it's a great way to > > learn about these things, and to get involved with a small open source > > project. > > > Technologies used: > > graphviz > > distutils > > boost.python > > boost.graph > > > See:http://yapgvb.sourceforge.net > > What do you need exactly? One of those executables created using bdist > or are you going for the msi? > > I usually attempt to create these things doing > > python setup.py bdist_wininst > > ...for executable installers. > > If you can provide a valid setup.py, I can probably create the exe/ > msi. > > Mike Yes, a bdist_wininst installer is what I had in mind. MSI would be fine, too --- whichever is easier. If anyone wants to have a look, there's a README file that details what I did to build yapgvb for Python 2.4. The source is available from anonymous subversion: svn co https://yapgvb.svn.sourceforge.net/svnroot/yapgvb yapgvb and is also web-browseable, http://yapgvb.svn.sourceforge.net/viewvc/yapgvb/ From george.sakkis at gmail.com Fri Jan 11 08:27:15 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 05:27:15 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> <478732db$0$19250$426a74cc@news.free.fr> Message-ID: <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> On Jan 11, 4:12 am, Bruno Desthuilliers wrote: > George Sakkis a ?crit : > > > On Jan 10, 3:37 am, Bruno Desthuilliers wrote: > > >> I fail to see how the existence of JIT compilers in some Java VM changes > >> anything to the fact that both Java (by language specification) and > >> CPython use the byte-code/VM scheme. > > > Because these "some Java VMs" with JIT compilers are the de facto > > standard used by millions; > > Repeating an argument doesn't make it more true nor more relevant. Once > again, this doesn't change anything to the fact exposed above. > > > the spec is pretty much irrelevant > > I mentionned this because this kind of choice is usually not part of the > language spec but of a specific implementation. Java is AFAIK the only > language where this implementation stuff is part of the spec. > > > (unless > > you're a compiler writer or language theorist). > > I thought it was quite clear and obvious that I was talking about points > relating to these fields. No it wasn't, and besides the OP is most likely interested in these as a simple user so the distinction between a spec and a de facto standard implementation (such as JDK for Java and CPython for Python) are almost pedantic if not misleading. We're not Lisp (yet ;-)), with five major implementations and a dozen of minor ones. George From list-ener at strank.info Tue Jan 22 08:46:00 2008 From: list-ener at strank.info (Stefan Rank) Date: Tue, 22 Jan 2008 14:46:00 +0100 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <5vm8t3F1m1797U1@mid.uni-berlin.de> References: <5vm8t3F1m1797U1@mid.uni-berlin.de> Message-ID: <4795F398.2050306@strank.info> on 22.01.2008 14:20 Diez B. Roggisch said the following: > > def isgenerator(v): > def _g(): yield > return type(v) == type(_g()) > > But I wonder why there is no such method already available? This tests for generator objects, and you could also use:: return type(v) is types.GeneratorType I think that this is pretty direct already. I also need to test for generator functions from time to time for which I use:: def _isaGeneratorFunction(func): '''Check the bitmask of `func` for the magic generator flag.''' return bool(func.func_code.co_flags & CO_GENERATOR) cheers, stefan From ramashish.lists at gmail.com Thu Jan 3 23:24:07 2008 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: Thu, 3 Jan 2008 20:24:07 -0800 (PST) Subject: Problem reading csv files Message-ID: <1788604d-5fed-435a-a9f3-f7e9f652b5a3@s12g2000prg.googlegroups.com> Hi, I am trying to read a csv file using csv.reader. The file is created using Open Office and saved in Excel format. import csv reader = csv.reader(open('test.xls')) for row in reader: print row It however throws the exception _csv.Error: : line contains NULL byte Any idea whats going wrong here? Thanks in advance, Ram From patrick.waldo at gmail.com Thu Jan 3 09:41:25 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Thu, 3 Jan 2008 06:41:25 -0800 (PST) Subject: Pivot Table/Groupby/Sum question References: <148c3214-77b9-47b0-a680-ffb85dd3efcd@e6g2000prf.googlegroups.com> <9f7b6dcc-216d-46a9-a9d5-022c00ee9d7d@d21g2000prf.googlegroups.com> <1caf93fd-3a50-4c77-87b0-5312cdebd35f@d21g2000prf.googlegroups.com> <63a5a87e-3385-4ef0-80a3-cd1a01eeeac3@w38g2000hsf.googlegroups.com> <276d150b-6b2a-4973-8569-bd8cad6df948@s19g2000prg.googlegroups.com> <018c37d5-67c0-4995-88e3-86f701580c26@e23g2000prf.googlegroups.com> <5d6721cc-1912-4adc-9e47-0afa21c51c89@21g2000hsj.googlegroups.com> <17de023b-8dfd-4478-8271-96e21968d489@s8g2000prg.googlegroups.com> Message-ID: <39fd9ee5-d874-4cea-a7bb-64ab62594332@m34g2000hsf.googlegroups.com> Yes in the sense that the top part will have merged cells so that Horror and Classics don't need to be repeated every time, but the headers aren't the important part. At this point I'm more interested in organizing the data itself and i can worry about putting it into a new excel file later. From stef.mientki at gmail.com Tue Jan 1 13:39:21 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 01 Jan 2008 19:39:21 +0100 Subject: Some specific exec behavior ? Message-ID: <477A88D9.4090708@gmail.com> hello, I find 2 strange behaviors in exec-function, and I can't find anything in the documentation. (Python 2.4.3 Enthought edition) 1. A function definition may not span more than 1 line, e.g. This generates an exception: def _func (x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) while this works correct: def _func (x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) 2. an emtpy line at the end also generates an exception Is this behavior correct ? where should I find information about it ? thanks, Stef Mientki From generalcody at gmail.com Sat Jan 12 14:49:45 2008 From: generalcody at gmail.com (GeneralCody) Date: Sat, 12 Jan 2008 20:49:45 +0100 Subject: Great Python books for the beginner References: Message-ID: <2008011220494516807-generalcody@gmailcom> On 2008-01-12 08:03:42 +0100, Landon said: > Hi, I'm a freshman in college and I'm going to be taking an intro to > programming course next semester which mainly uses Python, so I > thought it might be a good time to pick up Python beyond the scope of > the class as well. The text book for this class is Python for the > Absolute Beginner or something similar to that name. > > I was wondering if anyone had any opinions on what other titles I > could look into since this one seems from a glance at reviews to be > teaching mainly through game programming (a topic I'm not too > interested in) or if this one is a quality book by itself. I would definetly go for Learning Python first, maybe Apress "Python, from novice to Professional" as well... From socyl at 987jk.com.invalid Wed Jan 30 07:36:21 2008 From: socyl at 987jk.com.invalid (kj) Date: Wed, 30 Jan 2008 12:36:21 +0000 (UTC) Subject: Python noob SOS (any [former?] Perlheads out there?) References: <479f7492$0$27193$9b4e6d93@newsspool1.arcor-online.net> Message-ID: In <479f7492$0$27193$9b4e6d93 at newsspool1.arcor-online.net> Wildemar Wildenburger writes: >kj wrote: >> Is there any good reading (to ease the transition) for Perl >> programmers trying to learn Python? >> >www.diveintopython.org Thanks. Not for Perl programmers specifically, but it looks useful all the same. kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From stephen at theboulets.net Tue Jan 8 22:43:01 2008 From: stephen at theboulets.net (Stephen_B) Date: Tue, 8 Jan 2008 19:43:01 -0800 (PST) Subject: Default location of python on OS X Message-ID: <1519661f-97bd-4fdd-b2d5-a46dd9a81c81@e25g2000prg.googlegroups.com> I've installed the latest 2.5 python today from python.org, and I think it ended up in "/Applications/MacPython 2.5". I also have a "/Applications/MacPython 2.4" and a "/Applications/ MacPython-2.4". Can I delete these, or did one of them come with Leopard? I still have a "/Library/Python/2.3" and a "/Library/Python/2.5". Thanks. Stephen From deets at nospam.web.de Thu Jan 3 08:05:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 14:05:20 +0100 Subject: Installing pcaplib References: Message-ID: <5u44sgF1gldn9U1@mid.uni-berlin.de> ashish wrote: > Hi All, > > I am trying to install "pylibpcap-0.6.1" but i am getting these errors . > > > python ./setup.py install > > . > . > . > . > . > > constants.c:172: (near initialization for `pcapmodule_DLT[52]') > pcap.c: In function `init_pcap': > pcap.c:4246: structure has no member named `value' > pcap.c:4260: warning: passing arg 3 of `PyModule_AddStringConstant' > discards qualifiers from pointer target type > error: command 'gcc' failed with exit status 1 > > Please tell me how to solve this problem.Do i have to install anything > else before installing this library. Seems like a version-conflict. See which structure pcap.c:4246 refers to, and from what include it stems. If it's a 3rd-party-lib, install the proper version. Diez From sgeiger at ncee.net Tue Jan 15 02:14:18 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 15 Jan 2008 01:14:18 -0600 Subject: Is there some Python function that searches "sys.path" for a module? In-Reply-To: <478c5755$0$36354$742ec2ed@news.sonic.net> References: <478c5755$0$36354$742ec2ed@news.sonic.net> Message-ID: <478C5D4A.7090705@ncee.net> If I understand you correctly, you want this: module.__file__ John Nagle wrote: > Python's own loader searches "sys.path" for module names, but is there > some function that makes that search functionality accessible to > Python programs? I need the absolute pathname of a module, with the > search being done exactly the same way "import" does it. The loader for > "egg" files has this functionality, but I'd like to find out if there's > a standard way to do this before looking into that source code. > > Also, it seems that the environment variable "PYTHONPATH" applies to > "import", but not to the starting module named on the Python command > line. Is that correct? Thanks. > > John Nagle > -- 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 http Fri Jan 11 06:50:53 2008 From: http (Paul Rubin) Date: 11 Jan 2008 03:50:53 -0800 Subject: Learning Python via a little word frequency program References: <205c99df-2550-47b0-9c82-020b99ed3122@l1g2000hsa.googlegroups.com> Message-ID: <7x63y0ins2.fsf@ruckus.brouhaha.com> rent writes: > keys = freq.keys() > keys.sort(key = freq.get, reverse = True) > for k in keys: > print "%-10s: %d" % (k, freq[k]) I prefer (untested): def snd((x,y)): return y # I wish this was built-in sorted_freq = sorted(freq.iteritems(), key=snd, reverse=True) for k,f in sorted_freq: print "%-10s: %d" % (k, f) From pavlovevidence at gmail.com Sun Jan 6 12:08:10 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 6 Jan 2008 12:08:10 -0500 Subject: python interfaces References: <96b70141-f872-413a-a433-08b217cecb27@e4g2000hsg.googlegroups.com> Message-ID: On Sat, 05 Jan 2008 23:31:02 -0800, r.grimm wrote: > They force the user of a framework to use it in a defined way. This is the arrogance of the provider thinking that he can anticipate all the needs of the user. Even when interfaces exist, they should be there to guide the user rather than to force the user. A user should be able to refuse to implement the interface, if the user knows that full implmentation is not necessary, or dangerous. Frankly, a lot of interfaces suck. The user is often a lot smarter than the provider, and nearly always knows his needs better. My sympathies in these matters are entirely on the user's side--I know that's very different from the philosophies of languages like C++ and Java. There's a time and a place for interfaces. Your average run-of-the-mill polymorphism is not it. Usually interfaces are more of a burden than a benefit, especially in code that is young and still subject to lots of redesign and refactoring. And ehen interfaces do make sense, such as in a plugin system or a complex framework, the user should be free to ignore the interface at his own risk. Carl Banks From fetchinson at googlemail.com Wed Jan 30 19:55:09 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 30 Jan 2008 16:55:09 -0800 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> Message-ID: > I do not understand why no one has answered the following question: > > Has anybody worked with Gene Expression Programming???? Hmmmmm, maybe because nobody did? Just a thought. It can also be that everyone worked with it but everyone is part of a big conspiracy not to answer any of your emails just to make you act weird. I'm not sure, I'm really not sure. From arnodel at googlemail.com Mon Jan 28 14:19:33 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 28 Jan 2008 11:19:33 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> Message-ID: On Jan 28, 4:08?pm, "Andr?" wrote: [...] > If I may suggest, I would extend this so that autoassign's signature > would be as follows: > > autoassign(all=True, include_only=None, exclude=None) > > Either one of include_only or exclude could be a list of function to > which the automatic assignment would apply (or not). ? I was planning > to write this up and submit it to the cookbook later this evening, but > since the suggestion has been made, someone else can jump on it. ;-) > > Andr? I've modified my little decorator (see Test1, Test2, Test3 for usage). I'll post it later on the cookbook if there seems to be no bugs and noone raises valid point against it:) from functools import wraps from inspect import getargspec, isfunction from itertools import izip, ifilter, starmap def autoassign(*names, **kwargs): if kwargs: exclude, f = set(kwargs['exclude']), None sieve = lambda l:ifilter(lambda nv: nv[0] not in exclude, l) elif len(names) == 1 and isfunction(names[0]): f = names[0] sieve = lambda l:l else: names, f = set(names), None sieve = lambda l: ifilter(lambda nv: nv[0] in names, l) def decorator(f): fargnames, _, _, fdefaults = getargspec(f) # Remove self for fargnames and make sure fdefaults is a tuple fargnames, fdefaults = fargnames[1:], fdefaults or () defaults = list(sieve(izip(reversed(fargnames), reversed(fdefaults)))) @wraps(f) def decorated(self, *args, **kwargs): assigned = dict(sieve(izip(fargnames, args))) assigned.update(sieve(kwargs.iteritems())) # It would be nice to have a builtin to exhaust iterators: for _ in starmap(assigned.setdefault, defaults): pass self.__dict__.update(assigned) return f(self, *args, **kwargs) return decorated return f and decorator(f) or decorator class Test(object): @autoassign('foo', 'bar') def __init__(self, foo, bar=3, baz=6): print 'baz =', baz class Test2(object): @autoassign def __init__(self, foo, bar): pass class Test3(object): @autoassign(exclude=('foo', 'bar')) def __init__(self, foo, bar, baz=5, **kwargs): pass t = Test(1, 2, 5) u = Test(foo=8) v = Test2(10, 11) w = Test3(100, 101, foobar=102) print t.foo # 1 print t.bar # 2 print u.foo # 8 print u.bar # 3 (default) print v.foo, v.bar # 10 11 print w.baz, w.foobar # 5 102 for obj, attr in ('w', 'foo'), ('w', 'bar'), ('t', 'baz'): try: getattr(globals()[obj], attr) except AttributeError: print '%s.%s raises AttributeError' % (obj, attr) ==== output ==== baz = 5 baz = 6 1 2 8 3 10 11 5 102 w.foo raises AttributeError w.bar raises AttributeError t.baz raises AttributeError -- Arnaud From steven.klass at gmail.com Mon Jan 21 15:03:32 2008 From: steven.klass at gmail.com (rh0dium) Date: Mon, 21 Jan 2008 12:03:32 -0800 (PST) Subject: Building a pretrigger / posttrigger framework class Message-ID: <3b913ec9-aebd-49bf-b938-074df787afd8@q39g2000hsf.googlegroups.com> Hi all, I am thinking about a class which can automatically determine the order which it is run. I would like to implement a super class which has a run() method and a pretrigger() method. The purpose of the pretrigger method is to state what classes need to be run before this class.run() method is executed. So for example: class superclass(object): def run(self): """Method which will get overriden""" def pretrigger(self): """Method which will get overriden and determine the order""" class subclassA(superclass): def run(self): print "I am subclass A" def pretrigger(self): return [subclassB(),] class subclassB(superclass): def run(self): print "I am subclass B" def pretrigger(self): None return [subclassC(), ] class subclassC(superclass): def run(self): print "I am subclass C" def pretrigger(self): None return None Now what I am looking for is some logic which can look at this and draw the following conclusion. - In order to run subclassA, I first need to run subclassB. In order to run subclassB I need to run subclassC. So the order to run this would be subclassC, subclassB, then subclassA. I would also like some information on is this a good approach to using a superclass or not? Any and all comments are welcome. Thanks!! From http Mon Jan 28 01:17:30 2008 From: http (Paul Rubin) Date: 27 Jan 2008 22:17:30 -0800 Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <7xbq76pva9.fsf@ruckus.brouhaha.com> Message-ID: <7x1w82xymd.fsf@ruckus.brouhaha.com> Paddy writes: > Given the complexity of current microprocessors i'm guessing that > their previous testing methods would be too good to just junk in > totality because the FDIV bug was not found. Similarly if they were > not using formal methods then it makes sense to add it too your > arsenal; and unfortunately it takes a mistake like that to allow > different methods to be explored and incorporated. Fair enough. My main issue was against the notion that random testing is the only thing necessary. From fn681 at ncf.ca Sun Jan 27 08:29:56 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sun, 27 Jan 2008 08:29:56 -0500 Subject: how to make format operator % work with unicode as expected In-Reply-To: References: <13po55nc0q0s06@corp.supernews.com> Message-ID: Peter Pei wrote: > You didn't understand my question, but thanks any way. > > Yes, it is true that %s already support unicode, and I did not > contradict that. But it counts the number of bytes instead of > characters, and makes things like %-20s out of alignment. If you don't > understand my assertion, please don't argue back and I am only > interested in answers from those who are qualified. Peter, Rudeness is inappropriate whether the person being attacked is a frequent or infrequent contributer to this list. Colin W From tjreedy at udel.edu Mon Jan 14 22:21:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Jan 2008 22:21:08 -0500 Subject: SimCity GPLed Message-ID: http://weblogs.asp.net/bsimser/archive/2008/01/10/simcity-source-code-released-to-the-wild-let-the-ports-begin.aspx The release appears to include both a C/Tcl/TK version and a C++/Python version of at least part. "The code hopefully serves as a good example of how to use SWIG to integrate C++ classes into Python and Cairo, in a portable cross platform way that works on Linux and Windows." I have not gotten the code yet. From fredrik at pythonware.com Wed Jan 9 15:56:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 21:56:16 +0100 Subject: alternating string replace: Extended input (Long). In-Reply-To: References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: Donald 'Paddy' McCarthy wrote: > I created some more test strings and ran posters solutions against them. the point being? From usenet at nicko.org Fri Jan 25 13:45:02 2008 From: usenet at nicko.org (Nicko) Date: Fri, 25 Jan 2008 10:45:02 -0800 (PST) Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> Message-ID: <690cb460-fa8a-49a1-a6fa-69cdf480a918@i3g2000hsf.googlegroups.com> On Jan 24, 9:26 pm, Ira.Ko... at gmail.com wrote: > > If you really have a 2GB file and only 2GB of RAM, I suggest that you don't hold your breath. > > I am limited with resources. Unfortunately. As long as you have at least as much disc space spare as you need to hold a copy of the file then this is not too hard. Split the file into chunks that are small enough to fit in memory, sort each chunk and write it to a file and then interleave the chunks. Below is a cheap and cheesy outline of code to do this, from which you can start. For files which are hugely larger than your available memory you can do this recursively but for files which are 10 to 100 times too big the single-pass code below will probably work just fine. The complexity is technically O(n.(log(c)+(n/c))) where n is the size of input and c is the chunk size; once n/c (the number of chunks) exceeds log(c) the cost of merging the chunks will start to dominate, though a recursive version would be slowed by needing a lot more disc access. #!/usr/bin/env python from itertools import islice from tempfile import TemporaryFile import sys # Tweak this number to fill your memory lines_per_chunk = 100000 chunkfiles = [] mergechunks = [] while True: chunk = list(islice(sys.stdin, lines_per_chunk)) if not chunk: break chunk.sort() f = TemporaryFile() f.writelines(chunk) f.seek(0) mergechunks.append((chunk[0], len(chunkfiles))) chunkfiles.append(f) while mergechunks: # The next line is order O(n) in the number of chunks (line, fileindex) = min(mergechunks) mergechunks.remove((line, fileindex)) sys.stdout.write(line) nextline = chunkfiles[fileindex].readline() if nextline == "": chunkfiles[fileindex].close() else: mergechunks.append((nextline, fileindex)) From workitharder at gmail.com Fri Jan 4 11:51:45 2008 From: workitharder at gmail.com (bukzor) Date: Fri, 4 Jan 2008 08:51:45 -0800 (PST) Subject: how to use bool References: Message-ID: <05c5df8b-15c4-47e6-8c14-72c57a84a0ea@y5g2000hsf.googlegroups.com> On Jan 3, 7:49 am, jimgarde... at gmail.com wrote: > hi, i have some code where i set a bool type variable and if the value > is false i would like to return from the method with an error msg.. > being a beginner I wd like some help here > > class myclass: > ......... > def mymethod(self): > success=True > msg="all validation OK" > success=validateSthing() > if(success==False): > msg="sthing failed" > return (success,msg) > > dosomeprocessing() > ..... > success=validateSthingelse() > if(success==False): > msg="sthingelse failed" > return (success,msg) > domoreprocessing() > .... > return(success,msg) > > i would like to know if this way of doing this is OK..I have need of > many kinds of validations in this ..is there a better way of doing > this ? > > thank you class SthingError(Exception): def __init__(self, success, msg): class myclass: ......... def mymethod(self): success=True if not validateSthing(): msg="sthing failed" return (success,msg) dosomeprocessing() ..... if not validateSthingelse(): msg="sthingelse failed" return (success,msg) domoreprocessing() .... return(success,"all validation OK") From arnodel at googlemail.com Mon Jan 21 05:49:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 21 Jan 2008 02:49:19 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: <0cb72e5b-8fb4-453a-bd3e-f53a47c9b6bc@m34g2000hsb.googlegroups.com> On Jan 21, 9:01?am, dg.google.gro... at thesamovar.net wrote: > Hi all, > > It's great how many different sorts of solutions (or almost solutions) > this puzzle has generated. Speedwise, for reference my solution posted > above takes about 40 seconds on my 1.8GHz laptop, and the less elegant > version (on my webpage linked to in the original post) takes about 15 > seconds. It seems to me like surely this problem can be more > efficiently solved than that? I haven't had the time to look at your solution yet. I wanted to have a go without being influenced. > Arnaud: I haven't had time to play with your solution yet - how quick > does it run? I can't run test from here (work) but last night it seemed of the order of a second on my 2GHz MacBook Pro (it was late and I was quite tired so I didn't have the energy to time anything...). It depends if you stop when you hit the first solution or you want to go through all of them. I guess it will run quicker if I don't build a string representation of each calculation. You should run a test on your own machine though to make comparisons meaningful. > My fantasy is that there is a solution that isn't TOO slow where you > can just look at the code and go 'Oh yes, of course that works!' and > understand it immediately. Maybe that's too much to ask even of > Python! ;-) It's a laudable goal. We might get there :) -- Arnaud From hat at se-162.se.wtb.tue.nl Mon Jan 14 03:01:42 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 14 Jan 2008 09:01:42 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: On 2008-01-13, Erik Lind wrote: > I'm new to Python, and OOP. I've read most of Mark Lutz's book and more > online and can write simple modules, but I still don't get when __init__ > needs to be used as opposed to creating a class instance by assignment. For > some strange reason the literature seems to take this for granted. I'd > appreciate any pointers or links that can help clarify this. I think you mean the following: You'd like to do p = Person('me', 'here', 31) and you are wondering why you need the __init__() function in class Person(object): def __init__(self, name, addres, age): self.name = name self.address = address self.age = age right? If so, the answer is that while you think you are doing "Person('me', 'here', 31)", you are in reality executing "Person.__init__(self, 'me', 'here', 31)", where 'self' is refers to a shiny new, empty object created for you. (and the 'self' is obtained by the Person.__new__ function I think, but others here have much better knowledge about this). Sincerely, Albert From cokofreedom at gmail.com Wed Jan 23 03:58:54 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 23 Jan 2008 00:58:54 -0800 (PST) Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? References: Message-ID: <89c55be4-9110-4945-873e-00718994da68@u10g2000prn.googlegroups.com> On Jan 23, 9:45 am, Kristian Domke wrote: > Hello to all > > I am trying to learn python at the moment studying an example program > (cftp.py from the twisted framework, if you want to know) > > There I found a line > > foo = (not f and 1) or 0 > > In this case f may be None or a string. > > If I am not wrong here, one could simply write > > foo = not f > > because if f = None: > > (not f) = true, > (true and 1) = true, > (true or 0) = true > > or if f = 'bar' > > (not f) = false > (false and 1) = false > (false or 0) = false > > So why bothering with the longer version? > > I hope, I made clear, what I want... > > CU > > Kristian f = None foo = (not f and 1) or 0 # this gives you 1 f = None foo = not f # this gives you True From http Mon Jan 14 20:13:44 2008 From: http (Paul Rubin) Date: 14 Jan 2008 17:13:44 -0800 Subject: Dynamical scoping References: <1a3243ef-13f6-40d6-97eb-198b8742ac3d@d4g2000prg.googlegroups.com> Message-ID: <7xabn7hovr.fsf@ruckus.brouhaha.com> George Sakkis writes: > What's the best way to simulate dynamically scoped variables ala Lisp ? Ugh.... check the docs for the python 2.5 "with" statement, which gives you sort of a programmable unwind-protect (more powerful than try/except). You'd have an environment dictionary and use the "with" statement to maintain a stack of shallow-binding cells like in an old-time lisp system, automatically unwinding when the "with" suite finishes. The whole concept sounds hopelessly crufty--I think nobody even does it that way in Lisp any more, you're better off passing an environment around explicitly. If there were a lot of variables, this could be a good application for functional maps, which I've been wanting to implemetn for python. From dikkie at nospam.org Tue Jan 1 11:48:44 2008 From: dikkie at nospam.org (Dikkie Dik) Date: Tue, 01 Jan 2008 17:48:44 +0100 Subject: pexpect ssh login and ls | grep In-Reply-To: <3eb81375-3e4a-4e0f-a4e7-bbb1d6cd0f8c@s19g2000prg.googlegroups.com> References: <3eb81375-3e4a-4e0f-a4e7-bbb1d6cd0f8c@s19g2000prg.googlegroups.com> Message-ID: <477a6eec$0$17448$bf4948fe@news.tele2.nl> > shell_cmd = 'ls -l | grep mytest.log' > child = pexpect.spawn ('ssh my at mycomp2') I think you can give the ssh command an option to execute a file remotely. That way, one command would be enough. From rdm at rcblue.com Sat Jan 12 21:28:51 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 12 Jan 2008 18:28:51 -0800 Subject: Great Python books for the beginner In-Reply-To: References: Message-ID: <20080113022855.B97011E401B@bag.python.org> At 11:03 PM 1/11/2008, Landon wrote: >Hi, I'm a freshman in college and I'm going to be taking an intro to >programming course next semester which mainly uses Python, so I >thought it might be a good time to pick up Python beyond the scope of >the class as well. The text book for this class is Python for the >Absolute Beginner or something similar to that name. > >I was wondering if anyone had any opinions on what other titles I >could look into since this one seems from a glance at reviews to be >teaching mainly through game programming (a topic I'm not too >interested in) or if this one is a quality book by itself. Yes, it's a quality book, IMO. I hope by now you've gotten over your dislike for online tutorials. Please take a look at these 3: Hands-On Python How to Think Like a (Python) Programmer Alan Gauld's Learning to Program (heavy emphasis on Python) Also, do take advantage of the VERY helpful Tutor mailing list. . Dick Moores >-- >http://mail.python.org/mailman/listinfo/python-list From tarun.kap at gmail.com Wed Jan 16 13:02:15 2008 From: tarun.kap at gmail.com (Tarun Kapoor) Date: Wed, 16 Jan 2008 10:02:15 -0800 (PST) Subject: paramiko References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> Message-ID: <8ceaad4c-c725-4093-a204-ab09162d4629@c23g2000hsa.googlegroups.com> On Jan 16, 11:38 am, "Guilherme Polo" wrote: > 2008/1/16, Tarun Kapoor : > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across > > the connection > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > sock.connect((hostname, port)) > > > t = paramiko.Transport(sock) > > t.start_client() > > key = t.get_remote_server_key() > > > event = threading.Event() > > t.auth_password(username=username, password=password, event=event) > > event.wait() > > > if not t.is_authenticated(): > > print "not authenticated" > > > output: > > not authenticated > > This is a different problem I guess, now you are usin get_remote_server_key. > And why are you creating event after calling start_client without > specifying it ? > > > > > > > On Jan 16, 11:11 am, "Guilherme Polo" wrote: > > > 2008/1/16, Tarun Kapoor : > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > > > > the remote server using an SFTP client I have just to make sure that > > > > username and password are working.. This is the code. > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > > > > connection > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > > sock.connect((hostname, port)) > > > > > t = paramiko.Transport(sock) > > > > > event = threading.Event() > > > > > t.start_client(event) > > > > > event.wait(15) > > > > > if not t.is_active(): > > > > > print 'SSH negotiation failed.' > > > > > sys.exit(1) > > > > > else: > > > > > print "SSH negotiation sucessful" > > > > > event.clear() > > > > > t.auth_password(username=username, password=password,event=event) > > > > > if not t.is_authenticated(): > > > > > print "not authenticated" > > > > > output: > > > > > SSH negotiation successful > > > > > not authenticated > > > > > Tarun > > > > > Waterstone Capital Management > > > > > 2 Carlson Parkway, Suite 260 > > > > > Plymouth, MN 55447 > > > > > Direct: 952-697-4123 > > > > > Cell: 612-205-2587 > > > > Disclaimer This e-mail and any attachments is confidential and intended > > > > solely for the use of the individual(s) to whom it is addressed. Any views > > > > or opinions presented are solely those of the author and do not necessarily > > > > represent those of Waterstone Capital Management, L.P and affiliates. If you > > > > are not the intended recipient, be advised that you have received this > > > > e-mail in error and that any use, dissemination, printing, forwarding or > > > > copying of this email is strictly prohibited. Please contact the sender if > > > > you have received this e-mail in error. You should also be aware that > > > > e-mails are susceptible to interference and you should not assume that the > > > > contents of this e-mail originated from the sender above or that they have > > > > been accurately reproduced in their original form. Waterstone Capital > > > > Management, L.P. and affiliates accepts no responsibility for information, > > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > > > > please verify the authenticity with the sender. > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > You are missing an event.wait() after t.auth_password. > > > Also, why are you passing this magic value "15" to event.wait() ? That > > > parameter is passed to class _Verbose to indicate if debug messages > > > should be displayed or not, so typical values would be 0/1 or > > > False/True. > > > > -- > > > -- Guilherme H. Polo Goncalves > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves ok here is the problem... I don't know what is the correct way... The only demos i have from the paramiko library use a hostkeyfile. since i don't have that i thought i would use the get_remote_key to get the key and then connect it using the code in the demo.. But clearly nothing is working...I should not HAVE to use the key since i should be able to authenticate using the password... Can you please suggest the right way to go ? Thanks for your time ! From mail at timgolden.me.uk Wed Jan 30 07:01:51 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 30 Jan 2008 12:01:51 +0000 Subject: find nearest time in datetime list In-Reply-To: <15180398.post@talk.nabble.com> References: <15180398.post@talk.nabble.com> Message-ID: <47A0672F.3090702@timgolden.me.uk> washakie wrote: > Hello, > > I have a list of datetime objects: DTlist, I have another single datetime > object: dt, ... I need to find the nearest DTlist[i] to the dt .... is > there a simple way to do this? There isn't necessarily an exact match... import datetime dates = [datetime.date (2007, 1, (1+i)*2) for i in range (10)] one_date = datetime.date (2007, 1, 7) print sorted (dates, key=lambda x: abs (x-one_date))[0] TJG From pavloutefkros at gmail.com Mon Jan 28 16:32:45 2008 From: pavloutefkros at gmail.com (pavloutefkros at gmail.com) Date: Mon, 28 Jan 2008 13:32:45 -0800 (PST) Subject: post variable References: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> <87ir1dr8ms.fsf@mulj.homelinux.net> Message-ID: <0f634854-7d7a-4ad8-ba04-38d239ecf850@d70g2000hsb.googlegroups.com> 1. yes i've tried that technique but its annoying, the user can easily stop the redirection and not "elegant". 2. yes i'm aware of that, however what i've mentioned above is just an example, it's actually way more serious. guess i'll have to bare with it. From kar1107 at gmail.com Sat Jan 26 00:43:48 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Fri, 25 Jan 2008 21:43:48 -0800 (PST) Subject: finding child cpu usage of a running child Message-ID: Hi, Wondering if there is a way to measure a child process's cpu usage (sys and user) when the child is still running. I see os.times() working fine in my system (Linux 2.6.9-42.7.ELsmp), but it gives valid data only after the child has exited. When the child is alive, os.times() data for child is zero for both child-sys and child-user cpu. My script (process P1) launches child process P2 (using popen2.Popen3). P2 is a long running process (big compilation). Every minute or so, from P1, I want to measure how much cpu P2 has consumed and based on that I can make some estimate on the completion time of P2 (I have a rough idea how much total cpu P2 needs to complete). I understand it may be too expensive to update this information to the parent process when any of the child/grand-child completes; but wondering if any there is any way to get this info; the expensive operations is on-demand only when the request is made. Thanks, Karthik From steve at REMOVE-THIS-cybersource.com.au Sat Jan 26 06:46:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 26 Jan 2008 11:46:49 -0000 Subject: Hashable References: Message-ID: <13pm7d9sse1aba4@corp.supernews.com> On Sat, 26 Jan 2008 11:10:03 +0000, Simon Pickles wrote: > Hi, > > The term 'hashable'. > > Am I right in thinking it means it can be indexed? like a string or a > dict? No. A hash function is a function which takes an arbitrary object and generates an integer from it. Python has a built-in hash function hash(). It says: help(hash): hash(...) hash(object) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely. Examples: >>> hash(5.5) 1476493312 >>> hash('five') 202874452 >>> hash('fivf') 202874455 >>> hash(None) 54045056 Not all objects are hashable: >>> hash([]) Traceback (most recent call last): File "", line 1, in TypeError: list objects are unhashable Python dictionaries are "hash tables". A hash table is a data structure that let's you look up a key in (virtually) a constant amount of time no matter how many items there are in the table. It does this by calculating the hash of the key, then using that hash to calculate the index in the table where it expects to find the key's data. A good hash table (like Python dicts) is *very* fast. But notice that the object which _uses_ the hash (the dict) is not hashable itself; and that the objects which are hashable (strings, ints, floats, etc.) don't necessarily have an index. Strings do, tuples do, but ints and floats and other objects don't. -- Steven From Russ.Paielli at gmail.com Sun Jan 27 17:19:02 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 14:19:02 -0800 (PST) Subject: optional static typing for Python Message-ID: A while back I came across a tentative proposal from way back in 2000 for optional static typing in Python: http://www.python.org/~guido/static-typing Two motivations were given: -- faster code -- better compile-time error detection I'd like to suggest a third, which could help extend Python into the safety-critical domain: -- facilitates automated source-code analysis There has been much heated debate in the past about whether Python is appropriate for safety-critical software. Some argue that, with thorough testing, Python code can be as reliable as code in any language. Well, maybe. But then, a famous computer scientist once remarked that, "Program testing can be used to show the presence of bugs, but never to show their absence!" --Edsger Dijkstra The next step beyond extensive testing is automated, "static" analysis of source-code ("static" in the sense of analyzing it without actually running it). For example, Spark Ada is a subset of Ada with programming by contract, and in some cases it can formally prove the correctness of a program by static analysis. Then there is Java Pathfinder (http://javapathfinder.sourceforge.net), an "explicit state software model checker." The developers of JPF wanted to use it on a prototype safety-critical application that I wrote in Python, but JPF only works on Java code. We considered somehow using Jython and Jythonc, but neither did the trick. So they ended up having someone manually convert my Python code to Java! (The problem is that my code was still in flux, and the Java and Python versions have now diverged.) In any case, optional static typing in Python would help tremendously here. The hardest part of automated conversion of Python to a statically typed language is the problem of type inference. If the types are explicitly declared, that problem obviously goes away. Explicit typing would also greatly facilitate the development of a "Python Pathfinder," so the conversion would perhaps not even be necessary in the first place. Note also that, while "static" type checking would be ideal, "explicit" typing would be a major step in the right direction and would probably be much easier to implement. That is, provide a syntax to explicitly declare types, then just check them at run time. A relatively simple pre-processor could be implemented to convert the explicit type declarations into "isinstance" checks or some such thing. (A pre-processor command-line argument could be provided to disable the type checks for more efficient production runs if desired.) I noticed that Guido has expressed further interest in static typing three or four years ago on his blog. Does anyone know the current status of this project? Thanks. From bignose+hates-spam at benfinney.id.au Thu Jan 31 08:35:46 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 01 Feb 2008 00:35:46 +1100 Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> <58d1bc12-206f-4cec-ad86-928d16e962f5@i3g2000hsf.googlegroups.com> <8d69e9e8-c892-4c65-ac54-c184ce303a2e@i3g2000hsf.googlegroups.com> Message-ID: <87zlumjex9.fsf@benfinney.id.au> Dustan writes: > On Jan 30, 7:02 pm, FireNWater wrote: > > Thank you for the explanation. . . I think I now have a (foggy) > > understanding of hash tables. It seems to be a way to create order > > (an index) out of disorder (random numbers or characters) behind > > the scenes. . > > The key thing to realize is, quite simply, don't rely on order in a > dictionary. The poster to which you replied is using "order" as contrasted with "disorder". Clearly dictionaries *do* have order that can be relied upon. I think you're using "order" in the colloquial manner; more accurate would be to say "don't rely on *sequence* in a dictionary". -- \ "Our task must be to free ourselves from our prison by widening | `\ our circle of compassion to embrace all humanity and the whole | _o__) of nature in its beauty." ?Albert Einstein | Ben Finney From steven at REMOVE.THIS.cybersource.com.au Mon Jan 21 04:06:44 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 09:06:44 -0000 Subject: When is min(a, b) != min(b, a)? References: Message-ID: On Sun, 20 Jan 2008 21:15:02 -0600, Albert Hopkins wrote: > This issue may have been referred to in > news: but I didn't > entirely understand the explanation. Basically I have this: > > >>> a = float(6) > >>> b = float('nan') > >>> min(a, b) > 6.0 > >>> min(b, a) > nan > >>> max(a, b) > 6.0 > >>> max(b, a) > nan > > Before I did not know what to expect, but I certainly didn't expect > this. So my question is what is the min/max of a number and NaN or is > it not defined (for which I would have expected either an exception to > be raised or NaN returned in each case). According to the IEEE-754 standard the usual trichotomy of "x is less than y, x is equal to y, or x is greater than y" has to be extended to include "x and y are unordered". Comparisons with NaNs are unordered, and so expressions like "x < nan" should signal an exception. (However both == and != do not signal exceptions, they return False and True respectively.) Unfortunately, the standard conflicts with Python's requirement that comparisons should always return True or False, so the next "least bad" alternative is to have comparisons with NaN to return False. That is: >>> 5 < float('nan') False >>> 5 >= float('nan') False So BEWARE of assuming that if x < y returns False, y >= x must return True. That does not hold for floats. Aside: Apple's Power PC Numerics math library extended the usual six comparison operators to fourteen. I don't judge whether this was a good idea or not. http://developer.apple.com/documentation/mac/PPCNumerics/PPCNumerics-37.html#MARKER-9-1 Given that NaNs are unordered, the "right" thing for max() and min() to do is raise an exception. But failing that, the next best thing would be for them to ignore any NaNs. Any way you look at it, for min or max to return a nan is a mistake. Possibly even a bug. > As a corrollary would I be able to rely on the above behavior or is it > subject to change (to fix a bug in min/max perhaps :-)? Presently, you can't rely on *any* behaviour of NaNs and INFs in Python, since they all depend on the underlying C library. Even whether or not you can create them is not defined in Python. -- Steven From lizm at rcsltd.co.uk Wed Jan 23 09:41:32 2008 From: lizm at rcsltd.co.uk (LizzyLiz) Date: Wed, 23 Jan 2008 06:41:32 -0800 (PST) Subject: csv to xls using python 2.1.3 Message-ID: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> Hi I need to convert a .csv file to .xls file using python 2.1.3 which means I can't use pyExcelerator! Does anyone know how I can do this? Many thanks LizzyLiz From cesmiga at gmail.com Tue Jan 29 15:23:41 2008 From: cesmiga at gmail.com (epsilon) Date: Tue, 29 Jan 2008 12:23:41 -0800 (PST) Subject: Decision (if, else) routine is not working as intended with CGI module Message-ID: <9dc9f5d3-2392-48d6-8cb4-8b31c1ce4af9@e6g2000prf.googlegroups.com> All: I'm running into trouble figuring this one out. It seems that my decision routine is not working as intended. Does anyone know why my output continues to utilize the "else" portion of the routine. Thank you, Christopher ++++++++++ #!/usr/bin/python import cgi print "Content-type: text/plain\n" tag_form = cgi.FieldStorage(keep_blank_values=True) #if not tag_form.has_key("fse00"): if tag_form["fse00"] == "": fse000 = {"fse00": "0"} tag_form.update(fse000) print "Printing fse000: ", tag_form["fse00"] else: print "Printing fse00: ", tag_form["fse00"] From deets at nospam.web.de Fri Jan 11 11:16:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jan 2008 17:16:13 +0100 Subject: Python Frontend/GUI for C Program In-Reply-To: References: Message-ID: <5upj2dF1fbbb8U1@mid.uni-berlin.de> byte8bits at gmail.com schrieb: > I have a C program that works very well. However, being C it has no > GUI. Input and Output are stdin and stdout... works great from a > terminal. Just wondering, has anyone every written a Python GUI for an > existing C program? Any notes or documentation available? > > I have experience using wxPython from within Python apps and I like it > a lot for its cross-platform capabilities. I was hoping to use > wxPython for this as well. Modules subprocess and pexpect (3rd-party-package) are your friends. Alternatively, if you have the source for the C-app, exposing it's functionality as DLL/SO and using ctypes as means to access it might work as well. Diez From dwblas at gmail.com Wed Jan 23 20:14:35 2008 From: dwblas at gmail.com (dwblas at gmail.com) Date: Wed, 23 Jan 2008 17:14:35 -0800 (PST) Subject: Linux Journal Survey Message-ID: The annual Linux Journal survey is online now for any Linux users who want to vote for Python. http://www.linuxjournal.com/node/1006101 From Matthew_WARREN at bnpparibas.com Thu Jan 31 11:43:38 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Thu, 31 Jan 2008 16:43:38 +0000 Subject: very simple Genetic Algorithm completed Message-ID: 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 sum that evaluates to n using */+-0123456789' it's a really simple GA that would be useful for someone who doesn't quite get GA's to look at. I think it's simple enough to be fairly self explanatory. to see it come up with evolved solutions to n=1000 >>>from quickga import * >>>evolve() I like playing with stuff like this. I'm going to use this little toy to investigate how mutation rates/crossover gene length, pop size etc.. etc.. interact with each other. All completely unscientifically and for my own bemusement. One point, it's a good idea to keep mutationrate around 1000 - 10000 with genome and population sizes of say 50 - 100. Too low and you get no solution as the mutations mix up the genome too much for selection pressure to work. ...as this actually does need to go as quick as it can, and if anyone feels like it, I'd really appreciate picking it over on the list for optimization. I'm not too familiar with Pthon internals, nor programming for speed in general.
from random import randint
from operator import itemgetter


genes=['+','-','*','/','0','1','2','3','4','5','6','7','8','9']
signs=['+','-','*','/']
digits=['1','2','3','4','5','6','7','8','9']

table = {"++": "+", "+-": "-", "+*": "+", "+/": "+",
    "-+": "-", "--": "+", "-*": "-", "-/": "-",
    "*+": "*", "**": "*", "*/": "*",
    "/+": "/", "/*": "/", "//": "/",
         "+0":"+","*0":"*","-0":"-","/0":"/"} # keep out octal literals

def rationalise_signs(s):
        """Takes the genome string and twiddles it so eval() will work as
expected
        """
        prev = ''
        while s != prev:
                prev=s
                for z in ['+','-','*','/']:
                        s=s.replace(z+'0',z)
                for key, value in table.items():
                        s = s.replace(key, value)
        s=s.lstrip('0')
        s=s.strip('+-*/')
        return s



def generate(number,length):
        """Generate the initial population of genome strings
        """
        population=[]
        for i in range(number):
                s=rationalise_signs(''.join([
genes[randint(0,len(genes))-1] for n in range(length) ]))
                population.append(s)
        return population


def floatify(intstring):#So eval() be floating point.
        """kludge to ensure eval() does floating point math
        """
        prev=''
        while intstring != prev:
                prev=intstring
                for sign in signs:
                        for digit in digits:

intstring=intstring.replace(digit+sign,digit+'.0'+sign)
        return intstring

def express(population):
        """Get the 'expression' of the genome.
        """
        expressed_population=[]
        for individual in population:
                s=floatify(individual)
                expressed_population.append((individual,eval(s)))
        return expressed_population

def fitness(expressed_population,fitvalue,tolerance):
        """Test the expressed genome for fitness
        """
        population_fitness=[]
        sumfitness=0
        for expressed_individual in expressed_population:
                individual,expression=expressed_individual
                fitness=abs(fitvalue-expression)
                sumfitness=sumfitness+fitness
                population_fitness.append((individual,expression,fitness))
        avgfitness=sumfitness/len(expressed_population)
        return (population_fitness,avgfitness)



def get_fittest(population_fitness,pct,full=False):
        """Quick n dirty way of selecting - top n% fittest individuals
        """
        population_fitness.sort(key=itemgetter(2))#sort on fitness
        npct=(len(population_fitness)/100.0)*pct
        if not full:
                return [ n[0] for n in population_fitness[0:int(npct)] ]
        else:
                return population_fitness[0:int(npct)]


def mutate(individual,rate):
        """Does what it says on the tin. Mutates per gene
        if rate is 10000 mutatuion rate is 1 in 10000 on avg
        """
        newindividual=''
        for gene in individual:
                if randint(0,rate)==1:
                        newgene=genes[randint(0,14)-1]
                        newindividual=newindividual+newgene
                else:
                        newindividual=newindividual+gene
        return newindividual

def breed_new(individuals,number,mutationrate):#crossover with mutation
        """simple crossover of the two genomes around a point, then mutate
        """
        newpopulation=[]
        num_individuals=len(individuals)
        while len(newpopulation)<=number:
                lady=individuals[randint(0,num_individuals-1)]
                man=individuals[randint(0,num_individuals-1)]
                xpoint=randint(0,100)
                xlady=(len(lady)/100.0)*xpoint
                xman=(len(man)/100.0)*xpoint
                leftxlady=lady[:int(xlady)]
                rightxlady=lady[int(xlady):]
                leftxman=man[:int(xman)]
                rightxman=man[int(xman):]

new1=rationalise_signs(mutate(leftxlady+rightxman,mutationrate))

new2=rationalise_signs(mutate(leftxman+rightxlady,mutationrate))
                newpopulation.append(new1)
                newpopulation.append(new2)
        return newpopulation


def
evolve(popsize=50,genomelength=100,mutationrate=10000,fitcullpct=10,numsolutions=5,target=1000,tolerance=1):
        """Controls the whole process.
        """
        pop=generate(popsize,genomelength)
        fitgens=[]
        generation=1
        while len(fitgens)tolerance:

pop=breed_new(get_fittest(fpop,fitcullpct),popsize,mutationrate)
                        generation=generation+1
                else:
                        print "Pop avg fitness within tolerance"
                        print "********************************"
                        fitgens.append((fpop[0:],generation))
                        pop=generate(popsize,genomelength)
                        generation=1
        outlist=[]
        for fitpop,generation in fitgens:
                bestfitpop=get_fittest(fitpop,20,full=True)
                for fitgeneinfo in bestfitpop:
                        genome,number,avgfit=fitgeneinfo
                        prev=''
                        s=floatify(genome)
                        outlist.append(genome+" in "+str(generation)+"
generations got "+str(number)+" avg fit ="+str(avgfit))
        for line in set(outlist):
                print line

Matt. (Apologies for any 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 paddy3118 at googlemail.com Fri Jan 25 10:30:14 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 25 Jan 2008 07:30:14 -0800 (PST) Subject: Text-based data inspector for Python? References: <6398ab68-da01-408e-902b-0b488310e9b0@e10g2000prf.googlegroups.com> Message-ID: <98d4d552-20d6-42f4-9d50-2c9ca1b3a4d0@e25g2000prg.googlegroups.com> On Jan 25, 1:47 pm, kj wrote: > In <6398ab68-da01-408e-902b-0b488310e... at e10g2000prf.googlegroups.com> Paddy writes: > > >I tend to do the following at the python prompt: > > from pprint import pprint as pp > > Thanks, that's a good one to know, but isn't there a way to automate > it??? > > I looked around, but I couldn't find the name of any *rc-type file > that would hold interpreter customizations. The closest I found > was ~/.pythonrc.py, but that still requires doing "import user" at > every interpreter session. (As annoyances go, this is certainly > a minor one, but with me the psychological effects of such small > annoyances gets magnified in proportion to how unnecessary they > seem.) Plus, I'm not sure that it'd be such a great idea to execute > code intended to customize the interpreter every time that the user > module gets loaded... > > kynn > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. python -h gives me: ... Other environment variables: PYTHONSTARTUP: file executed on interactive startup (no default) ... - Paddy. From gagsl-py2 at yahoo.com.ar Fri Jan 25 18:00:02 2008 From: gagsl-py2 at yahoo.com.ar (gagsl-py2 at yahoo.com.ar) Date: Fri, 25 Jan 2008 20:00:02 -0300 (ART) Subject: paging in python shell In-Reply-To: Message-ID: <857659.95304.qm@web32813.mail.mud.yahoo.com> --- Alex K escribi?: > Thank you for this interesting tip. However I'm not > sure to know how > to use it. It seems pydoc.pager('text') just pages > the text passed in. > How do I actually make the python shell use a > different pager? I'm unsure of what you want. Do you want the print statement, inside the Python interpreter, to page its output? Write a function to page the output the way you like, and assign it to sys.displayhook (see http://docs.python.org/lib/module-sys.html#l2h-5124 ) -- Gabriel Genellina Tarjeta de cr?dito Yahoo! de Banco Supervielle. Solicit? tu nueva Tarjeta de cr?dito. De tu PC directo a tu casa. www.tuprimeratarjeta.com.ar From lists at cheimes.de Sun Jan 20 11:09:30 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 20 Jan 2008 17:09:30 +0100 Subject: Memory errors with imaplib In-Reply-To: <13p6pf5he8am89e@corp.supernews.com> References: <6012daff-0fd3-4835-a9ca-c18d2a2ac53c@v29g2000hsf.googlegroups.com> <13p6pf5he8am89e@corp.supernews.com> Message-ID: Grant Edwards wrote: > The problem and the one-line soulution have been known for over > two years and it's still an open bug? Nobody was interested to provide a patch. I raised the level of the bug. It's going to be fixed soonish. Christian From thermostat at gmail.com Wed Jan 16 13:45:46 2008 From: thermostat at gmail.com (Dan) Date: Wed, 16 Jan 2008 10:45:46 -0800 (PST) Subject: Interesting Thread Gotcha References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> <5v70v9F1kmtinU1@mid.uni-berlin.de> Message-ID: On Jan 16, 1:33 pm, "Diez B. Roggisch" wrote: > Dan schrieb: > > > > > On Jan 16, 11:06 am, "Diez B. Roggisch" wrote: > >> Hendrik van Rooyen wrote: > >>> "Dan" wrote: > >>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) > >>>> Needs to be > >>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) > >>>> Commas are important! > >>>> -Dan > >>> Absolutely! - well spotted! > >>> As the first correct respondent, you win the freedom to spend a week in > >>> Naboomspruit at your own expense. > >>> It would have been nice, however, to have gotten something like: > >>> TypeError - This routine needs a tuple. > >>> instead of the silent in line calling of the routine in question, > >>> while failing actually to start a new thread. > >> You can't prevent the silent inline-calling - otherwise, how would you do > >> this: > > >> def compute_thread_target(): > >> def target(): > >> pass > >> return target > > >> thread.start_new_thread(compute_thread_target()) > > >> Of course start_new_thread could throw an error if it got nothing callable > >> as first argument. No idea why it doesn't. > > >> Diez > > > Of course, in his case, having start_new_thread throw an error > > wouldn't have helped, since he went into an infinite loop while > > evaluating the parameters for start_new_thread. > > > Would it be possible to have pychecker (or some such) warn that there > > is an insufficient parameter count to start_new_thread? I guess that > > would require knowing the type of thread. . . > > What has this to do with the second argument? It's perfectly legal to > have a function as thread-target that takes no arguments at all, so > enforcing a second argument wouldn't be helpful - all it would do is to > force all developers that don't need an argument tuple to pass the empty > tuple. So there was no insufficient argument count. > > And none of these would solve the underlying problem that in python > expressions are evaluated eagerly. Changing that would mean that you end > up with a totally new language. > > the only thing that could help to a certain extend would be static > types. Which we don't want here :) > > Diez It doesn't seem to be legal in my version of python (or the doc): >>> import thread >>> def bat(): print "hello" >>> thread.start_new_thread(bat) Traceback (most recent call last): File "", line 1, in thread.start_new_thread(bat) TypeError: start_new_thread expected at least 2 arguments, got 1 >>> thread.start_new_thread(bat, ()) 2256hello >>> -Dan From lists at cheimes.de Fri Jan 11 15:55:24 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 11 Jan 2008 21:55:24 +0100 Subject: virtualpython / workingenv / virtualenv ... shouldn't this be part of python In-Reply-To: References: <4787981c$0$90268$14726298@news.sunsite.dk> Message-ID: Goldfish wrote: > What about security holes, like a malicious version of socket getting > downloaded into a user's directory, and overriding the default, safe > version? Don't forget that in your PEP. A malicious piece of software has already hundreds of way to overwrite modules. It could add a python executable to ~/bin and add ~/bin to PATH. it could modify .bashrc and add PYTHONPATH. Or it could drop some site.py and sitecustomize.py files in various directories. If you allow malicious or potential harmful software to write in your home directory you are lost. The new feature doesn't add new attack vectors. Christian From hrochonwo at googlemail.com Tue Jan 22 13:38:29 2008 From: hrochonwo at googlemail.com (hrochonwo) Date: Tue, 22 Jan 2008 10:38:29 -0800 (PST) Subject: printing escape character Message-ID: Hi, I want to print string without "decoding" escaped characters to newline etc. like print "a\nb" -> a\nb is there a simple way to do it in python or should i somehow use string.replace(..) function ? thanks for any reply hrocho From jyoung79 at kc.rr.com Wed Jan 2 09:23:07 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Wed, 2 Jan 2008 8:23:07 -0600 Subject: os.tmpfile() Message-ID: <12129859.93841199283787583.JavaMail.root@hrndva-web22-z01> > It's a file. You read strings from it and write strings to it. It > isn't a string itself. Given that what you're trying to do doesn't make > any sense, it's hard to know where to begin to identify what's confusing > you. > -- > Erik Max Francis Erik, I am going to be displaying sections of text in the Terminal Window on OS X. I wanted to format the text in a specific way and thought it might be quicker to output all the text to a temporary file that I could quickly read sections from instead of storing in memory. Not sure if this is the most efficient way to do this or not but thought at least it'd be a good way to learn something new in Python. I was assuming tmpfile() would automatically create some sort of temporary file that would automatically delete itself when the code was finished. -- > Try this: > >>> import os > >>> c = os.tmpfile() > >>> c.write('dude') > >>> c.seek(0) > >>> c.read() > 'dude' redawgts, thank you very much for the example! I appreciate you showing me how this works! -- > Please don't use os.tmpfile(). It's not safe and exists only for legacy > reasons. The tempfile module contains methods to create safe temporary > files and directories. > Christian Thanks Christian for this info! I'll look into using the tempfile module instead. Thank you all for sharing your knowledge of Python... this is extremely helpful to me! Jay From guptaabhishek1983 at gmail.com Fri Jan 4 10:35:39 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Fri, 4 Jan 2008 07:35:39 -0800 (PST) Subject: problem in importing .pyd Message-ID: hello group , I have build a python c extension. Using python 2.5 , VS.Net 2005 on Win server 2003. But when i am trying to imort this .pyd file into python interperter or my project source code . Code compilation as well as interpreter fails. Resulting in c/c++ runtime error "R6034". The description says " An application attempted to load a c runtime library without using manifest" What should i do to resolve this problem. Looking forward to your suggestions. Thank You Abhishek From faber at linuxnj.com Fri Jan 11 18:11:41 2008 From: faber at linuxnj.com (Faber J. Fedor) Date: Fri, 11 Jan 2008 18:11:41 -0500 Subject: Newbie Q: modifying SQL statements In-Reply-To: <20080110225352.2c112555@bhuda.mired.org> References: <20080111013206.GA18259@neptune.faber.nom> <20080110225352.2c112555@bhuda.mired.org> Message-ID: <20080111231141.GA24213@neptune.faber.nom> On 10/01/08 22:53 -0500, Mike Meyer wrote: > Personally, I think it would be more pythonic to not try and use two > different APIs to walk the list of jobs (... One Way To Do it): > > def __call__(self, where=None): > q = "select * from %s" % (self.name,) + ("" if not where else (" where %s" % where)) Does this '("" if not where...' syntax actually work? I couldn't get it to compile and I couldn't find any examples of such syntax (but you can't expect googling for 'if not' to be too successful). I ended up changing that line to: q = "select * from %s" % (self.name,) if where: q += "where %s" %where > for r in self.dbc.iterresults() # I assume it has something like this I don't think it does, if I read http://dustman.net/andy/python/MySQLdb_obsolete/doc/MySQLdb-3.html correctly. -- Regards, Faber Fedor -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From kyosohma at gmail.com Thu Jan 24 11:16:57 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 24 Jan 2008 08:16:57 -0800 (PST) Subject: Connecting to Sql Server from Python References: <56f14ea0-defb-445b-b957-7f379a000add@x69g2000hsx.googlegroups.com> Message-ID: <00bb6a7c-7e92-4ddf-af79-4ed6827f2a6b@s13g2000prd.googlegroups.com> On Jan 24, 9:44 am, bg... at yahoo.com wrote: > Hi, > > I have an sql server from which I'd like to read and write to. The > connection string is as follows - > > "Data Source=localhost\SQLExpress;Initial Catalog=Test;Integrated > Security=True;Pooling=False" > > Other properties as they appear in Visual Studio 2005 include - > > Data Provider: .NET Framework Data Provider for SQL Server > State: Open > Type: Microsoft SQL Server > > So my question is, how might I connect to my Test Catalog and update > data within its tables via perl, > > Thanks, > > Barry. If you want to do this in Perl, then why are you asking on a Python list? In Python, there are many ways to accomplish this task. Take a look at SQLAlchemy, SQLObject, pymssql or the adodb package. http://pymssql.sourceforge.net/ www.sqlalchemy.org http://www.sqlobject.org/ http://phplens.com/lens/adodb/adodb-py-docs.htm Mike From bernhard.merkle at googlemail.com Thu Jan 3 08:42:54 2008 From: bernhard.merkle at googlemail.com (Bernhard Merkle) Date: Thu, 3 Jan 2008 05:42:54 -0800 (PST) Subject: reassign to builtin possible !? References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> Message-ID: On Jan 3, 2:07 pm, "Diez B. Roggisch" wrote: > This hal always been possible. But it's not reassigning, it's shadowing - > which is a totally different beast. Shadowing builtins is bad style, but > lokal to your context. Which can get nasty of course, if you do the above > on e.g. module level. > > But you can't alter the values for True/False globally with this. Are you sure ? what about the following example ? Is this also shadowing ? Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import __builtin__ >>> __builtin__.True = False >>> __builtin__.True False >>> True False Berni From john.deas at gmail.com Fri Jan 25 17:45:01 2008 From: john.deas at gmail.com (John Deas) Date: Fri, 25 Jan 2008 14:45:01 -0800 (PST) Subject: basic output question Message-ID: <45577bb9-d0f2-42bf-adea-2ccf34d053ba@l32g2000hse.googlegroups.com> Hi, I am very new to Python (1 evening...) I need to process a series of files (toto-1.txt toto-2.txt toto-3.txt toto-4.txt), and as such I created a small program to go through the files in a directory. I want to call the script with arguments, like python script.py toto- 1 1 4 my script is as follow : import sys sys.argv header= sys.argv[1] start =eval(sys.argv[2]) step =eval(sys.argv[3]) nbit =eval(sys.argv[4]) for i in range(nbit): filename=header+str(start+i*step)+'.txt' f=open(filename,'r') f.read() f.close() My problem is that f.read() outputs nothing, and should I print filename, I can check that they are well formed, and the files sits in the same directory as my script. Anyone could help me on this ? From arian at sanusi.de Sun Jan 27 06:30:30 2008 From: arian at sanusi.de (Arian Sanusi) Date: Sun, 27 Jan 2008 12:30:30 +0100 Subject: python regex: misbehaviour with "\r" (0x0D) as Newline character in Unicode Mode Message-ID: <479C6B56.5030402@sanusi.de> Hi, concerning to unicode, "\n", "\r "and "\r\n" (0x000A, 0x000D and 0x000D+0x000A) should be threatened as newline character at least this is how i understand it: (http://en.wikipedia.org/wiki/Newline#Unicode) obviously, the re module does not care, and on unix, only threatens \n as newline char: >>> a=re.compile(u"^a",re.U|re.M) >>> a.search(u"bc\ra") >>> a.search(u"bc\na") <_sre.SRE_Match object at 0xb5908fa8> same thing for $: >>> b = re.compile(u"c$",re.U|re.M) >>> b.search(u"bc\r\n") >>> b.search(u"abc") <_sre.SRE_Match object at 0xb5908f70> >>> b.search(u"bc\nde") <_sre.SRE_Match object at 0xb5908fa8> is this a known bug in the re module? i couldn't find any issues in the bug tracker. Or is this just a user fault and you guys can help me? arian p.s.: appears in both python2.4 and 2.5 From gandalf at shopzeus.com Tue Jan 8 06:21:12 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 08 Jan 2008 12:21:12 +0100 Subject: Want a strange XML RPC server Message-ID: <47835CA8.1070009@shopzeus.com> Hi, I would like to have a strage XML RPC server. It should use one main thread for all connections. I have some code like this (using a custom RPC server class): server_address = (LISTEN_HOST, LISTEN_PORT) # (address, port) server = mess.SecureXMLRPCServer.SecureXMLRPCServer( server_address, RequestHandler, KEYFILE,CERTFILE, allow_none=True, logger = servicelog.getLogger('SecureXMLRPCServer',filename=LOGFILENAME), logRequests=False, stop_requested = stop_requested ) rpcserver = RPCServer() # Object containing public RPC methods. server.register_instance(rpcserver) It works perfectly. Now here is the tricky part. I would like to send back events. It is implemented by an RPC callback: #1. client calls server.get_event() #2. server waits until the event happens (or until a given timeout) #3. server returns the event (if any) The clients are running on multiple threads, and the idea is that any client can send an event by calling server.send_event(event). That event will be returned to another client by the server. Since the clients are blocking (waiting for the RPC call to return), events will go from one client to another immediatelly (through the rpc server). This goes through different kinds of proxies, and can be used from different programming languages (Python and PHP clients, in my case...) The problem is that in #2, waiting for the event to happen inside the RPC server's handler method will block all other connections to the RPC server. Preferred solution: The get_event() method should run in a different thread inside the server, and return the event to its xmlrpc client from that thread. However, all other methods should use one main thread. I would like to implement this as a decorator like: class RPCServer(object): """Object containing public RPC methods.""" def method1(self,arg1): ..... def method2(self,arg1): ..... def method3(self,arg1): ..... @nonblocking def get_event1(self): try: # Wait for 10 seconds until an event is available. return self.asinharvester.queued_events1.get(True,10) except Queue.Empty: return None # Indicates that there was no queued event. @nonblocking def get_event2(self): try: # Wait for 10 seconds until an event is available. return self.asinharvester.queued_events2.get(True,10) except Queue.Empty: return None # Indicates that there was no queued event. Is this possible? I have no idea how to write this "nonblocking" decorator. Thanks, Laszlo From grante at visi.com Thu Jan 24 11:56:22 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 24 Jan 2008 16:56:22 -0000 Subject: Beginner Pyserial Question References: <93223c7c-c891-424c-bc4f-00d61592663a@l32g2000hse.googlegroups.com> Message-ID: <13phgpma9fb3cb8@corp.supernews.com> On 2008-01-24, JAMoore84 at gmail.com wrote: > Hi Guys, > > I have a project where I'd like to save GPS data that is streamed to a > Sony Vaio over bluetooth. I can monitor the data stream over Hyper > Terminal, but I'd like to use python to capture it as well. I've > installed Python 2.5, pyserial 2.2 and the appropriate pywin program > (pywin32-210.win32-py2.5.exe). > > My problem comes when I try to open a serial port. After importing > "serial", I issue the following statement: > >>>> GPS = serial.Serial(0) > > Traceback (most recent call last): > File "", line 1, in > GPS = serial.Serial(0) > File "C:\Python25\lib\site-packages\serial\serialutil.py", line 156, > in __init__ > self.open() > File "C:\Python25\lib\site-packages\serial\serialwin32.py", line 55, > in open > raise SerialException("could not open port: %s" % msg) > SerialException: could not open port: (2, 'CreateFile', 'The system > cannot find the file specified.') > > I'm not sure where the source of the problem is. I was > wondering if someone could recognize what might be be. It's Windows... it's not expected to work. ;) My guess is that for whatever reason the 'first' serial port (which is what you're asking for by specifying a 0 when instantiating the Serial class) doesn't actually exist. Serial device names under Windows are broken. Just because you have only one serial port, it doesn't mean that serial port is the first serial port. Try using the actual name of the com port (e.g. 'COM3' or 'COM5') instead of 0. Oh, if you end up having to use a com port higher than COM9, that's broken in Windows as well, and you've got to sprinkle a bunch of backslashes into the device name (I don't remember the exact syntax). -- Grant Edwards grante Yow! ... this must be what at it's like to be a COLLEGE visi.com GRADUATE!! From tjreedy at udel.edu Tue Jan 29 04:26:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jan 2008 04:26:22 -0500 Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: "Roy Smith" wrote in message news:roy-3C105C.23015128012008 at 70-1-84-166.area1.spcsdns.net... | But, surely Python has plenty of "implementation defined" aspects. | Especially in the libraries. I personally do not consider the libraries as part of the language (as opposed to the distribution) and was not referring to them. The semantics of the syntax is pretty tightly defined. The main exception is floating point, which is a nuisance. Which is why one implementation aspect thereof is being standardized in the next version. | Especially those parts of the libraries which | are thin layers on top of operating system services (os and socket come to | mind as two highly variable areas). I am sure that sockets are not part of the C89 standard. Hence the high variability. (I don't know about the newer C standard). I would expect that socket.py makes the variability no worse and presume that it masks at least a bit of it. Ditto for some os services. tjr From mwm-keyword-python.b4bdba at mired.org Fri Jan 11 17:24:11 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 17:24:11 -0500 Subject: Import and execfile() In-Reply-To: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> References: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> Message-ID: <20080111172411.7323f1bc@bhuda.mired.org> On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis wrote: > I maintain a few configuration files in Python syntax (mainly nested > dicts of ints and strings) and use execfile() to read them back to > Python. This has been working great; it combines the convenience of > pickle with the readability of Python. So far each configuration is > contained in a single standalone file; different configurations are > completely separate files. You know, I've been there before. It's kinda neat, but not something you really want to put in the hands of most users. You can make the syntax cleaner by using classes to hold the values instead of nested dicts, etc. That way you don't have to quote the names of the values: class Foo: bar = 1 baz = 2 The really slick part was that if the config classes line up with the implementation classes, you can create an instance of the config class for the implementation object, and it can then change those values to change it's behavior without changing the defaults other instances see. > Now I'd like to factor out the commonalities of the different > configurations in a master config and specify only the necessary > modifications and additions in each concrete config file. I tried the > simplest thing that could possibly work: With classes you factor out the commonality by factoring it into a base class that the others inherit from. > ====================== > # some_config.py > > # master_config.py is in the same directory as some_config.py > from master_config import * > > # override non-default options > foo['bar']['baz] = 1 > ... > > ====================== > # trying to set the configuration: > CFG = {} > execfile('path/to/some_config.py', CFG) > > Traceback (most recent call last): > ... > ImportError: No module named master_config > > > I understand why this fails but I'm not sure how to tell execfile() to > set the path accordingly. Any ideas ? Manipulate sys.path yourself? http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From http Sun Jan 20 22:24:32 2008 From: http (Paul Rubin) Date: 20 Jan 2008 19:24:32 -0800 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> Message-ID: <7xir1nsvwv.fsf@ruckus.brouhaha.com> Terry Jones writes: > Here's a solution that doesn't use any copying of lists in for recursion. > It also eliminates a bunch of trivially equivalent solutions. The countdown > function is 37 lines of non-comment code. Sample (RPN) output below. Nice, I realized after I posted my 2nd solution that it was missing some cases and it's good to see confirmation that 239 is reachable. I'll see if I can fix my version. I think the list copying is ok given that the recursion depth always must be fairly small if the generator is to complete in any reasonable amount of time. From fw3 at hotmail.co.jp Thu Jan 3 20:51:46 2008 From: fw3 at hotmail.co.jp (wang frank) Date: Fri, 4 Jan 2008 01:51:46 +0000 Subject: calling system command in window is very slow in python 2.5.1 In-Reply-To: References: <3da337d8-2de0-4fdb-8c38-2f6fcd8348ac@i72g2000hsd.googlegroups.com> Message-ID: Hi, I am running a python script that will change the attribute of a directory and its subdiretory by command: os.system("chmod -R 7777 .") or os.system("attrib -R * /S") Both commands chmod and attrib run quite fast in dos command shell. However, inside python, they are very slow and I have to kill them by Control-C. I do not know why? Can anyone help me to figure it out? Thanks Frank _________________________________________________________________ Hotmail?????????????????????????????????? http://go.windowslive.jp/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Fri Jan 11 12:24:35 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 11 Jan 2008 09:24:35 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: On 9 Jan, 20:11, "dongie.ag... at gmail.com" wrote: > Is there a better way to do color tracking, or is Python just too slow > as an interpreted language to do any effective color tracking? You should code numerically intensive tasks using NumPy arrays. If things are getting slow, chances are you are using Python for loops instead of vectorized NumPy expressions. This is the same trick you would use in e.g. Matlab for boosting performance. If things are running slow despite of having properly vectorized your code, chances are that porting to C will not make a big difference. If you need to resort to C or Fortran, it is easy to interface Python with these languages (e.g. ctypes, Pyrex, Swig, f2py, or weave). Put the offending bottleneck in a lower level language (detect it using the profiler module) and leave everything else in Python. From ggpolo at gmail.com Mon Jan 7 10:15:08 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 13:15:08 -0200 Subject: introspection question In-Reply-To: References: Message-ID: 2008/1/7, Alex K : > Nice thank you. But anyway to make it look pretty? > pprint.pprint(inspect.getmembers(someobject)) > On 07/01/2008, Peter Otten <__peter__ at web.de> wrote: > > Alex K wrote: > > > > > What would be the simplest way of enumerating all methods and members > > > (including inherited) of a given object? Thank you. > > > > inspect.getmembers() > > > > Peter > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From http Fri Jan 11 15:57:39 2008 From: http (Paul Rubin) Date: 11 Jan 2008 12:57:39 -0800 Subject: removeall() in list References: Message-ID: <7xlk6ww058.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > Any ideas for a thread-safe list.removeall( X ): removing all > occurrences of X within list L, when L might be modified concurrently? That way lies madness. Do something sensible instead. Put a lock around the list, or put all mutators for the list into a single thread, or whatever. Don't do what you're describing. From hat at se-162.se.wtb.tue.nl Fri Jan 11 02:47:46 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 11 Jan 2008 08:47:46 +0100 Subject: Help needed References: <0da27dc1-785a-4796-a5a3-6ba1a0290cab@e25g2000prg.googlegroups.com> <66390246-aada-40fe-b8d3-4816771b950f@i3g2000hsf.googlegroups.com> Message-ID: On 2008-01-11, tijo wrote: > Hi mate > i created the socket and the connection with tcp and udp i dont know > how to check the bytes send and time > could you help me with this Have a look at the time or timeit modules. Albert From duncan.booth at invalid.invalid Fri Jan 11 03:27:48 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Jan 2008 08:27:48 GMT Subject: HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? References: <7243c2ac-fa22-4b5b-bd8c-34235123ab69@t1g2000pra.googlegroups.com> Message-ID: abhishek wrote: > Hi group any idea on HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? > > Yes, it indicates you haven't read http://catb.org/~esr/faqs/smart-questions.html From lloyd at paisite.com Sat Jan 12 14:22:58 2008 From: lloyd at paisite.com (lloyd at paisite.com) Date: Sat, 12 Jan 2008 14:22:58 -0500 (EST) Subject: =?UTF-8?Q?RE:=20where=20do=20my=20python=20files=20go=20in=20linux=3F?= Message-ID: <42229.192.168.1.35.1200165778.webmail@192.168.1.35> Hello, > Question 1. Where do I put the bulk of python scripts in a normal > linux environment? In my system I put them in /usr/local/lib/python2.4/site-packages/my_scripts. And, I have *.pth file in /usr/local/lib/python2.4/site-packages that points to my_scripts. The *.pth file simply reads "my_scripts" -- without the quotes, of course. This one area where Python docs are pretty vague. It took me awhile to piece this together. But it works. Best wishes, Lloyd -------------- next part -------------- An HTML attachment was scrubbed... URL: From horacius.rex at gmail.com Tue Jan 8 03:19:25 2008 From: horacius.rex at gmail.com (Horacius ReX) Date: Tue, 8 Jan 2008 00:19:25 -0800 (PST) Subject: Look for a string on a file and get its line number Message-ID: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> Hi, I have to search for a string on a big file. Once this string is found, I would need to get the number of the line in which the string is located on the file. Do you know how if this is possible to do in python ? Thanks From rajarshi.guha at gmail.com Fri Jan 11 17:02:21 2008 From: rajarshi.guha at gmail.com (Rajarshi) Date: Fri, 11 Jan 2008 14:02:21 -0800 (PST) Subject: extracting Javadocs using Python Message-ID: <30a4948a-7293-43d6-9381-824654e44416@s19g2000prg.googlegroups.com> Hi, I work on a Java project and I was thinking out creating a hook in the subversion repo for the project that would check whether a class and it's associated methods were documented with Javadocs. Since I have written Subversion hooks for other purposes in Python, I'd like to try and do this task in Python as well. However, it seems that I'd need a full fledged Java/Javadoc parser written in Python. Does anybody know if something like this is available? Or would I need to implement a parser from scratch? Thanks, From deets at nospam.web.de Tue Jan 29 07:20:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jan 2008 13:20:26 +0100 Subject: Executing other python code References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: <608k0aF1ovmf7U1@mid.uni-berlin.de> Tim Rau wrote: > I'm working on a game, and I'd like players to be able to define thier > ships with scripts. Naturally, I don't want to give them the entire > program as thier romping ground. I would like to invoke a seperate > interpreter for these files, and give it a limited subset of the > functions in my game. What is the best way to achieve this effect? You might consider spawning a process and using Pyro to communicate. I've done that before and it worked pretty well. Diez From tarun.kap at gmail.com Wed Jan 16 14:33:24 2008 From: tarun.kap at gmail.com (Tarun Kapoor) Date: Wed, 16 Jan 2008 11:33:24 -0800 (PST) Subject: paramiko References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> <8ceaad4c-c725-4093-a204-ab09162d4629@c23g2000hsa.googlegroups.com> Message-ID: <685fabb3-c9e8-47ac-84f2-405b831bccad@v4g2000hsf.googlegroups.com> On Jan 16, 12:22 pm, "Guilherme Polo" wrote: > 2008/1/16, Tarun Kapoor : > > > > > On Jan 16, 11:38 am, "Guilherme Polo" wrote: > > > 2008/1/16, Tarun Kapoor : > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across > > > > the connection > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > sock.connect((hostname, port)) > > > > > t = paramiko.Transport(sock) > > > > t.start_client() > > > > key = t.get_remote_server_key() > > > > > event = threading.Event() > > > > t.auth_password(username=username, password=password, event=event) > > > > event.wait() > > > > > if not t.is_authenticated(): > > > > print "not authenticated" > > > > > output: > > > > not authenticated > > > > This is a different problem I guess, now you are usin get_remote_server_key. > > > And why are you creating event after calling start_client without > > > specifying it ? > > > > > On Jan 16, 11:11 am, "Guilherme Polo" wrote: > > > > > 2008/1/16, Tarun Kapoor : > > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > > > > > > the remote server using an SFTP client I have just to make sure that > > > > > > username and password are working.. This is the code. > > > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > > > > > > connection > > > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > > > > sock.connect((hostname, port)) > > > > > > > t = paramiko.Transport(sock) > > > > > > > event = threading.Event() > > > > > > > t.start_client(event) > > > > > > > event.wait(15) > > > > > > > if not t.is_active(): > > > > > > > print 'SSH negotiation failed.' > > > > > > > sys.exit(1) > > > > > > > else: > > > > > > > print "SSH negotiation sucessful" > > > > > > > event.clear() > > > > > > > t.auth_password(username=username, password=password,event=event) > > > > > > > if not t.is_authenticated(): > > > > > > > print "not authenticated" > > > > > > > output: > > > > > > > SSH negotiation successful > > > > > > > not authenticated > > > > > > > Tarun > > > > > > > Waterstone Capital Management > > > > > > > 2 Carlson Parkway, Suite 260 > > > > > > > Plymouth, MN 55447 > > > > > > > Direct: 952-697-4123 > > > > > > > Cell: 612-205-2587 > > > > > > Disclaimer This e-mail and any attachments is confidential and intended > > > > > > solely for the use of the individual(s) to whom it is addressed. Any views > > > > > > or opinions presented are solely those of the author and do not necessarily > > > > > > represent those of Waterstone Capital Management, L.P and affiliates. If you > > > > > > are not the intended recipient, be advised that you have received this > > > > > > e-mail in error and that any use, dissemination, printing, forwarding or > > > > > > copying of this email is strictly prohibited. Please contact the sender if > > > > > > you have received this e-mail in error. You should also be aware that > > > > > > e-mails are susceptible to interference and you should not assume that the > > > > > > contents of this e-mail originated from the sender above or that they have > > > > > > been accurately reproduced in their original form. Waterstone Capital > > > > > > Management, L.P. and affiliates accepts no responsibility for information, > > > > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > > > > > > please verify the authenticity with the sender. > > > > > > -- > > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > You are missing an event.wait() after t.auth_password. > > > > > Also, why are you passing this magic value "15" to event.wait() ? That > > > > > parameter is passed to class _Verbose to indicate if debug messages > > > > > should be displayed or not, so typical values would be 0/1 or > > > > > False/True. > > > > > > -- > > > > > -- Guilherme H. Polo Goncalves > > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > -- > > > -- Guilherme H. Polo Goncalves > > > ok here is the problem... I don't know what is the correct way... The > > only demos i have from the paramiko library use a hostkeyfile. since i > > don't have that i thought i would use the get_remote_key to get the > > key and then connect it using the code in the demo.. But clearly > > nothing is working...I should not HAVE to use the key since i should > > be able to authenticate using the password... > > > Can you please suggest the right way to go ? > > You don't need to use key to authenticate using username and password, > indeed. And you don't. Your first email was almost correct, you just > needed to add event.wait() after t.auth_password. It worked here after > doing that change. You can check out my version: > > import sys > import socket > import paramiko > import threading > > if len(sys.argv) != 4: > print "%s hostname user password" % sys.argv[0] > sys.exit(1) > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((sys.argv[1], 22)) > > t = paramiko.Transport(sock) > event = threading.Event() > t.start_client(event) > > event.wait() > > if not t.is_active(): > print 'SSH negotiation failed.' > sys.exit(1) > else: > print "SSH negotiation sucessful" > > event.clear() > t.auth_password(username=sys.argv[2], password=sys.argv[3], event=event) > event.wait() > if not t.is_authenticated(): > print "Authentication failed." > else: > print "Authenticated!" > > t.close() > > > > > Thanks for your time ! > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves ok i tried the exact same code and here is the output SSH negotiation sucessful Authentication failed. I am positive that the username and paddword are correct. ! From f.guerrieri at gmail.com Sun Jan 6 16:48:04 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Sun, 6 Jan 2008 22:48:04 +0100 Subject: Basic inheritance question In-Reply-To: References: Message-ID: <79b79e730801061348m8f8594bmbf34c716a3fa6564@mail.gmail.com> On Jan 5, 2008 11:31 AM, wrote: > import tok > > class code: > def __init__( self, start, stop ): > startLoc = start > stopLoc = stop > > class token(code): > pass > Apart from the missing self, remember that the __init__(...) of the base classes is not automatically called, unless you do it explicitly or you do not provide one in the derived class. So for instance you could have something like class token(code): def __init__(self, ...): # do the token specific initialization here .... # Now init the base class code.__init__(self, ....) Or, better, you could use super if you were using new-style classes (which you are not...), like in the following: class token(code): def __init__(self, ...): # do your initialization here super(token, self).__init__(....) which is much better suited to allow multiple inheritance (there has been a discussion in these days about the MRO, look for a paper by Michele Simionato). Quoting Alex Martelli in Python in a nutshell (page 97): "If you get into the habit of always coding superclass calls with super, your classes will fit smoothly even in complicated inheritance structures. There are no ill effects whatsoever if the inheritance structure instead turns out to be simple, as long, of course, as you're only using the new-style object model, as I recommend". bye, Francesco From dg.google.groups at thesamovar.net Wed Jan 23 15:54:20 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Wed, 23 Jan 2008 12:54:20 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> Message-ID: Well I tried the NumPy array thing that I was talking about, to parallelise the problem, and there were some difficulties with it. Firstly, the pruning makes a really big difference to the speed, and you don't get that if you're trying to parallelise the problem because what is an equivalent calculation for one set of numbers is obviously not for another set. I think this problem disappears when you consider very large sets of numbers though (where the cost of doing equivalent computations vanishes in comparison to the alternative cost of starting up the whole recursive computation from scratch many times). The second problem is that you can't weed out division by zero and intermediate fractions. I haven't looked at the internals of how NumPy deals with these though, so this might be fixable or it might not. For my part, I'd consider the following equivalences to be right for defining equivalent expressions (where here a, b and c are any subexpression, and 1 and 0 means any subexpression that evaluates to 1 and 0). Commutativity: a*b <-> b*a a+b <-> b+a Associativity: (a+b)+c <-> a+(b+c) (a+b)-c <-> a+(b-c) (a-b)+c <-> a-(b-c) (a-b)-c <-> a-(b+c) (a*b)*c <-> a*(b*c) (a*b)/c <-> a*(b/c) (a/b)*c <-> a/(b/c) (a/b)/c <-> a/(b*c) Units (1 is multiplicative unit, 0 is additive unit): a*1 <-> a a/1 <-> a a+0 <-> a a-0 <-> a Substitution (swapping equal starting numbers is equivalent): expr(a,b,c,...,z) <-> expr(s(a,b,c,...,z)) where a,b,c,...,z are the original numbers given and s is a permutation of (a,b,c...,z) so that (a,b,c,...z) evaluates to the same thing as s(a,b,c,...,z) or equivalently, expr1 <-> expr2 if str(expr1)==str(expr2) Then, any two expressions which can be transformed into one another by the equivalences above are equivalent. Commutativity and units can be easily implemented as you go and most of the programs suggested so far do this, by for example only allowing a*b or a+b if a>=b, and not allowing a*1 or 1*a, etc. Substitution can be implemented by just taking set(map(str,expressions)) at the end. The associativity ones are a little more tricky to implement, but Arnaud's idea of the fully ordered binary tree seems to do it. Another way of saying it is that any subexpression consisting only of + and - operations should be reduced to a+b+c+...-z-y-x-.... where a>b>c>... and z>y>x>... (and similarly for an expression involving only * and /). Terry, I'd also be interested in a copy of your stack simulation code, btw. From phillip.sitbon at gmail.com Fri Jan 11 19:42:33 2008 From: phillip.sitbon at gmail.com (Phillip Sitbon) Date: Fri, 11 Jan 2008 16:42:33 -0800 (PST) Subject: Python in IIS + WSGI References: <86d01390-fb1c-4806-a10b-92446c008b10@k2g2000hse.googlegroups.com> Message-ID: <728a3b8a-074f-4435-89e3-4cdb095f193a@q39g2000hsf.googlegroups.com> Pardon my typo! http://pyisapie.sourceforge.net On Jan 11, 4:37 pm, Phillip Sitbon wrote: > Recently (finally) updated the PyISAPIe project. Version 1.0.4 > includes WSGI support (tested with current Django SVN and Trac 0.10) > and a Django-native handler, as well as other examples of using it as > a standalone web app. > > Also added some installation/usage docs on the project page. > > Comments/feedback welcome! > > http://pyisapie.sourceforege.net > > Cheers, > > Phillip From mnordhoff at mattnordhoff.com Tue Jan 15 22:47:02 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 15 Jan 2008 22:47:02 -0500 Subject: Is str/unicode.encode supposed to work? with replace/ignore In-Reply-To: References: Message-ID: <478D7E36.9020009@mattnordhoff.com> BerlinBrown wrote: > With this code, ignore/replace still generate an error > > # Encode to simple ascii format. > field.full_content = field.full_content.encode('ascii', 'replace') > > Error: > > [0/1] 'ascii' codec can't decode byte 0xe2 in position 14317: ordinal > not in ran > ge(128) > > The document in question; is a wikipedia document. I believe they use > latin-1 unicode or something similar. I thought replace and ignore > were supposed to replace and ignore? Is field.full_content a str or a unicode? You probably haven't decoded it from a byte string yet. >>> field.full_content = field.full_content.decode('utf8', 'replace') >>> field.full_content = field.full_content.encode('ascii', 'replace') Why do you want to use ASCII? UTF-8 is great. :-) -- From BjornSteinarFjeldPettersen at gmail.com Sun Jan 13 09:31:56 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 13 Jan 2008 06:31:56 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> Message-ID: On Jan 13, 1:51 pm, Richard Szopa wrote: > On Jan 13, 8:59 am, Marc 'BlackJack' Rintsch wrote: > > > On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: > > > However, I am very surprised to learn that > > > > super_object.__getattr__(name)(*args, **kwargs) > > > > getattr(super_object, name)(*args, **kwargs) > > > > are not equivalent. This is quite odd, at least when with len() > > > and .__len__, str() and .__str__. Do you maybe know what's the > > > rationale behind not following that convention by getattr? > > > I think you are confusing `__getattr__` and `__getattribute__` here! > > `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's > > different. > > Well, in my code calling super_object.__getattr__(name)(*args, > **kwargs) and getattr(super_object, name)(*args, **kwargs) gives > *different* effects (namely, the latter works, while the former > doesn't). That kinda suggests that they don't map to each other :-). > And that makes me feel confused. > > Cheers, > > -- Richard They do, except for when it comes to what super(..) returns. It isn't really an object in the sense that they're presented in the tutorial, but rather a sort of proxy to the methods in the ancestor classes of the concrete object (self), relative to the current method's class. I can't imagine that sentence would ease any confusion however, suffice it to say that you have to call getattr(super(..), 'name') instead of super(..).__getattr__('name') and you have to call super(..).__len__() instead of len(super(..)) -- I can't imagine that lessens any confusion either :-/ super(..) is designed to handle situations like this correctly class Root(object): n = 1 class Left(Root): def foo(self): print 'n =', self.n print 'super n = ', super(Left, self).n class Right(Root): n = 2 class Leaf(Left,Right): n = 3 x = Leaf() x.foo() the correct output is n = 3 super n = 2 -- bjorn From nstjelja at gmail.com Wed Jan 9 00:49:56 2008 From: nstjelja at gmail.com (Nikola Stjelja) Date: Wed, 9 Jan 2008 06:49:56 +0100 Subject: module pickle In-Reply-To: References: Message-ID: <2d24984a0801082149k4d0f5cb9y53e6094c756727ab@mail.gmail.com> On Jan 9, 2008 5:29 AM, Beema shafreen wrote: > Hi I am beginner in python. and I am not able to understand the Pickle > concept in python can. some body explain me about the use of this module, > few examples. which will help me a lot. > > regards > shafreen > > -- > http://mail.python.org/mailman/listinfo/python-list > You can find a good documentation of the pickle module here: http://docs.python.org/dev/library/pickle.html with exmaples to show you how you can use it. Pickle is used to serialize objects. What does that mean? In short you save your objects( remeber everything is an object in python, strings, lists, touples, dictionaries ...) to an external file (eg. object.pcl) for later usage( eg. you save your users personal data when exiting your software, and then you load it later when your software is restarted by the user. -- Please visit this site and play my RPG! http://www.1km1kt.net/rpg/Marinci.php -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Jan 21 10:10:17 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Jan 2008 16:10:17 +0100 Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> <13p998o7mskm7e0@corp.supernews.com> Message-ID: Steven D'Aprano wrote: >> The following relies on undocumented (I hope) behaviour: >>>>> preferences = [10, 30, 20] >>>>> hosts = [ "mx1.domain.com", "anotherhost.domain.com", >>... "mx2.domain.com"] >>>>> hosts.sort(key=lambda x, p=iter(preferences).next: p()) >>>>> preferences.sort() >>>>> hosts >> ['mx1.domain.com', 'mx2.domain.com', 'anotherhost.domain.com'] > What bit are you suggesting is undocumented? The lambda spits out the items in preferences in the same order as they occur in that list. If hosts.sort(key=...) in its C-implemented decoration phase would iterate over the items in hosts in, say, reverse order hosts would not be sorted correctly. Here's an illustration in Python: >>> def dsu(items, key, reorder=lambda x: x): ... for i in reorder(range(len(items))): ... items[i] = key(items[i]), items[i] ... items.sort() ... items[:] = [v for k, v in items] ... return items ... >>> dsu([1,2,3], lambda x, n=iter("acb").next: n()) [1, 3, 2] >>> dsu([1,2,3], lambda x, n=iter("acb").next: n(), reversed) [3, 1, 2] Peter From salgerman at gmail.com Tue Jan 8 13:11:08 2008 From: salgerman at gmail.com (gsal) Date: Tue, 8 Jan 2008 10:11:08 -0800 (PST) Subject: copy a numpy array References: Message-ID: <0cc33c4e-bb6b-4f80-8b4d-d702dc7789ec@v29g2000hsf.googlegroups.com> I am new to python and everything related to it, and it so happens that I just went through the numpy tutorial last night, it is in http://www.scipy.org/Tentative_NumPy_Tutorial and the answer to your question is in section 3.7 Basically, if you want to make a (deep) copy of it: destarray = srcarray.copy() gsal From alexandru.dumitrescu at gmail.com Mon Jan 14 09:52:34 2008 From: alexandru.dumitrescu at gmail.com (Alexandru Dumitrescu) Date: Mon, 14 Jan 2008 16:52:34 +0200 Subject: csv add lines Message-ID: Hi, I'm new to this list and to python. I am wondering, am I able to make my program read the *.txt files from a directory and to add, at the top of the file, three new lines which are stored in a *.csv file? For each *.txt file I have a line in the *.csv file which has in the first column the name of the *.txt file and in the next three columns the lines that I want to add in the corresponding *.txt file. If it is possible I'd appreciate some help. Thank you! Alex -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Mon Jan 21 05:49:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Jan 2008 11:49:55 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <5vi1r8F1mjs0rU1@mid.uni-berlin.de> <5360e13d-215d-4d3e-9930-daa6cddd996a@f10g2000hsf.googlegroups.com> <5vj79dF1m2nmlU1@mid.uni-berlin.de> <677d61a1-16be-40ae-8332-a5ff45ff8905@j78g2000hsd.googlegroups.com> Message-ID: <5vjbmjF1mp0hgU1@mid.uni-berlin.de> > > Diez, > > I repeat I am a newbie, so please don't be angry against me, if I say > something stupid or if I propose a method not efficient. Where did I sound angry? > An easy way to get the absolute path of site-packages seems very > useful to me, in order to check anything (all extensions available and > not provided by sys.path, etc.) related to the files on the > filesystem, if necessary. As I said - this is a wrong assumption. The whole purpose of the sys.path is to specify locations where modules/packages are installed. Note the plural. And matter of factly (as I told you in the last post already), this happens in e.g. debian based distributions install certain packages under /usr/share, which is by no means a prefix of /usr/python2.5 where the site-packages are. So if you want to find out if something is already installed, you need to consider ALL the contents of sys.path. Besides, I don't understand why you want to do it that way anyway. If you need a certain package, do try: import package except ImportError: do_install_package() This should/could be part of your installer script (most probably setup.py) And have you heard of setuptools? They do actually manage and install pytthon packages with dependencies. Before reinventing another wheel... > For the automatic installation of missing extensions (using admin > rights), I think that it is not difficult to do it on both > platforms... You are underestimating that task. It is, on both platforms. There are many discussions about this, why some people don't like setuptools because it works with python as center of it's perspective whereas linux often has package management for the whole system. I suggest you start acquainting yourself with setuptools and how and what they did to essentially solve what you seem to be wanting. And try and see if that's not a route you can go - just using setuptools. Diez From noahdain at gmail.com Thu Jan 10 12:31:53 2008 From: noahdain at gmail.com (Noah Dain) Date: Thu, 10 Jan 2008 12:31:53 -0500 Subject: run shell commands In-Reply-To: References: Message-ID: On Jan 10, 2008 9:24 AM, Riccardo Maria Bianchi wrote: > > Hello! :) > > I'm trying to run shell commands both with os.system() and > subprocess.Popen() class. > > But I can't run aliases or function defined in my .bashrc file, like in > the login interactive shell. > > Can you help me? > Maybe have I to add some commands to load the .bashrc? > > Thanks a lot! :) > > Ric. > > -- > http://mail.python.org/mailman/listinfo/python-list > you'd need to run an instance of the shell from python and probably as a login shell so that it pulls in .bashrc. so you'd need a command line like: /bin/bash -l -c "shell commands to run go here" if you want to feed more commands to bash, then use -s. It will read commands from standard input, which you would feed it from python, probably by writing to a Popen pipe. A lot of people also use the pexpect python library to "drive" other programs, especially if you need python to act differently depending upon the output of the called programs. Either way, this list's archives do have some good examples as to the uses and limitations of both subprocess and pexpect. -- Noah Dain "The beatings will continue, until morale improves" - the Management From projecteclipsor at gmail.com Sat Jan 12 15:04:42 2008 From: projecteclipsor at gmail.com (Landon) Date: Sat, 12 Jan 2008 14:04:42 -0600 Subject: Great Python books for the beginner In-Reply-To: <1a4d8dae-4722-4a10-a638-ac1b2d85227a@i72g2000hsd.googlegroups.com> References: <1a4d8dae-4722-4a10-a638-ac1b2d85227a@i72g2000hsd.googlegroups.com> Message-ID: One thing I wonder about is the examples these books use to teach the concepts. I found myself really attached to K&R because the end of section projects were utilities that I would find be able to find useful in day to day work such as a version of wc and a program that would take collapse all consecutive whitespace in a document into one space. I could just use the projects from K&R, but I imagine a Python book would have a better selection that highlight Python's abilities. On another note, I would prefer to have a paper book so I don't have to keep switching back and forth between documents on my computer. From ncoghlan at gmail.com Tue Jan 1 00:26:38 2008 From: ncoghlan at gmail.com (NickC) Date: Mon, 31 Dec 2007 21:26:38 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <6aba9463-f0ea-43a2-b8de-9c7026c4d14e@e4g2000hsg.googlegroups.com> Message-ID: <75ea72e9-f69f-4b3a-98fe-ffc364fa7543@l6g2000prm.googlegroups.com> On Jan 1, 3:22 am, Arnaud Delobelle wrote: > On Dec 31, 10:58 am, Odalrick wrote: > > > I'm surprised noone has said anything about the why of default > > mutables. I think it is becasue it isn't easy to do it an other way. > > [...] > > There is an easy enough way: evaluate default values when the function > is called rather than when it is defined. This behaviour comes with > its own caveats as well I imagine, and it's not 'as easy' to implement > as the current one. As Odalrick notes, there is no way to give different calls to a function their own copies of mutable default arguments without re- evaluating the defaults every time the function is called. The horrendous performance implications mean that that simply isn't going to happen. So the status quo, where the defaults are calculated once when the function is defined and the result cached in the function object is unlikely to change. > What's good about the current behaviour is that it is easy to reason > with (once you know what happens), even though you almost have to get > bitten once. But using this to have static variable is extremely ugly > IMHO. The only thing it doesn't give you is a static variable that isn't visible to the caller. Py3k's keyword-only arguments (PEP 3102) will make those cases a little tidier, since it won't be possible to accidentally replace the static variables by providing too many positional arguments. I believe the suggestion of permitting static variables after the ** entry in a function's parameter list was raised during the PEP 3102 discussions, but never gained much traction over a '_cache={}' keyword- only argument approach (and the latter has the distinct advantage of being *much* easier to test, since you can override the cache from the test code to ensure it is being handled correctly). Cheers, Nick. From bill.pursell at gmail.com Tue Jan 29 13:22:24 2008 From: bill.pursell at gmail.com (William Pursell) Date: Tue, 29 Jan 2008 10:22:24 -0800 (PST) Subject: object vs class oriented -- xotcl References: Message-ID: <2dfb6cd3-921a-4692-9627-d35bda40a93e@v29g2000hsf.googlegroups.com> On Jan 24, 9:16 pm, "Guilherme Polo" wrote: > 2008/1/24, William Pursell : > > Can I do it in Python? > > > class A(object): pass > class B(object): pass > > a = A() > a.__class__ = B > > That ? Maybe you meant something else. That is what I was referring to, but it isn't the core functionality that I'm after. (My bad for a poor description.) I'm fairly excited at the idea of being able to do per-object mixins in xotcl. I guess it would look like this in python: BROKEN CODE: a = object() a.__class__.append( foo ) a.__class__.append( bar ) In python, if you want an object to me a member of 2 classes, it seems that you have no choice but to declare a new class that inherits from both. eg: class foobar( foo, bar): pass a = foobar() Is it possible to make an object be a member of 2 classes without defining such a class? I believe "per object mixin" is the correct term for such an animal. The first several google hits on that phrase all reference xotcl, so I'm not sure if that is an xotcl inspired vocabulary that isn't really standard. From nagle at animats.com Thu Jan 24 18:14:32 2008 From: nagle at animats.com (John Nagle) Date: Thu, 24 Jan 2008 15:14:32 -0800 Subject: Testing whether something is of type Exception Message-ID: <47991a8a$0$36353$742ec2ed@news.sonic.net> How can I tell whether an object is of type Exception? At least in Python 2.4, "Exception" is an old-style class, and the "type" of Exception objects is "instance". Clearly "repr" knows; it returns: John Nagle From jatinpatni at gmail.com Wed Jan 9 11:29:03 2008 From: jatinpatni at gmail.com (jatin patni) Date: Wed, 9 Jan 2008 16:29:03 +0000 Subject: Problem in importing modules using py2exe Message-ID: I am trying to generate binaries on Windows platform using py2exe, but it is unable to import this module named "Mechanize". The error says " it could not find this module"...while the module is present along with all the other modules "Python/Lib/site-packages/"... Any help would be appreciated...Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Sun Jan 6 13:44:02 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 06 Jan 2008 19:44:02 +0100 Subject: Unexpected __metaclass__ method behavior In-Reply-To: References: <2273796e-87c6-4100-a5b5-1c6afa32a276@i29g2000prf.googlegroups.com> Message-ID: <4781216f$0$24469$426a74cc@news.free.fr> anne.nospam01 at wangnick.de a ?crit : > Well, you see, I have some database functions that deal with "things" > which are either classes or instances thereof. I though polymorphism > would be a nice way to handle them identically, like: > > def do(thing): thing.Foo() > do(t) > do(Test) > > But never mind, I now understand that Test.__dict__ can contain only > one entry for 'Foo', and that this must be matched. You may want to have a look at FormEncode's "declarative" API, with particular attention to the 'classinstancemethod' stuff. From miki.tebeka at gmail.com Tue Jan 15 02:02:41 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 14 Jan 2008 23:02:41 -0800 (PST) Subject: Is there some Python function that searches "sys.path" for a module? References: <478c5755$0$36354$742ec2ed@news.sonic.net> Message-ID: <6c9fb69f-04fb-460e-b78e-9b342e6f83ed@d21g2000prf.googlegroups.com> Hello John, > ? ?Python's own loader searches "sys.path" for module names, but is there > some function that makes that search functionality accessible to > Python programs? ?I need the absolute pathname of a module, with the > search being done exactly the same way "import" does it. ?The loader for > "egg" files has this functionality, but I'd like to find out if there's > a standard way to do this before looking into that source code. > > ? ?Also, it seems that the environment variable "PYTHONPATH" applies to > "import", but not to the starting module named on the Python command > line. ?Is that correct? ?Thanks. http://docs.python.org/lib/module-imp.html HTH, -- Miki Tebeka http://pythonwise.blogspot.com From henry.baxter at gmail.com Fri Jan 11 21:14:54 2008 From: henry.baxter at gmail.com (Henry Baxter) Date: Fri, 11 Jan 2008 18:14:54 -0800 Subject: ctypes, GetWindowLongPtr Message-ID: <8d04436f0801111814p31b3a98brd9fb5eed48860505@mail.gmail.com> Hello, I have been happily using ctypes for a while to do win32 programming. I use the Microsoft documentation to understand the function, then call it with the help of ctypes. The problem is that the docs says user32.dll has GetWindowLongPtr, but ctypes can't find it using windll.user32.GetWindowLongPtrA or windll.user32.GetWindowLongPtrW or windll.user32.GetWindowLongPtr. Errors look like this: Traceback (most recent call last): File "Z:\experiments\windowsapp3.py", line 106, in GetWindowLongPtr = windll.user32.GetWindowLongPtrA File "C:\Python25\lib\ctypes\__init__.py", line 353, in __getattr__ func = self.__getitem__(name) File "C:\Python25\lib\ctypes\__init__.py", line 358, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'GetWindowLongPtrA' not found I have the same problem with the SetWindowLongPtr function. I can use plenty of other functions (GetParent, CreateWindowExA, DefWindowProcA, and etc) but not these ones. I don't understand what goes on with ctypes under the hood really, so my troubleshooting abilities at this point are quite lacking! I would appreciate any help you could offer. Thanks! -- Henry -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Tue Jan 22 20:00:27 2008 From: wescpy at gmail.com (wesley chun) Date: Tue, 22 Jan 2008 17:00:27 -0800 (PST) Subject: Core Python Programming . . . References: <7xir1q29j5.fsf@ruckus.brouhaha.com> Message-ID: <40385ed1-6594-403e-934d-3d54a294101e@e25g2000prg.googlegroups.com> > > 6-11 Conversion. > > ? (a) Create a program that will convert from an integer to an > > Internet Protocol (IP) address in the four-octet format of WWW.XXX.YYY.ZZZ > > ? (b) Update your program to be able to do the vice verse of the above. > > I think it's is asking to convert a 32-bit int to the dotted form. > > It's a little known fact, but IP addresses are valid in non-dotted > long-int form. ?Spammers commonly use this trick to disguise their IP > addresses in emails from scanners. that is correct. don't read too much into it. i'm not trying to validate anything or any format, use old or new technology. it is simply to exercise your skills with numbers (specifically 32-bit/4- byte integers), string manipulation, and bitwise operations. if you wish to use different sizes of numbers, forms of addressing, IPv6, etc., that's up to you. don't forget about part (b), which is to take an IP address and turn it into a 32-bit integer. enjoy! -- wesley ps. since you're on p. 248, there is also a typo in the piece of code right above this exercise, Example 6.4, which is tied to exercise 6-7. "'fac_list'" should really be "`fac_list`", or even better, "repr(fac_list)". see the Errata at the book's website http://corepython.com for more details. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From fredrik at pythonware.com Wed Jan 9 14:38:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 20:38:38 +0100 Subject: problem of converting a list to dict In-Reply-To: <962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.googlegroups.com> References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> <962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.googlegroups.com> Message-ID: Louis.Soninhu at gmail.com wrote: >> to see what's going on on your machine, try printing "a" after the >> split, but before you use it to populate the dictionary. > > 'print a' works so what does it tell you? From washakie at gmail.com Wed Jan 30 17:34:33 2008 From: washakie at gmail.com (washakie) Date: Wed, 30 Jan 2008 14:34:33 -0800 (PST) Subject: dynamically set up ssh -r & paramiko? Message-ID: <15193757.post@talk.nabble.com> Hello, I'm trying to write a script which will allow me to initiate (spawn?) an SSH reverse tunnel from an internal box (inside a firewall) to an external box, while logged into the external box. I posted to another list and was pointed in the direction of paramiko. I've read the tutorials, but cannot seem to figure out exactly how I can do this... I'm hoping someone can look at what I'm trying to do below and provide an example... #!/usr/bin/python import os, time, subprocess REMOTE_HOME='/my/remote/mount' #mounted drive to REMOTE_HOME from LOCAL_MACHINE cmd = 'while true; do ssh -R 8022:localhost:22 MyUserName at RemoteHost ; sleep 60; done' while 1: while os.path.exists(os.path.join(REMOTE_HOME,'mySecretFile'): proc= subprocess.call(cmd,shell='True') if proc: os.kill(proc.pid) if os.path.exists(os.path.join(REMOTE_HOME,'KillScript'): break -- Note, I know the reverse tunnel script works on it's own run from the shell, but I don't want to leave it open always... furthermore it seems to be a rather 'brute force' method. It seems paramiko might provide a more elegant solution! Does anyone have any ideas on how to make this work? Thanks, john -- View this message in context: http://www.nabble.com/dynamically-set-up-ssh--r---paramiko--tp15193757p15193757.html Sent from the Python - python-list mailing list archive at Nabble.com. From fredrik at pythonware.com Tue Jan 8 06:03:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 Jan 2008 12:03:45 +0100 Subject: Open a List of Files In-Reply-To: References: Message-ID: BJ Swope wrote: > given a list such as > > ['messages', 'recipients', 'viruses'] > > how would I iterate over the list and use the values as variables and > open the variable names a files? > > I tried > > for outfile in ['messages', 'recipients', 'viruses']: > filename = os.path.join(Host_Path, outfile) > outfile = open(filename, 'w') > > But it's not working. the code looks ok. please define "not working". From gagsl-py2 at yahoo.com.ar Tue Jan 1 13:48:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Jan 2008 16:48:33 -0200 Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <6aba9463-f0ea-43a2-b8de-9c7026c4d14e@e4g2000hsg.googlegroups.com> <5c6a5515-a6ee-455d-83d4-48b2a2ae46c3@n20g2000hsh.googlegroups.com> <579f378d-d948-4c99-8507-a8c4e9a28096@i29g2000prf.googlegroups.com> <74a7edcf-f4ea-4835-b08e-499faaed8d81@i12g2000prf.googlegroups.com> Message-ID: En Tue, 01 Jan 2008 15:45:00 -0200, bukzor escribi?: > On Jan 1, 9:00 am, bukzor wrote: >> On Dec 31 2007, 1:30 pm, "Chris Mellon" wrote: >> >> > And also removing the only way you can currently do early binding in >> > Python. I agree that it's a gotcha, but unless someone comes up with >> > an answer to the following questions, I'll stick with the status quo >> > (Note that this is not blind Python group-think as a previous poster >> > implied, but a pragmatic decision that this is the most practical >> > solution): >> >> > a) If we don't evaluate default arguments at function compilation, >> > when do we do it? >> > b) If you do it at call time, how do you implement early binding? >> >> I'm confused by what you mean by 'early binding'. Can you give a quick- >> n-dirty example? > Is an 'early bound' variable synonymous with a 'static' variable (in > C)? No. It means, in which moment the name gets its value assigned. Usually Python does "late binding", that is, names are resolved at the time the code is executed, not when it's compiled or defined. Consider this example: z = 1 def foo(a) print a+z foo(3) # prints 4 z = 20 foo(3) # prints 23 The second time it prints 23, not 4, because the value for z is searched when the code is executed, so the relevant value for z is 20. Note that if you later assign a non-numeric value to z, foo(3) will fail. If you want to achieve the effect of "early binding", that is, you want to "freeze" z to be always what it was at the time the function was defined, you can do that using a default argument: z = 1 def foo(a, z=z) print a+z z = None foo(3) # prints 4 This way, foo(3) will always print 4, independently of the current value of z. Moreover, you can `del z` and foo will continue to work. This is what I think Chris Mellon was refering to. This specific default argument semantics allows one to achieve the effect of "early binding" in a language which is mostly "late binding". If someone changes this, he has to come with another way of faking early binding semantics at least as simple as this, else we're solving an [inexistant for me] problem but creating another one. -- Gabriel Genellina From martin at marcher.name Tue Jan 8 07:04:13 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 08 Jan 2008 13:04:13 +0100 Subject: Open a List of Files References: Message-ID: BJ Swope wrote: > On Jan 8, 2008 6:03 AM, Fredrik Lundh wrote: > >> BJ Swope wrote: >> >> > given a list such as >> > >> > ['messages', 'recipients', 'viruses'] >> > >> > how would I iterate over the list and use the values as variables and >> > open the variable names a files? >> > >> > I tried >> > >> > for outfile in ['messages', 'recipients', 'viruses']: >> > filename = os.path.join(Host_Path, outfile) >> > outfile = open(filename, 'w') files = dict() l = ['messages', 'recipients', 'viruses'] for f in l: files[f] = open(s.path.join(Host_Path, outfile), "w") files["messages].write("a string") hth martin PS: Code is untested -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From steven at REMOVE.THIS.cybersource.com.au Tue Jan 22 02:08:43 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 22 Jan 2008 07:08:43 -0000 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Mon, 21 Jan 2008 21:34:28 -0800, George Sakkis wrote: > I believe the "what is the fastest way" question for such small well- > defined tasks is worth asking on its own, regardless of whether it makes > a difference in the application (or even if there is no application to > begin with). Just because cpu cycles are cheap these days is not a good > reason to be sloppy. Moreover, often the fastest pure Python version > happens to be among the most elegant and concise, unlike other languages > where optimization usually implies obfuscation. I wonder why it is that people automatically assume that "optimization" means optimize the time taken, and not the developer effort to write it in the first place, the effort required to maintain it over time, or the memory used at runtime, let alone some combination of all four factors. Memory is cheap, but applications are hungry. CPUs are fast, and for most applications the difference between 3ms and 30ms is undetectable by the user. Why do we care so little about saving memory and so much about ever-decreasing time savings? -- Steven From bladedpenguin at gmail.com Sat Jan 26 00:20:23 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 21:20:23 -0800 (PST) Subject: Doesn't know what it wants Message-ID: Traceback (most recent call last): File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox \sandbox.py", line 242, in player = ship() File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox \sandbox.py", line 121, in __init__ self.phyInit() File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox \sandbox.py", line 147, in phyInit moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) ArgumentError: argument 4: : expected vec2d instance instead of vec2d As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't seems like it doesn't know what it wants, but I thought only teenagers did that, no programming languages. clearly, Im missing something. Line 147 reads: moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) From fredrik at pythonware.com Wed Jan 9 12:07:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 18:07:37 +0100 Subject: sqlite fetchall breacking because decoding. In-Reply-To: <8e81ff71-5e2e-4135-8159-6411a65e4100@v67g2000hse.googlegroups.com> References: <514759dc-faf7-4e34-bf6d-624a0cc540ae@e4g2000hsg.googlegroups.com> <8e81ff71-5e2e-4135-8159-6411a65e4100@v67g2000hse.googlegroups.com> Message-ID: tyoc wrote: >> well, the database *is* corrupt, since sqlite3 (both the engine and the >> Python binding) expects you to use a supported encoding for the data >> stored in the database: >> >> http://www.sqlite.org/datatype3.html >> http://docs.python.org/lib/node346.html > > Still like I said before, I have imported that data from python source > was a CVS with that encoding, I readed the lines with module CSV, then > used insert to the database like: the CSV module doesn't decode stuff for you; that's up to your code. see http://docs.python.org/lib/csv-examples.html#csv-examples for sample code (scroll down to the paragraph that starts with "The csv module doesn't directly support reading and writing Unicode"). From paul at boddie.org.uk Fri Jan 25 06:04:34 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 25 Jan 2008 03:04:34 -0800 (PST) Subject: time.gmtime References: <293bb767-603b-4aef-b9c8-23af565b090f@s8g2000prg.googlegroups.com> Message-ID: <6d8d8eac-3d4a-4b9a-9624-a1087c45ed6d@q39g2000hsf.googlegroups.com> On 25 Jan, 11:43, asit wrote: > we know that time.gmtime(secs) takes a parameter secs. what does this > secs suggest ??What is it's significance ?? >From the documentation [1] with some editing: """ gmtime([secs]) Convert a time expressed in seconds since the epoch to a time structure employing UTC. If secs is not provided or None, the current time as returned by time.time() is used. The epoch is the point where the time starts. On January 1st of that year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the epoch is 1970. To find out what the epoch is, look at gmtime(0). """ So, the significance of the secs parameter is that it indicates a specific point in time. Generally, you'll get this from functions like time.time or from "UNIX timestamps" stored in things like files and databases where people have wanted to indicate a point in time without having to mention things like dates, times and timezones. Paul P.S. The datetime module is preferable to the time module, really. The latter can drive you quite mad when things like timezones start to be taken into account. [1] http://docs.python.org/lib/module-time.html From mail at microcorp.co.za Sat Jan 12 03:44:39 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 12 Jan 2008 10:44:39 +0200 Subject: [Kamaelia] TCPClient: How to sense connection failure? References: <5uq49vF1jkgcoU1@mid.individual.net> Message-ID: <00c701c854f7$7b3cda20$03000080@hendrik> "Bjoern Schliessmann" wrote: >I'm currently trying to implement a simulation program with Kamaelia >and need a reliable TCP connection to a data server. > >From Twisted, I know that a method is called if the connection fails >by whatever reason. I tried to get the same results with Kamaelia's >TCPClient component. If I start up the component and try to connect >to a closed TCP port it fails and sends a message out of the signal >box, that's okay. > >But if the connection attempt succeeds and, after some time, the >server drops the connection with full TCP handshake (FIN, FIN+ACK, >ACK), the component just hangs and does nothing. Is this by design, >or could there be an error in my setup? > Not sure about Kamelia, but I have found that when a FIN comes along, a socket.recv() gives back an empty string, just like EOF on a file. I always have my sockets unblocked and fitted with time outs, but then I am basically a broken down assembler programmer, so there are probably better techniques around. Below is what I use - a sort of netstring, synced on a tilde, with human readable length implementation and escaping of tildes and the escape character. It seems to work reliably for me, and detects when the server goes down. The code for a typical client is below. If anybody is interested I will post the server too, but it should be trivial to make, given the example below. I hope the tabs survive the journey - Hendrik #start of code fragment def sockget_len(s,L,data): """ This fills a buffer of given length from the socket s, recursively. s is the socket L is the length to receive data is the buffer """ error = 0 req_L = L - len(data) try: data = data+s.recv(req_L) except socket.error,msg: # broken pipes again if 'timed out' in msg: rec = '2'*L return 2,rec # time out print 'socket error while receiving',msg rec = '1'*L return 1,rec # error = 1 is a snafu if not data: print 'end of file while receiving' rec = '0'*L return 3,rec # This is end of file if len(data) != L: error,data = sockget_len(s,L,data) return error,data def sockget(s): """ Gets a transmission from host. """ while True: tilde = '' error,tilde = sockget_len(s,1,tilde) # sync up on tilde if error == 1: return error,'' elif error == 2: return error,'' elif error == 3: return error,'' if tilde == '~': break length = '' error,length = sockget_len(s,4,length) # get the length of the data if error == 1: return error,'' # real error elif error == 2: return error,'' # Time out elif error == 3: return error,'' # End of file L = int(length) buf = '' error,data = sockget_len(s,L,buf) # get the data of length L return error, data # same errors as above 0 is all right # client communications program def comms_thread(qi,qo): """This listens for the latest values, and sends requests up.""" while True: HOST = 'Linuxbox' # The remote host PORT = 50007 # The same port as used by the server socket.setdefaulttimeout(10.00) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: qi.put('Connecting,') s.connect((HOST, PORT)) break except socket.error,msg: print 'error msg is:',msg time.sleep(10) continue print 'Connected - Time out is:',s.gettimeout() qi.put('Connected,') last_rx_time = time.time() last_tx_time = time.time() while True: while True: error,data = sockget(s) # see if a message from host if error == 0 and data: msg2 = data.replace('/\x81','~') msg1 = msg2.replace('/\xd0','/') qi.put(msg1) print 'received',msg1 last_rx_time = time.time() break elif error == 1: print 'Error after sockget' break if time.time() - last_rx_time > 180: print 'no comms from host for 3 minutes' error = 1 break # time out ok, unless they are too long if error == 2: error = 0 # time outs are all right here break if error == 3: error = 1 break # end of files are a snafu if error == 1: break try: i_string = qo.get(block=False) # see if stuff to transmit except Queue.Empty: if time.time()-last_tx_time > 8.5: i_string = 'Keepalive' # if not for a while, tell server we are alive print 'sending keepalive' else: time.sleep(0.1) # else wait a while and carry on continue msg1 = i_string.replace('/','/\xd0') msg2 = msg1.replace('~','/\x81') length = str(len(msg2)) L = len(length) if L == 1: length = '000'+length elif L == 2: length = '00'+length elif L == 3: length = '0'+length try: s.send('~'+length+msg2) last_tx_time = time.time() except socket.error,msg: print 'Socket error on transmit',msg break time.sleep(0.1) s.close() # Formally close the broken thing qi.put('Quit,') # Tell main thread its hopeless sys.exit() # Clobber this thread From aisaac at american.edu Fri Jan 25 18:41:08 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 25 Jan 2008 23:41:08 GMT Subject: find minimum associated values In-Reply-To: References: Message-ID: bearophileHUGS at lycos.com wrote: > I'd use the first solution. It can be speeded up a bit with a try/except: for k,v in kv: try: if d[k] > v: d[k] = v except KeyError: d[k] = v Cheers, Alan Isaac From steve at REMOVE-THIS-cybersource.com.au Sat Jan 26 07:01:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 26 Jan 2008 12:01:59 -0000 Subject: Custom class to a dictionary? References: <5025a3f7-9dcf-49d7-876c-df5c8d8a8df5@e6g2000prf.googlegroups.com> Message-ID: <13pm89n9avfl146@corp.supernews.com> On Sat, 26 Jan 2008 03:35:18 -0800, Oliver Beattie wrote: > Just wondering if it is possible to pass a custom class instance > instance to dict() by way of using methods like you can for iterators > (__iter__, __getitem__ etc.) I see there is no __dict__ -- is there > anything else I can use to achieve this? Just write a method to return (key, value) pairs, and call that: >>> class Parrot(object): ... def __init__(self): ... self.keys = [1, 2, 3, 4] ... self.values = ["one", "two", "three", "four"] ... def generate_tuples(self): ... for k,v in zip(self.keys, self.values): ... yield (k,v) ... >>> p = Parrot() >>> p.generate_tuples() >>> dict(p.generate_tuples()) {1: 'one', 2: 'two', 3: 'three', 4: 'four'} Here's another way: >>> class Foo(object): ... def __getitem__(self, i): ... if i > 4: ... raise IndexError ... return (i, 'foo %d' % i) ... >>> dict(Foo()) {0: 'foo 0', 1: 'foo 1', 2: 'foo 2', 3: 'foo 3', 4: 'foo 4'} Bonus marks if you can explain why they both work :) (Hint: consider the "sequence protocol" and the "iterator protocol".) -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Jan 17 23:36:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 18 Jan 2008 04:36:35 -0000 Subject: array and list References: <87bq7jbwxo.fsf@benfinney.id.au> Message-ID: <13p0b6jbn2ut6b4@corp.supernews.com> On Fri, 18 Jan 2008 15:05:23 +1100, Ben Finney wrote: > "J. Peng" writes: > >> what's the difference between an array and a list in python? > > In Python, 'list' is a basic built-in type. Python has no 'array' type, > though that term is often used to refer to the 'array' type defined in > Numeric Python (which is not part of the standard library, so not really > part of Python). Did you forget the array module? >>> import array >>> array >> I see list has all features of array in C or perl. > > You may also want to compare and constrast Python 'list' and 'dict'. The Original Poster might also like to check out the help() and dir() functions in the interactive interpreter: help(list) dir(list) help(array) help(array.array) etc. -- Steven From terry at jon.es Wed Jan 23 15:40:31 2008 From: terry at jon.es (Terry Jones) Date: Wed, 23 Jan 2008 21:40:31 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 10:12:22 on Wednesday, 23 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> <457550e3-f5e1-4fad-b553-c3e5e400dbb1@u10g2000prn.googlegroups.com> Message-ID: <18327.42559.997192.308761@jon.es> >>>>> "Arnaud" == Arnaud Delobelle writes: Arnaud> FWIW, I have a clear idea of what the space of solutions is, and Arnaud> which solutions I consider to be equivalent. I'll explain it Arnaud> below. I'm not saying it's the right model, but it's the one Arnaud> within which I'm thinking. OK. This reinforces why I'm not going to work on it anymore, the solution is subjective (once you start pruning). Arnaud> I think it's best to forbid negatives. Solutions always be written Arnaud> without any negative intermediate answer. E.g. 1-7*6*(3-9) can be Arnaud> done as 1+7*6*(9-3). That's a good optimization, and I think it's easy to prove that it's correct supposing the target is positive and the inputs are all positive. If you consider the intermediate results in a solution, then if you ever go negative it's because of an operation X (must be a sub or a div) and when you next become positive it's due to an operation Y (must be add or mul). So you can "reflect" that part of the computation by doing the opposite operations for that formerly sub-zero intermediate sequence. Arnaud> I don't consider these to be equivalent, because their equivalence Arnaud> depends on understanding the meaning of subtraction and addition. Ha - you can't have it both ways Arnaud! You don't want the computation to go negative... doesn't that (and my "proof") have something to do with the inverse nature of add and sub? :-) Arnaud> (I've also applied the 'big then small' rule explained below) And now you're taking advantage of your knowledge of > and < ... My original code did this big then small canonicalization too. That's my point exactly - pruning depends on who you are, how smart you are, how hard you work, your personal taste, etc. Arnaud> I see a solution as a full ordered binary tree. Each node has a Arnaud> weight (which is the result of the calculation it represents) and Arnaud> the left child of a node has to be at least as heavy as the right Arnaud> child. Each parent node can be labeled + - * or /. If a node x Arnaud> has two children y and z and is labeled , let me write x = (y Arnaud> z) Where does the sequence of numbers enter into this? You have a tree of operations - is it acting on a stack? What's on the stack? It sounds similar to what I've done. I walk up and down the tree, keeping the stack and the stack history, doing operations (including pushing onto the stack) and undoing them. There are several more prunings I could be doing, but these require looking further back in the stack. E.g., I force div before mul and sub before add, and I also apply the "big then small" rule to the intermediate stack results if there are series of identical operations (not just to a single operation). E.g. X / Y / Z can be re-ordered so that Y >= Z, and A + B + C can be reordered so A >= B >= C. Doing it on the stack results is different (but similar) to doing it on the raw input numbers. There are lots of other little and more complex things you can do to prune. You want to prune early, of course. The stack model of computation make this hard because it's always legitimate to push all the numbers onto the stack, by which point you're already deep in the tree. And this approach only lets you do local pruning - i.e., that affect the branch of the tree you're on. If you stored the state of the stack, the operation you're about to do, and the (sorted) numbers remaining to be input, then if you ever hit that configuration elsewhere in the massive tree, you could know that you'd been that way before. But are you justified in pruning at that point? The identical state of the computation could have been arrived at via a very different method. But that's where the big speed-up in this approach is. At this realization I decided to give up :-) Arnaud> To be perfectly honest (and expose my approach a little to your Arnaud> argument) I added a three additional rules: Arnaud> * Don't allow x - x Arnaud> * Don't allow x * 1 Arnaud> * Don't allow x / 1 Yes, I do these too, including not allowing a zero intermediate (which is a useless calculation that simply could not have been done - see, I have deep knowledge of zero!). Arnaud> If there are repeats in the list of starting numbers, I don't worry Arnaud> about repeating solutions. I handle most of those cases, but I didn't push all the way. With target 32 and input 8, 8, 8, 8 my code still gives 2 answers: 8 8 add 8 8 add add 8 8 add 8 add 8 add >> If anyone wants the stack simulation code, send me an email. Arnaud> I'd like to see it :) I'll send it. Terry From bignose+hates-spam at benfinney.id.au Wed Jan 23 18:06:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 24 Jan 2008 10:06:38 +1100 Subject: Increment Variable Name References: Message-ID: <87myqw87lt.fsf@benfinney.id.au> David Brochu writes: > I know the length of a list and I want to pass each element of a > list to a unique variable, thus I want to increment variable names. > If the list length = 4, i want to have the following variables: > var1, var2, var3, var4. This has a very bad code smell. What problem are you trying to solve by doing this? I strongly suspect there's a better solution. -- \ "If you do not trust the source do not use this program." | `\ ?Microsoft Vista security dialogue | _o__) | Ben Finney From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 08:41:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 27 Jan 2008 13:41:54 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> Message-ID: <13pp2h2eugn8594@corp.supernews.com> On Sun, 27 Jan 2008 10:55:20 +0000, over wrote: > I can understand people thinking I'm full of beans. Oh no, not full of beans. Full of something, but not beans. Everything you have written about assembly, machine code, compilers, Linux, Python and so forth has been a confused mish-mash of half-truths, distortions, vaguely correct factoids and complete nonsense. I'm starting to wonder if it is possible for somebody to be simultaneously so self-assured and so ignorant, or if we're being trolled. -- Steven From paul.hankin at gmail.com Wed Jan 16 11:10:35 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 16 Jan 2008 08:10:35 -0800 (PST) Subject: Generic string import like in strptime? References: Message-ID: On Jan 16, 8:34 am, Andre wrote: > Hi there > > Is there a function like strptime, which takes a string and converts it > into an array depending on a format string I provide. Like:>>> a = '3456\tblub-blib.0.9' > >>> b = '%d\t%s-%s.%f' > >>> c = mysticalfunction(a,b) > >>> print c > > [3456,'blub','blib',0.9] Use regular expressions: see http://docs.python.org/lib/node49.html -- Paul Hankin From asmodai at in-nomine.org Wed Jan 2 10:22:43 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 2 Jan 2008 16:22:43 +0100 Subject: Network-Packets In-Reply-To: <52da23100801020657v2d6e001ck5a9e126db77eb511@mail.gmail.com> References: <52da23100801020657v2d6e001ck5a9e126db77eb511@mail.gmail.com> Message-ID: <20080102152243.GE67953@nexus.in-nomine.org> -On [20080102 16:00], Sunil Ghai (sunilkrghai at gmail.com) wrote: >I know this is not the right place for asking about this but i am sure some of >you must have an idea about this. The networking community would be more appropriate, methinks. >I would like to know what do we actually mean by "Bandwidth". It is actually a fairly standardized term by now, to borrow Wikipedia's definition: In website hosting, the term "bandwidth" is often used metaphorically, to describe the amount of data that can be transferred to or from the website or server, measured in bytes transferred over a prescribed period of time. Even if a system discards packets, your NSP, ISP or webhost will still count it towards your total since it traversed their network. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ I must be cruel, only to be kind... From bernard.desnoues at univ-paris1.fr Mon Jan 21 09:02:11 2008 From: bernard.desnoues at univ-paris1.fr (Bernard Desnoues) Date: Mon, 21 Jan 2008 15:02:11 +0100 Subject: stdin, stdout, redmon Message-ID: <4794a5e3$0$9014$426a74cc@news.free.fr> Hi, I've got a problem with the use of Redmon (redirection port monitor). I intend to develop a virtual printer so that I can modify data sent to the printer. Redmon send the data flow to the standard input and lauchs the Python program which send modified data to the standard output (Windows XP and Python 2.5 context). I can manipulate the standard output. "import sys sys.stdout.write(data)" it works. But how to manipulate standard input so that I can store data in a string or in an object file ? There's no "read" method. "a = sys.stdin.read()" doesn't work. "f = open(sys.stdin)" doesn't work. I don't find anything in the documentation. How to do that ? Thanks in advance. Bernard Desnoues Librarian Biblioth?que de g?ographie - Sorbonne From software at ginstrom.com Thu Jan 17 20:55:21 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Fri, 18 Jan 2008 10:55:21 +0900 Subject: [OT] "Code Friendly" Blog? In-Reply-To: References: Message-ID: <0e1801c85975$2f89b9e0$0203a8c0@MOUSE> > On Behalf Of Miki > Posting code examples to blogger.com hosted blog is not fun > (need to remember alway escape < and >). > Is there any free blog hosting that is more "code friendly" > (easy to post code snippets and such)? I use WordPress with the Dean's Code Highlighter plugin[1] (which uses the Geshi code highlighter). You write your code like this:
print "hello, world!"
You do need to escape angle brackets, though. You also have to turn off WYSIWYG editing in WordPress, or it'll mess things up. Here's an example of how it turns out: http://ginstrom.com/scribbles/2007/11/17/fixing-jis-mojibake-with-python/ [1] http://www.deanlee.cn/wordpress/code_highlighter_plugin_for_wordpress/ Regards, Ryan Ginstrom From arnodel at googlemail.com Sat Jan 26 11:13:01 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 26 Jan 2008 16:13:01 +0000 Subject: Just for fun: Countdown numbers game solver In-Reply-To: <18327.47084.736074.304302@jon.es> References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> <457550e3-f5e1-4fad-b553-c3e5e400dbb1@u10g2000prn.googlegroups.com> <18327.47084.736074.304302@jon.es> Message-ID: <201F42DF-C0B1-482F-A0AB-59AD07AE77E0@gmail.com> Right, I've cleaned up my efforts a bit: * tried to improve the efficiency of the 'fold' technique that I posted earlier. * taken on Dan's email about equivalence of expressions * created a problem random generator * created a little function test to time and compare various things, and a 'random test' function. In the file there are two methods for combining two expressions: 'ops' and 'cleverops'. Ops is vanilla, cleverops only returns canonical expressions (roughly) as defined in Dan's email. The two strategies for walking the solution tree are 'divide and conquer' (divide) and 'origami' (fold). The code is pretty straighforward and is commented! Then there are some convenience functions for running the algorithms: print_countdown, all_countdown and first_countdown. Here's an example of how it works: >>> # print all solutions using the divide method, and cleverops: >>> print_countdown([50, 8, 5, 4, 9, 10], 983, method=divide, ops=cleverops) 50*5*4-9-8 (50*5+8-10)*4-9 (50+8/4)*(10+9)-5 50*(10-5)*4-9-8 >>> # Test which method is fastest, divide or fold: >>> randtest(10, 'method', method=[divide, fold], ops=cleverops) divide fold 0.317304 0.366359 ([1, 2, 4, 3, 6, 7], 249) 0.495667 0.660426 ([75, 100, 50, 25, 9, 3], 289) 0.443912 0.562409 ([50, 8, 5, 4, 9, 10], 399) 0.199696 0.231997 ([100, 1, 5, 7, 1, 4], 833) 0.406256 0.527588 ([50, 25, 10, 9, 3, 8], 123) 0.263348 0.315722 ([9, 8, 7, 5, 1, 7], 730) 0.403028 0.517426 ([25, 75, 9, 4, 10, 6], 605) 0.420140 0.564138 ([10, 6, 10, 9, 5, 4], 900) 0.278489 0.343525 ([4, 10, 5, 9, 9, 1], 388) 0.485815 0.643627 ([100, 10, 2, 6, 3, 9], 146) ------------ ------------ 0.371365 0.473322 >>> # Test which method is best for finding just one solution: >>> randtest(10, 'method', method=[divide, fold], countdown=first_countdown) divide fold 0.001674 0.043920 ([50, 75, 25, 9, 5, 8], 333) 0.164332 0.072060 ([75, 2, 7, 8, 8, 5], 409) 0.028889 0.212317 ([50, 100, 75, 6, 3, 9], 782) 0.049070 0.005830 ([75, 4, 3, 2, 1, 6], 471) 0.014728 0.091845 ([100, 75, 25, 50, 8, 7], 483) 0.290982 0.367972 ([3, 1, 7, 6, 5, 3], 794) 0.240363 0.118508 ([50, 100, 75, 3, 1, 10], 537) 0.001693 0.009519 ([50, 75, 8, 7, 5, 5], 180) 0.000289 0.037539 ([3, 9, 2, 4, 4, 1], 123) 0.079161 0.174323 ([50, 75, 100, 25, 4, 10], 723) ------------ ------------ 0.087118 0.113383 >>> # Test how cleverops improves over ops for the fold method: >>> randtest(10, 'ops', method=fold, ops=[ops, cleverops]) ops cleverops 1.689920 0.671041 ([75, 9, 6, 10, 3, 9], 874) 0.938402 0.338120 ([5, 7, 8, 2, 1, 7], 258) 0.982800 0.333443 ([25, 50, 9, 4, 8, 1], 309) 1.152037 0.407845 ([25, 50, 3, 5, 10, 1], 736) 0.892541 0.323406 ([9, 7, 1, 9, 4, 10], 108) 1.794778 0.677161 ([25, 50, 10, 8, 2, 6], 357) 1.534185 0.591878 ([50, 100, 25, 7, 7, 3], 773) 1.013421 0.350179 ([50, 6, 3, 1, 8, 9], 761) 0.612838 0.228354 ([25, 1, 4, 3, 1, 4], 148) 1.213055 0.430611 ([50, 100, 5, 3, 10, 1], 814) ------------ ------------ 1.182398 0.435204 I have found that the 'divide & conquer' strategy is faster than the 'origami' one. Moreover cleverops (i.e. clever pruning) improves origami by much more than divide&conquer. Code follows. Terry: I'm going to look at your code tonight and see if I can interface it with my little testing suite. Thanks for posting it! It was a lot of fun thinking about this, although I am sure that there is a lot of room for improvement. In particular, there must be a simple way to avoid the amount of list tinkering in fold(). Any feedback greatly appreciated. -- Arnaud ====================== countdown.py ======================= def getop(h): return 'n' if isinstance(h, int) else h[1] # An ops function takes two numbers with histories and yield all suitable # ways of combining them together. def ops(a, b): if a < b: a, b = b, a x, hx = a y, hy = b yield x + y, (a, '+', b) if x != 1 and y != 1: yield x * y, (a, '*', b) if x != y: yield x - y, (a, '-', b) if not x % y and y != 1: yield x / y, (a, '/', b) def cleverops(a, b, getop=getop): if a < b: a, b = b, a x, hx = a y, hy = b opx, opy = getop(hx), getop(hy) # rx is the right operand of hx (or x if no history) rx = x if opx == 'n' else hx[2][0] if opy not in '+-': # Only allow a+b+c-x-y-z if a >= b >= c... if (opx == '+' and rx >= y) or (opx not in '+-' and x >= y): yield x + y, (a, '+', b) # ... and x >= y >= z if x > y and (opx != '-' or rx >= y): yield x - y, (a, '-', b) if y != 1 and opy not in '*/': # Only allow a*b*c/x/y/z if a >= b >= c... if (opx == '*' and rx >= y) or (opx not in '*/' and x >= y): yield x * y, (a, '*', b) # ... and x >= y >= z if not x % y and (opx != '/' or rx >= y): yield x / y, (a, '/', b) # a method function takes a list of numbers, an action, and and ops # function. It should go through all ways of combining the numbers # together (using ops) and apply action to each. def fold(nums, action, ops=cleverops): "Use the 'origami' approach" nums = zip(nums, nums) # Attach a history to each number def recfold(start=1): for i in xrange(start, len(nums)): a, ii = nums[i], i-1 # Pick a number; for j in xrange(i): b = nums.pop(j) # Take out another before it; for x in ops(a, b): # combine them nums[ii] = x # into one; action(*x) # (with side-effect) recfold(ii or 1) # then fold the shorter list. nums.insert(j, b) nums[i] = a recfold() def divide(nums, action, ops=cleverops): "Use the 'divide and conquer' approach" def partitions(l): "generate all 2-partitions of l" for i in xrange(1, 2**len(l)-1, 2): partition = [], [] for x in l: i, r = divmod(i, 2) partition[r].append(x) yield partition def recdiv(l): if len(l) == 1: # if l in a singleton, yield l[0] # we're done. else: for l1, l2 in partitions(l): # Divide l in two; for a in recdiv(l1): # conquer the two for b in recdiv(l2): # smaller lists; for x in ops(a, b): # combine results action(*x) # (with side-effect) yield x # and yield answer. for x in recdiv(zip(nums, nums)): pass # Countdown functions def all_countdown(nums, target, method=fold, ops=cleverops): "Return all ways of reaching target with nums" all = [] def action(n, h): if n == target: all.append(h) method(nums, action, ops) return all def print_countdown(nums, target, method=fold, ops=cleverops): "Print all solutions" def action(n, h): if n == target: print pretty(h) method(nums, action, ops) class FoundSolution(Exception): "Helper exception class for first_countdown" def __init__(self, sol): self.sol = sol def first_countdown(nums, target, method=fold, ops=cleverops): "Return one way of reaching target with nums" def action(n, h): if n == target: raise FoundSolution(h) try: method(nums, action, ops) except FoundSolution, fs: return pretty(fs.sol) # Pretty representation of a number's history lbracket = ['+*', '-*', '+/', '-/', '/*'] rbracket = ['*+', '*-', '/+', '/-', '/*', '-+', '--'] def pretty(h): "Print a readable form of a number's history" if isinstance(h, int): return str(h) else: x, op, y = h x, y = x[1], y[1] x, y, xop, yop = pretty(x), pretty(y), getop(x), getop(y) if xop + op in lbracket: x = "(%s)" % x if op + yop in rbracket: y = "(%s)" % y return ''.join((x, op, y)) # This test function times a call to a countdown function, it allows # comparisons between differents things (methods, ops, ...) def test(enumkey=None, **kwargs): from time import time def do_countdown(countdown=all_countdown, target=758, nums=[2, 4, 5, 8, 9, 25], **kwargs): return countdown(nums, target, **kwargs) enum = kwargs.pop(enumkey) if enumkey else ['time'] for val in enum: if enumkey: kwargs[enumkey] = val t0 = time() do_countdown(**kwargs) t1 = time() yield t1-t0 # Tools for generating random countdown problems and doing random # tests. bignums, smallnums = [25, 50, 75, 100], range(1, 11)*2 from random import sample, randrange def randnums(nbig=None): if nbig is None: nbig = randrange(5) return sample(bignums, nbig) + sample(smallnums, 6-nbig) def randtarget(): return randrange(100, 1000) # Like test() but generates n tests with a new random problem to solve # each time, and prints the results. def randtest(n=1, enumkey=None, col=12, **kwargs): if enumkey: enums = kwargs[enumkey] nenums = len(enums) enums = [getattr(obj, '__name__', obj) for obj in enums] print ' '.join("%*s" % (col, obj[:col]) for obj in enums) else: nenums = 1 acc = [0] * nenums for i in xrange(n): target, nums = randtarget(), randnums() kwargs.update(target=target, nums=nums) times = tuple(test(enumkey, **kwargs)) print ' '.join("%*f" % (col, t) for t in times), print ' (%s, %s)' % (nums, target) for i, t in enumerate(times): acc[i] += t if n > 1: print ' '.join(['-'*col]*nenums) print ' '.join("%*f" % (col, t/n) for t in acc) From stanc at al.com.au Tue Jan 15 18:08:49 2008 From: stanc at al.com.au (Astan Chee) Date: Wed, 16 Jan 2008 10:08:49 +1100 Subject: Restart crashing modules in windows In-Reply-To: <86a0b31e-de71-4820-a37f-3c0fa26b768f@i72g2000hsd.googlegroups.com> References: <86a0b31e-de71-4820-a37f-3c0fa26b768f@i72g2000hsd.googlegroups.com> Message-ID: <478D3D01.9060303@al.com.au> Mike Driscoll wrote: > On Jan 14, 9:02 pm, Astan Chee wrote: > >> Hi, >> I have a python module that keeps on crashing with various windows >> errors (not BSOD but the less lethal windows XP popup ones). Now these >> are intentional and rather sporadic so I cant really solve it by >> attempting to fix the crash; rather what Im trying to do is make another >> module outside it that restarts this module every time it crashes. Is >> this possible? >> > > If you're not going to catch the error that is causing the crash, then > I think your only option is to restart your application with an > external program. > My understanding of using an external application to do this is to first create my module as an executable using py2exe. Then I have another python script that runs this module like this while (1): os.popen("program_module.exe") and make this other python script into another executable and execute this one. If Im not mistaken, when the python program crashes, the thread is killed. is this correct or how should I do it? Thanks again. Astan -------------- next part -------------- An HTML attachment was scrubbed... URL: From tkapoor at wscm.net Wed Jan 16 09:56:55 2008 From: tkapoor at wscm.net (Tarun Kapoor) Date: Wed, 16 Jan 2008 08:56:55 -0600 Subject: paramiko Message-ID: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> I am using paramiko to do an SFTP file transfer... I was able to connect to the remote server using an SFTP client I have just to make sure that username and password are working.. This is the code. # now, connect and use paramiko Transport to negotiate SSH2 across the connection sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) t = paramiko.Transport(sock) event = threading.Event() t.start_client(event) event.wait(15) if not t.is_active(): print 'SSH negotiation failed.' sys.exit(1) else: print "SSH negotiation sucessful" event.clear() t.auth_password(username=username, password=password,event=event) if not t.is_authenticated(): print "not authenticated" output: SSH negotiation successful not authenticated Tarun Waterstone Capital Management 2 Carlson Parkway, Suite 260 Plymouth, MN 55447 Direct: 952-697-4123 Cell: 612-205-2587 Disclaimer This e-mail and any attachments is confidential and intended solely for the use of the individual(s) to whom it is addressed. Any views or opinions presented are solely those of the author and do not necessarily represent those of Waterstone Capital Management, L.P and affiliates. If you are not the intended recipient, be advised that you have received this e-mail in error and that any use, dissemination, printing, forwarding or copying of this email is strictly prohibited. Please contact the sender if you have received this e-mail in error. You should also be aware that e-mails are susceptible to interference and you should not assume that the contents of this e-mail originated from the sender above or that they have been accurately reproduced in their original form. Waterstone Capital Management, L.P. and affiliates accepts no responsibility for information, or errors or omissions in this e-mail or use or misuse thereof. If in doubt, please verify the authenticity with the sender. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sromero at gmail.com Wed Jan 30 02:01:18 2008 From: sromero at gmail.com (Santiago Romero) Date: Tue, 29 Jan 2008 23:01:18 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> Message-ID: > how about > > >>> li = [1,2,3,4,5] > >>> filter(lambda x: x != 3, li) > [1, 2, 4, 5] I haven't measured it, but this should be the fast solution in all the thread ... From DustanGroups at gmail.com Wed Jan 16 20:13:38 2008 From: DustanGroups at gmail.com (Dustan) Date: Wed, 16 Jan 2008 17:13:38 -0800 (PST) Subject: anti-spam policy for c.l.py? References: <08ed32c4-6230-4b14-9c31-4b94e0231cf2@c4g2000hsg.googlegroups.com> <478dee4e$0$28424$426a34cc@news.free.fr> <478e1068$0$27280$426a34cc@news.free.fr> <63a12990-5e3f-4761-b0d3-785623199a7c@c4g2000hsg.googlegroups.com> Message-ID: <646b2724-4600-40c8-85c2-63775c1b1646@h11g2000prf.googlegroups.com> On Jan 16, 11:31 am, _wolf wrote: > On Jan 16, 3:11 pm, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > Jeroen Ruigrok van der Werven a ?crit : > > > > -On [20080116 12:51], Bruno Desthuilliers (bruno.42.desthuilli... at wtf.websiteburo.oops.com) wrote: > > >> Apart from checking posts headers and complaining about the relevant > > >> ISPs, there's not much you can do AFAIK. This is usenet, not a mailing-list. > > > > It is both actually. python-l... at python.org is linked to comp.lang.python due > > > to a news gateway. > > > Yes, I know - but the OP explicitely mentionned c.l.py (re-read the > > title), not the ML. > > technically correct, but the idea is of course to keep all those > archives relatively clean and informative. the new fad i've observed > seems to be to initiate whole threads where previously spam very often > stopped short of any second post. The ones that have received more than 2 responses have, the vast majority of the time, been cross posts. From fetchinson at googlemail.com Wed Jan 9 16:11:10 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 9 Jan 2008 13:11:10 -0800 Subject: Natural-language datetime parsing and display (was: user friendly datetime features) In-Reply-To: References: <873at7lq0d.fsf@benfinney.id.au> Message-ID: > For PARSING see http://code-bear.com/code/parsedatetime/ > > The OP was looking for presentation though. I know roundup has code for > this if an independent library can't be found. Thanks for all the responses! Indeed I was looking for presentation and not parsing, I'll take a look at roundup. Cheers, Daniel From python.list at tim.thechases.com Mon Jan 21 16:11:28 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 21 Jan 2008 15:11:28 -0600 Subject: Transforming ascii file (pseduo database) into proper database In-Reply-To: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> Message-ID: <47950A80.8060200@tim.thechases.com> > I need to take a series of ascii files and transform the data > contained therein so that it can be inserted into an existing > database. [snip] > I need to transform the data from the files before inserting > into the database. Now, this would all be relatively simple if > not for the following fact: The ascii files are each around > 800MB, [snip] > My questions are: > 1. Has anyone done anything like this before, and if so, do > you have any advice? Yes, I regularly do ETL on files from cellular providers to transform hundreds of megs worth (some approach a gig) of data into our internal system. > 2. In the abstract, can anyone think of a way of amassing all > the related data for a specific identifier from all the > individual files without pulling all of the files into memory > and without having to repeatedly open, search, and close the > files over and over again? if the file is sorted by something you can use, you can iterate over it and just deal with one grouping at a time. In my case, iterating over gobs of call-detail, the file happens to be sorted by the phone-number on the account. So I iterate over the file maintaining a list of calls for the given phonenumber, and when the phonenumber changes, I deal with the previous cache of data, then re-initialize with the new phone's data. Other ideas: 1) create a temp DB (such as sqlite), skim through the file inserting all your data into a table in this DB, then use DB functionality on it 2) in a light-weight way, assuming there's lots of data per row, and that you have multiple rows associated with a given ID (in my case, such as a phonenumber), you can create a dictionary of an ID to a list of file-offsets in which that ID is used. You can then skim through the file once gathering all the offsets with calls to tell() and then when you want to process an item, you can seek to that particular offset and read in the line. Not greatly efficient, but hackable. But mostly, it helps if you have a sorted field that's useful to you :) -tkc From toby at tobiah.org Wed Jan 16 14:58:14 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 16 Jan 2008 11:58:14 -0800 Subject: itertools.groupby In-Reply-To: <7xejcii3zb.fsf@ruckus.brouhaha.com> References: <478d0b7d$0$26094$88260bb3@free.teranews.com> <7xejcii3zb.fsf@ruckus.brouhaha.com> Message-ID: <478e55db$0$26033$88260bb3@free.teranews.com> Paul Rubin wrote: > Tobiah writes: >> I tried doing this with a simple example, but noticed >> that [].sort(func) passes two arguments to func, whereas >> the function expected by groupby() uses only one argument. > > Use: [].sort(key=func) Oh cool. Thanks. Only in 2.4+ it seems. >>> a = [1,2,3,4,5] >>> def sorter(thing): ... return thing % 2 == 0 ... >>> a.sort(key = sorter) >>> print a [1, 3, 5, 2, 4] >>> Nifty -- Posted via a free Usenet account from http://www.teranews.com From paddy3118 at googlemail.com Mon Jan 7 03:14:01 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 7 Jan 2008 00:14:01 -0800 (PST) Subject: Should HTML entity translation accept "&"? References: <47817BDC.7020707@animats.com> Message-ID: On Jan 7, 1:09 am, John Nagle wrote: > Another in our ongoing series on "Parsing Real-World HTML". > > It's wrong, of course. But Firefox will accept as HTML escapes > > & > > > < > > as well as the correct forms > > & > > > < > > To be "compatible", a Python screen scraper at > > http://zesty.ca/python/scrape.py > > has a function "htmldecode", which is supposed to recognize > HTML escapes and generate Unicode. (Why isn't this a standard > Python library function? Its inverse is available.) > > This uses the regular expression > > charrefpat = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?',re.UNICODE) > > to recognize HTML escapes. > > Note the ";?", which makes the closing ";" optional. > > This seems fine until we hit something valid but unusual like > > http://www.example.com?foo=1?? > > for which "htmldecode" tries to convert "1234567" into > a Unicode character with that decimal number, and gets a > Unicode overflow. > > For our own purposes, I rewrote "htmldecode" to require a > sequence ending in ";", which means some bogus HTML escapes won't > be recognized, but correct HTML will be processed correctly. > What's general opinion of this behavior? Too strict, or OK? > > John Nagle > SiteTruth Maybe htmltidy could help: http://tidy.sourceforge.net/ ? From paddy3118 at googlemail.com Mon Jan 28 02:24:22 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 27 Jan 2008 23:24:22 -0800 (PST) Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> <790eec65-c7dc-4a5e-bc1b-f9138d18eae0@1g2000hsl.googlegroups.com> Message-ID: <2577f982-523e-4ced-8e04-295a638d3b19@e10g2000prf.googlegroups.com> On Jan 28, 4:44 am, "Russ P." wrote: > On Jan 27, 5:41 pm, Roy Smith wrote: > > > > > In article > > , > > > ajaksu wrote: > > > On Jan 27, 10:32 pm, Paddy wrote: > > > > I would value the opinion of fellow Pythoneers who have also > > > > contributed to Wikipedia, on the issue of "Is Python Standardized". > > > > Specifically in the context of this table: > > > > http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Gene... > > > > (Comparison of programming languages) > > > > And this entry in the talk page > > > > http://en.wikipedia.org/wiki/Talk:Comparison_of_programming_languages... > > > > (Talk:Comparison of programming languages#Standardized Python?) > > > > > - Thanks. > > > > Hmmm. Seems to me that "Is X Standardized" in the given context means > > > having a formal, published standard issued by some Standards > > > organization. > > > That's exactly what it means. For example, if I'm buying a C++ compiler, I > > can specify in the contract, "Must comply with ISO 14882", and everybody > > will know what I'm talking about. > > > On the other side of the fence, if I'm a free-lance C++ developer, I can > > specify to my customers that the code I write will work properly when > > compiled with a compiler that meets ISO 14882. Whether such a compiler > > actually exists, is besides the point :-) > > > Python has no such standard. Sure, there's the stuff on docs.python.org, > > but it's kind of hard to write a contract which says, "Must comply with the > > stuff on docs.python.org", and have it be meaningful in a legal sense. > > > So, I think the "No" in the "Standardized?" column for python is exactly > > right. That's not to say you can't have something good which isn't > > standardized. Sometimes standards committees even go off into left field > > and field break stuff in the process of standardizing it. Some things have > > so many different standards (i.e. the pletora of unix standards), it's > > almost worthless to say it's standardized. But, as it stands, the > > Wikipedia article is correct. > > I agree. As far as I know, Python is not formally > "standardized" by any recognized standards > authority such as ANSI or ISO. (If it were, it > wouldn't have a "BDFL.") > > For most domains in which Python is used, that is > not an issue, but for some potential uses it could > be (e.g., safety-critical). > > FWIW, the "most" standardized language is probably > Ada. Not only does it have a formal written > standard, but I believe it also has a formal > suite of tests that a standard Ada compiler is > required to pass. [For some reason, Ada does not > get the respect or the attention it deserves, but > that's another topic.] Thanks Roy, Russ. I agree that Python is not standardized the way other languages are. But still, I look at the table, read the article linked as the column header, and can see that their is discrepancy. The column header links to the article on standardization: http://en.wikipedia.org/wiki/Standardization Which has a definition of standardization which is very different from what you may cite. I read the column headings article and just can't help feeling that Python conforms to *that* definition. - Paddy. From rong.xian at gmail.com Wed Jan 23 22:49:01 2008 From: rong.xian at gmail.com (glacier) Date: Wed, 23 Jan 2008 19:49:01 -0800 (PST) Subject: Some questions about decode/encode Message-ID: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> I use chinese charactors as an example here. >>>s1='???' >>>repr(s1) "'\\xc4\\xe3\\xba\\xc3\\xc2\\xf0'" >>>b1=s1.decode('GBK') My first question is : what strategy does 'decode' use to tell the way to seperate the words. I mean since s1 is an multi-bytes-char string, how did it determine to seperate the string every 2bytes or 1byte? My second question is: is there any one who has tested very long mbcs decode? I tried to decode a long(20+MB) xml yesterday, which turns out to be very strange and cause SAX fail to parse the decoded string. However, I use another text editor to convert the file to utf-8 and SAX will parse the content successfully. I'm not sure if some special byte array or too long text caused this problem. Or maybe thats a BUG of python 2.5? From remco at gerlich.nl Thu Jan 17 07:35:48 2008 From: remco at gerlich.nl (Remco Gerlich) Date: Thu, 17 Jan 2008 13:35:48 +0100 Subject: Loop in a loop? In-Reply-To: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <7ae3ca10801170435x8803cc0rad2c3453c503a0a0@mail.gmail.com> Use zip() to combine them into a single list, then loop over that: for x, y in zip(array1, array2): ... Remco On Jan 17, 2008 1:21 PM, Sacred Heart wrote: > Hi, > I'm new to Python and have come across a problem I don't know how to > solve, enter com.lang.python :) > > I'm writing some small apps to learn the language, and I like it a lot > so far. > > My problem I've stumbled upon is that I don't know how to do what I > want. I want to do a loop in a loop. I think. > > I've got two arrays with some random stuff in, like this. > > array1 = ['one','two','three','four'] > array2 = ['a','b','c','d'] > > I want to loop through array1 and add elements from array2 at the end, > so it looks like this: > > one a > two b > three c > four c > > I'm stuck. I know how to loop through the arrays separatly and print > them, but both at the same time? Hmmm. > > A push in the right direction, anyone? > > R, > SH > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Tue Jan 15 19:00:25 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 15 Jan 2008 16:00:25 -0800 (PST) Subject: Data mapper - need to map an dictionary of values to a model References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com> <2d59f289-2def-43a8-93b7-f326b8f12066@z17g2000hsg.googlegroups.com> Message-ID: On Jan 15, 6:53 pm, George Sakkis wrote: > name_tranformer = lambda input: dict( > zip(('first_name', 'last_name'), > input['name'])) Of course that should write: name_tranformer = lambda input: dict( zip(('first_name', 'last_name'), input['name'].split())) George From workitharder at gmail.com Tue Jan 1 12:45:00 2008 From: workitharder at gmail.com (bukzor) Date: Tue, 1 Jan 2008 09:45:00 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <6aba9463-f0ea-43a2-b8de-9c7026c4d14e@e4g2000hsg.googlegroups.com> <5c6a5515-a6ee-455d-83d4-48b2a2ae46c3@n20g2000hsh.googlegroups.com> <579f378d-d948-4c99-8507-a8c4e9a28096@i29g2000prf.googlegroups.com> Message-ID: <74a7edcf-f4ea-4835-b08e-499faaed8d81@i12g2000prf.googlegroups.com> On Jan 1, 9:00 am, bukzor wrote: > On Dec 31 2007, 1:30 pm, "Chris Mellon" wrote: > > > > > On Dec 31, 2007 2:08 PM, Odalrick wrote: > > > > On 31 Dec, 18:22, Arnaud Delobelle wrote: > > > > On Dec 31, 10:58 am, Odalrick wrote: > > > > > > On 30 Dec, 17:26, George Sakkis wrote: > > > > > > > On Dec 29, 9:14 pm, bukzor wrote: > > > > > > > > Here's the answer to the question:http://www.python.org/doc/faq/general/#why-are-default-values-shared-... > > > > > > > > It looks like Guido disagrees with me, so the discussion is closed. > > > > > > > Note that the FAQ mainly explains *what* happens, not *why* was this > > > > > > decision taken. Although it shows an example where "this feature can > > > > > > be useful", it's neither the only way to do it nor is memoization as > > > > > > common as wanting fresh default arguments on every call. > > > > > > I'm surprised noone has said anything about the why of default > > > > > mutables. I think it is becasue it isn't easy to do it an other way. > > > > > [...] > > > > > There is an easy enough way: evaluate default values when the function > > > > is called rather than when it is defined. This behaviour comes with > > > > its own caveats as well I imagine, and it's not 'as easy' to implement > > > > as the current one. > > > > Adding overhead to *all* function calls, even the ones without mutable > > > defaults. That doesn't sound like an attractive tradeoff. > > > And also removing the only way you can currently do early binding in > > Python. I agree that it's a gotcha, but unless someone comes up with > > an answer to the following questions, I'll stick with the status quo > > (Note that this is not blind Python group-think as a previous poster > > implied, but a pragmatic decision that this is the most practical > > solution): > > > a) If we don't evaluate default arguments at function compilation, > > when do we do it? > > b) If you do it at call time, how do you implement early binding? > > c) If you want to introduce new syntax for the current behavior, what > > is it and can you justify it? > > d) What are the performance implications of your proposal versus the > > current behavior? > > > Note that the desired behavior can be implemented under the current > > behavior, at the expense of verbosity - using factories and sentinel > > values as the default arguments, and then expanding them in the > > function. It's not possible to implement the current behavior of > > early-bound arguments if default arguments are evaluated with every > > call. This alone is a good reason to keep the current behavior until > > someone actually has a good alternative that covers the current use > > cases and isn't just upset by the behavior. > > I'm confused by what you mean by 'early binding'. Can you give a quick- > n-dirty example? > > Thanks, > --Buck Is an 'early bound' variable synonymous with a 'static' variable (in C)? From arnodel at googlemail.com Thu Jan 24 02:25:30 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 23:25:30 -0800 (PST) Subject: Smart factory class References: Message-ID: On Jan 24, 7:11?am, kramer31 wrote: > Can anyone tell me if there is a way in python that I can implement a > factory function which takes as input a string ClassName and returns > an object of type ClassName? >>> def mkobj(classname, ns=globals()): return ns[classname]() ... >>> class A: pass ... >>> mkobj('A') <__main__.A instance at 0x6bd28> >>> But why do you want to do this? -- Arnaud From paddy3118 at googlemail.com Fri Jan 11 22:26:26 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 11 Jan 2008 19:26:26 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: On Jan 11, 8:55 pm, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of cesco > > Sent: Wednesday, January 09, 2008 5:34 AM > > To: python-l... at python.org > > Subject: alternating string replace > > > Hi, > > > say I have a string like the following: > > s1 = 'hi_cat_bye_dog' > > and I want to replace the even '_' with ':' and the odd '_' with ',' > > so that I get a new string like the following: > > s2 = 'hi:cat,bye:dog' > > Is there a common recipe to accomplish that? I can't come up with any > > solution... > > For those of us who still think in Perl, here's an easy to read, lazy > solution: > > s = 'hi_cat_bye_dog' > print s > s = re.sub(r'_(.*?(_|$))', r':\1', s) ## every odd '_' to ':' > print s > s = re.sub(r'_', r',', s) ## every even '_' to ',' > print s > > > hi_cat_bye_dog > > hi:cat_bye:dog > > hi:cat,bye:dog > > The equivalent Perl code: > my $s = 'hi_cat_bye_dog'; > > print $s, "\n"; > $s =~ s/_(.*?(_|$))/:$1/g; > print $s, "\n"; > $s =~ s/_/,/g; > print $s, "\n"; def altrep8(s): import re s = re.sub(r'_(.*?(_|$))', r':\1', s) ## every odd '_' to ':' return re.sub(r'_', r',', s) ## every even '_' to ',' altrep8.author="Reedick, Andrew" Gives: ## Program by: Reedick, Andrew '' RETURNS '' '1' RETURNS '1' '2_' RETURNS '2:' '3_4' RETURNS '3:4' '5_6_' RETURNS '5:6,' '7_8_9' RETURNS '7:8,9' '10_11_12_' RETURNS '10:11,12:' '13_14_15_16' RETURNS '13:14,15:16' '17_18_19_20_' RETURNS '17:18,19:20,' '_' RETURNS ':' '_21' RETURNS ':21' '_22_' RETURNS ':22,' '_23_24' RETURNS ':23,24' '_25_26_' RETURNS ':25,26:' '_27_28_29' RETURNS ':27,28:29' '_30_31_32_' RETURNS ':30,31:32,' '_33_34_35_36' RETURNS ':33,34:35,36' '__' RETURNS ':,' '___' RETURNS ':,:' '____' RETURNS ':,:,' '_____' RETURNS ':,:,:' From kvutza at gmail.com Sun Jan 27 09:23:50 2008 From: kvutza at gmail.com (Martin Saturka) Date: Sun, 27 Jan 2008 06:23:50 -0800 (PST) Subject: Python System information References: Message-ID: <35d49700-9def-478e-8047-de548553e8c0@s8g2000prg.googlegroups.com> > How can i get system information like CPU load and RAM usage in linux. What about 'pystatgrab'? It provides good info, with a limitation - it does not have CPU info for particular CPUs, it takes just the cumulative CPU info. http://www.i-scream.org/pystatgrab/ http://packages.debian.org/statgrab M. From steve at holdenweb.com Thu Jan 31 19:15:00 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 19:15:00 -0500 Subject: Design question - Sharing of single object by multiple processes In-Reply-To: <2b54d4370801311423y52904ed9o1e26ac98dced45c6@mail.gmail.com> References: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> <47A1AC61.7080007@holdenweb.com> <2b54d4370801311206j457ef51cm33d2a2420b11e688@mail.gmail.com> <2b54d4370801311208s4af458cdp8cea665a04c3bd7a@mail.gmail.com> <2b54d4370801311423y52904ed9o1e26ac98dced45c6@mail.gmail.com> Message-ID: Mike D wrote: > Steve, > > You raise some very good (and obvious) issues I did'nt consider. I'll > look further into this sort of implementation as I'm quite interested. > > I suppose a compromise could be to load the objects from a pickle, that > may have issues in terms of updating the pickle perhaps, though it would > be much safer. > > I'll continue to investigate, thanks for your input. > No problem - I've had a long time to think about these things. You might also want to investigate the ConfigParser module, or Michael Foord's ConfigObj. In practice it would have to be a pretty complex configuration to make it worth pre-compiling it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stefan.behnel-n05pAM at web.de Thu Jan 24 16:35:57 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 24 Jan 2008 22:35:57 +0100 Subject: Sorting Large File (Code/Performance) In-Reply-To: References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> Message-ID: <479904BD.9090400@web.de> Ira.Kovac at gmail.com wrote: >> What are you going to do with it after it's sorted? > I need to isolate all lines that start with two characters (zz to be > particular) "Isolate" as in "extract"? Remove the rest? Then why don't you extract the lines first, without sorting the file? (or sort it afterwards if you still need to). That would heavily cut down your memory footprint. Stefan From paddy3118 at googlemail.com Wed Jan 9 17:03:23 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 14:03:23 -0800 (PST) Subject: alternating string replace: Extended input (Long). References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: On Jan 9, 9:39 pm, Fredrik Lundh wrote: > Paddy wrote: > > To see how they act against 'corner cases' and > > an exercise for me in trying to create corner cases. (I'm in to > > functional testing at the mo'). > > sounds more like "pulling requirements out of thin air". not sure that > helps the OP get a better understanding of Python, really. > > Not really out of thin air. The OP transforming alternating occurrences of _ so corners would include a null string; strings with 1, 2 and 3 occurrences of the character to be replaced and the char to be replaced separated or not by other chars.... Ideally I would create a randomized interesting string generator and try each prog against a lot of generated examples and computed 'correct' answers, but I am unsure of what should be the right answer in some cases so the earlier posting can be used to give extra information for the spec. to be fleshed out with. You may be right in that the OP might see the extended input and dismiss them because he knows that the input data is never going to be like that - or - he may find that his input validation might well allow some of the cases through and he needs to either improve his input validation or define what to do with more types of input. Your also right in that its mostly not Python specific but it helps me think of corner cases and the interpretation of specs which is very important in helping solve the right problem. - Paddy. From grante at visi.com Fri Jan 4 16:08:00 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 04 Jan 2008 21:08:00 -0000 Subject: Question on os.tempnam() vulnerability References: Message-ID: <13nt81gftkfa32d@corp.supernews.com> On 2008-01-04, Fredrik Lundh wrote: > you get a name instead of a file, so someone else can create that file > after you've called tempnam/tmpnam, but before you've actually gotten > around to create the file yourself. which means that anyone on the > machine might be able to mess with your application's data. > > use the functions marked as "safe" in the tempfile module instead. Under Windows, is there a "safe" way to create a temp file that has a name that can be passed to a program which will then open it? I never figured out a way to do that and had to fall back on the "unsafe" tmpnam method. -- Grant Edwards grante Yow! I have seen these EGG at EXTENDERS in my Supermarket visi.com ... I have read the INSTRUCTIONS ... From martin at v.loewis.de Mon Jan 7 18:02:56 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 Jan 2008 00:02:56 +0100 Subject: What is the encoding of __file__? In-Reply-To: References: <736ae822-54a9-4ee6-91fe-92c2c6eb43db@21g2000hsj.googlegroups.com> <4782A255.8070604@v.loewis.de> Message-ID: <4782afa0$0$8649$9b622d9e@news.freenet.de> > Thanks, I'll then use sys.getfilesystemencoding() to decode _file__ > and re-encode into utf-8, which is the default encoding of all strings > in our software, as we deal a bit with Chinese terms. > > Windows-1252 on my box. I just created a directory containing Chinese > characters (on Vista), and whoa, files opened with IDLE are empty, > import doesn't find modules in that directory. Of course Windows-1252 > can't encode these ... > > But I understand that Python 3 will clean this up? In theory, yes. The current implementation doesn't. Contributions are welcome. Regards, Martin From ptmcg at austin.rr.com Tue Jan 29 07:38:28 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 29 Jan 2008 04:38:28 -0800 (PST) Subject: Error in parsing XML for following test data References: <479F03ED.6080308@web.de> Message-ID: <88a2fad8-d125-4946-a57e-d055c0649973@l1g2000hsa.googlegroups.com> On Jan 29, 4:46?am, Stefan Behnel wrote: > > How is this related to XML? > > Stefan I guess that's what makes so **nasty**! -- Paul From larry.bates at websafe.com Wed Jan 23 12:15:41 2008 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 23 Jan 2008 11:15:41 -0600 Subject: csv to xls using python 2.1.3 In-Reply-To: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> Message-ID: <4797763D.70604@websafe.com> LizzyLiz wrote: > Hi > > I need to convert a .csv file to .xls file using python 2.1.3 which > means I can't use pyExcelerator! Does anyone know how I can do this? > > Many thanks > LizzyLiz FYI - Excel can read .CSV files directly and convert them to .XLS. -Larry From mcfletch at vrplumber.com Sun Jan 20 10:48:12 2008 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Sun, 20 Jan 2008 10:48:12 -0500 Subject: TopSort in Python? In-Reply-To: <1deb5d71-a514-44d8-ae9e-dc320155628a@d21g2000prf.googlegroups.com> References: <0000161d@bossar.com.pl> <358cc5a3-300f-49ba-9857-2f0cd629a4df@i12g2000prf.googlegroups.com> <12f0f54e-5d30-40bc-9135-2c59b8a5acc2@i3g2000hsf.googlegroups.com> <1deb5d71-a514-44d8-ae9e-dc320155628a@d21g2000prf.googlegroups.com> Message-ID: <47936D3C.8090509@vrplumber.com> Paddy wrote: ... > I searched for dependancy sort, and later dependency sort (cos I > couldn't spell). I had convinced that I was using the right term and > was flummoxed by the lack of hits. Even today the term topological > sort means far less than what it describes: sorting items based on > their interdependencies. > "dependency sort python" typed into Google today gives a post pointing to http://www.vrplumber.com/programming/ (which has Tim and my algorithms (toposort.py)) as the second link... vagaries of Google I suppose. > Is this a case of something being named after its mathematical/ > technical description and so obscuring its wider practical use cases? > Could be, I tried to make sure that the word dependency was in the description on the download page (since I had the same problem starting out (I implemented the algorithm before I knew the name IIRC)). > P.S. we have revived a thread started in 1999! > For some of us 1999 is well into our Pythonic life-cycle :) Have fun, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From bladedpenguin at gmail.com Mon Jan 28 19:18:28 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Mon, 28 Jan 2008 16:18:28 -0800 (PST) Subject: Executing other python code Message-ID: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> I'm working on a game, and I'd like players to be able to define thier ships with scripts. Naturally, I don't want to give them the entire program as thier romping ground. I would like to invoke a seperate interpreter for these files, and give it a limited subset of the functions in my game. What is the best way to achieve this effect? From terry at jon.es Mon Jan 21 04:12:54 2008 From: terry at jon.es (Terry Jones) Date: Mon, 21 Jan 2008 10:12:54 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 23:21:04 on Sunday, 20 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> Message-ID: <18324.25110.878721.763191@terry.local> >>>>> "Arnaud" == Arnaud Delobelle writes: Arnaud> In countdown you are not required to use all numbers to reach the Arnaud> target. This means you are missing solutions, e.g. (1, 3, 6, Arnaud> 'mul', 'add', 7 , 'add', 9, 'mul') Hi Arnaud. Thanks, I didn't know that. The fix is a simple change to the first if my function below. WRT to the missing solution, note that my code only allowed multiplication by 1 if it was the last thing done. That was because you can multiply by 1 at any time, and I didn't want to see those trivially equivalent solutions (same goes for adding 0). Seeing as you're allowed to omit numbers, I've now gotten rid of those trivial operations altogether in my solution. Code and output below. Terry from operator import * def countdown(target, nums, numsAvail, value, partialSolution, solutions, ops=(add, mul, sub, div)): if value == target or not any(numsAvail): # Ran out of available numbers. Add the solution, if we're right. if value == target: solutions.add(tuple(partialSolution)) elif value is None: # Use each distinct number as a starting value. used = set() for i, num in enumerate(nums): if num not in used: numsAvail[i] = False used.add(num) partialSolution.append(num) countdown(target, nums, numsAvail, num, partialSolution, solutions, ops) numsAvail[i] = True partialSolution.pop() else: for op in ops: for i, num in enumerate(nums): if numsAvail[i]: numsAvail[i] = False moreAvail = any(numsAvail) try: lastNum, lastOp = partialSolution[-2:] except ValueError: lastNum, lastOp = partialSolution[-1], None # Don't allow any of: if not any(( # Div: after mul, by 1, by 0, producing a fraction. (op == div and (lastOp == 'mul' or num <= 1 or value % num != 0)), # If initial mul/add, canonicalize to 2nd operator biggest. ((op == mul or op == add) and lastOp is None and num > lastNum), # Don't allow add or sub of 0. ((op == add or op == sub) and num == 0), # Don't allow mult by 1. (op == mul and num == 1), # Don't allow sub after add (allow add after sub). (op == sub and lastOp == 'add'), # If same op twice in a row, canonicalize operand order. (lastOp == op.__name__ and num > lastNum) )): partialSolution.extend([num, op.__name__]) countdown(target, nums, numsAvail, op(value, num), partialSolution, solutions, ops) del partialSolution[-2:] numsAvail[i] = True for nums, target in (((100, 9, 7, 6, 3, 1), 253), ((100, 9, 7, 6, 3, 1), 234), ((2, 3, 5), 21), ((7, 8, 50, 8, 1, 3), 923), ((8, 8), 16), ((8, 8, 8), 8), ((8, 0), 8), ((7,), 8), ((), 8), ((8, 8, 8, 8), 32)): solutions = set() countdown(target, nums, [True,] * len(nums), value=None, partialSolution=[], solutions=solutions) print "%d solutions to: target %d, numbers = %s" % (len(solutions), target, nums) for s in sorted(solutions, cmp=lambda a, b: cmp(len(a), len(b)) or cmp(a, b)): print '\t', s $ time countdown.py 8 solutions to: target 253, numbers = (100, 9, 7, 6, 3, 1) (6, 3, 'mul', 1, 'sub', 9, 'mul', 100, 'add') (7, 6, 'mul', 9, 'add', 3, 'mul', 100, 'add') (9, 3, 'sub', 7, 'mul', 6, 'mul', 1, 'add') (100, 9, 'sub', 7, 'sub', 3, 'mul', 1, 'add') (3, 1, 'add', 6, 'mul', 7, 'sub', 9, 'mul', 100, 'add') (7, 1, 'add', 6, 'mul', 3, 'mul', 100, 'add', 9, 'add') (7, 6, 'add', 3, 'add', 1, 'add', 9, 'mul', 100, 'add') (100, 7, 'sub', 6, 'sub', 3, 'mul', 9, 'sub', 1, 'add') 19 solutions to: target 234, numbers = (100, 9, 7, 6, 3, 1) (6, 3, 'mul', 7, 'add', 1, 'add', 9, 'mul') (7, 1, 'add', 9, 'mul', 6, 'add', 3, 'mul') (7, 3, 'mul', 1, 'sub', 6, 'add', 9, 'mul') (7, 6, 'mul', 3, 'mul', 100, 'sub', 9, 'mul') (100, 1, 'sub', 3, 'div', 7, 'sub', 9, 'mul') (100, 1, 'sub', 7, 'mul', 9, 'add', 3, 'div') (100, 7, 'mul', 3, 'mul', 6, 'add', 9, 'div') (100, 9, 'sub', 7, 'div', 6, 'mul', 3, 'mul') (100, 9, 'sub', 7, 'sub', 6, 'sub', 3, 'mul') (6, 1, 'add', 100, 'mul', 7, 'sub', 9, 'add', 3, 'div') (6, 9, 'sub', 7, 'mul', 1, 'sub', 100, 'add', 3, 'mul') (7, 3, 'mul', 6, 'sub', 9, 'mul', 1, 'sub', 100, 'add') (7, 6, 'mul', 3, 'mul', 1, 'sub', 100, 'add', 9, 'add') (100, 1, 'sub', 3, 'div', 7, 'mul', 6, 'sub', 9, 'add') (100, 1, 'sub', 7, 'mul', 9, 'sub', 3, 'div', 6, 'add') (100, 7, 'mul', 6, 'sub', 1, 'sub', 9, 'add', 3, 'div') (100, 7, 'sub', 3, 'div', 1, 'sub', 9, 'add', 6, 'mul') (100, 7, 'sub', 3, 'div', 6, 'sub', 1, 'add', 9, 'mul') (100, 9, 'add', 7, 'add', 1, 'add', 3, 'div', 6, 'mul') 1 solutions to: target 21, numbers = (2, 3, 5) (5, 2, 'add', 3, 'mul') 1 solutions to: target 923, numbers = (7, 8, 50, 8, 1, 3) (50, 8, 'mul', 1, 'sub', 3, 'div', 7, 'mul', 8, 'sub') 1 solutions to: target 16, numbers = (8, 8) (8, 8, 'add') 1 solutions to: target 8, numbers = (8, 8, 8) (8,) 1 solutions to: target 8, numbers = (8, 0) (8,) 0 solutions to: target 8, numbers = (7,) 0 solutions to: target 8, numbers = () 1 solutions to: target 32, numbers = (8, 8, 8, 8) (8, 8, 'add', 8, 'add', 8, 'add') real 0m1.423s user 0m1.371s sys 0m0.047s From george.sakkis at gmail.com Mon Jan 14 18:09:08 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 14 Jan 2008 15:09:08 -0800 (PST) Subject: SyntaxError: 'import *' not allowed with 'from .' References: <9ac37212-7521-454d-a35f-afd6f7ec24f6@m34g2000hsf.googlegroups.com> <87ve5wdnbg.fsf@benfinney.id.au> Message-ID: <8d86398a-a16e-4e73-9d22-7a58bc234f91@s8g2000prg.googlegroups.com> On Jan 14, 6:01 pm, Ben Finney wrote: > George Sakkis writes: > > Unless I missed it, PEP 328 doesn't mention anything about this. > > What's the reason for not allowing "from .relative.module import *' > > ? > > It makes the code much harder to follow visually and inspect with > static analysis tools, since there's no way to see where names come > from in the code. It defeats the purpose of separate namespaces, > confusing the imported module's names with the current module's names > in a way that makes the indistinguishable. > > If you want to use all or most of the names in a module, keep them in > their own namespace: > > import spam > import eggs > > spam.do_stuff() > eggs.do_stuff() > > If you don't like the name of the module, then use whatever one suits > you: > > import your_mother_was_a_hamster as spam > import your_father_smelled_of_elderberries as eggs > > spam.do_stuff() > eggs.do_stuff() > > Both of these are superior to 'from spam import *' because it's clear > (to the reader and to static analysis tools) where every name comes > from: unqualified names must be defined in the current module, any > ones from the imported module are qualified with the module name. > > You also, in cases like the above example, avoid unknowingly > clobbering existing names by importing from another module into the > current namespace. All the above are well-known and apply to both absolute and relative imports. I was asking why it's a syntax error specifically for relative imports. George From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 19:15:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 00:15:44 -0000 Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> Message-ID: <13og1lgcespv6c2@corp.supernews.com> On Fri, 11 Jan 2008 08:29:18 -0800, dg.google.groups wrote: > Hi all, > > I'm part of a small team writing a Python package for a scientific > computing project. The idea is to make it easy to use for relatively > inexperienced programmers. ... > This is fine, but we decided that for clarity of these programs, and to > make it easier for inexperienced programmers, we would like to be able > to write something like: > > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > run() > > The idea is that the run() function inspects the stack, and looks for > object which are instances of class Obj, creates a Bigobj with those > objects and calls its run() method. > > So, any comments on that approach? Your users are *scientists*, and you don't trust their intellectual ability to learn a programming language as simple as Python? Instead of spending time and effort writing, debugging and maintaining such a fragile approach, why not invest in a couple of introductory books on Python programming and require your scientists to go through the first few chapters? Or write out a one-page "cheat sheet" showing them simple examples. Or, and probably most effectively, make sure all your classes have doc strings with lots of examples, and teach them how to use help(). Some people problems are best dealt with by a technical solution, and some are not. -- Steven From deets at nospam.web.de Tue Jan 29 17:45:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jan 2008 23:45:07 +0100 Subject: breaking out of outer loops In-Reply-To: References: Message-ID: <609ojrF1phb32U1@mid.uni-berlin.de> noemailplease0001 at gmail.com schrieb: > Any elegant way of breaking out of the outer for loop than below, I > seem to have come across something, but it escapes me > > for i in outerLoop: > for j in innerLoop: > if condition: > break > else: > continue > break It's working because for-loops else statements are are executed only if the loop hasn't been terminated unexpectedly. Which is what happens here: if the inner loop is breaked, it's else is not executed. So the outer loop's break is called. Diez From jgardner at jonathangardner.net Thu Jan 24 16:41:04 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 24 Jan 2008 13:41:04 -0800 (PST) Subject: a newbie regex question References: Message-ID: <4227b8d4-c2c7-4395-97a3-5aadcec94b7d@p69g2000hsa.googlegroups.com> On Jan 24, 12:14 pm, Shoryuken wrote: > Given a regular expression pattern, for example, \([A-Z].+[a-z]\), > > print out all strings that match the pattern in a file > > Anyone tell me a way to do it? I know it's easy, but i'm completely > new to python > > thanks alot You may want to read the pages on regular expressions in the online documentation: http://www.python.org/doc/2.5/lib/module-re.html The simple approach works: import re # Open the file f = file('/your/filename.txt') # Read the file into a single string. contents = f.read() # Find all matches in the string of the regular expression and iterate through them. for match in re.finditer(r'\([A-Z].+[a-z]\)', contents): # Print what was matched print match.group() From odysseus1479-at at yahoo-dot.ca Sat Jan 12 23:15:06 2008 From: odysseus1479-at at yahoo-dot.ca (Odysseus) Date: Sun, 13 Jan 2008 04:15:06 GMT Subject: Elementary string-formatting Message-ID: Hello, group: I've just begun some introductory tutorials in Python. Taking off from the "word play" exercise at I've written a mini-program to tabulate the number of characters in each word in a file. Once the data have been collected in a list, the output is produced by a while loop that steps through it by incrementing an index "i", saying print '%2u %6u %4.2f' % \ (i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0]) My problem is with the last entry in each line, which isn't getting padded: 1 0 0.00 2 85 0.07 3 908 0.80 4 3686 3.24 5 8258 7.26 6 14374 12.63 7 21727 19.09 8 26447 23.24 9 16658 14.64 10 9199 8.08 11 5296 4.65 12 3166 2.78 13 1960 1.72 14 1023 0.90 15 557 0.49 16 261 0.23 17 132 0.12 18 48 0.04 19 16 0.01 20 5 0.00 21 3 0.00 I've tried varying the number before the decimal in the formatting string; "F", "g", and "G" conversions instead of "f"; and a couple of other permutations (including replacing the arithmetical expression in the tuple with a variable, defined on the previous line), but I can't seem to get the decimal points to line up. I'm sure I'm missing something obvious, but I'd appreciate a tip -- thanks in advance! FWIW I'm running Python 2.3.5 (#1, Oct 5 2005, 11:07:27) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin from the Terminal on Mac OS X v10.4.11. P.S. Is there a preferable technique for forcing floating-point division of two integers to that used above, multiplying by "100.0" first? What about if I just wanted a ratio: is "float(n / m)" better than "1.0 * n / m"? -- Odysseus From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 21:52:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 02:52:33 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: <13ogarhbepg9l29@corp.supernews.com> On Fri, 11 Jan 2008 09:55:08 -0800, sturlamolden wrote: > It seems the code he is referring to is doing k-means clustering on each > frame. The clustering is done by from SciPy's cluster module, which is > doing 'vector quantitization'. The algorithm is written in plain C. It > is not Python that is slow. It is the amount of processing done on each > frame. As the bottleneck is already in C, it cannot be done any faster > without radically changing the algorithm and/or the hardware. Thank you for taking the effort to actually investigate the OP's *actual* problem. Such a pity that the chances are he's probably gone away in disgust at the pedantry and insults in this thread. He'll probably become another one of those people convinced that Python is "slow" because it's interpreted when in fact this is an example of C being slow in spite of being compiled. -- Steven From tommy.nordgren at comhem.se Wed Jan 9 00:33:16 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Wed, 9 Jan 2008 06:33:16 +0100 Subject: Default location of python on OS X In-Reply-To: <1519661f-97bd-4fdd-b2d5-a46dd9a81c81@e25g2000prg.googlegroups.com> References: <1519661f-97bd-4fdd-b2d5-a46dd9a81c81@e25g2000prg.googlegroups.com> Message-ID: <830C7771-6EB1-48FC-9A96-D34266C15E4C@comhem.se> On 9 jan 2008, at 04.43, Stephen_B wrote: > I've installed the latest 2.5 python today from python.org, and I > think it ended up in "/Applications/MacPython 2.5". > > I also have a "/Applications/MacPython 2.4" and a "/Applications/ > MacPython-2.4". Can I delete these, or did one of them come with > Leopard? > > I still have a "/Library/Python/2.3" and a "/Library/Python/2.5". > > Thanks. > > Stephen > -- > http://mail.python.org/mailman/listinfo/python-list Leopard INCLUDES Python 2.5, there is no need to install it. ------------------------------------- This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren tommy.nordgren at comhem.se From siona at chiark.greenend.org.uk Wed Jan 30 08:03:08 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Jan 2008 13:03:08 +0000 (GMT) Subject: refcount References: Message-ID: Benjamin wrote: >> [ help(sys.getrefcount) says: ] >> [ ... ] The count returned is generally >> one higher than you might expect, because it includes the (temporary) >> reference as an argument to getrefcount(). >Are there any cases when it wouldn't? When the temporary reference which is the argument to getrefcount is the *only* reference, eg: >>> sys.getrefcount (set()) 1 The return value for a weakly referenced object may also be not what you "expect": >>> s = set() >>> sys.getrefcount(s) 2 >>> r = weakref.ref(s) >>> r() is s True >>> sys.getrefcount(r()) 2 -- \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 rong.xian at gmail.com Sun Jan 27 05:18:48 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 02:18:48 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <5vr1ekF1njt09U2@mid.uni-berlin.de> Message-ID: <84f39f37-4d18-47c1-9349-bf3f471b2bf5@s19g2000prg.googlegroups.com> On 1?24?, ??4?44?, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote: > > My second question is: is there any one who has tested very long mbcs > > decode? I tried to decode a long(20+MB) xml yesterday, which turns out > > to be very strange and cause SAX fail to parse the decoded string. > > That's because SAX wants bytes, not a decoded string. Don't decode it > yourself. > > > However, I use another text editor to convert the file to utf-8 and > > SAX will parse the content successfully. > > Because now you feed SAX with bytes instead of a unicode string. > > Ciao, > Marc 'BlackJack' Rintsch Yepp. I feed SAX with the unicode string since SAX didn't support my encoding system(GBK). Is there any way to solve this better? I mean if I shouldn't convert the GBK string to unicode string, what should I do to make SAX work? Thanks , Marc. :) From Scott.Daniels at Acm.Org Tue Jan 1 18:16:40 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 01 Jan 2008 15:16:40 -0800 Subject: confusion about package/module imports In-Reply-To: References: <13nlc7fecs63099@corp.supernews.com> Message-ID: <13nli6lenc9vdc1@corp.supernews.com> Jugdish wrote: > Thanks very much for your helpful response! > >> You'll see that b is executed (making module __main__), >> (1) it imports pkg.subpkg.a, >> (2) which is accomplished by importing pkg (successfully), >> (3) then by importing pkg.subpkg >> (4) which imports pkg.subpkg.a (successfully) >> (5) and then imports pkg.subpkg.b >> (6) which then attempts to import pkg.subpkg.a > > What I'm not really understanding here is why this fails at lines (5) > and (6). If pkg.subpkg.a has already been successfully imported at > line (4), then (6) should be detected as a duplicate import and just > be skipped, right? So the import at line (5) should succeed. I'm sorry, I used shorthand. While a module is being imported, it only provisionally has a name. Until subpkg is fully imported, there is no module named pkg.subpkg. At the root level (pkg, for example), the module is provisionally added. Further down the tree, the module (such as that for pkg/subpkg/__init__.py) is only added to the symbol table (the packages __dict__) when the module has been completely imported. -Scott From Rens.Duijsens at gmail.com Mon Jan 28 04:12:12 2008 From: Rens.Duijsens at gmail.com (Dox33) Date: Mon, 28 Jan 2008 01:12:12 -0800 (PST) Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> <87dd811e-3095-41d0-80fd-7312338e5254@i3g2000hsf.googlegroups.com> <489b6fc5-e871-425e-b242-45be618fc9f4@n20g2000hsh.googlegroups.com> <87r6g4q7hq.fsf@mulj.homelinux.net> Message-ID: <37633f9e-64c1-406f-9e30-d9b56f2a61cc@u10g2000prn.googlegroups.com> YES! This is what I was looking for. Great! All works fine now. Thank you very much Gabriel. Gabriel Genellina schreef: > Add this on your sitecustomize.py module (or create one) > > import sys > def raw_input(prompt=None): > if prompt: sys.stdout.write(prompt) > return original_raw_input() > > import __builtin__ > original_raw_input = __builtin__.raw_input > __builtin__.raw_input = raw_input > > It just replaces the builtin raw_input with a custom function. From alisonken1 at gmail.com Wed Jan 9 00:29:06 2008 From: alisonken1 at gmail.com (alisonken1) Date: Tue, 8 Jan 2008 21:29:06 -0800 (PST) Subject: pipes python cgi and gnupg References: <8aa1d294-cbef-45b2-9e0f-dcc44323e520@v4g2000hsf.googlegroups.com> Message-ID: <38031e39-f1a6-482c-a196-d2f9e6fef22c@u10g2000prn.googlegroups.com> On Dec 28 2007, 7:07 pm, byte8b... at gmail.com wrote: > form = cgi.FieldStorage() > if not form.has_key("pass"): > print "Enter password" > > filename = "test.gpg" > pass = form.getvalue("pass").strip() > os.system("gpg --version > gpg.out") > os.system("echo %s | gpg --batch --password-fd 0 --decrypt %s > d.out" > %(pass,filename)) The last time I checked, "pass" is a reserved word in Python. Since you are using a reserved word as a variable, maybe that's what's messing with your output? From wuwei23 at gmail.com Wed Jan 30 19:55:07 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 30 Jan 2008 16:55:07 -0800 (PST) Subject: Events in Python References: Message-ID: <8157c4a1-3c6b-49b0-9cad-b633a7bb891e@e6g2000prf.googlegroups.com> Hey Si, The PEAK lib Trellis (http://peak.telecommunity.com/DevCenter/Trellis) is worth checking out. I haven't had a chance to use it yet but am keen to. There are several other modules that may apply, I recommend searching on the Python Package Index (http://pypi.python.org/pypi), for "observer" or "dispatcher". Hope this helps. -alex23 From ggpolo at gmail.com Wed Jan 16 11:23:43 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 16 Jan 2008 14:23:43 -0200 Subject: list classes in package In-Reply-To: <5v6mk4F1kbh4nU1@mid.uni-berlin.de> References: <5cff1706-3bb1-4a54-bccb-175ff384788c@q77g2000hsh.googlegroups.com> <5v6mk4F1kbh4nU1@mid.uni-berlin.de> Message-ID: 2008/1/16, Diez B. Roggisch : > Dmitry wrote: > > > Hi All, > > > > I've trying to develop one Python application, and > > neet to solve one problem. I need to list all classes defined in one > > package (not module!). > > > > Could anybody please show me more convinient (correct) way to > > implement this? > > Look at the module inspect and it's predicates. Something like > > > for name in dir(module_or_package): > if inspect.isclass(getattr(module_or_package, name)): > print "%s is a class" % name > > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > You should be able to adapt this one. You need to pass a directory to it (warning: directory names including dots will cause you errors): import os import sys import pyclbr def pkg_modules(package): return filter(lambda x: x.endswith(".py"), os.listdir(package)) def module_classes(module): dict = pyclbr.readmodule_ex(module, []) objs = dict.values() objs.sort(lambda a, b: cmp(getattr(a, 'lineno', 0), getattr(b, 'lineno', 0))) print module for obj in objs: if isinstance(obj, pyclbr.Class): print " class %s %s line: %d" % (obj.name, obj.super, obj.lineno) def pkg_classes(package): for module in pkg_modules(package): module_classes("%s.%s" % (package, module[:-3])) if __name__ == "__main__": pkg_classes(sys.argv[1]) -- -- Guilherme H. Polo Goncalves From lists at cheimes.de Fri Jan 18 03:31:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 18 Jan 2008 09:31:19 +0100 Subject: Unique thread ID In-Reply-To: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> References: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> Message-ID: Benjamin wrote: > Is there a way to obtain a unique ID for the current thread? I have an > object that I need to store local thread data in, and I don't want to > use threading.local because each thread might have multiple instances > of my object. threading.get_ident() but please use threading.local. Nobody is going to stop you if you use a list or dict in threading.local. Christian From p at ulmcnett.com Thu Jan 31 15:25:05 2008 From: p at ulmcnett.com (Paul McNett) Date: Thu, 31 Jan 2008 12:25:05 -0800 Subject: PIL linux err In-Reply-To: <15211773.post@talk.nabble.com> References: <15211773.post@talk.nabble.com> Message-ID: <47A22EA1.1020101@ulmcnett.com> dzizes wrote: > I'm trying to run simple .py on linux, which is using PIL. Below error > message which I receive: > > IOError: decoder jpeg not available > > Do you know what might be the problem? No, but google seems to: http://effbot.org/zone/pil-decoder-jpeg-not-available.htm Paul -- http://paulmcnett.com From seberino at spawar.navy.mil Wed Jan 23 09:03:05 2008 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: Wed, 23 Jan 2008 06:03:05 -0800 (PST) Subject: How avoid both a newline and a space between 2 print commands? Message-ID: print "foo" print "bar" has a newline in between "foo" and "bar" print "foo", print "bar" has a space in between "foo" and "bar" How prevent ANYTHING from going in between "foo" and "bar" ?? (Without defining a string variable.) Chris From martin at v.loewis.de Sat Jan 12 18:19:05 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jan 2008 00:19:05 +0100 Subject: different encodings for unicode() and u''.encode(), bug? In-Reply-To: <1c3f85a5-6bf3-4534-afb2-186f50a060cd@v29g2000hsf.googlegroups.com> References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> <76ba16c8-6ba0-4609-80bd-cd54aa08d74b@5g2000hsg.googlegroups.com> <590e6f12-16ad-4919-a87d-a2f2cc0b3516@t1g2000pra.googlegroups.com> <1c3f85a5-6bf3-4534-afb2-186f50a060cd@v29g2000hsf.googlegroups.com> Message-ID: <47894AE9.5020706@v.loewis.de> > What I'd like to understand better is the "compatibility heirarchy" of > known encodings, in the positive sense that if a string decodes > successfully with encoding A, then it is also possible that it will > encode with encodings B, C; and in the negative sense that is if a > string fails to decode with encoding A, then for sure it will also > fail to decode with encodings B, C. Any ideas if such an analysis of > the relationships between encodings exists? Most certainly. You'll have to learn a lot about many encodings though to really understand the relationships. Many encodings X are "ASCII supersets", in the sense that if you have only characters in the ASCII set, the encoding of the string in ASCII is the same as the encoding of the string in X. ISO-8859-X, ISO-2022-X, koi8-x, and UTF-8 fall in this category. Other encodings are "ASCII supersets" only in the sense that they include all characters of ASCII, but encode them differently. EBCDIC and UCS-2/4, UTF-16/32 fall in that category. Some encodings are 7-bit, so that they decode as ASCII (producing moji-bake if the input wasn't ASCII). ISO-2022-X is an example. Some encodings are 8-bit, so that they can decode arbitrary bytes (again producing moji-bake if the input wasn't that encoding). ISO-8859-X are examples, as are some of the EBCDIC encodings, and koi8-x. Also, things will successfully (but meaninglessly) decode as UTF-16 if the number of bytes in the input is even (likewise for UTF-32). HTH, Martin From agnel.joel at gmail.com Tue Jan 22 02:23:00 2008 From: agnel.joel at gmail.com (Joel) Date: Mon, 21 Jan 2008 23:23:00 -0800 (PST) Subject: Boa constructor debugging - exec some code at breakpoint? References: <7f96223d-e5bd-4bbc-a242-75826eeb100a@d70g2000hsb.googlegroups.com> Message-ID: Can you please tell me how this can be done.. are there any other IDEs for the same purpose if Boa can't do it? Joel On Jan 6, 11:01?am, Joel wrote: > Hey there.. > I'm using boa constructor to debug a python application. For my > application, I need to insert break points and execute some piece of > code interactively through shell or someother window when the > breakpoint has been reached. Unfortunately the shell I think is a > seperate process so whatever variables are set while executing in > debugger dont appear in the shell when I try to print using print > statement. > > Can anyone tell me how can I do this? > > Really appreciate any support, Thanks > > Joel > P.S. Please CC a copy of reply to my email ID if possible. From gagsl-py2 at yahoo.com.ar Thu Jan 31 19:25:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 31 Jan 2008 22:25:42 -0200 Subject: Removal of element from list while traversing causes the next element to be skipped References: <51302a8c0801300504i30c02ea3jfbf3228a62532720@mail.gmail.com> Message-ID: En Thu, 31 Jan 2008 15:45:42 -0200, escribi?: > Hmm, how does this fare?? > > for i in range(len(a)): > if a[i]==99: a=a[:i]+a[i+1:] > > > I like following your guys code noodling. I can come up with something > that does what it appears your doing, sometimes, but as to it's relevant > merits I havent a clue :) It's worse than the original `del a[i]`; not only skips over some elements, but you'll get an IndexError at the end -- Gabriel Genellina From kyosohma at gmail.com Fri Jan 18 10:55:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jan 2008 07:55:25 -0800 (PST) Subject: get the size of a dynamically changing file fast ? References: Message-ID: <198fd91f-912b-4f56-a840-af96225125a7@c23g2000hsa.googlegroups.com> On Jan 17, 3:56 pm, Stef Mientki wrote: > hello, > > I've a program (not written in Python) that generates a few thousands > bytes per second, > these files are dumped in 2 buffers (files), at in interval time of 50 msec, > the files can be read by another program, to do further processing. > > A program written in VB or delphi can handle the data in the 2 buffers > perfectly. > Sometimes Python is also able to process the data correctly, > but often it can't :-( > > I keep one of the files open en test the size of the open datafile each > 50 msec. > I have tried > os.stat ( ....) [ ST_SIZE] > os.path.getsize ( ... ) > but they both have the same behaviour, sometimes it works, and the data > is collected each 50 .. 100 msec, > sometimes 1 .. 1.5 seconds is needed to detect a change in filesize. > > I'm using python 2.4 on winXP. > > Is there a solution for this problem ? > > thanks, > Stef Mientki Tim Golden has a method to watch for changes in a directory on his website: http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html This old post also mentions something similar: http://mail.python.org/pipermail/python-list/2007-October/463065.html And here's a cookbook recipe that claims to do it as well using decorators: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/426620 Hopefully that will get you going. Mike From gherron at islandtraining.com Fri Jan 11 03:46:52 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 11 Jan 2008 00:46:52 -0800 Subject: python recursive function In-Reply-To: References: Message-ID: <47872CFC.9080303@islandtraining.com> Tom_chicollegeboy wrote: > here is what I have to do: > > This question involves a game with teddy bears. The game starts when I > give you some bears. You then start giving me back some bears, but you > must follow these rules (where n is the number of bears that you > have): > This sounds very much like a homework assignment, and so should probably not be answered here. (Neither should it have been asked here.) If, in your attempt to write this program, you have some questions about Python, then I encourage to ask those questions here. Gary Herron > If n is even, then you may give back exactly n/2 bears. (Hint: To test > whether n is even, use the expression ((n % 2) == 0).) > If n is divisible by 3 or 4, then you may multiply the last two digits > of n and give back this many bears. (By the way, the last digit of n > is n%10, and the next-to-last digit is (n%100)/10; this rule may not > be used if either of the last two digits is 0.) > > If n is divisible by 5, then you may give back exactly 42 bears. > The goal of the game for you is to end up with EXACTLY 42 bears. > > For example, suppose that you start with 250 bears. Then you could > make these moves: > > Start with 250 bears. > Since 250 is divisible by 5, you may return 42 of the bears, leaving > you with 208 bears. > Since 208 is even, you may return half of the bears, leaving you with > 104 bears. > Since 104 is even, you may return half of the bears, leaving you with > 52 bears. > Since 52 is divisible by 4, you may multiply the last two digits > (resulting in 10) and return these 10 bears. This leaves you with 42 > bears. > You have reached the goal! > Now, you are to write a program that, if I give you n bears, returns > true if it is at all possible for you to win the game. Your program > must use recursion to check all possible ways in which you can apply > the rules. > > > Usage: > > >>>> bears(42) >>>> > True > >>>> bears(250) >>>> > True > >>>> bears(50) >>>> > False > >>>> bears(84) >>>> > True > >>>> bears(41) >>>> > False > > > As you see my program must use recursion. > > I came up with this idea but I am not sure if its right or are there > any minor errors that I can easily fix: > > def bears (n): > if n==42: > return True > if n%5==0: > bears(n-42) > if n%2==0: > bears(n/2) > if n%3==0 or n%4==0: > one = (n%10) > two = ((n%100)/10) > if one!=0 and two!=0: > bears(n-(one*two)) > return False > > If a game hits 42 it should return True, otherwise False. If program > never hits 42 and return True, then it returns False. I figured out > base case, but I still get False when I enter bears(250). Any help > would be very appreciated! > From __peter__ at web.de Mon Jan 7 08:48:58 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 7 Jan 2008 14:48:58 +0100 Subject: code doesn't reference immutables? References: <5e6d3674-fddb-402f-9e5c-19afcd7fcc22@i7g2000prf.googlegroups.com> Message-ID: MartinRinehart wrote: > From the manual: > > "code objects are immutable and contain no references (directly or > indirectly) to mutable objects" (3.2) > > I thought my code worked with both mutable and immutable objects. > Whassup? A code object is an internal data structure that describes a piece of compiled python code. You can create one using compile(): >>> code = compile("a = 42", "", "exec") It is immutable: >>> code.a = 42 Traceback (most recent call last): File "", line 1, in TypeError: 'code' object has only read-only attributes (assign to .a) And you can use it like so: >>> a = "whatever" >>> exec code >>> a 42 If you have some spare time you can explore its attributes using dir(code); otherwise: don't bother. Peter From guptaabhishek1983 at gmail.com Fri Jan 11 03:07:36 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Fri, 11 Jan 2008 00:07:36 -0800 (PST) Subject: HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? Message-ID: <7243c2ac-fa22-4b5b-bd8c-34235123ab69@t1g2000pra.googlegroups.com> Hi group any idea on HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? Thank you From albert at spenarnc.xs4all.nl Tue Jan 29 08:37:49 2008 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 29 Jan 2008 13:37:49 GMT Subject: Changing module variables. Message-ID: I have made a sudoku solver, and discovered I simply can turn it into a hexadoku solver, like so: _______________________________ # sudoku solver using sets import sudoku sudoku.symbols="0123456789ABCDEF" sudoku.size=16 sudoku.sqs=4 # square root of size . _______________________________ Example of usage: _______________________________ y=sudoku.sudoku( " " " B " "95E " "8 1C" " 9 7" " 1 C" " 8 B" "A 46" " 4 " "0 8" " 71" "3 59" " C 8" "7F " "A 24" "BD " " 7 " "4 1" " 5" " " "42 " " 0" " BAC" " 1" "8 6A" "F 5" "2 9 " " D " " " "C28 " " 1 7" " 9 " " A3 " " " " E " " 5 B" "08 E" "B C " " 96 " "1A3 " "D 5 " " " "0 A" " E" "6 1" " A F" "5DC2" " 8" " 58 " "3C " " 6" "41AD" "1E 6" "542 " " 73D" " 08F" "B3 " " 8 " "14 " " 67" "240D" "16F " " 8 " " 3" ) y.show() y.solve() y.show() _______________________________ I like this. It certainly is reusability. Still I wonder what you guys think of this? (I know some OO-boys who would spank me for it.) Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- like all pyramid schemes -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From jr9445 at ATT.COM Thu Jan 17 09:56:02 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 17 Jan 2008 08:56:02 -0600 Subject: Creating unique combinations from lists In-Reply-To: <478E6BA7.5030509@tim.thechases.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> <478E6BA7.5030509@tim.thechases.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 Tim Chase > Sent: Wednesday, January 16, 2008 3:40 PM > To: breal > Cc: python-list at python.org > Subject: Re: Creating unique combinations from lists > > You can use a recursive generator: > > def iterall(*iterables): > if iterables: > for head in iterables[0]: > for remainder in iterall(*iterables[1:]): > yield [head] + remainder > else: > yield [] > > for thing in iterall( > ['big', 'medium', 'small'], > ['old', 'new'], > ['blue', 'green'], > ): > print thing Recursion definitely makes for an elegant solution. However you do take a bit of a performance hit. If performance matters (and comprehensions are supposed to be optimized/fast) and you want a "works for N nested loops solution," then you could build a N deep comprehension on the fly and eval() it: def gen(lists): out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in range(len(lists))]) return eval('[ ' + out + comp + ' ]') gen([a, b, c]) So for a three item list, it would build and execute the following comprehension: [ [v0,v1,v2] for v0 in lists[0] for v1 in lists[1] for v2 in lists[2] ] Seven item list: [ [v0,v1,v2,v3,v4,v5,v6] for v0 in lists[0] for v1 in lists[1] for v2 in lists[2] for v3 in lists[3] for v4 in lists[4] for v5 in lists[5] for v6 in lists[6] ] Some rough performance numbers in seconds for 1,000 iterations over a three item list: list comprehension: 0.74 nested for loop : 0.97 31% slower recursion : 3.91 428% slower =P eval : 1.11 50% slower from timeit import Timer s = "a = [ i for i in range(10) ]; b = a; c = a" t = Timer( "l = [ [i, j, k] for i in a for j in b for k in c]", s) iterations = 1000 print "list comprehension: %4.2f" % t.timeit(iterations) t = Timer(''' l = [] for i in a: for j in b: for k in c: l.append([i, j, k]) ''', s) print "nested for loop : %4.2f" % t.timeit(iterations) t = Timer(''' def iterall(*iterables): if iterables: for head in iterables[0]: for remainder in iterall(*iterables[1:]): yield [head] + remainder else: yield [] for thing in iterall(a, b, c): pass #print thing ''', s) print "recursion : %4.2f" % t.timeit(iterations) t = Timer(''' def gen(lists): out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in range(len(lists))]) return eval('[ ' + out + comp + ' ]') gen([a, b, c]) ''', s) print "eval : %4.2f" % t.timeit(iterations) ***** 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 mrmakent at cox.net Thu Jan 24 16:04:28 2008 From: mrmakent at cox.net (Mike Kent) Date: Thu, 24 Jan 2008 13:04:28 -0800 (PST) Subject: Can someone explain this unexpected raw_input behavior? References: Message-ID: <13ff90c7-60ee-4306-8459-890a2b2b178a@e25g2000prg.googlegroups.com> > If it weren't for the documentation... > > "If the prompt argument is present, it is written to *standard output* > without a trailing newline." > > -- > mvh Bj?rn I have reported this issue to the python-dev mailing list, and Guido agrees that this is a bug in Python. It turns out that the key is that my site does not have GNU readline installed, so Python falls back to its own implementation of readline. Using GNU readline, raw_input will write its prompt to stdout. Python's own implementation of readline sends the output to stderr. As Bjorn states, the documentation for raw_input says it writes its prompt to stdout. A bug issue has been opened in the Python Trac system for this. From nytrokiss at gmail.com Tue Jan 8 15:02:27 2008 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 8 Jan 2008 21:02:27 +0100 Subject: Python's great, in a word In-Reply-To: <7c77bd1c-3930-4078-b687-12cc7df849a9@d21g2000prf.googlegroups.com> References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <7c77bd1c-3930-4078-b687-12cc7df849a9@d21g2000prf.googlegroups.com> Message-ID: <8a6b8e350801081202q7f043b37q224584f023effd51@mail.gmail.com> We have such nice names so the word Python will be something people like and not something people fear (A massive 12 foot snake) and Pythonic is a behavior pattern we should all follow! In layman's terms it means we should all act like snakes a little more! On Jan 8, 2008 5:13 PM, Carl Banks wrote: > On Jan 7, 6:29 pm, MRAB wrote: > > On Jan 7, 5:40 pm, Martin Marcher wrote:> > MartinRineh... at gmail.com wrote: > > > > The best thing about Python is _______. > > > > > it's pythonicness. > > > > I think it sounds better as "its pythonicity". > > Mixing Greek and Latin suffixes usually works better than mixing Greek > and Germanic, doesn't it. > > > Carl Banks > -- > 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 Russ.Paielli at gmail.com Sun Jan 27 18:00:57 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 15:00:57 -0800 (PST) Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> Message-ID: <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> On Jan 27, 2:49 pm, "Andr?" wrote: > On Jan 27, 6:19 pm, "Russ P." wrote: > > > > > A while back I came across a tentative proposal from way back in 2000 > > for optional static typing in Python: > > >http://www.python.org/~guido/static-typing > > > Two motivations were given: > > > -- faster code > > -- better compile-time error detection > > > I'd like to suggest a third, which could help extend Python into the > > safety-critical domain: > > > -- facilitates automated source-code analysis > > > There has been much heated debate in the past about whether Python is > > appropriate for safety-critical software. Some argue that, with > > thorough testing, Python code can be as reliable as code in any > > language. Well, maybe. But then, a famous computer scientist once > > remarked that, > > > "Program testing can be used to show the presence of bugs, but never > > to show their absence!" --Edsger Dijkstra > > > The next step beyond extensive testing is automated, "static" analysis > > of source-code ("static" in the sense of analyzing it without actually > > running it). For example, Spark Ada is a subset of Ada with > > programming by contract, and in some cases it can formally prove the > > correctness of a program by static analysis. > > > Then there is Java Pathfinder (http://javapathfinder.sourceforge.net), > > an "explicit state software model checker." The developers of JPF > > wanted > > to use it on a prototype safety-critical application that I wrote in > > Python, but JPF only works on Java code. We considered somehow using > > Jython and Jythonc, but neither did the trick. So they ended up having > > someone manually convert my Python code to Java! (The problem is that > > my code was still in flux, and the Java and Python versions have now > > diverged.) > > > In any case, optional static typing in Python would help tremendously > > here. The hardest part of automated conversion of Python to a > > statically typed language is the problem of type inference. If the > > types are explicitly declared, that problem obviously goes away. > > Explicit typing would also greatly facilitate the development of a > > "Python Pathfinder," so the conversion would perhaps not even be > > necessary in the first place. > > > Note also that, while "static" type checking would be ideal, > > "explicit" typing would be a major step in the right direction and > > would probably be much easier to implement. That is, provide a syntax > > to explicitly declare types, then just check them at run time. A > > relatively simple pre-processor could be implemented to convert the > > explicit type declarations into "isinstance" checks or some such > > thing. (A pre-processor command-line argument could be provided to > > disable the type checks for more efficient production runs if > > desired.) > > > I noticed that Guido has expressed further interest in static typing > > three or four years ago on his blog. Does anyone know the current > > status of this project? Thanks. > > Perhaps this:http://www.python.org/dev/peps/pep-3107/might be > relevant? > Andr? Thanks. If I read this correctly, this PEP is on track for Python 3.0. Wonderful! From cptnwillard at gmail.com Thu Jan 17 10:05:49 2008 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Thu, 17 Jan 2008 07:05:49 -0800 (PST) Subject: Is this a bug, or is it me? Message-ID: Hello all, For some reason, the following does not work : class C: TYPES = [None] DICT = {} for Type in TYPES: DICT.update((E,Type) for E in [1]) >>> NameError: global name 'Type' is not defined What do you think? Is this a bug? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 18 04:18:01 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 18 Jan 2008 10:18:01 +0100 Subject: Loop in a loop? In-Reply-To: <7xy7aong73.fsf@ruckus.brouhaha.com> References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> <7xy7aong73.fsf@ruckus.brouhaha.com> Message-ID: <47906e95$0$16946$426a74cc@news.free.fr> Paul Rubin a ?crit : > George Sakkis writes: >> And if the iterables don't necessarily support len(), here's a more >> general solution: > > Not trying to pick on you personally but there's this disease > when a newbie comes with a basically simple question (in this case, > how to solve the problem with ordinary lists) and gets back a lot > of complex, overly general "graduate level" solutions. As far as I'm concerned, it's certainly a GoodThing(tm) - everyone learns in the process. From gagsl-py2 at yahoo.com.ar Thu Jan 24 02:08:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 Jan 2008 05:08:46 -0200 Subject: Can someone explain this unexpected raw_input behavior? References: Message-ID: En Thu, 24 Jan 2008 01:00:53 -0200, Mike Kent escribi?: > Gabriel, thank you for clarifying the source of this behavior. Still, > I'm surprised it would be hard-coded into Python. Consider an > interactive program, that asks the user several questions, and > displays paragraphs of information based on those questions. The > paragraphs are output using print, and the questions are asked via > raw_input. You want to do some simple debugging of the program by > printing some debugging statements via 'print >>sys.stderr', and you > don't want the debug output mixed in with the normal output on the > screen, so you try to route the debugging output to a file by adding > '2>filename' to the end of the command line. > > Unfortunately, you will no longer see any of the questions being > printed via raw_input. The rest of the output will be fine, but the > questions disappear. Your program just stops, without asking > anything... you have to guess what should be there. You have one console, two streams to output data (stdout and stderr), and three data sources (program output, user prompt, and debugging messages). Someone has to give. I'm now convinced that the current behavior is rather reasonable... > I'm surprised that Python hard-codes this behavior without giving the > programmer any way to change it. It leaves me with two options: to > either always use the logging module for debugging messages (which is > not odious at all, it's just that the code in question predates the > logging module, which is why debugging was done as it is), or change > the program so that raw_input is never used with a prompt parameter; > the prompt must always be printed separately. Perhaps raw_input could have a use_stderr=True parameter; with False would display the prompt on stdout. -- Gabriel Genellina From sjmachin at lexicon.net Wed Jan 9 15:26:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 9 Jan 2008 12:26:33 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> Message-ID: <9baa43c2-2a39-4f09-a62c-54f29cc08473@e4g2000hsg.googlegroups.com> On Jan 10, 7:12 am, Tim Chase wrote: > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] > > > I'd like to remove the first and the last item as they are irrevalent, > > and convert it to the dict: > > {'tom':'boss','mike':'manager','paul':'employee'} > > > I tried this but it didn't work: > > > mydict={} > > for i in mylist[1:-1]: > > a=i.split('=') # this will disect each item of mylist into a 2-item > > list > > mydict[a[0]]=a[1] > > > and I got this: > > File "srch", line 19, in > > grab("a/tags1") > > File "srch", line 15, in grab > > mydict[mylist[0]]=mylist[1] > > IndexError: list index out of range > > This can be rewritten a little more safely like > > mydict = dict(pair.split('=',1) > for pair in mylist > if '=' in pair) > > Some of John Machin's caveats still apply: > (2) a[0] is empty or not what you expect (a person's name) > (3) a[1] is empty or not what you expect (a job title) > (consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = ' > boss') > (4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...] > > to which I'd add > > (5) what happens if you have more than one equals-sign in your > item? ("bob=robert=manager" or "bob=manager=big-cheese") > or "bob==manager" ummm ... isn't more than one equals-sign covered by check #1: len(a) == 2 ? From bladedpenguin at gmail.com Sat Jan 26 00:33:48 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 21:33:48 -0800 (PST) Subject: Puzzled by behaviour of class with empty constructor References: <99b8e2ac-1c72-430a-9172-a809e169f96a@i12g2000prf.googlegroups.com> <5vv75rF1nt2o7U1@mid.individual.net> Message-ID: On Jan 25, 5:54 pm, dbas... at gmail.com wrote: > On Jan 25, 5:46 pm, Bjoern Schliessmann > > > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > dbas... at gmail.com wrote: > > > print x.ends,y.ends,z.ends > > > ############# > > > Running the following code outputs: > > >>>> [(0, 2)] [(0, 2)] [(0, 2)] > > > > Can anyone explain this? > > > Yes. You bound a single list to the name "ends" inside the class. > > This name is shared by all instances. > > > If you want the instances to each have separate lists, delete > > the "ends" definition from class declaration and insert "self.ends > > = []" into __init__. > > > I also suggest you to have a look at the tutorial. > > > Regards, > > > Bj?rn > > > -- > > BOFH excuse #49: > > > Bogon emissions > > Bj?rn, > > Thanks for the help. I had misguidedly defined the members of all of > my classes as in the example above; I never noticed the issue with any > of the others because they did not have empty constructors. > > Thanks again for the correction. Yeah! thanks all. I did not realize the distinction either. From pablo at decode.com.ar Mon Jan 7 08:15:12 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Mon, 07 Jan 2008 11:15:12 -0200 Subject: Python's great, in a word In-Reply-To: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <478225E0.8060506@decode.com.ar> MartinRinehart at gmail.com wrote: > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is _______. Hi Martin, here is my top three: 1) Fun 2) Simplicity 3) Productivity From python at rcn.com Wed Jan 23 00:29:48 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 22 Jan 2008 21:29:48 -0800 (PST) Subject: Cleanup when a object dies References: <601f19ce-ac60-4145-9e99-6eacb8ea74e2@e6g2000prf.googlegroups.com> Message-ID: <7c1171cb-f463-420a-8abe-70d68f587f55@u10g2000prn.googlegroups.com> On Jan 22, 7:54?pm, Benjamin wrote: > I writing writing a class to allow settings (options, preferences) to > written file in a cross platform manner. I'm unsure how to go a about > syncing the data to disk. Of course, it's horribly inefficient to > write the data every time something changes a value, however I don't > see how I can do it on deletion. I've read that __del__ methods should > be avoided. So am I just going to have to force the client of my > object to call sync when they're done? Lots of ways 1. Try the atexit module 2. Use a weakref callback 3. Embed a client callback in a try/finally. 4. Or, like you said, have the client call a sync() method -- this is explicit and gives the client control over when data is written. Raymond From steven at REMOVE.THIS.cybersource.com.au Mon Jan 21 04:25:04 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 09:25:04 -0000 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: On Mon, 21 Jan 2008 01:15:50 -0800, dg.google.groups wrote: > Decided I may as well post my other solution while I'm at it. The neat > trick here is redefining the add, mul, etc. functions so that they raise > exceptions for example if x>y then add(x,y) raises an exception which is > handled by the search algorithm to mean don't continue that computation > - this stops you from having to evaluate x+y AND y+x, etc. Setting up a try...except block is very fast, but actually responding to an exception is very slow. You _might_ find that it is quicker to evaluate both expressions than it is to catch the exception. Better still is to find another way of avoiding both the exception and the symmetrical calls. -- Steven From bignose+hates-spam at benfinney.id.au Mon Jan 14 17:35:22 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 09:35:22 +1100 Subject: [ANN] pylint 0.14 / logilab-astng 0.17.2 References: Message-ID: <878x2sf32t.fsf@benfinney.id.au> Sylvain Th?nault writes: > I'm pleased to announce a new release of pylint [1] and logilab-astng > [2]. I haven't personally found a lot of time to work on those projects > since the latest releases but others contributors have and so I decided > to publish releases including various contributions and other minor bug > or crash fixes (some of which were pending for a while now). You're > greatly encouraged to upgrade, see projects'changelog for more > information about what changed. Thanks very much for this. Can you please give an overview of the major user-visible changes? That will help in convincing people to upgrade. -- \ "Most people don't realize that large pieces of coral, which | `\ have been painted brown and attached to the skull by common | _o__) wood screws, can make a child look like a deer." -- Jack Handey | Ben Finney From bj_666 at gmx.net Mon Jan 21 14:18:18 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Jan 2008 19:18:18 GMT Subject: problem with 'global' References: Message-ID: <5vk9fqF1n19plU1@mid.uni-berlin.de> On Mon, 21 Jan 2008 17:08:46 -0200, Gabriel Genellina wrote: > The future statement is another example, even worse: > > if 0: > from __future__ import with_statement > > with open("xxx") as f: > print f In Python >=2.5 it's a compile time error if that import is not the very first statement in a source file. Ciao, Marc 'BlackJack' Rintsch From steven at REMOVE.THIS.cybersource.com.au Wed Jan 2 04:09:24 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 02 Jan 2008 09:09:24 -0000 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au> <87bq85rp2d.fsf@physik.rwth-aachen.de> <87abnoc13h.fsf@benfinney.id.au> Message-ID: On Wed, 02 Jan 2008 15:17:54 +1100, Ben Finney wrote: > Torsten Bronger writes: > >> [...] the width of a tab is nowhere defined. It really is a matter of >> the editor's settings. > > RFC 678 "Standard File Formats" > : Dated 19 December 1974. I really recommend that anyone following this thread read the RFC. It will give you a good mindset of how things were THIRTY YEARS AGO, before Unicode, before extended ASCII character sets, before Postscript, before laser printers, before graphical monitors, before you could choose your display resolution and typeface. Some recommendations from the RFC, with my comments in braces {}: The end of line convention is the Telnet end of line convention which is the sequence . { anyone here like to predict what Ben, a Linux user, uses as his end of line terminator? } Format 1 [Basic Document] This format is designed to be used for documents to be printed on line printers, which normally have 66 lines to a physical page, but often have forced top and bottom margins of 3 lines each. Active Format Effectors , , . Page Length 60 lines. Page Width 72 Characters. { who measures page width in characters any more? doesn't that depend on how wide each character is? and lines per page? } I think it tells a lot about the spaces-only argument that it is based on the state of the art thirty years ago, when people's choice in displaying and printing code was limited to one fixed width typeface per platform. If you actually view the RFC in question, it demonstrates just how obsolete it really is: fixed page breaks, hard coded page numbers, and with a hard coded 72 characters per line, the page's text takes up just over a third of my browser window, leaving 2/3rds blank. Printed is a little better: only 1/3rd of the printed page is left blank. Follow this RFC, and you too can needlessly waste screen real estate and paper! That's the world the spaces-only proponents still live in: everybody must write to the lowest common denominator just in case some day, some where some programmer might have to edit a source file by telnet on a fixed width character terminal using ed. If you are writing in an environment where it is likely, or even conceivable, that this could happen, then of course you should set in place an appropriate coding convention. That's the beauty of it: your code base, you get to tell everybody who works on it what conventions to follow. But for the rest of us, needlessly writing to the technology of 1974 is such a waste -- and I guarantee the 90% of programmers who aren't using a Unix-based OS aren't doing the same. And without the limitations of the 72 character line printer, there is no advantage to using fixed spaces for indents, and significant disadvantages. > How many columns to indent source code is an orthogonal question to how > wide an ASCII TAB (U+0009) should be rendered. The former question is > open to matters of style; the latter at least is standardised, even > given the caveats about enforcement. The existence of an RFC that nobody pays any attention to is not a standard. >> If all Python code used tabs, eveybody could use their own preferences, >> for both reading and writing code, and interoperability would be >> maintained nevertheless. > > Interoperability isn't the only criterion though. On the contrary, > source code is primarily for reading by programmers, and only > incidentally for reading by the compiler. Exactly, and allowing programmers to set their own indent width aids readability. Forcing your choice on others works against readability. It also hurts *editability*. Consider copying code from a source file with 8-space indents into a source file with 4-space indents, or vice versa. If you're lucky, your editor has a command to "clean spaces", or otherwise re-indent, and it might even get it right. At worst, you have to laboriously add or delete spaces by hand. That problem simply does not exist if you use the rule one tab = one indent level. You only need to re-indent when you are actually changing the number of indent levels, not as a side-effect of different conventions for the number of spaces per level. -- Steven From kyosohma at gmail.com Thu Jan 3 16:40:34 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 3 Jan 2008 13:40:34 -0800 (PST) Subject: How is AI implemented References: Message-ID: On Jan 3, 11:49 am, "Martin Marcher" wrote: > Hi, > > I know it's not a trivial field but I had some readings about > artificial intelligence lately and my personal conclusion is that it's > mostly just statistics. > > Naively explained: > > continiously gather and store information and apply a default rating > > 1) answer "questions" with gathered information according to rating > 2) store/calculate rating based upon input (be it an interface or user input) > 3) goto 1 (sorry for the goto) > > So I think that in general there hasn't yet been any artificial > intelligence programmed (Note: I believe I'm aware of the difference > between artificial intelligence and artificial conscusiness where the > second would be able to answer things like: "How are you today" and > the first can answer factual knowledge) > > Am I thinking right here or is there some (preferrably) web reading > available on that or in depth links about the topic? > > thanks and sorry for OT posting > martin > > --http://noneisyours.marcher.namehttp://feeds.feedburner.com/NoneIsYours Some readings: http://www-formal.stanford.edu/jmc/whatisai/whatisai.html http://www.sciencedaily.com/news/computers_math/artificial_intelligence/ http://www.jair.org/ http://dir.yahoo.com/Science/computer_science/artificial_intelligence/ Fuzzy Logic usually crops up as a related topic: http://www.seattlerobotics.org/encoder/mar98/fuz/flindex.html http://www.austinlinks.com/Fuzzy/ I'm not involved in this field, but I think saying that AI is just statistics is a pretty sweeping statement. It's more like super complicated stats using algorithms worthy of Calculus with branch logic thrown in for good measure. How's that for a load of buzz words!? Hope those links give you lots of info. Let us know when you've got a cool talking Python program! Mike From Russ.Paielli at gmail.com Thu Jan 10 02:39:38 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 9 Jan 2008 23:39:38 -0800 (PST) Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: On Jan 9, 9:47 pm, "Steve Brown" wrote: > I've got a series of modules which look like this: > > #************ > # > # Temperature Sense Test > # > #************ > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > I don't like the duplicated information: But the comment is attractive, and > the docstring self.__doc__ is already in use in the test log. I've read that > all modules and classes should have docstrings, but I don't really have > anything else to say, and each module contains only one class. I don't think > that > > """Temperature Sense Test""" > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > would be a real improvement. > > What do you think? > > Steve. I tend to be a bit skimpy with one-line comments for classes and methods, but I think a more complete (""" style) comment is often appropriate for the top of the file. I'm sure you can think of more to say than "Temperature Sense Test." What temperature? What kind of temperature sensor? What kind of test is it, and why are you doing it? That may all be obvious in context, but you've provided no context in your post. Also, if the module is of any significant size, you might want to provide a clue about who wrote it. Then, if someone has a question about it later, they will know who to ask. From george.sakkis at gmail.com Mon Jan 21 14:16:02 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 21 Jan 2008 11:16:02 -0800 (PST) Subject: is it possible to set namespace to an object. References: <27529efd-b8d8-4a8e-b72d-379a607366b7@i7g2000prf.googlegroups.com> <4794dd6c$0$27198$9b4e6d93@newsspool1.arcor-online.net> <62e9433b-4f04-4020-b1e6-581496ba3f3e@s19g2000prg.googlegroups.com> Message-ID: <9b656006-3b97-4ee8-b992-ff06b970904b@q77g2000hsh.googlegroups.com> On Jan 21, 1:56 pm, glomde wrote: > On 21 Jan, 18:59, Wildemar Wildenburger > > > > wrote: > > glomde wrote: > > > Hi, > > > > is it somehow possible to set the current namespace so that is in an > > > object. > > > [snip] > > > set namespace testObj > > > Name = "Test" > > > > Name would set testObj.Name to "Test". > > > > [snip] > > > > Is the above possible? > > > Don't know, sorry. But let me ask you this: Why do you want to do this? > > Maybe there is another way to solve the problem that you want to solve. > > The reason is that I do not want to repeat myself. It is to set up XML > type like > trees and I would like to be able to do something like. > > with ElemA(): > Name = "Top" > Description "Blahaha..." > with ElemB(): > Name = "ChildA" > Description "Blahaha..." > .... > > This would be the instead of. > with ElemA() as node: > node.Name = "Top" > node.Description "Blahaha..." > with ElemB() as node: > node.Name = "ChildA" > node.Description "Blahaha..." > .... > > So to save typing and have something that I think looks nicer. ... and more confusing for anyone reading the code (including you after a few weeks/months). If you want to save a few keystrokes, you may use 'n' instead of 'node' or use an editor with easy auto completion. By the way, is there any particular reason for generating the XML programmatically like this ? Why not have a separate template and use one of the dozen template engines to populate it ? George From not at valid.com Fri Jan 4 18:08:48 2008 From: not at valid.com (yomgui) Date: Fri, 04 Jan 2008 23:08:48 GMT Subject: opensg or openscenegraph Message-ID: <40zfj.33787$lD6.31634@newssvr27.news.prodigy.net> Hi, I need to use a scengraph for my python/opengl application but I have trouble finding out which one I should use. opensg or openscenegraph (OSG) ? I suppose the quality of the python bindings will make the decision. any advice ? thanks yomgui From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 21 18:34:31 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 22 Jan 2008 00:34:31 +0100 Subject: Max Long References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> Message-ID: <5vkog7F1m4dhvU1@mid.individual.net> tjhnson at gmail.com wrote: > How can I figure out the largest long available? Why would you? AFAIK, longs are only limited by available memory. > I was hoping for something like sys.maxint, but I didn't see it. > Also, can someone point me to where I can (concisely) read about > size of such types (int, float, long). Well, how about the docs? http://docs.python.org/lib/typesnumeric.html Regards, Bj?rn -- BOFH excuse #397: T-1's congested due to porn traffic to the news server. From arnodel at googlemail.com Sun Jan 20 11:22:28 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 20 Jan 2008 08:22:28 -0800 (PST) Subject: Bug in __init__? References: Message-ID: <88580064-3590-471e-8036-a631dd5a38b4@i3g2000hsf.googlegroups.com> On Jan 20, 3:39?pm, Bart Ogryczak wrote: > On 2008-01-18, citizen Zbigniew Braniecki testified: > > > It's really a nice pitfall, I can hardly imagine anyone expecting this, > > AFAIR, it's described in Diving Into Python. Still there seems to be about one message a week about this. Indeed I reckon the greatest benefit of early binding of default function arguments is that it attracts lots of new people to comp.lang.python. > It's quiet elegant way of creating cache. IMHO, calling it 'elegant' is pushing it too far! -- Arnaud From fredrik at pythonware.com Wed Jan 9 05:43:43 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 11:43:43 +0100 Subject: alternating string replace In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: cesco wrote: > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... how about splitting on "_", joining pairs with ":", and finally joining the result with "," ? >>> s1 = "hi_cat_bye_dog" >>> s1 = s1.split("_") >>> s1 ['hi', 'cat', 'bye', 'dog'] >>> s1 = [s1[i]+":"+s1[i+1] for i in range(0,len(s1),2)] >>> s1 ['hi:cat', 'bye:dog'] >>> s1 = ",".join(s1) >>> s1 'hi:cat,bye:dog' (there are many other ways to do it, but the above 3-liner is short and straightforward. note the use of range() to step over every other item in the list) From over at thepond.com Sun Jan 27 05:55:20 2008 From: over at thepond.com (over at thepond.com) Date: Sun, 27 Jan 2008 10:55:20 GMT Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> Message-ID: On Sat, 26 Jan 2008 14:47:50 +0100, Bjoern Schliessmann wrote: >over at thepond.com wrote: > >> Intel processors can only process machine language[...] There's no >> way for a processor to understand any higher level language, even >> assembler, since it is written with hexadecimal codes and basic >> instructions like MOV, JMP, etc. The assembler compiler can >> convert an assembler file to a binary executable, which the >> processor can understand. > >This may be true, but I think it's not bad to assume that machine >language and assembler are "almost the same" in this context, since >the translation between them is non-ambiguous (It's >just "recoding"; this is not the case with HLLs). I have no problem with your explanation. It's nearly impossible to program in machine code, which is all 1's and 0's. Assembler makes it infinitely easier by converting the machine 1's and 0's to their hexadecimal equivalent and assigning an opcode name to them, like PUSH, MOV, CALL, etc. Still, the older machine-programmable processors used switches to set the 1's and 0's. Or, the machine code was fed in on perforated cards or tapes that were read. The computer read the switches, cards or tapes, and set voltages according to what it scanned. the difference is that machine code can be read directly, whereas assembler has to be compiled in order to convert the opcodes to binary data. > >> Both Linux and Windows compile down to binary files, which are >> essentially 1's and 0's arranged in codes that are meaningful to >> the processor. > >(Not really -- object code files are composed of header data and >different segments, data and code, and only the code segments are >really meaningful to the processor.) I agree that the code segments, and the data, are all that's meaningful to the processor. There are a few others, like interrupts that affect the processor directly. I understand what you're saying but I'm refering to an executable file ready to be loaded into memory. It's stored on disk in a series of 1's and 0's. As you say, there are also control codes on disk to separate each byte along with CRC codes, timing codes, etc. However, that is all stripped off by the hard drive electronics. The actual file on disk is in a certain format that only the operating system understands. But once the code is read in, it goes into memory locations which hold individual arrays of bits. Each memory location holds a precise number of bits corresponding to the particular code it represents. For example, the ret instruction you mention below is represent by hex C3 (0xC3), which represents the bits 11000011. That's a machine code, since starting at 00000000 to 11111111, you have 256 different codes available. When those 1's and 0's are converted to volatges, the computer can analyze them and set circuits in action which will bring about the desired operation. Since Linux is written in C, it must convert down to machine code, just as Windows must. > >> Once a python py file is compiled into a pyc file, I can >> disassemble it into assembler. > >But you _do_ know that pyc files are Python byte code, and you could >only directly disassemble them to Python byte code directly? that's the part I did not understand, so thanks for pointing that out. What I disassembled did not make sense. I was looking for assembler code, but I do understand a little bit about how the interpreter reads them. For example, from os.py, here's part of the script: # Note: more names are added to __all__ later. __all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep", "defpath", "name", "path", "devnull"] here's the disassembly from os.pyc: 00000C04 06 00 00 00 dd 6 00000C08 61 6C 74 73 65 70 74 db 'altsept' 00000C0F 06 00 00 00 dd 6 00000C13 63 75 72 64 69 72 74 db 'curdirt' 00000C1A 06 00 00 00 dd 6 00000C1E 70 61 72 64 69 72 74 db 'pardirt' 00000C25 03 00 00 00 dd 3 00000C29 73 65 70 db 'sep' 00000C2C 74 07 00 00 dd 774h 00000C30 00 db 0 00000C31 70 61 74 68 73 65 70 db 'pathsep' 00000C38 74 07 00 00 dd 774h 00000C3C 00 db 0 00000C3D 6C 69 6E 65 73 65 70 db 'linesep' 00000C44 74 07 00 00 dd 774h 00000C48 00 db 0 00000C49 64 65 66 70 61 74 68 db 'defpath' 00000C50 74 04 00 00 dd offset unk_474 00000C54 00 db 0 00000C55 6E 61 6D 65 db 'name' 00000C59 74 04 00 00 dd offset unk_474 00000C5D 00 db 0 00000C5E 70 61 74 68 db 'path' 00000C62 74 07 00 00 dd 774h 00000C66 00 db 0 00000C67 64 65 76 6E 75 6C 6C db 'devnull' you can see all the ASCII names in the disassembly like altsep, curdir, etc. I'm not clear as to why they are all terminated with 0x74 = t, or if that's my poor interpretation. Some ASCII strings don't use a 0 terminator. The point is that all the ASCII strings have numbers between them which mean something to the interpreter. Also, they are at a particular address. The interpreter has to know where to find them. The script is essentially gone. I'd like to know how to read the pyc files, but that's getting away from my point that there is a link between python scripts and assembler. At this point, I admit the code above is NOT assembler, but sooner or later it will be converted to machine code by the interpreter and the OS and that can be disassembled as assembler. I realize this is a complicated process and I can understand people thinking I'm full of beans. Python needs an OS like Windows or Linux to interface it to the processor. And all a processor can understand is machine code. > >> Assembler is nothing but codes, which are combinations of 1's and >> 0's. > >No, assembly language source is readable text like this (gcc): > >.LCFI4: > movl $0, %eax > popl %ecx > popl %ebp > leal -4(%ecx), %esp > ret > Yes, the source is readable like that, but the compiled binary is not. A disaasembly shows both the source and the opcodes. The ret statement above is a mneumonic for hex C3 in assembler. You have left out the opcodes. Here's another example of assembler which is disassembled from python.exe: 1D001250 FF 74 24 04 push [esp+arg_0] 1D001254 E8 D1 FF FF FF call 1D00122A 1D001259 F7 D8 neg eax 1D00125B 1B C0 sbb eax, eax 1D00125D F7 D8 neg eax 1D00125F 59 pop ecx 1D001260 48 dec eax 1D001261 C3 retn the first column is obviously the address in memory. The second column are opcodes, and the third column are mneumonics, English words attached to the codes to give them meaning. The second and third column mean the same thing. A single opcode instruction like 59 = pop ecx and 48 = dec eax, are self-explanatory. 59 is hexadecimal for binary 01011001, which is a binary code. When a processor receives that binary as voltages, it is wired to push the contents of the ecx register onto the stack. The second instruction, call 1D00122A is not as straight forward. it is made up of two parts: E8 = the opcode for CALL and the rest 'D1 FF FF FF' is the opcode operator, or the data which the call is referencing. In this case it's an address in memory that holds the next instruction being called. It is written backward, however, which is convention in certain assemblers. D1 FF FF FF actually means FF FF FF D1. This instruction uses F's to negate the instruction, telling the processor to jump back. The signed number FFFFFFD1 = -2E. A call counts from the end of it's opcode numbers which is 1D001258, and 1D001258 - 2E = 1D00122A, the address being called. As you can see, it's all done with binary codes. The English statements are purely for the convenience of the programmer. If you look at the Intel definitons for assembler instructions, it lists both the opcodes and the mneumonics. I would agree with what you said earlier, that there is a similarity between machine code and assembler. You can actually write in machine code, but it is often entered in hexadecimal, requiring a hex to binary interpreter. In tht case, the similarity to compiled assembler is quite close. >Machine language is binary codes, yes. > >> You can't read a pyc file in a hex editor, > if I knew what the intervening numbers meant I could. :-) >By definition, you can read every file in a hex editor ... > >> but you can read it in a disassembler. It doesn't make a lot of >> sense to me right now, but if I was trying to trace through it >> with a debugger, the debugger would disassemble it into >> assembler, not python. > >Not at all. Again: It's Python byte code. Try experimenting with >pdb. I will eventually...thanks for reply. From http Wed Jan 16 03:12:08 2008 From: http (Paul Rubin) Date: 16 Jan 2008 00:12:08 -0800 Subject: itertools.groupby References: <478d0b7d$0$26094$88260bb3@free.teranews.com> Message-ID: <7xejcii3zb.fsf@ruckus.brouhaha.com> Tobiah writes: > I tried doing this with a simple example, but noticed > that [].sort(func) passes two arguments to func, whereas > the function expected by groupby() uses only one argument. Use: [].sort(key=func) From aekidens at yahoo.es Sun Jan 13 05:09:11 2008 From: aekidens at yahoo.es (Gabriel) Date: Sun, 13 Jan 2008 02:09:11 -0800 (PST) Subject: Graphics Module References: Message-ID: On 11 ene, 22:51, Mike wrote: > On Jan 11, 3:31 pm, "Gabriel" wrote: > > > Hi all ! > > > I'm developing a math program that shows graphics of functions. > > I would hear suggestions about the way of drawing 2D . > > > Thanks a lot for your answers. > > > - Gabriel - > > That's not a very descriptive question, however most people talk about > matplotlib for graphing and 2D drawings. > > Here's a few links on graphing in Python: > > http://matplotlib.sourceforge.net/http://wiki.python.org/moin/PythonGraphApihttp://alpha-leonis.lids.mit.edu/nlp/pygraph/http://boost.org/libs/graph/doc/python.htmlhttp://www.python.org/doc/essays/graphs.html > > Some of these may have dependencies, such as numpy or scipy. Be sure > to read the docs for full details either way. > > Mike Thanks ! Yes. This is what I was looking for.. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 21 07:48:45 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 13:48:45 +0100 Subject: Basic inheritance question In-Reply-To: <34aa1a1f-2034-471d-91ee-2a758dab555b@f47g2000hsd.googlegroups.com> References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> <478e1e3e$0$18054$426a74cc@news.free.fr> <34aa1a1f-2034-471d-91ee-2a758dab555b@f47g2000hsd.googlegroups.com> Message-ID: <47949466$0$18516$426a34cc@news.free.fr> Lie a ?crit : > On Jan 16, 9:23 pm, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: >> Lie wrote: >>> 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >>>> I used to systematically use it - like I've always systematically >>>> used 'this' in C++ and Java. >>> And that is what reduces readability. >> IMHO not, IOPHO not. This is the nth time (n >> 1) this discussion >> comes up here. If I have learned one thing from those very lengthy >> discussions, it's that Python's "self" handling is not going to >> change. > > And ah... yes, I don't wish it go away either. In VB, excessive Me > reduces readability, but in Python it doesn't. > >>> A proficient VB/C/Java programmer would frown upon the extra, >>> unneeded garbage as they thought it was clear already that the >>> variable refers to a class-level variable. >> C programmers surely have no opinion concerning C because it has no >> native classes. > > C-family, ok? Well... I'm not sure what "C-family" means, but to me it would consist in C, C++, Objective C, and D. > Please stop taking my words to its letters. So we're supposed to actually guess what you really mean ??? >> Personally, I've seen many C++ programs with complex class designs >> where it definitely helps to consistently use "this->". I cannot >> remember all local (and global) variables in bigger methods. > > In that case, you have the _option_ to do it. Make no sens when maintaining code wrote by someone that didn't use this 'option'. (snip) >>>> it's the first argument of the function - which usually happens to be >>>> the current instance when the function is used as a method. >>> And that's the point, self (or anything you name it) is almost always >>> the current instance >> # this is a plain function. In this function, >> # 'obj' can be whatever that happens to have a (numeric) >> # 'stuff' attribute >> def func(obj, arg): >> return (obj.stuff + arg) / 2.0 >> >> # this is a class with an instance attribute 'stuff' >> class Foo(object): >> def __init__(self, bar): >> self.stuff = bar + 42 >> >> # this is another (mostly unrelated) class >> # with a class attribute 'stuff' >> class Bar(object): >> stuff = 42 >> >> # this is a dummy container class: >> class Dummy(object): pass >> >> # now let's play: >> import new >> >> d = Dummy() >> d.stuff = 84 >> print func(d, 1) >> >> d.baaz = new.instancemethod(func, d, type(d)) >> print d.baaz(2) >> >> f = Foo(33) >> print func(f, 3) >> Foo.baaz = func >> f.baaz(4) >> >> print func(Bar, 5) >> Bar.baaz = classmethod(func) >> Bar.baaz(6) >> >>> and that makes it functionally the same as Me and >>> this in VB and Java. >> Depends on the context, cf above !-) > > Please again, stop taking letters to the words, I don't meant them to > be exactly the same, rather the same would meant that they generally > can be considered equal, If you still think that way after having read the above code, then I can't help. We obviously don't share the same mental model here. > exceptions exists of course. And btw, I don't > understand what you meant by your example, they seemed to be a > completely OK program for me, Indeed it's ok (even if totally useless by itself). The point is that 'self' (or whatever you name it) is just and only the first argument of a function, period. > even though it's a bit confusing to > follow[2]. Nothing in it should be confusing to anyone having a decent knowledge of Python's object model IMHO. > [2] btw, the reason it's a bit confusing to follow is one of my > points: It is a Bad Thing(tm) to use the same name for different > variables Where do I "use the same name for different variables" here ? > even in a language like Python that enforce explicit naming > of classes Python doesn't "enforce" explicit name of classes - IIRC, there are ways to instanciate anonymous class objects. But I definitively don't see how this relate to this discussion. Yes, I know, "please guess what I mean" !-) but sorry, there's no sens discussing a technical point without using accurate and appropriate technical naming of technical concepts invlved. >>>>> Most other languages >>>>> 1) automatically assign the containing class' object >>>> s/containing class' object/current instance/ >>>>> in a keyword >>>>> (Java: this, VB: Me) behind the screen, >>>> That's not very far from what a Python method object does - >>>> automatically assign the current instance to something. The difference >>>> is that Python uses functions to implement methods (instead of having >>>> two distinct contructs), so the only reliable way to "inject" the >>>> reference to the current instance is to pass it as an argument to the >>>> function (instead of making it pop from pure air). >>> It isn't very far, but Python makes it obvious about the assignment >>> (not behind the screen). >> Exactly. And given both the simplicity of the solution and what it let >> you do, that's a *very* GoodThing(tm) IMHO. > > I agree, it's a Good Thing but it doesn't make the point less pointy, > the difference between Me/this and self is just the explicit > assignment. Other things that is possible because of the explicit > assignment is just a "coincidence" of design choice. Are you sure ? As far as I'm concerned, I think that the design choice somehow results from what it makes possible. (snip pointless discussion wrt/ # of attributes) >>> And it is always a Bad Thing(tm) to use the same name for two >>> variable in the class and in function (which is the main and only >>> source of possible ambiguity) in ANY language, even in Python. >> Ho, yes.... Like, this would be bad ? >> >> class Person(object): >> def __init__(self, firstname, lastname, birthdate, gender): >> self.firstname = firstname >> self.lastname = lastname >> self.birthdate = birthdate >> self.gender = gender >> >> C'mon, be serious. It's often hard enough to come with sensible names, >> why would one have to find synonyms too ? Try to come with something >> more readable than the above, and let us know. Seriously, this braindead >> rule about "not using the same name for an attribute and a local var" >> obviously comes from languages where the "this" ref is optional, and >> FWIW it's obviously the wrong solution to a real problem (the good >> solution being, of course, to use the fully qualified name for >> attributes so there's no possible ambiguity). > > The code fragment you've given way above (about the Foo, Bar, bazz, > and func) also suffers from the bad habits of using the same name for > different variables. Where ? And how does this answer the question above ? > And it's not a "braindead" rule The way you express it, and as far as i'm concerned, it is, definitively. > The example you've given IS the most readable form since the function > is _simple_, consider a function that have complex codes, possibly > calculations instead of simply assigning initial values I'm sure you'd > slip up between the self.* variables and the * variables once or > twice, *you* would perhaps have this problem. And you would indeed have this problem in Java or C++. In Python, this problem just don't exist. > possibly becoming the source of hard-to-find bugs. Consistant and intelligible naming is quite another problem. And it's too much dependant on the context, language, domain and whatnot for any rule like your one above to be universally applyable. > And in languages that doesn't enforce explicit naming of classes, I still don't understand how all this relates to the naming of class objects ? Oops, sorry: you meant "in languages that has implicit instance reference available in methods" ? Python doesn't have it, so any rule deriving from this "feature" is out of scope here. > when > there is the two or more same names, the one with the smallest scope > is picked, so in _simple_ functions, the trick of using full qualified > names and overloaded local names is still possible and feasible. In > complex functions, the trick fails even in Python, because even if > Python and our full-concentration-brain is aware of the difference > between self.* and *, our spreaded-concentration-brain that is > scanning the code for the source of bugs might get stumbled on the > confusing use of self.* and *. Here again, *you* may have this problem. I don't, since I always used explicit instance reference. >>>> Anyway, I actually know 3 languages (4 if C# works the same) that has >>>> this implicit 'this' (or whatever the name) 'feature', and at least 5 >>>> that don't. So I'm not sure that the "most other languages" qualifier >>>> really applies to point 2 !-) >>> What's this 5 languages? >> Smalltalk, Python, PHP, javascript, Ruby. I don't remember how Scheme, >> CLOS and OCaml handle the case. > > Among all them, only Javascript is considerably mainstream. Is that a joke ? PHP is probably the most used language for web apps (server side of course). And Python is certainly not an obscure unknown geek-only language no more. But anyway: you were talking about "most other languages" - not "most mainstream languages". >>> Are they a mainstream, high-level languages >>> or lesser known, low-level languages? C-family, Java, and Basic are >>> the Big Three of high-level programming language. >> None of C, C++, Java nor Basic qualify as "hi-level". C is the lowest >> possible level above assembly, C++ is often refered to as an "object >> oriented assembler", Java is way too static, crippled, verbose an >> unexpressive to qualify as "hi-level" (even if it suffers from some >> problems usually associated with higher level languages). I won't even >> comment on basic (is that really a language at all ?). > > Your criteria on being high-level is simply just odd. My criteria on being hi-level seems quite common: automatic memory management, portability, "rich" builtin data types, functions as first class citizens, lexical closures, strong introspection features, strong metaprogramming support, etc... > The rest of the > world recognizes C-family, Java, and Basic as high-level languages. C was "hi-level" wrt/ assembler, indeed. And Java is "hi-level" wrt/ C++. Ho, and _please_ don't get me started on basic !-) > If I have to say it, Python is actually lower level than Basic. No comment. > While > Java is just below Python and C and C++ is just below Java. Why do I > consider Basic the highest-level? Because it is the cleanest to scan > (no confusing symbols, i.e. no curly braces, no confusing use of > parens (Python uses (), [], and {}, VB only use ()[3]), Basic != VB. There are quite a few other basics here. Now if you choose this criteria, you may want to learn some Lisp dialect. > > In what way C++ resembles an assembler? C++ is some OO stuff bolted on a very close-to-the-metal language itself designed to write operating systems, drivers and other low-level stuff. > Have you ever programmed in > assembly? I did. > How hard is it to create a simple program in assembly? And > how hard is it to create a complex program in C++ Roughly the same, thanks to scoping rules, dependencies hell, lack of automatic memory management and overcomplex features. > (which AFAIK is used > by hundreds of mega projects including CPython)? CPython - as the name implies - is written in C. > And have you ever used Basic at all? I did. And not only VB. > Some programmers would instantly frown upon Basic, simply because they > don't know that Basic is "just another language". I've used at least four different variants of Basic. >>>>> In VB, Me is extremely rarely used, >>>> I used to systematically use it - like I've always systematically used >>>> 'this' in C++ and Java. >>> And that is what reduces readability. A proficient VB/C/Java >>> programmer >> There are quite a few proficient C/C++/Java programmers here. As far as >> I'm concerned, I would not pretend being one - I just have a good enough >> knowledge of C, Java and (alas) VB to be able to get up to speed in a >> reasonnable time frame. >> >> As a side note, the problem just doesn't exists in C, which has >> absolutely no support for OO. > > When I said C, it might mean C and C-family, When you say "C", it means "C" to everyone reading you. > so please stop > misunderstanding me. Please learn to express yourself clearly. If you say "X" when you mean "Y", *you* are the one responsible for misunderstandings. This is human communication 101 skill. (snip) > I'm not saying my mindset is better than yours (it have its positives > and negatives), in fact I apologize for getting you confused. My "mindset", as you say, is the one you'll find in each and every technical communication. You can't discuss technical points without a clear, unambiguous naming of technical concepts. And when a community exists, it usually has it's own technical idiom, whether highly specific (ie : "member variables" in C++, "attributes" in Python), or more general (ie: C is not the same thing as C++, whenever language you're using). >>> would frown upon the extra, unneeded garbage as they >>> thought it was clear already that the variable refers to a class-level >>> variable. >> In C++, the canonical way to make this "clear" is to use the m_name >> convention. There must be some reason C++ programmers feel a need for >> this "extra, unneeded garbage" ?-) > > In some cases, an extremely complex class that can't be fragmented any > further, the m_ convention is surely useful, but in most cases you > could skip them out. You "could" skip this convention, but it's really considered bad practice by quite a lot of C++ programmers. > And the canonical way to make this "clear" is not > the m_ convention, it's the name itself. A well-designed class would > choose names that is recognizable instantly from the name itself, even > without the pseudo-name appended to it (or prepended). I await for your exemples. > btw you must have been memorizing names braindeadly, because the only > way you could stumble on that is by memorizing names braindeadly. > Names shouldn't be memorized, it should be inferred and memorized. For > example, when you met a variable name firstname and lastname inside a > class called Person, you'd immediately realize that it is Class Level > variable because you know that the function you're currently working > on use the name initialfirstname and initiallastname. Fine, I now have four names to handle, each of them being possibly an argument, a local variable, a member variable or a global variable. Great. Sorry but I won't buy this. (snip) >>> As I've pointed out, there is little harm in class-level variable's >>> implicit reference. >> Have some working experience on any non-trivial C++ project ? > > No I would have been surprised if you had answer otherwise. > (you could say I'm a student so I've never "worked"[1]). But I've > done some medium-sized projects in other languages. > > [1] If you understand the irony, you'd realized I was deliberately > misunderstanding you Not sure. >>>>> Compare the following codes: >>>>> VB.NET: >>>>> Public Class A >>>>> Dim var >>>>> Public Function aFunction() >>>>> return var >>>> Add three levels of inheritence and a couple globals and you'll find out >>>> that readability count !-) >>> It's the mental model that have to be adapted here, if the current >>> class is inheriting from another class, you've got to think it as >>> names from parent class as it is a native names, so you don't actually >>> need to know where the variable comes from >> In C++ (and VB IIRC), it might as well be a global So sorry but yes, I >> have to know where it comes from. > > How many times would you use globals, it is a Bad Thing(tm) to use > globals in the first case. It is, most of the time, indeed. The problem is that you rarely start a project from scratch - most of the time, you have to work on legacy code. And you really seldom have the possibility to do a major rewrite to fix all warts. > In some exceptional cases globals might be > unavoidable, but it is trivial to work out that you have to reduce the > amount of globals to a minimum, in almost any cases to a number you > can use a hand to count with. That very nice, from a theoretical POV. That's alas just not how it works in real life. > And applying the hacks mentioned, why > don't you use the m_ convention for globals, and retains the > convenience of m_-free variables in your class variable. You use class > variable much more often than globals, and in most projects class- > level variable is used just as often as local-variable. The problem is not what *I* (would) do, but how is the existing code. >>> since knowing where it >>> comes from is breaking the encapsulation >> Nope, it's knowing what you're doing and how the piece of software at >> hand is working. And FWIW, while data hiding is one possible mean of >> encapsulation, it's by no way a synonym for encapsulation. > > I agree that knowing an underlying class's implementation is useful > (in fact, very useful) but what I'm talking is about should-ness, > we > shouldn't _need_ to know the underlying implementation, How can you hope to extend a class without _any_ knowledge of it's implementation ? (snip) > >>> (which, in Python is very >>> weakly implemented, which favors flexibility in many cases[1]). >>> [1] In Python, it is impossible to create a completely private >>> variable, which is the reason why the mental model of these other >>> languages doesn't fit Python. >> Never heard about the infamous '#define private public' hack in C++ ? >> And don't worry, there are also ways to get at so called 'private' vars >> in Java. > > No, but it's violating the language's rule. Nope. It's just making use of some part of the language's rules. > Python OTOH, provides > formal ways to got to private vars. Python doesn't have "private vars" at all. >>>> In any non-trivial piece of C++ code, and unless the author either used >>>> the explicit 'this' reference or the 'm_xxx' naming convention, you'll >>>> have hard time figuring out where a given name comes from when browsing >>>> a function's code. >>> If you're used to the implicit naming scheme it's easy to know where a >>> variable came from, if not the current scope, it's the class' scope >> You forgot the global scope. > > How many global variables do you have in your projects on average? If > you always have a pageful list of globals in your projects, then you > should consider unlearning and relearning the basic programming > concepts. I'll come to you when I'll need more training, don't worry. > It's easy to keep track of globals, as you shouldn't have a > lot of them even in a huge project. Can't you understand that starting a new project afresh is *not* the common case ? >>> As a final note: >>> I don't think implicit class reference is superior to explicit class >>> reference, neither >> ... > > I'm sure you don't believe it since I'm talking on implicit's side, > but that's the fact, I just pointed you out that implicits do have its > positive side (even if you don't consider them positive in _your_ > book) but that doesn't meant I believe it is better than the other. > > To clear things up: > As a final note: > I don't think implicit class reference is superior to explicit class > reference, but I don't think the vice versa is true either. Once again : what classes have to do with this ? Seriously, how can you hope to be taken seriously when you're obviously confusing such important concepts as instance and class ? From robert.kern at gmail.com Sat Jan 12 17:44:27 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 12 Jan 2008 16:44:27 -0600 Subject: Is unicode.lower() locale-independent? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Robert Kern wrote: > >>> However it appears from your bug ticket that you have a much narrower >>> problem (case-shifting a small known list of English words like VOID) >>> and can work around it by writing your own locale-independent casing >>> functions. Do you still need to find out whether Python unicode >>> casings are locale-dependent? >> I would still like to know. There are other places where .lower() is used in >> numpy, not to mention the rest of my code. > > "lower" uses the informative case mappings provided by the Unicode > character database; see > > http://www.unicode.org/Public/4.1.0/ucd/UCD.html > > afaik, changing the locale has no influence whatsoever on Python's > Unicode subsystem. Even if towlower() gets used? I've found an explicit statement that the conversion it does can be locale-specific: http://msdn2.microsoft.com/en-us/library/8h19t214.aspx Thanks, Fredrik. -- 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 mario at ruggier.org Thu Jan 3 16:03:08 2008 From: mario at ruggier.org (mario) Date: Thu, 3 Jan 2008 13:03:08 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> Message-ID: <76ba16c8-6ba0-4609-80bd-cd54aa08d74b@5g2000hsg.googlegroups.com> On Jan 2, 2:25 pm, Piet van Oostrum wrote: > Apparently for the empty string the encoding is irrelevant as it will not > be used. I guess there is an early check for this special case in the code. In the module I an working on [*] I am remembering a failed encoding to allow me, if necessary, to later re-process fewer encodings. In the case of an empty string AND an unknown encoding this strategy failed... Anyhow, the question is, should the behaviour be the same for these operations, and if so what should it be: u"".encode("non-existent") unicode("", "non-existent") mario [*] a module to decode heuristically, that imho is actually starting to look quite good, it is at http://gizmojo.org/code/decodeh/ and any comments very welcome. From bignose+hates-spam at benfinney.id.au Thu Jan 17 19:31:53 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 18 Jan 2008 11:31:53 +1100 Subject: Complex discussions of "simple" problems (was: Loop in a loop?) References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> <7xy7aong73.fsf@ruckus.brouhaha.com> Message-ID: <87ir1sas92.fsf_-_@benfinney.id.au> Paul Rubin writes: > Not trying to pick on you personally but there's this disease when a > newbie comes with a basically simple question (in this case, how to > solve the problem with ordinary lists) and gets back a lot of > complex, overly general "graduate level" solutions. Is that a disease? I would characterise it as symptomatic of a very healthy programming community. We like interesting problems, and enjoy coming up with ever more elegant solutions. The discussions that ensue are healthy, not diseased. Whether that's exactly what the original poster in such a thread wants is beside the point. This forum is for the benefit of all participants, and discussing an apparently simple problem to discover its complexities is part of the enjoyment. Enjoyment of the discussion, after all, is the main reward most people can ever hope to get for participation in most threads here. -- \ "Remember: every member of your 'target audience' also owns a | `\ broadcasting station. These 'targets' can shoot back." -- | _o__) Michael Rathbun to advertisers, news.admin.net-abuse.email | Ben Finney From xena-die-kriegerprinzessin at gmx.de Thu Jan 17 10:08:14 2008 From: xena-die-kriegerprinzessin at gmx.de (Heiko Niedermeyer) Date: Thu, 17 Jan 2008 15:08:14 +0000 (UTC) Subject: How to create graphs an embed them in GUI? Message-ID: Sorry for the fuzzy subject... Currently I'm writing a little programm to extract some chemical information out of a text file, and then present it in a pleasant way. The Extraction works so far, so now the presentation will be next. As I'm learning Python from scratch, I don't care wether to use (=learn) TKinter or PyQt or whatever, I just need some advice, which suits my needs best. It would be nice to have the programm working under win and linux (shouldn't be a big Problem) and my requirements concerning the standard elements should be met by almost every framework. My problem is, that I want to add graph (simple, line connected X,Y- scatter plots) and if possible the 3D representation of atoms in a molecule (-> coloured spheres in space). I think it would take me years to program those by myself, so I would ne ready to use packages, if available. Long story short: Are there packages that could do this, and does it matter which GUI I want to embed them in? best wishes From mwm-keyword-python.b4bdba at mired.org Fri Jan 11 18:21:45 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 18:21:45 -0500 Subject: encrypting python modules In-Reply-To: <87sl14getd.fsf@benfinney.id.au> References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <87sl14getd.fsf@benfinney.id.au> Message-ID: <20080111182145.6be85d50@bhuda.mired.org> On Sat, 12 Jan 2008 09:47:26 +1100 Ben Finney wrote: > Paul Sijben writes: > > I know that I can not stop a dedicated hacker deconstructing my code. > A direct consequence of this is that you can not stop *anyone* from > deconstructing your code if it's in their possession. It takes only > one dedicated, skilled person to crack your obfuscation system and > distribute an automated process for doing so to anyone interested. Except that's not what he's trying to do. > > However I can not imagine that I would be the first one planning to > > do this. So is there a solution like this available somewhere? > Trying to make bits uncopyable and unmodifiable is like trying to make > water not wet. And again, that's not what he's trying to do. He wants to arrange things so that he doesn't have to support unmodified versions of his code, by making it impossible to import modified modules. While that's still impossible, once you decide how difficult you want to make it for people to do that, you can *probably* make it that difficult - but the process gets progressively more difficult and expensive as you make it harder. I think he's contemplating only the simplest, least expensive step: adding an import hook that only allows imports of digitally signed modules. If planning to deploy on Windows, where he has to bundle a python with his application, he may well implement the hook in the interpreter instead of in python, so it's harder to find. If you wanted to go to the expense, you could probably arrange things so that the digital signatures are the more vulnerable attack vectors, but I'd expect to spend millions of dollars doing so. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From jr9445 at ATT.COM Fri Jan 11 15:55:18 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 11 Jan 2008 14:55:18 -0600 Subject: alternating string replace In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.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 cesco > Sent: Wednesday, January 09, 2008 5:34 AM > To: python-list at python.org > Subject: alternating string replace > > Hi, > > say I have a string like the following: > s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... > For those of us who still think in Perl, here's an easy to read, lazy solution: s = 'hi_cat_bye_dog' print s s = re.sub(r'_(.*?(_|$))', r':\1', s) ## every odd '_' to ':' print s s = re.sub(r'_', r',', s) ## every even '_' to ',' print s > hi_cat_bye_dog > hi:cat_bye:dog > hi:cat,bye:dog The equivalent Perl code: my $s = 'hi_cat_bye_dog'; print $s, "\n"; $s =~ s/_(.*?(_|$))/:$1/g; print $s, "\n"; $s =~ s/_/,/g; print $s, "\n"; From xng at xs4all.nl Thu Jan 10 08:47:22 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Thu, 10 Jan 2008 14:47:22 +0100 Subject: Python or PowerShell ? In-Reply-To: <225fb03f-a385-4651-be3b-7f8998901d46@q77g2000hsh.googlegroups.com> References: <87hchodstr.fsf@physik.rwth-aachen.de> <4783d594$0$8926$e4fe514c@dreader16.news.xs4all.nl> <225fb03f-a385-4651-be3b-7f8998901d46@q77g2000hsh.googlegroups.com> Message-ID: <478621d7$0$30541$e4fe514c@dreader32.news.xs4all.nl> kyosohma at gmail.com wrote: > On Jan 8, 1:57 pm, "Martin P. Hellwig" wrote: >> And adding to that, if you don't care about cross platform anyway, why >> even bother with python? I am sure that MS has tools that can do in a >> point and click kind of way all the things you might encounter. > > I code mostly for Windows users, but I use Python almost exclusively. > Why? > > 1) Python is "free" > 2) Microsoft Visual Studio is very expensive > 3) Python is Open Source > 4) Visual Studio is not Open Source > 5) I can actually take the code from IDLE and refine it for my > purposes if it doesn't suit me. Good luck doing that with practically > anything Microsoft supplies. > 6) With relative ease, I can go cross-platform with my code if > requirements change > > I could go on. There are many good reasons to use Python (or some > other good open source language, like Ruby) even if you just program > for Windows. > > Mike Well if that are your requirements, which are all good ones btw, then you have answered your own question :-) -- mph From timr at probo.com Sat Jan 12 00:52:37 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 12 Jan 2008 05:52:37 GMT Subject: ISO Python example projects (like in Perl Cookbook) References: Message-ID: <4clgo35m078db7q0i4gt615fsvb6g74kk3@4ax.com> "Delaney, Timothy (Tim)" wrote: > >You know you've been working at a large company for too long when you >see that subject and think "ISO-certified Python?" That's exactly what I thought, too. After reading the post I assume he actually meant "In Search Of"? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From grante at visi.com Sun Jan 27 10:56:25 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 27 Jan 2008 15:56:25 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <13ppad9ahqrqh92@corp.supernews.com> On 2008-01-27, over at thepond.com wrote: > Whatever is typed in a Python script must be converted to > binary code. Python scripts _are_ in a binary code when the start out. -- Grant Edwards grante Yow! What UNIVERSE is at this, please?? visi.com From manugarg at gmail.com Wed Jan 23 05:28:36 2008 From: manugarg at gmail.com (Manu Garg) Date: Wed, 23 Jan 2008 15:58:36 +0530 Subject: Announcement: Python module for pacparser (parses proxy auto-config files) Message-ID: <8ea71edb0801230228y249bff93x3fc9b174b3187453@mail.gmail.com> Fellas, I am mighty pleased to announce the release of python module for pacparser. pacparser is a library to parse proxy auto-config (PAC) files. Proxy auto-config files are already a vastly used web proxy configuration method these days (either directly or via web proxy autodiscovery protocol) and almost all popular web browsers support them. pacparser python module brings in PAC file parsing capability to python programs. Using it, python web software can now work with proxy auto-config files. I am hoping, web software programmers will appreciate it. At least I've been looking for such a thing for a while :). For documentation and available packages, please visit project homepage at http://code.google.com/p/pacparser Direct download links: Source archive: http://pacparser.googlecode.com/files/pacparser-1.0.3.tar.gz Compiled module for python 2.5 and win32: http://pacparser.googlecode.com/files/pacparser-python25-1.0.3-win32.zip I have tested the module to work on Python 2.2 - 2.5 on Linux and Win32. Cheers :-), Manu -- Manu Garg http://www.manugarg.com "Journey is the destination of life." From nagle at animats.com Thu Jan 3 13:22:24 2008 From: nagle at animats.com (John Nagle) Date: Thu, 03 Jan 2008 10:22:24 -0800 Subject: urllib timeout hole - long timeout if site doesn't send headers. Message-ID: <477d26f4$0$36384$742ec2ed@news.sonic.net> urllib has a "hole" in its timeout protection. Using "socket.setdefaulttimeout" will make urllib time out if a site doesn't open a TCP connection in the indicated time. But if the site opens the TCP connection and never sends HTTP headers, it takes about 20 minutes for the read in urllib's "open" to time out. There are some web servers that produce this behavior, and many seem to be associated with British universities and nonprofits. With these, requesting "http://example.com" opens a TCP connection on which nothing is ever sent, while "http://www.example.com" yields a proper web page. Even Firefox doesn't time this out properly. Try "http://soton.ac.uk" in Firefox, and be prepared for a long wait. There was some active work in the urllib timeout area last summer. What happened to that? John Nagle From hv at tbz-pariv.de Fri Jan 4 03:03:25 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Fri, 04 Jan 2008 09:03:25 +0100 Subject: Resetting Signal Mask Message-ID: <5u67idF1g380iU1@mid.individual.net> Hi, with mod_wsgi (apache2) a process created with os.system() has a modified signal mask, that SIGPWR gets ignored. A small wrapper (see bottom) resets the signal mask and uses execv to run the programm. Unfortunately python does not support sigprocmask. Is there any other way to reset the signal mask? I guess it could be done with ctypes (I never used it up to now). Why is sigprocmask not available in Python? Python exposes most of the other POSIX API. Thomas 1 #include 2 #include 3 #include 4 5 int main(int argc, char *argv[]) { 6 sigset_t newmask; 7 8 sigemptyset(&newmask); 9 sigprocmask(SIG_SETMASK, &newmask, NULL); 10 int ret=execv(argv[1], &argv[1]); 11 if (ret != 0) { perror(argv[0]); } 12 return ret; 13 } From Lie.1296 at gmail.com Fri Jan 11 06:24:01 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 11 Jan 2008 03:24:01 -0800 (PST) Subject: what does **kw mean? References: <99cc3280-bffd-4004-a3ae-a06244a82759@e6g2000prf.googlegroups.com> Message-ID: On Jan 11, 4:38?pm, "zsl... at gmail.com" wrote: > I've been reading the following example, and couldn't figure out, what > **kw mean. (It's an empty dictionary, but what's the semantics): It's a keyword argument. It's some kind of repository for arguments that aren't recognized. If you have function like this: def func(a, *args, *kw): print a print args print kw and you call the functin like this: func('value A', 'value B', 'value C', argumentA = 'value D', argumentB = 'value D') the extra arguments would normally raise an error, but with the * and **, Python would: - assign 'value B' and 'value C' to args - assign 'argumentA':'value D' and 'argumentB':'value E' to kw so if you run the function, it will output: #### value A ('value B', 'value C') {'argumentB': 'value E', 'argumentA': 'value D'} #### this args and kw can be accessed like a tuple and dictionary respectively See '4.7.2 Keyword Arguments' and '4.7.3 Arbitrary Argument Lists' on Python Help File From lepto.python at gmail.com Wed Jan 9 01:48:39 2008 From: lepto.python at gmail.com (oyster) Date: Wed, 9 Jan 2008 14:48:39 +0800 Subject: hkimball's question on ctypes Message-ID: <6a4f17690801082248i7d9119a3s57264b062e86345b@mail.gmail.com> 2008/1/9, python-list-request at python.org : > Date: Tue, 8 Jan 2008 17:11:18 -0800 (PST) > Subject: ctypes 1. please make your title more specific > >>> from ctypes import * > >>> cdecl = > cdll.LoadLibrary("c:\projects\python\geinterface.dll") 2. are you sure '\' is ok? cdll.LoadLibrary(r"c:\projects\python\geinterface.dll") or cdll.LoadLibrary("c:/projects/python/geinterface.dll") 3. if possibile, you can upload your dll and post the link in the mail-list 4. there is a ctypes official maillist on http://sourceforge.net/projects/ctypes/. but it seems that it is closed to the users since some of my mail from 2007.12 does not appear here. but maybe you can have a try. From asmodai at in-nomine.org Wed Jan 9 01:54:52 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 9 Jan 2008 07:54:52 +0100 Subject: Pet Store In-Reply-To: <44713824-c8c9-4a4c-af7e-042260068c0c@x69g2000hsx.googlegroups.com> References: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com> <5ugv69F1hqn2cU3@mid.uni-berlin.de> <44713824-c8c9-4a4c-af7e-042260068c0c@x69g2000hsx.googlegroups.com> Message-ID: <20080109065452.GN75977@nexus.in-nomine.org> -On [20080108 19:36], George Maggessy (george.maggessy at gmail.com) wrote: >Yeap. It is. I'm looking for something like that app. Smth that I >could base my future developments on. If you want to go the Ruby on Rails-like road then you have Django, Pylons, TurboGears, Zope, to name four of the bigger ones. If you want a basic HTTP handling framework under which you can hang your own code more easily then you should look at things like Paste, WebOb, CherryPy, Werkzeug, Twisted and others. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Teachers open the door, but you must enter by yourself. -Chinese Proverb From kyosohma at gmail.com Fri Jan 18 14:00:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jan 2008 11:00:13 -0800 (PST) Subject: Pythonland documentation References: Message-ID: <0ca3afaa-9e35-42e6-b3fd-da6d2cf012b5@i7g2000prf.googlegroups.com> On Jan 18, 12:51 pm, Simon Pickles wrote: > Hi > > I am new to python (fairly) but can't stop pythonning. > > c++ seems so far away now.... from here it looks like a horrid scribble :) > > Anyway.... my question is really about doc tools. I've been used to > doxygen in c++ land, and although it makes a reasonable stab with a > python project in java mode, the output is a bit messy. > > Can any one suggest a more tailored tool? or do I risk a flamewar? :) > > Thanks > > SiPi > > -- > Linux user #458601 -http://counter.li.org. Well, there's DocUtils: http://docutils.sourceforge.net/ And here are some others: http://peak.telecommunity.com/protocol_ref/protocols-example1.html And finally, there's this: http://www.python.org/community/sigs/current/doc-sig/otherlangs/ Mike From sjmachin at lexicon.net Fri Jan 11 15:22:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 12 Jan 2008 07:22:39 +1100 Subject: scope question in a switch mixin In-Reply-To: References: Message-ID: <4787D00F.7030900@lexicon.net> browerg at verizon.net wrote: > The code that follows is the result of noodling around with switches as a learning tool. I've played with python for a few years, but I'm self-taught, so . . . > > Class Switch builds a set of functions. Method switch executes one of them given a value of the switch variable. > > My question is, why are modules imported at the top of the program not visible to the functions Switch builds? There is > no problem when the import is in the function, but I thought initially that imports at the top would be in its globals. The global namespace of the to-be-exec'ed code is the dictionary that you supply. That dictionary doesn't contain "math". More comments below. [snip] > > #import math > > class Switch(object): > > def __init__(self, keys, vals, base): > self.dictionary = {} > tmpd = {} Uncomment the above import, remove the import from your constructed source code and try tmpd = {'math': math} > for i in range(len(vals)): > func = ''.join([base[0] % keys[i], vals[i], base[1]]) > compile(func, '', 'exec') > exec(func, tmpd) compile returns a code object, which you are throwing away. Comment out that statement, and the behaviour of your code will not change. This is because if the first argument to exec is a string, it is compiled into a code object. It's a long time since exec has been documented as a *function*. Why? Because it isn't: >>> exec "print 'xxx'" xxx >>> exec("print 'xxx'") xxx >>> foo = compile >>> foo >>> foo = exec File "", line 1 foo = exec ^ SyntaxError: invalid syntax >>> What book/tutorial did you get that from? Cheers, John From lasses_weil at klapptsowieso.net Sat Jan 12 08:21:30 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sat, 12 Jan 2008 14:21:30 +0100 Subject: extracting Javadocs using Python In-Reply-To: <30a4948a-7293-43d6-9381-824654e44416@s19g2000prg.googlegroups.com> References: <30a4948a-7293-43d6-9381-824654e44416@s19g2000prg.googlegroups.com> Message-ID: <4788bedd$0$5968$9b4e6d93@newsspool3.arcor-online.net> Rajarshi wrote: > Does anybody know if something like this is available? Or would I need > to implement a parser from scratch? > Probably. But using pyparsing, you shouldn't have a lot of trouble with it. You may want to take a look at epydoc, a python API-doc generator. I seem to remember that in addition to using rST markup, it also provides markup similar to Javadocs. Maybe you can get some "inspiration" from the epydoc sources. regards /W From piet at cs.uu.nl Fri Jan 4 15:02:23 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 04 Jan 2008 21:02:23 +0100 Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: >>>>> bukzor (B) wrote: >B> Why cant you implement < for complex numbers? Maybe I'm being naive, >B> but isn't this the normal definition? >B> a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) There doesn't exist a `normal' definition of < for the complex numbers. For example you would expect that x URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From jr9445 at ATT.COM Tue Jan 29 12:26:30 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 29 Jan 2008 11:26:30 -0600 Subject: Python noob SOS (any [former?] Perlheads out there?) 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 kj > Sent: Tuesday, January 29, 2008 11:39 AM > To: python-list at python.org > Subject: Python noob SOS (any [former?] Perlheads out there?) > > > > For many months now I've been trying to learn Python, but I guess > I'm too old a dog trying to learn new tricks... For better or > worse, I'm so used to Perl when it comes to scripting, that I'm > just having a very hard time getting a hang of "The Python Way." > > It's not the Python syntax that I'm having problems with, but rather > with larger scale issues such as the structuring of packages, > techniques for code reuse, test suites, the structure of > distributions,... Python and Perl seem to come from different > galaxies altogether... It sound like less of a "How to do Things the Python Way" problem, a more of a "How to do Object Oriented Programming" problem. Coming from a C++/Perl background, I found the O'Reilly 'Learning Python' book to be useful. It has a section on OOP, which covers basic OO theory that you may find useful. I can't think of a decent OO book to recommend though. > Be that as it may, the activation barrier to using Python for my > scripting remains too high. > > I'd written a Perl module to facilitate the writing of scripts. > It contained all my boilerplate code for parsing and validating > command-line options, generating of accessor functions for these > options, printing of the help message and of the full documentation, > testing, etc. Bleh. Perl and Python have really good libraries. Why waste time rolling your own when you can use Python's getopt or optparse, or Perl's Getopt and Getopt::Long? From hniksic at xemacs.org Mon Jan 14 11:29:16 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 14 Jan 2008 17:29:16 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> Message-ID: <873at0mkv7.fsf@mulj.homelinux.net> Mel writes: >> I don't understand the purpose of this "correction". After all, >> __init__ *is* the closest equivalent to what other languages would >> call a constructor. > > Nevertheless, __init__ doesn't construct anything. Only if by "construct" you mean "allocate". __init__ starts out with an empty object and brings it to a valid state, therefore "constructing" the object you end up with. That operation is exactly what other languages call a constructor. From thynnus at gNOTmail.com Tue Jan 22 11:33:48 2008 From: thynnus at gNOTmail.com (Thynnus) Date: Tue, 22 Jan 2008 16:33:48 GMT Subject: stdin, stdout, redmon In-Reply-To: <372ff091-2739-4178-bc36-4f8aaffe2972@e23g2000prf.googlegroups.com> References: <4794a5e3$0$9014$426a74cc@news.free.fr> <4794ab22$0$19179$426a74cc@news.free.fr> <4795ba80$0$17176$426a74cc@news.free.fr> <372ff091-2739-4178-bc36-4f8aaffe2972@e23g2000prf.googlegroups.com> Message-ID: On 1/22/2008 8:54 AM, Konstantin Shaposhnikov wrote: > Hi, > > This is Windows bug that is described here: http://support.microsoft.com/default.aspx?kbid=321788 > > This article also contains solution: you need to add registry value: > > HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies > \Explorer > InheritConsoleHandles = 1 (REG_DWORD type) > > Do not forget to launch new console (cmd.exe) after editing registry. > > Alternatively you can use following command > > cat file | python script.py > > instead of > > cat file | python script.py > > Regards, > Konstantin Nice one, Konstantin! I can confirm that adding the registry key solves the problem on XPsp2: -----After adding InheritConsoleHandles DWORD 1 key----- Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. D:\temp>type test3.py | test3.py ['import sys\n', '\n', 'print sys.stdin.readlines ()\n'] D:\temp> The KB article is quite poorly written. Even though it seems to state that issue was 'solved for win2k with sp4, for XP with sp1', and gives no indication that the key is needed after the sp's are applied *even though* it is in fact necessary to the solution. Questions: -Any side effects to look out for? -If the change is relatively benign, should it be part of the install? -Is this worth a documentation patch? If yes to where, and I'll give it a shot. -Thynnus From cptnwillard at gmail.com Thu Jan 17 10:29:28 2008 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Thu, 17 Jan 2008 07:29:28 -0800 (PST) Subject: Is this a bug, or is it me? References: Message-ID: > > You cannot access a class's class variables in it's class-statement > scope, since the name of the type is not bound until after the class > statement is completed. > Thanks for the answer, but then why is there no error with the variable 'TYPES'? This one is accessed first... From sromero at gmail.com Tue Jan 29 12:51:19 2008 From: sromero at gmail.com (Santiago Romero) Date: Tue, 29 Jan 2008 09:51:19 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: Message-ID: > Look at this -- from Python 2.5.1: > > >>> a = [1, 2, 3, 4, 5] > >>> for x in a: > ... if x == 3: > ... a.remove(x) > ... print x Well ... you could use: >>> for i in range(len(a)-1, -1, -1): ... print a[i] ... if a[i] == 3: del a[i] ... 5 4 3 2 1 >>> print a [1, 2, 4, 5] Bye. From bj_666 at gmx.net Thu Jan 10 09:30:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Jan 2008 14:30:19 GMT Subject: Embedding python code into text document question. References: Message-ID: <5umofrF1hs5vpU2@mid.uni-berlin.de> On Thu, 10 Jan 2008 14:10:05 +0100, Thomas Troeger wrote: > I've written a program that parses a string or file for embedded python > commands, executes them and fills in the returned value. The input might > look like this: > > process id: $$return os.getpid()$$ > current date: $$return time.ctime()$$ > superuser: $$ > if os.geteuid(): > return "Yes" > else: > return "No"$$ > > I've tried several solutions using eval, execfile or compile, but none > of those would solve my problem. Does anyone have a solution that works? > Any suggestions? Any help will be appreciated :) My suggestion would be: use one of the many already existing templating systems. Ciao, Marc 'BlackJack' Rintsch From nagle at animats.com Sat Jan 26 15:26:15 2008 From: nagle at animats.com (John Nagle) Date: Sat, 26 Jan 2008 12:26:15 -0800 Subject: Portably killing/signalling another process not supported? In-Reply-To: References: <479b6c58$0$36354$742ec2ed@news.sonic.net> Message-ID: <479b961b$0$36377$742ec2ed@news.sonic.net> Christian Heimes wrote: > John Nagle wrote: >> There doesn't seem to be any way to portably kill another process >> in Python. "os.kill" is Mac/Unix only. The "signal" module only lets >> you send signals to the current process. And the "subprocess" module >> doesn't have a "kill" function. >> >> Subprocess objects really should have a portable "interrupt" or >> "kill" function. They already have "poll" and "wait", which have >> to be implemented differently for different systems; that's the >> logical place for "kill". >> >> Yes, there are nonportable workarounds >> (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462) >> but no portable solution. > > We are looking for somebody to implement a portable and cross platform > implementation of kill() and send_signal() for the subprocess module. > Are you interested in working on a patch for Python 2.6 and 3.0? > Since I use 2.4 and 2.5, I'm interested in something that goes back to at least 2.4. The ActiveState solution above needs C modules that aren't part of the regular CPython distribution, unfortunately. John Nagle From brian at briansmith.org Sun Jan 20 11:09:19 2008 From: brian at briansmith.org (Brian Smith) Date: Sun, 20 Jan 2008 08:09:19 -0800 Subject: HTTP POST uploading large files In-Reply-To: References: Message-ID: <000601c85b7e$d31a4420$0501a8c0@T60> Wolfgang Draxinger wrote: > The problem is, that videos, by nature are rather big files, > however urllib2 wants it's Request objects being prepared > beforehand, which would mean to first load the whole file to memory. Try using mmap. Here is some untested code: map = mmap(file.fileno(), len(file), access=ACCESS_READ) try: data = mmap.read() request = Request(url, data, headers) ... finally: map.close() - Brian From pablo at decode.com.ar Wed Jan 23 18:19:39 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Wed, 23 Jan 2008 21:19:39 -0200 Subject: Increment Variable Name In-Reply-To: <87myqw87lt.fsf@benfinney.id.au> References: <87myqw87lt.fsf@benfinney.id.au> Message-ID: <4797CB8B.3090500@decode.com.ar> Ben Finney wrote: > This has a very bad code smell (...) > > \ `\ _o__) Ben Finney That is forcefulness. (sorry, couldn't resist) From jholg at gmx.de Fri Jan 4 05:43:46 2008 From: jholg at gmx.de (jholg at gmx.de) Date: Fri, 04 Jan 2008 11:43:46 +0100 Subject: adding class functionality, nested scoping Message-ID: <20080104104346.39070@gmx.net> Hi, regarding automatically adding functionality to a class (basically taken from the cookbook recipee) and Python's lexical nested scoping I have a question wrt this code: #----------------- import types # minor variation on cookbook recipee def enhance_method(cls, methodname, replacement): 'replace a method with an enhancement' method = getattr(cls, methodname) def _f(*args, **kwargs): return replacement(method, *args, **kwargs) _f.__name__ = methodname setattr(cls, methodname, types.MethodType(_f, None, cls)) # loop over class dict and call enhance_method() function # for all methods to modify def enhance_all_methods(cls, replacement): for methodname in cls.__dict__: if not methodname.startswith("__"): method = getattr(cls, methodname) def _f(*args, **kwargs): return replacement(method, *args, **kwargs) _f.__name__ = methodname enhance_method(cls, methodname, replacement) # Does not work: all enhanced methods only call the last wrapped originial # method. It seems the name 'method' in the surrounding scope of the # def _(...) function definition only refers to the last loop value(?) def ERRONEOUS_enhance_all_methods(cls, replacement): for methodname in cls.__dict__: if not methodname.startswith("__"): method = getattr(cls, methodname) def _f(*args, **kwargs): return replacement(method, *args, **kwargs) _f.__name__ = methodname setattr(cls, methodname, types.MethodType(_f, None, cls)) class Foo(object): def foo(self, x): print "foo", x def bar(self, x): print "bar", x def logme(method, *args, **kwargs): print "-->", method.__name__, args, kwargs try: return method(*args, **kwargs) finally: print "<--" #enhance_all_methods(Foo, logme) ERRONEOUS_enhance_all_methods(Foo, logme) foo = Foo() foo.foo(2) foo.bar(2) #----------------- ...give this output: >>> foo = Foo() >>> foo.foo(2) --> foo (<__main__.Foo object at 0x1b08f0>, 2) {} foo 2 <-- >>> foo.bar(2) --> foo (<__main__.Foo object at 0x1b08f0>, 2) {} foo 2 <-- >>> So, while using enhance_all_methods() to add functionality does work, ERRONEOUS_enhance_all_methods() does not. Why is this? Is the explanation I tried to give in the code comment on the right track: # Does not work: all enhanced methods only call the last wrapped originial # method. It seems the name 'method' in the surrounding scope of the # def _(...) function definition only refers to the last loop value(?) Thanks for any hint, Holger -- Psssst! Schon vom neuen GMX MultiMessenger geh?rt? Der kann`s mit allen: http://www.gmx.net/de/go/multimessenger?did=10 From ganeshborse at gmail.com Thu Jan 31 05:49:29 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 31 Jan 2008 02:49:29 -0800 (PST) Subject: PyImport_ImportModule("cStringIO") failure with undefined symbol References: Message-ID: <30aeea04-d4bf-4864-a2c4-518311b10677@c23g2000hsa.googlegroups.com> On Jan 11, 9:31?am, "Borse, Ganesh" wrote: > Hi, > Can you please guide me for the following problem? > The call to "PyImport_ImportModule("cStringIO");" is failing with an error of "undefined symbol:PyObject_SelfIter". > > Before importing this module, I am importing only the sys module. > > ? ?Py_SetProgramName("/usr/bin/python"); > ? ?Py_Initialize(); > ? ?char* argv[] = { "python","-v",""}; > ? ?PySys_SetArgv(2,argv); > ? ?PyRun_SimpleString("import sys"); > > ? ?PyObject *modStringIO = NULL; > ? ?// Import cStringIO module > ? ?modStringIO = PyImport_ImportModule("cStringIO"); > > Should I be importing any other additional module(s) to make this import work? > > Please help. > > I am trying to use the function GetPythonErrorMessage provided in this post:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > Thanks in advance for your help. > Regards. ========================================== Function "PyObject_SelfIter" is part of libPython.a. But when library which is linked with libPython.a tries to import cStringIO (which is nothing but dlopen("lib-dynload/cStringIO.so"), ld.so does not find this symbol. So, as a workaround, we can get the cStringIO.so also linked with the library which has linked libPython.a. By this we ensure that PyObject_SelfIter is already resolved in the library. Then at the time of importing cStringIO at runtime, this symbol is already referenced & won't cause problems. From timr at probo.com Thu Jan 3 02:36:56 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 03 Jan 2008 07:36:56 GMT Subject: Choosing a new language References: <20071228162351.f29a3ce4.coolzone@it.dk> Message-ID: Joachim Durchholz wrote: >> Xah Lee wrote: >>> [...] PHP and Perl are practically identical in their >>> high-levelness or expressiveness or field of application (and >>> syntax), > >That must have been a very, very distant point of view with narrowly >squinted eyes. Do you really think so? It seems clear to me that the syntax of PHP was heavily influenced by Perl. PHP lacks the @array and %hash weirdnesses, but most PHP code will work just fine as Perl. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From vfmevm at gmail.com Tue Jan 1 04:45:19 2008 From: vfmevm at gmail.com (vfmevm at gmail.com) Date: Tue, 1 Jan 2008 09:45:19 +0000 (UTC) Subject: M-I,5.Perse cution - cost of the operati on Message-ID: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -= MI5: cost of the. operation -= -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Here's what a couple of other people on Usenet (uk.misc) had to. say regarding the cost. of running such an operation... PO: >Have some sense, grow up. and smell reality. What you are talking about PO: >would take loads of planning, tens of thousands of pounds and. lots of PO: >people involved. in the planning, execution and maintenance of it. You PO: >must have a very high opinion of yourself to think you are. worth it. PM: >But. why? And why you? Do you realize how much it would cost to keep PM: >one person under continuous. surveillance for five years? Think about PM: >all the man/hours. Say they. _just_ allocated a two man team and a PM:. >supervisor. OK., Supervisor's salary, say, #30,000 a year. Two men, PM: >#20,000 a year each. But. they'd need to work in shifts -- so it would PM: >be six men at #20,000 (which with on-costs would work. out at more like PM: >#30,000 to the. employer.) PM:. > PM: >So, we're talking. #30,000 x 6. #180,000. plus say, #40,000 for the PM: >supervisor. #220,000. Then you've got the hardware involved.. And PM: >any transcription that needs doing. You don't think. the 'Big Boss' PM: >would listen. to hours and hours of tapes, do you. PM:. > PM: >So, all in all, you couldn't actually do. the job for much less than PM: >a quarter million a year. Over five years. What are you doing that. makes PM: >it worth the while of the state to spend over one and a quarter. million PM: >on. you? Those are pretty much the sort of calculations that went through. my head once I stopped to consider what it must be. costing them to run this operation. The partial answer is,. there have been periods when the intensity. has been greater, and times when little has happened. In fact, for. much of 1993 and the first half of 1994, very little happened. Although I. don't think that was for reasons of money - if they can tap into the taxpayer they're not going to be short of resources,. are they? The more complete answer is in the enormity of what. they're doing. Relative to the cost to British pride of seeing their country humiliated. for the persecution of their own citizens, isn't is worth the. cost of four or five people to try. to bring things to a close in the manner they would wish? To the government a million or. two is quite honestly nothing - if they can convince themselves of the necessity of what. they're doing, resources will not be the limiting. factor. 7633 From sjmachin at lexicon.net Tue Jan 29 17:49:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 29 Jan 2008 14:49:31 -0800 (PST) Subject: Removing Pubic Hair Methods References: <878x28e0u1.fsf@benfinney.id.au> Message-ID: <32f6097f-9d77-4005-b05c-30d857b83074@e23g2000prf.googlegroups.com> On Jan 30, 9:14 am, Ben Finney wrote: > xiko... at yahoo.com.tw writes: > > Shaving is the most common removing pubic hair method. However, it > > is not the only one. > > Clearly you haven't done the Python tutorial, otherwise you'd realise > there's no distinction between pubic methods and privy methods. > > Also, there's one, and preferably only one, obvious way to do it:: > > >>> del foo.hair > Brazilians allegedly have some expertise in this area -- the OP could try comp.lang.lua From timr at probo.com Thu Jan 3 02:32:37 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 03 Jan 2008 07:32:37 GMT Subject: Choosing a new language References: <20071228162351.f29a3ce4.coolzone@it.dk> <81737bc2-99df-4295-b894-19d3ba47662e@c4g2000hsg.googlegroups.com> Message-ID: <1m3pn3pntfj99vd85gedvplrlonv96p1ea@4ax.com> kevin cline wrote: > >As if there were such a thing as an 'Ada programmer'. Any decent >programmer should be productive in Ada long before their security >clearance is approved. That's only true because the security clearance process has become so complicated. Ada is not a trivial language by any means. Even an experienced C programmer is going to find enough sharp edges to send him back to the reference manuals on a regular basis. >The real problem the DoD has is that defense work is not attractive to >the best and brightest. Bull crap. You don't HEAR about them because of that same security clearance issue, but some of the most complicated and certainly some of the LARGEST computing systems in the world come out of the DoD. You don't create reliable large systems using a corral full of bright-eyed college new hires. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From deets at nospam.web.de Mon Jan 28 10:27:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jan 2008 16:27:31 +0100 Subject: Encryption Recommendation References: <6b40b773-8554-4e9c-838f-e6934212d16e@n20g2000hsh.googlegroups.com> Message-ID: <606aj3F1pa0tfU1@mid.uni-berlin.de> rogerrath2 at gmail.com wrote: > Hello - > > I'm still using Python 2.4. In my code, I want to encrypt a password > and at another point decrypt it. What is the standard way of doing > encryption in python? Is it the Pycrypto module? Usually, one doesn't store clear-text passwords. Instead, use a hash-algorithm like md5 or crypt (the former is in the standard lib, don't know of the other out of my head) and hash the password, and store that hash. If a user enters the password, use the same algorithm, and compare the resulting hashes with the stored one. Diez From asmodai at in-nomine.org Thu Jan 3 08:58:19 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 3 Jan 2008 14:58:19 +0100 Subject: reassign to builtin possible !? In-Reply-To: References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> Message-ID: <20080103135819.GN67953@nexus.in-nomine.org> -On [20080103 14:47], Bernhard Merkle (bernhard.merkle at googlemail.com) wrote: >Are you sure ? what about the following example ? >Is this also shadowing ? It is, as it is local to your current executing interpreter. Any other Python process that is currently running is unaffected by your shadowing. So as Diez says, you are not tampering with it on a persistent global level. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Any fool can make a rule. And every fool will mind it... From doug.farrell at gmail.com Wed Jan 16 14:30:00 2008 From: doug.farrell at gmail.com (writeson) Date: Wed, 16 Jan 2008 11:30:00 -0800 (PST) Subject: handlers.SocketHandler and exceptions Message-ID: <02de2e9c-331d-45c0-afaa-578ddad55664@j78g2000hsd.googlegroups.com> Hi all, On our Linux systems at work I've written a Twisted logging server that receives log messages from multiple servers/processes to post them to a log file, essentially serializing all the process log messages. This works well, that is until I tried this test code: try: t = 10 / 0 except Exception, e: log.exception("divide by zero") where log is the logger instance retreived from a call to getLogger(). The problem is the handlers.SocketHandler tries to cPickle.dump() the log record, which in this case contains an exc_info tuple, the last item of which is a Traceback object. The pickling fails with an "unpickleable error" and that's that. Does anyone have any ideas how to handle this situation? I'd hate to have to give up using the log.exception(...) call as it's useful to get strack trace information in the log file. Thanks in advance, Doug Farrell From aezell at gmail.com Mon Jan 21 22:06:47 2008 From: aezell at gmail.com (Alex Ezell) Date: Mon, 21 Jan 2008 21:06:47 -0600 Subject: read files In-Reply-To: <47955C65.8080604@block.duxieweb.com> References: <47955C65.8080604@block.duxieweb.com> Message-ID: <71dd7f400801211906v17e383a1m34cfa9187ed8d9c3@mail.gmail.com> You might could do one of these two methods: fd.readlines() or: for line in fd: print line These are both from the Python tutorial found here: http://docs.python.org/tut/node9.html#SECTION009210000000000000000 /alex On Jan 21, 2008 9:00 PM, J. Peng wrote: > first I know this is the correct method to read and print a file: > > fd = open("/etc/sysctl.conf") > done=0 > while not done: > line = fd.readline() > if line == '': > done = 1 > else: > print line, > > fd.close() > > > I dont like that flag of "done",then I tried to re-write it as: > > fd = open("/etc/sysctl.conf") > while line = fd.readline(): > print line, > fd.close() > > > this can't work.why? > -- > http://mail.python.org/mailman/listinfo/python-list > From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 15 05:10:53 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 15 Jan 2008 11:10:53 +0100 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> Message-ID: <478c868a$0$7040$426a34cc@news.free.fr> Jaimy Azle a ?crit : > wrote: > >>>> fact 1: CPython compiles source code to byte-code. >>>> fact 2: CPython executes this byte-code. >>>> fact 3: Sun's JDK compiles source code to byte-code. >>>> fact 4: Sun's JDK executes this byte-code. >>> Fact 4 is misleading because it is only one option available to Sun's >>> JDK. Sun's JDK is also capable of transforming the byte-code to >>> native code and letting the processor execute that instead of the >>> original byte code, and that is where the most significant speed >>> increase comes from. Most importantly, it does so automatically, by >>> default, with no programmer intervention or configuration, and with >>> 100% compatibility, so it doesn't compare well to Python accelerators >>> like psyco. >> Then fact 1 is misleading too since Python handles the compilation >> automatically without programmer's intervention while Java requires >> someone to explicitely invoke the byte-code compiler. >> > > Sadly it is true also, I read somewhere this silly point was used also to > make distinction between java and python, then claiming python is just like > another interpreter, while java has it's own (what they call as) 'compiler'. > :) > > perhaps in the future another sillly point could be added also, Java has > Jython, while Python doesn't have some thing like PyJava or... perhaps Py-va > (Python based Java Language). Lol. At least some common sens in this stupid thread. Thanks Jaimy, you made my day !-) > Salam, Peace. PS : and BTW : my apologies to the community - I should have made my point only once and then shut up. Sorry. From __peter__ at web.de Fri Jan 18 17:27:58 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jan 2008 23:27:58 +0100 Subject: Is this a bug, or is it me? References: <87myr4o3sg.fsf@mulj.homelinux.net> <8afa3779-6803-43ed-ae4d-d0a102eda00d@x69g2000hsx.googlegroups.com> Message-ID: cptnwillard wrote: > I filed a bug report, and here is the short answer to my question: > genexps are code blocks, and code blocks cannot see variables in class > scopes. Congrats to Neil Cerutti who figured it out. > > Now here is another one for your enjoyment: > > class C: > @staticmethod > def f1(): pass > F = { '1' : f1 } > > C().F['1']() > >>>> TypeError: 'staticmethod' object is not callable > > > What do you think of this one? If you want it to be callable you can subclass: >>> class static(staticmethod): ... def __call__(self, *args, **kw): ... return self.__get__(object)(*args, **kw) ... >>> class A(object): ... @static ... def f(x="yadda"): print x ... f() ... yadda >>> A.f() yadda >>> A().f() yadda Peter From martin at v.loewis.de Mon Jan 7 18:06:28 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 Jan 2008 00:06:28 +0100 Subject: Does PIL work with Tk 8.5? In-Reply-To: <2870$4782a5c4$4275d90a$673@FUSE.NET> References: <2870$4782a5c4$4275d90a$673@FUSE.NET> Message-ID: <4782B074.8080709@v.loewis.de> > Since Python itself is the same version number (2.5.1), the only thing I > can find to account for the crash is the different version of Tk--could > this be making a difference, or am I doing something wrong? Yes, Tk 8.5 isn't quite compatible with existing Tkinter code; there have been a lot of changes which break Tkinter applications (though not Tkinter itself). OTOH, it's more likely that the PIL binaries you are using conflict with your Tk installation - if the binaries were for Tk 8.4 (which isn't quite clear to me whether that's indeed the case), then they can't work with Tk 8.5, as Tk doesn't provide that kind of binary compatibility. Regards, Martin From marcroy.olsen at gmail.com Wed Jan 23 10:16:34 2008 From: marcroy.olsen at gmail.com (marcroy.olsen at gmail.com) Date: Wed, 23 Jan 2008 07:16:34 -0800 (PST) Subject: Lxml on mac Message-ID: Hi, What to one do if one what to use lxml(http://codespeak.net/lxml/ index.html) on a mac? Best regards From arnodel at googlemail.com Thu Jan 31 17:45:51 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 31 Jan 2008 14:45:51 -0800 (PST) Subject: helper function in a class' namespace References: <47a226bb$0$2982$ba620e4c@news.skynet.be> <47a22a17$0$8306$9b622d9e@news.freenet.de> <13q4jg6edfvi970@corp.supernews.com> Message-ID: On Jan 31, 10:39?pm, Steven D'Aprano wrote: > On Thu, 31 Jan 2008 20:05:44 +0000, Stargaming wrote: > > String concatenation is generally considered unpythonic, better use > > string interpolation:: > > > ? ? 'H> %s' % (M,) [...] > Also, the tuple above is totally unnecessary. 'H> %s' % M will work fine. ...except if M is a tuple: >>> M = 'spam', 'eggs' >>> 'H> %s' % (M,) "H> ('spam', 'eggs')" >>> 'H> %s' % M Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting Pedantically yours, -- Arnaud From Russ.Paielli at gmail.com Sun Jan 27 23:44:43 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 20:44:43 -0800 (PST) Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: <790eec65-c7dc-4a5e-bc1b-f9138d18eae0@1g2000hsl.googlegroups.com> On Jan 27, 5:41 pm, Roy Smith wrote: > In article > , > > > > ajaksu wrote: > > On Jan 27, 10:32 pm, Paddy wrote: > > > I would value the opinion of fellow Pythoneers who have also > > > contributed to Wikipedia, on the issue of "Is Python Standardized". > > > Specifically in the context of this table: > > > http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Gene... > > > (Comparison of programming languages) > > > And this entry in the talk page > > > http://en.wikipedia.org/wiki/Talk:Comparison_of_programming_languages... > > > (Talk:Comparison of programming languages#Standardized Python?) > > > > - Thanks. > > > Hmmm. Seems to me that "Is X Standardized" in the given context means > > having a formal, published standard issued by some Standards > > organization. > > That's exactly what it means. For example, if I'm buying a C++ compiler, I > can specify in the contract, "Must comply with ISO 14882", and everybody > will know what I'm talking about. > > On the other side of the fence, if I'm a free-lance C++ developer, I can > specify to my customers that the code I write will work properly when > compiled with a compiler that meets ISO 14882. Whether such a compiler > actually exists, is besides the point :-) > > Python has no such standard. Sure, there's the stuff on docs.python.org, > but it's kind of hard to write a contract which says, "Must comply with the > stuff on docs.python.org", and have it be meaningful in a legal sense. > > So, I think the "No" in the "Standardized?" column for python is exactly > right. That's not to say you can't have something good which isn't > standardized. Sometimes standards committees even go off into left field > and field break stuff in the process of standardizing it. Some things have > so many different standards (i.e. the pletora of unix standards), it's > almost worthless to say it's standardized. But, as it stands, the > Wikipedia article is correct. I agree. As far as I know, Python is not formally "standardized" by any recognized standards authority such as ANSI or ISO. (If it were, it wouldn't have a "BDFL.") For most domains in which Python is used, that is not an issue, but for some potential uses it could be (e.g., safety-critical). FWIW, the "most" standardized language is probably Ada. Not only does it have a formal written standard, but I believe it also has a formal suite of tests that a standard Ada compiler is required to pass. [For some reason, Ada does not get the respect or the attention it deserves, but that's another topic.] From radiosrfun at radiosrfun.com Sat Jan 12 14:00:16 2008 From: radiosrfun at radiosrfun.com (radiosrfun) Date: Sat, 12 Jan 2008 14:00:16 -0500 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> <4788de48$0$26887$ecde5a14@news.coretel.net> Message-ID: <47890e3e$0$26886$ecde5a14@news.coretel.net> "ChairmanOfTheBored" wrote in message news:batho35a2r7pog5n67ajc1dpta4g5qt3k9 at 4ax.com... > On Sat, 12 Jan 2008 10:35:38 -0500, "radiosrfun" > wrote: > >>"default" wrote in message >>news:91hho3tr56dpsfqsav4lnr8sl944bbrviv at 4ax.com... >>> On Sat, 12 Jan 2008 02:01:09 -0500, "radiosrfun" >>> wrote: >>> >>>>I WISH - that the President and Congress of this country would shut off >>>>ALL >>>>foreign aid. >>> >>> Ditto that. >>> >>> Israel is the chief beneficiary of our foreign aid largesse. Some 8 >>> billion dollars annually. What doesn't find its way into politicians >>> pockets goes to pay for a military that is winning us a lot of new >>> friends in the Arab world. >>> >>> We pay Egypt ~ 2 billion a year in extortion to keep them from >>> attacking Israel. >>> >>> The actually amount Israel receives is not really known to the public. >>> The official numbers read something like 3 billion in aid, and another >>> 5 billion in guaranteed loans - which are turned into grants year >>> after year. This is money we borrow so there's an additional interest >>> burden. >>> >>> Actually when you talk about shutting off "foreign aid" you may be >>> making thermate's point for him. >>> -- >> >>Well - the first cup of coffee hasn't exactly kicked in yet - but I >>believe >>I know what you're saying and if correct - you may have a point there. >> > You are both fucked in the head, coffee or not. He more than you, but > still, you both don't know what you are talking about. > > If we stop giving aid to other nations, we are letting the retarded US > hating bastards win, dipshit. > I'm not so sure I agree there - money or no money - they hate our guts. Case in point - Mushariff. It has long been rumored that Bin-Laden is lurking near by - yet "Mushariff" seems to be too weak in the knees to try to hunt him down or allow us to. If he doesn't have the balls to do it - let us! I am willing to bet - Bin - Laden will eventually cause Mushariff's downfall too. > This nation has to be strong within, DESPITE what we give out. > I couldn't agree with you more! > Some of us are... some of us just want to piss and moan about things > they know nothing about. > I DO know - I'm sick of our tax dollars being blown on every damned "emergency" abroad - and we get kicked in the teeth each and every time - following. > Which do you think both of you fucktards are? None of the above. Chairman - I don't think "anyone" (American) will disagree with you - least of all me - that "WE" need to be strong from "within". The question comes - at what cost? IS it an investment? OR "Black mail"? In some cases - it could be a fine line. I would find it hard to believe that 100% of our money is distributed to those who are "supposed" to get it. I think we would be fooling ourselves to think that. Maybe I don't operate with "all" facts in hand - but up until now - you and I have pretty much been on the same page. Regardless which sentence or paragraph we parted company on - the fact remains - "I" am a U.S.citizen - born and raised here - and tired of the shit from all those piss ants. It is bad enough we have to put up with "crooked" politicians sucking us dry for all they can get - without the rest coming in to play their games. We can agree to disagree with respect to "how" it is done - but we both want to see it "BE" done - for the benefit of this country. You and I - or anyone else can debate this in a friendly manner - or be pissed off at each other over it - the fact remains - those in charge will do as they please - and we have little say in the matter. Any time some outsider slams this country or our people - it just pisses me off - which is why I bothered to reply to this thread at all. Whether we agree on "tactics" or not - if it come to a battlefield with the two of us - or any Americans there - we're still going to fight the same enemy - not each other. From python.list at tim.thechases.com Tue Jan 8 10:53:07 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 08 Jan 2008 09:53:07 -0600 Subject: stupid/style/list question In-Reply-To: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> References: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> Message-ID: <47839C63.3050001@tim.thechases.com> > To flush a list it is better doing "del mylist[:]" or "mylist = []"? > Is there a preferred way? If yes, why? It depends on what you want. The former modifies the list in-place while the latter just reassigns the name "mylist" to point to a new list within the local scope as demonstrated by this: def d1(mylist): "Delete in place" del mylist[:] def d2(mylist): "Just reassign" mylist = [] for test in [d1,d2]: input = [1,2,3] print 'Before:', input print test.__doc__ test(input) print 'After:', input print As performance goes, you'd have to test it, but I suspect it's not a glaring difference, and would suspect that the latter is a bit faster. -tkc From gagsl-py2 at yahoo.com.ar Tue Jan 29 18:28:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jan 2008 21:28:44 -0200 Subject: Decision (if, else) routine is not working as intended with CGI module References: <9dc9f5d3-2392-48d6-8cb4-8b31c1ce4af9@e6g2000prf.googlegroups.com> Message-ID: En Tue, 29 Jan 2008 18:23:41 -0200, epsilon escribi?: > I'm running into trouble figuring this one out. It seems that my > decision routine is not working as intended. Does anyone know why my > output continues to utilize the "else" portion of the routine. > > tag_form = cgi.FieldStorage(keep_blank_values=True) > > #if not tag_form.has_key("fse00"): > if tag_form["fse00"] == "": tag_form["fse00"] is a FieldStorage instance, not a string. To get its value, use: if tag_form["fse00"].value == "" if tag_form.getvalue("fse00")=="" if tag_form.getfirst("fse00")=="" See http://docs.python.org/lib/module-cgi.html -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Thu Jan 31 00:44:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 31 Jan 2008 05:44:08 -0000 Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> <9275bfdb-8f07-4c63-abbf-40c136388bf3@i7g2000prf.googlegroups.com> <87sl0en02e.fsf@benfinney.id.au> Message-ID: <13q2o18fif6ml6b@corp.supernews.com> (Top-posting corrected.) On Wed, 30 Jan 2008 22:38:30 -0500, Sergio Correia wrote: > On Jan 30, 2008 10:30 PM, Ben Finney > wrote: >> MRAB writes: >> >> > On Jan 31, 12:57 am, Asun Friere wrote: >> > > Ouch!! If on the other hand 'females' is populated by instances of >> > > (or merely includes instances of) class 'Human', I suggest you test >> > > for female.consent somewhere in your code! >> > > >> > The Pythonic approach would be to try the action and catch a >> > NoConsentException. >> >> You're making the classic Pythonista mistake: you behave as though EAFP >> applies everywhere. I assure you, in the above situation, it does not >> apply. > > So in this case it is REALLY better to ask for permission rather than > forgiveness? Oh yes. The NoConsentException has a number of extremely unpleasant side- effects on both the code that raises it and the code that catches it. -- Steven From aahz at pythoncraft.com Fri Jan 18 09:42:17 2008 From: aahz at pythoncraft.com (Aahz) Date: 18 Jan 2008 06:42:17 -0800 Subject: Some Berkeley DB questions (being maintained? queries?) References: <0ba30836-8e2d-4061-94ea-ccddb24bc290@s19g2000prg.googlegroups.com> <003601c85904$904150c0$0401a8c0@T60> Message-ID: In article , Terry Jones wrote: > >I'm also interested in any ongoing or planned work on the Python interface. Someone recently volunteered to take over primary maintenance, but I can't find the mailing list post. -- 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 jarausch at igpm.rwth-aachen.de Tue Jan 15 06:19:41 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 15 Jan 2008 12:19:41 +0100 Subject: common problem - elegant solution sought In-Reply-To: <5v3gg1F1kkla5U1@mid.dfncis.de> References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <5v3j6fF1kcmmvU1@mid.dfncis.de> Thanks to you all for your help. The solution to regenerate the list skipping the one to be deleted is fine for me since my lists are of moderate size and the operation is infrequent. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From milusi.pysiaczek at buziaczek.pl Fri Jan 4 10:51:40 2008 From: milusi.pysiaczek at buziaczek.pl (Artur M. Piwko) Date: Fri, 4 Jan 2008 15:51:40 +0000 (UTC) Subject: What's the limit of variables size in pyhton? References: <5673329f-2269-4696-837b-079ef041fc3c@j20g2000hsi.googlegroups.com> <6fa8f652-3893-4132-8f6a-519bea467d88@t1g2000pra.googlegroups.com> Message-ID: In the darkest hour on Mon, 31 Dec 2007 20:53:28 -0200, Gabriel Genellina screamed: >> Is that mean that i can deal with files with size more than 2GB only >> if the available memory allow > > To be more precise, that depends on the OS. On Windows there is a limit of > 2GB adressable memory per process (this is unrelated to the amount of > physical memory). That's the 32bit Windows limit only (afaik). -- [ Artur M. Piwko : Pipen : AMP29-RIPE : RLU:100918 : From == Trap! : SIG:240B ] [ 16:51:04 user up 11576 days, 4:46, 1 user, load average: 0.97, 0.71, 0.01 ] No wonder people are so horrible when they start life as children. -- K. Amis From washakie at gmail.com Tue Jan 15 06:27:31 2008 From: washakie at gmail.com (washakie) Date: Tue, 15 Jan 2008 03:27:31 -0800 (PST) Subject: MySQL-python-1.2.2 install with no mysql In-Reply-To: References: <14836669.post@talk.nabble.com> Message-ID: <14837853.post@talk.nabble.com> Okay, I've installed mysql then using yum... it installed the same version running on another machine with identical python where all works well... but now I get this error during build... thoughts?!?? mysql_config is there, and the site.cfg file is pointing correctly to it... : [root@ MySQL-python-1.2.2]# python setup.py build running build running build_py copying MySQLdb/release.py -> build/lib.linux-i686-2.4/MySQLdb running build_ext building '_mysql' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC -fPIC -Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/usr/include/mysql -I/usr/include/python2.4 -c _mysql.c -o build/temp.linux-i686-2.4/_mysql.o -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing -fwrapv _mysql.c:35:23: error: my_config.h: No such file or directory _mysql.c:40:19: error: mysql.h: No such file or directory _mysql.c:41:26: error: mysqld_error.h: No such file or directory _mysql.c:42:20: error: errmsg.h: No such file or directory _mysql.c:78: error: expected specifier-qualifier-list before ?MYSQL? _mysql.c:92: error: expected specifier-qualifier-list before ?MYSQL_RES? _mysql.c: In function ?_mysql_Exception?: _mysql.c:122: warning: implicit declaration of function ?mysql_errno? _mysql.c:122: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:125: error: ?CR_MAX_ERROR? undeclared (first use in this function) _mysql.c:125: error: (Each undeclared identifier is reported only once _mysql.c:125: error: for each function it appears in.) _mysql.c:133: error: ?CR_COMMANDS_OUT_OF_SYNC? undeclared (first use in this function) _mysql.c:134: error: ?ER_DB_CREATE_EXISTS? undeclared (first use in this function) _mysql.c:135: error: ?ER_SYNTAX_ERROR? undeclared (first use in this function) _mysql.c:136: error: ?ER_PARSE_ERROR? undeclared (first use in this function) _mysql.c:137: error: ?ER_NO_SUCH_TABLE? undeclared (first use in this function) _mysql.c:138: error: ?ER_WRONG_DB_NAME? undeclared (first use in this function) _mysql.c:139: error: ?ER_WRONG_TABLE_NAME? undeclared (first use in this function) _mysql.c:140: error: ?ER_FIELD_SPECIFIED_TWICE? undeclared (first use in this function) _mysql.c:141: error: ?ER_INVALID_GROUP_FUNC_USE? undeclared (first use in this function) _mysql.c:142: error: ?ER_UNSUPPORTED_EXTENSION? undeclared (first use in this function) _mysql.c:143: error: ?ER_TABLE_MUST_HAVE_COLUMNS? undeclared (first use in this function) _mysql.c:172: error: ?ER_DUP_ENTRY? undeclared (first use in this function) _mysql.c:215: warning: implicit declaration of function ?mysql_error? _mysql.c:215: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:215: warning: passing argument 1 of ?PyString_FromString? makes pointer from integer without a cast _mysql.c: In function ?_mysql_server_init?: _mysql.c:310: warning: label ?finish? defined but not used _mysql.c:236: warning: unused variable ?item? _mysql.c:235: warning: unused variable ?groupc? _mysql.c:235: warning: unused variable ?i? _mysql.c:235: warning: unused variable ?cmd_argc? _mysql.c:234: warning: unused variable ?s? _mysql.c: In function ?_mysql_ResultObject_Initialize?: _mysql.c:365: error: ?MYSQL_RES? undeclared (first use in this function) _mysql.c:365: error: ?result? undeclared (first use in this function) _mysql.c:370: error: ?MYSQL_FIELD? undeclared (first use in this function) _mysql.c:370: error: ?fields? undeclared (first use in this function) _mysql.c:379: error: ?_mysql_ResultObject? has no member named ?use? _mysql.c:382: warning: implicit declaration of function ?mysql_use_result? _mysql.c:382: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:384: warning: implicit declaration of function ?mysql_store_result? _mysql.c:384: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:385: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:388: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:391: warning: implicit declaration of function ?mysql_num_fields? _mysql.c:392: error: ?_mysql_ResultObject? has no member named ?nfields? _mysql.c:393: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:394: warning: implicit declaration of function ?mysql_fetch_fields? _mysql.c:438: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c: In function ?_mysql_ResultObject_traverse?: _mysql.c:450: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:451: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c: In function ?_mysql_ResultObject_clear?: _mysql.c:462: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:462: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:462: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:462: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:463: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c: In function ?_mysql_ConnectionObject_Initialize?: _mysql.c:475: error: ?MYSQL? undeclared (first use in this function) _mysql.c:475: error: ?conn? undeclared (first use in this function) _mysql.c:484: error: ?MYSQL_PORT? undeclared (first use in this function) _mysql.c:500: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:501: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:524: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:546: warning: implicit declaration of function ?mysql_init? _mysql.c:546: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:549: warning: implicit declaration of function ?mysql_options? _mysql.c:549: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:549: error: ?MYSQL_OPT_CONNECT_TIMEOUT? undeclared (first use in this function) _mysql.c:553: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:553: error: ?MYSQL_OPT_COMPRESS? undeclared (first use in this function) _mysql.c:554: error: ?CLIENT_COMPRESS? undeclared (first use in this function) _mysql.c:557: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:557: error: ?MYSQL_OPT_NAMED_PIPE? undeclared (first use in this function) _mysql.c:559: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:559: error: ?MYSQL_INIT_COMMAND? undeclared (first use in this function) _mysql.c:561: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:561: error: ?MYSQL_READ_DEFAULT_FILE? undeclared (first use in this function) _mysql.c:563: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:563: error: ?MYSQL_READ_DEFAULT_GROUP? undeclared (first use in this function) _mysql.c:566: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:566: error: ?MYSQL_OPT_LOCAL_INFILE? undeclared (first use in this function) _mysql.c:574: warning: implicit declaration of function ?mysql_real_connect? _mysql.c:574: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:589: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c: In function ?_mysql_ConnectionObject_traverse?: _mysql.c:670: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:671: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c: In function ?_mysql_ConnectionObject_clear?: _mysql.c:679: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:679: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:679: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:679: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:680: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c: In function ?_mysql_ConnectionObject_close?: _mysql.c:695: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:697: warning: implicit declaration of function ?mysql_close? _mysql.c:697: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:699: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c: In function ?_mysql_ConnectionObject_affected_rows?: _mysql.c:721: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:722: warning: implicit declaration of function ?mysql_affected_rows? _mysql.c:722: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_debug?: _mysql.c:738: warning: implicit declaration of function ?mysql_debug? _mysql.c: In function ?_mysql_ConnectionObject_dump_debug_info?: _mysql.c:756: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:758: warning: implicit declaration of function ?mysql_dump_debug_info? _mysql.c:758: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_autocommit?: _mysql.c:782: warning: implicit declaration of function ?mysql_query? _mysql.c:782: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_commit?: _mysql.c:805: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_rollback?: _mysql.c:827: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_errno?: _mysql.c:939: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:940: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_error?: _mysql.c:955: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:956: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:956: warning: passing argument 1 of ?PyString_FromString? makes pointer from integer without a cast _mysql.c: In function ?_mysql_escape_string?: _mysql.c:980: warning: implicit declaration of function ?mysql_escape_string? _mysql.c: In function ?_mysql_escape?: _mysql.c:1087: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c: In function ?_mysql_ResultObject_describe?: _mysql.c:1167: error: ?MYSQL_FIELD? undeclared (first use in this function) _mysql.c:1167: error: ?fields? undeclared (first use in this function) _mysql.c:1170: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1171: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1172: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1183: warning: implicit declaration of function ?IS_NOT_NULL? _mysql.c: In function ?_mysql_ResultObject_field_flags?: _mysql.c:1203: error: ?MYSQL_FIELD? undeclared (first use in this function) _mysql.c:1203: error: ?fields? undeclared (first use in this function) _mysql.c:1206: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1207: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1208: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: At top level: _mysql.c:1249: error: expected declaration specifiers or ?...? before ?MYSQL_ROW? _mysql.c: In function ?_mysql_row_to_tuple?: _mysql.c:1255: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1257: warning: implicit declaration of function ?mysql_fetch_lengths? _mysql.c:1257: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1257: warning: assignment makes pointer from integer without a cast _mysql.c:1260: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:1261: error: ?row? undeclared (first use in this function) _mysql.c: At top level: _mysql.c:1274: error: expected declaration specifiers or ?...? before ?MYSQL_ROW? _mysql.c: In function ?_mysql_row_to_dict?: _mysql.c:1279: error: ?MYSQL_FIELD? undeclared (first use in this function) _mysql.c:1279: error: ?fields? undeclared (first use in this function) _mysql.c:1281: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1283: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1283: warning: assignment makes pointer from integer without a cast _mysql.c:1284: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1287: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:1288: error: ?row? undeclared (first use in this function) _mysql.c: At top level: _mysql.c:1313: error: expected declaration specifiers or ?...? before ?MYSQL_ROW? _mysql.c: In function ?_mysql_row_to_dict_old?: _mysql.c:1318: error: ?MYSQL_FIELD? undeclared (first use in this function) _mysql.c:1318: error: ?fields? undeclared (first use in this function) _mysql.c:1320: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1322: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1322: warning: assignment makes pointer from integer without a cast _mysql.c:1323: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1326: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:1327: error: ?row? undeclared (first use in this function) _mysql.c: At top level: _mysql.c:1349: error: expected declaration specifiers or ?...? before ?MYSQL_ROW? _mysql.c: In function ?_mysql__fetch_row?: _mysql.c:1360: error: ?MYSQL_ROW? undeclared (first use in this function) _mysql.c:1360: error: expected ?;? before ?row? _mysql.c:1364: error: ?_mysql_ResultObject? has no member named ?use? _mysql.c:1365: error: ?row? undeclared (first use in this function) _mysql.c:1365: warning: implicit declaration of function ?mysql_fetch_row? _mysql.c:1365: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1368: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1371: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1379: error: too many arguments to function ?convert_row? _mysql.c: In function ?_mysql_ResultObject_fetch_row?: _mysql.c:1403: error: expected declaration specifiers or ?...? before ?MYSQL_ROW? _mysql.c:1418: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1430: error: ?_mysql_ResultObject? has no member named ?use? _mysql.c:1444: warning: implicit declaration of function ?mysql_num_rows? _mysql.c:1444: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ConnectionObject_character_set_name?: _mysql.c:1511: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c: In function ?_mysql_get_client_info?: _mysql.c:1602: warning: implicit declaration of function ?mysql_get_client_info? _mysql.c:1602: warning: passing argument 1 of ?PyString_FromString? makes pointer from integer without a cast _mysql.c: In function ?_mysql_ConnectionObject_get_host_info?: _mysql.c:1616: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1617: warning: implicit declaration of function ?mysql_get_host_info? _mysql.c:1617: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1617: warning: passing argument 1 of ?PyString_FromString? makes pointer from integer without a cast _mysql.c: In function ?_mysql_ConnectionObject_get_proto_info?: _mysql.c:1631: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1632: warning: implicit declaration of function ?mysql_get_proto_info? _mysql.c:1632: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_get_server_info?: _mysql.c:1646: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1647: warning: implicit declaration of function ?mysql_get_server_info? _mysql.c:1647: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1647: warning: passing argument 1 of ?PyString_FromString? makes pointer from integer without a cast _mysql.c: In function ?_mysql_ConnectionObject_info?: _mysql.c:1663: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1664: warning: implicit declaration of function ?mysql_info? _mysql.c:1664: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1664: warning: assignment makes pointer from integer without a cast _mysql.c: In function ?_mysql_ConnectionObject_insert_id?: _mysql.c:1696: error: ?my_ulonglong? undeclared (first use in this function) _mysql.c:1696: error: expected ?;? before ?r? _mysql.c:1698: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1700: error: ?r? undeclared (first use in this function) _mysql.c:1700: warning: implicit declaration of function ?mysql_insert_id? _mysql.c:1700: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_kill?: _mysql.c:1717: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1719: warning: implicit declaration of function ?mysql_kill? _mysql.c:1719: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_field_count?: _mysql.c:1738: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1740: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ResultObject_num_fields?: _mysql.c:1755: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1756: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ResultObject_num_rows?: _mysql.c:1771: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1772: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ConnectionObject_ping?: _mysql.c:1801: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1802: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1804: warning: implicit declaration of function ?mysql_ping? _mysql.c:1804: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_query?: _mysql.c:1825: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1827: warning: implicit declaration of function ?mysql_real_query? _mysql.c:1827: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_select_db?: _mysql.c:1855: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1857: warning: implicit declaration of function ?mysql_select_db? _mysql.c:1857: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_shutdown?: _mysql.c:1876: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1878: warning: implicit declaration of function ?mysql_shutdown? _mysql.c:1878: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_stat?: _mysql.c:1903: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1905: warning: implicit declaration of function ?mysql_stat? _mysql.c:1905: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1905: warning: assignment makes pointer from integer without a cast _mysql.c: In function ?_mysql_ConnectionObject_store_result?: _mysql.c:1926: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1927: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:1936: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ConnectionObject_thread_id?: _mysql.c:1965: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1967: warning: implicit declaration of function ?mysql_thread_id? _mysql.c:1967: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_use_result?: _mysql.c:1987: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1988: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:1997: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ConnectionObject_dealloc?: _mysql.c:2015: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c: In function ?_mysql_ConnectionObject_repr?: _mysql.c:2027: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:2028: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ResultObject_data_seek?: _mysql.c:2046: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:2047: warning: implicit declaration of function ?mysql_data_seek? _mysql.c:2047: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ResultObject_row_seek?: _mysql.c:2060: error: ?MYSQL_ROW_OFFSET? undeclared (first use in this function) _mysql.c:2060: error: expected ?;? before ?r? _mysql.c:2062: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:2063: error: ?_mysql_ResultObject? has no member named ?use? _mysql.c:2068: error: ?r? undeclared (first use in this function) _mysql.c:2068: warning: implicit declaration of function ?mysql_row_tell? _mysql.c:2068: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:2069: warning: implicit declaration of function ?mysql_row_seek? _mysql.c:2069: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ResultObject_row_tell?: _mysql.c:2081: error: ?MYSQL_ROW_OFFSET? undeclared (first use in this function) _mysql.c:2081: error: expected ?;? before ?r? _mysql.c:2083: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:2084: error: ?_mysql_ResultObject? has no member named ?use? _mysql.c:2089: error: ?r? undeclared (first use in this function) _mysql.c:2089: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:2090: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ResultObject_dealloc?: _mysql.c:2098: warning: implicit declaration of function ?mysql_free_result? _mysql.c:2098: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: At top level: _mysql.c:2329: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:2336: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:2343: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:2350: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:2357: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:2420: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:2420: error: initializer element is not constant _mysql.c:2420: error: (near initialization for ?_mysql_ResultObject_memberlist[0].offset?) _mysql.c: In function ?_mysql_ConnectionObject_getattr?: _mysql.c:2442: error: ?_mysql_ConnectionObject? has no member named ?open? error: command 'gcc' failed with exit status 1 [root@ MySQL-python-1.2.2]# Jarek Zgoda wrote: > > >> >> How can I install MySQL-python-1.2.2 without installing MySQL??? > > In short: without installing client libraries you cann't. > > -- > 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 > > &-(&-( -- View this message in context: http://www.nabble.com/MySQL-python-1.2.2-install-with-no-mysql-tp14836669p14837853.html Sent from the Python - python-list mailing list archive at Nabble.com. From bearophileHUGS at lycos.com Fri Jan 18 19:59:34 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 18 Jan 2008 16:59:34 -0800 (PST) Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> <54efb87e-5a54-42a4-adcc-3d05e03a4859@s8g2000prg.googlegroups.com> <2f5524f1-2a9b-4d04-8b37-15d20940da72@v4g2000hsf.googlegroups.com> Message-ID: ...and just for fun this D code is about 3.2 times faster than the Psyco version for the same dataset (30% lines with a space): import std.stdio, std.conv, std.string, std.stream; int[int] get_hist(string file_name) { int[int] hist; foreach(string line; new BufferedFile(file_name)) { int pos = find(line, ' '); if (pos == -1) hist[toInt(line)]++; else hist[toInt(line[0 .. pos])] += toInt(line[pos+1 .. $]); } return hist; } void main(string[] args) { writefln( get_hist(args[1]).length ); } Bye, bearophile From berlin.brown at gmail.com Mon Jan 14 18:05:01 2008 From: berlin.brown at gmail.com (BerlinBrown) Date: Mon, 14 Jan 2008 15:05:01 -0800 (PST) Subject: Append zip files together, just get the binary data (in memory) References: <53f66038-ccc3-4c3d-97b2-fa5deb148809@d4g2000prg.googlegroups.com> <5v27oiF1kavhlU1@mid.uni-berlin.de> Message-ID: <3c56d5b5-2dfb-4fd7-9a70-8022bd822430@j78g2000hsd.googlegroups.com> On Jan 14, 5:58 pm, "Diez B. Roggisch" wrote: > BerlinBrown schrieb: > > > Is it possible to just build the binary content of a zip file. I want > > to create the content in memory (e.g. return binary data) and then get > > those byte strings representing the zip file? Is that possible? > > > Or could I possibly override functions in the zip class. > > > 1. Create a zip file object (e.g. dont actually create the file). > > 2. Append stuff to the zip file (e.g. a file) > > 3. Zip that content into memory (but still not touching the > > filesystem) > > 4. Extract those byte strings for (an array?) later use. > > > My goal is to concatenate multiple zip files into another binary file. > > Module StringIO is your friend. > > Diez Clearly, someone doesn't know python as well as he should. That is good idea, thanks. So basically treat StringIO as the in memory container to write the zip file data to. From george.sakkis at gmail.com Sat Jan 19 13:14:17 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 19 Jan 2008 10:14:17 -0800 (PST) Subject: Default attribute values pattern Message-ID: A situation that often comes up is having to initialize several instance attributes that accept a default value. For a single class, passing the default values in __init__ is fine: class Base(object): def __init__(self, x=0, y=None): self.x = x self.y = y For inherited classes that need to override __init__ while keeping a compatible interface though, the default values have to be repeated: class Derived(Base): def __init__(self, x=0, y=None, z=''): super(Derived,self).__init__(self,x,y) self.z = '' For just two attributes and two classes that's maybe not too bad but for many attributes and/or derived classes that may span multiple modules, that doesn't seem to scale from a maintenance point of view, especially if the defaults change over time. A pattern I've been using lately instead is store the defaults in class attributes and let __init__ accept keyword arguments: class Base(object): x = 0 y = None def __init__(self, **kwds): setattrs(self, kwds) where setattrs is: def setattrs(self, attrvals, strict=True): if strict: # raise AttributeError if some attr doesn't exist already for attr in attrvals.iterkeys(): getattr(self,attr) for attr,val in attrvals.iteritems(): setattr(self, attr, val) This way, only the new and overriden default attributes have to repeated in derived classes: class Derived(Base): x = 1 z = '' def __init__(self, **kwds): super(Derived,self).__init__(**kwds) print 'In Derived.__init__' Is this a good way of doing it ? Is there a better pattern ? George From tejovathi.p at gmail.com Tue Jan 8 06:04:29 2008 From: tejovathi.p at gmail.com (Teja) Date: Tue, 8 Jan 2008 03:04:29 -0800 (PST) Subject: COM server and EXE References: Message-ID: On Jan 8, 3:33?pm, Teja wrote: > Hi All, > > I have a Python COM server. I need to deploy it on various sytems. > When I run the COM server from > python its showing an output " Registered : sample.lib" > > If I try to use the COM obj from a VB client like: > > obj = CreateObject("sample.lib") > > Its working fine without any errors > > Now I am trying to convert this COM server to an exe through py2exe > and after I run the exe, I am > getting the same output " Registered : sample.lib" > > But If I try to use the COM obj from a VB client like > > obj = CreateObject("sample.lib") > > A console pops up saying " Registered : sample.lib" and VB application > hangs there. > Its throwing a VB error that "ActiveX object cannot be > created......etc etc" > > Any suggestions please....... > > Regards, > Tejovathi Here is my sample COM server and py2exe setup file testCOM.py import win32com.client import os.path import shutil from win32api import Sleep import string import os import sys import pythoncom class FirstEx: _reg_clsid_ = "{A6DE9DF8-5EBF-48E6-889E-C71CB84CFF2C}" pythoncom.frozen = 1 if hasattr(sys, 'importers'): # In the py2exe-packed version, specify the module.class # to use. In the python script version, python is able # to figure it out itself. _reg_class_spec_ = "__main__.FirstEx" _reg_desc_ = "My first COM server" _reg_progid_ = "SAMPLE.Lib" _public_methods_ = ['init', 'Version'] _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER def __init__(self): self.softspace = 1 self.noCalls = 0 def Version(self): self.noCalls = self.noCalls + 1 # insert "softspace" number of spaces return "Version: 0.0.1" if __name__=='__main__': import sys if hasattr(sys, 'importers'): # running as packed executable. if '--register' in sys.argv[1:] or '--unregister' in sys.argv[1:]: # --register and --unregister work as usual import win32com.server.register win32com.server.register.UseCommandLine(FirstEx) else: # start the server. from win32com.server import localserver localserver.main() else: import win32com.server.register win32com.server.register.UseCommandLine(FirstEx) Here is my setup file: #Start here from distutils.core import setup import py2exe setup(options = {"py2exe": {"compressed": 1, "optimize": 2, "ascii": 1, "bundle_files": 1}}, zipfile = None, com_server = ["win32com.servers.interp"], console = ["testCOM.py"]) #End here Here is my VB code: Sub subRoutine() Dim connection As Object Dim returnvalue1 As String Dim returnvalue2 As String Dim flag3 As Boolean Set connection = CreateObject("SAMPLE.Lib") returnvalue1 = connection.Version() MsgBox (returnvalue1) End Sub The non exe version of the COM server ie. directlly running the testCOM.py registers the library properly and in the VB application, the message box displays the version as 0.0.1. But, after I create the EXE file using the setup.py file and run it, it registers the library. When I run the VB application, it hangs at the line Set connection = CreateObject("SAMPLE.Lib") and displays. " ACTIVEX cannot create the object" Any suggestions please.... From bearophileHUGS at lycos.com Tue Jan 15 11:48:30 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 15 Jan 2008 08:48:30 -0800 (PST) Subject: Benchmark [was Re: common problem - elegant solution sought] References: <5v3gg1F1kkla5U1@mid.dfncis.de> <478ccc9e$0$29264$ba620e4c@news.skynet.be> Message-ID: Helmut Jarausch: > The clear winner is > > def del_by_key(L,key) : > for pos, (k,d) in enumerate(L): > if k == key : > del L[pos] > break If you use Psyco this is faster: def del_by_key(L,key): pos = 0 for pair in L: if pair[0] == key : del L[pos] break pos += 1 Bye, bearophile From caca at mailinator.com Sat Jan 5 11:14:46 2008 From: caca at mailinator.com (caca at mailinator.com) Date: Sat, 5 Jan 2008 08:14:46 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> Message-ID: <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> On Jan 5, 5:07 pm, c... at mailinator.com wrote: > Hello, Paul and Arnaud. > While I think about your answers: do you think there is any way to > avoid shuffle? > It may take unnecessary long on a long list most of whose elements > have the property. Umm... You provide nice answers in the case many elements are picked from the same list. Any ideas for the case when the picker is called many times on a program, but never twice with the same list? From jimgardener at gmail.com Sun Jan 6 11:56:14 2008 From: jimgardener at gmail.com (jimgardener at gmail.com) Date: Sun, 6 Jan 2008 08:56:14 -0800 (PST) Subject: how to use bool References: <05c5df8b-15c4-47e6-8c14-72c57a84a0ea@y5g2000hsf.googlegroups.com> <2c516040-0193-4de3-bf7d-b61e739cdc2d@l57g2000hsa.googlegroups.com> Message-ID: some more doubts in this area,,forgive the ignorance of a beginner i have class MyError(Exception): def __init__(self,msg) self.msg=msg now my method that can raise this is class SomeClass: ........... def mymethod(self): if (somecondition): raise MyError("somecondn failed") if another method in the same class calls this method but wants to pass the error to a gui code which calls it,,can i do like this def callingmethode(self): try: mymethod() except MyError,myerr: raise myerr so that I can handle the error in a gui code that calls callingmethode() class MyGUI: def guimethode(self): someinst=SomeClass() try: someinst.callingmethode() except MyError,myer: self.dealwithMyError(myer) is this kind of raising exception the correct way?I am getting syntax error at except MyError,myerr: raise myerr From bignose+hates-spam at benfinney.id.au Fri Jan 18 03:07:51 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 18 Jan 2008 19:07:51 +1100 Subject: array and list References: <87bq7jbwxo.fsf@benfinney.id.au> <13p0b6jbn2ut6b4@corp.supernews.com> Message-ID: <877ii7blpk.fsf@benfinney.id.au> Steven D'Aprano writes: > On Fri, 18 Jan 2008 15:05:23 +1100, Ben Finney wrote: > > In Python, 'list' is a basic built-in type. Python has no 'array' > > type [...] > Did you forget the array module? Yes. -- \ "Always code as if the guy who ends up maintaining your code | `\ will be a violent psychopath who knows where you live." ?John | _o__) F. Woods | Ben Finney From bigblueswope at gmail.com Wed Jan 9 00:40:56 2008 From: bigblueswope at gmail.com (BJ Swope) Date: Wed, 9 Jan 2008 00:40:56 -0500 Subject: Open a List of Files In-Reply-To: <18308.12959.742868.758136@terry.local> References: <874pdomrrd.fsf@mulj.homelinux.net> <18308.12959.742868.758136@terry.local> Message-ID: On Jan 8, 2008 9:34 PM, Terry Jones wrote: > > I think you should revisit this decision. Something like Fredrik's code > is > the way to go. It has multiple advantages: > > - It's much shorter. > - It's arguably easier to add/remove to/from. > - It has less risk of error (much less repetition). > - It allows your code to later take a string file tag and > write to that file by looking up its file descriptor in the dict. > - You can close all open files with a trivial loop. > > Also, if you start writing code like Fredrik's instead of like what you > fell back on you'll make yourself a better programmer (in general, not > just > in Python). > > Terry > Thanks for the advice Terry. With your prompting I went back and looked at the examples and sought to understand them. The results are... #File Creations/Openings def getfilename(host_path, fn): return os.path.join(host_path, '%s.txt' % fn) outfiles_list = ['messages', 'deliveries', 'actions', 'parts', 'recipients', 'viruses', 'esp_scores'] open_files = {} for fn in outfiles_list: open_files[fn] = open(getfilename(host_path, fn), 'wb') #Referring to files to write in various places... open_files['deliveries'].write(flat_line) open_files['deliveries'].write('\n') #And finally to close the opened files for fn in open_files.keys(): open_files[fn].close() I sure am glad I posted this to the list. It is exactly the kind of stuff I was hoping to find. Again, to all who answered, Thank You! BJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Jan 10 13:42:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 19:42:40 +0100 Subject: What is "lambda x=x : ... " ? In-Reply-To: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> Message-ID: zslevi at gmail.com wrote: > #################### > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ################### > > What does "y=y" and "c=c" mean in the lambda function? they bind the argument "y" to the *object* currently referred to by the outer "y" variable. for example, y = 10 f = lambda y=y: return y y = 11 calling f() will return 10 no matter what the outer "y" is set to. in contrast, if you do y = 10 f = lambda: y y = 11 calling f() will return whatever "y" is set to at the time of the call. or in other words, default arguments bind to values, free variables bind to names. > I thought it bounds the outer variables, so I experimented a little > bit: > > ################# > x = 3 > y = lambda x=x : x+10 > > print y(2) > ################## > > It prints 12, so it doesn't bind the variable in the outer scope. it does, but you're overriding the bound value by passing in a value. try: x = 3 y = lambda x=x : x+10 y() x = 10 y() instead. From khoard at gmail.com Wed Jan 30 20:02:18 2008 From: khoard at gmail.com (FireNWater) Date: Wed, 30 Jan 2008 17:02:18 -0800 (PST) Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> Message-ID: <58d1bc12-206f-4cec-ad86-928d16e962f5@i3g2000hsf.googlegroups.com> On Jan 30, 3:09 pm, Berteun Damman wrote: > On Wed, 30 Jan 2008 14:47:36 -0800 (PST), FireNWater wrote: > > I'm curious why the different outputs of this code. If I make the > > dictionary with letters as the keys, they are not listed in the > > dictionary in alphabetical order, but if I use the integers then the > > keys are in numerical order. > > > I know that the order of the keys is not important in a dictionary, > > but I was just curious about what causes the differences. Thanks!! > > I don't know the exact way Python's hash function works, but I can take > a guess. I'm sorry if I explain something you already know. > > A hash is for quickly looking up data. Yet, you don't want to waste too > much memory. So there is a limit number of spaces allocated, in which to > store objects. This number of spaces can be thought of as a list. Then, > if you put something into the dict, Python computes the 'hash' of this > object, which basically forms the index in the list where to store it. > So every object should be mapped onto some index within the list. (If > you retrieve it, the hash is computed again, and the value on that index > is looked up, like list indexing, these are fast operations.) > > Say, if you have 100 spaces, and someone puts in integer in the list, > the hashfunction used might be % 100. So the first 100 integers would > always be placed at consecutive places. For strings however, a more > complicated hash-function would be used, which takes into account more > characters, so strings don't end up in order. > > For integers, if you put in integers that are spread very widely apart, > they won't end up in order either (see the mod 100 example, 104 will > come before 10). > > If you replace the list2 in your example by: > list2 = [10000 * x for x in range(1,9)] > > You will see that this one doesn't end up in order either. So, there's > no exception for integers when it comes to the order, yet the particular > properties of the hash function will cause sequential integers to end up > in order under some circumstances. > > Berteun > > PS: > What happens if two values map onto the same space is of course an > obvious question, and the trick is choosing your hashfunction so this > occurs not very often on average. If it happens there are several > strategies. Wikipedia probably has an explanation of how hash-functions > can work in such a case. Thank you for the explanation. . . I think I now have a (foggy) understanding of hash tables. It seems to be a way to create order (an index) out of disorder (random numbers or characters) behind the scenes. . From lists at cheimes.de Sun Jan 20 08:59:06 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 20 Jan 2008 14:59:06 +0100 Subject: finding memory leak in edgewall trac 0.11 In-Reply-To: <4f9304e4-3847-41ee-8064-b881f7b9e073@f47g2000hsd.googlegroups.com> References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> <0c6fc35d-91d2-4767-968d-e6eb56096eba@z17g2000hsg.googlegroups.com> <4f9304e4-3847-41ee-8064-b881f7b9e073@f47g2000hsd.googlegroups.com> Message-ID: rupert.thurner wrote: > i forgot to mention that i cannot see any explicit sys._getframe(), or > __del__ in the genshi code, while the ones in trac-core seemed to be > there in 0.10.4. Does the code keep a reference to a traceback object or an attribute of a traceback object? Christian From boblatest at yahoo.com Wed Jan 9 05:01:14 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 10:01:14 GMT Subject: "Canonical" way of deleting elements from lists Message-ID: <5ujkbaF1e11ksU1@mid.dfncis.de> Hello, >From a list of strings I want to delete all empty ones. This works: while '' in keywords: keywords.remove('') However, to a long-term C programmer this looks like an awkward way of accomplishing a simple goal, because the list will have to be re-evaluated in each iteration. Is there a way to just walk the list once and throw out unwanted elements as one goes along? I started programming back when such little things were real performance issues, so I have some sort of cringe reflex when something looks inefficient. robert From castironpi at gmail.com Wed Jan 23 21:16:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 23 Jan 2008 18:16:01 -0800 (PST) Subject: Function wrappers Message-ID: def f( callback, *bar, **bkwar ): def preg ( callfore, *far, **fkwar ): return g( callback, callfore, bar, bkwar, far, fkwar ) return preg Does anyone see a way to rewrite this, perhaps along the lines of partial( partial, partial )? Ok to modify 'g' call. From gagsl-py2 at yahoo.com.ar Tue Jan 22 21:50:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 00:50:57 -0200 Subject: Don't want child process inheriting open sockets References: <800886C2A4A73E44BA0FE45152C023702503AD6561@ADSK-NAMSG-02.MGDADSK.autodesk.com> Message-ID: En Tue, 22 Jan 2008 13:02:35 -0200, Steven Watanabe escribi?: > I'm using subprocess.Popen() to create a child process. The child > process is inheriting the parent process' open sockets, but I don't want > that. I believe that on Unix systems I could use the FD_CLOEXEC flag, > but I'm running Windows. Any suggestions? You could use the DuplicateHandle Windows API function with bInheritHandle=False to create a non inheritable socket handle, then close the original one. This should be done for every socket you don't want to be inherited. -- Gabriel Genellina From mensanator at aol.com Mon Jan 7 18:50:57 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 7 Jan 2008 15:50:57 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python References: Message-ID: On Jan 7, 5:10?pm, dgoldsmith_89 wrote: > On Jan 7, 2:54 pm, "mensana... at aol.com" wrote: > > > On Jan 7, 4:37 pm, dgoldsmith_89 wrote: > > > > Can anyone point me to a downloadable open source English dictionary > > > suitable for programmatic use with python: I'm programming a puzzle > > > generator, and I need to be able to generate more or less complete > > > lists of English words, alphabetized. ?Thanks! ?DG > > >www.puzzlers.orghasnumerous word lists & dictionarys in text > > format that can be downloaded. I recommend you insert them into > > some form of database. I have most of them in an Access db and > > it's 95 MB. That's a worse case as I also have some value-added > > stuff, the OSPD alone would be a lot smaller. > > > > > Sorry for my ignorance: I can query an Access DB w/ standard SQL > queries (and this is how I would access it w/ Python)? Yes, if you have the appropriate way to link to the DB. I use Windows and ODBC from Win32. I don't know what you would use on a Mac. As Paul McGuire said, you could easily do this with SqlLite3. Personnaly, I always use Access since my job requires it and I find it much more convenient. I often use Crosstab tables which I think SqlLite3 doesn't support. Typically, I'll write complex queries in Access and simple select SQL statements in Python to grab them. Here's my anagram locator. (the [signature] is an example of the value-added I mentioned). ## I took a somewhat different approach. Instead of in a file, ## I've got my word list (562456 words) in an MS-Access database. ## And instead of calculating the signature on the fly, I did it ## once and added the signature as a second field: ## ## TABLE CONS_alpha_only_signature_unique ## -------------------------------------- ## CONS text 75 ## signature text 26 ## ## The signature is a 26 character string where each character is ## the count of occurences of the matching letter. Luckily, in ## only a single case was there more than 9 occurences of any ## given letter, which turned not to be a word but a series of ## words concatenated so I just deleted it from the database ## (lots of crap in the original word list I used). ## ## Example: ## ## CONS signature ## aah 20000001000000000000000000 # 'a' occurs twice & 'h' once ## aahed 20011001000000000000000000 ## aahing 20000011100001000000000000 ## aahs 20000001000000000010000000 ## aaii 20000000200000000000000000 ## aaker 20001000001000000100000000 ## aal 20000000000100000000000000 ## aalborg 21000010000100100100000000 ## aalesund 20011000000101000010100000 ## ## Any words with identical signatures must be anagrams. ## ## Once this was been set up, I wrote a whole bunch of queries ## to use this table. I use the normal Access drag and drop ## design, but the SQL can be extracted from each, so I can ## simply open the query from Python or I can grab the SQL ## and build it inside the program. The example ## ## signatures_anagrams_select_signature ## ## is hard coded for criteria 9 & 10 and should be cast inside ## Python so the criteria can be changed dynamically. ## ## ## QUERY signatures_anagrams_longest ## --------------------------------- ## SELECT Len([CONS]) AS Expr1, ## Count(Cons_alpha_only_signature_unique.CONS) AS CountOfCONS, ## Cons_alpha_only_signature_unique.signature ## FROM Cons_alpha_only_signature_unique ## GROUP BY Len([CONS]), ## Cons_alpha_only_signature_unique.signature ## HAVING (((Count(Cons_alpha_only_signature_unique.CONS))>1)) ## ORDER BY Len([CONS]) DESC , ## Count(Cons_alpha_only_signature_unique.CONS) DESC; ## ## This is why I don't use SQLite3, must have crosstab queries. ## ## QUERY signatures_anagram_summary ## -------------------------------- ## TRANSFORM Count(signatures_anagrams_longest.signature) AS CountOfsignature ## SELECT signatures_anagrams_longest.Expr1 AS [length of word] ## FROM signatures_anagrams_longest ## GROUP BY signatures_anagrams_longest.Expr1 ## PIVOT signatures_anagrams_longest.CountOfCONS; ## ## ## QUERY signatures_anagrams_select_signature ## ------------------------------------------ ## SELECT Len([CONS]) AS Expr1, ## Count(Cons_alpha_only_signature_unique.CONS) AS CountOfCONS, ## Cons_alpha_only_signature_unique.signature ## FROM Cons_alpha_only_signature_unique ## GROUP BY Len([CONS]), ## Cons_alpha_only_signature_unique.signature ## HAVING (((Len([CONS]))=9) AND ## ((Count(Cons_alpha_only_signature_unique.CONS))=10)) ## ORDER BY Len([CONS]) DESC , ## Count(Cons_alpha_only_signature_unique.CONS) DESC; ## ## QUERY signatures_lookup_by_anagram_select_signature ## --------------------------------------------------- ## SELECT signatures_anagrams_select_signature.Expr1, ## signatures_anagrams_select_signature.CountOfCONS, ## Cons_alpha_only_signature_unique.CONS, ## Cons_alpha_only_signature_unique.signature ## FROM signatures_anagrams_select_signature ## INNER JOIN Cons_alpha_only_signature_unique ## ON signatures_anagrams_select_signature.signature ## = Cons_alpha_only_signature_unique.signature; ## ## ## Now it's a simple matter to use the ODBC from Win32 to extract ## the query output into Python. import dbi import odbc con = odbc.odbc("words") cursor = con.cursor() ## This first section grabs the anagram summary. Note that ## queries act just like tables (as long as they don't have ## internal dependencies. I read somewhere you can get the ## field names, but here I put them in by hand. ##cursor.execute("SELECT * FROM signature_anagram_summary") ## ##results = cursor.fetchall() ## ##for i in results: ## for j in i: ## print '%4s' % (str(j)), ## print ## (if this wraps, each line is 116 characters) ## 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 23 ## 2 259 None None None None None None None None None None None None None None None None None ## 3 487 348 218 150 102 None None None None None None None None None None None None None ## 4 1343 718 398 236 142 101 51 26 25 9 8 3 2 None None None None None ## 5 3182 1424 777 419 274 163 106 83 53 23 20 10 6 4 5 1 3 1 ## 6 5887 2314 1051 545 302 170 114 54 43 21 15 6 5 4 4 2 None None ## 7 7321 2251 886 390 151 76 49 37 14 7 5 1 1 1 None None None None ## 8 6993 1505 452 166 47 23 8 6 4 2 2 None None None None None None None ## 9 5127 830 197 47 17 6 None None 1 None None None None None None None None None ## 10 2975 328 66 8 2 None None None None None None None None None None None None None ## 11 1579 100 5 4 2 None None None None None None None None None None None None None ## 12 781 39 2 1 None None None None None None None None None None None None None None ## 13 326 11 2 None None None None None None None None None None None None None None None ## 14 166 2 None None None None None None None None None None None None None None None None ## 15 91 None 1 None None None None None None None None None None None None None None None ## 16 60 None None None None None None None None None None None None None None None None None ## 17 35 None None None None None None None None None None None None None None None None None ## 18 24 None None None None None None None None None None None None None None None None None ## 19 11 None None None None None None None None None None None None None None None None None ## 20 6 None None None None None None None None None None None None None None None None None ## 21 6 None None None None None None None None None None None None None None None None None ## 22 4 None None None None None None None None None None None None None None None None None ## From the query we have the word size as row header and size of ## anagram set as column header. The data value is the count of ## how many different anagram sets match the row/column header. ## ## For example, there are 7321 different 7-letter signatures that ## have 2 anagram sets. There is 1 5-letter signature having a ## 23 member anagram set. ## ## We can then pick any of these, say the single 10 member anagram ## set of 9-letter words, and query out out the anagrams: cursor.execute("SELECT * FROM signatures_lookup_by_anagram_select_signature") results = cursor.fetchall() for i in results: for j in i: print j, print ## 9 10 anoretics 10101000100001100111000000 ## 9 10 atroscine 10101000100001100111000000 ## 9 10 certosina 10101000100001100111000000 ## 9 10 creations 10101000100001100111000000 ## 9 10 narcotise 10101000100001100111000000 ## 9 10 ostracine 10101000100001100111000000 ## 9 10 reactions 10101000100001100111000000 ## 9 10 secration 10101000100001100111000000 ## 9 10 tinoceras 10101000100001100111000000 ## 9 10 tricosane 10101000100001100111000000 ## Nifty, eh? > > DG From thelanguageofcities at gmail.com Sun Jan 27 19:19:13 2008 From: thelanguageofcities at gmail.com (Max) Date: Sun, 27 Jan 2008 16:19:13 -0800 (PST) Subject: Python Genetic Algorithm References: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Jan 27, 6:35 pm, Wildemar Wildenburger wrote: > Max wrote: > > In GAs, you operate on a Population of solutions. Each Individual from > > the Population is a potential solution to the problem you're > > optimizing, and Individuals have what's called a chromosome - a > > specification of what it contains. For example, common chromosomes are > > bit strings, lists of ints/floats, permutations...etc. I'm stuck on > > how to implement the different chromosomes. I have a Population class, > > which is going to contain a list of Individuals. Each individual will > > be of a certain chromosome. I envision the chromosomes as subclasses > > of an abstract Individual class, perhaps all in the same module. I'm > > just having trouble envisioning how this would be coded at the > > population level. Presumably, when a population is created, a > > parameter to its __init__ would be the chromosome type, but I don't > > know how to take that in Python and use it to specify a certain class. > > I'm not sure I'm following you here. So a "chromosome" is bit of > functionality, right? So basically it is a function. So my advice would > be to write these functions and store it to the "indivuals"-list like so: > > class Population(object): > def __init__(self, *individuals): > self.individuals = list(individuals) > > Then you can say: > p = Population(indiv1, indiv2, indiv3) > for individual in p.individual: > individual(whatever_your_problem) > > (Don't know if this is the way GA's are supposed to work) > > You can also create callable classes (that is, classes that implement > the __call__ method), and use instances of these as the individuals. For > example you can create a Permutation class that returns a permutation > (defined in it's __init__()) when it's __call__ method is called. (Am I > making sense?) > > This is just generic advice, maybe this helps and maybe it doesn't at > all. :) > > > I'm doing something similar with my crossover methods, by specifying > > them as functions in a module called Crossover, importing that, and > > defining > > > crossover_function = getattr(Crossover, "%s_crossover" % xover) > > > Where xover is a parameter defining the type of crossover to be used. > > I'm hoping there's some similar trick to accomplish what I want to do > > with chromosomes - or maybe I'm going about this completely the wrong > > way, trying to get Python to do something it's not made for. Any help/ > > feedback would be wonderful. > > This isn't too bad, but for such things dictionaries are your Go-To > datatype. Just have a dictionary of xover-functions handy and call the > thusly: > > crossover_function = Crossover.function[xover] > > > Thanks, > > Max Martin > > If that helps :) > > regards > /W This is definitely useful information, but I don't think I explained chromosomes very well. A chromosome is a choice of representation. So let's say your problem is diagnosis, so a representation of a solution will be a list of diagnoses (e.g. Disease1 = yes, Disease2 = no, Disease3 = yes, etc.). Your chromosome choice could be a bitstring, in which the previous solution would = 101, or it could be a list of floats to represent the probability that you have Disease x, etc. So a chromosome is like a choice of representation. In the case of humans, the chromosome is, well, chromosomes. From mr.cerutti at gmail.com Wed Jan 30 08:45:03 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 30 Jan 2008 08:45:03 -0500 Subject: Removal of element from list while traversing causes the next element to be skipped In-Reply-To: <7xwsprxxe6.fsf@ruckus.brouhaha.com> References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> <7xwsprxxe6.fsf@ruckus.brouhaha.com> Message-ID: <51302a8c0801300545i4d4f9460pbbbc489f11bef5ee@mail.gmail.com> On 30 Jan 2008 05:20:49 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Neil Cerutti" writes: > > Or one can put on his bellbottoms, horn-rimmed glasses, and wear a mullet: > > > > i = 0 > > while i < len(a): > > if a[i] == 99: > > del a[i] > > else: > > i += 1 > > Quadratic time!! Yowch!! Back to the future: > > def rocket_science(xs): > for x in xs: > if x != 99: > yield x > > a[:] = list(rocket_science(a)) Heh. It's probably a fairly peppy quadratic operation though. Besides, wherever will I find plutonium or a bolt of lightning? -- Neil Cerutti From m.schibler at gmail.com Thu Jan 3 03:14:43 2008 From: m.schibler at gmail.com (Matthew Schibler) Date: Thu, 3 Jan 2008 00:14:43 -0800 (PST) Subject: shelve and nested dictionaries Message-ID: I'm a newbie to Python, with some experience using perl (where I used nested arrays and hashes extensively). I am building a script in python for a MUD I play, and I want to use the shelve module to store persistent information between script executions. The following code does not work for me, import shelve, sys, os, string db = shelve.open(os.path.abspath(os.path.dirname(sys.argv[0])) + '/' + 'sandbox.dat', 'c') db['JustSomeVariable'] = 'apple' db['subdb'] = {} db['subdb']['anotherdict'] = {} db['subdb']['anotherdict']['bleh'] = 'hello world' db.close() of course, that's just a working example but it illustrates the problem i'm having. I think shelve objects act like dictionaries in a way, at least they seem to have dictionary keys beneath them. And I don't seem to have this problem when I use a normal dictionary as opposed to shelve for nesting other dictionaries. So i'm now confused, i've hit a brick wall and i'm not sure how to solve this problem. Can anyone explain what i'm doing wrong? Thanks From bignose+hates-spam at benfinney.id.au Fri Jan 25 18:45:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 26 Jan 2008 10:45:38 +1100 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> Message-ID: <87k5lx5v19.fsf@benfinney.id.au> "Gabriel Genellina" writes: > You can also put, in animal/__init__.py: > from monkey import Monkey > and now you can refer to it as org.lib.animal.Monkey, but keep the > implementation of Monkey class and all related stuff into > .../animal/monkey.py This (as far as I can understand) is exactly the solution the original poster desired to "shoot down", for reasons I still don't understand. -- \ "Reichel's Law: A body on vacation tends to remain on vacation | `\ unless acted upon by an outside force." -- Carol Reichel | _o__) | Ben Finney From hoo.smth at gmail.com Thu Jan 10 03:59:43 2008 From: hoo.smth at gmail.com (BlackjadeLin) Date: Thu, 10 Jan 2008 00:59:43 -0800 (PST) Subject: Why my program (using pexpect to switch user) doesn't work well? Message-ID: <97b80c0e-9199-464e-a52e-615f98972ee0@e4g2000hsg.googlegroups.com> I'm new to python I want to write a simple script to switch user,for example,from user_A to user_B. This my codes: #!/usr/bin/python import pexpect import os passwd="user_B" child = pexpect.spawn('su user_B') child.expect('Password:') child.sendline(passwd) child.expect('$') child.close() Maybe it's the easiest pexpect program.Sometimes ,it work well,it switch to user_B successfully .But after i type the command exit to switch back to user_A,execute the python script again,it can't work,do nothing or just waiting.Why it have different results? Sorry for my poor English,and many thanks to all. Blackjade From asmodai at in-nomine.org Wed Jan 16 06:55:56 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 16 Jan 2008 12:55:56 +0100 Subject: anti-spam policy for c.l.py? In-Reply-To: <478dee4e$0$28424$426a34cc@news.free.fr> References: <08ed32c4-6230-4b14-9c31-4b94e0231cf2@c4g2000hsg.googlegroups.com> <478dee4e$0$28424$426a34cc@news.free.fr> Message-ID: <20080116115556.GA61556@nexus.in-nomine.org> -On [20080116 12:51], Bruno Desthuilliers (bruno.42.desthuilliers at wtf.websiteburo.oops.com) wrote: >Apart from checking posts headers and complaining about the relevant >ISPs, there's not much you can do AFAIK. This is usenet, not a mailing-list. It is both actually. python-list at python.org is linked to comp.lang.python due to a news gateway. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ I accept that some things will never change, I've let your tiny minds magnify my agony... From richarwils at gmail.com Wed Jan 23 05:19:47 2008 From: richarwils at gmail.com (Richi) Date: Wed, 23 Jan 2008 02:19:47 -0800 (PST) Subject: Computer Laptops Message-ID: Zenith Director Laptop, Lenovo Laptop Model No: 3000 Y500, HCL Notebook Model No: AXX2202, Zenith Presidio Laptop many model of laptop.... please visit - http://www.homeshop18.com/hs18shop/faces/tiles/category.jsp?catalogueID=2&categoryID=920&parentCategoryID=909&q=&sid=&bid=&prc=&k1=&k2=&k3=&k4=&k5=&k6=&k7=&k8=&k9=&k10=&k11=&k12= From theCodeMaiden at gmail.com Thu Jan 3 15:15:27 2008 From: theCodeMaiden at gmail.com (Adeola Bannis) Date: Thu, 3 Jan 2008 12:15:27 -0800 (PST) Subject: PyOpenGL, wxPython weird behaviour References: <71ae5a6b-31e9-41e9-a39e-919138dc4a03@l6g2000prm.googlegroups.com> Message-ID: Thanks, will do... On Jan 3, 2:07 pm, kyoso... at gmail.com wrote: > On Jan 3, 11:50 am, Adeola Bannis wrote: > > > > > Hi everyone, > > > I'm doing a project using wxPython and pyopengl, and I seem to have a > > problem rendering textures. This is code that worked before my hard > > drive had a meltdown, but not since I re-installed everything. > > > I've determined the problem is in the OpenGL part of my program. I do > > some calculations to generate a 2D numpy array that holds the image > > data, and pylab.imshow() shows me the image as it is meant to be. I > > used the same algorithm in Octave and MATLAB, and all are giving me > > the right picture. > > > However, using pyOpenGL and the numpyhandler functions (http://cours- > > info.iut-bm.univ-fcomte.fr/docs/python/OpenGL/ > > OpenGL.arrays.numpymodule.NumpyHandler-class.html) doesn't seem to > > work. I get a garbled screen pocked with black pixels. I am including > > my openGL code below. What am I doing wrong? > > > And yes, I did make the dtype of my array 'float32'. > > > -------code snippets------ > > > import wx > > from wx.glcanvas import GLCanvas > > > from OpenGL.GLU import * > > from OpenGL.GL import * > > from OpenGL.arrays.numpymodule import NumpyHandler > > > PC = 1 > > RI = 0 > > > class myGLCanvas(GLCanvas): > > def __init__(self, parent): > > GLCanvas.__init__(self, parent,-1) > > wx.EVT_PAINT(self, self.OnPaint) > > self.init = 0 > > self.mode = -1 > > # making a texture for the range image > > self.texture = glGenTextures(1) > > # making a spot for the point cloud points > > self.cloud = None > > return > > > def OnPaint(self,event): > > dc = wx.PaintDC(self) > > self.SetCurrent() > > if not self.init: > > self.InitGL() > > self.init = 1 > > self.OnDraw() > > return > > > def OnDraw(self): > > glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) > > if self.mode == RI: > > self.drawRange() > > elif self.mode == PC: > > self.drawCloud() > > > def InitGL(self): > > glClearColor(0.0, 0.0, 0.0, 0.0); > > glClearDepth(1.0) > > glEnable(GL_DEPTH_TEST) > > glDepthFunc(GL_LEQUAL) > > glClear(GL_COLOR_BUFFER_BIT) > > > glPixelStorei(GL_UNPACK_ALIGNMENT, 1) > > glPixelStorei(GL_PACK_ALIGNMENT, 1) > > > #NTSC colour scales... > > glPixelTransferf(GL_RED_SCALE, 0.299); > > glPixelTransferf(GL_GREEN_SCALE, 0.587); > > glPixelTransferf(GL_BLUE_SCALE, 0.114); > > > glMatrixMode(GL_PROJECTION) > > glLoadIdentity() > > glOrtho(0.0,1.0,0,1.0,-1.0,1.0) > > glMatrixMode(GL_MODELVIEW) > > glLoadIdentity() > > > return > > > def rangeImage(self, image): > > > glBindTexture(GL_TEXTURE_2D, self.texture) > > glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) > > > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, > > GL_LINEAR) > > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) > > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) > > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) > > > # flatten it into a list so the OpenGL calls work > > n = NumpyHandler() > > fI = image.flatten() > > flatImage = n.dataPointer(n.contiguous(fI)) > > > print n.contiguous(fI) > > > gluBuild2DMipmaps(GL_TEXTURE_2D, 1, image.shape[0]+1, > > image.shape[1]+1, > > GL_LUMINANCE, GL_FLOAT, flatImage) > > self.mode = RI > > self.OnDraw() > > > def drawRange(self): > > ''' Controls the actual drawing of the range image''' > > > glMatrixMode(GL_MODELVIEW) > > glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) > > > glColor3f(1.0,1.0,1.0) > > glEnable(GL_TEXTURE_2D) > > glBindTexture(GL_TEXTURE_2D, self.texture) > > glBegin(GL_TRIANGLE_FAN) > > glTexCoord2d(1,1); glVertex3f(0.0, 0.0, 0.0) > > glTexCoord2d(1,0); glVertex3f(0.0, 1.0, 0.0) > > glTexCoord2d(0,0); glVertex3f(1.0, 1.0, 0.0) > > glTexCoord2d(0,1); glVertex3f(1.0, 0.0, 0.0) > > glEnd() > > self.SwapBuffers() > > > --------end snippet----------- > > I've never messed with pyOpenGL, but it seems that they have their own > user's group, which would probably be better at answering your > question: > > http://sourceforge.net/mail/?group_id=5988 > > Of course, it could be that you upgraded your wxPython to the latest > version and as I recall, they were discussing some subtle differences > in DCs, blitting, paint events and other things that I just don't > understand at this point in my "Pythoneering". You might ask them at > their group, which is usually very helpful: wxPython.org > > Mike From tinnews at isbd.co.uk Fri Jan 4 11:31:39 2008 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: 04 Jan 2008 16:31:39 GMT Subject: how to use bool References: <477d08d1$0$510$bed64819@news.gradwell.net> Message-ID: <477e5f6b$0$514$bed64819@news.gradwell.net> Chris Mellon wrote: > On 03 Jan 2008 16:09:53 GMT, wrote: > > > > jimgardener at gmail.com wrote: > > > hi, i have some code where i set a bool type variable and if the value > > > is false i would like to return from the method with an error msg.. > > > being a beginner I wd like some help here > > > > > > class myclass: > > > ......... > > > def mymethod(self): > > > success=True > > > msg="all validation OK" > > > success=validateSthing() > > > if(success==False): > > > msg="sthing failed" > > > return (success,msg) > > > > > > dosomeprocessing() > > > ..... > > > success=validateSthingelse() > > > if(success==False): > > > msg="sthingelse failed" > > > return (success,msg) > > > domoreprocessing() > > > .... > > > return(success,msg) > > > > > > i would like to know if this way of doing this is OK..I have need of > > > many kinds of validations in this ..is there a better way of doing > > > this ? > > > > > With my philosophical programming hat on the first thing I'd say (as a > > fairly beginning python programmer) is "avoid multiple returns from a > > function/method if at all possible". They breed all sorts of problems > > and errors, in particular if there's any clearing up to do you have to > > do it in lots of places (or you forget it in some places). > > > > This advice is highly controversial, and in the presence of exceptions > it is, at best, voodoo coding. Since your function can exit at any > point whether you do it intentionally or not, if you have crucial > cleanup it's best to write your code in a way that does it correctly > even if you return early. Following this style also often leads to odd > contortions, like extra layers of indentation, and a proliferation of > temporary flags and value-holders that aren't necessary if you write > the code in a more straight forward manner. > OK, I agree, I had my C hat on (no exceptions). On the other hand if you end with lots of levels of indentation going this way it suggests to me that maybe breaking up into more functions would be a good idea. > Make your decisions on a case by case basis of complexity, > readability, and reliability instead of following pronouncements from > on high (especially decades old pronouncements made in a different > context). Forcing a single return site in the code below adds > complexity, arguable harms readability, and provides *zero* benefit in > the code at hand. > > > So:- > > > > def mymethod(self): > > msg="sthing failed" > > success=validateSthing() > > if success: > > dosomeprocessing() > > ..... > > success=validateSthingelse() > > if success: > > domoreprocessing() > > .... > > msg="all validation OK" > > return (success,msg) > > > > I've lost the different messages for different errors but you get the > > idea. > > > > > > "if success:" rather than "if (success==True)", more readable. For > > the opposite "if not success:". > > > > > > > > -- > > Chris Green > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > -- Chris Green From bruno.desthuilliers at gmail.com Mon Jan 28 17:20:36 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 28 Jan 2008 14:20:36 -0800 (PST) Subject: post variable References: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> <87ir1dr8ms.fsf@mulj.homelinux.net> <0f634854-7d7a-4ad8-ba04-38d239ecf850@d70g2000hsb.googlegroups.com> Message-ID: <2bc110e7-de2d-47ac-89e8-c87793ec1a14@b2g2000hsg.googlegroups.com> On 28 jan, 22:32, "pavloutefk... at gmail.com" wrote: > 1. yes i've tried that technique but its annoying, the user can easily > stop the redirection and not "elegant". It's a very canonical technique with HTTP (at least after a successful POST). But I suspect you're not doing it the right way, since you're talking about "the user (...) stop(ing) the redirection". "Redirecting" here means "sending an HTTP redirection status code and the appropriate location header" (according to the rfc, code should be 303, but for legacy reasons it's often a 302). You must indeed *not* have send *anything* else to the client before (which means that you'd better use a log file to trace your code) ! From oliver at obeattie.com Sat Jan 26 06:35:18 2008 From: oliver at obeattie.com (Oliver Beattie) Date: Sat, 26 Jan 2008 03:35:18 -0800 (PST) Subject: Custom class to a dictionary? Message-ID: <5025a3f7-9dcf-49d7-876c-df5c8d8a8df5@e6g2000prf.googlegroups.com> Just wondering if it is possible to pass a custom class instance instance to dict() by way of using methods like you can for iterators (__iter__, __getitem__ etc.) I see there is no __dict__ -- is there anything else I can use to achieve this? Kind Regards, Oliver From ceccarelli.aldo at gmail.com Thu Jan 24 17:49:33 2008 From: ceccarelli.aldo at gmail.com (Aldo Ceccarelli) Date: Thu, 24 Jan 2008 14:49:33 -0800 (PST) Subject: Anybody has ported talib to Python via SWIG Message-ID: <6fa2a3e3-ab77-41dc-a01e-55770a764b0e@k39g2000hsf.googlegroups.com> Hi Everybody, TaLib (technical analysis package with function indicators coded in C/C ++, http://www.ta-lib.org ) has a complete library with source in C/C+ +. I am new to SWIG (wrapper interface generator) and would really appreciate any Python (.py) port of TaLib to be able to call and test TaLib's functions (f.i. MACD, Parabolic SAR and so on) in some Python (2.5) script. Do you have idea whether TaLib Python package has already been generated and can be eventually downloaded anywhere? Many thanks, kind regards. Aldo From Matthew_WARREN at bnpparibas.com Tue Jan 29 05:49:16 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Tue, 29 Jan 2008 10:49:16 +0000 Subject: validate string is valid maths In-Reply-To: <25d89a47-6380-4129-a7b8-3a70ca1b216f@c4g2000hsg.googlegroups.com> Message-ID: It was a very loosely thought out problem, and my Maths isn't good enough to define 'sane' rules for collapsing the signs/operators to make a sensible expression; so take my constraints with a pinch of salt. I guess a better way of putting it may be - now it has been pointed out that 8+++++++9 is valid; Remove the smalles number of symbols such that eval() will always return a number, and the result is always the same. ....and I havent had a chance to play with the couple of solutions posted yet, so those criteria may have already been met. One thing I have discovered is you cant just pass arbitrary valid (expression wise) numeral/symbol strings to eval and have it work as expected; >>> eval('8-038') Traceback (most recent call last): File "", line 1, in File "", line 1 8-038 ^ SyntaxError: invalid token becasue of >>> eval('8-010') 0 Can I escape the meaning of the leading 0's on an integer? ....and despite my initial claims, there is an overall aim. Still purely just to play with python though - after someone mentioned Genetic Algorithms on the list yesterday I thought I'd have a go at a very simple one. These long symbol/number strings are the 'genomes/chromosomes' (not certain on correct terms), the 'genes' are 1234567890+/-* I'm generating large populations of arbitrary length chromosomes. Using eval(chromosome) to compute a number. The fittest individuals are the ones who's genome evaluates closest to 10000000, so in essence I'm evolving solutions to making the number 10000000 using 1234567890/*-+ (this was partially inspired by the countdown numbers game discussed here too.). Trivial and possibly pointless, but shiny enough for me to play with :) Matt. Internet gagsl-py2 at yahoo.com.ar To python-list Sent by: cc python-list-bounces+matthew.warren=uk.bnpparibas.com@ python.org Subject Re: validate string is valid maths 28/01/2008 18:30 impor tOn 28 ene, 14:31, Matthew_WAR... at bnpparibas.com wrote: > What would be the 'sensible' way of transforming the string, for example > changing '3++++++8' into 3+8 > or '3++--*-9' into '3+-9' such that eval(string) will always return a > number? '3++++++8' is already a valid expresion, like '3++---9' > in cases where multiple symbols conflict in meaning (as '3++--*-9' the > earliest valid symbols in the sequence should be preserved > > so for example, > > '3++*/-9' = 3+-9 > '45--/**/+7' = 45-+7 > '55/-**+-6**' = 55/-6 Why not 3++-9, 45--+7? Does it have to be two operators? Why not 3++9 instead? they're the two earliest valid symbols. Can't repeat yourself then? (I'm trying to understand the rules...) This approach uses regular expressions. It doesn't follow all your rules, and tries to get the longest valid expression: import re def repl_middle(match): g = match.group() if g[0] in '*/': g0 = g[0] g = g[1:] else: g0 = '' return g0 + g.replace('*','').replace('/','') def repl_start(match): g = match.group() return g.replace('*','').replace('/','') def dropinvalid(s): s = re.sub(r'(?<=\d)[+*/-]+(?=\d)', repl_middle, s) s = re.sub(r'^[+*/-]+', repl_start, s) s = re.sub(r'[+*/-]+$', '', s) return s cases = [ ('3++++++8', '3+8'), ('3++--*-9', '3+-9'), ('3++*/-9', '3+-9'), ('45--/**/+70', '45-+70'), ('55/-**+-6**', '55/-6'), ('55/**6**', '55/6'), ] for expr, matthew in cases: print expr, dropinvalid(expr), matthew > I've tried testing, but I'm not certain wether repeated iterations over a > dict return different sequences of key,value pairs or wether I'll be > getting the same (but arbitrary) sequence each time even though they are > unordered, etc If the dictionary hasn't changed, you'll get the same sequence each time (see note (3) in http://docs.python.org/lib/typesmapping.html ) > So for testing, what could I do to guarantee the next iteration over the > dict will give keys/pairs in a different sequence to last time? items = dict.items() random.shuffle(items) for key,value in items: ... (Ok, no guarantee, there is only a certain probability that it will be different each time...) -- Gabriel Genellina -- 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 kimsmith005 at googlemail.com Fri Jan 4 13:53:33 2008 From: kimsmith005 at googlemail.com (kimsmith005 at googlemail.com) Date: Fri, 4 Jan 2008 10:53:33 -0800 (PST) Subject: :::> A Powerful, Safe and Economical Alternative to VIAGRA <::: Message-ID: <75cc7d70-af4b-41a3-bc96-de4fa5cc5883@s8g2000prg.googlegroups.com> :::>> A Powerful, Safe and Economical Alternative to VIAGRA <<::: >>> Naturally improves Erectile Dysfunction increasing your Sex Drive, Endurance,and Pleasure. * Creates Firmer Harder Erections. * Increases SEMINAL VOLUME & SPERM COUNT Naturally with NO SIDE EFFECTS. * Creates Heightened Desire, Sensitivity and Pleasure. * Sub-lingual tablets are dissolved under the tongue offering complete and rapid absorption. .::>> 100% Full MONEY BACK guarantee if not completely satisfied with results. For More Details >>> http://lovetools.cq.bz/ __________________________________________________________________________________________________ Learn Why ProVIGRAX is Better than Viagra >>> http://proviagrax.blogspot.com/ From rowen at cesmail.net Thu Jan 24 18:27:25 2008 From: rowen at cesmail.net (Russell E. Owen) Date: Thu, 24 Jan 2008 15:27:25 -0800 Subject: Problem with Tkinter scrollbar callback References: Message-ID: In article , "Ivan Van Laningham" wrote: > Hi All-- > I'm having two problems with the scrollbar callback on linux systems > (Fedora 7, Suse 10.1,2 and 3 all exhibit the issues). > > Problem one: on Windows, the callback is called with the arguments as > specified in the doc: "scroll", "1" or "-1", "units". When I run the > identical code on linux, the callback is invoked with only one > argument, "1" or "-1". Here's a small program which demos the > problem: > > ========begin============ > #!/usr/bin/env python > > from Tkinter import * > import sys > > def die(event): > sys.exit(0) > def sDoit(*args): > for i in args: > print "scrollbar:",i, type(i) > root=Tk() > f=Frame(root) > f.pack(expand=1,fill=BOTH) > button=Button(f,width=25) > button["text"]="Quit" > button.bind("
this is in a table, woo-hoo!
19 """ 20 Thank you, Christopher From tangjin93 at hotmail.com Sun Jan 20 00:15:33 2008 From: tangjin93 at hotmail.com (Janet93) Date: Sat, 19 Jan 2008 21:15:33 -0800 (PST) Subject: an Invitation to be Involved in a Survey on Developing Scientific Computing Software Message-ID: If you are involved in the development of scientific computing software, you are invited to participate in a survey on developing this kind of software. If you have already received this request, I apologize for the cross-posting, but I am attempting to advertise to as many developers as possible. I would appreciate it if you could take 20-30 minutes to complete this questionnaire. If you know others involved in the development of scientific computing software, could you please forward this survey to them. Your assistance is highly appreciated. There are 37 questions in the survey, which can be accessed via the following link: http://www.eSurveysPro.com/Survey.aspx?id=b67ce1c1-84c2-4c2b-b66d-70db013d8038 The survey is for a research experiment conducted by myself, Jin Tang, a master student at the Department of Computing and Software, McMaster University, Canada, under the supervision of Dr. Spencer Smith. The result of this survey will help me with my research on the processes used to develop scientific computing software, where scientific computing is defined as the use of computer tools to analyze or simulate mathematical models of continuous real world system of engineering or scientific importance so that we can better understand and potentially predict the system's behaviour. The short term goal of this survey is to find the processes that industry and academia follow to develop their scientific computing software. The mid term objective is to direct research on adapting software engineering methodologies to improve the quality of scientific computing software. Questions in this survey are related to the process of developing scientific computing software. For example: What kind of libraries do you use to develop scientific computing software? In your current group, do you consider software reuse? What level of software reuse do you reach? What method(s) do you use for software validation and verification. All questions are voluntary and you need only answer those questions that you wish to. If you agree to participate in the survey, you can change your mind and discontinue the survey at any time. This research will pose risks no greater than what you would experience in the course of your day-to-day work life. If you are interested in this study, we are very happy to share our survey report with you. Please provide your email address in the survey, the survey report will be sent to you. All your answers to the survey questions will be kept in Excel files, which will be completely confidential and only available to myself and Dr. Spencer Smith. If you have any questions, please contact Jin Tang or Dr. Spencer Smith. The following is our contact information. Jin Tang Department of Computing and Software McMaster University 1280 Main Street West Hamilton, Ontario, Canada L8S 4K1 Phone: 905-525-9140 Ext. 27029 Email: tangj29 at mcmaster.ca Spencer Smith, Ph.D. Associate Professor Department of Computing and Software McMaster University 1280 Main Street West Hamilton, Ontario, Canada L8S 4K1 Phone: 905-525-9140 Ext. 27929 Fax: 905-524-0340 Email: smiths at mcmaster.ca This study has been reviewed and approved by the McMaster Research Ethics Board. If you have concerns or questions about your right as a participant or about the way the study is conducted, you may contact McMaster Research Ethics Board Secretariat at 905-525-9140 ext. 23142, email: ethicsoffice at mcmaster.ca. Thank you. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 28 04:51:00 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 28 Jan 2008 10:51:00 +0100 Subject: optional static typing for Python In-Reply-To: References: Message-ID: <479da584$0$25625$426a74cc@news.free.fr> Russ P. a ?crit : > A while back I came across a tentative proposal from way back in 2000 > for optional static typing in Python: > (snip) > In any case, optional static typing in Python would help tremendously > here. The hardest part of automated conversion of Python to a > statically typed language is the problem of type inference. If the > types are explicitly declared, that problem obviously goes away. (snip) > Note also that, while "static" type checking would be ideal, > "explicit" typing would be a major step in the right direction Lord have mercy(tm). From bg_ie at yahoo.com Mon Jan 7 08:27:27 2008 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Mon, 7 Jan 2008 05:27:27 -0800 (PST) Subject: Launching a wx GUI from within our python framework Message-ID: <0f4a1b94-9fc0-457f-81c3-b8986f5086cd@d70g2000hsb.googlegroups.com> Hi, At my work we have a framework writen in python which allows us to test our equipment. This framework is quite large and uses a Singelton called frameworkExec which we pass around between objects in order to share functionailty. For example, frameWorkExec stores an instance of the BatteryManagement module which I use to set the voltage during certain tests. I've just writen a gui using wx which I wish to use to calibrate our voltage supply. I launch this app at the moment within python win as follows - app = VoltageCalibrationApp(0) app.MainLoop() class VoltageCalibrationApp(wx.App): def OnInit(self): voltageCalibration = {} voltageCalibration[0.0] = 1.2 voltageCalibration[9.0] = 10.1 voltageCalibration[22.0] = 22.7 voltageCalibration[24.0] = 24.8 voltageCalibration[30.0] = 31.1 voltageCalibration[35.0] = 36.9 frame = VoltageCalibrationFrame(None, -1, 'Voltage Calibration', voltageCalibration) frame.Show(True) frame.Centre() return True I hope that by adding the code above into the framework, I will be able to call this app as part of the framework before the execution of certain tests, as follows - app = VoltageCalibrationApp(0) app.MainLoop() test1.run() test2.run() As you can see in the VoltageCalibrationApp class, I am currently hardcoding voltageCalibration. Rather than doing this, I wish to store them in our singleton which is available at the scope at which I create my VoltageCalibrationApp instance. But I can't figure our a way of referencing my singleton with the OnInit function. Normally, you would pass the reference via __init__ How can I do this? Thanks, Barry. From kay.schluehr at gmx.net Mon Jan 7 09:27:36 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 7 Jan 2008 06:27:36 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Message-ID: On Jan 7, 12:53 pm, Berco Beute wrote: > Cool! We knew it would happen one day :) > What could be the reason? Python 3? Jython 2.2? Java's loss of > sexiness? Python eats Perls lunch as a scripting language. From sebastien.ramage at gmail.com Wed Jan 16 05:37:58 2008 From: sebastien.ramage at gmail.com (=?ISO-8859-1?Q?S=E9bastien_Ramage?=) Date: Wed, 16 Jan 2008 02:37:58 -0800 (PST) Subject: using pyopengl 3.0.0b1 with py2exe Message-ID: Hi ! How can I make an exe that use the new pyopengl 3.0.0b1 ??? I use py2exe 0.6.6 with the 3.0.0a6 version I have make it working by copying the egg and by forcing loading it at the start of the app but it doesn't work with this version py2exe correctly detect it and include it in the app but I get this Traceback (most recent call last): File "texas.py", line 8, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\GL\__init__.pyo", line 2, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\raw\GL\__init__.pyo", line 6, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\raw\GL\constants.pyo", line 7, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\platform\__init__.pyo", line 20, in ImportError: No module named pkg_resources if I add an unzipped copy of setuptools in my app folder, py2exe include pkg_resources but I get this Traceback (most recent call last): File "texas.py", line 8, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\GL\__init__.pyo", line 2, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\raw\GL\__init__.pyo", line 6, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\raw\GL\constants.pyo", line 7, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\platform\__init__.pyo", line 57, in File "OpenGL\platform\__init__.pyo", line 53, in _load RuntimeError: Unable to find an implementation for the 'win32' ('nt') platform if anybody ahs a solution.... Seb From mr.cerutti at gmail.com Wed Jan 9 08:41:35 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 9 Jan 2008 08:41:35 -0500 Subject: alternating string replace In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <51302a8c0801090541u921bee9k79eebf2a84463e31@mail.gmail.com> On Jan 9, 2008 5:34 AM, cesco wrote: > Hi, > > say I have a string like the following: > s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... > > Thanks in advance Hum, hum... If I had a hammer... from pyparsing import * word = Word(alphas) sep = Literal('_').suppress() pair = Group(word + sep + word) pairs = delimitedList(pair, '_') print ','.join(':'.join(t) for t in pairs.parseString('hi_cat_bye_dog').asList()) -- Neil Cerutti From ckuanglim at yahoo.com Fri Jan 11 05:05:21 2008 From: ckuanglim at yahoo.com (Chan Kuang Lim) Date: Fri, 11 Jan 2008 02:05:21 -0800 (PST) Subject: help for installing PIL Message-ID: <32600.51914.qm@web60520.mail.yahoo.com> I'm using Window XP. How to install PIL 1.1.6? The Python i installed, is come with Plone. So, is it ok? Thank you. Regards, Chan Kuang Lim --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 28 04:53:37 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 28 Jan 2008 10:53:37 +0100 Subject: optional static typing for Python In-Reply-To: <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> Message-ID: <479da620$0$25625$426a74cc@news.free.fr> Russ P. a ?crit : > On Jan 27, 5:03 pm, Paddy > >> If static typing is optional then a program written in a dynamic >> language that passes such an automated static analysis of source code >> would have to be a simple program written in a simplistic way, and >> also in a static style. > > Yes, but for safety-critical software you usually want the simplest > possible solution. The last think you want is an unnecessarily "fancy" > design. Unless there is a darn good reason to write a "non-static" > program, you just don't do it. > > You might want to check into what the FAA allows in "flight-critical" > code, for example. I am certainly not an expert in that area, but I've > had a passing exposure to it. My understanding is that every possible > branch of the code must be fully and meticulously analyzed and > verified. Hence, the dynamic dispatching of ordinary object-oriented > code is either prohibited or severely frowned upon. Then Python is definitively out, so this whole thread is pointless. From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 19:25:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 28 Jan 2008 00:25:36 -0000 Subject: Python Genetic Algorithm References: Message-ID: <13pq880abaohbe4@corp.supernews.com> On Sun, 27 Jan 2008 15:09:52 -0800, Max wrote: > Hi all. I'm just getting introduced to Python (mostly through Dive Into > Python), and I've decided to use it for a project where I have to write > my own Genetic Algorithm. Even if you don't know about GAs, you might be > able to help with an issue I'm having. I'm just starting the project > off, so I'm still in the conceptual phase, and I'm stuck on how I'm > going to be able to implement something. > > In GAs, you operate on a Population of solutions. Each Individual from > the Population is a potential solution to the problem you're optimizing, > and Individuals have what's called a chromosome - a specification of > what it contains. For example, common chromosomes are bit strings, lists > of ints/floats, permutations...etc. I'm stuck on how to implement the > different chromosomes. I have a Population class, which is going to > contain a list of Individuals.Each individual will be of a certain > chromosome. Presumably all the individuals in the same population need to have the same kind of chromosome (differing only in the specific genes). > I envision the chromosomes as subclasses of an abstract > Individual class, perhaps all in the same module. How would that work? Shouldn't the different kinds of chromosomes (strings, lists of ints, etc.) be subclasses of an abstract Chromosome kind? What you need to think of is the difference between Is-A and Has-A relationships. An individual Has A chromosome, so you want a relationship something like this: class Individual(object): def __init__(self): self.chromosome = get_chromosome() On the other hand, something like a string chromosome Is A chromosome, and so is a list-of-ints Chromosome: class Chromosome(object): pass # abstract class class StringChromosome(Chromosome): pass # implement extra/different functionality class ListIntsChromosome(Chromosome): pass > I'm just having > trouble envisioning how this would be coded at the population level. There are so many ways... here's one possibility that doesn't even use a Population class. chromosome = StringChromosome # the class, not an instance default_genes = "GATACATATGGATTAGGGACCACTAC" size = 100 population = [] for i in range(size): genes = chromosome(default_genes) genes.mutate() population.append(Individual(genes)) I'm sure you can modify that to work on a class instance basis. > Presumably, when a population is created, a parameter to its __init__ > would be the chromosome type, but I don't know how to take that in > Python and use it to specify a certain class. Just pass the class itself. For example: # Define a class. class Parrot(object): pass x = "Parrot" # x is the NAME of the class y = Parrot # y is the CLASS itself z = Parrot() # z is an INSTANCE of the class You can use the class as a object, exactly the same as you can use a dict or a string or a float or any other object. y() will create a new Parrot instance exactly the same way that Parrot() would. Here's one possibility: class Population(object): def __init__(self, size=1000, chromosome_type=StringChromosome): individuals = [] for i in xrange(size): genes = chromosome_type() # create new set of genes x = Individual(genes) # add them to a new individual individuals.append(x) # and store it in the population self.individuals = individuals > I'm doing something similar with my crossover methods, by specifying > them as functions in a module called Crossover, importing that, and > defining > > crossover_function = getattr(Crossover, "%s_crossover" % xover) > > Where xover is a parameter defining the type of crossover to be used. The only time you need something like that is when you need to go from user-input (a string) to a binary object (e.g. a class, a function...). Suppose you read the crossover type from a text config file, or user input: import Crossover xover = raw_input("Enter a crossover type: valid values are X, Y, Z: ") crossover_function = getattr(Crossover, "%s_crossover" % xover) Instead of passing the string xover around as a parameter, you use it *once* to get the actual function object itself, and pass that around. Another alternative is to define something like this in the Crossover module, assuming you have three functions xcrossover etc.: user_map = {"X": xcrossover, "Y": ycrossover, "Z": zcrossover} Again, use it once to get the function object from the user input. Hope this helps, -- Steven From zugnush at gmail.com Wed Jan 16 17:40:38 2008 From: zugnush at gmail.com (zugnush at gmail.com) Date: Wed, 16 Jan 2008 14:40:38 -0800 (PST) Subject: Creating unique combinations from lists References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> <13osvl1j4pvka15@corp.supernews.com> Message-ID: <001640bd-7759-423b-ad74-275b27e5d5d6@v4g2000hsf.googlegroups.com> > > for a in range(5): ... > for z in range(5): means the inner loop runs 5**26 times so perhaps it's not only unpythonic but also uncomputable... From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 28 12:09:17 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 28 Jan 2008 18:09:17 +0100 Subject: sharing objects between classes In-Reply-To: <606aolF1pa0tfU2@mid.uni-berlin.de> References: <606aolF1pa0tfU2@mid.uni-berlin.de> Message-ID: <479e0c3b$0$1158$426a74cc@news.free.fr> Diez B. Roggisch a ?crit : > Gerardo Herzig wrote: > >> Hi all. Im wondering the way to share a database connection between some >> classes: >> >> So far, i came up with a simple class schema, where each class means >> each different relation, i mean i have the follow classes >> >> class Database(object): >> ## make the connection >> self.conn = make_conn(....) >> >> class Table(object): >> def get_fields: >> .... >> (snip) > > Take a look at the sources of e.g. SQLObject and how they do it (in SO, the > concept is called "HUB") > And while you're at it, take a look at SQLAlchemy too, and ask yourself if you really need to roll your own solution !-) From paddy3118 at googlemail.com Fri Jan 18 19:01:57 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 18 Jan 2008 16:01:57 -0800 (PST) Subject: TopSort in Python? References: <0000161d@bossar.com.pl> Message-ID: <358cc5a3-300f-49ba-9857-2f0cd629a4df@i12g2000prf.googlegroups.com> On Jan 18, 9:47 pm, startec... at gmail.com wrote: > Tim, > > Thanks for the topsort code. It would be useful in a project I'm > working on. Can I use the code for free under public domain? Thanks! > When I needed one I didn't know the name. I'm curious, how did you know to look for the topological sort algorithm by name? (http://paddy3118.blogspot.com/2007/10/whats-in-name.html) - Paddy. From DustanGroups at gmail.com Thu Jan 31 07:39:28 2008 From: DustanGroups at gmail.com (Dustan) Date: Thu, 31 Jan 2008 04:39:28 -0800 (PST) Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> <58d1bc12-206f-4cec-ad86-928d16e962f5@i3g2000hsf.googlegroups.com> Message-ID: <8d69e9e8-c892-4c65-ac54-c184ce303a2e@i3g2000hsf.googlegroups.com> On Jan 30, 7:02 pm, FireNWater wrote: > Thank you for the explanation. . . I think I now have a (foggy) > understanding of hash tables. It seems to be a way to create order > (an index) out of disorder (random numbers or characters) behind the > scenes. . The key thing to realize is, quite simply, don't rely on order in a dictionary. If you do, bad things can happen. The underlying implementation is not important to know. But if you really do want to know, let me correct you here, and give a perhaps clearer explanation (if not, there's no need to read any further): The 'order' that your speaking of is not implemented by the hash *table*, per se, but rather by the hash function, which returns an integer (the hash code). The hash table takes the hash code and calculates where in its list to place the object (as explained before, using modulo to shrink the integer into the range of the list). If multiple items end up in the same list, they are placed into a kind of linked list, with each node containing an object and pointing to the next. Of course, if too many objects end up in the same bucket, the efficiency of finding an object in the hash table reduces to that of a linked list, so hash functions are generally implemented to ensure a unique number (or as unique as possible) to every object. Python dictionaries are hash tables that automatically grow as space is needed. While integers in the range of the list will never change location unless the list shrinks, larger hash codes can move around quite apparently randomly. Space available is also a factor, as others have found out on this list. The order of a dictionary *is* determined, but factors involved in deciding that order may appear surprisingly mundane, and certainly variable across runs of your program. From software at ginstrom.com Tue Jan 8 05:29:11 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Tue, 8 Jan 2008 19:29:11 +0900 Subject: Look for a string on a file and get its line number In-Reply-To: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> Message-ID: <03a301c851e1$4f211a00$0203a8c0@MOUSE> > On Behalf Of Horacius ReX > I have to search for a string on a big file. Once this string > is found, I would need to get the number of the line in which > the string is located on the file. Do you know how if this is > possible to do in python ? This should be reasonable: >>> for num, line in enumerate(open("/python25/readme.txt")): if "Guido" in line: print "Found Guido on line", num break Found Guido on line 1296 >>> Regards, Ryan Ginstrom From lists at cheimes.de Sun Jan 27 20:37:08 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 28 Jan 2008 02:37:08 +0100 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: <92e2e361-68f4-4cd2-b0d4-750e19a06faf@s19g2000prg.googlegroups.com> References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net><60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <92e2e361-68f4-4cd2-b0d4-750e19a06faf@s19g2000prg.googlegroups.com> Message-ID: Paul McGuire wrote: > I thought at one time there was to be a "decorators" module in the > stdlib for just this kind of useful item. At minimum, you could post > this to the Python wiki at http://wiki.python.org/moin/PythonDecoratorLibrary. Please take the idea to the Python developer list. Several decorators are either already implemented (e.g. the first decorator is functools.wraps) and others are too special but some of the decorators including auto assignment seem useful. Christian From fredrik at pythonware.com Wed Jan 9 16:39:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 22:39:28 +0100 Subject: alternating string replace: Extended input (Long). In-Reply-To: References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: Paddy wrote: > To see how they act against 'corner cases' and > an exercise for me in trying to create corner cases. (I'm in to > functional testing at the mo'). sounds more like "pulling requirements out of thin air". not sure that helps the OP get a better understanding of Python, really. From kyosohma at gmail.com Sat Jan 12 09:32:35 2008 From: kyosohma at gmail.com (Mike) Date: Sat, 12 Jan 2008 06:32:35 -0800 (PST) Subject: Great Python books for the beginner References: <87fxx3gnoz.fsf@benfinney.id.au> Message-ID: <6d07f64b-beba-4e81-a4a9-4a7f21de473d@v46g2000hsv.googlegroups.com> On Jan 12, 7:47 am, Ben Finney wrote: > Landon writes: > > I was wondering if anyone had any opinions on what other titles I > > could look into since this one seems from a glance at reviews to be > > teaching mainly through game programming (a topic I'm not too > > interested in) or if this one is a quality book by itself. > > The book "Learning Python" is currently proving very useful to an > associate of mine. I'm watching his knowledge of Python grow > substantially every week, from what was an essentially zero start. > > Learning Python, 3rd Edition > Mark Lutz > O'Reilly > > > Looking through the text, it is very well structured, thoroughly > teaching all the fundamentals of the language and types and idioms > while referring back to already-learned material. The author makes a > living training people in Python, and the third edition has benefited > from his many years of experience finding effective ways to teach the > language. > > -- > \ "If you ever teach a yodeling class, probably the hardest thing | > `\ is to keep the students from just trying to yodel right off. | > _o__) You see, we build to that." -- Jack Handey | > Ben Finney I would recommend Lutz's other book, the wonderful Python tome "Programming Python 3rd Ed." as well. It's good for getting into the deepest part of Python's jungle. Mike From mail at timgolden.me.uk Wed Jan 23 10:10:07 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Jan 2008 15:10:07 +0000 Subject: subprocess and & (ampersand) In-Reply-To: References: Message-ID: <479758CF.5070600@timgolden.me.uk> Ross Ridge wrote: > Tim Golden wrote: >> but this doesn't: >> >> >> "c:\Program Files\Mozilla Firefox\firefox.exe" "%*" >> >> >> >> import subprocess >> >> cmd = [ >> r"c:\temp\firefox.bat", >> "http://local.goodtoread.org/search?word=tim&cached=0" >> ] >> subprocess.Popen (cmd) >> >> > > You need to use double quotes both in the .BAT file and in the string > you pass to subprocess.Popen(). > > Ross Ridge In the context of my example above, could you just say which bit you thing should be quoted and isn't? (That sounds sarcastic, but isn't; I just want to understand if I've missed something). If you simply requote the second element in the cmd list ('"http:/....."') then the internal quotes are escaped by some part of the mechanism and it still doesn't work. TJG From deets at nospam.web.de Sun Jan 20 13:50:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 20 Jan 2008 19:50:44 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt In-Reply-To: References: Message-ID: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> pythonewbie schrieb: > On 20 jan, 12:20, Christian Heimes wrote: >> pythonewbie wrote: >>> I am stucked on creating a function to get the Python install >>> directory (and site-packages directory) with a 100% reliable method... >> Only one method is 100% reliable: >> >> try: >> import yourextension >> except ImportError: >> available = False >> else: >> available = True >> >> Christian > > Hi Christian, > > OK thanks, interesting to detect if an extension is available or not. > > But for different reasons I also want to get the absolute path of > Python install directory (not only the executable under Linux) and > site-packages directory. > > How could I proceed ? Maybe sys.path is a starter? Diez From grante at visi.com Mon Jan 28 15:49:35 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 28 Jan 2008 20:49:35 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> <6067h9F1otsbrU1@mid.individual.net> <13ps3djqrl4ap5b@corp.supernews.com> <606s53F1p4slrU1@mid.individual.net> Message-ID: <13psfuvk77f5oc3@corp.supernews.com> On 2008-01-28, Bjoern Schliessmann wrote: > Grant Edwards wrote: >> No, it doesn't output corresponding machine code (that's what >> some Java JIT implementations do, but I'm not aware of any >> Python implementations that do that). The virtual machine >> interpreter just does the action specified by the bytecode. > > By "outputs corresponding machine code" I meant "feeds corresponding > machine code to the CPU" to make the analogy clearer. Which can > mean a function call. OK, but I think you're reaching a little. :) It's pretty hard for me to think of a program as something that's "feeding machine code to the CPU". In my mind, the VM is a program that's reading data from one source (the bytecode files) and performing operations on a second set of data (in-memory structures representing Python objects) based on what is found in that first set of data. -- Grant Edwards grante Yow! Is it clean in other at dimensions? visi.com From Karsten.Hilbert at gmx.net Mon Jan 14 12:46:33 2008 From: Karsten.Hilbert at gmx.net (Karsten Hilbert) Date: Mon, 14 Jan 2008 18:46:33 +0100 Subject: problem with logging exceptions with non-ASCII __str__ result Message-ID: <20080114174633.GH3926@merkur.hilbert.loc> Dear all, I have a problem with logging an exception. environment: Python 2.4, Debian testing ${LANGUAGE} not set ${LC_ALL} not set ${LC_CTYPE} not set ${LANG}=de_DE.UTF-8 activating user-default locale with returns: [de_DE.UTF-8] locale.getdefaultlocale() - default (user) locale: ('de_DE', 'utf-8') encoding sanity check (also check "locale.nl_langinfo(CODESET)" below): sys.getdefaultencoding(): [ascii] locale.getpreferredencoding(): [UTF-8] locale.getlocale()[1]: [utf-8] sys.getfilesystemencoding(): [UTF-8] _logfile = codecs.open(filename = _logfile_name, mode = 'wb', encoding = 'utf8', errors = 'replace') logging.basicConfig ( format = fmt, datefmt = '%Y-%m-%d %H:%M:%S', level = logging.DEBUG, stream = _logfile ) I am using psycopg2 which in turn uses libpq. When trying to connect to the database and providing faulty authentication information: try: ... try to connect ... except StandardError, e: _log.error(u"login attempt %s/%s failed:", attempt+1, max_attempts) print "exception type :", type(e) print "exception dir :", dir(e) print "exception args :", e.args msg = e.args[0] print "msg type :", type(msg) print "msg.decode(utf8):", msg.decode('utf8') t,v,tb = sys.exc_info() print "sys.exc_info() :", t, v _log.exception(u'exception detected') the following output is generated: exception type : exception dir : ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] exception args : ('FATAL: Passwort-Authentifizierung f\xc3\xbcr Benutzer \xc2\xbbany-doc\xc2\xab fehlgeschlagen\n',) msg type : msg.decode(utf8): FATAL: Passwort-Authentifizierung f?r Benutzer ?any-doc? fehlgeschlagen sys.exc_info() : psycopg2.OperationalError FATAL: Passwort-Authentifizierung f?r Benutzer ?any-doc? fehlgeschlagen Traceback (most recent call last): File "/usr/lib/python2.4/logging/__init__.py", line 739, in emit self.stream.write(fs % msg.encode("UTF-8")) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 191: ordinal not in range(128) Now, the string "FATAL: Passwort-Auth..." comes from libpq via psycopg2. It is translated to German via gettext within libpq (at the C level). As we can see it is of type string. I know from the environment that it is likely encoded in utf8 manually applying which (see the decode call) succeeds. On _log.exception() the logging module wants to output the message as encoded as utf8 (that's what the log file is set up as). So it'll look at the string, decide it is of type "str" and decode with the *Python default encoding* to get to type "unicode". Following which it'll re-encode with utf8 to get back to type "str" ready for outputting to the log file. However, since the Python default encoding is "ascii" that conversion fails. Changing the Python default encoding isn't really an option as it is advocated against and would have to be made to work reliably on other users machines. One could, of course, write code to specifically check for this condition and manually pre-convert the message string to unicode but that seems not as things should be. How can I cleanly handle this situation ? Should the logging module internally use an encoding gotten from the locale module rather than the default string encoding ? Karsten -- GPG key ID E4071346 @ wwwkeys.pgp.net E167 67FD A291 2BEA 73BD 4537 78B9 A9F9 E407 1346 From marduk at python.invalid Sun Jan 20 22:15:02 2008 From: marduk at python.invalid (Albert Hopkins) Date: Sun, 20 Jan 2008 21:15:02 -0600 Subject: When is min(a, b) != min(b, a)? Message-ID: This issue may have been referred to in news: but I didn't entirely understand the explanation. Basically I have this: >>> a = float(6) >>> b = float('nan') >>> min(a, b) 6.0 >>> min(b, a) nan >>> max(a, b) 6.0 >>> max(b, a) nan Before I did not know what to expect, but I certainly didn't expect this. So my question is what is the min/max of a number and NaN or is it not defined (for which I would have expected either an exception to be raised or NaN returned in each case). As a corrollary would I be able to rely on the above behavior or is it subject to change (to fix a bug in min/max perhaps :-)? From arkanes at gmail.com Fri Jan 25 21:55:41 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 25 Jan 2008 20:55:41 -0600 Subject: looking for a light weighted library/tool to write simple GUI above the text based application In-Reply-To: <45a8d4a7-d24d-461e-9783-59a7d697a041@q77g2000hsh.googlegroups.com> References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> <45a8d4a7-d24d-461e-9783-59a7d697a041@q77g2000hsh.googlegroups.com> Message-ID: <4866bea60801251855s305da3ebx4eb4c51a202b5a8a@mail.gmail.com> On Jan 25, 2008 5:17 PM, Paul Boddie wrote: > On 25 Jan, 22:06, "Lorenzo E. Danielsson" > wrote: > > > > What you need then is something like SVGAlib (http;//svgalib.org). Only > > really old people like myself know that it exists. I've never heard of > > any Python bindings for it, but that might be where you come in. I > > haven't looked at SVGAlib for years, and I'm not sure about the state of > > the video drivers. I suggest you look at that first. > > I believe that SVGAlib was superseded by GGI and other projects, and I > recall that SVGAlib was considered to be something of a nightware with > respect to how it handles various resources. Certainly, I haven't been > very impressed by the behaviour of software using it. > > > You could also look at GGI (http://ggi-project.org). GGI has different > > output targets. IIRC, one of them is directfb. To tell you the truth > > I've never really used GGI. There seems to be a python wrapper for GGI, > > although it is fairly old. Maybe you could look at the code for some ideas. > > I've had to build software using GGI, and the biggest problem has been > getting packages for it. That said, it seemed to work fairly > acceptably once built and installed. Meanwhile, some people favour > Allegro [1] for this kind of work, and I've been confronted with newly > developed software which uses Allegro, so it's arguably in a different > maintenance state than something like SVGAlib or GGI. > > > You should also be able to compile SDL to be able to use directfb as a > > target. If your libSDL handles it, then that should apply to wrapper > > libraries as well, including pygame. I've never tried running SDL apps > > this way, but if it works well, that would probably be your 'best' option. > > I'd agree with these sentiments; SDL seems to be the best supported > technology of this kind in the Python universe, and one of the most > widely deployed in general; I've felt quite comfortable building > software against it. It would be very interesting to see whether a > framebuffer-based SDL could support Pygame, and I imagine that the > Pygame mailing list might already have some answers in its archives on > this topic. > I agree that SDL is probably the best choice but for the sake of completeness, Gtk can (at least in theory - I've never tried it) be built against directfb and run without X. From duncan.booth at invalid.invalid Fri Jan 25 13:39:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Jan 2008 18:39:31 GMT Subject: is possible to get order of keyword parameters ? References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> Message-ID: rndblnch wrote: > (sorry, draft message gone to fast) > > i.e. is it possible to write such a function: > > def f(**kwargs): > > return result > > such as : > f(x=12, y=24) == ['x', 'y'] > f(y=24, x=12) == ['y', 'x'] > > what i need is to get the order of the keyword parameters inside the > function. > any hints ? > It would be best to do something which makes it obvious to someone reading the function call that something magic is going on. Either get people to pass a tuple, or if you want you could wrap a tuple in some sugar: class _OrderedVal(object): def __init__(self, name, current): self._name = name self._current = current def __call__(self, value): return _Ordered(self._current + ((self._name, value),)) class _Ordered(tuple): def __init__(self, current=()): self._current = current def __getattr__(self, name): return _OrderedVal(name, self._current) ordered = _Ordered() def f(args): return [ k for (k,v) in args] print f(ordered.x(12).y(24)) print f(ordered.y(24).x(12)) The question remains, what use is there for this? From ggpolo at gmail.com Mon Jan 7 08:57:38 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 11:57:38 -0200 Subject: dealing with binary files In-Reply-To: <47822DA4.9020401@fmed.uba.ar> References: <47822DA4.9020401@fmed.uba.ar> Message-ID: 2008/1/7, Gerardo Herzig : > Hi all. Im trying to read a binary data from an postgres WAL archive. > If i make a > xfile = open('filename', 'rb').xreadlines() > line = xfile.next() > > i see this sort of thing: > ']\xd0\x03\x00\x01\x00\x00\x00\r\x00\x00\x00\x00\x00\x00JM//DI+,D\x00\x00\x00\x01$\x00\x00\x00\x7f\x06\x00\x00y\r\t\x00\x02\x0f\t\x00\x00\x00\x10\x00)\x00\x01\x00\x12\x08 > \x00^\xc2\x0c\x00\x08\x00\x00\x003001({\xe8\x10\r\x00\x00\x00\xe4\xff\xffI\x10?l\x01@\x00\x00\x00$\x00\x00\x00\x00\n' > > This file suppose to have some information about database activity, but > at this point i cant do more than this, because i cant figure out what > to do in order to have some 'readable' text. > > Im guessing is some C code, im reading the struct module to see if it > helps, but im not into C programming, and im lost at the start of my > problem. You are looking at the correct module, struct. But in order to understand or even correctly extract data from a binary file, you need to know its structure. There should be some document describing the Postgre WAL file format. > > Can someone point me out some advice? > Thanks! > > Gerardo > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From ivan.illarionov at gmail.com Thu Jan 31 17:58:22 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 31 Jan 2008 14:58:22 -0800 (PST) Subject: REALLY simple xml reader 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: > 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. From nagle at animats.com Fri Jan 11 14:41:41 2008 From: nagle at animats.com (John Nagle) Date: Fri, 11 Jan 2008 11:41:41 -0800 Subject: Analyzing Python GC output - turns out to be MySQLdb problem In-Reply-To: References: <478707f2$0$36360$742ec2ed@news.sonic.net> <4787a42e$0$36403$742ec2ed@news.sonic.net> Message-ID: <4787C675.3030201@animats.com> Francesco Guerrieri wrote: > On Jan 11, 2008 6:20 PM, John Nagle wrote: >> Tried: >> print item.dir() >> got: >> 'cell' object has no attribute 'dir' It's a problem inside MySQLdb's "connections.py": def _get_unicode_literal(): def unicode_literal(u, dummy=None): return db.literal(u.encode(unicode_literal.charset)) return unicode_literal Each time a MySQLdb Connection object is created, it generates a closure, with another instance of the function "unicode_literal" plus some other junk. That generates circular references. Eventually those things get garbage-collected, but if you're running GC in leak detection mode, they show up. The reason for the closure is that "unicode_literal.charset" of the function is being stored into from outside the function. So there actually is a reason to use a closure. John Nagle From nospam-abuse at ilyaz.org Sat Jan 26 16:39:02 2008 From: nospam-abuse at ilyaz.org (Ilya Zakharevich) Date: Sat, 26 Jan 2008 21:39:02 +0000 (UTC) Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> Message-ID: [A complimentary Cc of this posting was sent to Summercool ], who wrote in article <27249159-9ff3-4887-acb7-99cf0d2582a8 at n20g2000hsh.googlegroups.com>: > so for example, it will grep for > > winter tire > tire > retire > tired > > but will not grep for > > snow tire > snow tire > some snowtires This does not describe the problem completely. What about thisnow tire snow; tire etc? Anyway, one of the obvious modifications of (^ | \b(?!snow) \w+ ) \W* tire should work. Hope this helps, Ilya From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 04:16:35 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 10:16:35 +0100 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <478733e8$0$18055$426a34cc@news.free.fr> Fredrik Lundh a ?crit : > A.T.Hofkamp wrote: > >> Now the question you need to answer for yourself, is how much more >> worth is >> your own time compared to the gain in CPU time. If you think they are >> equal (ie >> the problem as a whole should be solved as fast as possible, thus the >> sum of >> development time + execution time should be as short as possible), you >> can >> spend an additional 1.5 seconds development in the alternative solution. > > so you only run your programs once? Lol !-) From robert.kern at gmail.com Sat Jan 5 19:59:49 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 05 Jan 2008 18:59:49 -0600 Subject: Request for help with Image color space conversion In-Reply-To: <37094242-5728-466f-a3b9-c5ae76a9f3c5@s12g2000prg.googlegroups.com> References: <8586a895-f238-4a22-a1bb-31c39f22b4cc@n20g2000hsh.googlegroups.com> <37094242-5728-466f-a3b9-c5ae76a9f3c5@s12g2000prg.googlegroups.com> Message-ID: ttest wrote: >> Reimplement colorsys.rgb_to_hsv() such that it operates on arrays instead of >> scalars. Only minor modifications are necessary. >> >> -- >> Robert Kern > > Thanks! I'll try and see if a newcomer like me can get his head > around the array-centric modifications to colorsys. If you hit any roadblocks, drop in on numpy-discussion, and we'll help you out. http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mensanator at aol.com Mon Jan 7 17:54:02 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 7 Jan 2008 14:54:02 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python References: Message-ID: On Jan 7, 4:37?pm, dgoldsmith_89 wrote: > Can anyone point me to a downloadable open source English dictionary > suitable for programmatic use with python: I'm programming a puzzle > generator, and I need to be able to generate more or less complete > lists of English words, alphabetized. ?Thanks! ?DG www.puzzlers.org has numerous word lists & dictionarys in text format that can be downloaded. I recommend you insert them into some form of database. I have most of them in an Access db and it's 95 MB. That's a worse case as I also have some value-added stuff, the OSPD alone would be a lot smaller. From dg.google.groups at thesamovar.net Sun Jan 20 15:51:36 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Sun, 20 Jan 2008 12:51:36 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Message-ID: <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> Hi Marek, That's a really nice solution (and ultrafast). Unfortunately I realise I stated the problem imprecisely. You're only allowed to use each number once (otherwise there's a trivial solution for every problem, i.e. x/x + x/x + x/x + ... + x/x repeated y times for target y given any source number x). Trying your program on 234 from [100,9,7,6,3,1] gives you 9*9*3-9 using the 9 three times. Does your solution adjust to deal with this additional requirement? At first I thought it would be an easy fix, but maybe it's a little more complicated than I thought... Dan Goodman From HoustonJuliet at yahoo.com Sat Jan 26 19:54:55 2008 From: HoustonJuliet at yahoo.com (HoustonJuliet) Date: Sat, 26 Jan 2008 16:54:55 -0800 (PST) Subject: do design patterns still apply with Python? In-Reply-To: <15114748.post@talk.nabble.com> References: <8SINf.1718$No6.40137@news.tufts.edu> <120eok46fkf0j2b@corp.supernews.com> <15114746.post@talk.nabble.com> <15114748.post@talk.nabble.com> Message-ID: <15114781.post@talk.nabble.com> I think the world of Oliver Reed, and I was so sad to learn about his death. I always had a crush on Oliver Reed, and I have been a fan for over 35 years now. I was born on June 13, 1972, and I am 35 years old. HoustonJuliet wrote: > > I am a fan of Oliver Reeds since a toddler > > HoustonJuliet wrote: >> >> I am a fan of these people: >> >> Goldie Hawn >> Kate Hudson >> Oliver Reed >> Robert Conrad >> Vic Morrow >> Bill Bixby >> >> >> >> >> Grant Edwards wrote: >>> >>> On 2006-03-02, John Salerno wrote: >>> >>>> Since Python does so many things different, especially compared to >>>> compiled and statically typed languages, do most of the basic design >>>> patterns still apply when writing Python code? >>> >>> Definitely. Especially plaid, paisley, and a nice medium >>> houndstooth check. But please, not all at the same time. >>> >>> -- >>> Grant Edwards grante Yow! Maybe we could >>> paint >>> at GOLDIE HAWN a rich >>> PRUSSIAN >>> visi.com BLUE -- >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> :drunk: >> > > :drunk: -- View this message in context: http://www.nabble.com/do-design-patterns-still-apply-with-Python--tp3210321p15114781.html Sent from the Python - python-list mailing list archive at Nabble.com. From roman.yakovenko at gmail.com Sat Jan 12 02:24:33 2008 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Sat, 12 Jan 2008 09:24:33 +0200 Subject: opensg or openscenegraph In-Reply-To: <88ef87d8-d63b-4a7e-96db-07bc2a7a1fc9@s19g2000prg.googlegroups.com> References: <40zfj.33787$lD6.31634@newssvr27.news.prodigy.net> <88ef87d8-d63b-4a7e-96db-07bc2a7a1fc9@s19g2000prg.googlegroups.com> Message-ID: <7465b6170801112324p72bc8f77ye044438e47663afa@mail.gmail.com> On Jan 11, 2008 10:01 PM, wrote: > On Jan 4, 3:08pm, yomgui wrote: > > Hi, > > > > I need to use a scengraph for my python/opengl application > > but I have trouble finding out which one I should use. > > > > opensg or openscenegraph (OSG) ? > > > > I suppose the quality of the python bindings will make the decision. > > > > any advice ? > > > > thanks > > > > yomgui > > Hi yomgui, > > I am considering either of these as well for writing a simulation > game. > The Python Bindings I have found to date are: > > For OpenSG: > https://realityforge.vrsource.org/trac/pyopensg > > For OSG (there seems to be several variations of these): > http://code.astraw.com/projects/pyosg > > I suppose you could also use something like Py++ to create your own. PyOpenSG uses Py++ too :-) -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From george.sakkis at gmail.com Mon Jan 14 09:01:31 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 14 Jan 2008 06:01:31 -0800 (PST) Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> Message-ID: By the way, why do we need both NotImplementedError and the NotImplemented singleton object ? Couldn't we have just one of them ? From tjreedy at udel.edu Sun Jan 27 18:58:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jan 2008 18:58:48 -0500 Subject: Python self-evaluating strings References: <1BEEBF03-1A38-4745-B08B-DCA3106D1CC5@gmail.com> Message-ID: "Arnaud Delobelle" wrote in message news:1BEEBF03-1A38-4745-B08B-DCA3106D1CC5 at gmail.com... | An earlier post today got me thinking about "quines" (programs that | output themselves) in Python. I tried to find some on the web but | didn't find many ([1]). In particular I didn't find any that | corresponded to my instinctive (LISP-induced, probably) criterion: ... | I'd like to know if anyone on the list has indulged in this time- | bending/mind-wasting activity before. If so, it would be nice to | create a list of such expressions. Some years ago there was a substantial thread on this, (Shortest Self-Reproducing Programs, or some such) including a fairly long one from me that gave several 'shortest' (depending of definition and input method). It included a Python tranlation of at least one standard Lisp version. I presume you could find it on groups.google Terry J. Reedy From brunoacf at gmail.com Fri Jan 4 07:31:55 2008 From: brunoacf at gmail.com (Bruno Ferreira) Date: Fri, 4 Jan 2008 09:31:55 -0300 Subject: problem with global var In-Reply-To: References: Message-ID: <3448388f0801040431y37d9b58chdd4c7b120a17e30f@mail.gmail.com> Hello all, Amazing :) The program is working properly now, the code is much better and I learned a bit more Python. Thank you all, guys. Bruno. 2008/1/4, Peter Otten <__peter__ at web.de>: > Bruno Ferreira wrote: > > > I wrote a very simple python program to generate a sorted list of > > lines from a squid access log file. > > Now that your immediate problem is solved it's time to look at the heapq > module. It solves the problem of finding the N largest items in a list > much more efficiently. I think the following does the same as your code: > > import heapq > > def key(record): > return int(record[4]) > > logfile = open("squid_access.log", "r") > records = (line.split() for line in logfile) > topsquid = heapq.nlargest(50, records, key=key) > > for record in topsquid: > print record[4] > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From martin at marcher.name Sun Jan 20 14:58:34 2008 From: martin at marcher.name (Martin Marcher) Date: Sun, 20 Jan 2008 20:58:34 +0100 Subject: Looping through the gmail dot trick References: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> Message-ID: On Sunday 20 January 2008 17:38 Joshua Gilman wrote: > So I have a very interesting task ahead of me and it is to loop through an > email using the 'gmail dot trick'. Essentially this trick puts periods > throughout your email to make it look different. Even though it has > periods gmail will replace them all and send it to that email. are you saying that when i have 2 gmail addresses "foo.bar at gmail.com" and "foobar at gmail.com" they are actually treated the same? That is plain wrong and would break a lot of mail addresses as I have 2 that follow just this pattern and they are delivered correctly! Do you have any reference on that where one could read up why gmail would have such a behaviour? > So blah at gmail.com is the same as bl.ah at gmail.com. To my best knowledge it is not the same and must not be the same. The localpart of an email is entirely up to the receiving mailserver and cannot be tempered with without risking misdelivery (at least). If I'm wrong I'd be gladly corrected, just point me to the references. /martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From globophobe at gmail.com Fri Jan 25 21:11:28 2008 From: globophobe at gmail.com (globophobe) Date: Fri, 25 Jan 2008 18:11:28 -0800 (PST) Subject: ElementTree.fromstring(unicode_html) Message-ID: <58b4d6e5-da52-4247-9892-3fbcfd0f1979@m34g2000hsb.googlegroups.com> This is likely an easy problem; however, I couldn't think of appropriate keywords for google: Basically, I have some raw data that needs to be preprocessed before it is saved to the database e.g. In [1]: unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f \u3044\r\n' I need to turn this into an elementtree, but some of the data is japanese whereas the rest is html. This string contains a
. In [2]: e = ET.fromstring('%s' % unicode_html) In [2]: e.text Out[3]: u'\u3055\u3080\u3044\uff0f\n\u3064\u3081\u305f\u3044\n' In [4]: len(e) Out[4]: 0 How can I decode the unicode html
into a string that ElementTree can understand? From zorg724 at yahoo.fr Tue Jan 29 18:25:26 2008 From: zorg724 at yahoo.fr (sccs cscs) Date: Wed, 30 Jan 2008 00:25:26 +0100 (CET) Subject: Python UML Metamodel Message-ID: <183729.1052.qm@web90504.mail.mud.yahoo.com> Hello, I find an OPEN SOURCE tool (http://bouml.free.fr/) that Recently generates Python code from UML model. I like to model the Python language metamodel himself, with it, e.g the model of the language: I need that to better understand the language constraint of the language. for example, i like to model that : -a class "class" may inherit from 0..* class -a class "class" is create from a class that is its "metaclass" -a class "class" has 0..n attributes and 0..n method -a class "module" has 0..n class "class" Does anyone know a document that describes it already, because I think it is complicated to find this information in the documentation of Python. For example, can i say that: -a class "class" has 0..n properties ? It seems that the Python metamodel is not perfect, because I do not find attribute which give me the property list with a code like: "myPropertyList = myclass.properties" - a class "method" can contains nested "method", but what is the way to get a list of internal methods, without use ? Can i just write: "myNestedMethodList = method.nestedMethodList" I think a metamodel Python would be welcome to complement the BNF (http://docs.python.org/ref/grammar.txt), so as to know fully understand the relationships between the various elements of language. Thank you --------------------------------- Ne gardez plus qu'une seule adresse mail ! Copiez vos mails vers Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Mon Jan 14 06:30:04 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 14 Jan 2008 05:30:04 -0600 Subject: Threaded server References: Message-ID: Giampaolo Rodola' wrote: > I'm trying to run an asynchronous FTP server I wrote into a thread for > being able to run a test suite against it. > The code below is the threaded FTP server code I'm using: > > class FTPd(threading.Thread): > > def __init__(self): > self.active = False > threading.Thread.__init__(self) > > def start(self, flag=None): > assert not self.active > self.flag = flag > threading.Thread.start(self) > > def run(self): > assert not self.active > ftpd = ftpserver.FTPServer(address, ftp_handler) > if self.flag: > self.flag.set() > self.active = True > while self.active: > ftpd.server_forever(timeout=1, count=1) > ftpd.close() > > def stop(self): > assert self.active > self.active = False > > flag = threading.Event() > ftpd = FTPd() > ftpd.start(flag) > flag.wait() # wait for it to start > unittest.main() # run the test suite > ftpd.stop() > > Sometimes I get a strange error when all the tests have finished, the > server is stopped and Python is exiting: > > Ran 50 tests in 1.515s > > OK > Exception exceptions.TypeError: "'NoneType' object is not callable" in > thod FTPHandler.__del__ of 127.0.0.1:2 > 249 at 0xa4b080>> ignored > Exception exceptions.TypeError: "'NoneType' object is not callable" in > thod FTPServer.__del__ of 127.0.0.1:543 > 21 at 0x9e1a30>> ignored > > > I sincerely don't know why that happens but it's likely because I'm > not using threads properly. > My concern is that this could be caused by a sort of race condition > (e.g. Python tries to exit when ftpd.close call is not yet > completed). It looks like when python is shutting down, it has removed an object the ftphandler code relies on. I see you attempt to kill the ftp server with ftpd.stop(). That is good, but you don't wait for the thread to finish (it might take up to a second in ftpd.server_forever if I understand correctly). I expect if you put a self.join() at the end of the stop() method the problem will go away. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bronger at physik.rwth-aachen.de Thu Jan 10 07:20:10 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 10 Jan 2008 13:20:10 +0100 Subject: Conventions for dummy name References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de> <873at6k2qt.fsf_-_@benfinney.id.au> <87sl1613c8.fsf@physik.rwth-aachen.de> Message-ID: <87odbt27ph.fsf@physik.rwth-aachen.de> Hall?chen! David.Reksten at sweco.no writes: > Torsten Bronger wrote: > >> [...] >> >> Right, that's because I've used "__" where not all returning >> values are interesing to me such as >> >> a, b, __ = function_that_returns_three_values(x, y) > > Variable name "dummy" serves the same purpose, such as: > > a, b, dummy = function_that_returns_three_values(x, y) Granted, but my rationale is that "__" is less visible in the source code, so there is more emphasis on the actually interesting variables. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From a at b.c Thu Jan 10 08:37:05 2008 From: a at b.c (Caleb) Date: Thu, 10 Jan 2008 15:37:05 +0200 Subject: Python's great, in a word In-Reply-To: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: > The best thing about Python is _______. this. From sambo at voidstar.com Wed Jan 23 18:09:11 2008 From: sambo at voidstar.com (Sambo) Date: Wed, 23 Jan 2008 18:09:11 -0500 Subject: port forwarding: python scrypt or C ? Message-ID: Anyone aware of something that I could test my new DSL modem with. when I finally unlocked it ( Siemens 4200 ) some setting I saw made me wonder if it is filtering at all, but tiberian sun internet play was having problems. After going through the instructions at {http://portforward.com/english/routers/port_forwarding/Siemens/4200/Command_and_Conquer_Tiberian_Sun.htm} although not carefully since later I realized they entered the stuff in different order (not lowest to highest like I did, but it's not IPtables so hopefully it shouldn't matter). Soooo, I'd like to see it to believe it. Since I'll most likely going test from dialup on Linux to DSL on windows, Python would be best. Cheers. From mr.cerutti at gmail.com Fri Jan 18 13:20:33 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 18 Jan 2008 13:20:33 -0500 Subject: Bug in __init__? In-Reply-To: References: Message-ID: <51302a8c0801181020m3b5d4bebjf7ba6db9672bed9d@mail.gmail.com> On Jan 18, 2008 12:33 PM, Zbigniew Braniecki wrote: > > class A: > > def __init__ (self, val=[]): > > print val > > self.lst = val > > > > val is created only *once* and shared across all instaces of A. > > Thanks for help guys! > > It's really a nice pitfall, I can hardly imagine anyone expecting this, > or how easily could I find this info (e.g. what query should I give to > google to get it without bothering people on this group) In this unfortunate case, useful searches were "default arguments", which would be hard to guess without already knowing what's going wrong, or "python gotchas pitfalls", which is a good general purpose search for when you can't understand what's happening in simple code. -- Neil Cerutti From __peter__ at web.de Thu Jan 17 13:07:04 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jan 2008 19:07:04 +0100 Subject: Interesting Thread Gotcha References: Message-ID: Hendrik van Rooyen wrote: > "Duncan Booth" wrote: > >> Given that the start_new_thread function never actually got called, what >> code exactly do you expect to complain about the absence of a tuple? > > I don't understand this assertion. > > I thought that start_new_thread was called with a missing comma in > its argument list, which had the effect that I am complaining about. > > Putting the comma in place solved the problem, without any other > changes, so why do you say that start_new_thread was not called? Well, when kbd_driver() is called the kbd_q queue is probably empty, and as kbd_driver() runs in the main thread, who could ever put something into that queue? The function will therefore never terminate. Peter From SSchukat at dspace.de Fri Jan 4 08:50:45 2008 From: SSchukat at dspace.de (Stefan Schukat) Date: Fri, 4 Jan 2008 14:50:45 +0100 Subject: pydepend (checking dependencies like jdepend) ? References: <1969e240-9e80-4df1-b085-7956dfa4f7ae@t1g2000pra.googlegroups.com> <71a1c5ae-2051-44ff-998e-a342fa88ffab@e25g2000prg.googlegroups.com> Message-ID: <3E7E58237D756A4D85E7A36CB8C953ED01E24A@exchange2003.dspace.de> No, py2exe does not display such information but has an algorithm to collect such information. Perhaps this is a starting point for you. Stefan -----Original Message----- From: python-list-bounces+sschukat=dspace.de at python.org [mailto:python-list-bounces+sschukat=dspace.de at python.org] On Behalf Of Bernhard Merkle Sent: Friday, January 04, 2008 2:25 PM To: python-list at python.org Subject: Re: pydepend (checking dependencies like jdepend) ? On Jan 4, 1:57 pm, "Stefan Schukat" wrote: > Hi, > > try to look at py2exe. This module scans all dependencies to pack them > into one executable. my intention is to _know_ (or display or list or whatever) the dependencies. (see also my original posting). The aim is to control and have a view on modularization and e.g. avoid unnecessary bidirectional dependencies etc. does py2.exe display such information ? Berni. -- http://mail.python.org/mailman/listinfo/python-list From arnodel at googlemail.com Sun Jan 27 17:46:56 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 27 Jan 2008 14:46:56 -0800 (PST) Subject: explicit protocols and duck typing References: <5e28034f-a20f-4aa7-b299-9c9132ef2566@c4g2000hsg.googlegroups.com> Message-ID: On Jan 27, 7:10?pm, dg.google.gro... at thesamovar.net wrote: > Hi all, > > As I understand it, the idea behind duck typing is that you just take > an object and if it has the methods you want to use you use it > assuming it to be the right type of object. I'm interested in > extending this idea a bit, but I feel the sort of thing I have in mind > has already been thought of. So for example, in the program I'm > writing a 'state variable' specifier can be either an integer or a > string (the string name is mapped to an integer by another function > getvarindex(name)). In this case, I can't do duck typing by seeing if > the object has a method or not, because both of the types are built in > types. I don't want to have to force the user to have objects like > StateVariableSpecifier(name). Now at the moment, what I'm doing is > accepting anything as a state variable specifier, and just passing it > through the getvarindex function when I want to use it. This sort of > specifies a protocol for state variable specifiers without making it > explicit (like the sequence or mapping protocols built in to Python). > > What I'm wondering though is whether there is any value in making this > more explicit? Say, have a class which makes explicit the various > relationships involved, such as that the type of a state variable > specifier can be correct or incorrect (it has to be an int or a > string), that the value has to be correct (the integer has to be > between 0 and n for some n, and the string has to be in a dict of > names), and that there is a relationship between state variable > specifiers (int, string) and the underlying data type (the index of > the variable in an array). Making it more explicit seems like a good > idea, the question is in what way to make it more explicit. I can make > it explicit just by documenting the behaviour, or I can make it > explicit by adding code that enforces certain ways of using things. I would filter uses of a state variable specifier through a 'decode' function: def decode_svs(svs): for decode in decode_as_int, decode_as_str: try: return decode_as_int(svs) except DecodeError: continue raise DecodeError("Invalid svs") That could be done via overloading (see below) > For this simple example, it seems like just documenting it is the best > route, but I have similar issues with other more complicated parts of > the code. At the moment, a model for instance can be a Model object, > an Equation object or a tuple of functions, but this could be subject > to change in the future. What does object have to promise to be able to do in order to be a 'model'? > The issue I want to address is the long term maintainability of the > code when possibly many people might be contributing, the transparency > for other users, and the ease of documenting it. Any opinions? Maybe I'm way off mark here, but have you looked at overloading/ generic functions? The concept is explained in PEP 3124 [http://www.python.org/dev/peps/ pep-3124/] There's an implementation by Philip J. Eby in the svn repository: Some documentation: http://svn.python.org/view/sandbox/trunk/Overload3K/overloading.txt?rev=45971&view=markup The implementation: http://svn.python.org/view/sandbox/trunk/Overload3K/overloading.py?rev=45971&view=markup From ppetrick at gmail.com Mon Jan 21 15:51:59 2008 From: ppetrick at gmail.com (p.) Date: Mon, 21 Jan 2008 12:51:59 -0800 (PST) Subject: Transforming ascii file (pseduo database) into proper database Message-ID: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> I need to take a series of ascii files and transform the data contained therein so that it can be inserted into an existing database. The ascii files are just a series of lines, each line containing fields separated by '|' character. Relations amongst the data in the various files are denoted through an integer identifier, a pseudo key if you will. Unfortunately, the relations in the ascii file do not match up with those in the database in which i need to insert the data, i.e., I need to transform the data from the files before inserting into the database. Now, this would all be relatively simple if not for the following fact: The ascii files are each around 800MB, so pulling everything into memory and matching up the relations before inserting the data into the database is impossible. My questions are: 1. Has anyone done anything like this before, and if so, do you have any advice? 2. In the abstract, can anyone think of a way of amassing all the related data for a specific identifier from all the individual files without pulling all of the files into memory and without having to repeatedly open, search, and close the files over and over again? From paul at boddie.org.uk Tue Jan 22 17:36:22 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 22 Jan 2008 14:36:22 -0800 (PST) Subject: Processing XML that's embedded in HTML References: <6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> Message-ID: On 22 Jan, 21:48, Mike Driscoll wrote: > On Jan 22, 11:32 am, Paul Boddie wrote: > > > [1]http://www.python.org/pypi/libxml2dom > > I must have tried this module quite a while ago since I already have > it installed. I see you're the author of the module, so you can > probably tell me what's what. When I do the above, I get an empty list > either way. See my code below: > > import libxml2dom > d = libxml2dom.parse(filename, html=1) > rows = d.xpath('//XML[@id="grdRegistrationInquiryCustomers"]/BoundData/ > Row') > # rows = d.xpath("//XML/BoundData/Row") > print rows It may be namespace-related, although parsing as HTML shouldn't impose namespaces on the document, unlike parsing XHTML, say. One thing you can try is to start with a simpler query and to expand it. Start with the expression "//XML" and add things to make the results more specific. Generally, namespaces can make XPath queries awkward because you have to qualify the element names and define the namespaces for each of the prefixes used. Let me know how you get on! Paul From bdesth.quelquechose at free.quelquepart.fr Mon Jan 21 17:15:40 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 23:15:40 +0100 Subject: Transforming ascii file (pseduo database) into proper database In-Reply-To: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> Message-ID: <47952796$0$17606$426a74cc@news.free.fr> p. a ?crit : > I need to take a series of ascii files and transform the data > contained therein so that it can be inserted into an existing > database. The ascii files are just a series of lines, each line > containing fields separated by '|' character. Relations amongst the > data in the various files are denoted through an integer identifier, a > pseudo key if you will. Unfortunately, the relations in the ascii file > do not match up with those in the database in which i need to insert > the data, i.e., I need to transform the data from the files before > inserting into the database. Now, this would all be relatively simple > if not for the following fact: The ascii files are each around 800MB, > so pulling everything into memory and matching up the relations before > inserting the data into the database is impossible. > > My questions are: > 1. Has anyone done anything like this before, More than once, yes. > and if so, do you have > any advice? 1/ use the csv module to parse your text files 2/ use a temporary database (which schema will mimic the one in the flat files), so you can work with the appropriate tools - ie: the RDBMS will take care of disk/memory management, and you'll have a specialized, hi-level language (namely, SQL) to reassemble your data the right way. > 2. In the abstract, can anyone think of a way of amassing all the > related data for a specific identifier from all the individual files > without pulling all of the files into memory and without having to > repeatedly open, search, and close the files over and over again? Answer above. From gowricp at gmail.com Sat Jan 12 02:31:48 2008 From: gowricp at gmail.com (Gowri) Date: Fri, 11 Jan 2008 23:31:48 -0800 (PST) Subject: converting JSON to string References: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> <13og5g06rvrtefa@corp.supernews.com> Message-ID: On Jan 11, 7:21 pm, Adonis Vargas wrote: > Gowri wrote: > > Hello, > > > I actually have two questions: > > 1. Are there any libraries which convert XML to JSON? > > 2. I am currently doing the above using the DOM parser and creating a > > JSON array > > > > > for node in doc.getElementsByTagName("book"): > > isbn = node.getAttribute("isbn") > > titleNode = (node.getElementsByTagName("title") > > [0]).childNodes[0] > > title = titleNode.data > > primarykeys.append({'isbn': isbn, 'title': title}) > > return primarykeys > > > I want to send primarykeys as a response to my client. i use > > mod_python and apache. The problem is, I have not been able to figure > > out how to convert my JSON output to a string. > > > Could someone please help me? > > > Thanks in advance > > do: > > return str(primarykeys) > > Also there are Python modules for just this. Here is the very first link > from Google: > > http://pypi.python.org/pypi/python-json > > I have used this one personally and have been very satisfied with it. > There is another one (CJSON?) which is similar, but written in C, for > when performance may be an issue. > > Hope this helps. > > Adonis Actually, I have one other problem after all this. I see that if I try to construct JSON output as above, it is of the form [{'isbn': u'1-56592-724-9', 'title': u'The Cathedral & the Bazaar'}, {'isbn': u'1-56592-051-1', 'title': u'Making TeX Work'}] The extra 'u' seems to causing syntax error in JavaScript which is not able to parse this response string. Any idea how I can fix this? From paddy3118 at googlemail.com Fri Jan 11 22:18:14 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 11 Jan 2008 19:18:14 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <7x7iifsrur.fsf@ruckus.brouhaha.com> Message-ID: On Jan 12, 2:55 am, Pablo Ziliani wrote: > * die, thread! :-) def altrep7(s): from itertools import cycle import re a = cycle(':,') return re.sub('_', lambda x: a.next(), s) altrep7.author="George Sakkis(&Paul Rubin)" Gives: ## Program by: George Sakkis(&Paul Rubin) '' RETURNS '' '1' RETURNS '1' '2_' RETURNS '2:' '3_4' RETURNS '3:4' '5_6_' RETURNS '5:6,' '7_8_9' RETURNS '7:8,9' '10_11_12_' RETURNS '10:11,12:' '13_14_15_16' RETURNS '13:14,15:16' '17_18_19_20_' RETURNS '17:18,19:20,' '_' RETURNS ':' '_21' RETURNS ':21' '_22_' RETURNS ':22,' '_23_24' RETURNS ':23,24' '_25_26_' RETURNS ':25,26:' '_27_28_29' RETURNS ':27,28:29' '_30_31_32_' RETURNS ':30,31:32,' '_33_34_35_36' RETURNS ':33,34:35,36' '__' RETURNS ':,' '___' RETURNS ':,:' '____' RETURNS ':,:,' '_____' RETURNS ':,:,:' - Paddy. From duncan.booth at invalid.invalid Thu Jan 3 08:45:59 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Jan 2008 13:45:59 GMT Subject: Treating a unicode string as latin-1 References: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Message-ID: Simon Willison wrote: > How can I tell Python "I know this says it's a unicode string, but I > need you to treat it like a bytestring"? Can you not just fix your xml file so that it uses the same encoding as it claims to use? If the xml says it contains utf8 encoded data then it should not contain cp1252 encoded data, period. If you really must, then try encoding with latin1 and then decoding with cp1252: >>> print u'Bob\x92s Breakfast'.encode('latin1').decode('cp1252') Bob?s Breakfast The latin1 codec will convert unicode characters in the range 0-255 to the same single-byte value. From timr at probo.com Fri Jan 18 02:04:50 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 18 Jan 2008 07:04:50 GMT Subject: ANN:proxysocket(socks4,socks5)v0.1 References: <7228288b-cb34-40ba-8483-a2dc57115511@d21g2000prf.googlegroups.com> Message-ID: Samuel wrote: > >http://code.google.com/p/proxysocket/downloads/list Allow me to introduce you to the concept of comments. Python allows you to include descriptive sentences in your program that explain what the functions do, what your intentions were, what the variables do, what the states mean, etc. It's easy to do; you just start the text with # signs. # This function allows you to ... # These variables define the connection state as the connection is # made. They're great. You should try them. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From boblatest at yahoo.com Tue Jan 8 05:42:39 2008 From: boblatest at yahoo.com (Robert Latest) Date: 8 Jan 2008 10:42:39 GMT Subject: (SOLVED) Re: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> <5ugulaF1hqn2cU1@mid.uni-berlin.de> <5ugv5dF1i0edtU1@mid.dfncis.de> <87fxx8mycm.fsf@mulj.homelinux.net> <5uh0gcF1hoialU2@mid.dfncis.de> Message-ID: <5uh2cvF1hpvl4U1@mid.dfncis.de> pexpect is the solution. Seems to wrap quite a bit of dirty pseudo-tty hacking. robert From aipa_6 at msn.com Mon Jan 28 21:06:03 2008 From: aipa_6 at msn.com (aida) Date: Mon, 28 Jan 2008 18:06:03 -0800 (PST) Subject: LEELO NO TE ARREPENTIRAS Message-ID: <9e7f5fc4-ebe7-4f8c-a192-82a460573680@l32g2000hse.googlegroups.com> L?elo, no te arrepentir?sPOR FAVOR ANTES DE ELIMINAR ESTE MENSAJE, LEAN PRIMEROY TOMEN LA DECISI?N DESPU?S.ESTO TE PUEDE AYUDAR A PAGAR TUS DEUDAS O TUS ESTUDIOSHola amigos:Esto es lo me pas? d?as atr?s, mientras navegaba por estas p?ginas de noticias, as? como usted lo est? haciendo ahora. Se me apareci? un art?culo similar a este que dec?a:"Usted puede recibir miles de d?lares en pocas semanas con una inversi?n de US $6.00 d?lares (seis d?lares)". Enseguida pens?: "?Oh no, otra estafa m?s?" Pero como la mayor?a de nosotros, la curiosidad pudo m?s y segu? leyendo; segu?a diciendo: " Usted enviar? US $1.00 (un d?lar) a cada uno de los 6 nombres y direcciones mencionados en este art?culo. Despu?s, anote usted su nombre y direcci?n al final de la lista reemplazando al numero #6, y env?e o ponga este art?culo en por lo menos 200 NEWSGROUPS (hay miles de estos en todo el mundo).Nota: Si te encuentras en otro pa?s, debes cambiar tu moneda nacional a d?lares, pues en todos los pa?ses cambian d?lares y es m?s f?cil para todos.No existe ning?n truco, la diferencia de este sistema y otros, es que usted tiene una lista de 6 en vez de 5, esto significa que el promedio de ayuda ser? aproximadamente ?????15 veces mayor!!!!! Despu?s de pensarlo una y otra vez y de consultarlo con unos amigos, decid? probarlo. Pens? que lo ?nico que podr?a perder eran 6 estampillas y US $6 d?lares y que me quedar?a la satisfacci?n de haber contribuido a ayudar a 6 personas en el mundo, que como yo se encuentran con serios problemas econ?micos.Como probablemente muchos de nosotros estaba un poco preocupado por la legalidad de todo esto. Entonces consulte al Servicio de Correos y me confirmaron que en realidad era legal!!!!!!!. Me qued? asombrado y de inmediato envi? mis US $6 d?lares... IMAG?NENSE QUE!!!!...Siete d?as despu?s, empec? a recibir DINERO por correo!!!!Estaba feliz, como ni?o con juguete nuevo, y muy sorprendido!!!! Y pensaba que esto se acabar?a en)unos pocos d?as m?s. Me trat? de olvidar del tema, en todo caso ya hab?a recibido una ayuda similar a la que hab?a dado... pero el dinero segu?a llegando. En mi primera semana recib? entre US $20 y US $30 d?lares. Para el final de la segunda semana hab?a recibido un total de US $1,000 (mil d?lares)!!!!!! No lo POD?A CREER!! En la tercera semana $10,000 (diez mil) y todav?a segu?a llegando m?s!!! En mi cuarta semana ten?a un total de $41,000 d?lares y a?n sigue llegando m?s ayuda (en mi casa se la pasan abriendo sobres y yo consiguiendo "NEWSGROUP" para continuar ayudando a m?s gente y retribuir la ayuda recibida hasta este momento. ESTO SE PUSO SERIO.Todo esto vali? la pena, la ayuda de US $6 d?lares que ofrec? las 6 estampillas dio sus frutos; y pensar que yo gastaba m?s de US $6 d?lares semanales en sorteos y loter?a tratando de obtener los recursos que necesitaba para salir de mis problemas econ?micos y no pasaba nada.AHORA PERM?TANME EXPLICARLES COMO FUNCIONA ESTOY LO MAS IMPORTANTE......... EL POR QU? FUNCIONA EXCELENTEMENTEUsted aseg?rese de imprimir este art?culo AHORA, para sacar toda la informaci?n a medida que la necesite. El proceso es muy f?cil y consiste en 3 (tres) sencillos pasos:PASO N?.1: Obtenga 6 hojas de papel y escriba en cada una de ellas: "FAVOR DE INCLUIRME EN SU LISTA DE CORRESPONDENCIA O E-MAIL".Ahora consiga 6 billetes de US $1 (un d?lar) e introduzca cada d?lar en un sobre, procurando envolverlo con la hoja de manera que el billete no se vea a trav?s del sobre!!Es mejor que el papel sea de color oscuro para prevenir los robos de correspondencia. En este momento usted deber?a tener 6 sobres sellados y en ellos un papel con la frase mencionada, su nombre y direcci?n, y un billete de US $1 (un dolar). Lo que usted est? haciendo con esto es crear un "servicio de ayuda" y esto hace que sea ABSOLUTAMENTE LEGAL!!!Env?e los 6 sobres a las siguientes direcciones: #1.- NAYVI DEL CARMEN LEAL FLORESCalle 47 #215 x 20 y 43 DiagonalFraccionamiento BrisasC.P. 97144 M?rida, Yucat?n, M?xico.# 2.- ERNESTO JAVIER ESTRELLA ALCOCERCalle 50 #117-A x 39 y 39CFracc. Francisco de MontejoC.P. 97203 M?rida, Yucat?n, M?xico. #3.- PATRICIA NAVARRO FUENTESTabunco # 1697.Villa la Providencia de Macul La FloridaSantiago, Chile#4.-ANDREA LEBLANC ORDENESNUEVA MATURANA #0495, VILLA ALEMANAQUINTA REGION, CHILE #5.- CATALINA INOSTROZA CATALANVOLCAN PARINACOTA #642, VILLA CORDILLERA TALAGANTE, CHILE #6.-AIDA PACHECO SAAVEDRA.Casilla 3612. Oficina Moneda. Santiago. Chile PASO N? 2: Ahora elimine el numero #1 de lista de arriba y mueva los otros nombres un numero para arriba ( el #6 se convierte en el #5, y el # 5 se convierte en el #4, etc...) y agregue su NOMBRE Y SU DIRECCI?N en el #6 de la lista.LES COMENTO QUE SON DIRECCIONES VERDADERAS Y CREO QUE NO CUALQUIER PERSONA PONE LA DIRECCI?N DE SU CASA O NEGOCIO S?LO PORQUE S?.PASO N? 3: Cambie todo lo que crea conveniente de este art?culo, pero trate de mantenerlo lo m?s cercano posible al original. Ahora ponga su art?culo en por lo menos 200 NEWSGROUP (existen m?s de 24,000,000 Newsgroups). S?lo necesita 200, pero en cuantos m?s ponga esta carta con sus datos, m?s dinero recibir? como ayuda.Aqu? van algunas indicaciones de c?mo introducirse a los Newsgroups:COMO MANEJAR LOS "NEWSGROUPS" (GRUPOS):N? 1.-Usted no necesita redactar toda esta carta para hacer la suya propia. Solamente ponga su cursor al comienzo de esta carta, haga "click" con el bot?n izquierdo del mouse y d?jelo presionado; b?jelo hasta el final de la carta y suelte el bot?n del mouse.Toda la carta deber? estar "sombreada". Entonces haga un "click" con el bot?n derecho del mouse en cualquier lugar de la parte sombreada y seleccione "COPY" o "COPIAR". Esto har? que toda la carta quede en la memoria temporal de su computadora.N? 2.- Abra un archivo nuevo "NOTEPAD" o "WORD". Haga un "clik" con el bot?n derecho del mouse y elija "PASTE" o "PEGAR". Grabe el)archivo con el nombre que desee y que le permita identificarlo en cualquier momento. Desde ese momento tendr? esta carta en su computadora y podr? agregar su nombre en el lugar #6 de la lista siguiendo las instrucciones que aparecen m?s arriba.N? 3.- Teniendo grabada esta carta en su computadora, cada vez que lo desee le podr? agregar o cambiar algo sin problemas.PARA LOS QUE USAN INTERNET EXPLORER.N? 4.- Vaya a Newsgroups y seleccione "post an article" o "escribir nuevo mensaje/discusi?n"N? 5.- Cargue el art?culo que guard? previamente.N? 6.- Seleccione el contenido completo del archivo que contiene la carta y copie usando el mismo procedimiento descrito anteriormente. Regrese a Newsgroups y elija "TO NEWS" o "NUEVA DISCUSI?N", de esta forma est? creando el espacio para poder "pegar" el contenido de la carta.N? 7.- Presione el bot?n "post" ("Enviar Mensaje")PARA LOS QUE MANEJAN NETSCAPE.N? 4. Dentro del programa Netscape, vaya a la ventana titulada "Window" y seleccione "NetscapeNews". Entonces elija del men? "Options", seleccione "Show all Newsgroups".En seguida aparecer? una lista de todos los newsgroups de su server , haga clic en cualquier nuewsgroup. De este newsgroup haga clic debajo de "TO NEWS", el cual deber?a estar arriba, en el extremo izquierdo de la pagina de newsgroup. Esto le llevara a la caja de mensajes.N? 5.-Llene este espacio. Este ser? el titulo que ver?n todos cuando recorran por la lista de un grupo en particular.N? 6.- Marque Seleccione el contenido completo del archivo que contiene la carta y copie usando el mismo procedimiento descrito anteriormente. Regrese a newsgroup "TO NEWS" y usted esta creando y empastando esta carta dentro de su programa o "posting".N? 7.- Presione "send", que est? en la parte superior izquierda y usted ha finalizado con su primer newsgroup.........FELICIDADES!!!!!!!!!!!!!!!!!!!!!!!!!!ESO ES TODO!!! Todo lo que tiene que hacer es meterse en diferentes Newsgroups (grupos) y empastarlos; cuando ya tenga pr?ctica, solo le tomar? unos 30 segundos yor cada newsgroupRECUERDE: MIENTRAS MAS NEWSGROUPS CONSIGA, MAS RESPUESTAS Y DINERO RECIBIR?!!!!, PERO DEBE DE ENTRAR EN PO[ LO MENOS... 200 NEWSGROUPS...Y YA ESTA!!!!!... Usted estar? recibiendo dinero de todo el mundo, de lugares que ni conoce y en unos pocos d?as!!!. Eventualmente querr? rentar un P.O. BOX. por la cantidad de sobres que ir? recibiendo!!!(((ASEGURESE DE QUE TODAS LAS DIRECCIONES EST?N CORRECTAS)))Ahora el POR QU? de todo esto:De 200 cartas que ya coloqu? en igual n?mero de Newsgroups (Grupos), digamos que recibiera s?lo 5 repuestas (baj?simo ejemplo). Entonces recib? $5 D?lares de ayuda From deets at nospam.web.de Sun Jan 27 09:15:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jan 2008 15:15:10 +0100 Subject: how to make format operator % work with unicode as expected In-Reply-To: References: Message-ID: <603hvkF1orqggU1@mid.uni-berlin.de> Peter Pei schrieb: > I am using things like "%-20s%-60s%-10s" in tkinter listbox to make it > look like a table, with mono sized font like lucie system. But this does > not work with data contains "Les mis?rables", because it is unicode, and > one byte is not neccessary one character. Now how can I resolve this issue? By learning that unicode is not UTF-8, instead of insulting others of being incompetent. Diezz From thelanguageofcities at gmail.com Sun Jan 27 20:28:10 2008 From: thelanguageofcities at gmail.com (Max) Date: Sun, 27 Jan 2008 17:28:10 -0800 (PST) Subject: Python Genetic Algorithm References: Message-ID: On Jan 27, 8:01 pm, "Terry Reedy" wrote: > "Max" wrote in message > > news:caf75b0d-7ed3-421a-93f8-6f7d90a98923 at p69g2000hsa.googlegroups.com... > | In GAs, you operate on a Population of solutions. Each Individual from > | the Population is a potential solution to the problem you're > | optimizing, and Individuals have what's called a chromosome - a > | specification of what it contains. For example, common chromosomes are > | bit strings, lists of ints/floats, permutations...etc. I'm stuck on > | how to implement the different chromosomes. I have a Population class, > | which is going to contain a list of Individuals. Each individual will > | be of a certain chromosome. I envision the chromosomes as subclasses > | of an abstract Individual class, perhaps all in the same module. I'm > | just having trouble envisioning how this would be coded at the > | population level. Presumably, when a population is created, a > | parameter to its __init__ would be the chromosome type, but I don't > | know how to take that in Python and use it to specify a certain class. > | > | I'm doing something similar with my crossover methods, by specifying > | them as functions in a module called Crossover, importing that, and > | defining > | > | crossover_function = getattr(Crossover, "%s_crossover" % xover) > | > | Where xover is a parameter defining the type of crossover to be used. > | I'm hoping there's some similar trick to accomplish what I want to do > | with chromosomes - or maybe I'm going about this completely the wrong > | way, trying to get Python to do something it's not made for. Any help/ > | feedback would be wonderful. > > 'Python genetic algorithm' returns 25000 hits with Google. > But here is what I would do without looking at them. > > Start with the Individual base class and common methods, some virtual (not > implemented). An example of a virtual method would be the > crossover(self,other) method, since its implementation depends on the > concrete chromosome implementation. Make subclasses with concrete > chromosome types (initialized in .__init__). For each, implement the > methods that depend on that type. In particular, the mutate(self, args) > and crossover(self,other, args) methods. > > For the Population class, give __init__ an 'individual' parameter and > store it as an attribute. If you want, check that it > 'issubclass(Individual)'. To add members to the population, call the > stored subclass. To operate on the population, write Population methods. > There should not depend on the particular chromosome implementations. To > operate on the members within the Population methods, call their Individual > methods. b = a.mutate(args); c = a.crossover(b, args). > > I see two ways to deal with scoring the fitness of individuals within a > Population instance. Once is to write a particular fitness function, pass > it to the Population init to save as an attribute, and then call as needed. > The other is to subclass an Individual subclass, give it that funtion > fitness method, and pass that subsubclass to Population. The difference is > between having Population methods calling self.fitness(some_member) versus > some_member.fitness(). > > I hope this is helpful for getting started. > > Terry Jan Reedy Yeah, I looked up some of those GAs, but talking with people about code helps me a lot more than looking at other code. I know it's strange for a programmer to prefer social interaction, but...just something about how I'm wired. This sounds a lot like what I was thinking of doing. In particular, I was planning on having the problem's program itself (which would create an instance of a GA to optimize something) specify the fitness function and pass it upwards to the population (or maybe to the GA, which contains a population). Thanks for the help. From jigisbert.etra-id at grupoetra.com Sun Jan 13 16:06:55 2008 From: jigisbert.etra-id at grupoetra.com (j igisbert.etra-id) Date: Sun, 13 Jan 2008 22:06:55 +0100 Subject: *SPAM*: 04.6/4.0 - Re: Manually installing PIL In-Reply-To: References: <001001c84dda$23d26760$2000a8c0@depid.local> Message-ID: My PDA runs with Windows Mobile 2003 SE.... could you or someone please explain me what to do? Thanks a lot for your effort. -----Original Message----- From: Fredrik Lundh To: python-list at python.org Date: Sun, 13 Jan 2008 21:18:37 +0100 Subject: *SPAM*: 04.6/4.0 - Re: Manually installing PIL j igisbert.etra-id wrote: > this. I have download Imaging-1.1.6 source code, and I found PIL folder, > but not binary file. If I download windows exe installer, it works > great, but I want to install manually for installing it on my PDA.... as the name implies, the source code distribution contains source code only. to turn that into a binary component, you need a working compiler for your target platform. what OS does your PDA run? -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet at rudnyi.ru Sat Jan 5 11:12:50 2008 From: usenet at rudnyi.ru (Evgenii Rudnyi) Date: Sat, 5 Jan 2008 08:12:50 -0800 (PST) Subject: Fortran to Python References: Message-ID: On Jan 4, 2:21?pm, Jeroen Ruigrok van der Werven wrote: > I got someone who asked me to make changes in an old Fortran program she is > using for some calculations. > The calculations are pretty standard aside from 2 calls to DLINCG (an IMSL > numerical_libraries function to calculate an inverse matrix). > > What I wonder about, does anybody have a Fortran to Python conversion page > somewhere to map some of the basic types to Python equivalents? > What kind of speed difference should I expect? When it comes to matrices the difference can be quite big. You can find the comparison of NumPy, Fortran 77, C, and C++ for matrix multiplication with and without optimized BLAS at http://matrixprogramming.com/MatrixMultiply/ NumPy interfaces optimized BLAS, and you can find a LAPACK interface in SciPy, so it is a good choice. Evgenii From Scott.Daniels at Acm.Org Thu Jan 10 20:33:33 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 10 Jan 2008 17:33:33 -0800 Subject: What is "lambda x=x : ... " ? In-Reply-To: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> Message-ID: <13odhiipb1ddi45@corp.supernews.com> zslevi at gmail.com wrote: > I'm reading this page: http://www.ps.uni-sb.de/~duchier/python/continuations.html > and I've found a strange usage of lambda: > > #################### > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ################### > > What does "y=y" and "c=c" mean in the lambda function? > I thought it bounds the outer variables, so I experimented a little > bit: > > ################# > x = 3 > y = lambda x=x : x+10 > > print y(2) > ################## > > It prints 12, so it doesn't bind the variable in the outer scope. Primary use: funcs = [lambda x=x: x+2 for x in range(10)] print funcs[3]() _or_ funcs = [] for x in range(10): funcs.append(lambda x=x: x+2) print funcs[3]() Try these w/o the default binding. --Scott David Daniels Scott.Daniels at Acm.Org From menkaur at gmail.com Sun Jan 20 05:17:03 2008 From: menkaur at gmail.com (menkaur at gmail.com) Date: Sun, 20 Jan 2008 02:17:03 -0800 (PST) Subject: Quixote cookies Message-ID: <0f43cf8f-0ce1-42ea-bd8e-4a5d7925c6dd@s12g2000prg.googlegroups.com> Hi, guys I'm trying to use cookies in Quixote. This is the code: env = copy(os.environ) req = HTTPRequest(sys.stdin, env) req.response.set_cookie("xxx","666") cc = req.get_cookie("xxx"); For some reason it cc is always None. What am I doing wrong? From arnodel at googlemail.com Tue Jan 29 08:26:25 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 29 Jan 2008 05:26:25 -0800 (PST) Subject: Executing other python code References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: On Jan 29, 12:18?am, Tim Rau wrote: > I'm working on a game, and I'd like players to be able to define thier > ships with scripts. Naturally, I don't want to give them the entire > program as thier romping ground. I would like to invoke a seperate > interpreter for these files, and give it a limited subset of the > functions in my game. What is the best way to achieve this effect? One simple solution would be to forbid import statements in the scripts, to import the scripts as modules and inject whatever functions you want them to be able to use in the module's namespace. So: ====== script.py ======= def play(): if enemy_is_near(): fire_gun() else: move_forward() ======================= ====== Game engine ==== scriptobjs = [enemy_is_near, fire_gun, move_forward, turn_left, turn_right] def getscript(scriptname): script = __import__(scriptname) for obj in scriptobjs: setattr(script, obj.__name__, obj) return script def playscript(script): script.play() ======================= Something like this. Obviously this is over simplified! -- Arnaud From king.a.joe at gmail.com Mon Jan 21 14:52:34 2008 From: king.a.joe at gmail.com (Joseph king) Date: Mon, 21 Jan 2008 14:52:34 -0500 Subject: question Message-ID: I just need to pass this through....... How does everyone feel about the fact that SUN bought mySQL for $1 billion. I don't find it possible that they would keep it a free product if they invested that much money on it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tiwarishravan at gmail.com Wed Jan 30 06:26:33 2008 From: tiwarishravan at gmail.com (tiwarishravan at gmail.com) Date: Wed, 30 Jan 2008 03:26:33 -0800 (PST) Subject: HI all Message-ID: <1b6a8d39-8077-4d4e-b05f-1e0037472ed8@d4g2000prg.googlegroups.com> I am shravan tiwari, i want to know that how i'll run any python file(*.py) on command prompt r python GUI. i tried this python test.py but i have got error, syntax error. so can i get the solution. From martin at v.loewis.de Sat Jan 5 12:12:48 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 05 Jan 2008 18:12:48 +0100 Subject: fastest method to choose a random element In-Reply-To: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> Message-ID: <477fba91$0$8348$9b622d9e@news.freenet.de> > Any other ideas? How about this: def random_pick(list, property): L = len(list) pos = start = random.randrange(L) while 1: x = list[pos] if property(x): return x pos = (pos + 1) % L if pos == start: raise ValueError, "no such item" Regards, Martin From bj_666 at gmx.net Sun Jan 27 04:39:21 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jan 2008 09:39:21 GMT Subject: how to make format operator % work with unicode as expected References: <13po55nc0q0s06@corp.supernews.com> Message-ID: <6031q9F1oh17aU1@mid.uni-berlin.de> On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: > You didn't understand my question, but thanks any way. > > Yes, it is true that %s already support unicode, and I did not contradict > that. But it counts the number of bytes instead of characters, and makes > things like %-20s out of alignment. If you don't understand my assertion, > please don't argue back and I am only interested in answers from those who > are qualified. I have the impression from your original post [?] because it is unicode, and one byte is not neccessary one character. that you confuse unicode and utf-8. Are you sure you are qualified to ask such a question in the first place!? :-? Ciao, Marc 'BlackJack' Rintsch From washakie at gmail.com Wed Jan 30 06:50:27 2008 From: washakie at gmail.com (washakie) Date: Wed, 30 Jan 2008 03:50:27 -0800 (PST) Subject: find nearest time in datetime list Message-ID: <15180398.post@talk.nabble.com> Hello, I have a list of datetime objects: DTlist, I have another single datetime object: dt, ... I need to find the nearest DTlist[i] to the dt .... is there a simple way to do this? There isn't necessarily an exact match... Thanks! .john -- View this message in context: http://www.nabble.com/find-nearest-time-in-datetime-list-tp15180398p15180398.html Sent from the Python - python-list mailing list archive at Nabble.com. From nagle at animats.com Tue Jan 15 01:53:36 2008 From: nagle at animats.com (John Nagle) Date: Mon, 14 Jan 2008 22:53:36 -0800 Subject: Is there some Python function that searches "sys.path" for a module? Message-ID: <478c5755$0$36354$742ec2ed@news.sonic.net> Python's own loader searches "sys.path" for module names, but is there some function that makes that search functionality accessible to Python programs? I need the absolute pathname of a module, with the search being done exactly the same way "import" does it. The loader for "egg" files has this functionality, but I'd like to find out if there's a standard way to do this before looking into that source code. Also, it seems that the environment variable "PYTHONPATH" applies to "import", but not to the starting module named on the Python command line. Is that correct? Thanks. John Nagle From fliot at kyriba.com Fri Jan 4 12:48:57 2008 From: fliot at kyriba.com (Francois Liot) Date: Fri, 4 Jan 2008 18:48:57 +0100 Subject: Simple calculation error Message-ID: <3CDC4613E97B134A9A7E61A5E43DCA55010FDE36@fr-mail1.fr.kyriba.com> Dear all, I observed a strange calculation answer, on both python 2.3.4 and 2.4.4 >>> print 753343.44 - 753361.89 -18.4500000001 >>> print ( (753361.89*100) - (753343.44*100) ) / 100 18.45 Can somebody help me to play correctly with decimal values? Thanks in advance, Francois Liot -------------- next part -------------- An HTML attachment was scrubbed... URL: From ndbecker2 at gmail.com Mon Jan 21 13:28:40 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 21 Jan 2008 13:28:40 -0500 Subject: index of min element of sequence Message-ID: What's a good/fast way to find the index of the minimum element of a sequence? (I'm fairly sure sorting the sequence is not the fastest approach) From over at thepond.com Fri Jan 25 20:10:26 2008 From: over at thepond.com (over at thepond.com) Date: Sat, 26 Jan 2008 01:10:26 GMT Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: On Thu, 24 Jan 2008 08:02:06 GMT, Tim Roberts wrote: >Bjoern Schliessmann wrote: > >>Grant Edwards wrote: >> >>> Trying to find assembly language stuff to look at is futile. >>> Python doesn't get compiled into assembly language. >> >>So, how do processors execute Python scripts? :) > >Is that a rhetorical question? Grant is quite correct; Python scripts (in >the canonical CPython) are NOT compiled into assembly language. Scripts >are compiled to an intermediate language. Processors execute Python >scripts when the interpreter, written in a high-level language and compiled >to assembly, interprets the intermediate language created by the Python >"compiler". Intel processors can only process machine language, which is essentially binary 1's and 0's. All a processor understands is voltages, either 0 Volts or 5 volts on older systems, or 3.3 volts and less on newer systems. Generally, a positive voltage is a logical 1 and 0 volts is a logical 0. There's no way for a processor to understand any higher level language, even assembler, since it is written with hexadecimal codes and basic instructions like MOV, JMP, etc. The assembler compiler can convert an assembler file to a binary executable, which the processor can understand. If you look at the Python interpreter, Python.exe, or Pythonw, the Windows interface, or the Python24.dll, the main library for python, you will see they are normal 32 bit PE files. That means they are stored on disk in codes of 1's and 0's, and decompile into assembler. You can't decompile them into Python directly, although I'm sure someone is trying. No compiled file can be decompiled into it's original format easily or automatically, although there are decompilers that will convert them to a reasonable assembler decompilation. If a Python script was understood directly by the processor, no interpreter would be necessary. Ask yourself what the interpreter is doing. It's taking the scripting language and converting to the language of the operating system. However, it's the processor that dictates how programs are written, not the OS. That's why a Linux OS will run on an Intel machine, as a Windows OS does. Both Linux and Windows compile down to binary files, which are essentially 1's and 0's arranged in codes that are meaningful to the processor. Once a python py file is compiled into a pyc file, I can disassemble it into assembler. Assembler is nothing but codes, which are combinations of 1's and 0's. You can't read a pyc file in a hex editor, but you can read it in a disassembler. It doesn't make a lot of sense to me right now, but if I was trying to trace through it with a debugger, the debugger would disassemble it into assembler, not python. From haag at lsu.edu.invalid Thu Jan 3 22:08:55 2008 From: haag at lsu.edu.invalid (Alaric) Date: Fri, 04 Jan 2008 03:08:55 GMT Subject: Information on PyGMT? Message-ID: Hello - I'm seeking info on the PyGMT python wrapper for the Generic Mapping Tools package. Unfortunately, the only site (forge.nesc.ac.uk) that seems to offer the code (written by Magnus Hagdorn) is not responding. I don't know if that's a temporary condition or if that site is out of commission. Google isn't revealing much recent discussion either.... which is sad, as I would imagine this to be a valuable tool! Can anyone shed any light?? Better yet, does anyone have the latest tarball, and an FTP site they can offer it on? :) Many thanks! Alaric From JO3chiang at gmail.com Fri Jan 4 01:11:04 2008 From: JO3chiang at gmail.com (jo3c) Date: Thu, 3 Jan 2008 22:11:04 -0800 (PST) Subject: linecache and glob References: <0e16ca26-9e34-4f97-83de-9ddc3693d085@i12g2000prf.googlegroups.com> <0a62d553-7fe9-41c0-84dc-a1f3749b46f8@e23g2000prf.googlegroups.com> Message-ID: <3682a1dd-a3a6-436f-87a0-37feaef65ccc@h11g2000prf.googlegroups.com> i have a 2000 files with header and data i need to get the date information from the header then insert it into my database i am doing it in batch so i use glob.glob('/mydata/*/*/*.txt') to get the date on line 4 in the txt file i use linecache.getline('/mydata/myfile.txt/, 4) but if i use linecache.getline('glob.glob('/mydata/*/*/*.txt', 4) won't work i am running out of ideas thanks in advance for any help jo3c From dfabrizio51 at gmail.com Thu Jan 31 21:34:13 2008 From: dfabrizio51 at gmail.com (chewie54) Date: Thu, 31 Jan 2008 18:34:13 -0800 (PST) Subject: Will Python on day replace MATLAB????????????????????????????????????????????????????? References: Message-ID: > 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 From q16941 at motorola.com Thu Jan 3 07:58:41 2008 From: q16941 at motorola.com (ashish) Date: Thu, 03 Jan 2008 18:28:41 +0530 Subject: Installing pcaplib Message-ID: <477CDC01.4050508@motorola.com> Hi All, I am trying to install "pylibpcap-0.6.1" but i am getting these errors . python ./setup.py install . . . . . constants.c:172: (near initialization for `pcapmodule_DLT[52]') pcap.c: In function `init_pcap': pcap.c:4246: structure has no member named `value' pcap.c:4260: warning: passing arg 3 of `PyModule_AddStringConstant' discards qualifiers from pointer target type error: command 'gcc' failed with exit status 1 Please tell me how to solve this problem.Do i have to install anything else before installing this library. Thanks in Advance Ashish From sjmachin at lexicon.net Mon Jan 21 15:06:19 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jan 2008 12:06:19 -0800 (PST) Subject: index of min element of sequence References: <7xfxwrt1dx.fsf@ruckus.brouhaha.com> Message-ID: <6243b2e3-e2eb-41fb-bb7c-88b40ffcef60@e25g2000prg.googlegroups.com> On Jan 22, 6:38 am, Paul Rubin wrote: > Neal Becker writes: > > What's a good/fast way to find the index of the minimum element of a > > sequence? (I'm fairly sure sorting the sequence is not the fastest > > approach) > > Python 2.5 (untested): > > from operator import itemgetter > minindex = min(enumerate(seq), key=itemgetter(1))[1] Bzzzt! >>> seq = [1000, 9, 8, 7, 2000, 3000] >>> from operator import itemgetter >>> minindex = min(enumerate(seq), key=itemgetter(1))[1] >>> minindex 7 >>> min(enumerate(seq), key=itemgetter(1)) (3, 7) s/[1]/[0]/ or more generally: minindex, minvalue = min(enumerate(seq), key=itemgetter(1)) From python at rcn.com Wed Jan 2 11:44:49 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 2 Jan 2008 08:44:49 -0800 (PST) Subject: Two candies References: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com> Message-ID: [bearophileH] > > 1) A fast and memory efficient way to create an array.array at a > certain size. > At the moment I can see some ways to do it: > > from array import array > from itertools import repeat > a = array("l", repeat(0, n)) #3 . . . > - #3 interacts badly with Psyco (Psyco doesn't digest itertools at > all), and it seems not memory efficient. #3 is a fine choice. It is memory efficient -- the repeat() itertool takes-up only a few bytes. It doesn't need psyco, you already have to fast C routines talking to each other without having to go through the interpreter loop. Raymond From odysseus1479-at at yahoo-dot.ca Mon Jan 14 03:38:51 2008 From: odysseus1479-at at yahoo-dot.ca (Odysseus) Date: Mon, 14 Jan 2008 08:38:51 GMT Subject: Elementary string-formatting References: <7d17fa05-67c5-4acb-91b6-c53fdf70ae27@q77g2000hsh.googlegroups.com> Message-ID: In article <7d17fa05-67c5-4acb-91b6-c53fdf70ae27 at q77g2000hsh.googlegroups.com>, John Machin wrote: > > div operator? The integer division operator is // Yes, sorry, that's what I meant. -- Odysseus From ptmcg at austin.rr.com Fri Jan 4 11:46:27 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 4 Jan 2008 08:46:27 -0800 (PST) Subject: how to use bool References: <477d08d1$0$510$bed64819@news.gradwell.net> Message-ID: On Jan 3, 10:09?am, tinn... at isbd.co.uk wrote: > > With my philosophical programming hat on the first thing I'd say (as a > fairly beginning python programmer) is "avoid multiple returns from a > function/method if at all possible". ?They breed all sorts of problems > and errors, in particular if there's any clearing up to do you have to > do it in lots of places (or you forget it in some places). > This conventional wisdom predates the introduction of constructs such as try-catch-finally. In fact, you are just lulling yourself into some false security if you think that that single return at the end of your method is the only exit point of your routine. Exceptions can (and will) happen just about anywhere. I know, you had your C hat on, but even C++'ers fall into this trap. I was on a project that cited explicit delete statements during code reviews as likely memory leaks in the face of exceptions, and each was to be replaced with auto-cleanup objects such as auto_ptr. The same was done for other resource alloc/release pairs, such as locks, database connections, cursors, etc. These were looooong-running server processes, and they ran for months with no memory growth at all. If I were to suggest a similar topic for Python code reviews, it would be to look at paired statements and to ensure that the cleanup/ recovery statement was wrapped in a finally block. There's more than just memory that needs bookkeeping, so garbage collection wont solve all these other resource management problems. -- Paul From khoard at gmail.com Wed Jan 30 17:47:36 2008 From: khoard at gmail.com (FireNWater) Date: Wed, 30 Jan 2008 14:47:36 -0800 (PST) Subject: Dictionary Keys question Message-ID: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> I'm curious why the different outputs of this code. If I make the dictionary with letters as the keys, they are not listed in the dictionary in alphabetical order, but if I use the integers then the keys are in numerical order. I know that the order of the keys is not important in a dictionary, but I was just curious about what causes the differences. Thanks!! list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] list2 = [1,2,3,4,5,6,7,8] Dictionary = dict(zip(list1, list2)) print Dictionary Dictionary1 = dict(zip(list2, list1)) print Dictionary1 From dstromberglists at gmail.com Mon Jan 21 18:13:35 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Mon, 21 Jan 2008 23:13:35 GMT Subject: bags? 2.5.x? References: <478bbae6$0$25383$9b4e6d93@newsspool4.arcor-online.net> <437501ef-1b38-4e47-9106-c846a456dd49@c23g2000hsa.googlegroups.com> Message-ID: On Thu, 17 Jan 2008 18:18:53 -0800, Raymond Hettinger wrote: >> >> I keep wanting something like them - especially bags with something >> >> akin to set union, intersection and difference. >> >> > How about this recepie >> > > >> The author of the bag class said that he was planning to submit bags >> for inclusion in 2.5 - is there a particular reason why they didn't go >> in? > > Three reasons: > > 1. b=collections.defaultdict(int) went a long way towards meeting the > need to for a fast counter. > > 2. It's still not clear what the best API would be. What should list(b) > return for b.dict = {'a':3, 'b':0, 'c':-3}? Perhaps, [('a', 3), ('b', > 0), ('c', -3)] or ['a', 'a', 'a'] > or ['a'] > or ['a', 'b', 'c'] > or raise an Error for the negative entry. I'd suggest that .keys() return the unique list, and that list() return the list of tuples. Then people can use list comprehensions or map() to get what they really need. It might not be a bad thing to have an optional parameter on __init__ that would allow the user to specify if they need negative counts or not; so far, I've not needed them though. > 3. I'm still working on it and am not done yet. > Decent reasons. :) Thanks! Here's a diff to bag.py that helped me. I'd like to think these meanings are common, but not necessarily! $ diff -b /tmp/bag.py.original /usr/local/lib/bag.py 18a19,58 > def _difference(lst): > left = lst[0] > right = lst[1] > return max(left - right, 0) > _difference = staticmethod(_difference) > > def _relationship(self, other, operator): > if isinstance(other, bag): > self_keys = set(self._data.keys()) > other_keys = set(other._data.keys()) > union_keys = self_keys | other_keys > #print 'union_keys is',union_keys > result = bag() > for element in list(union_keys): > temp = operator([ self[element], other [element] ]) > #print 'operator is', operator > #print 'temp is', temp > result[element] += temp > return result > else: > raise NotImplemented > > def union(self, other): > return self._relationship(other, sum) > > __or__ = union > > def intersection(self, other): > return self._relationship(other, min) > > __and__ = intersection > > def maxunion(self, other): > return self._relationship(other, max) > > def difference(self, other): > return self._relationship(other, self._difference) > > __sub__ = difference > From levilista at gmail.com Fri Jan 11 04:38:05 2008 From: levilista at gmail.com (zslevi@gmail.com) Date: Fri, 11 Jan 2008 01:38:05 -0800 (PST) Subject: what does **kw mean? Message-ID: <99cc3280-bffd-4004-a3ae-a06244a82759@e6g2000prf.googlegroups.com> I've been reading the following example, and couldn't figure out, what **kw mean. (It's an empty dictionary, but what's the semantics): def wrap(method): def wrapped(self, *args, **kw): print "begin" method(self, *args, **kw) print "end" return wrapped class Test(object): def method(self, name): print "method(%r)" % name t = Test() t.method("pure") Test.method = wrap(Test.method) t.method("wrapped") From montyphyton at gmail.com Thu Jan 3 16:46:47 2008 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: Thu, 3 Jan 2008 13:46:47 -0800 (PST) Subject: How is AI implemented References: Message-ID: On Jan 3, 6:49 pm, "Martin Marcher" wrote: > Hi, > > I know it's not a trivial field but I had some readings about > artificial intelligence lately and my personal conclusion is that it's > mostly just statistics. > > Naively explained: > > continiously gather and store information and apply a default rating > > 1) answer "questions" with gathered information according to rating > 2) store/calculate rating based upon input (be it an interface or user input) > 3) goto 1 (sorry for the goto) really naively :) > > So I think that in general there hasn't yet been any artificial > intelligence programmed (Note: I believe I'm aware of the difference > between artificial intelligence and artificial conscusiness where the > second would be able to answer things like: "How are you today" and > the first can answer factual knowledge) > What you want to do is look up the difference between weak AI and strong AI. Everything we have to this day is weak AI, and there is still a debate between various scientists as to whether strong AI is even possible. Be sure to look at Chinese room argument to see if strong AI is really what you need. (http://en.wikipedia.org/wiki/Chinese_room) > Am I thinking right here or is there some (preferrably) web reading > available on that or in depth links about the topic? > > thanks and sorry for OT posting > martin > > --http://noneisyours.marcher.namehttp://feeds.feedburner.com/NoneIsYours From lefevrol at yahoo.com Thu Jan 24 18:04:50 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Fri, 25 Jan 2008 00:04:50 +0100 Subject: read and readline hanging Message-ID: I am calling subprocess.Popen with p = Popen(args, bufsize=-1, stdin=PIPE, stdout=PIPE, stderr=PIPE) and after sending come command to the process, I try to read from p.stdout but after a few calls I hang. What is the correct way to do this, i.e., to read everything w/o getting stuck? I am not familiar with all these low-level functions and their annoying blocking behaviour. Note that I don't want to close the process because I want to send more commands to it after that, read the results, and so on and on. Thanks, -- O.L. From aspineux at gmail.com Tue Jan 15 09:02:48 2008 From: aspineux at gmail.com (aspineux) Date: Tue, 15 Jan 2008 06:02:48 -0800 (PST) Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> <7xsl105fvv.fsf@ruckus.brouhaha.com> <13onli9dk7mu926@corp.supernews.com> <7xhchgatin.fsf@ruckus.brouhaha.com> Message-ID: <4dc54032-e139-49d6-9270-793915ec3612@i29g2000prf.googlegroups.com> On Jan 15, 12:15 am, Paul Rubin wrote: > Steven D'Aprano writes: > > map = {'a': Aclass, 'b': Bclass, 'c': Cclass} > > class_ = map.get(astring, default=Zclass) > > > The result I want is the class, not the result of calling the class > > (which would be an instance). If I wanted the other semantics, I'd be > > using defaultdict instead. > > I used default as a keyward arg name indicating the presence of > a callable. I probably should have called it defaultfunc or something. > > x = d.get('a', f) # --> default value is f > x = d.get('a', defaultfunc=f) # --> default value is result of f() . Nice idea, but if I want args I need to write it like that: x=d.get('a', defaultfunc=f, funcargs=(1,2,3)) instead of d['a', f(1,2,3)] From dzizes451 at gmail.com Thu Jan 31 13:41:38 2008 From: dzizes451 at gmail.com (dzizes) Date: Thu, 31 Jan 2008 10:41:38 -0800 (PST) Subject: PIL linux err Message-ID: <15211773.post@talk.nabble.com> Hi, I'm trying to run simple .py on linux, which is using PIL. Below error message which I receive: File "/usr/lib/python2.4/site-packages/PIL/Image.py", line 960, in histogram self.load() File "/usr/lib/python2.4/site-packages/PIL/ImageFile.py", line 180, in load d = Image._getdecoder(self.mode, d, a, self.decoderconfig) File "/usr/lib/python2.4/site-packages/PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available Do you know what might be the problem? michal -- View this message in context: http://www.nabble.com/PIL-linux-err-tp15211773p15211773.html Sent from the Python - python-list mailing list archive at Nabble.com. From ejensen at visi.com Wed Jan 9 20:41:10 2008 From: ejensen at visi.com (Ed Jensen) Date: Thu, 10 Jan 2008 01:41:10 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: <13oattm5ijqvf58@corp.supernews.com> Bruno Desthuilliers wrote: > And the reference implementation of Python (CPython) is not > interpreted, it's compiled to byte-code, which is then executed by a VM > (just like Java). Wow, this is pretty misleading. Java is, indeed, compiled to bytecode; however, modern JVMs typically compile the bytecode to native code and then execute the native code. CPython strictly interprets bytecode; it does not compile the bytecode to native code. From Russ.Paielli at gmail.com Sun Jan 27 18:13:54 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 15:13:54 -0800 (PST) Subject: optional static typing for Python References: Message-ID: <23f7c55a-949f-41a4-b558-81861ede258f@f10g2000hsf.googlegroups.com> On Jan 27, 3:08 pm, Jarek Zgoda wrote: > Russ P. pisze: > > >>> I noticed that Guido has expressed further interest in static typing > >>> three or four years ago on his blog. Does anyone know the current > >>> status of this project? Thanks. > >> I thought it was april fools joke? > > > On January 21, 2000? Which calendar do you use? > > Static typing in Python is usual theme of april fools jokes. I hope Guido doesn't find out about that! From aaron.watters at gmail.com Wed Jan 2 10:33:22 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Wed, 2 Jan 2008 07:33:22 -0800 (PST) Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <13nn9k48n7ohr95@corp.supernews.com> Message-ID: <69337707-ff18-4b39-af0a-78cf0a14b667@1g2000hsl.googlegroups.com> > I must admit I feel a hint of amusement though at your comment above, when > it's sent from precisely the sort of setup you appear bemused by - since > you appear to have already bought into it without realising ! :-D Ok, so if we include yahoo mail and gmail in "cloud computing" then I guess usenet is also cloud computing. How about ftp? ssh? nfs? Oh I get it. It's another meaningless marketing buzz phrase. I mean, really, I've been using web-mail and various varieties of remote storage for over a decade. What is *new* about the concept? (I see some hints above, but it's mixed in with a lot of other stuff...) -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=fud From bkasterm at gmail.com Fri Jan 25 09:03:24 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Fri, 25 Jan 2008 06:03:24 -0800 (PST) Subject: Convert list to file object without creating an actual file. References: <32ae7d79-248a-4ac3-b51c-756699f11837@t1g2000pra.googlegroups.com> <13piogo8c3edd02@corp.supernews.com> Message-ID: <88916c48-11ed-4e18-b164-c1fd30023ff8@c4g2000hsg.googlegroups.com> The suggestion to use StringIO to make a string have the same interface as a file works perfect in my situation. Here is now the working result (just in case it is useful to anyone) part of this is still a definite hack and suggestions for improvement are certainly appreciated. Want: have an easily maintainable file containing homework assignments, but have it nicely formatted on my webpage. Solution: have a file with due dates and assignments as follows: Mon Jan 28 1.1: 1,2,3 (at this point only the indentation is taken into account). Then use the following script (setting some variables and server, login, and passwd for the ftp connection): #!/usr/bin/env python homeworktxt = "homework.txt" homeworkhtml = [] import sys import ftplib import StringIO Indent = ' ' StartTable = '
\n' EndTable = '
DueAssignment
' StartTitle = Indent + '\n' + Indent + Indent +'' EndTitle = Indent + Indent + '\n' + Indent + Indent + '' BeforeItems = Indent + Indent + Indent + '' AfterItems = Indent + Indent + Indent + '
\n' + Indent + Indent + '\n' + Indent + '' StartItem = Indent + Indent + Indent + Indent + '' EndItem = Indent + Indent + Indent + Indent + '' #if 1 >=len (sys.argv): # print "Need an filename as an argument" # print sys.argv[0] + " " #else: hw = open (homeworktxt).readlines() Last = 0 # 0: at the start, 1: just printed an item, 2: just printed a title #print StartTable homeworkhtml.append(StartTable) for x in hw: if ' ' == x[0]: if 2 == Last: homeworkhtml.append(BeforeItems) homeworkhtml.append(StartItem) homeworkhtml.append(Indent + Indent + Indent + Indent + Indent + x.strip()) homeworkhtml.append(EndItem) Last = 1 elif '#' != x[0]: if 1 == Last: homeworkhtml.append(AfterItems) homeworkhtml.append(StartTitle) homeworkhtml.append(Indent + Indent + Indent + x.strip()) homeworkhtml.append(EndTitle) Last = 2 # else : # homeworkhtml.append('COMMENT') # homeworkhtm if 1 == Last: homeworkhtml.append(AfterItems) homeworkhtml.append(EndTable) for i in range(0,len(homeworkhtml)): homeworkhtml[i] = homeworkhtml[i] + '\n' homeworkhtmlfile = StringIO.StringIO() homeworkhtmlfile.writelines(homeworkhtml) homeworkhtmlfile.seek(0) # open connection to the server ftp = ftplib.FTP('server', 'login', 'password' ) # go to location of root of website on server ftp.cwd('httpdocs') # put the contends of a file filename = "test.html" ftp.storlines("STOR " + filename, homeworkhtmlfile) # quite the connection ftp.quit() This will result in an html file that you can include (say with php include) into a webpage displaying a table. Examples of the result are currently on my webpage (www.bartk.nl/teach.php ) (if you read this much later look on the waybackmachine). Again, thanks for the suggestions, Best, Bart PS: apologies for the mixing of spaces and tabs. I had a computer crash and have not yet corrected the settings. So this is a combination of default behavior and my preferred settings. From ian at neustyle.com Sun Jan 6 05:13:40 2008 From: ian at neustyle.com (Soviut) Date: Sun, 6 Jan 2008 02:13:40 -0800 (PST) Subject: Point Object References: <4673edc3-b76c-4c6e-98f0-4f2becee930e@j20g2000hsi.googlegroups.com> Message-ID: On Jan 5, 6:37 am, "pjmu... at googlemail.com" wrote: > I am nes to python and need some help. Can anyone lead me in the > right direction to create and print a Point object, and then use id to > print the object's unique identifier. Translate the hexadecimal form > into decimal and confirm that they match. > > Any help woul be much appreciated. > > Pete You shouldn't have to compare the hex IDs. Just a simple comparison operator will work: firstPoint = Point() secondPoint = Point() print(firstPoint == secondPoint) result: True From hacker.stevenson at gmail.com Wed Jan 16 14:15:16 2008 From: hacker.stevenson at gmail.com (breal) Date: Wed, 16 Jan 2008 11:15:16 -0800 (PST) Subject: Creating unique combinations from lists Message-ID: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> I have three lists... for instance a = ['big', 'small', 'medium']; b = ['old', 'new']; c = ['blue', 'green']; I want to take those and end up with all of the combinations they create like the following lists ['big', 'old', 'blue'] ['small', 'old', 'blue'] ['medium', 'old', 'blue'] ['big', 'old', 'green'] ['small', 'old', 'green'] ['medium', 'small', 'green'] ['big', 'new', 'blue'] ['small', 'new', 'blue'] ['medium', 'new', 'blue'] ['big', 'new', 'green'] ['small', 'new', 'green'] ['medium', 'new', 'green' ] I could do nested for ... in loops, but was looking for a Pythonic way to do this. Ideas? From deets at nospam.web.de Wed Jan 23 09:12:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 Jan 2008 15:12:29 +0100 Subject: How avoid both a newline and a space between 2 print commands? References: Message-ID: <5vp0adF1n7mjfU1@mid.uni-berlin.de> seberino at spawar.navy.mil wrote: > print "foo" > print "bar" > > has a newline in between "foo" and "bar" > > print "foo", > print "bar" > > has a space in between "foo" and "bar" > > How prevent ANYTHING from going in between "foo" and "bar" ?? > > (Without defining a string variable.) sys.stdout.write("foo") sys.stdout.write("bar") Diez From peterdonis at alum.mit.edu Thu Jan 10 19:54:30 2008 From: peterdonis at alum.mit.edu (Peter Donis) Date: Thu, 10 Jan 2008 19:54:30 -0500 Subject: doctest.testfile universal newline -- only when module_relative=True? Message-ID: <200801101954.31330.peterdonis@alum.mit.edu> When running a doctest text file with doctest.testfile, I noticed that universal newline support did not appear to work when module_relative is False. My text file was saved on a Windows machine but I was testing it on a Linux machine, hence the newline mismatch (doctest would throw a SyntaxError for every incorrect newline). I looked at the svn trunk history for doctest.py and found the following patch: http://svn.python.org/view?rev=59082&view=rev This patch corrected for the lack of universal newline support in package.__loader__ .get_data(), but that only applies when module_relative is True. If it is False, the _load_testfile function just calls open(filename) with the default mode of 'r'. It seems to me that, for consistent behavior when module_relative is False, the mode should be 'rU'. Here's a diff against the current svn trunk that corrects this' I've tested it on my machine and it runs correctly: --- doctest_trunk.py 2008-01-10 18:59:15.000000000 -0500 +++ doctest_modified.py 2008-01-10 18:59:15.000000000 -0500 @@ -213,7 +213,8 @@ # get_data() opens files as 'rb', so one must do the equivalent # conversion as universal newlines would do. return file_contents.replace(os.linesep, '\n'), filename - return open(filename).read(), filename + # Here we just need to ensure universal newline mode when opening + return open(filename, 'rU').read(), filename def _indent(s, indent=4): """ Has anyone else noticed this behavior? If it seems worthwhile, I can submit this to the patch tracker. (It would also seem that there should be a corresponding patch to test_doctest to include this case--that should be easy enough for me to generate from what I have already.) Peter Donis From jazle at localhost.com Fri Jan 11 00:56:31 2008 From: jazle at localhost.com (Jaimy Azle) Date: Fri, 11 Jan 2008 12:56:31 +0700 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> Message-ID: "Ed Jensen" wrote: > > Wow, this is pretty misleading. > > Java is, indeed, compiled to bytecode; however, modern JVMs typically > compile the bytecode to native code and then execute the native code. > > CPython strictly interprets bytecode; it does not compile the > bytecode to native code. By the existence of psyco which has equal functionality, i think he is right in term of terminology. Salam, -Jaimy. From alnilam at gmail.com Tue Jan 22 11:07:52 2008 From: alnilam at gmail.com (Alnilam) Date: Tue, 22 Jan 2008 08:07:52 -0800 (PST) Subject: Problem with processing XML References: <13pbudgks88rcf3@corp.supernews.com> Message-ID: <0bca5d25-ec4a-49d9-8264-0446697d4bbb@h11g2000prf.googlegroups.com> On Jan 22, 9:11?am, John Carlyle-Clarke wrote: > By the way, is pyxml a live project or not? ?Should it still be used? > It's odd that if you go tohttp://www.python.org/and click the link > "Using python for..." XML, it leads you tohttp://pyxml.sourceforge.net/topics/ > > If you then follow the download links tohttp://sourceforge.net/project/showfiles.php?group_id=6473you see that > the latest file is 2004, and there are no versions for newer pythons. > It also says "PyXML is no longer maintained". ?Shouldn't the link be > removed from python.org? I was wondering that myself. Any answer yet? From rridge at caffeine.csclub.uwaterloo.ca Wed Jan 23 10:56:58 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 23 Jan 2008 10:56:58 -0500 Subject: subprocess and & (ampersand) References: Message-ID: Tim Golden wrote: > but this doesn't: > > > "c:\Program Files\Mozilla Firefox\firefox.exe" "%*" > > > > import subprocess > > cmd = [ > r"c:\temp\firefox.bat", > "http://local.goodtoread.org/search?word=tim&cached=0" > ] > subprocess.Popen (cmd) > > Ross Ridge wrote: > You need to use double quotes both in the .BAT file and in the string > you pass to subprocess.Popen(). Tim Golden wrote: >... If you simply requote the second element in the cmd list >('"http:/....."') then the internal quotes are escaped by some part of >the mechanism and it still doesn't work. Hmm... I guess things are much more messy than that. CMD doesn't do standard quote processing of it's arguments or .BAT file arguments, and so is incompatible with how subprocess quotes args lists. It looks like you need use a string instead of list with subprocess.Popen and not use quotes in the batch file. So something like: firefox.bat: "c:\Program Files\Mozilla Firefox\firefox.exe" %1 code: subprocess.Popen(r'c:\temp\firefox.bat "http://local.goodtoread.org/search?word=tim&cached=0"') Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From rocco.rossi at gmail.com Mon Jan 7 04:01:28 2008 From: rocco.rossi at gmail.com (rocco.rossi at gmail.com) Date: Mon, 7 Jan 2008 01:01:28 -0800 (PST) Subject: Noob question References: <17e045f1-7891-4afc-a98b-42dffdc45dd4@41g2000hsy.googlegroups.com> Message-ID: <37473f96-8a12-4667-94b3-c264618d6bf2@u10g2000prn.googlegroups.com> On Jan 7, 12:09 am, GHZ wrote: > Had the same issue. What you want is: reload() Thanks :) From rw at smsnet.pl Mon Jan 28 08:36:29 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Mon, 28 Jan 2008 05:36:29 -0800 (PST) Subject: Set ulimit when using subprocess.Popen? References: Message-ID: Jarek Zgoda napisa?(a): > Hi, all, > > anybody has an idea on how to set ulimit (-v in my case, linux) for > process started using subprocess.Popen? What about: from subprocess import call call('ulimit -v 1000 && ulimit -v && ls', shell=True) HTH, Rob From jhouzard at gmail.com Tue Jan 29 11:42:55 2008 From: jhouzard at gmail.com (=?ISO-8859-1?Q?Jean-Fran=E7ois_Houzard?=) Date: Tue, 29 Jan 2008 17:42:55 +0100 Subject: Reflection and aspect programming in Python Message-ID: <5bf046ee0801290842i58a82fa1xac8f8d3a7ef2598d@mail.gmail.com> Hello, I'm a student at UCL Belgium and I have to write a paper about reflection and introspection in Python. It is somewhat difficult to find advanced information about reflection in Python, not only introspection but also the other sides of reflection. I'm using the book: "Programming Python, Thrid Edition" but the chapter only describes briefly some useful functions. The IBM site talks somewhat about the concept of "metaclass" but is there more about reflection than only metaclass programming? I'm also looking for a class diagram of the hierachy of the python classes "metaclass", "class", "object" but didn't find it nor did I find lots of information about that subject. I looked around on the site www.python.org and some others about what could be a killer application using reflection in Python an maybe more information about it. Like how does it use reflection to do the trick. Is there an advanced and completed Aspect Python plugin or are they all experimental? Are there some papers about that part of reflection or more detailed sites that talks about it. It's a wide subject with open questions. I lack a lot of information about it and finding advanced topics on the subject isn't that easy. That's why I ask those questions here, to have some enlightments and maybe some leads to explore. Thanks a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Jan 22 08:20:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 14:20:35 +0100 Subject: isgenerator(...) - anywhere to be found? Message-ID: <5vm8t3F1m1797U1@mid.uni-berlin.de> For a simple greenlet/tasklet/microthreading experiment I found myself in the need to ask the question isgenerator(v) but didn't find any implementation in the usual suspects - builtins or inspect. I was able to help myself out with a simple (out of my head, hope its def isgenerator(v): def _g(): yield return type(v) == type(_g()) But I wonder why there is no such method already available? Diez From MartinRinehart at gmail.com Tue Jan 8 11:45:23 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Tue, 8 Jan 2008 08:45:23 -0800 (PST) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> <1d895d6d-a649-439e-8223-0ae7d3a4eb40@l6g2000prm.googlegroups.com> Message-ID: <4fb7129f-3887-4e3b-a827-3255344047f3@c23g2000hsa.googlegroups.com> That's a great list, grflanagan! Thanks. I looked at each and copied to my disk either as a .txt (cut/paste from the browser) for a page or less or as .html (view source, chop off head and non-guideline stuff, save). This is the list plus PEP 8 minus the software. (No disrespect for the software, just sticking to written standards.) Zope may be a substantial guideline, but it linked to a page of Zope links, all of which were broken. This CSV file is sorted by filesize on my disk. One presumes that a relationship exists between size and extent of coverage. (Warning: Wiki text could be as much as twice the size of non-wiki for the same content.) The third column is empty (spacer between size and URL). A quick look (thorough analysis still required) shows that OLPC and PyPy are, indeed, extensive standards. one-laptop-per-child.html (olpc),74.3,,http://wiki.laptop.org/go/ Python_Style_Guide pypy.html,64.2,,http://codespeak.net/pypy/dist/pypy/doc/coding- guide.html pep-008.html,35.6,,http://www.python.org/dev/peps/pep-0008/ knight.html,33.7,,http://jaynes.colorado.edu/PythonGuidelines.html pep-257.html,23.8,,http://www.python.org/dev/peps/pep-0257/ webware.html,23.4,,http://www.webwareforpython.org/Docs/ StyleGuidelines.html twisted.html,23.3,,http://twistedmatrix.com/trac/browser/trunk/doc/ development/policy/co... voice-code.html,17.9,,http://voicecode.iit.nrc.ca/VoiceCode/uploads/ codingGuidelines.html fsl.html,15.0,,http://www-md.fsl.noaa.gov/eft/developer/ PythonCodingStandards.html wx.html,14.6,,http://www.wxpython.org/codeguidelines.php mnet.html,14.5,,http://mnet.sourceforge.net/coding_standards.html michael-foord.html,14.2,,http://www.voidspace.org.uk/python/weblog/ arch_d7_2006_04_01.shtml#e296 bazaar.html,10.4,,http://doc.bazaar-vcs.org/bzr.dev/en/developer-guide/ HACKING.html#cod... ipython.html,10.2,,http://ipython.scipy.org/moin/Developer_Zone/ Developer_Guidelines barry-warsaw.html,6.2,,http://barry.warsaw.us/software/STYLEGUIDE.txt django.html,5.6,,http://www.djangoproject.com/documentation/ contributing/#coding-style chandler.txt,4.0,,http://chandlerproject.org/Projects/ ChandlerCodingStyleGuidelines pyblosxom.txt,3.8,,http://pyblosxom.sourceforge.net/blog/static/ development#coding freevo.txt,3.4,,http://jaynes.colorado.edu/PythonGuidelines.html sql-object.txt,2.7,,http://www.sqlobject.org/DeveloperGuide.html#style- guide biopython.txt,2.5,,http://biopython.org/wiki/ Contributing#Coding_conventions tracdev.txt,1.8,,http://trac.edgewall.org/wiki/TracDev/CodingStyle docutils,1.8,,http://docutils.sourceforge.net/docs/dev/ policies.html#python-coding-... moinmoin.txt,1.8,,http://moinmoin.wikiwikiweb.de/CodingStyle cherrypy.txt,1.5,,http://www.cherrypy.org/wiki/CodeConventions skeletonz-naming.txt,1.4,,http://orangoo.com/skeletonz/Developer_guide/ Naming_convention/ mercurial.txt,0.9,,http://www.selenic.com/mercurial/wiki/index.cgi/ Basic_Coding_Style skeletonz-coding.txt,0.6,,http://orangoo.com/skeletonz/Developer_guide/ Coding_convention/ software-carpentry.txt,0.1,,http://www.swc.scipy.org/lec/style.html zope.txt,0.0,,http://wiki.zope.org/zope3/CodingStyle From nicola.musatti at gmail.com Fri Jan 4 09:39:22 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Fri, 4 Jan 2008 06:39:22 -0800 (PST) Subject: Who's to blame? References: <92dfc2fc-0677-43c0-b34f-4f240fa40205@e4g2000hsg.googlegroups.com> <255d32d0-43f5-4d34-a074-b87082dc6043@e23g2000prf.googlegroups.com> <2b076973-b132-4666-a163-b80bcbeaedfb@s8g2000prg.googlegroups.com> <8749bb13-4f31-4cfc-8878-cc19bd417275@f10g2000hsf.googlegroups.com> Message-ID: <2f03c850-14fc-40c3-a95b-5711e254f4e1@h11g2000prf.googlegroups.com> On Jan 4, 3:12 pm, kyoso... at gmail.com wrote: [...] > I have sub-classed wx.Dialog to do my own custom modal dialogs as > well. You can use sizers and put whatever widgets you want onto it > that way. Just make sure that when you create the Yes/No buttons, you > give them the wx.ID_YES or wx.ID_NO ids, rather than -1 or wx.ID_ANY. > > yesBtn = wx.Button(parent, wx.ID_YES, 'Yes') > noBtn = wx.Button(parent, wx.ID_NO, 'No') As far as I understand this should be taken care of by the XRC/ wxStdDialogButtonSizer combination. Anyway, I solved my problem by binding the following event handler to both buttons: def OnButton(self, event): if self.IsModal(): self.EndModal(event.GetId()) By the way, my assumption above appears to be supported by the fact that a call to ShowModal() on my dialog does return wx.ID_YES when I press the Yes button. I'm still a bit puzzled, but right now I can't afford to let it bother me too much. Thanks for your help! Cheers, Nicola From peng.kyo at gmail.com Fri Jan 18 00:55:17 2008 From: peng.kyo at gmail.com (J. Peng) Date: Fri, 18 Jan 2008 13:55:17 +0800 Subject: too long float Message-ID: <18c1e5f20801172155k32d2297fn669114a1ce220ed8@mail.gmail.com> hello, why this happened on my python? >>> a=3.9 >>> a 3.8999999999999999 I wanted 3.9 but got 3.89................ How to avoid it? thanks. this is my python version: >>> sys.version '2.3.4 (#1, Feb 6 2006, 10:38:46) \n[GCC 3.4.5 20051201 (Red Hat 3.4.5-2)]' From HerbAsher at googlemail.com Thu Jan 17 04:09:33 2008 From: HerbAsher at googlemail.com (HerbAsher at googlemail.com) Date: Thu, 17 Jan 2008 01:09:33 -0800 (PST) Subject: Some Berkeley DB questions (being maintained? queries?) Message-ID: <0ba30836-8e2d-4061-94ea-ccddb24bc290@s19g2000prg.googlegroups.com> Hi! I have some questions. I'm evaluating berkeley db as a embeddable storage engine for a project I'm working on. My questions: 1. Now that Berkeley DB is part of Oracle, is it still being maintained? Is it free? 2. Are there good python libraries for bdb available, that are being maintained? 3. Is it possible to query a berkeley db database? Just simple queries like: find me all items where key "name" = "John" 4. What are good, stable alternatives? thanks, herb From fetchinson at googlemail.com Sat Jan 12 19:56:09 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 12 Jan 2008 16:56:09 -0800 Subject: __init__ explanation please In-Reply-To: <47895d25$0$30708$4c368faf@roadrunner.com> References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: > I'm new to Python, and OOP. I've read most of Mark Lutz's book and more > online and can write simple modules, but I still don't get when __init__ > needs to be used as opposed to creating a class instance by assignment. For > some strange reason the literature seems to take this for granted. I'd > appreciate any pointers or links that can help clarify this. I'm not sure if I understand your question correctly but maybe this will help: If you want code to be run upon creating an instance of your class you would use __init__. Most common examples include setting attributes on the instance and doing some checks, e.g. class Person: def __init__( self, first, last ): if len( first ) > 50 or len( last ) > 50: raise Exception( 'The names are too long.' ) self.first = first self.last = last And you would use your class like so, p1 = Person( 'John', 'Smith' ) p2 = Person( "Some long fake name that you don't really want to except, I don't know if it's really longer than 50 but let's assume it is", "Smith" ) # This last one would raise an exception so you know that something is not okay HTH, Daniel From tjreedy at udel.edu Wed Jan 9 22:41:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 Jan 2008 22:41:55 -0500 Subject: ISO books of official Python docs References: Message-ID: "Doug Morse" wrote in message news:slrnfoae1t.c2f.morse at ikrg.com... | Hi Fredrik, | | I'm terribly confused. You want me to apologize for recommending that someone | buy your books? To apologize for noting that they are a quality reference | sources for Python? As a past and future technical writer, I can understand Fredrik's reaction. Your recommendation seemed somewhat lukewarm to me ("So, while not exactly what you asked for, the ORA books might be a viable alternative if what you want isn't available" ) and looking back at the original, I do not see 'quality' anywhere. If someone thinks of the docs as low quality, as some do, then labelling others' work as a reproduction would imply the same of the reproduction. There is a HUGH difference between a 'reproduction' and an intended-to-be more literate and readable writing that covers the same material. (I have not seen Fredrik's book, so I cannot comment on how well he succeeded.) Terry Jan Reedy | On Wed, 09 Jan 2008 21:59:34 +0100, Fredrik Lundh | wrote: | > Doug Morse wrote: | > | > > Several of the O'Reilly & Assoc. books -- such as Python in a Nutshell, The | > > Python Standard Library, etc -- are in large part reproductions of the | > > official docs and references. | > | > if you're using "reproduction" to mean "copy", I think you owe both me | > and Alex a big apology. From robert.kern at gmail.com Sat Jan 12 21:11:29 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 12 Jan 2008 20:11:29 -0600 Subject: Is unicode.lower() locale-independent? In-Reply-To: <47894E09.6030104@v.loewis.de> References: <47894E09.6030104@v.loewis.de> Message-ID: Martin v. L?wis wrote: >> Even if towlower() gets used? I've found an explicit statement that the >> conversion it does can be locale-specific: >> >> http://msdn2.microsoft.com/en-us/library/8h19t214.aspx > > Right. However, the build option of Python where that's the case is > deprecated. Excellent. Thank you. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From george.sakkis at gmail.com Mon Jan 21 14:30:07 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 21 Jan 2008 11:30:07 -0800 (PST) Subject: Default attribute values pattern References: Message-ID: <2b7d114d-f29d-49f8-8ef0-6e9f1013958d@k2g2000hse.googlegroups.com> On Jan 19, 6:02 pm, "David Tweet" wrote: > Hello, > > Seems to me that setattrs sort of assumes that you want to have all your > initialization arguments set as attributes of the same name. I would think > you'd sometimes want to be able to process the extra arguments inside of each > __init__, assign them to attributes with different names, etc. > > My approach would be to treat each __init__ as a wrapping function, grabbing > the items it needs out of the keyword dictionary and then calling the next > __init__. Curious to hear other approaches though: > > def Grab(argdict, key, default): > """Like argdict.get(key, default), but also deletes key from argdict.""" > if key in argdict: > retval = argdict["key"] > del(argdict[key]) > else: > retval = default > return retval > > class Base(object): > def __init__(self, x=0, y=None): > print "in Base init" > self.x = x > self.y = y > > class Derived1(Base): > def __init__(self, **kwargs): > print "in Derived1 init" > self.z = Grab(kwargs, "z", None) > super(Derived1, self).__init__(**kwargs) > > class Derived2(Derived1): > def __init__(self, **kwargs): > print "in Derived2 init" > self.a = Grab(kwargs, "a", 0) > self.b = Grab(kwargs, "b", False) > super(Derived2, self).__init__(**kwargs) > print self.__dict__ > > newthing = Derived2(x=234, y="blah", a=55555) The problem with this (apart from being somewhat more verbose and less explicit) is that you have to set existing attributes (like x and y) *after* the call to super __init__ while new attributes (like z, a and b) *before* the call. Mixing it up will either raise a runtime error for passing an unknown argument to the parent, or (worse) set the parent's default instead of the child's. So for the common attribute setting case it involves more error-prone boilerplate code. George From kyosohma at gmail.com Fri Jan 25 08:59:46 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 25 Jan 2008 05:59:46 -0800 (PST) Subject: Ideas for Python Programming References: <9daf42a0-90bf-4881-8c07-3851a2b3f564@c23g2000hsa.googlegroups.com> Message-ID: <146bcf41-28a1-4510-915e-bf764ba66ff3@k2g2000hse.googlegroups.com> On Jan 25, 2:22 am, mistersexy wrote: > I have been programming in python for some time but I have become > short of ideas. A software exhibition is coming up, and I plan to show > python's worth 'cos it is quite underrated in this part of the world. > Could anyone suggest any really good program ideas and information on > how to implement them? I heartily welcome any good ideas. Why not do a search on SourceForge and see what's being programmed in Python? Then you could get ideas and/or join some of those projects. Mike From grante at visi.com Sat Jan 26 00:03:06 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 26 Jan 2008 05:03:06 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <13plfoacnodml55@corp.supernews.com> On 2008-01-26, ajaksu wrote: > On Jan 25, 11:10 pm, o... at thepond.com wrote: >> Once a python py file is compiled into a pyc file, I can disassemble >> it into assembler. Assembler is nothing but codes, which are >> combinations of 1's and 0's. You can't read a pyc file in a hex >> editor, but you can read it in a disassembler. It doesn't make a lot >> of sense to me right now, but if I was trying to trace through it with >> a debugger, the debugger would disassemble it into assembler, not >> python. > > Please, tell me you're kidding... I think we've been trolled. Nobody could be that stubbornly ignorant. -- Grant Edwards grante Yow! This is PLEASANT! at visi.com From tjhnson at gmail.com Mon Jan 21 18:22:12 2008 From: tjhnson at gmail.com (tjhnson at gmail.com) Date: Mon, 21 Jan 2008 15:22:12 -0800 (PST) Subject: Max Long Message-ID: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> How can I figure out the largest long available? I was hoping for something like sys.maxint, but I didn't see it. Also, can someone point me to where I can (concisely) read about size of such types (int, float, long). From over at thepond.com Wed Jan 23 02:04:35 2008 From: over at thepond.com (over at thepond.com) Date: Wed, 23 Jan 2008 07:04:35 GMT Subject: python24 symbol file...pyhon24.pdb Message-ID: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> I've seen a few references on the net to a python24.pdb file. I assume it's a symbol file along the lines of the pdb files issued by microsoft for their products. Maybe I'm wrong. Has anyone seen such an animal? Also, is there source code available for python24 for Windoze? I have seen reference to source code but not in a package for Windows. thanks From jeremy+complangpython at jeremysanders.net Tue Jan 29 17:18:03 2008 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 29 Jan 2008 22:18:03 +0000 Subject: breaking out of outer loops References: Message-ID: noemailplease0001 at gmail.com wrote: > Any elegant way of breaking out of the outer for loop than below, I > seem to have come across something, but it escapes me > > for i in outerLoop: > for j in innerLoop: > if condition: > break > else: > continue > break Perhaps Python needs a "continue N" or a "break N" statement :-) for i in outerLoop: for j in innerLoop: if condition: break 2 Seeing as we can't have a goto :-) Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From thomas.troeger.ext at siemens.com Thu Jan 10 09:01:37 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 10 Jan 2008 15:01:37 +0100 Subject: Embedding python code into text document question. References: Message-ID: Ok I've written a small example program to clarify matters: ================ [SNIP] ================ #!/usr/bin/python import os, sys, time def template(src, dst, sep): """ Copy file from src to dst, executing embedded python code. """ try: # read template file. f=open(src, "rU") data="".join(f.readlines()) f.close() # find embedded python code and execute it. while True: # find embedded embedded python command. offset=data.find(sep) if offset < 0: break offset2=data.find(sep, offset+1) if offset2 < 0: break cmd=data[offset+len(sep):offset2] # execute command. try: ret="" exec(compile(cmd, '', 'exec')) except: print "error compiling code `%s'." % cmd # substitute command with return value. data=data[:offset]+str(ret)+\ data[offset2+len(sep):] # write translated input. f=open(dst, "w") f.write(data) f.close() except: print "error processing template file `%s'." % src # ------------------------------ main ------------------------------- if len(sys.argv) > 2: template(sys.argv[1], sys.argv[2], '$$') ================ [SNIP] ================ This is the example input that works: ================ [SNIP] ================ process id: $$ret=os.getpid()$$ current date: $$ret=time.ctime()$$ superuser: $$ if os.geteuid(): ret="No" else: ret="Yes"$$ ================ [SNIP] ================ Now the `ret= ...' mechanism is not nice, I'd prefer to have a return statement instead. From wanzathe at gmail.com Fri Jan 4 09:54:43 2008 From: wanzathe at gmail.com (wanzathe) Date: Fri, 4 Jan 2008 06:54:43 -0800 (PST) Subject: how to build a dict including a large number of data References: Message-ID: <92b6eaea-715f-4a4d-8603-4fa1aab8f3e7@v4g2000hsf.googlegroups.com> On 1?4?, ??10?17?, Fredrik Lundh wrote: > wanzathe wrote: > > i have a binary file named test.dat including 9600000 records. > > the record format is int a + int b + int c + int d > > i want to build a dict like this: key=int a,int b values=int c,int d > > i choose using bsddb and it takes about 140 seconds to build the dict. > > you're not building a dict, you're populating a persistent database. > storing ~70000 records per second isn't that bad, really... > > > what can i do if i want to make my program run faster? > > or is there another way i can choose? > > why not just use a real Python dictionary, and the marshal module for > serialization? > > hi,Fredrik Lundn you are right, i'm populating a persistent database. i plan to use a real Python dictionary and use cPickle for serialization at first, but it did not work because the number of records is too large. Thanks From shriphanip at gmail.com Wed Jan 2 06:23:12 2008 From: shriphanip at gmail.com (Shriphani) Date: Wed, 2 Jan 2008 03:23:12 -0800 (PST) Subject: pdf library. References: <133097f4-de83-4e13-93f1-1404213333a4@l6g2000prm.googlegroups.com> <3b429178-8c07-4dcb-8034-1912c0597830@d21g2000prf.googlegroups.com> <5tuqhgF187o9eU2@mid.uni-berlin.de> Message-ID: <1ebe3b15-8d14-4056-a112-f7c57063bf79@l6g2000prm.googlegroups.com> On Jan 1, 5:38 pm, Marc 'BlackJack' Rintsch wrote: > On Tue, 01 Jan 2008 04:21:29 -0800,Shriphaniwrote: > > On Jan 1, 4:28 pm, Piet van Oostrum wrote: > >> >>>>>Shriphani (S) wrote: > >> >S> I tried pyPdf for this and decided to get the pagelinks. The trouble > >> >S> is that I don't know how to determine whether a particular page is the > >> >S> first page of a chapter. Can someone tell me how to do this ? > > >> AFAIK PDF doesn't have the concept of "Chapter". If the document has an > >> outline, you could try to use the first level of that hierarchy as the > >> chapter starting points. But you don't have a guarantee that they really > >> are chapters. > > > How would a pdf to html conversion work ? I've seen Google's search > > engine do it loads of times. Just that running a 500odd page ebook > > through one of those scripts might not be such a good idea. > > Heuristics? Neither PDF nor HTML know "chapters". So it might be > guesswork or just in your head. > > Ciao, > Marc 'BlackJack' Rintsch I could parse the html and check for the words "unit" or "chapter" at the beginning of a page. I am using pdftohtml on Debian and it seems to be generating the html versions of pdfs quite fast. I am yet to run a 500 page pdf through it though. Regards, Shriphani From http Mon Jan 21 17:36:24 2008 From: http (Paul Rubin) Date: 21 Jan 2008 14:36:24 -0800 Subject: Prioritization function needed (recursive help!) References: <51180fda-304d-4f7e-812a-32032585675b@e23g2000prf.googlegroups.com> Message-ID: <7xbq7e4xhz.fsf@ruckus.brouhaha.com> rh0dium writes: > I am really struggling on simply how to organize the data and write > the corresponding function - I tried classes but I don't know if > that's the best approach. See my other post on this. We just had a discussion thread about this. Is it a homework problem? Anyway, look up "topological sorting" in a CS textbook or on Wikipedia. From dbaston at gmail.com Fri Jan 25 17:33:02 2008 From: dbaston at gmail.com (dbaston at gmail.com) Date: Fri, 25 Jan 2008 14:33:02 -0800 (PST) Subject: Puzzled by behaviour of class with empty constructor Message-ID: <99b8e2ac-1c72-430a-9172-a809e169f96a@i12g2000prf.googlegroups.com> Hello, I have a class called 'Axis' that I use as a base class for several types of axes that can be created by a grid generation program that I have written: equally-spaced grids, logarithmic grids, etc. In any case, if I use this base class by itself, I see some puzzling behaviour: ############# class Axis: ends = [] N = None def __init__(self): pass x = Axis() y = Axis() z = Axis() x.ends.append((0,2)) print x.ends,y.ends,z.ends ############# Running the following code outputs: >>> [(0, 2)] [(0, 2)] [(0, 2)] Can anyone explain this? From ryan at ryankaskel.com Wed Jan 23 15:23:53 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 12:23:53 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> <12d19814-b7b9-44b0-aee3-299befac7279@i12g2000prf.googlegroups.com> <66446d1e-189c-4c24-bd7a-83cbd66deb60@i12g2000prf.googlegroups.com> Message-ID: On Jan 23, 3:02 pm, John Machin wrote: > On Jan 24, 6:57 am, ryan k wrote: > > > So yea i will just have to count dashes. > > Read my lips: *you* counting dashes is dumb. Writing your code so that > *code* is counting dashes each time it opens the file is smart. Okay it's almost working ... new parser function: def _load_table(self): counter = 0 for line in self.table_fd: # Skip the second line if counter == 0: # This line contains the columns, parse it column_list = line.split() elif counter == 1: # These are the dashes line_l = line.split() column_width = [len(i) for i in line_l] print column_width else: # This is a row, parse it marker = 0 row_vals = [] for col in column_width: start = sum(column_width[:marker]) finish = sum(column_width[:marker+1]) print line[start:finish].strip() row_vals.append(line[start:finish].strip()) marker += 1 self.rows.append(Row(column_list, row_vals)) counter += 1 Something obvious you can see wrong with my start finish code? ['rimon', 'rimon', 'Barr', 'Rimon', '22 Greenside Cres., Thornhill, ON L3T 6W9', '2', '', 'm', '102', '100 -', '22.13 1234567890', 'barr at cs.cornell.edu', ''] ['UNAME', 'PASSWD', 'LNAME', 'FNAME', 'ADDR', 'ZONE', 'SEX', 'AGE', 'LIMIT', 'BALANCE', 'CREDITCARD', 'EMAIL', 'ACTIVE'] From dg.google.groups at thesamovar.net Sun Jan 27 13:47:13 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Sun, 27 Jan 2008 10:47:13 -0800 (PST) Subject: Python self-evaluating strings References: Message-ID: It's a bit cheap, but how about >>> from inspect import getsource >>> print getsource(getsource) or similarly def f(g): import inspect return inspect.getsource(g) print f(f) Dan From lewisnorton90 at googlemail.com Thu Jan 17 06:13:34 2008 From: lewisnorton90 at googlemail.com (Ionis) Date: Thu, 17 Jan 2008 03:13:34 -0800 (PST) Subject: Opening/Running files through python Message-ID: <239efd0e-5ac8-485c-b316-aa52b0a2c316@i72g2000hsd.googlegroups.com> Hey guys, hope you can help me here. I am running in windows and I am trying to open a file via python. I want the file (a text file) to open up in the users default text editor. I'm not wanting to read a file, I just want to open it. Is there a way? Thanks in advance. From michele.simionato at gmail.com Mon Jan 14 07:53:49 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 14 Jan 2008 04:53:49 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> Message-ID: <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> On Jan 14, 1:41 pm, Richard Szopa wrote: > However, there's one piece that doesn't completely fit to the puzzle: > why does getattr work? The help says: > > getattr(...) > getattr(object, name[, default]) -> value > > Get a named attribute from an object; getattr(x, 'y') is > equivalent to x.y. > When a default argument is given, it is returned when the > attribute doesn't > exist; without it, an exception is raised in that case. > > Does it work on the basis that "getattr(x, 'y') is equivalent to x.y"? > What is then a "named attribute for an object" in Python? It seems not > to be equivalent to the value of the item whose name is 'y' in the > object's class __dict__... > > Cheers, > > -- Richard I really need to publish this one day or another, since these questions about super keeps coming out: http://www.phyast.pitt.edu/~micheles/python/super.html From deets at nospam.web.de Fri Jan 18 03:15:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 18 Jan 2008 09:15:22 +0100 Subject: Unique thread ID In-Reply-To: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> References: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> Message-ID: <5vb5h0F1l2itoU1@mid.uni-berlin.de> Benjamin schrieb: > Is there a way to obtain a unique ID for the current thread? I have an > object that I need to store local thread data in, and I don't want to > use threading.local because each thread might have multiple instances > of my object. You can use the thread itself, it's usable as key (that's what threadlocals use for their implementation anyway) But I don't understand your problem - all thread-local implementations I know of (is there a standard?) can be instantiated in each object and then offer a get/set method (keyed or not) - but without interfering with outher instances of themselves of course. Diez From stefaan.himpe at gmail.com Fri Jan 4 06:31:55 2008 From: stefaan.himpe at gmail.com (stefaan) Date: Fri, 4 Jan 2008 03:31:55 -0800 (PST) Subject: storing setup.py (for py2exe) in other directory than main script directory Message-ID: <9cf3764d-fa07-499a-8c94-27b4fdeb98e9@j20g2000hsi.googlegroups.com> Hello list, I have the following problem after upgrading to python 2.5 and py2exe 0.6.6 It seems that py2exe is using the location of the setup.py file as its search path, instead of the current working folder. (This used to be different with an older version of py2exe) Can I tell py2exe somehow to use the current working directory as search path instead of the location of the setup.py file ? Also: is this a feature or a bug ? The reason I am asking is because I'd like to keep the build scripts in a "win32specific" subfolder of my code folder, and then run the following command in the code folder: python win32specific\setup.py py2exe Alternative suggestions also welcome! Best regards, Stefaan. From mtobis at gmail.com Fri Jan 11 20:36:10 2008 From: mtobis at gmail.com (Michael Tobis) Date: Fri, 11 Jan 2008 17:36:10 -0800 (PST) Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> <13og1lgcespv6c2@corp.supernews.com> Message-ID: On Jan 11, 6:15 pm, Steven D'Aprano wrote: > Your users are *scientists*, and you don't trust their intellectual > ability to learn a programming language as simple as Python? > > Instead of spending time and effort writing, debugging and maintaining > such a fragile approach, why not invest in a couple of introductory books > on Python programming and require your scientists to go through the first > few chapters? Or write out a one-page "cheat sheet" showing them simple > examples. Or, and probably most effectively, make sure all your classes > have doc strings with lots of examples, and teach them how to use help(). > > Some people problems are best dealt with by a technical solution, and > some are not. > > -- > Steven I am currently talking very similar trash on my blog, See http://initforthegold.blogspot.com/2008/01/staying-geeky.html and http://initforthegold.blogspot.com/2007/12/why-is-climate-modeling-stuck.html You seem to think that learning the simple language is equivalent to grasping the expressive power that the language provides. Yes, users are scientists. Therefore they do not have the time or interest to gain the depth of skill to identify the right abstractions to do their work. There are many abstractions that could be useful in science that are currently provided with awkward libraries or messy one-off codes. The idea that a scientist should be expected to be able to write correct and useful Python is reasonable. I and the OP are relying on it. The idea that a scientist should be expected to identify and build clever and elegant abstractions is not. If you think every scientist can be a really good programmer you underestimate at least one of what good scientists do or what good programmers do or what existing high performance scientific codes are called upon to do. mt From gbacon at hiwaay.net Tue Jan 29 12:12:09 2008 From: gbacon at hiwaay.net (Greg Bacon) Date: Tue, 29 Jan 2008 17:12:09 -0000 Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> <13ps95mg8am3l37@corp.supernews.com> Message-ID: <13punj94ev46910@corp.supernews.com> In article , Dr.Ruud wrote: : I negated the test, to make the regex simpler: [...] Yes, your approach is simpler. I assumed from the "need it all in one pattern" constraint that the OP is feeding the regular expression to some other program that is looking for matches. I dunno. Maybe it was the familiar compulsion with Perl to attempt to cram everything into a single pattern. Greg -- What light is to the eyes -- what air is to the lungs -- what love is to the heart, liberty is to the soul of man. -- Robert Green Ingersoll From mal at egenix.com Wed Jan 23 03:54:14 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 23 Jan 2008 09:54:14 +0100 Subject: HTML parsing confusion In-Reply-To: References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> <50269e4a-af44-4d73-b6cb-c42af6b5164d@e10g2000prf.googlegroups.com> <5vmkiiF1nadr7U1@mid.uni-berlin.de> Message-ID: <479700B6.1060505@egenix.com> On 2008-01-23 01:29, Gabriel Genellina wrote: > En Tue, 22 Jan 2008 19:20:32 -0200, Alnilam escribi?: > >> On Jan 22, 11:39 am, "Diez B. Roggisch" wrote: >>> Alnilam wrote: >>>> On Jan 22, 8:44 am, Alnilam wrote: >>>>>> Pardon me, but the standard issue Python 2.n (for n in range(5, 2, >>>>>> -1)) doesn't have an xml.dom.ext ... you must have the >>> mega-monstrous >>>>>> 200-modules PyXML package installed. And you don't want the 75Kb >>>>>> BeautifulSoup? >>>> Ugh. Found it. Sorry about that, but I still don't understand why >>>> there isn't a simple way to do this without using PyXML, BeautifulSoup >>>> or libxml2dom. What's the point in having sgmllib, htmllib, >>>> HTMLParser, and formatter all built in if I have to use use someone >>>> else's modules to write a couple of lines of code that achieve the >>>> simple thing I want. I get the feeling that this would be easier if I >>>> just broke down and wrote a couple of regular expressions, but it >>>> hardly seems a 'pythonic' way of going about things. >>> This is simply a gross misunderstanding of what BeautifulSoup or lxml >>> accomplish. Dealing with mal-formatted HTML whilst trying to make _some_ >>> sense is by no means trivial. And just because you can come up with a >>> few >>> lines of code using rexes that work for your current use-case doesn't >>> mean >>> that they serve as general html-fixing-routine. Or do you think the >>> rather >>> long history and 75Kb of code for BS are because it's creator wasn't >>> aware >>> of rexes? >> I am, by no means, trying to trivialize the work that goes into >> creating the numerous modules out there. However as a relatively >> novice programmer trying to figure out something, the fact that these >> modules are pushed on people with such zealous devotion that you take >> offense at my desire to not use them gives me a bit of pause. I use >> non-included modules for tasks that require them, when the capability >> to do something clearly can't be done easily another way (eg. >> MySQLdb). I am sure that there will be plenty of times where I will >> use BeautifulSoup. In this instance, however, I was trying to solve a >> specific problem which I attempted to lay out clearly from the >> outset. >> >> I was asking this community if there was a simple way to use only the >> tools included with Python to parse a bit of html. There are lots of ways doing HTML parsing in Python. A common one is e.g. using mxTidy to convert the HTML into valid XHTML and then use ElementTree to parse the data. http://www.egenix.com/files/python/mxTidy.html http://docs.python.org/lib/module-xml.etree.ElementTree.html For simple tasks you can also use the HTMLParser that's part of the Python std lib. http://docs.python.org/lib/module-HTMLParser.html Which tools to use is really dependent on what you are trying to solve. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jan 23 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 usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Jan 20 18:54:58 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 21 Jan 2008 00:54:58 +0100 Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> <478e1e3e$0$18054$426a74cc@news.free.fr> <34aa1a1f-2034-471d-91ee-2a758dab555b@f47g2000hsd.googlegroups.com> Message-ID: <5vi5aiF1m1n0oU1@mid.individual.net> (messed up references?) Lie wrote: > Please again, stop taking letters to the words Please don't mix up followups. Regards, Bj?rn -- BOFH excuse #11: magnetic interference from money/credit cards From gherron at islandtraining.com Wed Jan 23 11:36:40 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 23 Jan 2008 08:36:40 -0800 Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? In-Reply-To: References: Message-ID: <47976D18.8040503@islandtraining.com> Boris Borcic wrote: > I am surprised nobody pointed out explicitely that > > True==1 and False==0 > Several of us did indeed point this out by saying that bool's are a subclass of ints. > so that for instance > > 5*(True+True)==10 > > and even (but implementation-dependent) : > > 5*(True+True) is 10 > > BB > > From lists at cheimes.de Thu Jan 17 03:14:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 17 Jan 2008 09:14:17 +0100 Subject: Extending the readline module? In-Reply-To: References: Message-ID: Casey Rodarmor wrote: > What is the best way to go about doing this? You need some basic knowledge about C, the readline headers, Python sources and a compiler. Are you interested to contribute the extended code to the Python code base? We are always looking for new developers and additional features. Please join the Python developer list and tell us about your idea. Christian From pataphor at gmail.com Thu Jan 24 17:17:54 2008 From: pataphor at gmail.com (pataphor) Date: Thu, 24 Jan 2008 23:17:54 +0100 Subject: sudoku solver in Python ... References: <43b2a56b-c8eb-4851-a9f6-10aa7e32e3ce@i29g2000prf.googlegroups.com> <1r589888wvzss$.17bg43io6of00.dlg@40tude.net> Message-ID: <20080124231754.2706d426@hyperspace> On Thu, 24 Jan 2008 21:09:42 +0100 Thomas Thiel wrote: > Neither fast nor user friendly, but very concise: This is a bit faster: options = set([str(i) for i in range(1, 10)]) def allow(puzzle,i): exclude = set(x if i//9 == j//9 or i%9 == j%9 or i//27 == j//27 and (i%9)//3 == (j%9)//3 else '0' for j,x in enumerate(puzzle)) return options-exclude def solve(puzzle): zeros = [i for i,x in enumerate(puzzle) if x == '0'] if not zeros: print puzzle else: i,R = min(((j,allow(puzzle,j)) for j in zeros), key=lambda x: len(x[1])) for option in R: solve(puzzle[:i] + option + puzzle[i+1:]) P. From george.sakkis at gmail.com Fri Jan 11 10:18:15 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 07:18:15 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> Message-ID: On Jan 11, 9:41 am, Hrvoje Niksic wrote: > Bruno Desthuilliers > writes: > > > fact 1: CPython compiles source code to byte-code. > > fact 2: CPython executes this byte-code. > > fact 3: Sun's JDK compiles source code to byte-code. > > fact 4: Sun's JDK executes this byte-code. > > > Care to prove me wrong on any of these points ? Don't bother: you > > can't. > > Fact 4 is misleading because it is only one option available to Sun's > JDK. Sun's JDK is also capable of transforming the byte-code to > native code and letting the processor execute that instead of the > original byte code, and that is where the most significant speed > increase comes from. Most importantly, it does so automatically, by > default, with no programmer intervention or configuration, and with > 100% compatibility, so it doesn't compare well to Python accelerators > like psyco. Plus, IIRC Java's JIT is not limited to optimizing special cases, while psyco helps primarily with number-crunching code (admittedly an important special case) and can have zero or even (small) negative effect on arbitrary Python programs. George From tarun.kap at gmail.com Wed Jan 16 10:05:28 2008 From: tarun.kap at gmail.com (Tarun Kapoor) Date: Wed, 16 Jan 2008 07:05:28 -0800 (PST) Subject: Paramiko/SSH blues.... Message-ID: I am using paramiko to do an SFTP file transfer... I was able to connect to the remote server using an SFTP client I have just to make sure that username and password are working.. But when i try to connect using this script it fails .... **hostname, username and password are declared. # now, connect and use paramiko Transport to negotiate SSH2 across the connection sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) t = paramiko.Transport(sock) event = threading.Event() t.start_client(event) event.wait(15) if not t.is_active(): print 'SSH negotiation failed.' sys.exit(1) else: print "SSH negotiation sucessful" event.clear() t.auth_password(username=username, password=password,event=event) if not t.is_authenticated(): print "not authenticated" output: SSH negotiation successful not authenticated From deets at nospam.web.de Mon Jan 14 08:53:36 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 14 Jan 2008 14:53:36 +0100 Subject: Threaded server References: <7decdf29-aab4-4fc6-93d8-7b2565e23f78@m34g2000hsf.googlegroups.com> Message-ID: <5v17r0F1jvjc2U1@mid.uni-berlin.de> Giampaolo Rodola' wrote: > On 14 Gen, 12:30, Nick Craig-Wood wrote: >> Giampaolo Rodola' wrote: >> > I'm trying to run an asynchronous FTP server I wrote into a thread for >> > being able to run a test suite against it. >> > The code below is the threaded FTP server code I'm using: >> >> > class FTPd(threading.Thread): >> >> > def __init__(self): >> > self.active = False >> > threading.Thread.__init__(self) >> >> > def start(self, flag=None): >> > assert not self.active >> > self.flag = flag >> > threading.Thread.start(self) >> >> > def run(self): >> > assert not self.active >> > ftpd = ftpserver.FTPServer(address, ftp_handler) >> > if self.flag: >> > self.flag.set() >> > self.active = True >> > while self.active: >> > ftpd.server_forever(timeout=1, count=1) >> > ftpd.close() >> >> > def stop(self): >> > assert self.active >> > self.active = False >> >> > flag = threading.Event() >> > ftpd = FTPd() >> > ftpd.start(flag) >> > flag.wait() ?# wait for it to start >> > unittest.main() # run the test suite >> > ftpd.stop() >> >> > Sometimes I get a strange error when all the tests have finished, the >> > server is stopped and Python is exiting: >> >> > Ran 50 tests in 1.515s >> >> > OK >> > Exception exceptions.TypeError: "'NoneType' object is not callable" in >> > > > thod FTPHandler.__del__ of > > 127.0.0.1:2 >> > 249 at 0xa4b080>> ignored >> > Exception exceptions.TypeError: "'NoneType' object is not callable" in >> > > > thod FTPServer.__del__ of > > 127.0.0.1:543 >> > 21 at 0x9e1a30>> ignored >> >> > I sincerely don't know why that happens but it's likely because I'm >> > not using threads properly. >> > My concern is that this could be caused by a sort of race condition >> > (e.g. Python tries to exit when ftpd.close call is not yet >> > completed). >> >> It looks like when python is shutting down, it has removed an object >> the ftphandler code relies on. >> >> I see you attempt to kill the ftp server with ftpd.stop(). ?That is >> good, but you don't wait for the thread to finish (it might take up to >> a second in ftpd.server_forever if I understand correctly). >> >> I expect if you put a self.join() at the end of the stop() method the >> problem will go away. >> >> -- >> Nick Craig-Wood --http://www.craig-wood.com/nick- >> Nascondi testo tra virgolette - >> >> - Mostra testo tra virgolette - > > Tried it but the problem remains. > The strange thing is that it sometimes happens, sometimes doesn't. AFAIK you can safely ignore this error. It essentially stems from non-determinism when shutting down threads. Diez From JO3chiang at gmail.com Mon Jan 7 22:15:36 2008 From: JO3chiang at gmail.com (jo3c) Date: Mon, 7 Jan 2008 19:15:36 -0800 (PST) Subject: use fileinput to read a specific line Message-ID: hi everybody im a newbie in python i need to read line 4 from a header file using linecache will crash my computer due to memory loading, because i am working on 2000 files each is 8mb fileinput don't load the file into memory first how do i use fileinput module to read a specific line from a file? for line in fileinput.Fileinput('sample.txt') ???? From aahz at pythoncraft.com Wed Jan 2 23:32:43 2008 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2008 20:32:43 -0800 Subject: cloud computing (and python)? References: <69337707-ff18-4b39-af0a-78cf0a14b667@1g2000hsl.googlegroups.com> <4715e05f-456b-4274-9718-b6c009af7698@1g2000hsl.googlegroups.com> Message-ID: In article , Terry Reedy wrote: > >2. yes, cost. University mainframes cost $s/minute. I remember >blowing about $200 due to a misplaced comma or something in a >statistical analysis setup. So it was cost-effective (and rather >liberating) to spend $10000 on a desktop Unix system for both >statistics and text work. Same here, only it was not remembering that the filesystem disallowed names starting with digits. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From mark.e.tolonen at mailinator.com Wed Jan 30 22:43:05 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Wed, 30 Jan 2008 19:43:05 -0800 Subject: small problem with re.sub References: Message-ID: "Astan Chee" wrote in message news:mailman.78.1201748496.9267.python-list at python.org... > Hi, > I have a html text stored as a string. Now I want to go through this > string and find all 6 digit numbers and make links from them. > Im using re.sub and for some reason its not picking up the previously > matched condition. Am I doing something wrong? This is what my code looks > like: > htmlStr = re.sub('(?P\d{6})',' href=\"http://linky.com/(?P=id).html\">(?P=id)',htmlStr) > It seems that it replaces it alright, but it replaces it literally. Am I > not escaping certain characters? > Thanks again for the help. > Cheers > > Animal Logic > http://www.animallogic.com > > Please think of the environment before printing this email. > > This email and any attachments may be confidential and/or privileged. If > you are not the intended recipient of this email, you must not disclose or > use the information contained in it. Please notify the sender immediately > and delete this document if you have received it in error. We do not > guarantee this email is error or virus free. > > See the help for re.sub: "Backreferences, such as "\6", are replaced with the substring matched by group 6 in the pattern." This should work: htmlStr = re.sub('(?P\d{6})','\\1',htmlStr) --Mark From cwitts at gmail.com Tue Jan 8 07:04:01 2008 From: cwitts at gmail.com (Chris) Date: Tue, 8 Jan 2008 04:04:01 -0800 (PST) Subject: Open a List of Files References: Message-ID: <0cc061f5-fa3e-48ca-aff3-36e09de4e894@h11g2000prf.googlegroups.com> On Jan 8, 1:03 pm, Fredrik Lundh wrote: > BJ Swope wrote: > > given a list such as > > > ['messages', 'recipients', 'viruses'] > > > how would I iterate over the list and use the values as variables and > > open the variable names a files? > > > I tried > > > for outfile in ['messages', 'recipients', 'viruses']: > > filename = os.path.join(Host_Path, outfile) > > outfile = open(filename, 'w') > > > But it's not working. > > the code looks ok. please define "not working". > > Bad coding style in that one. Do you have Write permissions to that 'Host_path' ? import os, sys FILELIST = ['messages', 'recipients', 'viruses'] HOST_PATH = os.getcwd() # Or whatever path you are using if not os.access(HOST_PATH, os.W_OK): sys.exit('Unable to write to path specified.') for file in FILELIST: output_file = open(os.path.join(HOST_PATH, file), 'wb') do_something_with_file() A better definition of not working would be appreciated, Tracebacks if you have. From martin at v.loewis.de Wed Jan 16 23:56:59 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 Jan 2008 05:56:59 +0100 Subject: -fno-strict-aliasing turned off when cross compiling In-Reply-To: <66c2d5b4-c84f-47d9-aa4a-1cca3ae594b2@q39g2000hsf.googlegroups.com> References: <66c2d5b4-c84f-47d9-aa4a-1cca3ae594b2@q39g2000hsf.googlegroups.com> Message-ID: <478ee01b$0$4589$9b622d9e@news.freenet.de> > Does anyone have an idea why -fno-strict-aliasing is turned off when > cross compiling? Because detection of -fno-strict-aliasing is made through running the compiler output (AC_TRY_RUN, see configure.in instead). For cross-compilation, running the program isn't actually possible, so a default must be specified. Since we can't know whether the cross-compiler accepts -fno-strict-aliasing, we leave it out. Regards, Martin From python.list at tim.thechases.com Mon Jan 28 12:39:18 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 28 Jan 2008 11:39:18 -0600 Subject: referer url In-Reply-To: References: <0e7fb40e-809c-4979-bbb8-0cd9a7e816c2@t1g2000pra.googlegroups.com> Message-ID: <479E1346.90507@tim.thechases.com> > 1) CGI so i'm doing it right. that's helpful to know > 2) this is impossible as i'm doing the exact same thing with another > language and it utterly works. Just making sure...same browser/setup/configuration, different language? > 3) the same as above kinda figured...most servers give you the HTTP_REFERER, so you' have to > 4) no.. > > this gets nerve breaking! Well, you can always dump the contents of os.environ into your output to see if you can find why. from cgi import escape out.write('
'.join([ '%s:%s' % (escape(k), escape(v)) for k,v in os.environ.iteritems() ]) -tkc From hkimball at eti-web.com Mon Jan 7 09:51:51 2008 From: hkimball at eti-web.com (hkimball at eti-web.com) Date: Mon, 7 Jan 2008 06:51:51 -0800 (PST) Subject: ctypes Message-ID: <90434049-2860-4b6f-aece-be6f896e5ece@s19g2000prg.googlegroups.com> I am trying to call a funtinon in a third party dll that spawns another exe and I am using ctypes. Python does not complain at all but the other process does not get spawned. It appears that I am gaining access to the functions but with no results. Any ideas? Thanks in advance. >>> from ctypes import * >>> cdecl = cdll.LoadLibrary("c:\projects\python\geinterface.dll") >>> cdecl._GE_Connect <_FuncPtr object at 0x00B7E378> >>> cdecl._GE_Connect() 0 >>> cdecl._GE_IsConnected() 0 From mik3l3374 at gmail.com Mon Jan 7 07:43:55 2008 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: Mon, 7 Jan 2008 04:43:55 -0800 (PST) Subject: Delete lines containing a specific word References: Message-ID: <3bfab8d6-bcb6-46c3-8fd2-536a502d343d@41g2000hsy.googlegroups.com> On Jan 7, 1:21 am, Francesco Pietra wrote: > Please, how to adapt the following script (to delete blank lines) to delete > lines containing a specific word, or words? > > f=open("output.pdb", "r") > for line in f: > line=line.rstrip() > if line: > print line > f.close() > > If python in Linux accepts lines beginning with # as comment lines, please also > a script to comment lines containing a specific word, or words, and back, to > remove #. > > Thanks > francesco pietra > > ____________________________________________________________________________________ > Looking for last minute shopping deals? > Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping for line in open("file"): if not "word" in line: print line on the command, use the ">" operator to redirect to a file From grahn+nntp at snipabacken.dyndns.org Sun Jan 20 09:35:26 2008 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 20 Jan 2008 14:35:26 GMT Subject: writing Python in Emacs References: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> Message-ID: ["Followup-To:" header set to comp.lang.python.] On Sat, 19 Jan 2008 17:51:50 +0100, Terry Jones wrote: >>>>>> "Richard" == Richard Szopa writes: > >Richard> I am a devoted Emacs user and I write a lot in Python. > > Me too. > >Richard> I need the following features: > >Richard> 1) Tab completion, ideally Slime like. That is, when there's not >Richard> enough letters to unambiguously complete a symbol, I want it to >Richard> show a buffer (w/o taking the focus) w/ the possible >Richard> completions. In an ideal world, it would be able to complete >Richard> fo.ba to foo.bar. I imagine this would require quite tight >Richard> Emacs-Python integration. > > I know this is not what you want, but I use hippie expand (M-/) to cycle > through possible completions. It's not Python aware, but it is of some use. Also known as dabbrev-expand, and tied to Ctrl-TAB. I like it *a lot*, and I like it even more because it *isn't* Python aware. I can use the same function no matter what I am typing, often with files noone would dream of writing a mode for. ... >Richard> 4) (optional) I would like to see the definition of a function >Richard> function or class by hitting M-. on its name. (I understand that >Richard> this may be impossible for methods, as Emacs would have to >Richard> automagically infer the type of the object). > > This is just an emacs tag file need. Have you googled for something like > emacs tags python? Tags works fine, or at least as well as can be expected. I use the 'etags' which comes with 'ctags', apparently. > If you have the time, please summarize your findings. The emacs/python > world has always seemed quite amorphous to me too. I don't know; python-mode colorizes well and it knows how to help me keep the indentation sane. The Eclipse users I have seen seem to have more problems than I have, for example. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From michele.simionato at gmail.com Tue Jan 1 02:59:20 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 31 Dec 2007 23:59:20 -0800 (PST) Subject: using super References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> Message-ID: <58c1aa27-98e4-4129-852c-f9a8477605db@i7g2000prf.googlegroups.com> On Jan 1, 7:56 am, iu2 wrote: > no one has to remember to call the parent's get_name method. It's done > automatically. > > (A PEP maybe? I sense you don't really like it.. ;-) > What do you think? Good? Too implicit? > > iu2 No PEP, this would never pass. There would be no way to stop a method from calling its parent: you would lose control of your classes, so I think this is a bad idea. Having said so, it is easy to implement what you want with a metaclass: def callParent(*methodnames): class Meta(type): def __init__(cls, name, bases, dic): for methodname in methodnames: if methodname in dic: def new_meth(self, method=methodname): parent = getattr(super(cls, self), method, None) if parent: parent() child = dic.get(method) if child: child(self) setattr(cls, methodname, new_meth) return Meta class B(object): __metaclass__ = callParent('get_name') def get_name(self): print "This is B.get_name" class C(B): def get_name(self): print "This is C.get_name" C().get_name() Now every subclass of B defining a get_name method will automagically call its parent method. Michele Simionato From http Tue Jan 15 13:18:09 2008 From: http (Paul Rubin) Date: 15 Jan 2008 10:18:09 -0800 Subject: Benchmark [was Re: common problem - elegant solution sought] References: <5v3gg1F1kkla5U1@mid.dfncis.de> <478ccc9e$0$29264$ba620e4c@news.skynet.be> Message-ID: <7xbq7ngdge.fsf@ruckus.brouhaha.com> Helmut Jarausch writes: > def del_by_key(L,key) : > for pos, (k,d) in enumerate(L): > if k == key : > del L[pos] > break This looks very dangerous, mutating L while iterating over it. From thegooddale at gmail.com Mon Jan 28 16:28:12 2008 From: thegooddale at gmail.com (Yansky) Date: Mon, 28 Jan 2008 13:28:12 -0800 (PST) Subject: Problems installing Python on server Message-ID: I asked my hosting company if they would upgrade Python on my server to the latest version. They responded with: "Sorry no. We tend to stick with what comes packaged with the unix distribution to ease maintenance issues. There is nothing stopping you from running your own version of python from within your own account. Download the source and compile it and install it into your own space. Adjust the fist line of your python scripts to reflect the location of YOUR python binary: #! /home/youraccount/yourlibs/python and you should be all set." The build instructions for Python are: To start building right away (on UNIX): type "./configure" in the current directory and when it finishes, type "make". This creates an executable "./python"; to install in usr/local, first do "su root" and then "make install". The problem is, I don't have root access to the server so I can't do the "make install". I have ubuntu on my computer, but from what I understand I can't compile it on that and upload it because the server runs Red Had and the ./configure would have made it incompatible right? So how can I build Python without root access? From python.list at tim.thechases.com Thu Jan 10 13:39:16 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 10 Jan 2008 12:39:16 -0600 Subject: What is "lambda x=x : ... " ? In-Reply-To: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> Message-ID: <47866654.4090407@tim.thechases.com> > What does "y=y" and "c=c" mean in the lambda function? the same thing it does in a function definition: def myfunct(a, b=42, y=3.141): pass > ################# > x = 3 > y = lambda x=x : x+10 > > print y(2) > ################## > > It prints 12, so it doesn't bind the variable in the outer scope. You're mostly correct, as it does pull it out of the local context. Try x = 3 y = lambda x=x: x+10 print y(2) print y() to get "12" then "13" back. -tkc From arnodel at googlemail.com Wed Jan 30 08:22:45 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 30 Jan 2008 05:22:45 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> Message-ID: <091ecd90-0193-43b9-8abc-eddbb52e47af@z17g2000hsg.googlegroups.com> On Jan 30, 11:57?am, Arnaud Delobelle wrote: > n = len(a) > for i, x in enumerate(a): > ? ? if x == 99: del a[i-n] Oops. That can't work. Don't know what I was thinking here. I probably did had one mental refactoring too many... -- Arnaud From gagsl-py2 at yahoo.com.ar Sat Jan 19 20:53:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 Jan 2008 23:53:57 -0200 Subject: Gui front-end to version control program References: Message-ID: En Sat, 19 Jan 2008 17:15:21 -0200, David Delony escribi?: > I want something that can work with any file, as Subversion does. I can't > think of any > GUI wrappers written in Python off the top of my head. I would like to There exist TortoiseCVS and TortoiseSVN. They are very intuitive and easy to use front ends, but being Explorer extensions, they're tied to Windows. They're not written in Python, but in C++. -- Gabriel Genellina From kar1107 at gmail.com Tue Jan 8 19:58:54 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 8 Jan 2008 16:58:54 -0800 (PST) Subject: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> Message-ID: <14d3e04e-4bfb-4b1f-b8b6-3183de48f921@i3g2000hsf.googlegroups.com> On Jan 8, 1:20 am, Robert Latest wrote: > Hello, > > look at this function: > > -------------- > def test(): > child = os.popen('./slow') > for line in child: > print line > ------------- > > The program "slow" just writes the numbers 0 through 9 on stdout, one line a > second, and then quits. > > I would have expected the python program to spit out a numbers one by one, > instead I see nothing for 10 seconds and then the whole output all at once. > > How can I get and process the pipe's output at the pace it is generated? I've seen this problem and it took me a while to figure out what is happening. As other posts, I too first suspected it's a problem related to line/ full buffering on the sender side (./slow here). It turned out that the "for line in child:" line in the iterator is the culprit. The iterator does something like a child.readlines() underneath (in it's __iter__ call) instead of a more logical single line read. Change your reading to force line-by-line read e.g. While True: line = child.readline() if not line: break print line Karthik > > Thanks, > > robert From default at defaulter.net Sat Jan 12 13:27:16 2008 From: default at defaulter.net (default) Date: Sat, 12 Jan 2008 13:27:16 -0500 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> <4788de48$0$26887$ecde5a14@news.coretel.net> Message-ID: On Sat, 12 Jan 2008 09:15:44 -0800, ChairmanOfTheBored wrote: > You are both fucked in the head, coffee or not. He more than you, but >still, you both don't know what you are talking about. Any castigation from Bored is an accolade . . . I must be on the right track to get that knee jerk reaction. -- From http Sat Jan 26 00:32:10 2008 From: http (Paul Rubin) Date: 25 Jan 2008 21:32:10 -0800 Subject: Generational Interfaces References: <1b7b3b47-72f0-4a5d-9185-4903e75dba47@d70g2000hsb.googlegroups.com> Message-ID: <7xhch16tk5.fsf@ruckus.brouhaha.com> Carl Banks writes: > AirplaneInterface = InterfaceTracker("Airplane") > ... > set_up_initial_state() > ... > AirplaneInterface.report(self) > Thoughts? (Surely someone's thought to do this before.) A decorator might express the idea a little more naturally. Also, I'd say the interface tracker really should be told explicitly when something is part of the interface and when it's specific to a particular class implementing the interface. It shouldn't try to guess this based on some operation appearing in more than one class. Maybe there's some operation done on all jet planes and on no propeller planes, that shouldn't be part of the top level airplane interface. From ryan at ryankaskel.com Wed Jan 23 14:17:55 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 11:17:55 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> Message-ID: <12d19814-b7b9-44b0-aee3-299befac7279@i12g2000prf.googlegroups.com> I am taking a database class so I'm not asking for specific answers. Well I have this text tile: http://www.cs.tufts.edu/comp/115/projects/proj0/customer.txt And this code: # Table and row classes used for queries class Row(object): def __init__(self, column_list, row_vals): print len(column_list) print len(row_vals) for column, value in column_list, row_vals: if column and value: setattr(self, column.lower(), value) class Table(object): def __init__(self, table_name, table_fd): self.name = table_name self.table_fd = table_fd self.rows = [] self._load_table() def _load_table(self): counter = 0 for line in self.table_fd: # Skip the second line if not '-----' in line: if counter == 0: # This line contains the columns, parse it column_list = line.split() else: # This is a row, parse it row_vals = line.split() # Create a new Row object and add it to the table's # row list self.rows.append(Row(column_list, row_vals)) counter += 1 Because the addresses contain spaces, this won't work because there are too many values being unpacked in row's __init__'s for loop. Any suggestions for a better way to parse this file? I don't want to cheat but just some general ideas would be nice. Thanks! From fredrik at pythonware.com Wed Jan 9 05:37:21 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 11:37:21 +0100 Subject: Open a List of Files In-Reply-To: References: <874pdomrrd.fsf@mulj.homelinux.net> <4f67337a-14ea-4552-8a5a-6de9703e58ff@d70g2000hsb.googlegroups.com> Message-ID: Paul Hankin wrote: > Thanks Fredrik! I learnt something today. > > I wonder if there's a reason why it doesn't raise an exception when > you try to write to it? That would seem better to me than having it > sometimes update variables and sometimes not. probably because it returns a standard dictionary object, and Python's dictionary objects are writable. (and if someone wants to reopen the old discussion about how Python absolutely definitely needs frozen dictionaries to be useful at all, please do so in a new thread ;-) From ganeshborse at gmail.com Thu Jan 3 07:49:57 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 3 Jan 2008 04:49:57 -0800 (PST) Subject: PyObject_CallObject code dump after calling 4 times References: Message-ID: <938001bf-33d2-4071-9b08-f7bb041505b1@s19g2000prg.googlegroups.com> On Jan 3, 8:02?pm, Phil Thompson wrote: > On Thursday 03 January 2008, grbgooglefan wrote: > > > I have a following C++ code which uses PyObject_CallObject to evaluate > > expressions dynamically. This code sets the input parameters for the > > function also dynamically. After calling this function 4 times (with > > these shown values), PyObject_CallObject ?causes application to crash > > in frame_dealloc. > > 1) Can some one please help me understand why is this crash happening > > in frame_dealloc & how to solve it? > > 2) Is there anything wrong I am doing about incrementing or > > decrementing the reference counts of the object passed to > > PyObject_CallObject? > > Yes. > > > > > > > 3) Is it because of the big value (2299265.500000) I am trying to > > convert from double to float using PyFloat_FromDouble? > > > //========================= code reduced for readability > > =============== > > switch(ndtyp){ > > ? ? ?case(INT_T): > > ? ? ? ? ?{ > > ? ? ? ? ?printf("PyInt_FromLong val %d, var %s > > \n",inputVar.nionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > ? ? ? ? ?val = PyInt_FromLong(inputVar.nionum); > > ? ? ? ? ?break; > > ? ? ? ? ?} > > ? ? ? case(LONG_T): > > ? ? ? ? ?{ > > ? ? ? ? ?printf("PyLong_FromLong val %ld, var %s > > \n",inputVar.lionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > ? ? ? ? ?val = PyLong_FromLong(inputVar.lionum); > > ? ? ? ? ?break; > > ? ? ? ? ?} > > ? ? ? case(FLOAT_T): > > ? ? ? ? ?{ > > ? ? ? ? ?printf("PyFloat_FromDouble val %f, var %s > > \n",inputVar.fionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > ? ? ? ? ?val = PyFloat_FromDouble(inputVar.fionum); > > ? ? ? ? ?break; > > ? ? ? ? ?} > > ? ? ? case(DOUBLE_T): > > ? ? ? ? ?{ > > ? ? ? ? ?printf("PyFloat_FromDouble val %f, var %s > > \n",inputVar.dionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > ? ? ? ? ?val = PyFloat_FromDouble(inputVar.dionum); > > ? ? ? ? ?break; > > ? ? ? ? ?} > > ? ? ? ?case(STRING_T): > > ? ? ? ? ?{ > > ? ? ? ? ?printf("PyString_FromString val %s, var %s > > \n",inputVar.ioString,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > ? ? ? ? ?val = PyString_FromString(inputVar.ioString); > > ? ? ? ? ?break; > > ? ? ? ? ?} > > ? ? ? ?default: > > ? ? ? ? ?printf("Unknown data type [%d] for %s\n",ndtyp,pEvalFunc- > > > >pExprVarsArray[nCtr].szVarName); > > > } > > if(!val){ > > ? ?ret = -1; > > ? ?printf("Failed to convert %d %s to PyObject\n",ndtyp,pEvalFunc- > > > >pExprVarsArray[nCtr].szVarName); fflush(stdout); > > > ? ?Py_XDECREF(pTuple); > > ? ?break; > > } > > ? PyTuple_SetItem(pTuple, nCtr, val); > > ? Py_XDECREF(val); > > Don't do this - PyTuple_SetItem() steals a reference to val. > > > } > > // all variables are set, call Python function > > Py_XINCREF(pTuple); > > Why do this? > > > ? PyObject *pResult = PyObject_CallObject(pEvalFunc- > > > >pPyEvalFunction,pTuple); > > > Py_XDECREF(pTuple); > > Why do this? > > > if(PyErr_Occurred()){ > > ?PyErr_Print(); > > } else { > > ? ? ? char* plevel = NULL; > > ? ? ? if(NULL != (plevel = PyString_AsString(pResult))){ > > ? ? ? ? ret = 0; > > ? ? ? ? sprintf(szEvalResult,"%s",plevel); > > ? ? ? } > > } > > Py_XDECREF(pResult); > > pTuple will now have the same number of references as when you started the > above code, so you may want to Py_DECREF() it. > > Phil- Hide quoted text - > > - Show quoted text - Thanks for all the responses. These help me. I could simulate this crash in my small test program & I think (I could be wrong also) it is because of extraneous Py_XDECREF of "PyObject *val" which I am using to convert variables to tuple. When I change the code to simple do like this, it works fine. PyTuple_SetItem(pytuple,0,PyLong_FromLong(size)); PyTuple_SetItem(pytuple,1,PyLong_FromLong(maxvol)); PyTuple_SetItem(pytuple,2,PyFloat_FromDouble(adv)); From DustanGroups at gmail.com Mon Jan 7 15:25:37 2008 From: DustanGroups at gmail.com (Dustan) Date: Mon, 7 Jan 2008 12:25:37 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: On Jan 7, 11:40 am, Martin Marcher wrote: > it's pythonicness. "it is pythonicness"??? From alex.holkner at gmail.com Thu Jan 17 08:42:20 2008 From: alex.holkner at gmail.com (Alex Holkner) Date: Fri, 18 Jan 2008 00:42:20 +1100 Subject: ANN: pyglet 1.0 Message-ID: The first stable/production version of pyglet has been released. http://www.pyglet.org --- pyglet provides an object-oriented programming interface for developing games and other visually-rich applications for Windows, Mac OS X and Linux. Some of the features of pyglet are: * No external dependencies or installation requirements. For most application and game requirements, pyglet needs nothing else besides Python, simplifying distribution and installation. * Take advantage of multiple windows and multi-monitor desktops. pyglet allows you to use as many windows as you need, and is fully aware of multi-monitor setups for use with fullscreen games. * Load images, sound, music and video in almost any format. pyglet can optionally use AVbin to play back audio formats such as MP3, OGG/Vorbis and WMA, and video formats such as DivX, MPEG-2, H.264, WMV and Xvid. pyglet is provided under the BSD open-source license, allowing you to use it for both commercial and other open-source projects with very little restriction. Cheers Alex. From mail at timgolden.me.uk Tue Jan 15 05:55:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jan 2008 10:55:03 +0000 Subject: common problem - elegant solution sought In-Reply-To: <5v3gg1F1kkla5U1@mid.dfncis.de> References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <478C9107.9050406@timgolden.me.uk> Helmut Jarausch wrote: > I'm looking for an elegant solution of the following tiny but common problem. > > I have a list of tuples (Unique_ID,Date) both of which are strings. > I want to delete the tuple (element) with a given Unique_ID, but > I don't known the corresponding Date. > > My straight forward solution is a bit lengthy, e.g. > > L=[("a","070501"),("b","080115"),("c","071231")] > pos=-1 > found=-1 > for (Key,Date) in L : > pos+= 1 > if Key == "b" : > found= pos > break > > if found >= 0 : > del L[found] > > print L > > Most probably there are much more elegant solutions. > Unfortunately, the index-list-method doesn't take an > additional function argument for the comparisons. Probably the most common solution to this in Python is to produce a second list which has all the items in the first except for the one(s) you wish to delete: L=[("a","070501"),("b","080115"),("c","071231")] L2 = [(uniqid, date) for (uniqid, date) in L if not uniqid == 'b'] It might look a little wasteful, but since Python lists are supremely fast and since the tuples themselves aren't copied, only their references, the result is probably what you need. Obviously you've given us a toy example, which is fine for demonstrating the problem. Suggestions might vary if, for example, your data set were much bigger or if the tuples were more complex. TJG From google at mrabarnett.plus.com Thu Jan 10 15:52:21 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 10 Jan 2008 12:52:21 -0800 (PST) Subject: Embedding python code into text document question. References: Message-ID: On Jan 10, 1:10 pm, Thomas Troeger wrote: > Dear all, > > I've written a program that parses a string or file for embedded python > commands, executes them and fills in the returned value. The input might > look like this: > > process id: $$return os.getpid()$$ > current date: $$return time.ctime()$$ > superuser: $$ > if os.geteuid(): > return "Yes" > else: > return "No"$$ > > I've tried several solutions using eval, execfile or compile, but none > of those would solve my problem. Does anyone have a solution that works? > Any suggestions? Any help will be appreciated :) > You could wrap the bits of code in a def statement and then exec it: >>> print field return os.getpid() >>> exec("def field_func():\n" + "".join(" %s\n" % line for line in field.splitlines())) >>> print field_func() 3904 From peixu.zhu at gmail.com Sun Jan 20 23:02:23 2008 From: peixu.zhu at gmail.com (Bonjour) Date: Sun, 20 Jan 2008 20:02:23 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: <761690ad-0e00-42b4-a902-32bbb50fc074@v67g2000hse.googlegroups.com> 'NaN' means "Not a number". according to Python semantics, if you try to compare it with any other float numbers, it should return FALSE. just like >>> >>>1.0 > 'abc' False >>> Since it always return FALSE, it is not a surprise for your question. If you wish to get infinitive number, you'd use 'inf' or '-inf', from IEEE 754 semantics: >>>a=float(6) >>>b=float('inf') >>>c=float('-inf') Albert Hopkins wrote: > This issue may have been referred to in > news: but I didn't > entirely understand the explanation. Basically I have this: > > >>> a = float(6) > >>> b = float('nan') > >>> min(a, b) > 6.0 > >>> min(b, a) > nan > >>> max(a, b) > 6.0 > >>> max(b, a) > nan > > Before I did not know what to expect, but I certainly didn't expect > this. So my question is what is the min/max of a number and NaN or is it > not defined (for which I would have expected either an exception to be > raised or NaN returned in each case). > > As a corrollary would I be able to rely on the above behavior or is it > subject to change (to fix a bug in min/max perhaps :-)? From gagsl-py2 at yahoo.com.ar Wed Jan 23 18:14:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 21:14:07 -0200 Subject: Can someone explain this unexpected raw_input behavior? References: Message-ID: En Wed, 23 Jan 2008 18:27:56 -0200, Mike Kent escribi?: > It's often useful for debugging to print something to stderr, and to > route the error output to a file using '2>filename' on the command > line. > > However, when I try that with a python script, all prompt output from > raw_input goes to stderr. Consider the following test program: > [...] > This indicates to me that the prompt output of raw_input is being sent > to stderr. I did check the source code for raw_input, and it appears > to be sending it to stdout as expected. Surely you've seen that in bltinmodule.c, builtin_raw_input calls PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout), prompt); where fin and fout are sys.stdin and sys.stdout respectively. That function is defined in Parser/myreadline.c, and eventually calls PyOS_StdioReadline with the same arguments. But PyOS_StdioReadline doesn't use its sys_stdout parameter to output the prompt; instead, it always uses stderr, no matter what arguments it receives. Looking at the svn history, PyOS_StdioReadline always has used stderr; got its current signature in rev 29400 (2002). Perhaps that behavior is based on the reverse of your use case, which may be more common. A script writes most of its output to stdout, and you capture that using >filename. If raw_input prompted the user using stdout, that would not be visible in this case, so using stderr is more useful. -- Gabriel Genellina From mark.e.tolonen at mailinator.com Wed Jan 16 21:42:55 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Wed, 16 Jan 2008 18:42:55 -0800 Subject: handlers.SocketHandler and exceptions References: <02de2e9c-331d-45c0-afaa-578ddad55664@j78g2000hsd.googlegroups.com> Message-ID: "writeson" wrote in message news:02de2e9c-331d-45c0-afaa-578ddad55664 at j78g2000hsd.googlegroups.com... > Hi all, > > On our Linux systems at work I've written a Twisted logging server > that receives log messages from multiple servers/processes to post > them to a log file, essentially serializing all the process log > messages. This works well, that is until I tried this test code: > > try: > t = 10 / 0 > except Exception, e: > log.exception("divide by zero") > > where log is the logger instance retreived from a call to getLogger(). > The problem is the handlers.SocketHandler tries to cPickle.dump() the > log record, which in this case contains an exc_info tuple, the last > item of which is a Traceback object. The pickling fails with an > "unpickleable error" and that's that. > > Does anyone have any ideas how to handle this situation? I'd hate to > have to give up using the log.exception(...) call as it's useful to > get strack trace information in the log file. > > Thanks in advance, > Doug Farrell Check out the traceback module. It can translate the traceback into a variety of formats (such as a string) that can be pickled. --Mark From agnel.joel at gmail.com Fri Jan 11 23:38:45 2008 From: agnel.joel at gmail.com (Joel) Date: Fri, 11 Jan 2008 20:38:45 -0800 (PST) Subject: Boa constructor References: Message-ID: On Jan 12, 9:37?am, Joel wrote: > Hi, > In BOA constructor, is there any way to do the following: > Once a breakpoint has reached, I want to enter some code > and execute it. > Can anyone tell me of a technique? > > Also input stream doesn't seem to work, I do a standard input read and > then i enter something in the input window, but it isn't accepted. > What could be the reason? > > Thanks > Joel I wanted to clarify, when I say "enter code", I mean I want to enter some custom code, like print a or something to see the condition of variable 'a' at the breakpoint. From python.list at tim.thechases.com Mon Jan 7 15:47:22 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 07 Jan 2008 14:47:22 -0600 Subject: any() and all() shorthand In-Reply-To: <94640f15-6dde-4ef1-a737-5ee248ae32eb@j20g2000hsi.googlegroups.com> References: <2e589a86-02cf-4903-98aa-c28be2b0b48f@1g2000hsl.googlegroups.com> <94640f15-6dde-4ef1-a737-5ee248ae32eb@j20g2000hsi.googlegroups.com> Message-ID: <47828FDA.7050705@tim.thechases.com> > The idea is a shorthand for reduce. Here, _next_ meant the next item > in the iterable c. You mean like one of these: def lookahead(iterator): i = iter(iterator) x = i.next() for item in i: yield x, item x = item def lookahead2(iterator, **kwarg): i = iter(iterator) if 'initial' in kwarg: x = kwarg['initial'] else: x = i.next() for item in i: yield x, item x = item if 'last' in kwarg: yield x, kwarg['last'] print 'lookahead()' for this, next in lookahead([1,2,3,4,5]): print this, next print 'lookahead2()' for this, next in lookahead2([1,2,3,4,5]): print this, next print 'lookahead2(initial=42)' for this, next in lookahead2([1,2,3,4,5], initial=42): print this, next print 'lookahead2(last=42)' for this, next in lookahead2([1,2,3,4,5], last=42): print this, next print 'lookahead2(initial=3.14159, last=42)' for this, next in lookahead2([1,2,3,4,5], initial=3.14159, last=42): print this, next There are some alternate behaviors that can happen at the end points, so depending on which behavior you want, the lookahead() is cleanest, but doesn't allow you to handle edge cases. The lookahead2() is a little more complex, but allows you to specify a first item for pairing (so "next" touches every item in your list) or a trailing element (so "this" touches every item). -tkc From paddy3118 at googlemail.com Fri Jan 18 09:41:40 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 18 Jan 2008 06:41:40 -0800 (PST) Subject: array and list References: <24f854eb-93a8-414d-a518-842bb2d185fb@s13g2000prd.googlegroups.com> <010888f2-7755-4ec1-9f56-be8a43097a1f@i12g2000prf.googlegroups.com> Message-ID: > Paddy: > > > I guess 'under the hood' Python (& Perl?), arrays might be more like > > an implementation of what the C programmer might call a linked list, > > but even then there are differences as most linked list examples > > given in C tutorials are lists of the same type of object,.... > > Both Python "array.array" and "list" are implemented as dyn arrays, > not as lists. Only the good "deque" by Hettinger is something similar > to a list (of small arrays). > > Bye, > bearophile Ta! From nick at craig-wood.com Wed Jan 9 07:30:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 09 Jan 2008 06:30:05 -0600 Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <87ejcri96v.fsf@mulj.homelinux.net> <87abnfi84i.fsf@mulj.homelinux.net> <5ujp20F1ehvg2U2@mid.dfncis.de> Message-ID: Robert Latest wrote: > Hrvoje Niksic wrote: > > > keywords[:] = (s for s in keywords if s) > > Looks good but is so far beyond my own comprehension that I don't dare > include it in my code ;-) :-) Worth understanding thought I think - here are some hints keywords[:] = (s for s in keywords if s) is equivalent to this (but without creating a temporary list) keywords[:] = list(s for s in keywords if s) which is equivalent to keywords[:] = [s for s in keywords if s] This keywords[:] = .... Replaces the contents of the keywords list rather than making a new list. Here is a demonstration of the fundamental difference >>> a=[1,2,3,4] >>> b=a >>> a=[5,6,7] >>> print a, b [5, 6, 7] [1, 2, 3, 4] >>> a=[1,2,3,4] >>> b=a >>> a[:]=[5,6,7] >>> print a, b [5, 6, 7] [5, 6, 7] Using keywords[:] stops the creation of another temporary list. The other behaviour may or may not be what you want! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From tarundevnani at gmail.com Mon Jan 28 02:39:49 2008 From: tarundevnani at gmail.com (tarun) Date: Mon, 28 Jan 2008 13:09:49 +0530 Subject: [wxPython-users] Issue with docking wx.listctrl window In-Reply-To: <479A145C.40802@alldunn.com> References: <4798D1B1.7020908@alldunn.com> <479A145C.40802@alldunn.com> Message-ID: Thanks Robin. Can you please elobrate more on this. Regards, Tarun Devnani On Jan 25, 2008 10:24 PM, Robin Dunn wrote: > tarun wrote: > > Thanks a lot Robin. > > > > I tried using self.log and instead of self.log.list. *Code is attached.* > > But this gives me a panel and listctrl in it. The extra blank space > > around the listctrl in window1 is something that I don't need. > > Use a sizer to manage the layout of the listctrl. > > -- > Robin Dunn > Software Craftsman > http://wxPython.org Java give you jitters? Relax > with wxPython! > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Sun Jan 27 05:39:17 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jan 2008 10:39:17 GMT Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <5vr1ekF1njt09U2@mid.uni-berlin.de> <84f39f37-4d18-47c1-9349-bf3f471b2bf5@s19g2000prg.googlegroups.com> Message-ID: <6035alF1oh17aU3@mid.uni-berlin.de> On Sun, 27 Jan 2008 02:18:48 -0800, glacier wrote: > Yepp. I feed SAX with the unicode string since SAX didn't support my > encoding system(GBK). If the `decode()` method supports it, IMHO SAX should too. > Is there any way to solve this better? > I mean if I shouldn't convert the GBK string to unicode string, what > should I do to make SAX work? Decode it and then encode it to utf-8 before feeding it to the parser. Ciao, Marc 'BlackJack' Rintsch From casey at rodarmor.com Thu Jan 17 03:48:35 2008 From: casey at rodarmor.com (Casey Rodarmor) Date: Thu, 17 Jan 2008 00:48:35 -0800 Subject: Replace stop words (remove words from a string) In-Reply-To: <01be01c858e4$c6b8b280$542a1780$@com> References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> <01be01c858e4$c6b8b280$542a1780$@com> Message-ID: That's much better than what I was about to post: for s in stoplist: string.join(mystr.split(s, "")) Berlin: Why are you keen on avoiding split()? On 1/17/08, Karthik wrote: > > How about - > > for s in stoplist: > string.replace(mystr, s, "") > > Hope this should work. > > -----Original Message----- > From: python-list-bounces+karthik3186=gmail.com at python.org > [mailto:python-list-bounces+karthik3186=gmail.com at python.org] On Behalf Of > BerlinBrown > Sent: Thursday, January 17, 2008 1:55 PM > To: python-list at python.org > Subject: Replace stop words (remove words from a string) > > if I have an array of "stop" words, and I want to replace those values > with something else; in a string, how would I go about doing this. I > have this code that splits the string and then does a difference but I > think there is an easier approach: > > E.g. > > mystr = > > kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsldf > sd; > > if I have an array stop_list = [ "[BAD]", "[BAD2]" ] > > I want to replace the values in that list with a zero length string. > > I had this before, but I don't want to use this approach; I don't want > to use the split. > > line_list = line.lower().split() > res = list(set(keywords_list).difference(set(ENTITY_IGNORE_LIST))) > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajaksu at gmail.com Fri Jan 25 20:44:07 2008 From: ajaksu at gmail.com (ajaksu) Date: Fri, 25 Jan 2008 17:44:07 -0800 (PST) Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> On Jan 25, 11:36 pm, ajaksu wrote: > On Jan 25, 11:10 pm, o... at thepond.com wrote: [...] Gaah, is this what's going on? ajaksu at Belkar:~$ cat error.txt This is not assembler... ajaksu at Belkar:~$ ndisasm error.txt 00000000 54 push sp 00000001 686973 push word 0x7369 00000004 206973 and [bx+di+0x73],ch 00000007 206E6F and [bp+0x6f],ch 0000000A 7420 jz 0x2c 0000000C 61 popa 0000000D 7373 jnc 0x82 0000000F 656D gs insw 00000011 626C65 bound bp,[si+0x65] 00000014 722E jc 0x44 00000016 2E db 0x2E 00000017 2E db 0x2E 00000018 0A db 0x0A :/ From duncan.booth at invalid.invalid Mon Jan 21 14:36:29 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jan 2008 19:36:29 GMT Subject: problem with 'global' References: <5vk9fqF1n19plU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 21 Jan 2008 17:08:46 -0200, Gabriel Genellina wrote: > >> The future statement is another example, even worse: >> >> if 0: >> from __future__ import with_statement >> >> with open("xxx") as f: >> print f > > In Python >=2.5 it's a compile time error if that import is not the very > first statement in a source file. > That doesn't appear to be the case. With Python 2.5.1 the example Gabriel quoted will compile and run. From sunilkrghai at gmail.com Tue Jan 1 08:40:03 2008 From: sunilkrghai at gmail.com (Sunil Ghai) Date: Tue, 1 Jan 2008 19:10:03 +0530 Subject: Network Module Message-ID: <52da23100801010540s122337aci470e2ee4fa85fa1b@mail.gmail.com> Hello people, I am searching for a python module to interact with the network connections/interfaces. For example the number of active TCP/IP connections via eth0 interface and all that stuff. I have done googling and search at pythonorg but couldn't find any. Thanks Sunil Kumar Ghai -------------- next part -------------- An HTML attachment was scrubbed... URL: From BjornSteinarFjeldPettersen at gmail.com Sun Jan 13 10:01:49 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 13 Jan 2008 07:01:49 -0800 (PST) Subject: How to get user home directory on Windows References: <0bb27916-5416-47b2-b58c-1eb82ccb6d3e@k2g2000hse.googlegroups.com> Message-ID: On Jan 12, 6:50 pm, "Giampaolo Rodola'" wrote: > Update. > I found a way for getting the home directory of the user but it > requires to validate the user by providing username+password: > > def get_homedir(username, password): > token = win32security.LogonUser( > username, > None, > password, > win32security.LOGON32_LOGON_NETWORK, > win32security.LOGON32_PROVIDER_DEFAULT > ) > return win32profile.GetUserProfileDirectory(token) > > What I'd like to do is avoiding the requirement of the password, the > same way as if I would on UNIX where it would be enough just using the > pwd module: > > >>> import pwd > >>> pwd.getpwnam('user').pw_dir > '/home/user' Check out http://msdn2.microsoft.com/en-us/library/bb762181(VS.85).aspx for some of the complexities of special directories on Windows. If you give more details on what you need to get done, someone might come up with a better solution (my instinct tells me this might be a database problem, but then I'm a database person so that might not be terribly relevant ;-) -- bjorn From tonylabarbara at aol.com Fri Jan 25 11:12:27 2008 From: tonylabarbara at aol.com (tonylabarbara at aol.com) Date: Fri, 25 Jan 2008 11:12:27 -0500 Subject: Automatically Writing a Dictionary In-Reply-To: <47979785.502@tim.thechases.com> References: <8CA2C0BF25FCAA6-1374-117B@WEBMAIL-DC15.sysops.aol.com> <47979785.502@tim.thechases.com> Message-ID: <8CA2D8436C5B761-E80-5C4@FWM-D40.sysops.aol.com> d = {}? ? for line in input:? ? key, value = line.split(',').rstrip('\n')? ? d[key] = value? Thanks. That worked except for the rstrip. So I did this: for line in input: ? line = string.rstrip(line, '\n') ? key, value = line.split(',') ? dictionary[key] = value Thanks again, Tony -----Original Message----- From: Tim Chase To: tonylabarbara at aol.com Cc: python-list at python.org Sent: Wed, 23 Jan 2008 3:37 pm Subject: Re: Automatically Writing a Dictionary > input = "/usr/local/machine-lang-trans/dictionary.txt"? > > input = open(input,'r')? > > dict = "{"? > for line in input:? > ? tup = re.split(','line)? > ? dict += '"' + tup[0] +'":"' + tup[1] +'", '? > dict += "}"? > input.close()? > > > Of course, that will just give me a string. How do I convert? > it to, or make from scratch, a dictionary of that?? ? Don't bother with the string (and as a side-note, it's bad style to mask the built-in dict() so I'll use "d"):? ? ? d = {}? ? for line in input:? ? key, value = line.split(',').rstrip('\n')? ? d[key] = value? ? or even just? ? ? d = dict(line.split(',').rstrip('\n')? ? for line in input)? ? using the aforementioned dict() function :-)? ? You may want to clean it up a bit in case there are spurious leading/trailing spaces to be trimmed:? ? ? from string import strip? ? d = dict(map(strip, line.split(','))? ? for line in input)? ? or even ignore lines with the wrong number of commas:? ? ? d = dict(map(strip, line.split(','))? ? for line in input? ? if line.count(',') == 1)? ? or assume any extra commas are part of the value:? ? ? d = dict(map(strip, line.split(',',1))? ? for line in input? ? if line.count(',') > 0)? ? HTH,? ? -tkc? ? ? ________________________________________________________________________ More new features than ever. Check out the new AOL Mail ! - http://webmail.aol.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From peixu.zhu at gmail.com Sun Jan 20 23:12:19 2008 From: peixu.zhu at gmail.com (Bonjour) Date: Sun, 20 Jan 2008 20:12:19 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: <73891c67-4726-44b0-a815-9620279fb0f0@c4g2000hsg.googlegroups.com> 'NaN' means "Not a number". according to Python semantics, if you try to compare it with any other float numbers, it should return FALSE. just like: >>>1.0 > 'abc' False Since it always return FALSE, it is not a surprise for your question. If you wish to get infinitive number, you'd use 'inf' for positive infinitive or '-inf' for negative infinitive, from IEEE 754 semantics, just like: >>>a=float(6) >>>b=float('inf') >>>c=float('-inf') For more information, PEP-0754 may be helpful. From cp02sdh02 at sneakemail.com Tue Jan 8 12:22:45 2008 From: cp02sdh02 at sneakemail.com (C Martin) Date: 8 Jan 2008 17:22:45 -0000 Subject: Tkinter variable trace problem Message-ID: <16157-56584@sneakemail.com> Thank you for your replies. I understand there are better ways to handle 'normal' UI behavior, but I was curious about the trace feature and wanted to understand how it worked. I may not actually need it in my project, but I wanted to see what my options were. Thanks again. -------------------------------------- Protect yourself from spam, use http://sneakemail.com From fredrik at pythonware.com Wed Jan 9 17:41:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 23:41:17 +0100 Subject: for loop without variable In-Reply-To: References: Message-ID: erik gartz wrote: > Hi. I'd like to be able to write a loop such as: > for i in range(10): > pass > but without the i variable. The reason for this is I'm using pylint > and it complains about the unused variable i. if a computer tells you to do something stupid, it's often better to find a way to tell the computer to shut up than to actually do some- thing stupid. (pylint's online documentation is remarkably unreadable, so I cannot help you with the details, but surely there's a way to disable that test, either globally, or for a specific region of code?). From sjmachin at lexicon.net Wed Jan 2 06:28:38 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 2 Jan 2008 03:28:38 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> Message-ID: <4af890f4-acbc-467c-995d-0593b0ef08ee@e6g2000prf.googlegroups.com> On Jan 2, 9:57 pm, mario wrote: > On Jan 2, 10:44 am, John Machin wrote: > > > > > Two things for you to do: > > > (1) Try these at the Python interactive prompt: > > > unicode('', 'latin1') > > unicode('', 'mbcs') > > unicode('', 'raboof') > > unicode('abc', 'latin1') > > unicode('abc', 'mbcs') > > unicode('abc', 'raboof') > > $ python > Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> unicode('', 'mbcs') > u'' > >>> unicode('abc', 'mbcs') > > Traceback (most recent call last): > File "", line 1, in > LookupError: unknown encoding: mbcs > > > > Hmmn, strange. Same behaviour for "raboof". > > > (2) Read what the manual (Library Reference -> codecs module -> > > standard encodings) has to say about mbcs. > > Page athttp://docs.python.org/lib/standard-encodings.htmlsays that > mbcs "purpose": > Windows only: Encode operand according to the ANSI codepage (CP_ACP) > > Do not know what the implications of encoding according to "ANSI > codepage (CP_ACP)" are. Neither do I. YAGNI (especially on darwin) so don't lose any sleep over it. > Windows only seems clear, but why does it only > complain when decoding a non-empty string (or when encoding the empty > unicode string) ? My presumption: because it doesn't need a codec to decode '' into u''; no failed codec look-up, so no complaint. Any realistic app will try to decode a non-empty string sooner or later. From bg_ie at yahoo.com Fri Jan 25 05:26:35 2008 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Fri, 25 Jan 2008 02:26:35 -0800 (PST) Subject: The dimensions of a tuple Message-ID: Hi, I wish to pass an argument to a function which will inset rows in a db. I wish to have the follow possibilities - ("one","two") (("one","two"),("three","four")) The first possibility would mean that one row is added with "one and "two" being its column values. The second possibility means that two rows are added. So to do this I need to establish the dimension of the duple. Is it a one dimentional or two dimentional. How do I do this? Thanks, Barry. From carsten at uniqsys.com Fri Jan 4 09:32:27 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 04 Jan 2008 09:32:27 -0500 Subject: Cursors in a Loop In-Reply-To: References: <3da337d8-2de0-4fdb-8c38-2f6fcd8348ac@i72g2000hsd.googlegroups.com> Message-ID: <1199457147.3453.5.camel@dot.uniqsys.com> On Fri, 2008-01-04 at 00:03 -0800, Chris wrote: > You should bind all variables to save the pool. > > cursor = connection.cursor() > cursor.executemany("""insert into as_siebel_hosts_temp > values (:whole, :lot, :of, :bind, :variables) > """ > ,[(i,)[0] for i in hostlist] > ) > connection.commit() > connection.close() Huh? In the OP's example, the table one has one column. I'll openly admit that I don't know anything about Oracle, but that code doesn't make sense to me. Maybe you're trying to execute a multi-row insert, but that would be done with execute(), not executemany(), wouldn't it? Also, isn't "[(i,)[0] for i in hostlist]" exactly the same as "[i for i in hostlist]" which in turn is exactly the same as "hostlist"? -- Carsten Haese http://informixdb.sourceforge.net From bearophileHUGS at lycos.com Sat Jan 26 04:51:51 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 26 Jan 2008 01:51:51 -0800 (PST) Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> Message-ID: <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> > Henry Baxter wrote: > > def maxi(l): > > m = max(l) > > for i, v in enumerate(l): > > if m == v: > > return i > > What's about l.index(max(l)) ? The version I use: def posmax(seq, key=None): """Return the position of the first maximum item of a sequence. It accepts the usual key parameter too.""" if key: return max(enumerate(seq), key=lambda k: key(k[1]))[0] else: return max(enumerate(seq), key=itemgetter(1))[0] Bye, bearophile From berlin.brown at gmail.com Mon Jan 14 17:15:38 2008 From: berlin.brown at gmail.com (BerlinBrown) Date: Mon, 14 Jan 2008 14:15:38 -0800 (PST) Subject: Append zip files together, just get the binary data (in memory) Message-ID: <53f66038-ccc3-4c3d-97b2-fa5deb148809@d4g2000prg.googlegroups.com> Is it possible to just build the binary content of a zip file. I want to create the content in memory (e.g. return binary data) and then get those byte strings representing the zip file? Is that possible? Or could I possibly override functions in the zip class. 1. Create a zip file object (e.g. dont actually create the file). 2. Append stuff to the zip file (e.g. a file) 3. Zip that content into memory (but still not touching the filesystem) 4. Extract those byte strings for (an array?) later use. My goal is to concatenate multiple zip files into another binary file. From bazwal at googlemail.com Mon Jan 7 13:30:04 2008 From: bazwal at googlemail.com (Baz Walter) Date: Mon, 7 Jan 2008 18:30:04 +0000 (UTC) Subject: Does Python cache the startup module? Message-ID: Hello I remember reading somewhere (probably this list) that python may cache the module that starts a program (e.g. 'main.py'). I'm asking because I have found that this can sometimes cause problems when making small edits to the module. For instance, in my current module I changed the name of the main gui widget. When I ran the program, the program started to leak memory like a sieve. I then changed the name back again, and the problem went away. This looks very much like some sort of weird caching behaviour to me. I've tried deleting the .pyc file and even re-booting, but I can't make the problem go away! Can anyone confirm that this caching happens? And if so, is it documented anywhere? TIA From f.guerrieri at gmail.com Fri Jan 11 12:29:33 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Fri, 11 Jan 2008 18:29:33 +0100 Subject: Analyzing Python GC output - what is a "cell", and what information is available about it. In-Reply-To: <4787a42e$0$36403$742ec2ed@news.sonic.net> References: <478707f2$0$36360$742ec2ed@news.sonic.net> <4787a42e$0$36403$742ec2ed@news.sonic.net> Message-ID: <79b79e730801110929w35169d0fhd4ed9785f7ea7c36@mail.gmail.com> On Jan 11, 2008 6:20 PM, John Nagle wrote: > Tried: > print item.dir() > got: > 'cell' object has no attribute 'dir' I don't know nothing about cell objects... but why don't you try dir(item) instead? Francesco From devraj at gmail.com Tue Jan 29 01:18:58 2008 From: devraj at gmail.com (Devraj) Date: Mon, 28 Jan 2008 22:18:58 -0800 (PST) Subject: Where do glade files go? Message-ID: <384ee7e6-3776-4ed1-a947-db1c3067023c@i3g2000hsf.googlegroups.com> Hi everyone, I am writing an application using Python/GTK/Hildon/Glade. I will be creating a debian package as the final distribution mechanism for the package. What would be the ideal place to put glade files that my application uses on the target system? Thanks. From rbianchi at physik.uni-freiburg.de Thu Jan 10 09:24:37 2008 From: rbianchi at physik.uni-freiburg.de (Riccardo Maria Bianchi) Date: Thu, 10 Jan 2008 15:24:37 +0100 Subject: run shell commands Message-ID: Hello! :) I'm trying to run shell commands both with os.system() and subprocess.Popen() class. But I can't run aliases or function defined in my .bashrc file, like in the login interactive shell. Can you help me? Maybe have I to add some commands to load the .bashrc? Thanks a lot! :) Ric. From Thomas.Ploch at gmx.net Mon Jan 28 14:47:25 2008 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Mon, 28 Jan 2008 20:47:25 +0100 Subject: [Q] Is there a way to minimize a Tkinter application to the system tray? Message-ID: <10253dff3d5784edf50d5d2ac78662c9@gmx.net> Hello folks, I already found some answers on the net, which said that the Tk library that Tkinter wraps does not offer functionality to minimize an application to the system tray. But I hope there are some wizards in here that might tell me that how it (possibly) could be done. Thomas From stanc at al.com.au Mon Jan 14 00:45:00 2008 From: stanc at al.com.au (Astan Chee) Date: Mon, 14 Jan 2008 16:45:00 +1100 Subject: (bit)torrent source code help Message-ID: <478AF6DC.8040600@al.com.au> Hi, Im using windows XP and I was wondering if anyone had any experience in compiling (using py2exe) the official bittorrent client ( http://download.bittorrent.com/dl/BitTorrent-5.2.0.tar.gz ) or any bittorrent client open source and written in python. I ask since I am trying to make several of my own modification to the protocol but the official open source client keeps on giving me missing modules (I have all the required modules and components and it keeps on failing due to platform-based errors) when I try to create an executable of it using py2exe. Can anyone either suggest another source code for a torrent client or any torrent client in python that compiles nicely with py2exe in windows? Thanks Astan From stefan.behnel-n05pAM at web.de Mon Jan 7 16:07:32 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 07 Jan 2008 22:07:32 +0100 Subject: Python's great, in a word In-Reply-To: References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <08f0c528-0619-432a-80a1-569cd9183e09@s12g2000prg.googlegroups.com> Message-ID: <47829494.2010000@web.de> Henry Chang wrote: > On Jan 7, 2008 5:41 AM, alain wrote: >> Paraphrasing Steve Jobs but in this context: >> PYTHON = a bycycle for the mind > What exactly does it mean "a bycycle for the mind"?? Ask the Dutch guy near you. Stefan From MartinRinehart at gmail.com Wed Jan 9 08:02:24 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 9 Jan 2008 05:02:24 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <5cf4c5bb-01b1-4ece-a09a-24c4491764b1@f47g2000hsd.googlegroups.com> Message-ID: <7486a4ff-e801-4036-86d3-2ad0aaf542df@v29g2000hsf.googlegroups.com> Thanks to all for many helpful suggestions. Python, by the way, is verbose when compared to APL. (See http://catpad.net/michael/apl/ if you don't believe this.) You need to stick in an adverb (maybe "gracefully concise") as standalone "concise" is owned by APL. Basilisk96 wrote: > Did programmers stop writing programs on punch cards because they ran > out of punch paper? If you drive on the NYS Thruway, you still get a punch card when you enter. You turn it in when you pay your toll. From pablo at decode.com.ar Fri Jan 11 21:55:47 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Sat, 12 Jan 2008 00:55:47 -0200 Subject: alternating string replace In-Reply-To: <7x7iifsrur.fsf@ruckus.brouhaha.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <7x7iifsrur.fsf@ruckus.brouhaha.com> Message-ID: <47882C33.5010500@decode.com.ar> Paul Rubin wrote: > George Sakkis writes: > >> from itertools import chain, izip, cycle >> print ''.join(chain(*izip(s1.split('_'),cycle(':,'))))[:-1] >> > > from itertools import cycle > a = cycle(':,') > print re.sub('_', lambda x: a.next(), s1) > Lovely. If there OP didn't vanished into thin air*, I'd declare you the winner (although you forgot to import re). This said, I'm still kind of partial to any re-only solution, but it would require someone outlines the behavior in the corner cases. * die, thread! -- Pablo From bignose+hates-spam at benfinney.id.au Wed Jan 23 23:59:35 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 24 Jan 2008 15:59:35 +1100 Subject: Terminology: "script" versus "program" (was: Linux Journal Survey) References: <1666950d-e9a5-4b7c-a614-5bba90e5b4ca@y5g2000hsf.googlegroups.com> Message-ID: <87ir1j7r9k.fsf_-_@benfinney.id.au> George Sakkis writes: > 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. I agree entirely. The term "script" has the strong connotation of a limited-purpose program designed to solve a problem expressed almost entirely as a simple series of steps. Languages that are often used to write such scripts are usually referred to as "scripting languages", which becomes a denigration because such a language need not have support for much else. In contrast, the term "program" (and hence "programming language") implies support for a much broader set of practices and solutions. This term seems quite prevalent among the Python core developers, unfortunately. The 'distutils' module even has the term 'script' used in its interface, to refer to the programs that are to be distributed. -- \ "Money is always to be found when men are to be sent to the | `\ frontiers to be destroyed: when the object is to preserve them, | _o__) it is no longer so." -- Voltaire, _Dictionnaire Philosophique_ | Ben Finney From george.sakkis at gmail.com Fri Jan 11 21:06:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 18:06:48 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: On Jan 9, 6:34 am, Duncan Booth wrote: > cesco wrote: > > Hi, > > > say I have a string like the following: > > s1 = 'hi_cat_bye_dog' > > and I want to replace the even '_' with ':' and the odd '_' with ',' > > so that I get a new string like the following: > > s2 = 'hi:cat,bye:dog' > > Is there a common recipe to accomplish that? I can't come up with any > > solution... > > Here's yet another answer: > > from itertools import islice, cycle > > def interleave(*iterators): > iterators = [ iter(i) for i in iterators ] > while 1: > for i in iterators: > yield i.next() > > def punctuate(s): > parts = s.split('_') > punctuation = islice(cycle(':,'), len(parts)-1) > return ''.join(interleave(parts, punctuation)) > > s1 = 'hi_cat_bye_dog' > print punctuate(s1) > > # Or as a one-liner (once you have interleave): > > print ''.join(list(interleave(s1.split('_'), cycle(':,')))[:-1]) And yet another itertools-addicted one-liner (leaving out the import): from itertools import chain, izip, cycle print ''.join(chain(*izip(s1.split('_'),cycle(':,'))))[:-1] George From bernhard.merkle at googlemail.com Fri Jan 4 07:14:14 2008 From: bernhard.merkle at googlemail.com (Bernhard Merkle) Date: Fri, 4 Jan 2008 04:14:14 -0800 (PST) Subject: pydepend (checking dependencies like jdepend) ? Message-ID: <1969e240-9e80-4df1-b085-7956dfa4f7ae@t1g2000pra.googlegroups.com> Hi there, think %Subject says all. I am wondering if there is some tool to check dependencies within python programs. (something like jdepend for python ;-) Of course the dependencies are at runtime (dynamic) and not statically +dynamically (as in Java), but anyway it would be interesting to know of them (for better modularization e.g.) TIA, Berni. From stefan.behnel-n05pAM at web.de Sat Jan 19 08:34:57 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 19 Jan 2008 14:34:57 +0100 Subject: Excess whitespace in my soup In-Reply-To: References: <48eb8853-91b3-4c43-8014-a0c624e4c6e7@t1g2000pra.googlegroups.com> Message-ID: <4791FC81.5090004@web.de> John Machin wrote: > On Jan 19, 11:00 pm, Fredrik Lundh wrote: >> John Machin wrote: >>> I'm happy enough with reassembling the second item. The problem is in >>> reliably and correctly collapsing the whitespace in each of the above >> > fiveelements. The standard Python idiom of u' '.join(text.split()) >> > won't work because the text is Unicode and u'\xa0' is whitespace >> >>> and would be converted to a space. >> would this (or some variation of it) work? >> >> >>> re.sub("[ \n\r\t]+", " ", u"foo\n frab\xa0farn") >> u'foo frab\xa0farn' >> >> > > Yes, partially. Leading and trailing whitespace has to be removed > entirely, not replaced by one space. Sounds like adding a .strip() to me ... Stefan From ggpolo at gmail.com Thu Jan 10 09:08:34 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 10 Jan 2008 12:08:34 -0200 Subject: New Tk look (aka Ttk or Tile widgets) In-Reply-To: References: Message-ID: 2008/1/10, Robert Hicks : > Do I have to install something extra to use the new look? > > Robert > -- > http://mail.python.org/mailman/listinfo/python-list > Tk 8.5 -- -- Guilherme H. Polo Goncalves From yantao at telus.com Sun Jan 27 10:57:37 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 15:57:37 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: <13pode8n39n8ea8@corp.supernews.com> References: <13po55nc0q0s06@corp.supernews.com> <13pode8n39n8ea8@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13pode8n39n8ea8 at corp.supernews.com... > On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: > >> You didn't understand my question, but thanks any way. >> >> Yes, it is true that %s already support unicode, and I did not >> contradict that. But it counts the number of bytes instead of >> characters, and makes things like %-20s out of alignment. If you don't >> understand my assertion, please don't argue back and I am only >> interested in answers from those who are qualified. > > I understand your assertion. I think it is nonsense. this kind of reply only embarrase yourself > >>>> def test(): > ... print "12345678901234567890 +" > ... print "%-20s +" % "Plain ASCII" > ... print u"%-20s +" % u"Les mis?rables-\320\321\322" > ... >>>> test() > 12345678901234567890 + > Plain ASCII + > Les mis?rables-??? + > > > > > -- > Steven From mutawafayez at yahoo.com Sat Jan 12 11:36:04 2008 From: mutawafayez at yahoo.com (small giant) Date: Sat, 12 Jan 2008 08:36:04 -0800 (PST) Subject: what did the bible say about Mohammad Message-ID: <4123d276-f971-4658-a976-a147825b0d8e@v29g2000hsf.googlegroups.com> According to the Bible, God said to Moses, on whom be peace: I will raise up for them a prophet like you from among their brothers; I will put my words in his mouth, and he will tell them everything I command him. (The Holy Bible, New International Version, Deuteronomy chapter 18, verse 18). The prophet described in the above verse must have the following three characteristics: 1. He will be like Moses. 2. He will come from the brothers of the Israelites, i.e. the Ishmaelites. 3. God will put His words in the mouth of the prophet and he will declare what God commanded him. Let us see which prophet God was speaking of. 1. The prophet like Moses Some people feel that this prophecy refers to the prophet Jesus, on whom be peace. But, although Jesus (peace be upon him and all of God's prophets and messengers) was truly a prophet of God, he is not the prophet spoken of here. He was born miraculously, and finally God raised him up miraculously. On the other hand, Muhammad is more like Moses; both were born in a natural way and both died natural deaths. 2. From among the Ishmaelites Abraham had two sons, Ishmael and Isaac (Genesis, chapter 21). Ishmael became the grandfather of the Arab nation. And Isaac became the grandfather of Jewish nation. The prophet spoken of was to come not from among the Jews themselves, but from among their brothers, the Ishmaelites. Muhammad a descendant of Ishmael, is indeed that prophet. 3. God will put his words in his mouth 'Neither the content of the revelation, nor its form, were of Muhammad's devising. Both were given by the angel, and Muhammad's task was only to repeat what he heard.' (Word Religions from Ancient history to the Present, by Geoffrey Parrinder, p. 472). God sent the angel Gabriel to teach Muhammad the exact words that he should repeat to the people. The words are therefore not his own; they did not come from his own thoughts, but were put into his mouth by the angel. These are written down in the Qur'an word for word, exactly as they came from God. Now that we know that prophet we must listen to him, for, according to the Bible, God says: 'I will punish anyone who refuses to obey him' (Good News Bible, Deut. 18:19). Jesus (on whom be peace) In the Glorious Qur'an The Qur'an tells us many wonderful things about Jesus. As a result, believers in the Qur'an love Jesus, honor him and believe in him. In fact, no Muslim can be a Muslim unless he or she believes in Jesus, on whom be peace. The Qur'an says that Jesus was born of a virgin, that he spoke while he was still only a baby, that he healed the blind and the leper by God's leave and that he raised the dead by God's leave. What then is the significance of these miracles? First, the virgin birth. God demonstrates His power to create in every way. God created everyone we know from a man and a woman. But how about Adam, on whom be peace? God created him from neither a man nor a woman. And Eve from only a man, without a woman. And finally, to complete the picture, God created Jesus from a woman, without a man. What about the other miracles? These were to show that Jesus was not acting on his own behalf, but that he was backed by God. The Qur'an specifies that these miracles were performed by God's leave. This may be compared to the Book of Acts in the Bible, chapter 2, verse 22, where it says that the miracles were done by God to show that he approved of Jesus. Also, note that Jesus himself is recorded in the Gospel of John to have said: 'I can do nothing of my own authority' (5:30). The miracles, therefore, were done not by his own authority, but by God's authority. What did Jesus teach? The Qur'an tells us that Jesus came to teach the same basic message which was taught by previous prophets from God - that we must shun every false god and worship only the One True God. Jesus taught that he is the servant and messenger of the One True God, the God of Abraham. These Qur'anic teachings can be compared with the Bible (Mark 10:18; Matthew 26:39; John 14:28, 17:3, and 20:17) where Jesus teaches that the one he worshipped is the only true God. See also Matthew 12:18; Acts 3:13, and 4:27 where we find that his disciples knew him as 'Servant of God'. The Qur'an tells us that some of the Israelites rejected Jesus, and conspired to kill him, but God rescued Jesus and raised him to Himself. God will cause Jesus to descend again, at which time Jesus will confirm his true teachings and everyone will believe in him as he is and as the Qur'an teaches about him. Jesus is the Messiah. He is a word from God, and a spirit from Him. He is honored in this world and in the hereafter, and he is one of those brought nearest to God. Jesus was a man who spoke the truth which he heard from God. This can be compared with the Gospel According John where Jesus says to the Israelites: 'You are determined to kill me, a man who has told you the truth that I heard from God' (John 8:40). see this site www.sultan.org From inq1ltd at inqvista.com Thu Jan 31 10:43:01 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Thu, 31 Jan 2008 10:43:01 -0500 Subject: Fwd: Re: Problems installing Python on server In-Reply-To: <200801310946.50733.inq1ltd@inqvista.com> References: <200801310946.50733.inq1ltd@inqvista.com> Message-ID: <200801311043.02168.inq1ltd@inqvista.com> On Thursday 31 January 2008 09:46, jim-on-linux wrote: > > > Also be careful and setup all the > > > paths that is required for compiling > > > various Python modules etc. > > > > > > On Jan 29, 8:28 am, Yansky > > > > wrote: > > > > I asked my hosting company if they > > > > would upgrade Python on my server to > > > > the latest version. They responded > > > > with: > > > > > > > > "Sorry no. We tend to stick with > > > > what comes packaged with the unix > > > > distribution to ease maintenance > > > > issues. > > > > > > > > There is nothing stopping you from > > > > running your own version of python > > > > from within your own account. > > > > Download the source and compile it > > > > and install it into your own space. > > > > Adjust the fist line of your python > > > > scripts to reflect the location of > > > > YOUR python binary: > > > > > > > > #! /home/youraccount/yourlibs/python > > > > > > > > and you should be all set." > > > > Go to the ReadME file after you unpack > > python. > > Open and look for "Installing". > > Read the section, it explains how to > > install on the entire system and how to > > install locally. > > "Make altinstall" is what you are > > looking for. > > > > jim-on-linux > > http:\\www.inqvista.com > > > > > > The build instructions for Python > > > > are: To start building right away > > > > (on UNIX): type "./configure" in the > > > > current directory and when it > > > > finishes, type "make". This creates > > > > an executable "./python"; to install > > > > in usr/local, first do "su root" and > > > > then "make install". > > > > > > > > The problem is, I don't have root > > > > access to the server so I can't do > > > > the "make install". I have ubuntu on > > > > my computer, but from what I > > > > understand I can't compile it on > > > > that and upload it because the > > > > server runs Red Had and the > > > > ./configure would have made it > > > > incompatible right? > > > > > > > > So how can I build Python without > > > > root access? > > Will the "make install" make my Python the > default one? If I want to install some > Python modules, will I need to alter > their installation as well or will it see > my Python version as the right one to > install too? > > Cheers. From the Readme file enclose with Python; ------ " If you have a previous installation of Python that you don't want to replace yet, use make altinstall This installs the same set of files as "make install" except it doesn't create the hard link to "python" named "python" and it doesn't install the manual page at all. " ------ I installed python 2.5 using make altinstall by going to " /usr/local/lib " unpacking, then using make altinstall Folder 2.5 is created. To add modules, as I have added PIL to my system, I go to; " /usr/local/lib/python2.5/site-packages " where I installed PIL. installing a py module in the site-packages folder is where I would install any package unless otherwise directed. When upgrading you can go to the site directory and see what's in there, and what has to be added to a new upgrade. http:\\www.inqvista.com jim-on-linux From hniksic at xemacs.org Tue Jan 8 04:59:53 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 08 Jan 2008 10:59:53 +0100 Subject: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> <5ugulaF1hqn2cU1@mid.uni-berlin.de> <5ugv5dF1i0edtU1@mid.dfncis.de> Message-ID: <87fxx8mycm.fsf@mulj.homelinux.net> Robert Latest writes: > If 'slow' or some other program does buffered output, how come I can > see its output line-by-line in the shell? stdio uses different buffering strategies depending on the output type. When the output is a TTY, line buffering is used; when the output goes to a pipe or file, it is fully buffered. > In reality I want to call another program whose behavior I can't > influence (well, technically I could because it's open-source, but > let's assume it to be a black box for now). To test whether your black box buffers output to pipe, simply start it like this: $ ./slow | cat If you see lines one by one, you are in luck, and you can fix things on the Python level simply by avoiding buffering in popen. If not, you will need to resort to more advanced hackery (e.g. fixing stdio using LD_PRELOAD). From washakie at gmail.com Wed Jan 30 09:44:39 2008 From: washakie at gmail.com (washakie) Date: Wed, 30 Jan 2008 06:44:39 -0800 (PST) Subject: find nearest time in datetime list In-Reply-To: <47A0672F.3090702@timgolden.me.uk> References: <15180398.post@talk.nabble.com> <47A0672F.3090702@timgolden.me.uk> Message-ID: <15183205.post@talk.nabble.com> Thanks all! This is terrific, and a quick response... I have to go with the 2.4 version, but thanks to everyone... Tim Golden-4 wrote: > > washakie wrote: >> Hello, >> >> I have a list of datetime objects: DTlist, I have another single datetime >> object: dt, ... I need to find the nearest DTlist[i] to the dt .... is >> there a simple way to do this? There isn't necessarily an exact match... > > > import datetime > > dates = [datetime.date (2007, 1, (1+i)*2) for i in range (10)] > one_date = datetime.date (2007, 1, 7) > > print sorted (dates, key=lambda x: abs (x-one_date))[0] > > > > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/find-nearest-time-in-datetime-list-tp15180398p15183205.html Sent from the Python - python-list mailing list archive at Nabble.com. From dwblas at gmail.com Mon Jan 14 12:50:14 2008 From: dwblas at gmail.com (dwblas at gmail.com) Date: Mon, 14 Jan 2008 09:50:14 -0800 (PST) Subject: time.time or time.clock References: Message-ID: <87bab627-9fb4-4a39-9f44-08b8697384d2@i3g2000hsf.googlegroups.com> """ time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't high enough resolution on windows. Take a look at datetime. It is good to the micro-second on Linux and milli-second on Windows. """ import datetime begin_time=datetime.datetime.now() for j in range(100000): x = j+1 # wait a small amount of time print "Elapsed time =", datetime.datetime.now()-begin_time ## You can also access the individual time values print begin_time.second print begin_time.microsecond ## etc. From haraldarminmassa at gmail.com Tue Jan 22 09:14:41 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Tue, 22 Jan 2008 06:14:41 -0800 (PST) Subject: building psycopg2 on windows using mingw, "cannot find -lpq" References: Message-ID: <1095e286-cebe-4249-af42-8053a2e44417@d70g2000hsb.googlegroups.com> > I use psycopg2 all the time on windows. I use the binary installer > instead of source. Works great for me. > > -Tom Me2. Just in 7 out of 200 it does not work with the currently available binary installer, on some startups, so I decided to follow a recommendation out of the psycopg2 list to compile it from trunk :( Harald From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 9 07:19:55 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 09 Jan 2008 13:19:55 +0100 Subject: Learning Python via a little word frequency program In-Reply-To: References: Message-ID: <4784bbea$0$17616$426a74cc@news.free.fr> Andrew Savige a ?crit : > I'm learning Python by reading David Beazley's "Python Essential Reference" > book and writing a few toy programs. To get a feel for hashes and sorting, > I set myself this little problem today (not homework, BTW): > > Given a string containing a space-separated list of names: > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > > produce a frequency table of names, sorted descending by frequency. > then ascending by name. For the above data, the output should be: > > kevin : 3 > jock : 2 > andrew : 1 > bill : 1 > fred : 1 > freddy : 1 > > Here's my first attempt: > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > freq = {} > for name in names.split(): > freq[name] = 1 + freq.get(name, 0) > deco = zip([-x for x in freq.values()], freq.keys()) > deco.sort() > for v, k in deco: > print "%-10s: %d" % (k, -v) > > I'm interested to learn how more experienced Python folks would solve > this little problem. For a one-shot Q&D script: names = "freddy fred bill jock kevin andrew kevin kevin jock" freqs = [(- names.count(name), name) for name in set(names.split())] print "\n".join("%-10s : %s" % (n, -f) for f, n in sorted(freqs)) Now I might choose a very different solution for a more serious application, depending on detailed specs and intended use of the "frequency table". > Though I've read about the DSU Python sorting idiom, > I'm not sure I've strictly applied it above ... Perhaps not "strictly" since you don't really "undecorate", but that's another application of the same principle : provided the appropriate data structure, sort() (or sorted()) will do the right thing. > and the -x hack above to > achieve a descending sort feels a bit odd to me, though I couldn't think > of a better way to do it. The "other" way would be to pass a custom comparison callback to sort, which would be both slower and more complicated. Your solution is IMHO the right thing to do here. > I also have a few specific questions. Instead of: > > for name in names.split(): > freq[name] = 1 + freq.get(name, 0) > > I might try: > > for name in names.split(): > try: > freq[name] += 1 > except KeyError: > freq[name] = 1 or a couple other solutions, including a defaultdict (python >= 2.5). > Which is preferred? It's a FAQ - or it should be one. Globally: the second one tends to be faster when there's no exception (ie the key already exists), but slower when exceptions happen. So it mostly depends on what you expect your dataset to be. Now note that you don't necessarily need a dict here !-) > Ditto for: > > deco = zip([-x for x in freq.values()], freq.keys()) > > versus: > > deco = zip(map(operator.neg, freq.values()), freq.keys()) As far as I'm concerned, I'd favor the first solution here. Reads better IMHO > Finally, I might replace: > > for v, k in deco: > print "%-10s: %d" % (k, -v) > > with: > > print "\n".join("%-10s: %d" % (k, -v) for v, k in deco) That's what I'd do here too - but it depends on context (ie: for huge datasets and/or complex formating, i'd use a for loop). From yuri.feldman at gmail.com Thu Jan 17 07:14:38 2008 From: yuri.feldman at gmail.com (yuri.feldman at gmail.com) Date: Thu, 17 Jan 2008 04:14:38 -0800 (PST) Subject: Embedding Python - Freeing Python Objects Not Using Py_DECREF Message-ID: Hello, I'm embedding Python interpreter in a Win32 console application. I use C++. I would like to use the WinAPI LoadLibrary function to load the python dll at runtime (followed by GetProcAddress calls), so that I have to make no assumptions about the location of the dll. However I can't use the macro Py_DECREF if I load the dll this way. Is there a way to properly free python objects (specifically - dictionaries created by PyDict_New() and the object returned by PyRun_String()) not using Py_DECREF? Alternatively, is there a way to include the python header - to make the macro Py_DECREF available, but to be able to locate the python dll whenever python is installed? (The problem is that python may be installed anywhere, and the python dll does not always appear in system folders - sometimes it is in the python installation directory, thus it is unclear which targets to specify to the linker to search for the dll). I'd appreciate any help. Thanks in advance, From jr9445 at ATT.COM Thu Jan 24 13:24:32 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 24 Jan 2008 12:24:32 -0600 Subject: piping into a python script In-Reply-To: <200801241903.20082.donn.ingle@gmail.com> References: <668bb39a0801240845k70174c44xfb54d519f5c3ffe2@mail.gmail.com> <200801241903.20082.donn.ingle@gmail.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Donn > Sent: Thursday, January 24, 2008 12:03 PM > To: Micha? Bentkowski > Cc: python-list at python.org > Subject: Re: piping into a python script > > I have tested getopt and it strips the lone '-' out. I can get it from Try 'foo.py -- -'. The '--' normally tells the parser to stop parsing args. Ex: date > -foo.txt; rm -foo.txt; rm -- -foo.txt I think this will tell you if stdin is being piped in or not: import sys import os print os.isatty(sys.stdin.fileno()) D:\>type a.txt | python a.py False D:\>python a.py True Also if you're lazy, look at the StringIO class: if options.filelist is None and len(args) < 1: # read from stdin f = sys.stdin elif options.filelist is not None and len(args) < 1: # read filenames from file f = open(options.filelist, 'r') elif options.filelist is None and len(args) > 0: # filenames on command line f = StringIO.StringIO('\n'.join(args)) else: ## Thanks for playing. parser.print_help() exit(1) if f: for filename in f: > -- Segio Aragones (Groo the Wanderer Number 99) Ah yes, Groo. Ever wonder who would win if Groo and Forrest Gump fought each other? From mail at timgolden.me.uk Sun Jan 13 22:02:38 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 14 Jan 2008 03:02:38 +0000 Subject: How to get user home directory on Windows In-Reply-To: <478ab8a1$0$20930$e4fe514c@dreader19.news.xs4all.nl> References: <478ab8a1$0$20930$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <478AD0CE.4060406@timgolden.me.uk> Martin P. Hellwig wrote: > Giampaolo Rodola' wrote: >> Hi all, >> I'm trying to use the pywin32 extension to find out the user's home >> directory but currently I didn't find a solution yet. >> What I'd need to do is not getting the home directory of the currently >> logged in user but something like: >> >>>>> get_homedir("frank") >> "C:\home\users\frank" >>>>> get_homedir("josh") >> "C:\home\users\josh" >> >> Is there a way to do that? >> I tried to search through the Pywin32 documentation with no luck. >> In addition I'm not practiced with the Windows API at all. > > Well, windows, to my knowledge, uses the same base path for all profiles > (this is not true for the My Documents folder which can differ). So what > you could do is get the location from the ALLUSERPROFILE environment > variable, go one folder higher and iterate through that. > Ignoring the folders for the 'pseudo' users: 'All Users', 'Default > User', 'LocalService' and 'NetworkService'. The trouble with that is that any particular user's profile can be specifically overridden. I'm not attached to an AD network here, but I think a networked user's profile can be network based (whike a local user's won't be, say). And there are other ways to change the profile too, down to hacking the registry as described here: http://support.microsoft.com/kb/314843/#XSLTH3129121125120121120120 That said, it'll probably work for a lot of the people for a lot of the time. TJG From hinds.ja at gmail.com Thu Jan 3 10:55:17 2008 From: hinds.ja at gmail.com (hinds.ja at gmail.com) Date: Thu, 3 Jan 2008 07:55:17 -0800 (PST) Subject: Insert to a clob field using cx_Oracle via a stored procedure References: <87860f02-9c78-4248-8d30-c13c91a59f00@i29g2000prf.googlegroups.com> Message-ID: On Jan 2, 2:01?pm, hinds... at gmail.com wrote: > Hello, > > Does anyone have experience using cx_Oracle to call a stored procedure > that inserts to a clob field? ?We have done this successfully via > straight SQL, but we are at a loss on how to do the same insert using > a stored procedure call. ?Any assistance would be much appreciated. > Thanks. > > Jason Found a solution to this - see the following thread if you interested. http://forums.oracle.com/forums/thread.jspa?forumID=376&threadID=601700 From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 9 06:45:05 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 09 Jan 2008 12:45:05 +0100 Subject: How a smart editor could make "Postfix type declarations PEP3117" in Python3000 more readable In-Reply-To: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> References: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> Message-ID: <4784b3c0$0$18795$426a74cc@news.free.fr> aspineux a ?crit : > Hi > > I read the PEP 3117 about the new "Postfix type declarations" in > Python3000. > THIS PEP as been REJECTED ! Indeed - it's an april's fool joke !-) And BTW, no need to scream, we hear you pretty well. > But ... > > The notation in the PEP is very ugly ! This make python code more > difficult to read! > > Anyway when I switched to python (from C, C++, ..), I suffered a lot > of the > untyped python variables. > And I think this is a good idea to include > typing in python. The concept of "type" greatly differs between static typing and dynamic typing. FWIW, it also somewhat differs between declarative static type systems (C/C++/Java/etc) and inference-based static type systems (OCaml, Haskell etc). Anyway, Python is dynamically typed (FWIW, it's dynamic almost everywhere), and this is probably not going to change in a foreseeable future. So I guess you'd better learn to use dynamic typing instead of trying to write C++ in Python - or, if you just can't get used to dynamic typing, use another language. From kyosohma at gmail.com Fri Jan 4 16:05:46 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 4 Jan 2008 13:05:46 -0800 (PST) Subject: Tabnanny errors when Migrating Python 2.4 code to 2.5 References: <6d197192-0340-42f8-b764-cba91a92bb21@i3g2000hsf.googlegroups.com> Message-ID: On Jan 4, 2:06 pm, John Machin wrote: > On Jan 5, 3:56 am, kyoso... at gmail.com wrote: > > > Hi, > > > When Python 2.5 first came out, I eagerly downloaded it and > > immediately had issues with getting it to run my 2.4 code. So I just > > stuck to 2.4. However, I decided this week that I really should try to > > get 2.5 to work. Does anyone know why code that works perfectly for > > months in a 2.4 environment throws indentation errors in 2.5? > > No, not until you go to the bother of reproducing the problem with a > small file, tell us what platform you are on, how you are running this > code (IDLE, shell prompt, ...), how you installed Python 2.5 > (2.5.1?), ... I'm using Windows XP, using IDLE (which was mentioned already) and I downloaded the 2.5.1 exe/msi file from python.org to install it. I have yet to find a simple one which exhibits the issue to post. It seems to happen to my complex files, not the simple ones. Sorry to bother you. Mike From george.sakkis at gmail.com Fri Jan 18 12:50:40 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 18 Jan 2008 09:50:40 -0800 (PST) Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <54b11613-6b9c-4cb8-838c-d3e01699bf3d@e4g2000hsg.googlegroups.com> On Jan 18, 12:15 pm, David Sanders wrote: > Hi, > > I am processing large files of numerical data. Each line is either a > single (positive) integer, or a pair of positive integers, where the > second represents the number of times that the first number is > repeated in the data -- this is to avoid generating huge raw files, > since one particular number is often repeated in the data generation > step. > > My question is how to process such files efficiently to obtain a > frequency histogram of the data (how many times each number occurs in > the data, taking into account the repetitions). My current code is as > follows: > > ------------------- > #!/usr/bin/env python > # Counts the occurrences of integers in a file and makes a histogram > of them > # Allows for a second field which gives the number of counts of each > datum > > import sys > args = sys.argv > num_args = len(args) > > if num_args < 2: > print "Syntaxis: count.py archivo" > sys.exit(); > > name = args[1] > file = open(name, "r") > > hist = {} # dictionary for histogram > num = 0 > > for line in file: > data = line.split() > first = int(data[0]) > > if len(data) == 1: > count = 1 > else: > count = int(data[1]) # more than one repetition > > if first in hist: # add the information to the histogram > hist[first]+=count > else: > hist[first]=count > > num+=count > > keys = hist.keys() > keys.sort() > > print "# i fraction hist[i]" > for i in keys: > print i, float(hist[i])/num, hist[i] > --------------------- > > The data files are large (~100 million lines), and this code takes a > long time to run (compared to just doing wc -l, for example). > > Am I doing something very inefficient? (Any general comments on my > pythonic (or otherwise) style are also appreciated!) Is > "line.split()" efficient, for example? Without further information, I don't see anything particularly inefficient. What may help here is if you have any a priori knowledge about the data, specifically: - How often does a single number occur compared to a pair of numbers ? E.g. if a single number is much more common that a pair, you can avoid split() most of the times: try: first,count = int(line), 1 except ValueError: first,count = map(int,line.split()) Similarly if the pair is much more frequent than the single number, just invert the above so that the common case is in the 'try' block and the infrequent in 'except'. However if the two cases have similar frequency, or if you have no a priori knowledge, try/except will likely be slower. - What proportion of the first numbers is unique ? If it's small enough, a faster way to update the dict is: try: hist[first]+=count except KeyError: hist[first] = 1 > Is a dictionary the right way to do this? In any given file, there is > an upper bound on the data, so it seems to me that some kind of array > (numpy?) would be more efficient, but the upper bound changes in each > file. Yes, dict is the right data structure; since Python 2.5, collections.defaultdict is an alternative. numpy is good for processing numeric data once they are already in arrays, not for populating them. George From bronger at physik.rwth-aachen.de Mon Jan 28 02:04:05 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 28 Jan 2008 08:04:05 +0100 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> Message-ID: <87lk6a8m8q.fsf@physik.rwth-aachen.de> Hall?chen! Dustan writes: > On Jan 27, 12:41 pm, Torsten Bronger > wrote: > >> [...] >> >> Well, you save one or two lines per class. Not enough in my >> opinion. > > Are you referring to the alternate syntax or to the decorator? > Either way, you could be saving 4 or 5 or more lines, if you have > enough arguments. Mostly, I write them in one or two lines, e.g. def __init__(self, id, kind, person, feedname): self.id, self.kind, self.person = id, kind, person (Sometimes I break after the "=".) Still, I don't think that this at-most-once-per-class use case justifies a special syntax (whether within the current language or not) that everyone else has to learn, too. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From boblatest at yahoo.com Wed Jan 9 07:33:42 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 12:33:42 GMT Subject: How does unicode() work? Message-ID: <5ujt96F1i6h37U1@mid.dfncis.de> Here's a test snippet... import sys for k in sys.stdin: print '%s -> %s' % (k, k.decode('iso-8859-1')) ...but it barfs when actually fed with iso8859-1 characters. How is this done right? robert From kay.schluehr at gmx.net Wed Jan 30 02:53:21 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 29 Jan 2008 23:53:21 -0800 (PST) Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> <479e0225$0$36389$742ec2ed@news.sonic.net> <70c4064a-a65d-4fd5-b39c-38e6a3fb567b@i7g2000prf.googlegroups.com> <479fb907$0$25376$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Jan 30, 12:38 am, Wildemar Wildenburger wrote: > > Python has a JIT right no > > You mean in the Java-sense (outputting native machine code)? > > /W Sure. http://psyco.sourceforge.net/ From antroy at gmail.com Tue Jan 29 05:00:13 2008 From: antroy at gmail.com (Ant) Date: Tue, 29 Jan 2008 02:00:13 -0800 (PST) Subject: Python self-evaluating strings References: Message-ID: <20d655ca-0c5d-4f4a-b42c-89b47e00e0de@h11g2000prf.googlegroups.com> In the spirit of "Simple is better than complex." and totally bypassing the intention of quines (though not necessarily the definition): --- probably_not_a_real_quine.py ---- import sys for line in open(sys.argv[0]): print line, -------------------------------------- ;-) -- Ant. From nicola.musatti at gmail.com Fri Jan 4 04:35:25 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Fri, 4 Jan 2008 01:35:25 -0800 (PST) Subject: Who's to blame? References: <92dfc2fc-0677-43c0-b34f-4f240fa40205@e4g2000hsg.googlegroups.com> <255d32d0-43f5-4d34-a074-b87082dc6043@e23g2000prf.googlegroups.com> Message-ID: <2b076973-b132-4666-a163-b80bcbeaedfb@s8g2000prg.googlegroups.com> Hallo, Mike. First of all, thanks to both you and Rob for your answers. I now see that the wxPython group would have been a better place to post to, all the more so given the tight connection between the wxPython and wxWidgets projects, of which at first I wasn't aware. On Jan 3, 8:19 pm, kyoso... at gmail.com wrote: [...] > I've never created a modal dialog like this. Instead, I follow the > wxPython in Action book examples (most of the time), which would do a > yes/no dialog like this: > > > > dlg = wx.MessageDialog(None, 'Some Message', 'A Message Box', > wx.YES_NO | wx.QUESTION) > retCode = dlg.ShowModal() > if retCode == wx.ID_YES: > # do something > print 'yes' > else: > # do something else > print 'no' > dlg.Destroy() > > Actually my example started out as something like if wx.MessageBox(message="Some message", caption="Some caption", style=wx.YES|wx.NO) == wx.YES: pass I had to change it because the actual message can become very long, so I assembled a dialog with a scrollable text field. Maybe I'm expecting to much of wxStdDialogButtonSizer, but I still feel that given that both your method and mine above work straight away, it should provide the same behaviour with Yes/No buttons as with OK/Cancel ones. Cheers, Nicola Musatti From jeba.ride at gmail.com Tue Jan 15 23:09:37 2008 From: jeba.ride at gmail.com (Clement) Date: Tue, 15 Jan 2008 20:09:37 -0800 (PST) Subject: Asynchronous HTTP Message-ID: <6e33f161-1bba-437b-a3ca-e7bec80089ed@m34g2000hsb.googlegroups.com> Can i use asynchttp for http secure connection... If so plz how does it can be done. Is there any other library can do that that.... From nagle at animats.com Fri Jan 18 02:03:18 2008 From: nagle at animats.com (John Nagle) Date: Thu, 17 Jan 2008 23:03:18 -0800 Subject: Cannot catch _mysql_exceptions.OperationalError In-Reply-To: <5f435c88-ef42-4ca9-921a-675393824ccc@k39g2000hsf.googlegroups.com> References: <5f435c88-ef42-4ca9-921a-675393824ccc@k39g2000hsf.googlegroups.com> Message-ID: <47904de2$0$36326$742ec2ed@news.sonic.net> Bob wrote: > In our database code (we are using django v0.96) we wanted to catch > and handle MySQL OperationalErrors. We use both the Django models and > database connections. > > However, even though we confirmed that a > _mysql_exceptions.OperationalError are raised (particularly 1213 > deadlock), we cannot catch them with try/except. If you're using MySQLdb, it works fine: try: ... do database operations except MySQLdb.OperationalError, message: # handle trouble errorcode = message[0] # get MySQL error code if errorcode == kmysqlduplicateentry : # if dup on insert ... deal with duplicate entry If Django has a problem, you'll have to take that up with them. John Nagle From deets at nospam.web.de Thu Jan 3 08:07:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 14:07:27 +0100 Subject: reassign to builtin possible !? References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> Message-ID: <5u450fF1gldn9U2@mid.uni-berlin.de> Bernhard Merkle wrote: > Hi there, > > I am reading Learning Python 3e from Mark Lutz and just found out that > reassigning to builtins is possible. > What is the reason, why Python allows this ? IMO this is very risky > and can lead to hard to find errors. > (see also Learning Python 3e, Chapter 16, Page 315) > >>>> True > True >>>> False > False >>>> True = 1 >>>> True > 1 >>>> True = 0 >>>> True > 0 This hal always been possible. But it's not reassigning, it's shadowing - which is a totally different beast. Shadowing builtins is bad style, but lokal to your context. Which can get nasty of course, if you do the above on e.g. module level. But you can't alter the values for True/False globally with this. Diez From sergio.correia at gmail.com Fri Jan 18 20:38:24 2008 From: sergio.correia at gmail.com (Sergio Correia) Date: Fri, 18 Jan 2008 20:38:24 -0500 Subject: I don't understand what is happening in this threading code In-Reply-To: References: Message-ID: This is what's happening: 1) The chef thread releases the sema 2) While the chef thread is saying "Andiamo", decreasing "i", and ending the while loop, the waiter thread SERVES the dish and RUNS to reacquire the lock 3) Back in the main loop, chef.join() is run, and then the waiter's variable is changed. But it's already too late. The waiter is already locked. He'll wait and wait forever for another dish, which will never come. So you will have to kill him. All for a race condition. --- I've just read Carl's post (just b4 hitting submit). I agree with him, rewrite the logic. IMO, the objects should be the key, THEY are the ones that should be joined. You should run the chef and waiter as daemons, and just do something like orders.join() dishes.join() And when the chefs finishes with the orders and the waiter finishes serving them, the program ends. HTH, Sergio On Jan 18, 2008 7:43 PM, Matthew Wilson wrote: > In this code, I tried to kill my thread object by setting a variable on it > to False. > > Inside the run method of my thread object, it checks a different > variable. > > I've already rewritten this code to use semaphores, but I'm just curious > what is going on. > > Here's the code: > > import logging, threading, time > logging.basicConfig(level=logging.DEBUG, > format="%(threadName)s: %(message)s") > > class Waiter(threading.Thread): > def __init__(self, hot_food): > super(Waiter, self).__init__() > self.should_keep_running = True > self.hot_food = hot_food > > def run(self): > while self.should_keep_running: > logging.debug("Inside run, the id of should_keep_running is %s." > % id(self.should_keep_running)) > self.hot_food.acquire() > > def cook_food(hot_food): > i = 5 > while i >= 0: > logging.debug("I am cooking food...") > time.sleep(1) > hot_food.release() > logging.debug("Andiamo!") > i -= 1 > > def main(): > > hot_food = threading.Semaphore(value=0) > > chef = threading.Thread(name="chef", target=cook_food, args=(hot_food, )) > chef.start() > > w = Waiter(hot_food) > logging.debug("Initially, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > w.start() > logging.debug("After start, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > > # Wait for the chef to finish work. > chef.join() > > # Now try to kill off the waiter by setting a variable inside the waiter. > w.should_keep_running = False > logging.debug("Now, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > > if __name__ == "__main__": > main() > > And here's what I get when I execute it. I have to suspend the process > with CTRL=Z and then kill -9 it. > > $ python foo.py > MainThread: Initially, the id of w.should_keep_running is 135527852. > MainThread: After start, the id of w.should_keep_running is 135527852. > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > Thread-1: Inside run, the id of should_keep_running is 135527852. > MainThread: Now, the id of w.should_keep_running is 135527840. > > [1]+ Stopped python foo.py > > $ kill -9 %1 > > [1]+ Stopped python foo.py > > The memory address of should_keep_running seems to change when I set it > from True to False, and inside the run method, I keep checking the old > location. > > I am totally baffled what this means. > > Like I said earlier, I already rewrote this code to use semaphores, but > I just want to know what is going on here. > > Any explanation is welcome. > > TIA > > Matt > -- > http://mail.python.org/mailman/listinfo/python-list > From Matthew_WARREN at bnpparibas.com Mon Jan 28 05:36:34 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Mon, 28 Jan 2008 10:36:34 +0000 Subject: finding child cpu usage of a running child In-Reply-To: Message-ID: had to say, that subject conjoured up an interesting image in my head :) 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 michael at stroeder.com Tue Jan 29 04:10:01 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 29 Jan 2008 10:10:01 +0100 Subject: Encryption Recommendation In-Reply-To: <606aj3F1pa0tfU1@mid.uni-berlin.de> References: <6b40b773-8554-4e9c-838f-e6934212d16e@n20g2000hsh.googlegroups.com> <606aj3F1pa0tfU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > rogerrath2 at gmail.com wrote: > >> I'm still using Python 2.4. In my code, I want to encrypt a password >> and at another point decrypt it. What is the standard way of doing >> encryption in python? Is it the Pycrypto module? > > Usually, one doesn't store clear-text passwords. Instead, use a > hash-algorithm like md5 or crypt (the former is in the standard lib, don't > know of the other out of my head) and hash the password, and store that > hash. > > If a user enters the password, use the same algorithm, and compare the > resulting hashes with the stored one. And don't forget to add a salt so that same passwords do not have the same hash. But if the password checking is done with a challenge-response mechanism (e.g. HTTP-Digest Auth or SASL with DIGEST-MD5) it's required that the instance checking the password has the clear-text password available. So reversible encryption for storing passwords might be required. Ciao, Michael. From paul.hankin at gmail.com Fri Jan 25 04:44:57 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Fri, 25 Jan 2008 01:44:57 -0800 (PST) Subject: Which is more pythonic? References: <56518bb9-1d56-47c3-8112-6e0778832c12@v29g2000hsf.googlegroups.com> Message-ID: <7c2cc4fa-351a-4350-a20b-2f94b5a37c15@c23g2000hsa.googlegroups.com> benjamin.zimmerman at gmail.com wrote: > I have a goal function that returns the fitness of a given solution. I > need to wrap that function with a class or a function to keep track of > the best solution I encounter. Which of the following would best serve > my purpose and be the most pythonic? You could write a function that generates your trial solutions and use max. Eg: instead of using your Goal class: def f(score_function): goal = Goal(score_function) while there's more solutions: ... produce trial solution goal(trial_solution) return goal.best Write a solution generator... def all_solutions(): while there's more solutions: ... produce trial solution yield trial_solution ...and find the best using best = max(all_solutions(), key = score_function) This uses a builtin rather than either of the snippets in the original post, and it's also a much cleaner approach. -- Paul Hankin From rridge at caffeine.csclub.uwaterloo.ca Fri Jan 11 09:37:41 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 11 Jan 2008 09:37:41 -0500 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >fact 1: CPython compiles source code to byte-code. >fact 2: CPython executes this byte-code. >fact 3: Sun's JDK compiles source code to byte-code. >fact 4: Sun's JDK executes this byte-code. > >Care to prove me wrong on any of these points ? Don't bother: you can't. >So my first assertion that "CPython is compiled to byte-code, which is >then executed by a VM" is true, and since the same assertion also stands >for Java (ie: sun's JDK), then the "just like" qualifier is true too. >Period. No, the "just like" qualifier is false. Python doesn't compile "just like" Java, nor does it execute "just like" Java. The "byte-code" langauges are very different and they perform much differently. Java compiles slower but executes faster. Python's byte-code is ment to quickly generated on the fly to save having to reparse the source code. Java code is compiled using optimizations into a virtual machine languague ment to be executed as fast as possible on a wide range of processors. The similarities between the two are superficial, Python doesn't compile and execute code "just like" Java. Try all you want to try to reparse what you wrote in to a different meaning, it doesn't change the fact your intent was to mislead. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From mtobis at gmail.com Fri Jan 11 22:36:24 2008 From: mtobis at gmail.com (Michael Tobis) Date: Fri, 11 Jan 2008 19:36:24 -0800 (PST) Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> <13og1lgcespv6c2@corp.supernews.com> <13oga52q3f2gg1c@corp.supernews.com> Message-ID: On Jan 11, 8:40 pm, Steven D'Aprano wrote: > Read the OP's post again. His (her?) users aren't expected to create the > toolkit, merely to use it. To create good toolkits you need both a master > programmer and an expert in the field. It is an advantage if they are the > same person. But to use such a good toolkit, you shouldn't need to be a > master programmer. It appears we are in agreement, then. But that leaves me in a position where I can't understand your complaint. There's no reason I can see for the sort of compromise you ask for. Clean abstractions benefit from their cleanliness. Of course the users will have a lot to learn regardless, but that's the point. A user has to decide whether to take on a new tool. If that learning is about meaningless incantations (the way beginning programmers are currently taught to say "abracadabra public static void main") users will be less impressed with the advantage of the abstractions and be less likely to engage the new methods on offer. If the learning exposes new potential, that makes your tool more attractive. What's more, the next higher layer of abstraction will be easier to compose if the composer of that abstraction doesn't have to make the sort of compromise you suggest. Abstractions that stay out of the way until you need to expand on them is a big part of what Python is all about. It's not clear that this is the sort of application where cutting corners makes sense, so I don't see how your advice is justified. mt From eefacm at gmail.com Wed Jan 16 15:01:43 2008 From: eefacm at gmail.com (eefacm at gmail.com) Date: Wed, 16 Jan 2008 12:01:43 -0800 (PST) Subject: Perl Template Toolkit: Now in spicy new Python flavor References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> <13a75830-5416-4fe3-9460-018e1240e6e6@e32g2000prn.googlegroups.com> Message-ID: On Jan 15, 1:45 pm, George Sakkis wrote: > > eef... at gmail.com wrote: > > > I'd like to inform the Python community that the powerful and popular > > > Template Toolkit system, previously available only in its original > > > Perl implementation, is now also available in a beta Python > > > implementation: > > > >http://tt2.org/python/index.html > > > > I created this port both as a fun programming project, and for use in > > > environments where Perl is not available, for reasons technical, > > > cultural, or otherwise. The extensive Perl test suites have also been > > > ported, and most templates require no or very little modification. > How does it compare with other "mainstream" Python template engines > such as Cheetah, Mako, etc. ? I can't claim a comprehensive familiarity with Python template offerings, but all of the packages approved for use at my previous workplace left me cold. The most popular were ClearSilver and Django, and both felt horribly limiting compared to the Template Toolkit, which I became acquainted with when hacking on Bugzilla some years ago. Neither supports what I would consider very basic operations on the template data. Nothing like the following can be expressed in those packages: from pprint import PrettyPrinter from template import Template print Template().processString( "the list is [% a.pformat(b(c + d)) %]", { "a": PrettyPrinter(2, 40), "b": range, "c": 10, "d": 20 } ) Here we have a template that includes a method call, a function call, and simple addition. Neither Django nor ClearSilver can manage any of these three things. Both of those packages offer other features not found in the Template Toolkit; it was the relative impotence of the templating systems that drove me to attack the translation. > Unless I missed it, the documentation > covers the Perl version only. The online documentation, yes. All source-level documentation (from which the online documentation is largely drawn) has been converted into Python docstrings in the source code. They can be read by browsing the Subversion repository or by importing the code and using help(); eg: >>> import template.stash >>> help(template.stash) ... module docs ... >>> help(template.stash.Stash) ... class docs ... >>> help(template.stash.Stash.get) ... method docs ... From paul.hankin at gmail.com Mon Jan 14 08:03:23 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 14 Jan 2008 05:03:23 -0800 (PST) Subject: ucs2 or ucs4? References: Message-ID: <3430dce1-27da-471c-98c4-418170544c08@s12g2000prg.googlegroups.com> On Jan 14, 12:56 pm, Neal Becker wrote: > How do I tell if my python-2.5 is build with ucs2 or ucs4? See if unichr(0x10000) raises ValueError: if it does, you're ucs2. -- Paul Hankin From scrdhrt at gmail.com Fri Jan 18 05:25:06 2008 From: scrdhrt at gmail.com (Sacred Heart) Date: Fri, 18 Jan 2008 02:25:06 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <7xr6gguwiq.fsf@ruckus.brouhaha.com> Message-ID: <75a76c52-1b07-4b77-8ba9-2ca09db7b1e1@p69g2000hsa.googlegroups.com> On Jan 17, 7:39 pm, Paul Rubin wrote: > Sacred Heart writes: > > array1 = ['one','two','three','four'] > > array2 = ['a','b','c','d'] > > > I want to loop through array1 and add elements from array2 at the end, > > so it looks like this: > > > one a > > two b > > three c > > four c > > The "functional" style is to use the zip function that someone > described. The old-fashioned way is simply: > > n = len(array1) > for i in xrange(n): > print array1[i], array2[i] > > You can modify this in various ways if the lengths of the lists are > not equal. E.g. Thank you Paul, and everybody else contributing with answers of various complexity. Although a whole bunch of them was way too complex for my simple problem, but that's ok. I now know how to use map and zip, and also learned some tips and tricks. Thanks. All the best, SH From ggpolo at gmail.com Wed Jan 23 17:18:25 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jan 2008 20:18:25 -0200 Subject: Creating new types and invoking super In-Reply-To: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> References: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> Message-ID: 2008/1/23, Arnaud Delobelle : > On Jan 23, 8:55 pm, "Guilherme Polo" wrote: > > Hello, > > Hi > [...] > > First I tried this: > > > > def init(func): > > def _init(inst): > > super(inst.__class__, inst).__init__() > > func(inst) > > > > return _init > > > > class A(object): > > @init > > def __init__(self): pass > > This kind of approach can't work, you need to call super(A, obj). > super(type(obj), obj) is pointless, it defeats the whole purpose of > the mro! > Yeh, as shown in the next examples in the previous email. Using a decorator for that doesn't sound useful at all, was just trying something different ;) I will stick to the no-decorator option. > The only way I can think of would be to create a metaclass, but I > don't think it's worth it. super(A, obj).__init__() isn't that bad! > Metaclass doesn't apply here because metaclass is related to class-construction. This is related to instance initialization, and I'm creating the types as the user asks. > -- > Arnaud > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From ejensen at visi.com Thu Jan 10 15:47:07 2008 From: ejensen at visi.com (Ed Jensen) Date: Thu, 10 Jan 2008 20:47:07 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> Message-ID: <13od12b23hfv772@corp.supernews.com> Bruno Desthuilliers wrote: > I fail to see how the existence of JIT compilers in some Java VM changes > anything to the fact that both Java (by language specification) and > CPython use the byte-code/VM scheme. While your answer was technically correct, by omitting pertinent information, your answer lead readers to the wrong conclusion. The only question that remains is if you were being accidentally misleading or purposefully misleading. From robin at alldunn.com Thu Jan 24 12:58:09 2008 From: robin at alldunn.com (Robin Dunn) Date: Thu, 24 Jan 2008 09:58:09 -0800 Subject: [wxPython-users] Issue with docking wx.listctrl window In-Reply-To: References: Message-ID: <4798D1B1.7020908@alldunn.com> tarun wrote: > Hello All, > > I'm trying to create a Frame with AuiManager. The code is attached. > > *Problem:* > - I want 2 windows to be docked in the frame. One is a text control and > other is a list control. > - The text control gets docked, but on trying to dock the list control, > all the tabs dis-appear. > The tabs appear only when the list control window is kept floating. > > In the attached code the list control window is kept floating. This can > be docked > To see the issue with docking, comment line 33 and un-comment line 35 in > the attached file and then try to execute, the issue would be clearly > visible. On un-docking the window1, the tabs again appear.. > > *Please let me the solution to this ASAP* The main problem is that you are putting the listctrl on a panel, but you are telling AUI to manage the listctrl, not the panel. If I understand correctly then your other problems stem from that as well. Try passing self.log to AddPane, instead of self.log.list. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From princismo at gmail.com Mon Jan 21 23:33:30 2008 From: princismo at gmail.com (=?Big5?B?w0P4rw==?=) Date: Mon, 21 Jan 2008 20:33:30 -0800 (PST) Subject: How to solve "TypeError: list indices must be integers". References: <3f3ca8c6-b57c-43ff-bf80-11768e1a0f94@s8g2000prg.googlegroups.com> <9f38b518-20d5-4cc1-bf6d-0be6346d5f64@s27g2000prg.googlegroups.com> Message-ID: <225d984b-1187-467e-9a61-61aef697deeb@q77g2000hsh.googlegroups.com> On 1?22?, ??3?05?, John Machin wrote: > On Jan 22, 3:15 am, "??" wrote: > > > This is more details about my problem, which I running my py script > > for my project. Programming in pythoncard that we can develop a GUI > > based application easily. > > > I was assigned dialog.colorDialog(self) return value to a result > > object, but I suspect that result.color is the attribute of the result > > object that can assign to a string variable. > > The concepts " assigned to a object" > and " can be assigned to a variable" just don't > exist in Python. > > # Initially "name1" isn't bound to anything > name1 = 42 > # "name1" now refers to an int object whose value is 42 > name1 = 'abc' > # "name1" now refers to a str object whose value is 'abc' > name2 = name1 > # "name2" now refers to the same str object > > What is "dialog.colorDialog(self) return value"? What is "a result > object"? Show us the code! > > What is the connection between your last sentence above and the > "TypeError: list indices must be integers" problem? Show us the code! > > > > > There is a error prompt from python console "TypeError: list indices > > must be integers". > > Have any suggestion to solve this problem? > > Communication would be much easier if you show us the line of code > that causes the error message. > > Here are two simple examples of what can trigger that error message: > > >>> a_list = [1, 42, 666] > >>> not_an_integer = None > >>> a_list[not_an_integer] = 9876 > > Traceback (most recent call last): > File "", line 1, in > TypeError: list indices must be integers > > >>> a_name = a_list[not_an_integer] > > Traceback (most recent call last): > File "", line 1, in > TypeError: list indices must be integers > > Look for the pattern a_list[not_an_integer] in the statement that > triggers the exception. > > > > > When I print result.color, it is print out something like (255,0,0). > > Yes, that's most likely a tuple of (red, green, blue) values ... I'm > not astonished; are you? > > > How to covert result.color into a string? > > How? Use elementary Python functionality, after you've decided what > string representation you want. Examples: > > >>> color = (255, 128, 0) > >>> "red=%d green=%d blue=%d" % color > > 'red=255 green=128 blue=0'>>> '.someclass {background-color: #%02x%02x%02x; }' % color > > '.someclass {background-color: #ff8000; }' > > > > > How to convert a string to > > result.color type? > > Reverse the process. > > Again, what is the connection between "result.color" and the > "TypeError: list indices must be integers" problem? Many thanks, John Machin for your fast reply! Regards, Andreas From mgierdal at gmail.com Fri Jan 18 15:13:44 2008 From: mgierdal at gmail.com (mgierdal at gmail.com) Date: Fri, 18 Jan 2008 12:13:44 -0800 (PST) Subject: how to resolve Windows pathnames into cygwin ones References: <2ba97fb6-6bef-44aa-937b-2aa9582e4341@e4g2000hsg.googlegroups.com> <13p1m36m9htom5f@corp.supernews.com> <09ba7d26-d411-4bc5-9518-78a882882c66@q39g2000hsf.googlegroups.com> Message-ID: Well yes, I was hoping for a library function, but none provides it. Thanks for the code. Works nicely. On Jan 18, 12:12 pm, apatheticagnostic wrote: > Here we go then (are forward slashes valid in a filename in windows?) > def path_into_cygpath(path): > drive, destination = path.replace('\\','/').split(':') > return '/cygdrive/' + drive.lower() + destination From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 24 12:50:52 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 24 Jan 2008 18:50:52 +0100 Subject: Duplicating a variable In-Reply-To: References: Message-ID: <4798cfa2$0$31909$426a74cc@news.free.fr> hnessenospam at yahoo.com a ?crit : > I have run into a bit of a subtle problem. How do I go about > duplicating a variable (particularly a list of lists) in python. using the deepcopy function of the copy module. > I > was surprised when simple assignment didn't work. For example, let y = > [1,2,3] > >>>> x = y >>>> x[2] = 5 >>>> y > [1,2,5] Python only uses object references. It never copy anything unless explicitely asked for. From boblatest at yahoo.com Wed Jan 9 06:21:01 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 11:21:01 GMT Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> Message-ID: <5ujp0tF1ehvg2U1@mid.dfncis.de> Fredrik Lundh wrote: > keywords = filter(None, keywords) # get "true" items only Makes seinse. BTW, where can I find all methods of the built-in types? Section 3.6 only talks about strings and mentions the list append() method only in an example. Am I too stupid to read the manual, or is this an omission? robert From gagsl-py2 at yahoo.com.ar Fri Jan 25 17:03:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 Jan 2008 20:03:55 -0200 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> Message-ID: En Thu, 24 Jan 2008 11:57:49 -0200, Peter Schuller escribi?: > In this case my > problem is more related to the "file == module" and "directory == > module" semantics, since I want to break contents in a single module > out into several files. You already can do that, just import the public interfase of those several files onto the desired container module. See below for an example. >> Isn't org.lib.animal a package, reflected as a directory on disk? That's >> the same both for Java and Python. Monkey.py and Tiger.py would be >> modules >> inside that directory, just like Monkey.java and Tiger.java. Aren't the >> same thing? > > No, because in Java Monkey.java is a class. So we have class Monkey in > package org.lib.animal. In Python we would have class Monkey in module > org.lib.animal.monkey, which is redundant and does not reflect the > intended hierarchy. I have to either live with this, or put Monkey in > .../animal/__init__.py. Neither option is what I would want, ideally. You can also put, in animal/__init__.py: from monkey import Monkey and now you can refer to it as org.lib.animal.Monkey, but keep the implementation of Monkey class and all related stuff into .../animal/monkey.py -- Gabriel Genellina From jpeng at block.duxieweb.com Mon Jan 21 23:23:54 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Tue, 22 Jan 2008 12:23:54 +0800 Subject: read files In-Reply-To: References: Message-ID: <47956FDA.30009@block.duxieweb.com> Thank you. That gave so much solutions. And thanks all. Steven D'Aprano ??: > On Tue, 22 Jan 2008 11:00:53 +0800, J. Peng wrote: > >> first I know this is the correct method to read and print a file: >> >> fd = open("/etc/sysctl.conf") >> done=0 >> while not done: >> line = fd.readline() >> if line == '': >> done = 1 >> else: >> print line, >> >> fd.close() > > > The evolution of a Python program. > > # Solution 2: > > fd = open("/etc/sysctl.conf") > done = False > while not done: > line = fd.readline() > if line: > print line, > else: > done = True > fd.close() > > > > # Solution 3: > > fd = open("/etc/sysctl.conf") > while True: > line = fd.readline() > if line: > print line, > else: > break > fd.close() > > > # Solution 4: > > fd = open("/etc/sysctl.conf") > lines = fd.readlines() > for line in lines: > print line, > fd.close() > > > # Solution 5: > > fd = open("/etc/sysctl.conf", "r") > for line in fd.readlines(): > print line, > fd.close() > > > # Solution 6: > > for line in open("/etc/sysctl.conf").readlines(): > print line, > # garbage collector will close the file (eventually) > > > # Solution 7: > > fd = open("/etc/sysctl.conf", "r") > line = fd.readline() > while line: > print line, > line = fd.readline() > fd.close() > > > # Solution 8: > > fd = open("/etc/sysctl.conf", "r") > for line in fd: > print line, > fd.close() > > > # Solution 9: > > for line in open("/etc/sysctl.conf"): > print line, > > > # Solution 10: > # (the paranoid developer) > > try: > fd = open("/etc/sysctl.conf", "r") > except IOError, e: > log_error(e) # defined elsewhere > print "Can't open file, please try another." > else: > try: > for line in fd: > print line, > except Exception, e: > log_error(e) > print "Reading file was interrupted by an unexpected error." > try: > fd.close() > except IOError, e: > # Can't close a file??? That's BAD news. > log_error(e) > raise e > > > > From remco at gerlich.nl Sat Jan 19 07:12:57 2008 From: remco at gerlich.nl (Remco Gerlich) Date: Sat, 19 Jan 2008 13:12:57 +0100 Subject: Excess whitespace in my soup In-Reply-To: <48eb8853-91b3-4c43-8014-a0c624e4c6e7@t1g2000pra.googlegroups.com> References: <48eb8853-91b3-4c43-8014-a0c624e4c6e7@t1g2000pra.googlegroups.com> Message-ID: <7ae3ca10801190412w1648bd24xe9a1f4b85e6d1eb2@mail.gmail.com> Not sure if this is sufficient for what you need, but how about import re re.sub(u'[\s\xa0]+', ' ', s) That should replace all occurances of 1 or more whitespace or \xa0 characters, by a single space. Remco On Jan 19, 2008 12:38 PM, John Machin wrote: > I'm trying to recover the original data from some HTML written by a > well-known application. > > Here are three original data items, in Python repr() format, with > spaces changed to tildes for clarity: > > u'Saturday,~19~January~2008' > u'Line1\nLine2\nLine3' > u'foonly~frabjous\xa0farnarklingliness' > > Here is the HTML, with spaces changed to tildes, angle brackets > changed to square brackets, > omitting \r\n from the end of each line, and stripping a large number > of attributes from the [td] tags. > > ~~[td]Saturday,~19 > ~~January~2008[/td] > ~~[td]Line1[br] > ~~~~Line2[br] > ~~~~Line3[/td] > ~~[td]foonly > ~~frabjous farnarklingliness[/td] > > Here are the results of feeding it to ElementSoup: > > >>> import ElementSoup as ES > >>> elem = ES.parse('ws_soup1.htm') > >>> from pprint import pprint as pp > >>> pp([(e.tag, e.text, e.tail) for e in elem.getiterator()]) > [snip] > (u'td', u'Saturday, 19\n January 2008', u'\n'), > (u'td', u'Line1', u'\n'), > (u'br', None, u'\n Line2'), > (u'br', None, u'\n Line3'), > (u'td', u'foonly\n frabjous\xa0farnarklingliness', u'\n')] > > I'm happy enough with reassembling the second item. The problem is in > reliably and > correctly collapsing the whitespace in each of the above five > elements. The standard Python > idiom of u' '.join(text.split()) won't work because the text is > Unicode and u'\xa0' is whitespace > and would be converted to a space. > > Should whitespace collapsing be done earlier? Note that BeautifulSoup > leaves it as   -- ES does the conversion to \xa0 ... > > Does anyone know of an html_collapse_whitespace() for Python? Am I > missing something obvious? > > Thanks in advance, > John > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Mon Jan 21 12:31:33 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 21 Jan 2008 09:31:33 -0800 Subject: Is there a portable way to tell if data is available on a pipe? In-Reply-To: <47941112$0$36375$742ec2ed@news.sonic.net> References: <47941112$0$36375$742ec2ed@news.sonic.net> Message-ID: <13p9le6nu1u9l4d@corp.supernews.com> John Nagle wrote: > I need some way to find out if a pipe has data available for > a read without blocking if it does not. ... > I'd like to avoid having a thread to manage each pipe, but if I > have to, so be it. Well, without granting your wish, put a Queue.Queue "in front" of each pipe. The per-pipe thread reads a chunk, waiting if it has to, and then writes to the queue. To read from a pipe w/o waiting from one of these assemblies, you can use the get_nowait method on the associated queue. --Scott David Daniels Scott.Daniels at Acm.Org From thierry.volpiatto at gmail.com Sat Jan 19 15:41:59 2008 From: thierry.volpiatto at gmail.com (Thierry Volpiatto) Date: Sat, 19 Jan 2008 21:41:59 +0100 Subject: writing Python in Emacs In-Reply-To: (Terry Jones's message of "Sat, 19 Jan 2008 17:51:50 +0100") References: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> Message-ID: <87zlv14kfc.fsf@thievol.homelinux.org> I add just a note about ipython: if you use a version > 0.6.15 may be you will have a bad output on error like: == " ": instead of: if __name__ == "__main__": all the characters are missing. To avoid that, run in ipython: %upgrade -nolegacy uncomment in ~/.ipython/ipy_user_config.py: import ipy_defaults restart emacs and try a .py with some syntax errors. It should be ok now. Terry Jones writes: >>>>>> "Richard" == Richard Szopa writes: > > Richard> I am a devoted Emacs user and I write a lot in Python. > > Me too. > > Richard> I need the following features: > > Richard> 1) Tab completion, ideally Slime like. That is, when there's not > Richard> enough letters to unambiguously complete a symbol, I want it to > Richard> show a buffer (w/o taking the focus) w/ the possible > Richard> completions. In an ideal world, it would be able to complete > Richard> fo.ba to foo.bar. I imagine this would require quite tight > Richard> Emacs-Python integration. > > I know this is not what you want, but I use hippie expand (M-/) to cycle > through possible completions. It's not Python aware, but it is of some use. > > Richard> 2) Sending the toplevel definition (class or function) to the Python > Richard> buffer. > > I switched to IPython to have better interaction with a spawned Python. > > To use IPython you need to use the Python mode that is NOT the one from > (endorsed?) by the FSF. It gives you some completion (at least in the > *Python* buffer) and you can send pieces of the buffer to the python > process, via py-send-region (C-c |), py-execute-def-or-class (M-C-x), etc. > > Richard> 3) Hints on function/method arguments. IDLE has this done nearly > Richard> right, but the hints are a bit too intrusive for me. I would like to > Richard> see them in the minibuffer. > > I don't have this. > > Richard> 4) (optional) I would like to see the definition of a function > Richard> function or class by hitting M-. on its name. (I understand that > Richard> this may be impossible for methods, as Emacs would have to > Richard> automagically infer the type of the object). > > This is just an emacs tag file need. Have you googled for something like > emacs tags python? The issue of methods might be overcome by just moving > through tags with the same name. Yes, that requires _you_ to know when > you've hit the right thing. That's not optimal, but it's better than > nothing. Ideally you could send the definition to IPython, ask it for the > class info, and use that to jump to the right tag. > > Richard> I have tried a couple of times both python-modes (the one shipped w/ > Richard> Python and the one shipped w/ Emacs), pymacs and stuff like that... > Richard> And, as I said, never got it right. But, maybe I just cannot find the > Richard> way to configure it, and some configuration hints will be enough... > > If you have the time, please summarize your findings. The emacs/python > world has always seemed quite amorphous to me too. > > Terry > _______________________________________________ > help-gnu-emacs mailing list > help-gnu-emacs at gnu.org > http://lists.gnu.org/mailman/listinfo/help-gnu-emacs > -- A + Thierry Pub key: http://pgp.mit.edu From ivan.illarionov at gmail.com Wed Jan 30 21:52:43 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 30 Jan 2008 18:52:43 -0800 (PST) Subject: REALLY simple xml reader References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> Message-ID: >>> from xml.etree import ElementTree as et >>> from decimal import Decimal >>> >>> root = et.parse('file/with/your.xml') >>> debits = dict((debit.attrib['category'], Decimal(debit.find('amount').text)) for debit in root.findall('debit')) >>> >>> for cat, amount in debits.items(): ... print '%s: %s' % (cat, amount) ... food: 24.30 car: 909.56 medical: 188.20 savings: 25 withdrawal: 40 supplies: 10.58 clothes: 31.19 From george.sakkis at gmail.com Tue Jan 22 00:34:28 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 21 Jan 2008 21:34:28 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> Message-ID: <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> On Jan 22, 12:15 am, Paddy wrote: > On Jan 22, 3:20 am, Alan Isaac wrote:> I want to generate sequential pairs from a list. > <> > > What is the fastest way? (Ignore the import time.) > > 1) How fast is the method you have? > 2) How much faster does it need to be for your application? > 3) Are their any other bottlenecks in your application? > 4) Is this the routine whose smallest % speed-up would give the > largest overall speed up of your application? I believe the "what is the fastest way" question for such small well- defined tasks is worth asking on its own, regardless of whether it makes a difference in the application (or even if there is no application to begin with). Just because cpu cycles are cheap these days is not a good reason to be sloppy. Moreover, often the fastest pure Python version happens to be among the most elegant and concise, unlike other languages where optimization usually implies obfuscation. George From sathish.suray at gmail.com Sat Jan 26 08:30:57 2008 From: sathish.suray at gmail.com (sathish.suray at gmail.com) Date: Sat, 26 Jan 2008 05:30:57 -0800 (PST) Subject: nayanthara nake out Message-ID: nayanthara nake out namitha hot photos trisha bathing videos ____________________________ http://www.geocities.com/terfavet/ http://www.geocities.com/terfavet/ http://www.geocities.com/terfavet/ From george.sakkis at gmail.com Wed Jan 23 13:39:25 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 23 Jan 2008 10:39:25 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> Message-ID: On Jan 23, 4:37 am, Steven D'Aprano wrote: > On Tue, 22 Jan 2008 23:33:00 -0800, George Sakkis wrote: > > As I mentioned already, I consider the seeking of the most efficient > > solution a legitimate question, regardless of whether a "dumb" solution > > is fast enough for an application. Call it a "don't be sloppy" principle > > if you wish. > > Sure, by why do you limit "efficient" and "don't be sloppy" to mean > "write the fastest executing code you can, regardless of every other > trade-off"? I explicitly didn't limit sloppiness to inefficiency and mentioned it's a tradeoff: "... all else being equal or at least comparable (elegance, conciseness, readability, etc.). Of course it's a tradeoff; spending a week to save a few milliseconds on average is usually a waste for most applications, but being a lazy keyboard banger writing the first thing that pops into mind is not that good either." > But... do you write list.__len__() instead of len(list) to save a few > nanoseconds? No, of course not, it's not worth it, but that doesn't mean that being curious about what's faster and using timeit to find out is totally worthless. Another example: avoiding attribute lookups within a loop. I rarely write bar = foo.bar for i in big_list: bar(i) but it's valuable to know that it can make a difference when I really need it. Always writing the first thing that "just works" prevents one from even considering that there might be faster (or more elegant, more general, etc.) alternatives. George From deets at nospam.web.de Thu Jan 3 08:52:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 14:52:08 +0100 Subject: Treating a unicode string as latin-1 References: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Message-ID: <5u47k8F1gbcngU2@mid.uni-berlin.de> Simon Willison wrote: > Hello, > > I'm using ElementTree to parse an XML file which includes some data > encoded as cp1252, for example: > > Bob\x92s Breakfast > > If this was a regular bytestring, I would convert it to utf8 using the > following: > >>>> print 'Bob\x92s Breakfast'.decode('cp1252').encode('utf8') > Bob's Breakfast > > But ElementTree gives me back a unicode string, so I get the following > error: > >>>> print u'Bob\x92s Breakfast'.decode('cp1252').encode('utf8') > Traceback (most recent call last): > File "", line 1, in > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/encodings/cp1252.py", line 15, in decode > return codecs.charmap_decode(input,errors,decoding_table) > UnicodeEncodeError: 'ascii' codec can't encode character u'\x92' in > position 3: ordinal not in range(128) > > How can I tell Python "I know this says it's a unicode string, but I > need you to treat it like a bytestring"? I don't get your problem. You get a unicode-object. Which means that it got decoded by ET for you, as any XML-parser must do. So - why don't you get rid of that .decode('cp1252') and happily encode it to utf-8? Diez From steven.bethard at gmail.com Fri Jan 25 12:26:29 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 25 Jan 2008 10:26:29 -0700 Subject: find minimum associated values In-Reply-To: References: Message-ID: Alan Isaac wrote: > I have a small set of objects associated with a larger > set of values, and I want to map each object to its > minimum associated value. The solutions below work, > but I would like to see prettier solutions... > [snip] > > # arbitrary setup > keys = [Pass() for i in range(10)]*3 > vals = [random.random() for i in range(30)] > kv = zip(keys,vals) > random.shuffle(kv) > > #OBJECTIVE: > # find minimum val associated with each "key" in kv > [snip] > > print "method 3: defaultdict" > t=time.clock() > d = defaultdict(list) > for k,v in kv: > d[k].append(v) > for k in d: > d[k] = min(d[k]) > print time.clock()-t > print d This is definitely the approach I'd use. Seems "pretty" enough to me. ;-) STeVe From martin at v.loewis.de Tue Jan 1 16:28:03 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 01 Jan 2008 22:28:03 +0100 Subject: TK 8.5 In-Reply-To: <477A8345.5050303@codebykevin.com> References: <477A7066.9000402@v.loewis.de> <477A8345.5050303@codebykevin.com> Message-ID: <477AB063.4000606@v.loewis.de> >> Hence, there is no need to talk about this very much. That >> Python "supports" Tk 8.5 is too minor to mention - I think >> even Python 2.4 supports Tk 8.5. > > In terms of building and linking Python to Tk 8.5, this is certainly true. > > However, I think most people who ask about Python "supporting" Tk 8.5 > are probably asking how easily can the new features in Tk 8.5 be > accessed from Python, particularly the platform-specific themed widgets. I just found that there is also "middle ground": would most existing Tkinter applications work when Python was linked with Tk 8.5; in particular, would IDLE work? This is not the case for Python 2.5. Tk 8.5 changed the data types it returns from certain commands, affecting existing code. Likely, IDLE should work with Tk 8.5 in Python 2.6 and 3.0, but won't work for Python 2.5. > The answer to that question is, "At present, not very easily." There is > currently no support at all in lib-tk for themed widgets, for instance. > The external Tile.py module that I maintain at > http://tkinter.unpythonic.net/wiki/TileWrapper works well enough, but as > I am not the original author of this module, I cannot really offer it > for inclusion in the core Python distribution. As such, someone will > have to step up and write a new implememtation. That is of no concern for me whatsoever. Contributions are welcome. I know people are jumping up and down because of these themed widgets; the "I won't do anything actively" goes beyond that, though: even if existing widgets get new commands, or new widgets are added, then support for them in Tkinter is only added through user contributions. If "supports Tk 8.x" means "Tkinter has wrappers for all commands and options", then Tkinter has no support for any version of Tk, as a lot of commands remain unwrapped. Regards, Martin From grante at visi.com Thu Jan 24 15:28:50 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 24 Jan 2008 20:28:50 -0000 Subject: Ignore exceptions References: Message-ID: <13pht82n9il8k21@corp.supernews.com> On 2008-01-24, SMALLp wrote: > Hy. Hi. > Is there any way to make interrupter ignore exceptions. Nope. Either handle the exceptions or write code that doesn't generate exceptions. > I'm working on bigger project and i used to put try catch > blocks after writing and testing code You're getting unhandled exceptions after you've tested your code? I guess you need to do better testing. > what's boring and it's easy to make mistake. I remember of > something like that in C++ but I cant find anythin like that > for python. I should hope not. The Python language wouldn't _work_ if the VM ignored exceptions. Exceptions are used for all sorts of things besides errors (terminating a loop, exiting a program, etc.). If exceptions were ignored all sorts of things would stop working. -- Grant Edwards grante Yow! I'll show you MY at telex number if you show me visi.com YOURS ... From sturlamolden at yahoo.no Fri Jan 11 12:55:08 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 11 Jan 2008 09:55:08 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: On 10 Jan, 03:10, Steven D'Aprano wrote: > You are correct that optimizing Python is hard. However, in many cases, > the problem is not that Python is too slow, but the specific algorithm > chosen by the programmer is slow, e.g. no compiler optimization is going > to turn an O(n**2) algorithm into an O(1) algorithm. This is possibly the number one cause of 'slowness' complained about on mailing lists. > The Original Poster says it takes one or two seconds to process an > 800x600 GIF. That sounds believable: on my PC, it takes about five > seconds to loop over range(800*600) and do a tiny bit of processing. > Something like Psycho might speed that up a lot, possibly by an order of > magnitude or two. It seems the code he is referring to is doing k-means clustering on each frame. The clustering is done by from SciPy's cluster module, which is doing 'vector quantitization'. The algorithm is written in plain C. It is not Python that is slow. It is the amount of processing done on each frame. As the bottleneck is already in C, it cannot be done any faster without radically changing the algorithm and/or the hardware. From zentraders at gmail.com Wed Jan 9 15:18:42 2008 From: zentraders at gmail.com (Zentrader) Date: Wed, 9 Jan 2008 12:18:42 -0800 (PST) Subject: executing newgrp from python in current shell possible? References: Message-ID: <755e7fd2-5e4a-4a4b-b848-a5e4ca756087@l6g2000prm.googlegroups.com> On Jan 9, 5:56?am, Svenn Are Bjerkem wrote: >I have been looking for a way to execute this command > as a part of a script, but it seems that the changes are only valid in > the context of the script and when the script exits, the current shell > still have the original "users" group setting. I don't think you would want it any other way. Would you want a user to be able to change the group and have it remain permanently? Who's going to remember whether they were last in "A" or "B", and it opens up oportunities for the practical joker when you go to the restroom and leave the terminal on. Put the "change the group" code into a separate function in a separate file (with only you as the owner) and call it whenever you want to change groups. From toby at tobiah.org Wed Jan 16 15:14:02 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 16 Jan 2008 12:14:02 -0800 Subject: import from question In-Reply-To: <87tzleb2st.fsf@benfinney.id.au> References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> <478d04d4$0$26042$88260bb3@free.teranews.com> <87tzleb2st.fsf@benfinney.id.au> Message-ID: <478E658A.9070003@tobiah.org> Ben Finney wrote: > Tobiah writes: > >> This is a little surprising. So "from mod import *" really copies >> all of the scalars into new variables in the local namespace. > > No. Nothing is copied. All the objects (remembering that in Python, > *everything* is an object) created by the code in module 'mod' are > given names in the current namespace. Yeah, copied. Just as in: >>> a = 3 >>> b = a >>> a = 5 >>> b 3 >>> given b.py: ########################## thing = 0 ########################## and a.py: ########################## from b import * import b print thing print b.thing b.thing = 1 print b.thing print thing ########################### 0 0 1 0 -- Posted via a free Usenet account from http://www.teranews.com From wim at fixnum.org Tue Jan 22 17:55:02 2008 From: wim at fixnum.org (Wim Vander Schelden) Date: Tue, 22 Jan 2008 23:55:02 +0100 Subject: translating Python to Assembler In-Reply-To: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: Python modules and scripts are normally not even compiled, if they have been, its probably just the Python interpreter packaged with the scripts and resources. My advice is that if you want to learn Python, is that you just read a book about it or read only resources. Learning Python from assembler is kind of... strange. Not only are you skipping several generations of programming languages, spanned over a period of 40 years, but the approach to programming in Python is so fundamentally different from assembler programming that there is simply no reason to start looking at if from this perspective. I truly hope you enjoy the world of high end programming languages, but treat them as such. Looking at them in a low-level representation or for a low-level perspective doesn't bear much fruits. Kind regards, Wim On 1/22/08, over at thepond.com wrote: > > My expertise, if any, is in assembler. I'm trying to understand Python > scripts and modules by examining them after they have been > disassembled in a Windows environment. > > I'm wondering if a Python symbols file is available. In the Windows > environment, a symbol file normally has a PDB extension. It's a little > unfortunate that Python also uses PDB for its debugger. Google, for > whatever reason, wont accept queries with dots, hyphens, etc., in the > query line. For example a Google for "python.pdb" returns +python > +pdb, so I get a ridiculous number of returns referring to the python > debugger. I have mentioned this to Google several times, but I guess > logic isn't one of their strong points. :-) > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Jan 30 07:58:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jan 2008 04:58:27 -0800 (PST) Subject: HI all References: <1b6a8d39-8077-4d4e-b05f-1e0037472ed8@d4g2000prg.googlegroups.com> Message-ID: <054b4b69-a415-4e8a-8651-c3e3f93ad4d3@c4g2000hsg.googlegroups.com> On 30 ene, 09:26, tiwarishra... at gmail.com wrote: > I am shravan tiwari, i want to know that how i'll run any python > file(*.py) on command prompt r python GUI. > i tried this > > python test.py > > but i have got error, syntax error. so can i get the solution. This is the right way to run it. If you get a syntax error, it means that test.py is not correctly written. Fix the code and try again. -- Gabriel Genellina From stephan.diehl at gmx.net Mon Jan 21 12:38:16 2008 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Mon, 21 Jan 2008 18:38:16 +0100 Subject: Berlin (Germany) Python User Group is meeting on 23.1. Message-ID: The Berlin Python User Group is meeting on the 23.1. at newthinking store at 7pm. All details can be found at http://wiki.python.de/User_Group_Berlin. The Berlin Python User Group is planning to meet every two month to talk about Python. Most talking will be done in german, but I can assure you that english could be spoken as well, if the need arises... From nikbaer at gmail.com Mon Jan 28 21:03:09 2008 From: nikbaer at gmail.com (nik) Date: Mon, 28 Jan 2008 18:03:09 -0800 (PST) Subject: ISO with timezone Message-ID: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Hi, How does one express the time in ISO format with the timezone designator? what I want is YYYY-MM-DDThh:mm:ss.sTZD >From the documentation I see: >>> from datetime import tzinfo, timedelta, datetime >>> class TZ(tzinfo): ... def utcoffset(self, dt): return timedelta(minutes=-399) ... >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') '2002-12-25 00:00:00-06:39' and I've also figured out: >>>datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3] '2008-01-23T11:22:54.130' But can't figure out how to fit them together. Thank you, Nik From mwm at mired.org Fri Jan 11 11:51:17 2008 From: mwm at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 11:51:17 -0500 Subject: Magic function In-Reply-To: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> Message-ID: <20080111115117.134ad8be@mbook.mired.org> On Fri, 11 Jan 2008 08:29:18 -0800 (PST) dg.google.groups at thesamovar.net wrote: > Hi all, > > I'm part of a small team writing a Python package for a scientific > computing project. The idea is to make it easy to use for relatively > inexperienced programmers. As part of that aim, we're using what we're > calling 'magic functions', and I'm a little bit concerned that they > are dangerous code. I'm looking for advice on what the risks are (e.g. > possibility of introducing subtle bugs, code won't be compatible with > future versions of Python, etc.). > > Quick background: Part of the way our package works is that you create > a lot of objects, and then you create a new object which collects > together these objects and operates on them. We originally were > writing things like: > > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > bigobj = Bigobj(objects=[obj1,obj2]) > bigobj.run() > > This is fine, but we decided that for clarity of these programs, and > to make it easier for inexperienced programmers, we would like to be > able to write something like: > > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > run() > > The idea is that the run() function inspects the stack, and looks for > object which are instances of class Obj, creates a Bigobj with those > objects and calls its run() method. > > So, any comments on that approach? The basic idea is ok, but looking at the stack makes me a bit nervous. That makes the code complicated, and probably fragile in the face of changing python versions. The unittest module does much the same thing - you run unittest.main, and it runs all the tests in any TestCase subclass in your module (assuming you didn't do something to limit it). However, it does it by examining the module, not the stack. The real difference is that your "magic" classes have to be global to your module. On the other hand, it provides some nice tools to let you partition things, so you can easily run subsets of the classes from the command line. It's probably worth a look. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From arnodel at googlemail.com Mon Jan 21 12:11:55 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 21 Jan 2008 09:11:55 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: <3f9c0e91-c493-4a2d-8ef3-1a081602e8e8@q77g2000hsh.googlegroups.com> On Jan 21, 9:01?am, dg.google.gro... at thesamovar.net wrote: > Arnaud: I haven't had time to play with your solution yet - how quick > does it run? Ok I've done some quick timings, it's faster than I remembered it: numbers = [2, 4, 5, 8, 25] target = 758 Average time to find (1) best solution (in terms of length of repr): 0.0418s (2) first solution: 0.00421s (2.2GHz MacBook Pro, done with the timeit module) (1) involves working out all possible calculations with the 6 numbers. -- Arnaud From kyosohma at gmail.com Fri Jan 4 09:12:22 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 4 Jan 2008 06:12:22 -0800 (PST) Subject: Who's to blame? References: <92dfc2fc-0677-43c0-b34f-4f240fa40205@e4g2000hsg.googlegroups.com> <255d32d0-43f5-4d34-a074-b87082dc6043@e23g2000prf.googlegroups.com> <2b076973-b132-4666-a163-b80bcbeaedfb@s8g2000prg.googlegroups.com> Message-ID: <8749bb13-4f31-4cfc-8878-cc19bd417275@f10g2000hsf.googlegroups.com> On Jan 4, 3:35 am, Nicola Musatti wrote: > Hallo, Mike. > First of all, thanks to both you and Rob for your answers. I now see > that the wxPython group would have been a better place to post to, all > the more so given the tight connection between the wxPython and > wxWidgets projects, of which at first I wasn't aware. > > On Jan 3, 8:19 pm, kyoso... at gmail.com wrote: > [...] > > > > > I've never created a modal dialog like this. Instead, I follow the > > wxPython in Action book examples (most of the time), which would do a > > yes/no dialog like this: > > > > > > dlg = wx.MessageDialog(None, 'Some Message', 'A Message Box', > > wx.YES_NO | wx.QUESTION) > > retCode = dlg.ShowModal() > > if retCode == wx.ID_YES: > > # do something > > print 'yes' > > else: > > # do something else > > print 'no' > > dlg.Destroy() > > > > > Actually my example started out as something like > > if wx.MessageBox(message="Some message", caption="Some caption", > style=wx.YES|wx.NO) == wx.YES: > pass > > I had to change it because the actual message can become very long, so > I assembled a dialog with a scrollable text field. Maybe I'm expecting > to much of wxStdDialogButtonSizer, but I still feel that given that > both your method and mine above work straight away, it should provide > the same behaviour with Yes/No buttons as with OK/Cancel ones. > > Cheers, > Nicola Musatti Nicola, I have sub-classed wx.Dialog to do my own custom modal dialogs as well. You can use sizers and put whatever widgets you want onto it that way. Just make sure that when you create the Yes/No buttons, you give them the wx.ID_YES or wx.ID_NO ids, rather than -1 or wx.ID_ANY. yesBtn = wx.Button(parent, wx.ID_YES, 'Yes') noBtn = wx.Button(parent, wx.ID_NO, 'No') Mike From grante at visi.com Sat Jan 5 11:13:22 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 05 Jan 2008 16:13:22 -0000 Subject: Question on os.tempnam() vulnerability References: <13nt81gftkfa32d@corp.supernews.com> <13nv5m68qeknk1f@corp.supernews.com> <477FA9B5.9050609@v.loewis.de> Message-ID: <13nvb525r3m6m39@corp.supernews.com> On 2008-01-05, Martin v. L?wis wrote: >> I know. That's the point of my question: how do you do that >> under Windows? > > When you create a new process, you have the option to inherit > file handles to the new process. So the parent should open the > file, and then inherit the handle to the new process. That's an answer, though not for the question I asked. The program that's being run requires a that it be passed a filename on the command-line. I'm not writing the program that is to open the file. If I were, I'd just make it a python module and call it instead of running it in a separate process. > IOW, it's the same approach as on Unix. Not really. Under Unix you can safely create a temp file with a name that can be used to open the file. I asked about a way to do that under Windows as well. -- Grant Edwards grante Yow! ... I live in a at FUR-LINE FALLOUT SHELTER visi.com From nabble.dserodio at neverbox.com Thu Jan 10 13:24:59 2008 From: nabble.dserodio at neverbox.com (Daniel Serodio) Date: Thu, 10 Jan 2008 10:24:59 -0800 (PST) Subject: subprocess "handle is invalid" error In-Reply-To: <46266279.5050105@ctypes.org> References: <132cdrpqsmnvpa7@corp.supernews.com> <46266279.5050105@ctypes.org> Message-ID: <14740517.post@talk.nabble.com> Thomas Heller-2 wrote: > > Grant Edwards schrieb: > > [snip] > >> >> Traceback (most recent call last): >> File "surfedit.py", line 28, in ? >> File "Gnuplot\_Gnuplot.pyc", line 178, in __init__ >> File "Gnuplot\gp_win32.pyc", line 117, in __init__ >> File "subprocess.pyc", line 533, in __init__ >> File "subprocess.pyc", line 607, in _get_handles >> File "subprocess.pyc", line 634, in _make_inheritable >> WindowsError: [Errno 6] The handle is invalid >> >> How does one troubleshoot errors that happen three layers deep >> in the subprocess module? >> > > I think this is a subprocess bug. It is often attributed to py2exe > because > usually developers do never run the script in pythonW.exe instead of > python.exe, > and later build a *windows* program with py2exe (the *windows* program has > no > console, and that triggers the bug). > > [snip] > > I thought that this bug was fixed in Python2.5.1 (the release candidate), > but it seems it wasn't. The bug is at > http://sourceforge.net/tracker/index.php?func=detail&aid=1124861&group_id=5470&atid=105470 > > If all this is correct, I hope that someone adds a section to the py2exe > wiki; > and reopens the above bug report. > > Thomas > I've been bitten by this same bug in 2.5.1, and the bug you linked to (which is now @ http://bugs.python.org/issue1124861) is still marked as fixed. I've tried to reopen it but it seems only the reporter (or some "admin" user) is able to do it. -- View this message in context: http://www.nabble.com/subprocess-%22handle-is-invalid%22-error-tp10060967p14740517.html Sent from the Python - python-list mailing list archive at Nabble.com. From gherron at islandtraining.com Wed Jan 23 04:06:39 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 23 Jan 2008 01:06:39 -0800 Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? In-Reply-To: References: Message-ID: <4797039F.9080702@islandtraining.com> Kristian Domke wrote: > Hello to all > > I am trying to learn python at the moment studying an example program > (cftp.py from the twisted framework, if you want to know) > > There I found a line > > foo = (not f and 1) or 0 > > In this case f may be None or a string. > > If I am not wrong here, one could simply write > > foo = not f > > because if f = None: > > (not f) = true, > (true and 1) = true, > (true or 0) = true > > or if f = 'bar' > > (not f) = false > (false and 1) = false > (false or 0) = false > > So why bothering with the longer version? > Good catch! It's my guess that you've found a way to improve on a bit of carelessly written code. However there *is* a (subtle) difference between not f and (not f and 1) or 0 The first produces a boolean value, and the second produces an int value, but since one is a subclass of the other, you'd have to write quite perverse code care about the difference. Gary Herron > I hope, I made clear, what I want... > Quite. > CU > > Kristian > From donn.ingle at gmail.com Mon Jan 14 03:19:30 2008 From: donn.ingle at gmail.com (Donn) Date: Mon, 14 Jan 2008 10:19:30 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A77F0.4000502@v.loewis.de> References: <200801132048.08966.donn.ingle@gmail.com> <478A77F0.4000502@v.loewis.de> Message-ID: <200801141019.30792.donn.ingle@gmail.com> > Can you please type > paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] > f = open(paf, "r") I think I was getting a ghost error from another try somewhere higher up. You are correct, this does open the file - no matter what the locale is. I have decided to keep the test for a decode error because files created under different locales should not be written-to under the current one. I don't know if one can mix encodings in a single text file, but I don't have time to find out. It is getting messy with my test files created in differing locales, and my code changing so quickly. > See above. The encoding in codecs.open has no effect at all on > the file name; it only talks about the file content. Thanks, I suspected as much but it's a subtle thing. Best, \d -- "It is almost as if the human brain were specifically designed to misunderstand Darwinism, and to find it hard to believe.." -- Richard Dawkins Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From python.list at tim.thechases.com Wed Jan 9 12:49:36 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 09 Jan 2008 11:49:36 -0600 Subject: How to get memory size/usage of python object In-Reply-To: References: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> Message-ID: <47850930.8070309@tim.thechases.com> Sion Arrowsmith wrote: > Santiago Romero wrote: >> Is there a way to check the REAL size in memory of a python object? >> >> Something like >> >>> print sizeof(mylist) >> [ ... ] > > Would you care to precisely define "REAL size" first? Consider: > >>>> atuple = (1, 2) >>>> mylist = [(0, 0), atuple] > > Should sizeof(mylist) include sizeof(atuple) ? > >>>> del atuple > > What about now, when mylist has the only reference to the (1, 2) > object that also used to be referred to as atuple? or add to the mix >>> mylist = [(0,0), atuple] * 1000 where the same atuple is referenced 1000 times. And then if you >>> del atuple defining "sizeof()" becomes even more peculiar if you have a thousand things that "have" the same item that nothing else claims ownership of. Or, if you have this: >>> alist = [1,2,3] >>> mylist = ['a', 'b', alist] * 10 >>> s1 = sizeof(mylist) >>> alist.append(42) >>> s2 = sizeof(mylist) should s1==s2 ? -tkc From nanjundi at gmail.com Fri Jan 11 14:28:08 2008 From: nanjundi at gmail.com (Nanjundi) Date: Fri, 11 Jan 2008 11:28:08 -0800 (PST) Subject: split parameter line with quotes References: Message-ID: On Jan 11, 1:50 pm, teddyber wrote: > Hello, > > first i'm a newbie to python (but i searched the Internet i swear). > i'm looking for some way to split up a string into a list of pairs > 'key=value'. This code should be able to handle this particular > example string : > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > i know i can do that with some regexp (i'm currently trying to learn > that) but if there's some other way... > > thanks This is unconventional and using eval is not SAFE too. >>> s = 'qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,3des",maxbuf=1024,charset="utf-8",algorithm="md5-sess"' >>> d = eval(' dict(%s)' % s) >>> d.items() [('algorithm', 'md5-sess'), ('maxbuf', 1024), ('charset', 'utf-8'), ('cipher', 'rc4-40,rc4-56,rc4,des,3des'), ('qop', 'auth,auth-int,auth- conf')] >>> for k,v in d.iteritems(): print k, '=', v ... algorithm = md5-sess maxbuf = 1024 charset = utf-8 cipher = rc4-40,rc4-56,rc4,des,3des qop = auth,auth-int,auth-conf For safe eval, take a look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 -N From te_rem_ra_ove_an_forspam at consistent.org Thu Jan 31 20:47:36 2008 From: te_rem_ra_ove_an_forspam at consistent.org (Terran Melconian) Date: Thu, 31 Jan 2008 19:47:36 -0600 Subject: Naive idiom questions References: <60ev9jF1qdpctU1@mid.individual.net> Message-ID: On 2008-01-31, Bjoern Schliessmann wrote: > Did you measure such impact on your application? > Also see http://www.skymind.com/~ocrow/python_string/ I don't have a real application yet. That was, in fact, exactly the web page which informed me that the MutableString class was not implemented with mutable primitives. > Look at "lower level" HLLs. In C++, you'd have to use Well, in C++, I would use something like: string sa[5][5]; string has a default constructor, so I'll get a 5x5 array of empty strings. Alternatively, I could use boost::array if I wanted container semantics. If I needed something dynamically resizable, I could use: vector > vs(5); and then I could append elements to each one. If I wanted needed to resize them all to 5 immediately, I would have to loop: for (vector >::iterator i = vs.begin(); i != vs.end(); i++) i->resize(5); and that isn't particularly concise or elegant either, but the odds of needing them to start out at size 5 and *also* be resizable later are low for most applications. > Personally, I like list comprehensions much better. Perhaps the take-away lesson is that comprehensions should be seen as a very fundamental operation in Python, and I have the wrong idea by considering them advanced. From http Tue Jan 22 15:00:47 2008 From: http (Paul Rubin) Date: 22 Jan 2008 12:00:47 -0800 Subject: A global or module-level variable? References: <7637fd0b-961e-4730-abd8-96e85c907082@i72g2000hsd.googlegroups.com> Message-ID: <7xwsq1tyts.fsf@ruckus.brouhaha.com> Bret writes: > nextport=42000 > > def getNextPort(): > nextport += 1 > return nextport If you have to do it that way, use: def getNextPort(): global nextport nextport += 1 return nextport the global declaration stops the compiler from treating nextport as local and then trapping the increment as to an uninitialized variable. From rupert.thurner at gmail.com Sun Jan 20 06:40:39 2008 From: rupert.thurner at gmail.com (rupert.thurner) Date: Sun, 20 Jan 2008 03:40:39 -0800 (PST) Subject: finding memory leak in edgewall trac 0.11 References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> Message-ID: <0c6fc35d-91d2-4767-968d-e6eb56096eba@z17g2000hsg.googlegroups.com> On Jan 19, 10:31?pm, Christian Heimes wrote: > Jeroen Ruigrok van der Werven wrote: > > > Hi Christian, > > > -On [20080119 16:16], Christian Heimes (li... at cheimes.de) wrote: > >> I forgot one important point in my reply. The GC module contains some > >> useful methods for debugging. Check gc.garbage. It should be empty. > > > Yeah, we're messing around with that stuff as well as many other ways of > > trying to track issues, but it can really be looking for a needle in a > > haystack to be honest. > > There's so much output that, I guess, make sense only when you're semi-deep > > into the Python internals to even make heads or tails out of it. =\ > > And even third-party code is not helping much to reduce the clutter and > > provide insight. > > Under normal circumstances gc.garbage should be an empty list. In > general it's a bad sign if gc.garbage contains lots of objects. > > I found several potential leaks in trac: > > $ find -name \*.py | xargs grep __del__ > ./trac/versioncontrol/svn_fs.py: ? ?def __del__(self): > ./trac/versioncontrol/svn_fs.py: ? ?def __del__(self): > ./trac/db/pool.py: ? ?def __del__(self): > > $ find -name \*.py | xargs grep frame > ./trac/web/main.py: > [...] > ./trac/core.py: ? ? ? ?frame = sys._getframe(1) > ./trac/core.py: ? ? ? ?locals_ = frame.f_locals > > I recommend that you either replace __del__ with a weak reference > callback or to remove it. Referencing a frame, traceback or f_locals is > going to leak, too. You *must* explicitly del every frame and locals > variable. > > Christian many thanks! as the main change was replacing clearsilver with genshi, this means one could do the same thing with genshi, http://genshi.edgewall.org/? $ find -name \*.py | xargs grep frame ./genshi/filters/html.py: 'dir', 'disabled', 'enctype', 'for', 'frame', 'headers', 'height', ./genshi/input.py: _EMPTY_ELEMS = frozenset(['area', 'base', 'basefont', 'br', 'col', 'frame', ./genshi/output.py: 'http://www.w3.org/TR/html4/frameset.dtd' ./genshi/output.py: 'http://www.w3.org/TR/xhtml1/DTD/xhtml1- frameset.dtd' ./genshi/output.py: * "html-transitional" for the HTML 4.01 frameset DTD ./genshi/output.py: * "xhtml-frameset" for the XHTML 1.0 frameset DTD ./genshi/output.py: 'html-frameset': DocType.HTML_FRAMESET, ./genshi/output.py: 'xhtml-frameset': cls.XHTML_FRAMESET, ./genshi/output.py: _EMPTY_ELEMS = frozenset(['area', 'base', 'basefont', 'br', 'col', 'frame', ./genshi/template/base.py: _ctxt2dict = lambda ctxt: ctxt.frames[0] ./genshi/template/base.py: self.frames = deque([data]) ./genshi/template/base.py: self.pop = self.frames.popleft ./genshi/template/base.py: self.push = self.frames.appendleft ./genshi/template/base.py: return repr(list(self.frames)) ./genshi/template/base.py: for frame in self.frames: ./genshi/template/base.py: if key in frame: ./genshi/template/base.py: del frame[key] ./genshi/template/base.py: value, frame = self._find(key) ./genshi/template/base.py: if frame is None: ./genshi/template/base.py: self.frames[0][key] = value ./genshi/template/base.py: """Retrieve a given variable's value and the frame it was found in. ./genshi/template/base.py: for frame in self.frames: ./genshi/template/base.py: if key in frame: ./genshi/template/base.py: return frame[key], frame ./genshi/template/base.py: for frame in self.frames: ./genshi/template/base.py: if key in frame: ./genshi/template/base.py: return frame[key] ./genshi/template/base.py: for frame in self.frames: ./genshi/template/base.py: keys += [key for key in frame if key not in keys] ./genshi/template/directives.py: # Store the function reference in the bottom context frame so that it ./genshi/template/directives.py: ctxt.frames[-1][self.name] = function ./genshi/template/directives.py: frame = {} ./genshi/template/directives.py: ctxt.push(frame) ./genshi/template/tests/directives.py: frame = exc_traceback.tb_next ./genshi/template/tests/directives.py: frames = [] ./genshi/template/tests/directives.py: while frame.tb_next: ./genshi/template/tests/directives.py: frame = frame.tb_next ./genshi/template/tests/directives.py: frames.append(frame) ./genshi/template/tests/directives.py: frames[-1].tb_frame.f_code.co_name) ./genshi/template/tests/directives.py: frames[-1].tb_frame.f_code.co_filename) ./genshi/template/tests/directives.py: self.assertEqual(2, frames[-1].tb_lineno) ./genshi/template/tests/eval.py: frame = exc_traceback.tb_next ./genshi/template/tests/eval.py: frames = [] ./genshi/template/tests/eval.py: while frame.tb_next: ./genshi/template/tests/eval.py: frame = frame.tb_next ./genshi/template/tests/eval.py: frames.append(frame) ./genshi/template/tests/eval.py: frames[-3].tb_frame.f_code.co_name) ./genshi/template/tests/eval.py: frames[-3].tb_frame.f_code.co_filename) ./genshi/template/tests/eval.py: self.assertEqual(50, frames[-3].tb_lineno) ./genshi/template/tests/eval.py: frame = exc_traceback.tb_next ./genshi/template/tests/eval.py: while frame.tb_next: ./genshi/template/tests/eval.py: frame = frame.tb_next ./genshi/template/tests/eval.py: code = frame.tb_frame.f_code ./genshi/template/tests/eval.py: self.fail("never found the frame I was looking for") ./genshi/template/tests/eval.py: self.assertEqual(50, frame.tb_lineno) ./genshi/template/tests/eval.py: frame = exc_traceback.tb_next ./genshi/template/tests/eval.py: while frame.tb_next: ./genshi/template/tests/eval.py: frame = frame.tb_next ./genshi/template/tests/eval.py: code = frame.tb_frame.f_code ./genshi/template/tests/eval.py: self.fail("never found the frame I was looking for") ./genshi/template/tests/eval.py: self.assertEqual(50, frame.tb_lineno) rupert From jmgimeno at gmail.com Mon Jan 21 02:45:23 2008 From: jmgimeno at gmail.com (babui) Date: Sun, 20 Jan 2008 23:45:23 -0800 (PST) Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> Message-ID: <88dc9784-6d06-46cc-980e-0fe233912572@l32g2000hse.googlegroups.com> On 21 ene, 08:41, Santiago Romero wrote: > Hi ... > > I have the following DNS MX records info: > > domain.com > preference 10 host mx1.domain.com > preference 30 host anotherhost.domain.com > preference 20 host mx2.domain.com > And finally ... do you think there is a better python structure to > store this data and sort it in a more easy way? Why don't you use a list of tuples? L = [ (10, "mx1.domain.com"), (30, "anotherhost.domain.com", (20, "mx2.domain.com") ] and L.sort() sorts the list !!! Juan M. Gimeno > Thanks. From mfrancis at tcore.org Fri Jan 11 16:12:17 2008 From: mfrancis at tcore.org (Monica Francis) Date: Fri, 11 Jan 2008 13:12:17 -0800 Subject: Rapid desktop application development Message-ID: <404C1A9C83B11D41BEC3944A111FB28F62A3DD@tlcsmail.int-tlcssac.org> I am looking for Stephan Eilert who was an exchange student from Germany to the U.S. (Northern California) in the 1980's. Could you possibly be one in the same? Monica Erwin-Francis -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Sun Jan 27 08:02:38 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 27 Jan 2008 05:02:38 -0800 (PST) Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> <7xy7acsx2l.fsf@ruckus.brouhaha.com> <8ddebd68-43dc-4320-86e1-887aadff4af3@d70g2000hsb.googlegroups.com> <7xmyqs722t.fsf@ruckus.brouhaha.com> <13pnbp9l8lk1j8b@corp.supernews.com> Message-ID: On Jan 27, 11:32?am, Arnaud Delobelle wrote: [...] > > simple_posmax is more than 3x faster on my machine. ?It's not > surprising as even though the list is walked twice, it is all done in > C and no new objects have to be created. Then only non-C bit is when > the result of max(l) is fed to l.index(). Of course that's incorrect in general: if comparison functions between objects in l are python functions then some bytecode will be run and some new objects may be created. But in most cases I think it stands true. -- Arnaud From steven.bethard at gmail.com Mon Jan 28 10:45:54 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 28 Jan 2008 08:45:54 -0700 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > Sligthly improved (not for performance! but signature-preserving and > looks for default values) > > from functools import wraps > from inspect import getargspec > from itertools import izip, chain > > def autoassign(*names): > def decorator(f): > fargnames, _, _, fdefaults = getargspec(f) > defaults = [(n,v) for (n,v) > in izip(reversed(fargnames), reversed(fdefaults)) > if n in names] > @wraps(f) > def decorated(self, *args, **kwargs): > self.__dict__.update(defaults) > for name, arg in chain(izip(fargnames, args), > kwargs.iteritems()): > if name in names: > setattr(self, name, arg) > return f(self, *args, **kwargs) > return decorated > return decorator > > class Test(object): > @autoassign('foo', 'bar') > def __init__(self, foo, bar=3, baz=6): > print 'baz =', baz > > t = Test(1, 2, 6) > u = Test(foo=8) > > print t.foo # 1 > print t.bar # 2 > > print u.foo # 8 > print u.bar # 3 (default) You should definitely post this to the cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python STeVe From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 06:00:44 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 12:00:44 +0100 Subject: adding methods at runtime In-Reply-To: <940fcb28-764e-46ab-a627-aff513e009e1@j78g2000hsd.googlegroups.com> References: <940fcb28-764e-46ab-a627-aff513e009e1@j78g2000hsd.googlegroups.com> Message-ID: <47874c50$0$13390$426a34cc@news.free.fr> zslevi at gmail.com a ?crit : > Can I access the class attributes from a method added at runtime? Of course. > (My > experience says no.) So there's something wrong with your experience !-) > I experimented with the following code: > > > class myclass(object): > myattr = "myattr" > > instance = myclass() > def method(x): > print x > > instance.method = method As Marc pointed out, you're not adding a method but a function. What you want is: def method(self, x): print "x : %s - myattr : %s" % (x, self.myattr) import new instance.method = new.instancemethod(method, instance, myclass) Note that this is only needed for per-instance methods - if you want to add a new method for all instances, you just set the function as attribute of the class. The lookup mechanism will then invoke the descriptor protocol on the function object, which will return a method (FWIW, you have to do it manually on per-instance methods because the descriptor protocol is not invoked on instance attributes, only on class attributes). HTH From arnodel at googlemail.com Wed Jan 23 02:16:37 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 23:16:37 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> Message-ID: On Jan 22, 10:56?pm, dg.google.gro... at thesamovar.net wrote: > Arnaud and Terry, > > Great solutions both of you! Much nicer than mine. I particularly like > Arnaud's latest one based on folding because it's so neat and > conceptually simple. For me, it's the closest so far to my goal of the > most elegant solution. Thanks! It's a great little problem to think of and it helps bring more fun to this list. Sadly work takes over fun during the week, but I will try to improve it at the weekend. > So anyone got an answer to which set of numbers gives the most targets > from 100 onwards say (or from 0 onwards)? Is Python up to the task? I bet it is :) > A thought on that last one. Two ways to improve speed. First of all, > you don't need to rerun from scratch for each target Yes, I've been doing this by writing an 'action' (see my code) that takes note of all reached results. > Secondly, you > can try multiple different sets of numbers at the same time by passing > numpy arrays instead of single values (although you have to give up > the commutativity and division by zero optimisations). Have to think about this. -- Arnaud From cokofreedom at gmail.com Thu Jan 17 09:57:46 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 17 Jan 2008 06:57:46 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <478f699d$0$17578$426a74cc@news.free.fr> Message-ID: > > > Yes, small typo there. > > > Okey, so if my array1 is has 4 elements, and array2 has 6, it won't > > loop trough the last 2 in array2? How do I make it do that? > > > Please gentlemen: Python has no builtin type named 'array', so > s/array/list/g > > > Just pad your shortest list. I agree, but was merely showing how he would use the variables he had given. From nospam at invalid.com Wed Jan 9 23:45:34 2008 From: nospam at invalid.com (Jack) Date: Wed, 9 Jan 2008 20:45:34 -0800 Subject: Using a proxy with urllib2 Message-ID: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> I'm trying to use a proxy server with urllib2. So I have managed to get it to work by setting the environment variable: export HTTP_PROXY=127.0.0.1:8081 But I wanted to set it from the code. However, this does not set the proxy: httpproxy = '127.0.0.1:3129' proxy_support = urllib2.ProxyHandler({"http":"http://" + httpproxy}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) urllib2.install_opener(opener) I'm using it from a web.py URL handler file, not sure if it matters. I have another question though. It seems that using either of the methods above, the proxy will be global. What if I want to use a proxy with one site, but not with another site? Or even use a proxy for some URLs but not others? The proxy having to be global is really not convenient. Is there any way to do per-fetch proxy? From dg.google.groups at thesamovar.net Mon Jan 21 04:15:50 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Mon, 21 Jan 2008 01:15:50 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: Decided I may as well post my other solution while I'm at it. The neat trick here is redefining the add, mul, etc. functions so that they raise exceptions for example if x>y then add(x,y) raises an exception which is handled by the search algorithm to mean don't continue that computation - this stops you from having to evaluate x+y AND y+x, etc. sub = lambda x,y:x-y def add(x,y): if x<=y: return x+y raise ValueError def mul(x,y): if x<=y or x==1 or y==1: return x*y raise ValueError def div(x,y): if not y or x%y or y==1: raise ValueError return x/y add.disp = '+' mul.disp = '*' sub.disp = '-' div.disp = '/' standard_ops = [ add, sub, mul, div ] def strexpression(e): if len(e)==3: return '('+strexpression(e[1])+e[0].disp+strexpression(e[2]) +')' elif len(e)==1: return str(e[0]) # I don't like this function, it's nice and short but is it clear # what it's doing just from looking at it? def expressions(sources,ops=standard_ops,minremsources=0): for i in range(len(sources)): yield ([sources[i]],sources[:i]+sources[i+1:],sources[i]) if len(sources)>=2+minremsources: for e1, rs1, v1 in expressions(sources,ops,minremsources+1): for e2, rs2, v2 in expressions(rs1,ops,minremsources): for o in ops: try: yield ([o,e1,e2],rs2,o(v1,v2)) except ValueError: pass def findfirsttarget(target,sources,ops=standard_ops): for e,s,v in expressions(sources,ops): if v==target: return strexpression(e) return None print findfirsttarget(923,[7,8,50,8,1,3]) gives: ((7*(((8*50)-1)/3))-8) Dan Goodman From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Jan 27 05:37:50 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 27 Jan 2008 11:37:50 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <60357uF1perd0U1@mid.individual.net> over at thepond.com wrote: > hehe...which part am I kidding about? The explanation was for > someone who thought python scripts were translated directly by the > processor. Who might this have been? Surely not Tim. > I have already disassembled a pyc file as a binary file. Have you? How's it look? > Maybe I was using the term assembler too broadly. A binary > compiled from an assembler source would look similar in parts to > what I disassembled. What is this supposed to mean? > That's not the point, however. I'm trying to say that a processor > cannot read a Python script, and since the Python interpreter as > stored on disk is essentially an assembler file, It isn't; it's an executable. > any Python script must be sooner or later be converted to > assembler form in order to be read by its own interpreter. This "assembler form" is commonly referred to as "Python byte code". > Whatever is typed in a Python script must be converted to binary > code. That, however, is true, though blurred. Regards, Bj?rn -- BOFH excuse #120: we just switched to FDDI. From martin at v.loewis.de Mon Jan 7 17:06:13 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Jan 2008 23:06:13 +0100 Subject: What is the encoding of __file__? In-Reply-To: <736ae822-54a9-4ee6-91fe-92c2c6eb43db@21g2000hsj.googlegroups.com> References: <736ae822-54a9-4ee6-91fe-92c2c6eb43db@21g2000hsj.googlegroups.com> Message-ID: <4782A255.8070604@v.loewis.de> > can someone quickly tell me what the encoding of __file__ is? I can't > find it in the documentation. > > BTW, I'm using Python 2.5.1 on WIndows XP and Vista. It's platform-specific - the same encoding that is used for file names (i.e. sys.getfilesystemencoding()). On Windows, it will be "mbcs", which in turn is installation-specific - on Western European/US installations, it's "windows-1252". Regards, Martin From mnordhoff at mattnordhoff.com Thu Jan 3 09:48:18 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 03 Jan 2008 09:48:18 -0500 Subject: problem with global var In-Reply-To: <3448388f0801030638sd285c7dh78b9ea9f7b911139@mail.gmail.com> References: <3448388f0801030638sd285c7dh78b9ea9f7b911139@mail.gmail.com> Message-ID: <477CF5B2.3020500@mattnordhoff.com> Bruno Ferreira wrote: > Hi, > > I wrote a very simple python program to generate a sorted list of > lines from a squid access log file. > > Here is a simplified version: > > ################################## > 1 logfile = open ("squid_access.log", "r") > 2 topsquid = [["0", "0", "0", "0", "0", "0", "0"]] > 3 > 4 def add_sorted (list): Don't call your variable "list". There's already the built-in type "list". > 5 for i in range(50): You should probably use xrange here. > 6 if int(list[4]) > int(topsquid[i][4]): > 7 topsquid.insert(i,list) > 8 break > 8 # Max len = 50 > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] I'd just use "[:50]", the 0 is implied. > 13 while True: > 14 logline = logfile.readline() > 15 linefields = logline.split() > 16 > 17 if logline != "": > 18 add_sorted (linefields) > 19 else: > 20 break for logline in logfile: if logline: linefields = logline.split() add_sorted(linefields) else: break > 22 for i in range (len(topsquid)): > 23 print topsquid[i][4] for i in topsquid: print i[4] (You probably want to use a name other than "i" then.) > #################################### > > When I execute the program _without_ the lines 10 and 11: > > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > > it runs perfectly. > > But if I execute the program _with_ those lines, this exception is thrown: > > bruno at ts:~$ python topsquid.py > Traceback (most recent call last): > File "topsquid.py", line 20, in > add_sorted (linefields) > File "topsquid.py", line 6, in add_sorted > if int(list[4]) > int(topsquid[i][4]): > UnboundLocalError: local variable 'topsquid' referenced before assignment > > > Note that now the error shown is not related with the lines 10 and 11, > but wiht a line prior to them. > > Any hints? Basically, you're trying to read the global variable "topsquid", and then you're trying to define a local variable "topsquid". Python doesn't like that. Declare it as global by adding "global topsquid" to the top of the function. -- From bignose+hates-spam at benfinney.id.au Wed Jan 9 18:17:46 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 10 Jan 2008 10:17:46 +1100 Subject: Conventions for dummy name (was: for loop without variable) References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de> Message-ID: <873at6k2qt.fsf_-_@benfinney.id.au> "Diez B. Roggisch" writes: > The underscore is used as "discarded" identifier. So maybe > > for _ in xrange(10): > ... The problem with the '_' name is that it is already well-known and long-used existing convention for an entirely unrelated purpose: in the 'gettext' i18n library, the '_' function to get the locally-translated version of a text string. Since the number of programs that need to use something like 'gettext' (and therefore use the '_' function) is likely only to increase, it seems foolish to set one's program up for a conflict with that established usage. I've seen 'dummy' used as a "don't care about this value" name in other Python code. That seems more readable, more explicit, and less likely to conflict with existing conventions. -- \ "It is forbidden to steal hotel towels. Please if you are not | `\ person to do such is please not to read notice." -- Hotel | _o__) sign, Kowloon, Hong Kong | Ben Finney From donn.ingle at gmail.com Thu Jan 24 12:03:19 2008 From: donn.ingle at gmail.com (Donn) Date: Thu, 24 Jan 2008 19:03:19 +0200 Subject: piping into a python script In-Reply-To: <668bb39a0801240845k70174c44xfb54d519f5c3ffe2@mail.gmail.com> References: <668bb39a0801240845k70174c44xfb54d519f5c3ffe2@mail.gmail.com> Message-ID: <200801241903.20082.donn.ingle@gmail.com> > wget -i - > it doesn't do anything, just waits for your input. Your applications > probably should behave the same. Okay, that works for me. > Paddy wrote: > > ls *.a | ./fui.py -f - *.b > It doesn't seem to me that -f parameter is necessary for your > application. Yes and no, I have another option that needs to take a variable number of args. > It should treat all the arguments as the filenames, > shouldn't it? And when one of the filenames is -, just try to read > stdin. I have tested getopt and it strips the lone '-' out. I can get it from sys.argv, but then I am really doing more parsing than I want to. It's a tricky job this. I think I will look in sys.argv, if I find a single dash the I will replace that element in the list with whatever comes from stdin. Then I'll pass all of it to getopt. Thanks for the help. \d -- When you allow legends to rule your life, your world is based on fiction -- Segio Aragones (Groo the Wanderer Number 99) Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From mwm-keyword-python.b4bdba at mired.org Sat Jan 12 14:59:39 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Sat, 12 Jan 2008 14:59:39 -0500 Subject: Import and execfile() In-Reply-To: References: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> Message-ID: <20080112145939.49f59e26@bhuda.mired.org> On Fri, 11 Jan 2008 20:55:07 -0800 (PST) George Sakkis wrote: > On Jan 11, 5:24 pm, Mike Meyer > wrote: > > On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis wrote: > > > I maintain a few configuration files in Python syntax (mainly nested > > > dicts of ints and strings) and use execfile() to read them back to > > > Python. This has been working great; it combines the convenience of > > > pickle with the readability of Python. So far each configuration is > > > contained in a single standalone file; different configurations are > > > completely separate files. > > You can make the syntax cleaner by using classes to hold the values > > instead of nested dicts, etc. That way you don't have to quote the > > names of the values: > > class Foo: > > bar = 1 > > baz = 2 > Actually I am using the dict() constructor instead of literals so it's > as clean as with classes; IMO for nested options it's cleaner than > nested classes: Yup, that does that. Wasn't available last time I did this, so... > > > I understand why this fails but I'm not sure how to tell execfile() to > > > set the path accordingly. Any ideas ? > > Manipulate sys.path yourself? > That's what Mitko suggested too, and indeed it works: > However this doesn't look very clean to me. Also it's not thread-safe; I don't know that there is a clean solutions. As for not being thread-safe, I'd suggest that you should have all your configuration information loaded *before* you start any threads. This makes shutting down in case you decide there's something wrong in it easier, and in some cases may prevent inadvertently doing things that shouldn't oughta be done. In the case where you config files are parsed by the python interpreter, this goes double because a busted config file could lead to exceptions, leaving your application in an unknown state. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From haag at lsu.edu Sat Jan 5 00:47:19 2008 From: haag at lsu.edu (Alaric Haag) Date: Fri, 04 Jan 2008 23:47:19 -0600 Subject: Information on PyGMT? References: Message-ID: In article , Jeroen Ruigrok van der Werven wrote: > -On [20080104 04:11], Alaric (haag at lsu.edu.invalid) wrote: > >Unfortunately, the only site (forge.nesc.ac.uk) that seems to offer the code > >(written by Magnus Hagdorn) is not responding. I don't know if that's a > >temporary condition or if that site is out of commission. > > > >Google isn't revealing much recent discussion either.... which is sad, as I > >would imagine this to be a valuable tool! > > I am not sure how appropriate > http://www.cdc.noaa.gov/people/jeffrey.s.whitaker/python/gmt/gmt-src/doc/html/ > public/gmt.gmt-module.html > might be? > > I cannot find Magnus' PyGMT-0.2 tarball anywhere, sorry. Many thanks! I was aware of that package, which seemed to be a less complete approach, but the good news is that the NESC site came back up! From ryszard.szopa at gmail.com Mon Jan 14 17:47:36 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Mon, 14 Jan 2008 14:47:36 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> Message-ID: <65cfbd40-6612-4bd5-aa5c-a1338da0f5a7@n20g2000hsh.googlegroups.com> On Jan 14, 1:53 pm, Michele Simionato wrote: > I really need to publish this one day or another, since these > questions > about super keeps coming out: > > http://www.phyast.pitt.edu/~micheles/python/super.html Thanks, Michele! Your essay was enlightening [2]. Specially if you take in account super's documentation is slightly outdated :). I also read Raymond Hettinger's article about descriptors (which you mention, but don't link to!) and decided to use them to reimplement methods that always call their superclass [1] method of the same name. Could you tell me what are the pros and cons of the two approaches (i.e. writing a decorator function and a decorator descriptor class)? The former gives slightly shorter code, while the second gives access to the original function and I somehow feel it is more... classy :) [code follows] Cheers, -- Richard [1] By which I mean the first class in their MRO. [2] I also found some other papers of yours about the "not for the faint of heart" corners of Python: MRO, metaclasses, class memoization, etc. and they were most enjoyable and interesting. def callingprevious1(fun): """Decorator to call a superclass' fun first. Decorator function approach. >>> class parent(object): ... def foo(self): ... print "I am foo of parent" ... >>> class child(parent): ... @callingprevious1 ... def foo(self): ... print "I am foo of child" ... >>> x = child() >>> x.foo() I am foo of parent I am foo of child >>> child.foo(x) I am foo of parent I am foo of child """ name = fun.__name__ def decorated(self, *args, **kwargs): try: super_object = super(self.__class__, self) getattr(super_object, name)(*args, **kwargs) except AttributeError: pass # if parent doesn't implement fun, we don't care # about it return fun(self, *args, **kwargs) # hopefully None decorated.__name__ = name return decorated class callingprevious(object): """ Decorator making the defined method call the method of the first superclass in mro at the beginning. Descriptor approach. >>> class parent(object): ... def foo(self): ... print "I am foo of parent" ... >>> class child(parent): ... @callingprevious ... def foo(self): ... print "I am foo of child" ... >>> x = child() >>> x.foo() I am foo of parent I am foo of child >>> child.foo(x) I am foo of parent I am foo of child """ def __init__(self, initval): self.name = initval.__name__ self.__combine_methods(initval) def __combine_methods(self, val): self.val = val def with_parent(obj, *args, **kwargs): try: parent_method = getattr(super(type(obj), obj), self.val.__name__) except AttributeError: pass else: parent_method(*args, **kwargs) return self.val(obj, *args, **kwargs) with_parent.__name__ = self.val.__name__ self.to_return = with_parent def __get__(self, obj, objtype): from types import MethodType # btw, is it anyhow better than just returning the function? return MethodType(self.to_return, obj, objtype) def __set__(self, obj, val): self.__combine_methods(val) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 28 15:27:15 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 28 Jan 2008 21:27:15 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> <6067h9F1otsbrU1@mid.individual.net> <13ps3djqrl4ap5b@corp.supernews.com> Message-ID: <606s53F1p4slrU1@mid.individual.net> Grant Edwards wrote: > No, it doesn't output corresponding machine code (that's what > some Java JIT implementations do, but I'm not aware of any > Python implementations that do that). The virtual machine > interpreter just does the action specified by the bytecode. By "outputs corresponding machine code" I meant "feeds corresponding machine code to the CPU" to make the analogy clearer. Which can mean a function call. Regards, Bj?rn -- BOFH excuse #325: Your processor does not develop enough heat. From paul at boddie.org.uk Fri Jan 11 08:38:38 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 11 Jan 2008 05:38:38 -0800 (PST) Subject: Detecting OS platform in Python References: Message-ID: <7441a2f9-e0b3-4686-b799-4c25e78ea94c@k2g2000hse.googlegroups.com> On 11 Jan, 04:14, Mike Meyer wrote: > On Thu, 10 Jan 2008 18:37:59 -0800 (PST) Devraj wrote: > > > My Python program needs reliably detect which Operating System its > > being run on, infact it even needs to know which distribution of say > > Linux its running on. The reason being its a GTK application that > > needs to adapt itself to be a Hildon application if run on devices > > like the N800. > > I don't think it can be done. For most Unix system, os.uname() will give > you the information you want: > > >>> os.uname() [...] > GNU/Linux distributions are collections of lots of people software, so > each has it's own way to state what "distribution" it is. I believe > there's some sort of standard - except not everybody follows it. So > you wind up using a series of heuristics to chase this information > down. On Red Hat distributions, there appears to be a file called /etc/ redhat-release containing the distribution name. I can't remember the Debian equivalent, but it may be /etc/debian_version or something like that. There's LSB-related stuff, too, but I'm not sure if any of that tells you about the distribution itself. [...] > I'm not a GTK programmer, and have never even heard of Hildon. Is > there some associated module you could try and import that doesn't > exist on the N800? I.e.: > > try: > import gtk > mygui = 'gtk' > except ImportError: > import Hildon > mygui = 'Hildon' > > or maybe something like: > > import gtk > mygui = 'gtk' if not hasattr(gtk, 'Hildon') else 'Hildon' There must be Hildon-related modules or features that one can import or test for, as Mike suggests. In the desktop module [1], I generally test various environment variables or the output of various programs in order to deduce which desktop environment is being used, but this is in software which isn't generally trying to display a graphical user interface. Just testing for the presence of a file or a program isn't usually enough because on systems where desktop environments co- exist, for example, the presence of a GNOME-related file or program doesn't mean that the user is actually using GNOME at that particular time. If you might be using Hildon and are actually displaying a GUI, however, attempting to get the resources you need should be enough to confirm whether you're running Hildon or not. Paul [1] http://www.python.org/pypi/desktop From jared.grubb at gmail.com Tue Jan 15 13:35:52 2008 From: jared.grubb at gmail.com (Jared Grubb) Date: Tue, 15 Jan 2008 10:35:52 -0800 Subject: Iterate through slots Message-ID: <925822270801151035x7975fdb6s972efc40ed4f6902@mail.gmail.com> How can I iterate through the slots of a class, including those it inherits from parent classes? class C(object): __slots__ = ['a'] class D(C): __slots__ = ['b'] >>> d = D() >>> d.__slots__ ['b'] >>> d.a = 1 # this works, so slots inherit properly >>> d.b = 2 >>> d.c = 3 # this doesnt work, like we expect Traceback (most recent call last): File "", line 1, in ? AttributeError: 'D' object has no attribute 'c' The reason I want to do this is that I want to have the following, and let all the children inherit the parent's __init__: class Parent(object): __slots__ = ['whatever'] def __init__(self, context=None, **kw): if context is None: context=getContext() for slot in SLOTITERATORHERE: # Resolve the slot's value, even for those things not specifically set in kw class Child1(Parent): __slots__ = ['for_me_only'] -------------- next part -------------- An HTML attachment was scrubbed... URL: From peng.kyo at gmail.com Wed Jan 16 22:40:59 2008 From: peng.kyo at gmail.com (J. Peng) Date: Thu, 17 Jan 2008 11:40:59 +0800 Subject: assigning values in python and perl In-Reply-To: <18c1e5f20801161934m69ff44edo1e35f5381f7d2928@mail.gmail.com> References: <18c1e5f20801161934m69ff44edo1e35f5381f7d2928@mail.gmail.com> Message-ID: <18c1e5f20801161940m4966b4dfod288fed0ae5eca46@mail.gmail.com> May I ask, python's pass-by-reference is passing the object's reference to functions, but perl, or C's pass-by-reference is passing the variable itself's reference to functions. So althought they're all called pass-by-reference,but will get different results.Is it? On Jan 17, 2008 11:34 AM, J. Peng wrote: > I just thought python's way of assigning value to a variable is really > different to other language like C,perl. :) > > Below two ways (python and perl) are called "pass by reference", but > they get different results. > Yes I'm reading 'Core python programming', I know what happened, but > just a little confused about it. > > $ cat t1.py > def test(x): > x = [4,5,6] > > a=[1,2,3] > test(a) > print a > > $ python t1.py > [1, 2, 3] > > $ cat t1.pl > sub test { > my $ref = shift; > @$ref = (4,5,6); > } > > my @a = (1,2,3); > test(\@a); > > print "@a"; > > $ perl t1.pl > 4 5 6 > From devnew at gmail.com Wed Jan 2 00:00:50 2008 From: devnew at gmail.com (devnew at gmail.com) Date: Tue, 1 Jan 2008 21:00:50 -0800 (PST) Subject: using Tix.FileSelectBox in python Message-ID: hi i was using Tix.FileSelectBox to select imagefiles from a directory..when i click on image and click my app's okbutton i can get the selected image name by self.selimgname=self.myfileselectbox.selection.cget("value") after this if i just select a folder and not an image and click ok then again the myfileselectbox.selection.cget("value") gives the previously selected image name. i would like to give an error msg asking the user if he doen't select an image..how can i do this? devnew From ptmcg at austin.rr.com Sun Jan 27 20:17:04 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 27 Jan 2008 17:17:04 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net><60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> Message-ID: <92e2e361-68f4-4cd2-b0d4-750e19a06faf@s19g2000prg.googlegroups.com> On Jan 27, 6:13?pm, "Terry Reedy" wrote: > > I think this version, with this name convention, is nice enough to possibly > go in the stdlib if there were an appropriate place for it. ?Not sure where > though. ?If there were a classtools module.... > > tjr +1 I thought at one time there was to be a "decorators" module in the stdlib for just this kind of useful item. At minimum, you could post this to the Python wiki at http://wiki.python.org/moin/PythonDecoratorLibrary. -- Paul From davidben at fmtc.com Wed Jan 16 15:01:32 2008 From: davidben at fmtc.com (DBenjamin) Date: Wed, 16 Jan 2008 12:01:32 -0800 (PST) Subject: Help wanted with GTK+ program References: Message-ID: <794b1708-2668-408e-8149-c52e1b0ff909@j78g2000hsd.googlegroups.com> On Jan 8, 5:49 pm, Hollabu... at gmail.com wrote: > I'm working on a simple GTK+ wrapper around the flash Pandora Radio > player (Pandora.com). > > It's very basic right now but I've got it almost working. > I'm using gtkmozembed to fetch and use the player and dbus to detect > multimedia keys. > The only problem I'm having is that the mozembed widget doesn't seem > to recognize the fake keypress event sent to it. > > CODE > > #!/usr/bin/env python > > import gtk > import gtkmozembed > import dbus > from dbus.mainloop.glib import DBusGMainLoop > > class Wrapper: > def __init__(self): > # Set-up the wrapper for the player > > self.win = gtk.Window() # Create a new GTK window called 'win' > > self.win.set_title("Pandora Player") # Set the title of the > window > self.win.set_icon_from_file('favicon.ico') # Set the window > icon to a web browser icon > self.win.set_position(gtk.WIN_POS_CENTER) # Position the > window in the centre of the screen > > self.win.connect("destroy", self.close_window) # Connect the > 'destroy' event to the 'CloseWindow' function, so that the app will > quit properly > > # Handle media keys under Gnome > DBusGMainLoop(set_as_default=True) > bus = dbus.Bus(dbus.Bus.TYPE_SESSION) > settings = bus.get_object('org.gnome.SettingsDaemon', '/org/ > gnome/SettingsDaemon') # Connect to gnome settings D-Bus > settings.connect_to_signal("MediaPlayerKeyPressed", > self.action) > > # Create the browser widget > gtkmozembed.set_profile_path("/tmp", "simple_browser_user") # > Set a temporary Mozilla profile (works around some bug) > self.mozbrowser = gtkmozembed.MozEmbed() # Create the browser > widget > > # Set-up the browser widget before we display it > self.win.add(self.mozbrowser) # Add the 'mozbrowser' widget to > the main window 'win' > self.mozbrowser.load_url("https://www.pandora.com:443/radio/ > tuner_8_2_0_2_pandora.swf") # Load Pandora > self.mozbrowser.set_size_request(640,540) # Size arrived at > after careful trial and error > self.mozbrowser.show() # Needed for correct size > > self.win.show_all() # Show the window > > def PlayPause(self, ): > event = gtk.gdk.Event(gtk.gdk.KEY_PRESS) > event.keyval = gtk.keysyms.space > event.time = 0 # assign current time > self.mozbrowser.grab_focus() > self.win.emit('key_press_event', event) > > def ThumbsDown(self): > event = gtk.gdk.Event(gtk.gdk.KEY_PRESS) > event.keyval = gtk.keysyms.minus > event.time = 0 # assign current time > self.mozbrowser.grabfocus() > self.win.emit('key_press_event', event) > > def ThumbsUp(self): > event = gtk.gdk.Event(gtk.gdk.KEY_PRESS) > event.keyval = gtk.keysyms.plus > event.time = 0 # assign current time > self.mozbrowser.grabfocus() > self.win.emit('key_press_event', event) > > def Skip(self): > event = gtk.gdk.Event(gtk.gdk.KEY_PRESS) > event.keyval = gtk.keysyms.Right > event.time = 0 # assign current time > self.mozbrowser.grabfocus() > self.win.emit('key_press_event', event) > > # Handles key presses > def action(self, *keys): > for key in keys: > if key == "Play": > self.PlayPause() > elif key == "Stop": > self.ThumbsUp() > elif key == "Previous": > self.ThumbsDown() > elif key == "Next": > self.Skip() > > def close_window(self, caller_widget): > """Close the window and exit the app""" > gtk.main_quit() # Close the app fully > > if __name__ == "__main__": > wrapper = Wrapper() > gtk.main() I was looking for something like you are writing and seen this post, maybe it would help you? http://rjoblog.wordpress.com/2007/12/19/pandora-4-all/ He is showing this url: https://www.pandora.com/radio/tuner_8_2_0_2_pandora.swf From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 25 08:05:09 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 25 Jan 2008 14:05:09 +0100 Subject: [OT] "just like Java" (was :Re: translating Python to Assembler) In-Reply-To: References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: <4799de28$0$12358$426a74cc@news.free.fr> Christian Heimes a ?crit : > Wim Vander Schelden wrote: >> Python modules and scripts are normally not even compiled, if they have >> been, >> its probably just the Python interpreter packaged with the scripts and >> resources. > > No, that is not correct. Python code is compiled to Python byte code and > execute inside a virtual machine just like Java or C#. I'm surprised you've not been flamed to death by now - last time I happened to write a pretty similar thing, I got a couple nut case accusing me of being a liar trying to spread FUD about Java vs Python respective VMs inner working, and even some usually sensible regulars jumping in to label my saying as "misleading"... From noemailplease0001 at gmail.com Tue Jan 29 14:51:04 2008 From: noemailplease0001 at gmail.com (noemailplease0001 at gmail.com) Date: Tue, 29 Jan 2008 11:51:04 -0800 (PST) Subject: breaking out of outer loops Message-ID: Any elegant way of breaking out of the outer for loop than below, I seem to have come across something, but it escapes me for i in outerLoop: for j in innerLoop: if condition: break else: continue break Thanks, K From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 23 08:02:39 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 23 Jan 2008 14:02:39 +0100 Subject: translating Python to Assembler References: <6ircp35hju5cb2iu9ip6rc7qjt9d585cde@4ax.com> Message-ID: <5vos7fF1nn9odU1@mid.individual.net> over at thepond.com wrote: > My expertise, if any, is in assembler. I'm trying to understand > Python scripts and modules by examining them after they have been > disassembled in a Windows environment. IMHO, that approach doesn't make sense to understand scripts or modules (except if you have some kind of super brain -- because Python is _very_ high level). It only does if you want to understand the Python compiler/interpreter you use. For compilers that output machine code directly this *may* make sense (but for more complex programs it will become very difficult). If you'd like to get a "low level" look into how things are done in Python, try the dis module. Using dis.dis, you can look at disassembled Python byte code. Regards, Bj?rn -- BOFH excuse #251: Processes running slowly due to weak power supply From hniksic at xemacs.org Sat Jan 26 22:25:12 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 27 Jan 2008 04:25:12 +0100 Subject: file write question References: <62b96f11-1a81-4be8-9dcb-348ee38ebe16@f10g2000hsf.googlegroups.com> Message-ID: <87myqsq7af.fsf@mulj.homelinux.net> "Robb Lane (SL name)" writes: > ... or just leave it till it's done? > I don't need to use the file contents until the script is done > (although it would be nice... just to check it while it's working), Use flush() to force the contents out at opportune times without closing and reopening the file object. From mr.cerutti at gmail.com Thu Jan 17 11:28:35 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 17 Jan 2008 11:28:35 -0500 Subject: Is this a bug, or is it me? In-Reply-To: References: <87myr4o3sg.fsf@mulj.homelinux.net> Message-ID: <51302a8c0801170828u1c5adad9j7170dc51c8a07a1d@mail.gmail.com> On Jan 17, 2008 11:08 AM, wrote: > On Jan 17, 4:59 pm, "Neil Cerutti" wrote: > > Generator expressions, unlike list comprehensions, have their own > > scope so that they don't "leak" names to the enclosing scope. The > > Python rule forbidding access to the locals of enclosing scopes is > > preventing the class names from working in the generator expression. > > Ah, that explains why my random suggestion worked but was not > helpful :) I feel like I am learning a lot today! Me, too. Especially about wrongly oversimplifying stuff that's complicated. My statement above isn't exactly right, since generator expressions usually *can* access stuff in the enclosing local scope. They wouldn't be very useful if they couldn't. -- Neil Cerutti From B.Ogryczak at addr.in.reply-to.invalid Sun Jan 20 10:42:16 2008 From: B.Ogryczak at addr.in.reply-to.invalid (Bart Ogryczak) Date: Sun, 20 Jan 2008 15:42:16 +0000 (UTC) Subject: too long float References: Message-ID: On 2008-01-18, citizen J. Peng testified: > hello, > > why this happened on my python? >>>> a=3.9 >>>> a > 3.8999999999999999 >>> a = 3.9 >>> print a 3.9 bart -- "PLEASE DO *NOT* EDIT or poldek will hate you." - packages.dir (PLD) http://candajon.azorragarse.info/ http://azorragarse.candajon.info/ From george.sakkis at gmail.com Mon Jan 7 13:21:55 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 7 Jan 2008 10:21:55 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Message-ID: On Jan 7, 9:27 am, Kay Schluehr wrote: > On Jan 7, 12:53 pm, Berco Beute wrote: > > > Cool! We knew it would happen one day :) > > What could be the reason? Python 3? Jython 2.2? Java's loss of > > sexiness? > > Python eats Perls lunch as a scripting language. Even better, it is not threatened by Ruby as many from the buzzword- ridden RoR crowd would like to believe. From dg.google.groups at thesamovar.net Tue Jan 22 17:56:23 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Tue, 22 Jan 2008 14:56:23 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> Message-ID: Arnaud and Terry, Great solutions both of you! Much nicer than mine. I particularly like Arnaud's latest one based on folding because it's so neat and conceptually simple. For me, it's the closest so far to my goal of the most elegant solution. So anyone got an answer to which set of numbers gives the most targets from 100 onwards say (or from 0 onwards)? Is Python up to the task? A thought on that last one. Two ways to improve speed. First of all, you don't need to rerun from scratch for each target. Secondly, you can try multiple different sets of numbers at the same time by passing numpy arrays instead of single values (although you have to give up the commutativity and division by zero optimisations). Dan Goodman From Scott.Daniels at Acm.Org Tue Jan 1 13:17:10 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 01 Jan 2008 10:17:10 -0800 Subject: Using mouse In-Reply-To: References: Message-ID: <13nl0ktmfgkgde5@corp.supernews.com> Lucas Prado Melo wrote: > I would like to control mouse events (i.e. I would like to "click" and > move mouse around by code). > How do I do this in python? A python doesn't have a mouse for long; it eats them up. It is your display and user I/O system that deals with mice, and so, inevitably, the answer to your question (and, indeed whether such a thing is even possible) depends on the OS and display packages you are using. --Scott David Daniels Scott.Daniels at Acm.Org From fcharlypillai at gmail.com Sat Jan 5 07:34:39 2008 From: fcharlypillai at gmail.com (cf29) Date: Sat, 5 Jan 2008 04:34:39 -0800 (PST) Subject: TextWrangler and new Python version (Mac) References: <4e34d25a-460b-40c2-96c0-60c98b5e0ab8@m34g2000hsf.googlegroups.com> Message-ID: <7b89b172-29de-4e0e-841d-bd818413a92c@l1g2000hsa.googlegroups.com> Thank you Jean, I could fix this problem. Creating the symbolic link wasn't really obvious though. They also say about the documentation: *Extract the documentation files, and place them in some suitable location, e.g. ~/Library/Python-Docs *Edit your "environment.plist" file, and create an environment variable PYTHONDOCS to the location of the folder which contains the Python documentation. Is that the html version of the Python documentation? Do you know more about this "environment.plist" file? Where is it supposed to be? I didn't find any. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 9 04:13:50 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 09 Jan 2008 10:13:50 +0100 Subject: Newbie question: Classes In-Reply-To: References: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com> Message-ID: <4784904f$0$18061$426a34cc@news.free.fr> Daniel Fetchinson a ?crit : nb: answering to the (unknown) OP: >> Basically, I have created a program using tkinter without using any class >> structure, simply creating widgets and functions (and finding ways around >> passing variables from function to function, using global variables etc). One of the points of OO is indeed to avoid excessive use of global state and "cargo" data. Now note that this can also be (at least partially) done using closures, callbacks, partial application, and other functional tricks. >> The program has become rather large ( lines?) I am trying to now put it into >> a class structure, because I hear it is easier to handle. It can make thing easier - from a maintainance/reusability POV at least - if you're at ease with OO design and programming. But getting OO right - specially when it comes to design - is not necessarily trivial neither, so don't think of it as a "silver bullet". >> So basically, I put all the stuff into a class, making the widgets in the >> "def __init__(self, root)" (root being my Tk() ) and then I have had to put >> a "self." in front of any instance of any variable or widget. Is this right? Probably not. >> it seems like nothing is any easier (except having variables locally). Is >> this right? Should I be creating more classes for different things or what? Probably, yes. You could try to identify small sets of functions dealing with a common (small) set of data, and regroup them into (small) classes, then think about how instances of these classes will work together. Also remember to separate the "logic" (data structures and rules about these data structures) from the "presentation" (the GUI code). The "logic" part should be usable independantly (with a CLI interface, a web interface, etc). My two cents... From terry at jon.es Tue Jan 8 21:34:07 2008 From: terry at jon.es (Terry Jones) Date: Wed, 9 Jan 2008 03:34:07 +0100 Subject: Open a List of Files In-Reply-To: Your message at 21:03:08 on Tuesday, 8 January 2008 References: <874pdomrrd.fsf@mulj.homelinux.net> Message-ID: <18308.12959.742868.758136@terry.local> Hi BJ > > Fredrik Lundh writes: > > Or in a dict: > > > > open_files = {} > > for fn in ['messages', 'recipients', 'viruses']: > > open_files[fn] = open(getfilename(fn), 'w') > > I decided that I was just trying to be "too smooth by 1/2" so I fell back > to ... > > messages = open(os.path.join(host_path,'messages.txt'), 'wb') > deliveries = open(os.path.join(host_path,'deliveries.txt'), 'wb') > actions = open(os.path.join(host_path,'actions.txt'), 'wb') > parts = open(os.path.join(host_path,'parts.txt'), 'wb') > recipients = open(os.path.join(host_path,'recipients.txt'), 'wb') > viruses = open(os.path.join(host_path,'viruses.txt'), 'wb') > esp_scores = open(os.path.join(host_path,'esp_scores.txt'), 'wb') I think you should revisit this decision. Something like Fredrik's code is the way to go. It has multiple advantages: - It's much shorter. - It's arguably easier to add/remove to/from. - It has less risk of error (much less repetition). - It allows your code to later take a string file tag and write to that file by looking up its file descriptor in the dict. - You can close all open files with a trivial loop. Also, if you start writing code like Fredrik's instead of like what you fell back on you'll make yourself a better programmer (in general, not just in Python). Terry From dstromberglists at gmail.com Thu Jan 17 15:26:07 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 17 Jan 2008 20:26:07 GMT Subject: bags? 2.5.x? References: <478bbae6$0$25383$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Mon, 14 Jan 2008 20:41:27 +0100, Wildemar Wildenburger wrote: > Dan Stromberg wrote: >> Is there a particular reason why bags didn't go into 2.5.x or 3000? >> >> I keep wanting something like them - especially bags with something >> akin to set union, intersection and difference. >> > How about this recepie > ? > > /W I'd found this with google, but thank you for making sure I was aware of it. The author of the bag class said that he was planning to submit bags for inclusion in 2.5 - is there a particular reason why they didn't go in? I keep finding a need for bags. In the past, I've done this sort of thing with dictionaries, but it's much nicer to have a bag class, and of course it's better to have it in the standard library than to slurp it into this, that and the other project. From NMBooker at googlemail.com Sun Jan 27 18:01:08 2008 From: NMBooker at googlemail.com (NMBooker) Date: Sun, 27 Jan 2008 15:01:08 -0800 (PST) Subject: Python System information References: <35d49700-9def-478e-8047-de548553e8c0@s8g2000prg.googlegroups.com> Message-ID: <655bcec0-1027-4fb6-a98d-2f5f4f600adf@z17g2000hsg.googlegroups.com> On Jan 27, 2:23 pm, Martin Saturka wrote: > > How can i get system information like CPU load and RAM usage in linux. > > What about 'pystatgrab'? > It provides good info, with a limitation - it does not have CPU info > for particular CPUs, it takes just the cumulative CPU info.http://www.i-scream.org/pystatgrab/http://packages.debian.org/statgrab > > M. Brilliant. Sorry about my misleading post I didn't know about statgrab. Thanks M. Nick Booker From sergio.correia at gmail.com Wed Jan 30 22:38:30 2008 From: sergio.correia at gmail.com (Sergio Correia) Date: Wed, 30 Jan 2008 22:38:30 -0500 Subject: Removing Pubic Hair Methods In-Reply-To: <87sl0en02e.fsf@benfinney.id.au> References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> <9275bfdb-8f07-4c63-abbf-40c136388bf3@i7g2000prf.googlegroups.com> <87sl0en02e.fsf@benfinney.id.au> Message-ID: So in this case it is REALLY better to ask for permission rather than forgiveness? On Jan 30, 2008 10:30 PM, Ben Finney wrote: > MRAB writes: > > > On Jan 31, 12:57 am, Asun Friere wrote: > > > Ouch!! If on the other hand 'females' is populated by instances of > > > (or merely includes instances of) class 'Human', I suggest you > > > test for female.consent somewhere in your code! > > > > > The Pythonic approach would be to try the action and catch a > > NoConsentException. > > You're making the classic Pythonista mistake: you behave as though > EAFP applies everywhere. I assure you, in the above situation, it does > not apply. > > -- > \ "He may look like an idiot and talk like an idiot but don't let | > `\ that fool you. He really is an idiot." ?Groucho Marx | > _o__) | > Ben Finney > -- > > http://mail.python.org/mailman/listinfo/python-list From ganeshborse at gmail.com Tue Jan 8 04:33:41 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Tue, 8 Jan 2008 01:33:41 -0800 (PST) Subject: Python modules - how to create & which are better Message-ID: <762240a7-ad30-47aa-a760-f1795b68915f@j20g2000hsi.googlegroups.com> I have embedded Python in my C++ application & creating Python function from the expression. I am then evaluating those Python compiled function (byte code) using PyObject_CallObject. I want to create a Python module which will have functions called by my user defined functions from the embedded Python interpreter. What will be best approach in this case? Should I be creating normal .py modules or .so modules (python extended with C code)? For me, most important is the executiong speed of the code in these modules. I want them to be fast, as those will be executed lot many times & in time bound fashion. Any suggestions on this? From BjornSteinarFjeldPettersen at gmail.com Sun Jan 27 04:07:38 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 27 Jan 2008 01:07:38 -0800 (PST) Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> Message-ID: On Jan 27, 9:58 am, o... at thepond.com wrote: > On Fri, 25 Jan 2008 17:44:07 -0800 (PST), ajaksu > wrote: > > > > >On Jan 25, 11:36 pm, ajaksu wrote: > >> On Jan 25, 11:10 pm, o... at thepond.com wrote: > >[...] > > >Gaah, is this what's going on? > > >ajaksu at Belkar:~$ cat error.txt > >This is not assembler... > > >ajaksu at Belkar:~$ ndisasm error.txt > >00000000 54 push sp > >00000001 686973 push word 0x7369 > >00000004 206973 and [bx+di+0x73],ch > >00000007 206E6F and [bp+0x6f],ch > >0000000A 7420 jz 0x2c > >0000000C 61 popa > >0000000D 7373 jnc 0x82 > >0000000F 656D gs insw > >00000011 626C65 bound bp,[si+0x65] > >00000014 722E jc 0x44 > >00000016 2E db 0x2E > >00000017 2E db 0x2E > >00000018 0A db 0x0A > > >:/ > > not sure what you're saying. Sure looks like assembler to me. Take the > '54 push sp'. The 54 is an assembler opcode for push and the sp is > the stack pointer, on which it is operating. go troll somewhere else (you obviously don't know anything about assembler and don't want to learn anything about Python). -- bjorn From thelanguageofcities at gmail.com Mon Jan 28 11:13:53 2008 From: thelanguageofcities at gmail.com (Max) Date: Mon, 28 Jan 2008 08:13:53 -0800 (PST) Subject: Python Genetic Algorithm References: <13pq880abaohbe4@corp.supernews.com> Message-ID: <327c3388-a2f2-425a-8d57-1cca68631457@j20g2000hsi.googlegroups.com> On Jan 27, 7:25 pm, Steven D'Aprano wrote: > Just pass the class itself. For example: > > # Define a class. > class Parrot(object): > pass > > x = "Parrot" # x is the NAME of the class > y = Parrot # y is the CLASS itself > z = Parrot() # z is an INSTANCE of the class > > You can use the class as a object, exactly the same as you can use a dict > or a string or a float or any other object. y() will create a new Parrot > instance exactly the same way that Parrot() would. > Okay, I'm getting into the thick of things, and I want to make sure I'm implementing this correctly. I have a module Individual.py which contains the abstract class Individual and the class BitString. My population __init__ takes chromosome as a parameter, and checks: if chromosome is not issubclass(Individual): raise Exception("Chromosome type must be a subclass of Individual.") Then it creates individuals as instances of chromosome (x = chromosome(params)). I'm pretty sure this is all right - what I'm wondering is, when actually creating a population, would I pass Individual.BitString as a parameter? That's what I have now. I have similar worries about my selection scheme. Right now I have the function rouletteWheel defined as a member of Population, so I pass the selector to my GA class as Population.rouletteWheel (making sure I have Population imported). I just want to ensure that this is correct. From bignose+hates-spam at benfinney.id.au Mon Jan 14 18:05:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 10:05:38 +1100 Subject: paging in python shell References: <31cb9b30-68f0-48ed-90f5-0e876fb08210@1g2000hsl.googlegroups.com> Message-ID: <87r6gkdn3x.fsf@benfinney.id.au> John Machin writes: > C:\junk>python demomore.py | more Your example uses the OS shell to invoke a pager on the output of the Python process. The OP was asking about paging *within* the Python shell. To my knowledge there's nothing in the default Python shell that enables what the OP is asking for. There are other Python shells, e.g. Idle, ipython, or a Python window inside Emacs, that may be better suited. -- \ "Compulsory unification of opinion achieves only the unanimity | `\ of the graveyard." -- Justice Roberts in 319 U.S. 624 (1943) | _o__) | Ben Finney From wicijowski at gmail.com Thu Jan 24 07:02:45 2008 From: wicijowski at gmail.com (janislaw) Date: Thu, 24 Jan 2008 04:02:45 -0800 (PST) Subject: Increment Variable Name References: Message-ID: <9e9714f6-24d8-46fe-908f-205d223574cd@p69g2000hsa.googlegroups.com> On Jan 23, 11:45?pm, David Brochu wrote: > This is probably really trivial but I'm stumped.... :-( > > Does anyone know how to increment a variable name? > > For example: > > I know the length of a list and I want to pass each element of a list ? > to a unique variable, thus I want to increment variable names. If the ? > list length = 4, i want to have the following variables: var1, var2, ? > var3, var4. > > Thanks Do you want to do this?: >>> locals() {'__builtins__': , '__name__': '__main__', 'pywin': , '__doc__': None} >>> locals()['var'+str(1)] = "spam" >>> locals() {'__builtins__': , '__name__': '__main__', 'var1': 'spam', 'pywin': , '__doc__': None} >>> var1 'spam' From stefan.behnel-n05pAM at web.de Wed Jan 23 11:08:59 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 17:08:59 +0100 Subject: Lxml on mac In-Reply-To: References: <47975B09.8090705@web.de> Message-ID: <4797669B.2040203@web.de> marcroy.olsen at gmail.com wrote: > On Jan 23, 4:19 pm, Stefan Behnel wrote: >> marcroy.ol... at gmail.com wrote: >>> What to one do if one what to use lxml(http://codespeak.net/lxml/ >>> index.html) on a mac? >> Have you tried installing up-to-date versions of libxml2/libxslt and running >> >> easy_install lxml >> >> ? > > No not yet. That was my nest step. > > But do anybody know if there is an easy way to use schema validation > in python(on a mac) ? You mean: easier than the above? Likely not many... Stefan From jens at aggergren.dk Tue Jan 29 08:58:54 2008 From: jens at aggergren.dk (Jens) Date: Tue, 29 Jan 2008 05:58:54 -0800 (PST) Subject: Terse Syntax through External Methods References: <5vu9gaF1no9i1U1@mid.uni-berlin.de> Message-ID: On Jan 25, 3:19 pm, "Diez B. Roggisch" wrote: > Jens schrieb: > > > > > Hello Everyone > > > I'm newbie to Zope and i have a few questions regarding external > > methods. What i wan't to do > > is provide a terse syntax for converting urls to special tracking > > urls: > > > > > > turns the provided url into something like > > >http://host/tracking?url=http%3A%2F%2Fmyurl%2F > > > in the output. > > > i've been trying to use a external procedure like this. > > > ## Script (Python) "track_link" > > ##bind container=container > > ##bind context=context > > ##bind namespace=_ > > ##bind script=script > > ##bind subpath=traverse_subpath > > ##parameters=self,url > > ##title=track link > > ## > > return "%s%s" % (self.tracking_prefix, url_quote(url)) > > > This doesn't work because because the method doesn't have access to > > the environment. Obviously I don't wan't to pass everything explicitly > > into the function as this would defeat the purpose of the exercise, > > namely to provide a terse syntax. > > > I have a background in other languages so I might be missing something > > conceptually with regard Zope and DTML.. Is there a better was of > > doing this, perhaps without using external methods? Currently im doing > > the following which isn't very elegant: > > > in content document > > > tracking>">link > > ... > > tracking: > > > > > Appreciate any input you might have on this- > > Is it really needed to use an external method for this, or isn't a > "normal" python script enough already? > > If it has to be an External method, you can't access such a context > AFAIK. But then you can create a python script that _has_ this context, > and passese it to the external method. Not the nicest solution, but > should work. > > Diez Like I said i'm a newbie. I though the deal with Zope was that i couldn't really do inline scripting (for security reasons) like in php but had to use these external methods. how does one go about creating a "normal" python script exactly and how do I invoke it's functionality? From noemailplease0001 at gmail.com Tue Jan 29 20:17:36 2008 From: noemailplease0001 at gmail.com (noemailplease0001 at gmail.com) Date: Tue, 29 Jan 2008 17:17:36 -0800 (PST) Subject: Appropriate use of Property() Message-ID: <72c9d910-f19a-407d-91cf-5599fa3e73b3@h11g2000prf.googlegroups.com> Property() can be used to rid ourselves of the extra effort of using two different methods (getAttrib() setAttrib()) for access of an attribute without giving direct access to the attribute, thus making it more elegant. So, the outsider using my module accesses the attribute with the syntax 'Object.attrib', but since this syntax looks as if he is accessing the attribute (rather than through a descrtiptor), should we subscribe to this syntax only when the attribute is both readable and writable? i.e., if I have an attribute which I strongly believe would always be only readable, should I go with the old style 'Object.getAttrib()'? Would like to know different perspectives. Thanks, K From xng at xs4all.nl Tue Jan 8 14:57:07 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Tue, 08 Jan 2008 20:57:07 +0100 Subject: Python or PowerShell ? In-Reply-To: <87hchodstr.fsf@physik.rwth-aachen.de> References: <87hchodstr.fsf@physik.rwth-aachen.de> Message-ID: <4783d594$0$8926$e4fe514c@dreader16.news.xs4all.nl> Torsten Bronger wrote: > Hall?chen! > > josepharmbruster at gmail.com writes: > >> I am all about using the right tool for the right purposes, [...] > > Which purpose? > >> I dug up one article from Google that talked about comparison but >> that was about it. >> >> http://www.simple-talk.com/sql/database-administration/comparing-python-and-powershell-dba-scripting-/ > > This comparison is about a very narrow field; additionally, it is a > field PowerShell was optimised for. > > Tsch?, > Torsten. > And adding to that, if you don't care about cross platform anyway, why even bother with python? I am sure that MS has tools that can do in a point and click kind of way all the things you might encounter. -- mph From sjmachin at lexicon.net Mon Jan 14 15:49:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 14 Jan 2008 12:49:02 -0800 (PST) Subject: paging in python shell References: Message-ID: <31cb9b30-68f0-48ed-90f5-0e876fb08210@1g2000hsl.googlegroups.com> On Jan 15, 7:35 am, "Alex K" wrote: > Hi Tim, > > Yes I mean piping the output into "more" for example. > Why don't you "suck it and see"??? E.g. C:\junk>copy con demomore.py for i in range(100): print 'line', i ^Z 1 file(s) copied. C:\junk>python demomore.py | more line 0 line 1 line 2 line 3 line 4 [snip] line 50 line 51 line 52 line 53 line 54 line 55 line 56 -- More -- From gagsl-py2 at yahoo.com.ar Wed Jan 2 00:14:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 02 Jan 2008 02:14:22 -0300 Subject: Newbie: Why doesn't this work References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> <13nldkj6ecl4j31@corp.supernews.com> Message-ID: En Wed, 02 Jan 2008 01:11:12 -0300, escribi?: > I am trying to experiment a little bit with new-style class and I am > confused why following example always returns 0 (zero). I was > expecting will return values from 0 to 9 and finaly > an Exception. > > class GenExample(object): > > def getInfo(self): > for no in range(10): > yield no > > myNo=property(getInfo) > > gen=GenExample() > print gen.myNo.next() > print gen.myNo.next() > . > . > print gen.myNo.next() Doing it this way, works as intended: py> gen=GenExample() py> myNo = gen.myNo py> print myNo.next() 0 py> print myNo.next() 1 ... py> print myNo.next() 9 py> print myNo.next() Traceback (most recent call last): File "", line 1, in StopIteration Why? I've seen you have read about the descriptor protocol. Methods are implemented as non-data descriptors. When you retrieve the "myNo" attribute from the "gen" instance, a bound method is created, combining the original getInfo function (stored into the class) with the gen instance. This is done *each* time the attribute is retrieved, and each time you get a different method object. That's why in your original example you always got 0: all methods are newly created ones, starting the iteration. (After the call finishes, as nobody holds any additional reference to it, the method object becomes a candidate to be garbage collected and eventually is deleted) Now it should be clear why my example above does work: I'm using always the *same* method object, previously saved into the "myNo" variable. This also explains a popular optimization technique: move attribute lookups out of a critical loop. That is, transforming this: for item in container: out.writerecord(item) into this: writerecord = out.writerecord for item in container: writerecord(item) Of course this should NOT be done blindly. -- Gabriel Genellina From arne.k.h at gmail.com Mon Jan 21 11:12:43 2008 From: arne.k.h at gmail.com (Arne) Date: Mon, 21 Jan 2008 08:12:43 -0800 (PST) Subject: Trouble writing to database: RSS-reader Message-ID: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> Hi! I try to make a rss-reader in python just for fun, and I'm almost finished. I don't have any syntax-errors, but when i run my program, nothing happends. This program is supposed to download a .xml-file, save the contents in a buffer-file(buffer.txt) and parse the file looking for start-tags. When it has found a start tag, it asumes that the content (between the start-tag and the end-tag) is on the same line, so then it removes the start-tag and the end-tag and saves the content and put it into a database. The problem is that i cant find the data in the database! If i watch my program while im running it, i can see that it sucsessfuly downloads the .xml-file from the web and saves it in the buffer. But I dont think that i save the data in the correct way, so it would be nice if someone had some time to help me. Full code: http://pastebin.com/m56487698 Saving to database: http://pastebin.com/m7ec69e1b Retrieving from database: http://pastebin.com/m714c3ef8 And yes, I know that there is rss-parseres already built, but this is only for learning. From google at mrabarnett.plus.com Tue Jan 22 15:45:05 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 22 Jan 2008 12:45:05 -0800 (PST) Subject: bags? 2.5.x? References: <478bbae6$0$25383$9b4e6d93@newsspool4.arcor-online.net> <437501ef-1b38-4e47-9106-c846a456dd49@c23g2000hsa.googlegroups.com> Message-ID: On Jan 21, 11:13 pm, Dan Stromberg wrote: > On Thu, 17 Jan 2008 18:18:53 -0800, Raymond Hettinger wrote: > >> >> I keep wanting something like them - especially bags with something > >> >> akin to set union, intersection and difference. > > >> > How about this recepie > >> > > >> The author of the bag class said that he was planning to submit bags > >> for inclusion in 2.5 - is there a particular reason why they didn't go > >> in? > > > Three reasons: > > > 1. b=collections.defaultdict(int) went a long way towards meeting the > > need to for a fast counter. > > > 2. It's still not clear what the best API would be. What should list(b) > > return for b.dict = {'a':3, 'b':0, 'c':-3}? Perhaps, [('a', 3), ('b', > > 0), ('c', -3)] or ['a', 'a', 'a'] > > or ['a'] > > or ['a', 'b', 'c'] > > or raise an Error for the negative entry. > > I'd suggest that .keys() return the unique list, and that list() return > the list of tuples. Then people can use list comprehensions or map() to > get what they really need. I think that a bag is a cross between a dict (but the values are always positive integers) and a set (but duplicates are permitted). I agree that .keys() should the unique list, but that .items() should return the tuples and list() should return the list of keys including duplicates. bag() should accept an iterable and count the duplicates. For example: >>> sentence = "the cat sat on the mat" >>> my_words = sentence.split() >>> print my_words ['the', 'cat', 'sat', 'on', 'the', 'mat'] >>> my_bag = bag(my_words) >>> print my_bag bag({'on': 1, 'the': 2, 'sat': 1, 'mat': 1, 'cat': 1}) my_list = list(my_bag) ['on', 'the', 'the', 'sat', 'mat', 'cat'] It should be easy to convert a bag to a dict and also a dict to a bag, raising ValueError if it sees a value that's not a non-negative integer (a value of zero just means "there isn't one of these in the bag"!). > > It might not be a bad thing to have an optional parameter on __init__ > that would allow the user to specify if they need negative counts or not; > so far, I've not needed them though. > > > 3. I'm still working on it and am not done yet. > > Decent reasons. :) > > Thanks! > > Here's a diff to bag.py that helped me. I'd like to think these meanings > are common, but not necessarily! > > $ diff -b /tmp/bag.py.original /usr/local/lib/bag.py > 18a19,58 > > > def _difference(lst): > > left = lst[0] > > right = lst[1] > > return max(left - right, 0) > > _difference = staticmethod(_difference) > > > def _relationship(self, other, operator): > > if isinstance(other, bag): > > self_keys = set(self._data.keys()) > > other_keys = set(other._data.keys()) > > union_keys = self_keys | other_keys > > #print 'union_keys is',union_keys > > result = bag() > > for element in list(union_keys): > > temp = operator([ self[element], other > [element] ]) > > #print 'operator is', operator > > #print 'temp is', temp > > result[element] += temp > > return result > > else: > > raise NotImplemented > > > def union(self, other): > > return self._relationship(other, sum) > > > __or__ = union > > > def intersection(self, other): > > return self._relationship(other, min) > > > __and__ = intersection > > > def maxunion(self, other): > > return self._relationship(other, max) > > > def difference(self, other): > > return self._relationship(other, self._difference) > > > __sub__ = difference From nagle at animats.com Thu Jan 24 14:56:48 2008 From: nagle at animats.com (John Nagle) Date: Thu, 24 Jan 2008 11:56:48 -0800 Subject: Sorting Large File (Code/Performance) In-Reply-To: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> Message-ID: <4798ec32$0$36333$742ec2ed@news.sonic.net> Ira.Kovac at gmail.com wrote: > Hello all, > > I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like > to sort based on first two characters. Given those numbers, the average number of characters per line is less than 2. Please check. John Nagle From cwitts at gmail.com Wed Jan 16 01:33:03 2008 From: cwitts at gmail.com (Chris) Date: Tue, 15 Jan 2008 22:33:03 -0800 (PST) Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> Message-ID: On Jan 16, 7:59 am, "J. Peng" wrote: > On Jan 16, 2008 1:45 PM, Dennis Lee Bieber wrote: > > > On Wed, 16 Jan 2008 11:09:09 +0800, "J. Peng" > > > alist = [] > > anint = 2 > > astr = "Touch me" > > > dummy(alist, anint, astr) > > > "dummy" can only modify the contents of the first argument -- the > > integer and string can not be mutated. > > Hi, > > How to modify the array passed to the function? I tried something like this: > > >>> a > [1, 2, 3] > >>> def mytest(x): > > ... x=[4,5,6] > ...>>> mytest(a) > >>> a > > [1, 2, 3] > > As you see, a was not modified. > Thanks! 'a' was not modified because you locally assigned a new object with 'x=[4,5,6]'. If you want the new list you created you will have to return it. You can see how you modify it if you were to use 'x.append()' or 'x.extend()' for eg. From steven.p.clark at gmail.com Thu Jan 10 17:02:53 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Thu, 10 Jan 2008 17:02:53 -0500 Subject: Newbie question on Classes In-Reply-To: References: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> Message-ID: <663744510801101402g14b77a71n12dd6694f0ed6ce5@mail.gmail.com> On Jan 10, 2008 4:54 PM, Fredrik Lundh wrote: > Adrian Wood wrote: > > > I can call man.state() and then woman.state() or Person.state(man) and > > Person.state(woman) to print the status of each. This takes time and > > space however, and becomes unmanageable if we start talking about a > > large number of objects, and unworkable if there is an unknown number. > > What I'm after is a way to call the status of every instance of Man, > > without knowing their exact names or number. > > > > I've gone through the relevant parts of the online docs, tried to find > > information elsewhere online, and looked for code samples, but the > > ionformation either isn't there, or just isn't clicking with me. I've > > tried tracking the names of each object in a list, and even creating > > each object within a list, but don't seem to be able to find the right > > syntax to make it all work. > > For a start, how about: > > class Person: > ... your class ... > > persons = [] > > man = Person() > persons.add(man) > > woman = Person() > persons.add(woman) > > for p in persons: > print p, p.state() > > Once you've gotten this to work, you can, if you want, look into moving > the list maintenance into the class itself (i.e. let the __init__ > function add the person to the list, and provide a destroy method that > removes it from the list). And once you've gotten that to work, you can > look at the "weakref" module for more elegant ways to handle > destruction. But one step at a time... > > > > -- > if you can keep all instances in a list, as Fredrik showed, it's easy. Otherwise you can do something like: class Person: people = [] def __init__(self, name): self.name = name Person.people.append(self) def print_state(self): print self.name some_folks = [Person('Bob'), Person('Mary')] other_guy = Person('Frank') for p in Person.people: p.print_state() This would keep the people from ever being garbage collected, but this may not be a problem for you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Wed Jan 30 04:22:18 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 30 Jan 2008 10:22:18 +0100 Subject: Unicode literals to latin-1 References: Message-ID: >>>>> (DR) wrote: >DR> How can I convert a string read from a database containing unicode literals, such as "Fr\u00f8ya" to the latin-1 equivalent, "Fr?ya"? >DR> I have tried variations around >DR> "Fr\u00f8ya".decode('latin-1') >DR> but to no avail. You have to use encode instead of decode, and the input string must be a unicode string. >>> print u"Fr\u00f8ya".encode('latin-1') Fr?ya >>> -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From paul at boddie.org.uk Fri Jan 11 12:52:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 11 Jan 2008 09:52:17 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <13od12b23hfv772@corp.supernews.com> Message-ID: <5b035c91-72eb-4d88-b19b-e89470865c5b@i7g2000prf.googlegroups.com> On 10 Jan, 21:47, Ed Jensen wrote: > Bruno Desthuilliers wrote: > > I fail to see how the existence of JIT compilers in some Java VM changes > > anything to the fact that both Java (by language specification) and > > CPython use the byte-code/VM scheme. > > While your answer was technically correct, by omitting pertinent > information, your answer lead readers to the wrong conclusion. Indeed. A perusal of the Java VM architecture documents plus any discussions around dynamic language support (and there's a discussion group about that very topic) reveal a number of differences between the CPython VM and Sun's Java VM. Moreover, despite claims about the Sun VM only being one of many, it holds a fairly similar position to that of the CPython VM in its own part of the computing world, with adoption only likely to increase now that it's open source. (And many new adopters were quite possibly using stuff like gcj previously which, as many will already know, is a native code compiler for Java.) These days, I seriously doubt that anyone uses the term "interpreted" to mean "parses the source text and works out what to do, over and over again as the program runs". Instead, I imagine that the term typically suggests the presence of a virtual processor doing what all processors do: interpret instructions. It's just that when native code is produced, we look away from the process of interpretation done by the hardware and consider it as the plain "on the metal" execution of the code. Sure, Sun's Java VM may not remove such a virtual processor entirely from the overall execution of a program, and the output of gcj may include the invocation of lots of moderately expensive library calls, but in contrast with CPython, some sequences of instructions will not ultimately be interpreted by the virtual machine at run-time. All this said, there are options other than CPython, and I imagine that they will become even more interesting to mainstream Python users over the next months and years. Paul From workitharder at gmail.com Sun Jan 6 17:23:50 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 6 Jan 2008 14:23:50 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> <617182dc-3ca1-4cf5-b1ca-1779dd8d6550@i3g2000hsf.googlegroups.com> Message-ID: On Jan 5, 5:36 pm, c... at mailinator.com wrote: > On Jan 5, 9:50 pm, Paul Hankin wrote: > > > > > On Jan 5, 5:12 pm, Paul Hankin wrote: > > > > On Jan 5, 4:14 pm, c... at mailinator.com wrote: > > > > > On Jan 5, 5:07 pm, c... at mailinator.com wrote: > > > > > > Hello, Paul and Arnaud. > > > > > While I think about your answers: do you think there is any way to > > > > > avoid shuffle? > > > > > It may take unnecessary long on a long list most of whose elements > > > > > have the property. > > > > You could generate a random shuffle of range(len(seq)) lazily, and use > > > that to iterate over your sequence. > > > > import random > > > import itertools > > > > def randxrange(n): > > > "Generate the numbers 0 to n-1 in a random order" > > > x = range(n) > > > for i in xrange(n): > > > r = random.randrange(n - i) > > > yield x[r] > > > x[r] = x[n - i - 1] > > > > def shuffled(seq): > > > "Generate the elements of seq in a random order" > > > return (seq[i] for i in randxrange(len(seq))) > > > > def pick_random(seq, prop): > > > return itertools.ifilter(prop, shuffled(seq)).next() > > > At the risk of filling this thread with my posts, here's a much > > simplified and faster version of this code that uses no extra storage. > > > import random > > > def pick_random(seq, prop): > > L = len(seq) > > for i in xrange(L): > > r = random.randrange(L - i) > > if prop(seq[r]): > > return seq[r] > > seq[r] = seq[L - i - 1] > > > -- > > Paul Hankin > > This one is good. Someone commented that you destroy the list, but > that can be fixed: > > def pick_random(seq, prop): > L = len(seq) > for i in xrange(L): > r = random.randrange(L - i) > if prop(seq[r]): > return seq[r] > seq[r], seq[L - i - 1]= seq[L - i - 1],seq[r] > > just pushing elements without the property to the end of the list > (list is mutated, true, but shuffle will do that too). In each > iteration of the for loop, there is only one random element, one check > of the property, and rebinding of elements without altering the lenght > of the list. This is optimal and has all the functionality. > > Two more comments: > for buzcor: deleting an element in the middle of a list is costly > for martin: that is certainly enough for me > > Thanks everybody! Just for fun, I profiled my answer versus the final answer over 300 seconds. I wrapped some parts of the functions in trivial functions so they would show up in the profiling. I found that my answer was 50% slower, but not because of the delete, but mostly the len() inside the loop, and the bool(seq) at the start of each loop. I was able to rewrite mine to only be 14 seconds slower (the time to make the copy at the beginning), but don't believe that's useful enough to post. ncalls tottime percall cumtime percall filename:lineno(function) 1516221 48.545 0.000 158.850 0.000 picked.py: 14(pick_random_bukzor) 3066421 19.359 0.000 53.815 0.000 picked.py:8(randrange2) 3066421 16.852 0.000 24.751 0.000 picked.py:9(len2) 1516221 14.712 0.000 14.712 0.000 picked.py:12(make_copy) 3066421 9.767 0.000 9.767 0.000 picked.py:10(notempty) 1550200 7.260 0.000 7.260 0.000 picked.py:7(delete) 1516221 31.574 0.000 104.384 0.000 picked.py: 27(pick_random) 3063737 19.556 0.000 54.617 0.000 picked.py:25(randrange3) 1516221 8.485 0.000 12.582 0.000 picked.py:26(len3) 1547516 5.611 0.000 5.611 0.000 picked.py: 24(do_transform) def delete(list, index): del list[index] def randrange2(X): return randrange(X) def len2(seq): return len(seq) def notempty(seq): if seq: return True def make_copy(l): return list(l) def pick_random_bukzor(seq, prop=bool): temp = make_copy(seq) while notempty(seq): i = randrange2(len2(temp)) if prop(temp[i]): return temp[i] else: delete(temp, i) def do_transform(seq, L, r, i): seq[r], seq[L - i - 1]= seq[L - i - 1],seq[r] def randrange3(X): return randrange(X) def len3(seq): return len(seq) def pick_random(seq, prop=bool): L = len3(seq) for i in xrange(L): r = randrange3(L - i) if prop(seq[r]): return seq[r] do_transform(seq, L, r, i) From paul at boddie.org.uk Wed Jan 30 07:19:12 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 30 Jan 2008 04:19:12 -0800 (PST) Subject: Trying to understand Python web-development References: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com> Message-ID: <2bb822db-0a33-4c47-bdd1-f4980a73fc00@m34g2000hsf.googlegroups.com> On 29 Jan, 18:11, walterbyrd wrote: > I don't know much php either, but running a php app seems straight > forward enough. I think that this (the ease of PHP application deployment) is one of the things that keeps Python framework developers up at night, regardless of whether the cause is technical (what processes or components are running) or social (that hosting providers install enough of the useful PHP stuff for people not to care about wanting to install more). > Python seems to always use some sort of development environment vs > production environment scheme. For development, you are supposed to > run a local browser and load 127.0.0.1:5000 - or something like that. > Then to run the same thing in a development environment, I have to > configure some files, or touch all the files, restart the web-server, > or something. Why is that? You can deploy Python Web applications using anything as simple as CGI (which only requires a single change to the Web server setup), right up to the full application server configuration. For a long time I've advocated the ability to be able to do this without having to switch frameworks and rewrite your code: that's what my WebStack package [1] is all about, and I guess that given the availability of the right adaptors and framework support, WSGI should let you do this as well. > Python also seems to require some sort of "long running processes" I > guess that the python interpretor has to running all of time. Not so: deploying anything as a CGI script/program means that the application code is only run when a request is made to the application. Lots of Python software can use this approach: MoinMoin, ViewVC, Trac... (All these things have, notably, implemented their own mechanisms for abstracting away the deployment technology, since they also work with things like mod_python. Another sad example of the community not coalescing around standards, although I think they're all looking into WSGI now.) > I am not really sure about what wsgi is supposed to accomplish. It's supposed to decouple the deployment technologies from the framework technologies, or at least that's what I'd use it for, and if all frameworks supported it, you'd supposedly be able to take, say, your Django application and run it on Zope 3, or your TurboGears application and run it on Twisted. Of course, you'd write your Django code differently from any Zope 3 code in your application, and the TurboGears code wouldn't look a lot like Twisted code, but that's another issue entirely. Paul [1] http://www.python.org/pypi/WebStack From lists at cheimes.de Wed Jan 9 16:15:35 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 09 Jan 2008 22:15:35 +0100 Subject: Python too slow? In-Reply-To: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: dongie.agnir at gmail.com wrote: > I'm pretty new to Python, and even newer to Image/Video processing, > and trying to get started on a project similar to GRL Vienna's laser > marker. I found some sample code here http://janto.blogspot.com/2006/01/motion-capture-in-python.html, > but after running the code with the included sample input file, it > seems quite slow (1-2 seconds from start to finish to do the 800 by > 600 gif image). Have you profiled your application? Do you know the bottle necks and the reason for the bottle necks? Is your application IO, memory or CPU bound? Have you considered rewriting the bottle necks in C? Christian From robert.kern at gmail.com Mon Jan 14 14:39:13 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 14 Jan 2008 13:39:13 -0600 Subject: help with slicing/replacing matrix sections. In-Reply-To: <478bb75f$0$5001$4c368faf@roadrunner.com> References: <478bb75f$0$5001$4c368faf@roadrunner.com> Message-ID: Erik Lind wrote: > I see a more complicated thread on a similar sounding question, but my > question is simpler, I hope. numpy questions are usually answered better on the numpy mailing list. http://www.scipy.org/Mailing_Lists > I have a large numpy matrix, initially created as: > > Mat = zeros((a,b), int) > > and a smaller array with other data > > Sub = [1,2,3,4,5],[6,7,8,9,0] > > I want to replace a section of Mat matrix with Sub matrix without having to > loop through each cell in each matrix individually. > > I thought index/slice assignments, should be able to do that, but I can only > get it to work (as per book examples) with simple arrays. Every syntax > combination I have tried gives one error or another, typically "can't > broadcast an object....", but intuitively it seems there should be a simple > solution. > > In short, how do I insert the data in the two (or any number of) rows in > Sub[0:2] into any part of Mat starting at Mat[x,y] without using "for" loops > ? In [11]: Sub = array([[1,2,3,4,5],[6,7,8,9,0]]) In [12]: Mat = zeros((10, 10), int) In [13]: Mat[5:5+2,4:4+5] = Sub In [14]: Mat Out[14]: array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 2, 3, 4, 5, 0], [0, 0, 0, 0, 6, 7, 8, 9, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) -- 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 afriere at yahoo.co.uk Wed Jan 23 02:54:00 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 22 Jan 2008 23:54:00 -0800 (PST) Subject: Removing objects References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> <27c8e3c8-3766-499c-9c62-82b03fa583d6@e23g2000prf.googlegroups.com> Message-ID: <430d47ec-1122-4016-b294-be20e0d4a0d9@s13g2000prd.googlegroups.com> On Jan 23, 6:16 pm, Asun Friere wrote: > >>> x.pop(x.index(c)) Umm, of course you would simply use x.remove(c) ... force of (bad) habit. %/ From pofuk at mzm.hr Thu Jan 3 18:26:33 2008 From: pofuk at mzm.hr (SMALLp) Date: Fri, 04 Jan 2008 00:26:33 +0100 Subject: py2exe command prompt whenr run Message-ID: HY! I'm using py2exe to port my applications on windows so user won't have to install python and other dependencies. Everything works file except when i run any of programs it star's command prompt before program starts. How can i avoid this to happen, and is there any other way of porting my applications on windows? Thanks! From aspineux at gmail.com Tue Jan 15 09:17:57 2008 From: aspineux at gmail.com (aspineux) Date: Tue, 15 Jan 2008 06:17:57 -0800 (PST) Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> Message-ID: On Jan 14, 8:07 pm, aspineux wrote: > On Jan 14, 7:49 pm, "Chris Mellon" wrote: > > > On Jan 14, 2008 12:39 PM, aspineux wrote: > > > > This append in both case > > > > dict(a=1).get('a', f()) > > > dict(a=1).setdefault('a', f()) > > > > This should be nice if f() was called only if required. > > > Think about the change to Python semantics that would be required for > > this to be true, and then use collections.defaultdict instead. > > Yes, I missed 'get' and 'setdefault' are functions :-) > Then why not some new semantic > > d.get('a', f()) --> d['a', f()] > d.setdefault('a', f()) --> d['a'=f()] > > Is is a good idea enough to change the python semantic ? > Or simply is it a good idea ? Thanks for all your answers. Anyway these notations are very compact, don't require the definition of a specific function, and work with old style/or already existing dictionary, dictionary you didn't created yourself. While the use of defaultdict require the definition of such a function and to control the creation of the dictionary. For me the best alternative that match the requirement above is the one provided by Paul Rubin. Regards. From mail at microcorp.co.za Tue Jan 15 10:07:32 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 15 Jan 2008 17:07:32 +0200 Subject: Interesting Thread Gotcha Message-ID: <000901c85788$74cfbfc0$03000080@hendrik> I thought I would share this nasty little gotcha with the group. Consider the following code fragment: print 'starting kbd thread' keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) print 'starting main loop' error = Mainloop(s,port_q,active_q_list) It produces, as output, the following: starting kbd thread we get here - a It does not print 'starting main loop', the Mainloop routine is never executed, and no exceptions are raised. Here is the offending routine that seems to capture the control: def kbd_driver(out_q,in_q): """ thread to look for keyboard input and to put it on the queue out_q also looks for replies on in_q and prints them """ kbdname = '/dev/stdin' kbd = open(kbdname,'r+',1) # Reading, line buffered unblock(kbd) # Call the magic to unblock keyboard print 'we get here - a' while True: try: d = kbd.readline() # see if any kbd input except: IOError try: msg=in_q.get(block=False) except Queue.Empty: time.sleep(0.1) continue print msg time.sleep(0.1) continue d = d.rstrip() # get rid of line feed out_q.put([d + '\r',in_q]) # add a carriage return and return q and send to port The unblock is a routine that unblocks a port using fcntl - it is not the problem. In case you don't believe me, here it is: def unblock(f): """Given file 'f', sets its unblock flag to true.""" fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) I will post the solution tomorrow when I read my mail, if no one has spotted it by then. - Hendrik From castironpi at gmail.com Sat Jan 12 13:55:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 10:55:05 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> <354c74f6-6e56-4e41-a686-56239aa4cea9@f47g2000hsd.googlegroups.com> <7x8x2uj3yb.fsf@ruckus.brouhaha.com> Message-ID: <0ad68aa8-735d-4cf0-b17a-d1f2be6af652@f47g2000hsd.googlegroups.com> On Jan 12, 12:26 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > 2) List is referenced by others; concurrent modifications may be going > > on; can not replace it. Can I make asynchronous modifications and > > merge the changes, SCM-style? > > Nothing else should have direct access to the list. Impossible to guarantee in Python. If you do, the reference to you does. From bperry.volatile at gmail.com Wed Jan 16 11:18:59 2008 From: bperry.volatile at gmail.com (Brandon Perry) Date: Wed, 16 Jan 2008 10:18:59 -0600 Subject: Unknown cause to error (new to python) In-Reply-To: <478e10bd$0$27280$426a34cc@news.free.fr> References: <478e10bd$0$27280$426a34cc@news.free.fr> Message-ID: <1200500339.6143.1.camel@bperry-laptop> Sorry, this is all I can get. :-( This isn't my webserver, so the only error logs I get are what they give me. I guess I will just have to keep working at it. Thanks for looking at it though, Brandon On Wed, 2008-01-16 at 15:12 +0100, Bruno Desthuilliers wrote: > Brandon Perry a ?crit : > > Hi, I am having to compile a standalone version of python for the web > > server I use (they don't allow access to /usr/bin/python). I posted > > earlier about a GLib error, but I have fixed that now. I am very close > > to getting this to work, but I am getting some weird errors. > > > > File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", > > line 41, in ? > > File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", line 71, in ? > > File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", line 4, in ? > > File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", line 4, in ? > > File "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", line 15, in ? > > Sorry but my crystal ball is broken. Please post the *whole* traceback. > From goon12 at gmail.com Sat Jan 12 14:07:04 2008 From: goon12 at gmail.com (Joe Riopel) Date: Sat, 12 Jan 2008 14:07:04 -0500 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** In-Reply-To: <47890e3e$0$26886$ecde5a14@news.coretel.net> References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> <4788de48$0$26887$ecde5a14@news.coretel.net> <47890e3e$0$26886$ecde5a14@news.coretel.net> Message-ID: <6a2ccd190801121107r7b728d09ve072909ba2863c04@mail.gmail.com> On Jan 12, 2008 2:00 PM, radiosrfun wrote: > Whether we agree on "tactics" or not - if it come to a battlefield with the > two of us - or any Americans there - we're still going to fight the same > enemy - not each other. This is a good resource for starting Python http://diveintopython.org/ From sjmachin at lexicon.net Fri Jan 4 17:28:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 4 Jan 2008 14:28:09 -0800 (PST) Subject: Tabnanny errors when Migrating Python 2.4 code to 2.5 References: <6d197192-0340-42f8-b764-cba91a92bb21@i3g2000hsf.googlegroups.com> Message-ID: <3e182358-9322-498a-822c-7a371c8b608f@e4g2000hsg.googlegroups.com> On Jan 5, 8:05 am, kyoso... at gmail.com wrote: > On Jan 4, 2:06 pm, John Machin wrote: > > > On Jan 5, 3:56 am, kyoso... at gmail.com wrote: > > > > Hi, > > > > When Python 2.5 first came out, I eagerly downloaded it and > > > immediately had issues with getting it to run my 2.4 code. So I just > > > stuck to 2.4. However, I decided this week that I really should try to > > > get 2.5 to work. Does anyone know why code that works perfectly for > > > months in a 2.4 environment throws indentation errors in 2.5? > > > No, not until you go to the bother of reproducing the problem with a > > small file, tell us what platform you are on, how you are running this > > code (IDLE, shell prompt, ...), how you installed Python 2.5 > > (2.5.1?), ... > > I'm using Windows XP, using IDLE (which was mentioned already) in the context of editing/displaying code, not executing it. Does the problem occur before or after you edit a file with IDLE? > and I > downloaded the 2.5.1 exe/msi file from python.org to install it. What you downloaded doesn't answer the question about how you installed it. Do you still have your 2.4 installation? > > I have yet to find a simple one which exhibits the issue to post. It > seems to happen to my complex files, not the simple ones. So chop up a complex file ... Have you inspected the failing files using a text editor that can display tabs and spaces (e.g. PythonWin, TextPad)? > > Sorry to bother you. You didn't bother me. You are bothering yourself by asking questions without enough information to get reasonable answers. From gordyt at gmail.com Wed Jan 9 15:46:10 2008 From: gordyt at gmail.com (gordyt) Date: Wed, 9 Jan 2008 12:46:10 -0800 (PST) Subject: ISO books of official Python docs References: fm38qu$6c7$1@reader2.panix.com Message-ID: <966c993a-2aa6-4724-852a-49d8da686675@k2g2000hse.googlegroups.com> Howdy kynnjo, > Is it possible to buy the official Python docs in book form? If > so, I'd very much appreciate the name(s) and author(s) of the > book(s). I haven't seen them in print form, but you can download PDF's from here: http://docs.python.org/download.html --gordy From DustanGroups at gmail.com Mon Jan 7 08:25:50 2008 From: DustanGroups at gmail.com (Dustan) Date: Mon, 7 Jan 2008 05:25:50 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <05595380-70b6-4e83-b15b-174af956c96c@j78g2000hsd.googlegroups.com> On Jan 7, 7:09 am, MartinRineh... at gmail.com wrote: > I'm a Java guy who's been doing Python for a month now and I'm > convinced that > > 1) a multi-paradigm language is inherently better than a mono-paradigm > language > > 2) Python writes like a talented figure skater skates. > > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is _______. > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > "grace" but I'm not sure I've done enough to choose. Here's a modest list: Masterly, tops, best obtainable, high-grade, very good, select, outstanding, exemplary, top-notch, boss, first-rate, crack, smashing, excelling, prime, skilled, crackerjack, sublime, super, terrific, peerless, notable, paramount, divine, premium, hand-picked, estimable, admirable, prize, choice, competent, desirable, attractive, foremost, to be desired, A-one, top-flight, dandy, incomparable, grade A, capital, great, dynamite, heavenly, unique, refined, matchless, high- quality, well-done, A-OK, blue-chip, frontline, sensational, highest, jim-dandy, splendid, extraordinary, exquisite, superlative, worthy, masterful, distinguished, magnificent, tiptop, accomplished, all right, first, first-class, fine, very fine, ace-high, exceptional, sharp, supreme, marvelous, transcendent, praiseworthy, custom-made, remarkable, world-class, invaluable, groovy, champion, rare, best, wonderful, superb, choicest, enticing, top, superfine, commendable, skillful, neat, striking, distinctive, priceless, sterling, superior, cool, classy, finest, hot, keen, above par. From mwm-keyword-python.b4bdba at mired.org Thu Jan 10 17:17:43 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 17:17:43 -0500 Subject: XML+Logs to Latex. XSLT? In-Reply-To: References: Message-ID: <20080110171743.5abc1e0b@bhuda.mired.org> On Thu, 10 Jan 2008 22:32:50 +0100 Fredrik Lundh wrote: > > Yes. For sure. I though XSLT was something like XML not other > > "language" and that Python will have any library that uses XSLT to do > > transformation... > XSLT is definitely a language (it's turing complete, after all), but > that there are of course several Python bindings to XSLT libraries; > here's one: XSLT is definitely something like XML - because an XSLT file is an XML file. But it represents a program, and hence is a programming language. It is unlike most other programming languages you will have encountered. XSLT may well be the most popular thing like XSLT, but Prolog is probably the language you've heard of that's closest to it. If you want to transform your XML into different-shaped XML or flat text, XSLT should be high on the list of tools to check out. > http://codespeak.net/lxml/ Very much recommended. > But please don't use SAX if you can avoid it; it's hard to work with, > and not very efficient. I'd recommend ElementTree, which is a light- > weight DOM library, that's part of the standard library: > http://effbot.org/zone/element-index.htm While I love the ElementTree API, the standard library implementation is missing tools that I find invaluable in working with XML. No schema support, for instance. The effort of maintaining a schema is repaid multiple times if you take advantage of it. If your application validates the XML on input, you *know* that when you translate a required attribute value to an the, the attribute will be there, and the it's value will repersent an int. And using a schema-aware editor is pretty much the only sane way for a human being to edit XML. The XPath implementation is also limited. Having written a little XSLT, not having pretty much all of XPath available for pulling values is painful. And of course, XSLT support, as there are things that XSLT is good for. Others I'm not so sure about. External entities seem to be unsupported by ElementTree. XInclude? More? > > Is this the way you will do it? > > As the author of ElementTree, I'm a bit biased, but I'd definitely do it > in Python ;-) Ditto - well, except I'm not the author of ElementTree. If all you want to do is read the XML into a tree of python strings, then the ElementTree implementation is an excellent API for doing so, and being in the standard library means you should already have it. If you want to leverage XML to make your job as easy as possible, then I'd recommend using the aforementioned lxml instead. It provides the same ElementTree API on top of the popular libxml2 and libxslt libraries (your Unix-like system probably comes with them pre-installed), and hence gives you access to all the XML tools they provide - like the ones I mentioned above. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From brett at python.org Mon Jan 28 20:20:09 2008 From: brett at python.org (Brett Cannon) Date: Mon, 28 Jan 2008 17:20:09 -0800 Subject: Announcing the Python core sprint at PyCon 2008 Message-ID: As has occurred since the inception of PyCon, there will be a sprint on the Python core at this year's conference! If you will be attending PyCon (or will be in Chicago during the dates of the sprints), attending the sprint is a great way to give back to Python. Working on Python itself tends to deepens one knowledge of the language and the standard library. Plus it is just plain fun getting to sit around some tables with fellow Python programmers for several days (the sprint will last four days, but you do not need to attend all four days to participate). The sprint is open to everyone of all skill levels. We can always use help with things from updating documentation to preparing for the next release of Python 3.0. On Sunday evening of the conference there will not only be a sprint intro session, but also a tutorial on how to develop for Python. Details will be covered from where to look in the code base for things to some best practices tips. If you are interested enough to want to sign up to attend, please go to http://wiki.python.org/moin/PyCon2008/SprintSignups/Python and add your name and email address. If you have questions you may email me. Please sign up for the sprint by the end of February as an email on what you need to do beforehand will be sent at that time based on the sprint sign-up page. And if you are not attending PyCon, we will most likely have several people in attendance on IRC, thus allowing even people not at PyCon to participate! -Brett Cannon Python core sprint coach, PyCon 2008 From steveo at syslang.net Fri Jan 4 17:55:33 2008 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 4 Jan 2008 17:55:33 -0500 (EST) Subject: Questions about subclassing an int Message-ID: class S(int): def __init__(self, value): self.value = value def addStr(self, str): self.doc = str s = S(44) s.addStr('Hello') print 's = ', s print 's.doc = ', s.doc class T(int): def __init__(self, value, str): self.value = value self.doc = str t = T(44, 'Goodbye') print 't = ', t print 't.doc = ', t.doc It works ok with S but it fails when I try to instantiate T with a syntax error. Why? Also, I don't understand why S works. If I change the name of value and use something else, the print of s still works by printing the integer value out. How does it know what value to use? Also, in S.__init__, should I be calling super(S, self).__init__(value) or is there a difference? And just for fun: class R(int): def __init__(self, value, doc): super(R, self).__init__(value) self.doc = doc r = R(66,'GGG') Traceback (most recent call last): File "", line 1, in ? TypeError: an integer is required Now it's no longer a syntax error but I don't see why it's different? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From terry at jon.es Wed Jan 23 10:45:30 2008 From: terry at jon.es (Terry Jones) Date: Wed, 23 Jan 2008 16:45:30 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 23:07:42 on Tuesday, 22 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> Message-ID: <18327.24858.376079.63735@jon.es> Hi Arnaud and Dan >>>>> "Arnaud" == Arnaud Delobelle writes: >> What was wrong with the very fast(?) code you sent earlier? Arnaud> I thought it was a bit convoluted, wanted to try something I Arnaud> thought had more potential. I think the problem with the second Arnaud> one is that I repeat the same 'fold' too many times. and later: Arnaud> Yes, I've been doing this by writing an 'action' (see my code) that Arnaud> takes note of all reached results. These are both comments about pruning, if I understand you. In the first you weren't pruning enough and in the second you're planning to prune more. I'm giving up thinking about this problem because I've realized that the pruning solution is fundamentally subjective. I.e., whether or not you consider two solutions to be the "same" depends on how hard you're willing to think about them (and argue that they're the same), or how smart you are. I have a new version that does some things nicely, but in trying to do efficient pruning, I've realized that you can't satisfy everyone. Some examples for the problem with target 253, numbers = 100, 9, 7, 6, 3, 1 Firstly, there are nice solutions that go way negative, like: 1 7 6 3 9 sub mul mul sub or 1 - 7 * 6 * (3 - 9) Here's a pruning example. Are these the "same"? 1 3 7 100 9 sub sub mul sub or 1 - 3 * (7 - 100 - 9) 1 3 7 9 100 sub add mul sub or 1 - 3 * (7 - 9 - 100) I think many people would argue that that's really the "same" and that one of the two should not appear in the output. The same goes for your earlier example for 406. It's 4 * 100 + 2 x 3, and 2 x 3 + 100 * 4, and so on. My latest program does all these prunings. But you can argue that you should push even further into eliminating things that are the same. You could probably make a pretty fast program that stores globally all the states it has passed through (what's on the stack, what numbers are yet to be used, what's the proposed op) and never does them again. But if you push that, you'll wind up saying that any two solutions that look like this: ....... 1 add e.g. 6 9 3 sub mul 7 mul 1 add or 6 * (9 - 3) * 7 + 1 7 6 mul 9 3 sub mul 1 add or 7 * 6 * (9 - 3) + 1 are the same. And if we go that far, then a really smart person might argue that this 100 7 sub 9 sub 3 mul 1 add or (100 - 7 - 9) * 3 + 1 is also the "same" (because all these solutions get to 252 and then add 1, so they're clearly the "same", right?): Once you've gone that far, you might even argue that on a particular problem of a particular difficulty (subjectively matching what your brain is capable of) all solutions that start out by pushing 1 onto the stack are actually the "same". And if you're even smarter than that, you might just look at any problem and say "Hey, that's easy! The answer is X" or "There's clearly no solution" because you'd immediately just see the answer (if any) and that all others were just obvious variants. E.g., if I said to you: "make 20 out of (20, 10, 10, 3)", I imagine you could immediately list the answer(s?) 20 = 20 20 = 10 + 10 20 = 20 + 10 - 10 20 = 20 - 10 + 10 etc., and explain that those are all really the same. You'd prune on the spot, and consider it obvious that the pruning was fully justified. But my 6-year-old son couldn't tell you that, and I doubt he'd agree with your prunings. OK, enough examples. I'm just trying to illustrate that the (difficult) problem of efficiently pruning doesn't have an objective solution. Pruning is subjective. OTOH, the decision problem "does this puzzle have any solutions or not (and if so, produce one)" does. That's why I'm going to stop working on this. My stack solution code is fun, but working on making it prune better is a black hole. And to make matters worse, the more I push it (i.e., the more advanced its prunings get), the less likely (some) people are to agree that its output is still correct. You can't win. If anyone wants the stack simulation code, send me an email. Terry From SSchukat at dspace.de Fri Jan 4 07:57:58 2008 From: SSchukat at dspace.de (Stefan Schukat) Date: Fri, 4 Jan 2008 13:57:58 +0100 Subject: pydepend (checking dependencies like jdepend) ? References: <1969e240-9e80-4df1-b085-7956dfa4f7ae@t1g2000pra.googlegroups.com> Message-ID: <3E7E58237D756A4D85E7A36CB8C953ED01E244@exchange2003.dspace.de> Hi, try to look at py2exe. This module scans all dependencies to pack them into one executable. Stefan -----Original Message----- From: python-list-bounces+sschukat=dspace.de at python.org [mailto:python-list-bounces+sschukat=dspace.de at python.org] On Behalf Of Bernhard Merkle Sent: Friday, January 04, 2008 1:14 PM To: python-list at python.org Subject: pydepend (checking dependencies like jdepend) ? Hi there, think %Subject says all. I am wondering if there is some tool to check dependencies within python programs. (something like jdepend for python ;-) Of course the dependencies are at runtime (dynamic) and not statically +dynamically (as in Java), but anyway it would be interesting to know of them (for better modularization e.g.) TIA, Berni. -- http://mail.python.org/mailman/listinfo/python-list From ganeshborse at gmail.com Wed Jan 30 02:38:46 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Tue, 29 Jan 2008 23:38:46 -0800 (PST) Subject: Replacing call to PyObject_CallObject with PyEval_CallFunction References: <5a99ab95-e225-4085-bce4-ea31da557d6d@j78g2000hsd.googlegroups.com> <740a5e65-64c3-45dc-95bf-691978fb4290@f47g2000hsd.googlegroups.com> Message-ID: <6e7b6586-ba2a-4e8b-8413-f7e666f6559e@s19g2000prg.googlegroups.com> On Jan 30, 1:58?pm, Gabriel Genellina wrote: > On 30 ene, 01:58, grbgooglefan wrote: > > > How do I pass the elements populated in struct variables of this > > vector dynamically to PyEval_CallFunction, in the fashion somewhat > > like below? > > PyEval_CallFunction(obj, "iii", vector[0].ioparam->nionum,vector[1].ioparam->nionum,vector[2].ioparam->nion?um); > > > PyEval_CallFunction(obj, "di", vector[0].ioparam->fionum,vector[1].ioparam->nionum); > > > PyEval_CallFunction(obj, "diiisis", vector[0].ioparam->fionum,vector[1].ioparam->nionum,vector[2].ioparam- > > >nionum,vector[3].ioparam->nionum,vector[4].ioparam- > > >ioString,vector[5].ioparam->nionum,vector[6].ioparam->ioString); > > I didn't know of PyEval_CallFunction until now, but aparently the > lines above are OK. Can't you use it that way? What's your problem? > > -- > Gabriel Genellina slowness of current code - vector is to parsed one by one & switch adds another time for checks. From paddy3118 at googlemail.com Fri Jan 25 02:51:52 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 23:51:52 -0800 (PST) Subject: Which is more pythonic? References: <56518bb9-1d56-47c3-8112-6e0778832c12@v29g2000hsf.googlegroups.com> Message-ID: <384a9c43-49e2-4feb-b21a-96f6b3a29a01@j78g2000hsd.googlegroups.com> On Jan 25, 5:14 am, "benjamin.zimmer... at gmail.com" wrote: > I have a goal function that returns the fitness of a given solution. I > need to wrap that function with a class or a function to keep track of > the best solution I encounter. Which of the following would best serve > my purpose and be the most pythonic? > > class Goal: > def __init__(self, goal): > self.goal = goal > self.best = None > self.best_score = None > > def __call__(self, solution): > score = self.goal(solution) > if self.best is None or score > self.best_score: > self.best_score = score > self.best = solution > return score > > def save_best_goal(goal): > def new_goal(solution): > score = goal(solution) > if new_goal.best is None or score > new_goal.best_score: > new_goal.best = solution > new_goal.best_score = score > return score > new_goal.best = new_goal.best_score = None > return new_goal > > -Ben You could also wrap the best score logic as a decorator applied to a function to save the best score as a function attribute. Whilst not class based, Python isn't solely an OO language. but if you know that extra capabilities are going to be needed you might favour the class based solution. - Paddy. From claird at lairds.us Tue Jan 1 20:04:55 2008 From: claird at lairds.us (Cameron Laird) Date: Wed, 2 Jan 2008 01:04:55 +0000 Subject: cloud computing (and python)? References: Message-ID: In article , Aaron Watters wrote: >So, in between skiing runs I noticed >a Business Week cover story on >"cloud computing". The article had >lots of interesting information in it like >about how somebody's mom used to >be an airline stewardess and the >interior decor of various office spaces. >It was a truly excellent piece of >journalism. > >However it gave me no idea what >"cloud computing" is and how it >could be used to solve a computational >problem. > >Could anyone on this list >which usually has highly informed >readers give me a clue at some >level of technical detail what cloud >computing is about and how it could >be used. Bonus points if you mention >Python in the response! > >An actual example would be great, >if it's not web scraping and searching. . . . Aaron, while I make time for a more pertinent response, might interest you. I owe you better examples, though. From stanc at al.com.au Fri Jan 18 00:28:42 2008 From: stanc at al.com.au (Astan Chee) Date: Fri, 18 Jan 2008 16:28:42 +1100 Subject: [python] How to detect a remote webpage is accessible? (in HTTP) In-Reply-To: References: Message-ID: <4790390A.7010406@al.com.au> How about: import socket, urllib2 timeout = 10 socket.setdefaulttimeout(timeout) try: auth_handler = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(auth_handler) #this used if we need authentication urllib2.install_opener(opener) req = urllib2.Request('http://website.com') f = urllib2.urlopen(req) notes= f.readlines() f.close() print "Everything is ok" except IOError, r: p = str(r) if re.search(r'urlopen error timed out',p): print "Web page timed out" You'll need to set up the timeout to whatever duration your website takes to load. Cheers Astan ?? wrote: > Howdy, all, > I want to use python to detect the accessibility of website. > Currently, I use urllib > to obtain the remote webpage, and see whether it fails. But the problem is that > the webpage may be very large; it takes too long time. Certainly, it > is no need to download > the entire page. Could you give me a good and fast solution? > Thank you. > -- > ShenLei > From lizm at rcsltd.co.uk Wed Jan 23 09:58:29 2008 From: lizm at rcsltd.co.uk (LizzyLiz) Date: Wed, 23 Jan 2008 06:58:29 -0800 (PST) Subject: csv to xls using python 2.1.3 References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> Message-ID: Perfect! Thanks :-) LizzyLiz From peng.kyo at gmail.com Thu Jan 17 01:07:02 2008 From: peng.kyo at gmail.com (J. Peng) Date: Thu, 17 Jan 2008 14:07:02 +0800 Subject: assigning values in python and perl In-Reply-To: <478EEF97.2070807@cheimes.de> References: <2d37f441-c01f-439b-9897-35b7e4dfa77b@h11g2000prf.googlegroups.com> <478EEF97.2070807@cheimes.de> Message-ID: <18c1e5f20801162207p18443838ma902c5bb740099a0@mail.gmail.com> On Jan 17, 2008 2:03 PM, Christian Heimes wrote: > George Sakkis wrote: > > Python's parameter passing is like passing a pointer in C/C++. > [snip] > > It's not (I repeat NOT) like passing a pointer in C. Please read > http://effbot.org/zone/call-by-object.htm > Yes I agree. Not the same at all. From rridge at caffeine.csclub.uwaterloo.ca Fri Jan 11 08:33:13 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 11 Jan 2008 08:33:13 -0500 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > And the reference implementation of Python (CPython) is not > interpreted, it's compiled to byte-code, which is then executed by a VM > (just like Java). Ross Ridge a ?crit : > Python's byte-code interpreter is not "just like" Java's virtual machine. Bruno Desthuilliers wrote: >of course it's not "just like" - different languages, different >byte-codes, different implementations. What is "just like" is the >byte-code/VM scheme. No the schemes aren't "just like" each other. They perform much differently. > Thought this was obvious to anyone able to parse a simple sentence. What's obvious is that you're lying. >> You're deliberately trying to mislead people into thinking Python performs >> similarily to Java. > >I don't know what you're smoking, but you should perhaps stop - because >this seems to drive you into parano?d delirium. This isn't the first time you've tried to mislead people into thinking Python's byte-code interpreter works just like Java's VM. Your over-zealous Python advocacy is benefiting no one. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From stefan.behnel-n05pAM at web.de Tue Jan 29 05:46:05 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 29 Jan 2008 11:46:05 +0100 Subject: Error in parsing XML for following test data In-Reply-To: References: Message-ID: <479F03ED.6080308@web.de> abhishek wrote: > I am having problem parsing following data set from XML. Please > provide hints on how to rectify this problem. > > I am using python2.4 version > > this is te test data that i am using -- > > """"""" > 1!!!!!!!!!!!!!!!11 > 2@@@@@@@@@@@@@@@22 > 3###############33 > 4$$$$$$$$$$$$$$$44 [...] How is this related to XML? Stefan From k_vinoj at yahoo.com Fri Jan 4 05:51:49 2008 From: k_vinoj at yahoo.com (vinoj davis) Date: Fri, 4 Jan 2008 16:21:49 +0530 (IST) Subject: how to connect to a remote machine using python........ Message-ID: <663493.85789.qm@web94609.mail.in2.yahoo.com> An HTML attachment was scrubbed... URL: From iclark at mail.ewu.edu Tue Jan 22 12:23:59 2008 From: iclark at mail.ewu.edu (Ian Clark) Date: Tue, 22 Jan 2008 17:23:59 +0000 (UTC) Subject: Curses and Threading References: <3924ad84-a513-4b25-b9af-cbd358f5d40a@i3g2000hsf.googlegroups.com> Message-ID: On 2008-01-22, Brett.Friermood at gmail.com wrote: >> In fact you have *two* threads: the main thread, and the one you create >> explicitly. > >> After you start the clock thread, the main thread continues executing, >> immediately entering the finally clause. >> If you want to wait for the other thread to finish, use the join() method. >> But I'm unsure if this is the right way to mix threads and curses. > > This is what the python documentation says: > > join([timeout]) > Wait until the thread terminates. This blocks the calling thread > until the thread whose join() method is called terminates. > > So according to this since I need to block the main thread until the > clock thread ends I would need the main thread to call > "cadtime().join()", correct? I'm not sure how to do this because I > don't have a class or anything for the main thread that I know of. I > tried putting that after cadtime().start() but that doesn't work. I > guess what I'm trying to say is how can I tell the main thread what to > do when it doesn't exist in my code? > > Thanks for the help > -Brett join() is a method on Thread objects. So you'll need a reference to the Thread you create, then call join() on that. thread = cadtime() thread.start() thread.join() Ian From loupgaroublond at gmail.com Fri Jan 4 10:07:44 2008 From: loupgaroublond at gmail.com (Yaakov Nemoy) Date: Fri, 4 Jan 2008 10:07:44 -0500 Subject: Memory Leaks and Heapy Message-ID: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> Hi list, Firstly, this is my first post here, so I hope I'm not breaking some unwritten etiquette rule about asking questions involving several different libraries. I'm trying to plug some memory leaks in a TurboGears program. We (the Fedora Project) have a few apps in Turbogears in infrastructure that all seem to be running into the same issues in a variety of configurations. Hopefully when I get to the cause of this in one app, Smolt, we can fix the others too. The app in question is Smolt, which uses TurboGears, SQLAlchemy with a MySQL backend, and simplejson for message passing between the server and client. Smolt takes voluntary hardware reports from its clients, and generally is configured to submit around the beginning of the month. Normally, our main data is cached by some separate processes that run short term, so we don't see any rapid memory growth, except for the beginning of each month, which makes isolating the problem to a few function calls fairly simple. To watch for memory growth, I simply have a client hammer the server with 1-3 threads submitting information simultaneously, 100 times, with a few deletion operations in between. To monitor for memory leaks, I'm using Heapy. To insert Heapy into the process, instead of calling 'start_server', a cherrypy method that does what you think it does and blocks, I'm using the module 'threading' to push it into a new thread. Using the process in heapy's documentation, I find that after running a single thread, there is about 1200 bytes of leaked memory. Despite this, the python process running the server has managed to grow from 16-18MB to something between 23-28MB each time I try this. After a second iteration, heapy shows 1168 bytes leaked. If heapy is correct, this means there are not many leaked objects in the python space. Running a larger example, say 100 threads, for a total of 10k submissions takes about an hour, and in the process, python baloons up to about 48MB. Still no signs of any missing objects. 48MB is not alot relatively speaking, but no amount of waiting seems to show python giving back that memory afterwards. On our production server, we have up to 200k machines all updating their information over a 3 day period, in which the server process manages to reach 600MB before we forcefully restart it. A couple of developers have mentioned that python might be fragmenting its memory space, and is unable to free up those pages. How can I go about testing for this, and are there any known problems like this? If not, what else can I do to look for leaks? -Yaakov From http Fri Jan 18 13:38:15 2008 From: http (Paul Rubin) Date: 18 Jan 2008 10:38:15 -0800 Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <7xlk6nou7c.fsf@ruckus.brouhaha.com> Tim Chase writes: > first = int(data[0]) > try: > count = int(data[1]) > except: > count = 0 By the time you're down to this kind of thing making a difference, it's probably more important to compile with pyrex or psyco. From ioscas at gmail.com Wed Jan 23 02:14:53 2008 From: ioscas at gmail.com (ioscas at gmail.com) Date: Tue, 22 Jan 2008 23:14:53 -0800 (PST) Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? Message-ID: Hi, I am looking for a HTML parser who can parse a given page into a DOM tree, and can reconstruct the exact original html sources. Strictly speaking, I should be allowed to retrieve the original sources at each internal nodes of the DOM tree. I have tried Beautiful Soup who is really nice when dealing with those god damned ill-formed documents, but it's a pity for me to find that this guy cannot retrieve original sources due to its great tidy job. Since Beautiful Soup, like most of the other HTML parsers in python, is a subclass of sgmllib.SGMLParser to some extent, I have investigated the source code of sgmllib.SGMLParser, see if there is anything I can do to tell Beautiful Soup where he can find every tag segment from HTML source, but this will be a time-consuming job. so... any ideas? cheers kai liu From sjmachin at lexicon.net Wed Jan 23 14:20:56 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 11:20:56 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <7x8x2g8isi.fsf@ruckus.brouhaha.com> Message-ID: <2b68cb79-220a-40db-9e6b-5b8ab9d41964@s13g2000prd.googlegroups.com> On Jan 24, 6:05 am, Paul Rubin wrote: > ryan k writes: > > Hello. I have a string like 'LNAME > > PASTA ZONE'. I want to create a list of those words and > > basically replace all the whitespace between them with one space so i > > could just do lala.split(). Thank you! > > import re > s = 'LNAME PASTA ZONE' > re.split('\s+', s) That is (a) excessive for the OP's problem as stated and (b) unlike str.split will cause him to cut you out of his will if his problem turns out to include leading/trailing whitespace: >>> lala = ' LNAME PASTA ZONE ' >>> import re >>> re.split(r'\s+', lala) ['', 'LNAME', 'PASTA', 'ZONE', ''] >>> lala.split() ['LNAME', 'PASTA', 'ZONE'] >>> From deets at nospam.web.de Wed Jan 23 18:27:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Jan 2008 00:27:44 +0100 Subject: Increment Variable Name In-Reply-To: References: Message-ID: <5vq0rjF1o724kU1@mid.uni-berlin.de> David Brochu schrieb: > This is probably really trivial but I'm stumped.... :-( > > Does anyone know how to increment a variable name? > > For example: > > I know the length of a list and I want to pass each element of a list to > a unique variable, thus I want to increment variable names. If the list > length = 4, i want to have the following variables: var1, var2, var3, var4. > Use a dictionary value_dict = {} for i, value in values: value_dict["var%i" % i] = value Diez From fredrik at pythonware.com Wed Jan 9 07:47:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 13:47:41 +0100 Subject: Collecting Rich Data Structures for students In-Reply-To: References: Message-ID: kirby.urner at gmail.com wrote: > Some have offered XML repositories, which I can well > understand, but in this case we're looking specifically for > legal Python modules (py files), although they don't have > to be Latin-1 (e.g. the sushi types file might not have a > lot of romanji). you can of course convert any XML file to legal Python code simply by prepending from xml.etree.ElementTree import XML data = XML(""" and appending """) and then using the ET API to navigate the data, but I guess that's not what you had in mind. From irmen.NOSPAM at xs4all.nl Thu Jan 17 19:24:57 2008 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 18 Jan 2008 01:24:57 +0100 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. In-Reply-To: References: <478FAC5A.50206@animats.com> Message-ID: <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> Christian Heimes wrote: > John Nagle wrote: >> It's possible to use "pickle" for interprocess communication over >> pipes, but it's not straightforward. > > IIRC the processing module uses pickle for IPC. Maybe you can get some > idea by reading its code? > > http://pypi.python.org/pypi/processing/0.40 > > Christian > So does Pyro: http://pyro.sourceforge.net/ However Pyro uses TCP-IP sockets for communication. It uses a small header that contains the size of the message and a few other things, and then the (binary by default) pickle stream. --irmen From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 28 12:19:06 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 28 Jan 2008 18:19:06 +0100 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: References: Message-ID: <479e0e88$0$1158$426a74cc@news.free.fr> Paddy a ?crit : (snip) > Is it not possible to write a function that queries its call stack > when run to find the name of all arguments and locals() of the level > above > so you could write: > > class test(object): > def __init__(self, x, y): > arg2inst() > > and automatically assign self.x=x; self.y=y ? Might be possible using the inspect module. But as far as I'm concerned, I'm not sure I really like the idea that much - no rationale here, just a feeling... From stefan.behnel-n05pAM at web.de Tue Jan 1 05:06:02 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 01 Jan 2008 11:06:02 +0100 Subject: ElementTree should parse string and file in the same way In-Reply-To: References: <4778A47B.9020201@web.de> Message-ID: <477A108A.20209@web.de> Peter Pei wrote: > To be preise [...] Preise the lord, not me. :) Happy New Year! Stefan From bearophileHUGS at lycos.com Tue Jan 15 04:53:24 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 15 Jan 2008 01:53:24 -0800 (PST) Subject: Data mapper - need to map an dictionary of values to a model References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com> Message-ID: <05398cdb-4c75-499b-bb52-d5de627a0906@j20g2000hsi.googlegroups.com> Luke: >What design patterns would you use here?< What about "generator (scanner) with parameters"? :-) Bye, bearophile From attn.steven.kuo at gmail.com Thu Jan 31 17:48:50 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 31 Jan 2008 14:48:50 -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> Message-ID: On Jan 31, 8:12 am, erikcw wrote: > Hi, > > I have a list of numbers each with a +/- margin of error. I need to > identify which ones overlab each other. > > For example: > 55 +/- 3 > 20 +/- 2 > 17 +/- 4 > 60 +/- 3 > > #base, max, min > list = [ > (55, 58, 52), > (20, 22, 18), > (17, 21, 13), > (60, 63, 57), > ] > > In this example the range of list[0] overlaps the range of list[3] AND > list[1] overlaps list[2] > > 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. > One way would be to use sets and check for intersection: for idx, s in enumerate(mysets): for next_idx, next_s in enumerate(mysets[idx+1:]): if s.intersection(next_s): print "mylist[%d] and mylist[%d] intersect" % ( idx, idx + next_idx + 1 ) -- Hope this helps, Steve From gandalf at shopzeus.com Fri Jan 11 08:57:11 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 11 Jan 2008 14:57:11 +0100 Subject: ftplib question (cannot open data connection) Message-ID: <478775B7.4040006@shopzeus.com> Hi All, I'm using a simple program that uploads a file on a remote ftp server. This is an example (not the whole program): def store(self,hostname,username,password,destdir,srcpath): self.ftp = ftplib.FTP(hostname) self.ftp.login(username,password) self.ftp.set_pasv(False) self.ftp.cwd(destdir) fobj = file(srcpath,"rb") destname = os.path.split(srcpath)[1] self.ftp.storbinary("STOR "+destname,fobj) The ftp server cannot use passive connections, and I can do nothing about that. Here is the problem: I can connect to this ftp server from my home computer, which is behind a NAT firewall. I can also connect to it from another computer, but I'm not able to upload any file. I tried to debug with a simple "ftp -v -d" command line program and apparently the problem is with the "EPRT" command: ftp> ls ---> EPRT |1|195.228.74.135|55749| 200 Port command successful. ---> LIST 425 Cannot open data connection. ftp> Well, the port number given by EPRT is bad - it is a closed port on this computer. I can open a small port range for this, but I would not like to open all ports and disable the firewall completely. Here are my questions: 1. How can I instruct ftplib to use specific ports for incoming connections? (For example, ports between 55000 and 56000). 2. How it is possible that the same program works from another computer that is behind a NAT firewall? Thanks, Laszlo From tinnews at isbd.co.uk Thu Jan 3 11:09:53 2008 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: 03 Jan 2008 16:09:53 GMT Subject: how to use bool References: Message-ID: <477d08d1$0$510$bed64819@news.gradwell.net> jimgardener at gmail.com wrote: > hi, i have some code where i set a bool type variable and if the value > is false i would like to return from the method with an error msg.. > being a beginner I wd like some help here > > class myclass: > ......... > def mymethod(self): > success=True > msg="all validation OK" > success=validateSthing() > if(success==False): > msg="sthing failed" > return (success,msg) > > dosomeprocessing() > ..... > success=validateSthingelse() > if(success==False): > msg="sthingelse failed" > return (success,msg) > domoreprocessing() > .... > return(success,msg) > > i would like to know if this way of doing this is OK..I have need of > many kinds of validations in this ..is there a better way of doing > this ? > With my philosophical programming hat on the first thing I'd say (as a fairly beginning python programmer) is "avoid multiple returns from a function/method if at all possible". They breed all sorts of problems and errors, in particular if there's any clearing up to do you have to do it in lots of places (or you forget it in some places). So:- def mymethod(self): msg="sthing failed" success=validateSthing() if success: dosomeprocessing() ..... success=validateSthingelse() if success: domoreprocessing() .... msg="all validation OK" return (success,msg) I've lost the different messages for different errors but you get the idea. "if success:" rather than "if (success==True)", more readable. For the opposite "if not success:". -- Chris Green From rw at smsnet.pl Mon Jan 28 09:26:05 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Mon, 28 Jan 2008 06:26:05 -0800 (PST) Subject: Set ulimit when using subprocess.Popen? References: Message-ID: Jarek Zgoda napisa?(a): > Rob Wolfe napisa?(a): > > > > Jarek Zgoda napisa?(a): > >> Hi, all, > >> > >> anybody has an idea on how to set ulimit (-v in my case, linux) for > >> process started using subprocess.Popen? > > > > What about: > > > > from subprocess import call > > call('ulimit -v 1000 && ulimit -v && ls', shell=True) > > subprocess.Popen('ulimit -v 1024; ls', shell=True) works perfect. > > Unfortunately, the nature of ulimit impacts deadly my application when > the limit is reached, so this knowledge is of no help in my case. ;) Use "ulimit -v unlimited" then. RW From stefan_ml at behnel.de Thu Jan 31 13:05:25 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 31 Jan 2008 19:05:25 +0100 Subject: REALLY simple xml reader In-Reply-To: <47A206D5.8020408@behnel.de> References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> <87tzkujeq6.fsf@benfinney.id.au> <13q3ri2707niqc6@corp.supernews.com> <47A206D5.8020408@behnel.de> Message-ID: <47A20DE5.3010407@behnel.de> Stefan Behnel wrote: > Steven D'Aprano wrote: >> 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. > [had a good laugh here] >> This is legal XML: >> >> """ >> Hello, world!""" >> >> and so is this: >> >> """ >> Hello, world!""" >> >> >> but not this: >> >> """ >> Hello, world!""" > > It's actually not that stupid. When you leave out the declaration, then the > XML is UTF-8 encoded (by spec), so normal ASCII whitespace doesn't matter. Sorry, strip the "ASCII" here. From the XML spec POV, your example """ Hello, world!""" is exactly equivalent to """ Hello, world!""" and whitespace between the declaration and the root element is allowed. It's just not allowed *before* the declaration, which in your case was left out, thus implying the default declaration. Stefan From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jan 15 14:22:22 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 15 Jan 2008 20:22:22 +0100 Subject: "env" parameter to "popen" won't accept Unicode on Windows -minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net><5v2cudF1k5a1oU1@mid.individual.net><478c551a$0$36354$742ec2ed@news.sonic.net> <5v3dq9F1k2577U1@mid.uni-berlin.de> Message-ID: <5v4ffeF1knst3U1@mid.individual.net> Brian Smith wrote: > popen() knows that it is running on Windows, and it knows what > encoding Windows needs for its environment (it's either UCS2 or > UTF-16 for most Windows APIs). At least when it receives a unicode > string, it has enough information to apply the conversion > automatically, and doing so saves the caller from having to figure > out what exact encoding is to be used. So you propose Python should employ a hidden automatism that automagically guesses the right encoding? Why not leave it explicitly/consistently and let the user decide? What will happen if a future Windows changes its encoding? Will we need another magic routine to tell it apart? Regards, Bj?rn -- BOFH excuse #353: Second-system effect. From steven.bethard at gmail.com Tue Jan 29 19:56:42 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 29 Jan 2008 17:56:42 -0700 Subject: breaking out of outer loops In-Reply-To: References: Message-ID: Jeremy Sanders wrote: > noemailplease0001 at gmail.com wrote: > >> Any elegant way of breaking out of the outer for loop than below, I >> seem to have come across something, but it escapes me >> >> for i in outerLoop: >> for j in innerLoop: >> if condition: >> break >> else: >> continue >> break > > Perhaps Python needs a "continue N" or a "break N" statement :-) > > for i in outerLoop: > for j in innerLoop: > if condition: > break 2 > > Seeing as we can't have a goto :-) Not true! You just have to import it: http://entrian.com/goto/ STeVe From ask at me Thu Jan 17 15:36:19 2008 From: ask at me (alf) Date: Thu, 17 Jan 2008 14:36:19 -0600 Subject: how django discovers changed sources In-Reply-To: References: <18udndZmKMfMNhLanZ2dnUVZ_rzinZ2d@comcast.com> <18udndFmKMfgMRLanZ2dnUVZ_rzinZ2d@comcast.com> Message-ID: Jeff wrote: > On Jan 17, 2:51 pm, "Guilherme Polo" wrote: >> 2008/1/17, alf :> Jeff wrote: >>>> That is the behavior of the development server. When you are writing >>>> your application, you don't want to have to manually restart the >>>> server every time you change a file. On apache it obviously doesn't >>>> do that. >>> thx for clarification, but still I am curious how it is done under the >>> hood. it really impressed me ... >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> It checks if modification time on registered files have changed since last check >> >> -- >> -- Guilherme H. Polo Goncalves > > django.utils.autoreload provides the functionality. thx for the reference, Andy From davidtweet at gmail.com Sat Jan 19 18:02:00 2008 From: davidtweet at gmail.com (David Tweet) Date: Sat, 19 Jan 2008 15:02:00 -0800 Subject: Default attribute values pattern In-Reply-To: References: Message-ID: <3fd0162e0801191502k57fb81f6q472e9b077a585ccd@mail.gmail.com> Hello, Seems to me that setattrs sort of assumes that you want to have all your initialization arguments set as attributes of the same name. I would think you'd sometimes want to be able to process the extra arguments inside of each __init__, assign them to attributes with different names, etc. My approach would be to treat each __init__ as a wrapping function, grabbing the items it needs out of the keyword dictionary and then calling the next __init__. Curious to hear other approaches though: def Grab(argdict, key, default): """Like argdict.get(key, default), but also deletes key from argdict.""" if key in argdict: retval = argdict["key"] del(argdict[key]) else: retval = default return retval class Base(object): def __init__(self, x=0, y=None): print "in Base init" self.x = x self.y = y class Derived1(Base): def __init__(self, **kwargs): print "in Derived1 init" self.z = Grab(kwargs, "z", None) super(Derived1, self).__init__(**kwargs) class Derived2(Derived1): def __init__(self, **kwargs): print "in Derived2 init" self.a = Grab(kwargs, "a", 0) self.b = Grab(kwargs, "b", False) super(Derived2, self).__init__(**kwargs) print self.__dict__ newthing = Derived2(x=234, y="blah", a=55555) On Jan 19, 2008 10:14 AM, George Sakkis wrote: > A situation that often comes up is having to initialize several > instance attributes that accept a default value. For a single class, > passing the default values in __init__ is fine: > > class Base(object): > def __init__(self, x=0, y=None): > self.x = x > self.y = y > > For inherited classes that need to override __init__ while keeping a > compatible interface though, the default values have to be repeated: > > class Derived(Base): > def __init__(self, x=0, y=None, z=''): > super(Derived,self).__init__(self,x,y) > self.z = '' > > For just two attributes and two classes that's maybe not too bad but > for many attributes and/or derived classes that may span multiple > modules, that doesn't seem to scale from a maintenance point of view, > especially if the defaults change over time. > > A pattern I've been using lately instead is store the defaults in > class attributes and let __init__ accept keyword arguments: > > class Base(object): > > x = 0 > y = None > > def __init__(self, **kwds): > setattrs(self, kwds) > > where setattrs is: > > def setattrs(self, attrvals, strict=True): > if strict: > # raise AttributeError if some attr doesn't exist already > for attr in attrvals.iterkeys(): > getattr(self,attr) > for attr,val in attrvals.iteritems(): > setattr(self, attr, val) > > This way, only the new and overriden default attributes have to > repeated in derived classes: > > class Derived(Base): > > x = 1 > z = '' > > def __init__(self, **kwds): > super(Derived,self).__init__(**kwds) > print 'In Derived.__init__' > > > Is this a good way of doing it ? Is there a better pattern ? > > George > -- > http://mail.python.org/mailman/listinfo/python-list > -- -David From ggpolo at gmail.com Mon Jan 7 09:33:55 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 12:33:55 -0200 Subject: introspection question In-Reply-To: References: Message-ID: 2008/1/7, Alex K : > Hi Guys, > > What would be the simplest way of enumerating all methods and members > (including inherited) of a given object? Thank you. > > Alex > -- > http://mail.python.org/mailman/listinfo/python-list > import inspect inspect.getmembers(yourobject) -- -- Guilherme H. Polo Goncalves From steve at REMOVE-THIS-cybersource.com.au Wed Jan 30 20:08:42 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 31 Jan 2008 01:08:42 -0000 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! References: Message-ID: <13q27sqncv487a9@corp.supernews.com> On Wed, 30 Jan 2008 19:40:24 -0500, Blubaugh, David A. wrote: > I do not understand why no one has answered the following question: > > Has anybody worked with Gene Expression Programming???? Yes, people have worked with Gene Expression Programming. I don't know who. I don't know where. But I'm sure that there have been people who have worked with it. -- Steven From http Mon Jan 21 18:08:30 2008 From: http (Paul Rubin) Date: 21 Jan 2008 15:08:30 -0800 Subject: Transforming ascii file (pseduo database) into proper database References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> <051e9305-6f9a-4d95-91cb-641c04b97b79@e10g2000prf.googlegroups.com> Message-ID: <7x4pd63hg1.fsf@ruckus.brouhaha.com> "p." writes: > So as an exercise, lets assume 800MB file, each line of data taking up > roughly 150B (guesstimate - based on examination of sample data)...so > roughly 5.3 million unique IDs. I still don't understand what the problem is. Are you familiar with the concept of external sorting? What OS are you using? If you're using a Un*x-like system, the built-in sort command should do what you need. "Internal" sorting means reading a file into memory and sorting it in memory with something like the .sort() function. External sorting is what you do when the file won't fit in memory. Basically you read sequential chunks of the file where each chunk fits in memory, sort each chunk internally and write it to a temporary disk file, then merge all the disk files. You can sort inputs of basically unlimited size this way. The unix sort command knows how to do this. It's often a good exercise with this type of problem, to ask yourself how an old-time mainframe programmer would have done it. A "big" computer of the 1960's might have had 128 kbytes of memory and a few MB of disk, but a bunch of magtape drives that held a few dozen MB each. With computers like that, they managed to process the phone bills for millions of people. The methods that they used are still relevant with today's much bigger and faster computers. If you watch old movies that tried to get a high tech look by showing computer machine rooms with pulsating tape drives, external sorting is what those computers spent most of their time doing. Finally, 800MB isn't all that big a file by today's standards. Memory for desktop computers costs around 25 dollars per gigabyte so having 8GB of ram on your desk to crunch those 800MB files with is not at all unreasonable. From boblatest at yahoo.com Tue Jan 8 04:20:16 2008 From: boblatest at yahoo.com (Robert Latest) Date: 8 Jan 2008 09:20:16 GMT Subject: popen question Message-ID: <5ugtigF1ia3o4U5@mid.dfncis.de> Hello, look at this function: -------------- def test(): child = os.popen('./slow') for line in child: print line ------------- The program "slow" just writes the numbers 0 through 9 on stdout, one line a second, and then quits. I would have expected the python program to spit out a numbers one by one, instead I see nothing for 10 seconds and then the whole output all at once. How can I get and process the pipe's output at the pace it is generated? Thanks, robert From deets at nospam.web.de Wed Jan 23 18:14:49 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Jan 2008 00:14:49 +0100 Subject: creating .pyo with make In-Reply-To: <4797c8d7$0$16956$426a74cc@news.free.fr> References: <4797c5d7$0$20781$426a34cc@news.free.fr> <4797c8d7$0$16956$426a74cc@news.free.fr> Message-ID: <5vq03cF1mod1jU1@mid.uni-berlin.de> Yann Leboulanger schrieb: > Yann Leboulanger wrote: >> Hi, >> >> I use autoconf / automake to manage my python project, and I'l like >> make / make install to create / install .pyo files instead of .py files. >> >> Is there something I should add to my Makefile.am files to do that? Or >> should I do all that myself with py_compile module? >> >> Are there some examples somewhere with autotools? >> >> Thanks for your help > > Hehe replying to myself. It seems I just have to replace > project_DATA = $(srcdir)/*.py > by > project_PYTHON = $(srcdir)/*.py > > Then when I do make install, it installs .py, .pyc and .pyo. > Would it be possible to install only .pyo? Is it a good idea? There might be the occasional code that relies on doc-strings to work - seldomly, but possible. Which are obmitted by .pyo, but not of pyc. Apart from that, having only pyc-files (or pyo for that matter) sucks. Just today I had to delve into a ZOPE-application, setting breakpoints and getting things done. It would have been impossible or at least much more inconvenient to debug if I hadn't had the sources available (and put at a place where they actually get invoked from the interpreter, not lying around unrelated) Diez From alnilam at gmail.com Tue Jan 22 16:20:32 2008 From: alnilam at gmail.com (Alnilam) Date: Tue, 22 Jan 2008 13:20:32 -0800 (PST) Subject: HTML parsing confusion References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> <50269e4a-af44-4d73-b6cb-c42af6b5164d@e10g2000prf.googlegroups.com> <5vmkiiF1nadr7U1@mid.uni-berlin.de> Message-ID: On Jan 22, 11:39?am, "Diez B. Roggisch" wrote: > Alnilam wrote: > > On Jan 22, 8:44 am, Alnilam wrote: > >> > Pardon me, but the standard issue Python 2.n (for n in range(5, 2, > >> > -1)) doesn't have an xml.dom.ext ... you must have the mega-monstrous > >> > 200-modules PyXML package installed. And you don't want the 75Kb > >> > BeautifulSoup? > > >> I wasn't aware that I had PyXML installed, and can't find a reference > >> to having it installed in pydocs. ... > > > Ugh. Found it. Sorry about that, but I still don't understand why > > there isn't a simple way to do this without using PyXML, BeautifulSoup > > or libxml2dom. What's the point in having sgmllib, htmllib, > > HTMLParser, and formatter all built in if I have to use use someone > > else's modules to write a couple of lines of code that achieve the > > simple thing I want. I get the feeling that this would be easier if I > > just broke down and wrote a couple of regular expressions, but it > > hardly seems a 'pythonic' way of going about things. > > This is simply a gross misunderstanding of what BeautifulSoup or lxml > accomplish. Dealing with mal-formatted HTML whilst trying to make _some_ > sense is by no means trivial. And just because you can come up with a few > lines of code using rexes that work for your current use-case doesn't mean > that they serve as general html-fixing-routine. Or do you think the rather > long history and 75Kb of code for BS are because it's creator wasn't aware > of rexes? > > And it also makes no sense stuffing everything remotely useful into the > standard lib. This would force to align development and release cycles, > resulting in much less features and stability as it can be wished. > > And to be honest: I fail to see where your problem is. BeatifulSoup is a > single Python file. So whatever you carry with you from machine to machine, > if it's capable of holding a file of your own code, you can simply put > BeautifulSoup beside it - even if it was a floppy ?disk. > > Diez I am, by no means, trying to trivialize the work that goes into creating the numerous modules out there. However as a relatively novice programmer trying to figure out something, the fact that these modules are pushed on people with such zealous devotion that you take offense at my desire to not use them gives me a bit of pause. I use non-included modules for tasks that require them, when the capability to do something clearly can't be done easily another way (eg. MySQLdb). I am sure that there will be plenty of times where I will use BeautifulSoup. In this instance, however, I was trying to solve a specific problem which I attempted to lay out clearly from the outset. I was asking this community if there was a simple way to use only the tools included with Python to parse a bit of html. If the answer is no, that's fine. Confusing, but fine. If the answer is yes, great. I look forward to learning from someone's example. If you don't have an answer, or a positive contribution, then please don't interject your angst into this thread. From http Thu Jan 24 19:14:40 2008 From: http (Paul Rubin) Date: 24 Jan 2008 16:14:40 -0800 Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <4799285d$0$36346$742ec2ed@news.sonic.net> Message-ID: <7x3asmep73.fsf@ruckus.brouhaha.com> John Nagle writes: > - Get enough memory to do the sort with an in-memory sort, like > UNIX "sort" or Python's "sort" function. Unix sort does external sorting when needed. From sergio.correia at gmail.com Wed Jan 30 19:54:11 2008 From: sergio.correia at gmail.com (Sergio Correia) Date: Wed, 30 Jan 2008 19:54:11 -0500 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> Message-ID: is this some kind of joke? if you get no answers, then the answer is no On Jan 30, 2008 7:40 PM, Blubaugh, David A. wrote: > I do not understand why no one has answered the following question: > > Has anybody worked with Gene Expression Programming???? > > > 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: Wednesday, January 30, 2008 6:10 PM > To: python-list at python.org > Subject: Python-list Digest, Vol 52, Issue 437 > > 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. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From skip at pobox.com Tue Jan 15 10:10:38 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 15 Jan 2008 09:10:38 -0600 Subject: Why this apparent assymetry in set operations? Message-ID: <18316.52462.481389.962217@montanaro.dyndns.org> I've noticed that I can update() a set with a list but I can't extend a set with a list using the |= assignment operator. >>> s = set() >>> s.update([1,2,3]) >>> s set([1, 2, 3]) >>> s |= [4,5,6] Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for |=: 'set' and 'list' >>> s |= set([4,5,6]) >>> s set([1, 2, 3, 4, 5, 6]) Why is that? Doesn't the |= operator essentially map to an update() call? Skip From Scott.Daniels at Acm.Org Tue Jan 1 16:34:48 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 01 Jan 2008 13:34:48 -0800 Subject: confusion about package/module imports In-Reply-To: References: Message-ID: <13nlc7fecs63099@corp.supernews.com> Jugdish wrote: > Why doesn't the following work? > ... [well boiled-down code skipped] >>>> setenv PYTHONPATH $HOME:$PYTHONPATH >>>> python $HOME/pkg/subpkg/b.py > Traceback (most recent call last): > File "pkg/subpkg/b.py", line 1, in ? > import pkg.subpkg.a > File "$HOME/pkg/subpkg/__init__.py", line 2, in ? > import b > File "$HOME/pkg/subpkg/b.py", line 2, in ? > class B(pkg.subpkg.a.A): > AttributeError: 'module' object has no attribute 'subpkg' OK, here's a trick for finding import problems: python -v (shows all imports) And for this case: sprinkle prints to find out what is happening. so, add "print __name, __file__" to the top of each file where you wonder what is going on. I later added prints in pkg/subpkg/__init__.py to make the steps clear. You'll see that b is executed (making module __main__), it imports pkg.subpkg.a, which is accomplished by importing pkg (successfully), then by importing pkg.subpkg which imports pkg.subpkg.a (successfully) and then imports pkg.subpkg.b which then attempts to import pkg.subpkg.a At that point, only the module pkg and what should eventually become pkg.subpkg.a have been successfully imported. pkg.subpkg had not yet been imported. If you remove the "import b" from subpkg's __init__, you will find your problems going away. Alternatively, you can remove the import a / import b from subpkg and add import subpkg.a, subpkg.b to pkg's __init__. Essentially, you need pkg.subpkg fully imported before you import pkg.subpkg.b Of course, in most of these cases you will have imported the code for b twice, once as a main program, and once as a module in the hierarchy, which is probably your actual problem (and why I use "print __name__, __file__"). --Scott David Daniels Scott.Daniels at Acm.Org From jzgoda at o2.usun.pl Fri Jan 18 05:03:54 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 18 Jan 2008 11:03:54 +0100 Subject: [python] How to detect a remote webpage is accessible? (in HTTP) In-Reply-To: References: Message-ID: ?? napisa?(a): > Howdy, all, > I want to use python to detect the accessibility of website. > Currently, I use urllib > to obtain the remote webpage, and see whether it fails. But the problem is that > the webpage may be very large; it takes too long time. Certainly, it > is no need to download > the entire page. Could you give me a good and fast solution? > Thank you. Issue HTTP HEAD request. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From bj_666 at gmx.net Wed Jan 2 06:29:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Jan 2008 11:29:35 GMT Subject: wxpython application ( problem ? ) References: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> Message-ID: <5u1asvF1fgr5bU2@mid.uni-berlin.de> On Wed, 02 Jan 2008 03:24:56 -0800, vedrandekovic wrote: > Here is sample of my simple script with wxpython and modules: > subprocess,threading, directpython....... Are you accessing the GUI from threads? Ciao, Marc 'BlackJack' Rintsch From http Mon Jan 21 03:34:46 2008 From: http (Paul Rubin) Date: 21 Jan 2008 00:34:46 -0800 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <80e1aed1-1d75-4409-bbc3-d48f9c3656ab@e6g2000prf.googlegroups.com> Message-ID: <7x8x2jh909.fsf@ruckus.brouhaha.com> Arnaud Delobelle writes: > Update: 2, 4, 5, 8, 9, 25 can reach any target between 100 and 999. Are you sure? What expression do you get for target = 758? From fredrik at pythonware.com Wed Jan 9 02:51:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 08:51:06 +0100 Subject: Open a List of Files In-Reply-To: <18308.12959.742868.758136@terry.local> References: <874pdomrrd.fsf@mulj.homelinux.net> <18308.12959.742868.758136@terry.local> Message-ID: Terry Jones wrote: > I think you should revisit this decision. Something like Fredrik's code is > the way to go. He used my suggestion, just for a few more files than he had in his original post. Seriously, for a limited number of files, the dictionary approach is mostly pointless; you end up replacing foo = open("foo") foo.write(...) with somedict["foo"] = open("foo") somedict["foo"].write(...) which, frankly, sucks in a whole lot of ways. > It has multiple advantages: > > - It's much shorter. For a small number of files, it isn't, really. > - It's arguably easier to add/remove to/from. Only if you're not using the files you're opening; as soon you try to do something with them, it's more work. > - It has less risk of error (much less repetition). No, it hasn't. There's more to type when using the files, and you have *two* things you can misspell; that is, you're replacing a NameError with either a NameError or a KeyError. > - It allows your code to later take a string file tag and > write to that file by looking up its file descriptor in the dict. Instead of allowing your code to take a file object and write to that file by writing to that file object? > - You can close all open files with a trivial loop. Ok, this is actually an advantage. Not that you need to do that very often, since Python does it for you. And if you find yourself needing to do this a lot, you can of course stuff all the output files in a list but *still* use the variables to refer to the file when writing to them. ::: There is one case where a dictionary of files makes perfect sense, of course, and that's when you can associate the file with some *other* value that you're *already* using. (Say, a user name or a machine name or a severity level or something like that.) But inventing your own string tags to use instead of variables is just plain bad design. From electronixtar at gmail.com Wed Jan 2 07:38:09 2008 From: electronixtar at gmail.com (est) Date: Wed, 2 Jan 2008 04:38:09 -0800 (PST) Subject: dbus-python for windows Message-ID: <194e7fee-728a-48eb-9f51-1e272ecca838@j20g2000hsi.googlegroups.com> Hi all I am trying to port Scribes to Windows, but I could not find a package named dbus-python for windows. There is a windbus but it not for Python, so how could I install dbus module for Windows Python 2.5 ? ps Is there anyone trying to port Scribes to Windows? From spaceoutlet at gmail.com Wed Jan 9 07:47:18 2008 From: spaceoutlet at gmail.com (Alex K) Date: Wed, 9 Jan 2008 13:47:18 +0100 Subject: PIL question Message-ID: Hello, Would anyone know how to generate thumbnails with rounded corners using PIL? I'm also considering imagemagick if PIL turns out not to be appropriate for the task. Thank you so much, Alex From mark.e.tolonen at mailinator.com Sat Jan 26 12:34:27 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Sat, 26 Jan 2008 09:34:27 -0800 Subject: Beginner String formatting question References: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> Message-ID: wrote in message news:68769e37-7787-414f-abd3-a447341e9f7d at v17g2000hsa.googlegroups.com... > Hi all, > > I am trying to write a simple program that will accept an integral > "time" input in the HHMMSS format and output a "HH:MM:SS" form. My > code is as follows: > ======================== > import string > > def FormatTime(time): > '''Converts an HHMMSS string to HH:MM:SS format.''' > > timeString = str(time) #converts the num to string > > hours = [timeString[0], timeString[1]] > minutes = [timeString[2], timeString[3]] > seconds = [timeString[4], timeString[5]] > > Ftime = "%s:%s:%s",(hours,minutes,seconds) > clock = Ftime.join() > > return clock > =========================== > > when I run it from IDLE, I get this: > >>>> Format.FormatTime(time) > ['1', '1', ':', '2', '2', ':', '3', '3'] > ['1', '1', ':', '2', '2', ':', '3', '3'] > > My questions- > 1) Why is this function printing out twice? > 2)It may be a formatting issue, but I want to have the output as > "HH:MM:SS", rather than having it broken out into each cell. I > thought the 'join' command would do this, but I must not be using it > properly/understanding something. > 3)as a side note, I've noticed that the parameter "time" passed in > must be passed in as a string, otherwise I receive an error that > "time" is unsubscriptable. Am I unable to pass in an int and then > convert it to a string within the function with str()? > > I've been at this for a while, so I may not be able to see the forest > through the trees at this point. I'd greatly appreciate any > suggestions or instruction on these mistakes. > > Best, > > Jimmy Your code as displayed above doesn't work. >>> Format.FormatTime(112233) Traceback (most recent call last): File "", line 1, in File "Format.py", line 13, in FormatTime clock = Ftime.join() AttributeError: 'tuple' object has no attribute 'join' >>> Format.FormatTime('112233') Traceback (most recent call last): File "", line 1, in File "Format.py", line 13, in FormatTime clock = Ftime.join() AttributeError: 'tuple' object has no attribute 'join' Make sure to copy/paste the exact working code. Look at the 'time' and 'datetime' modules and the functions and methods 'strftime' and 'strptime' for displaying and parsing times. --Mark From steve at REMOVE-THIS-cybersource.com.au Sat Jan 5 00:24:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 05 Jan 2008 05:24:19 -0000 Subject: How a smart editor could make "Postfix type declarations PEP3117" in Python3000 more readable References: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> Message-ID: <13nu54396vganbc@corp.supernews.com> On Fri, 04 Jan 2008 19:39:13 -0800, aspineux wrote: > Hi > > I read the PEP 3117 about the new "Postfix type declarations" in > Python3000. > THIS PEP as been REJECTED ! But ... > > The notation in the PEP is very ugly ! This make python code more > difficult to read! Please look at the date on the PEP: http://www.python.org/dev/peps/pep-3117/ -- Steven From kyosohma at gmail.com Tue Jan 15 15:36:58 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 15 Jan 2008 12:36:58 -0800 (PST) Subject: A question about event handlers with wxPython References: <478c3bb2$0$5150$4c368faf@roadrunner.com> <2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com> <478ccbc3$0$11000$4c368faf@roadrunner.com> <478d15b4$0$18437$4c368faf@roadrunner.com> Message-ID: <0571a7cd-f7f6-44b4-a4d5-e427de93590a@c4g2000hsg.googlegroups.com> On Jan 15, 2:20 pm, "Erik Lind" wrote: > That all looks cool. I will experiment more. I'm a bit slow on this as only > two weeks old so far. > > Thanks for the patience No problem. I'm pretty slow with some toolkits too...such as SQLAlchemy. Ugh. Mike From stef.mientki at gmail.com Tue Jan 22 16:35:45 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 22 Jan 2008 22:35:45 +0100 Subject: get the size of a dynamically changing file fast ? In-Reply-To: <198fd91f-912b-4f56-a840-af96225125a7@c23g2000hsa.googlegroups.com> References: <198fd91f-912b-4f56-a840-af96225125a7@c23g2000hsa.googlegroups.com> Message-ID: <479661B1.8010005@gmail.com> Mike Driscoll wrote: > On Jan 17, 3:56 pm, Stef Mientki wrote: > >> hello, >> >> I've a program (not written in Python) that generates a few thousands >> bytes per second, >> these files are dumped in 2 buffers (files), at in interval time of 50 msec, >> the files can be read by another program, to do further processing. >> >> A program written in VB or delphi can handle the data in the 2 buffers >> perfectly. >> Sometimes Python is also able to process the data correctly, >> but often it can't :-( >> >> I keep one of the files open en test the size of the open datafile each >> 50 msec. >> I have tried >> os.stat ( ....) [ ST_SIZE] >> os.path.getsize ( ... ) >> but they both have the same behaviour, sometimes it works, and the data >> is collected each 50 .. 100 msec, >> sometimes 1 .. 1.5 seconds is needed to detect a change in filesize. >> >> I'm using python 2.4 on winXP. >> >> Is there a solution for this problem ? >> >> thanks, >> Stef Mientki >> > > Tim Golden has a method to watch for changes in a directory on his > website: > > http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html > > This old post also mentions something similar: > > http://mail.python.org/pipermail/python-list/2007-October/463065.html > > And here's a cookbook recipe that claims to do it as well using > decorators: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/426620 > > Hopefully that will get you going. > > Mike > thanks Mike, sorry for the late reaction. I've it working perfect now. After all, os.stat works perfectly well, the problem was in the program that generated the file with increasing size, by truncating it after each block write, it apperently garantees that the file is flushed to disk and all problems are solved. cheers, Stef Mientki From t.rectenwald at gmail.com Thu Jan 3 20:25:18 2008 From: t.rectenwald at gmail.com (t_rectenwald) Date: Thu, 3 Jan 2008 17:25:18 -0800 (PST) Subject: Cursors in a Loop References: <3da337d8-2de0-4fdb-8c38-2f6fcd8348ac@i72g2000hsd.googlegroups.com> Message-ID: On Jan 3, 7:47?pm, t_rectenwald wrote: > I have a python script that uses the cx_Oracle module. ?I have a list > of values that I iterate through via a for loop and then insert into > the database. ?This works okay, but I'm not sure whether I can use one > cursor for all inserts, and define it outside of the loop, or > instantiate and close the cursor within the loop itself. ?For example, > I have: > > for i in hostlist: > ? ? cursor = connection.cursor() > ? ? sql= "insert into as_siebel_hosts_temp values('%s')" % (i) > ? ? cursor.execute(sql) > ? ? cursor.close() > > And I've also tried: > > cursor = connection.cursor() > for i in hostlist: > ? ? sql= "insert into as_siebel_hosts_temp values('%s')" % (i) > ? ? cursor.execute(sql) > cursor.close() > > Both work fine, and execute in the same amount of time. ?I'm just > trying to understand what is the "correct" approach to use. > > Thanks, > Tom I think I have this one figured out. The answer would be the second option, i.e. keep the cursor instantion and close outside of the loop. I wasn't aware that one cursor could be used for multiple executes. Regards, Tom From steve at holdenweb.com Thu Jan 31 09:10:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 09:10:50 -0500 Subject: REALLY simple xml reader In-Reply-To: <87tzkujeq6.fsf@benfinney.id.au> References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> <87tzkujeq6.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Steve Holden writes: > >> Diez B. Roggisch wrote: >>> Ricardo Ar?oz schrieb: >>>> doc = """ >>>> >>> It's not allowed to have a newline before the >>> >>> Put it on the line above, and things will work. >>> >> If you don't think that looks pretty enough just escape the first >> newline in the string constant to have the parser ignore it: > > 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. > >> doc = """\ >> > > This is fine. > Sure. The only difference in "prettiness" I was referring to was the difference betwee doc = """ ... and doc = """\ ... In other words, Python source-code prettiness. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From nonamehuang at yahoo.com.cn Sat Jan 5 08:55:22 2008 From: nonamehuang at yahoo.com.cn (nonamehuang at yahoo.com.cn) Date: Sat, 5 Jan 2008 05:55:22 -0800 (PST) Subject: Welcome to my webside that provides help in English Study for Chinese.. Message-ID: <9fcfae8c-4485-4df1-b10f-52a2e257a767@s12g2000prg.googlegroups.com> The address is http://englearn.zhan.cn.yahoo.com And I need your advice. Well, maybe your help. You see. aha! From travis.jensen at gmail.com Fri Jan 25 00:54:58 2008 From: travis.jensen at gmail.com (Travis Jensen) Date: Thu, 24 Jan 2008 22:54:58 -0700 Subject: Which is more pythonic? In-Reply-To: <56518bb9-1d56-47c3-8112-6e0778832c12@v29g2000hsf.googlegroups.com> References: <56518bb9-1d56-47c3-8112-6e0778832c12@v29g2000hsf.googlegroups.com> Message-ID: <6480447F-1496-430A-A9A6-555358EBCA97@gmail.com> Well, regardless of being "pythonic" or not, the first is far more understandable and therefore more maintainable. Objects were invented to handle holding state; using a function to hold state is, in my opinion, doing a language-based cheat. :) tj On Jan 24, 2008, at 10:14 PM, benjamin.zimmerman at gmail.com wrote: > I have a goal function that returns the fitness of a given solution. I > need to wrap that function with a class or a function to keep track of > the best solution I encounter. Which of the following would best serve > my purpose and be the most pythonic? > > class Goal: > def __init__(self, goal): > self.goal = goal > self.best = None > self.best_score = None > > def __call__(self, solution): > score = self.goal(solution) > if self.best is None or score > self.best_score: > self.best_score = score > self.best = solution > return score > > def save_best_goal(goal): > def new_goal(solution): > score = goal(solution) > if new_goal.best is None or score > new_goal.best_score: > new_goal.best = solution > new_goal.best_score = score > return score > new_goal.best = new_goal.best_score = None > return new_goal > > -Ben > -- > http://mail.python.org/mailman/listinfo/python-list Travis Jensen travis.jensen at gmail.com http://softwaremaven.innerbrane.com/ You should read my blog; it is more interesting than my signature. From lists at cheimes.de Sat Jan 19 16:31:38 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 19 Jan 2008 22:31:38 +0100 Subject: finding memory leak in edgewall trac 0.11 In-Reply-To: <20080119202909.GY61556@nexus.in-nomine.org> References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> Message-ID: <47926C3A.5060000@cheimes.de> Jeroen Ruigrok van der Werven wrote: > Hi Christian, > > -On [20080119 16:16], Christian Heimes (lists at cheimes.de) wrote: >> I forgot one important point in my reply. The GC module contains some >> useful methods for debugging. Check gc.garbage. It should be empty. > > Yeah, we're messing around with that stuff as well as many other ways of > trying to track issues, but it can really be looking for a needle in a > haystack to be honest. > There's so much output that, I guess, make sense only when you're semi-deep > into the Python internals to even make heads or tails out of it. =\ > And even third-party code is not helping much to reduce the clutter and > provide insight. Under normal circumstances gc.garbage should be an empty list. In general it's a bad sign if gc.garbage contains lots of objects. I found several potential leaks in trac: $ find -name \*.py | xargs grep __del__ ./trac/versioncontrol/svn_fs.py: def __del__(self): ./trac/versioncontrol/svn_fs.py: def __del__(self): ./trac/db/pool.py: def __del__(self): $ find -name \*.py | xargs grep frame ./trac/web/main.py: [...] ./trac/core.py: frame = sys._getframe(1) ./trac/core.py: locals_ = frame.f_locals I recommend that you either replace __del__ with a weak reference callback or to remove it. Referencing a frame, traceback or f_locals is going to leak, too. You *must* explicitly del every frame and locals variable. Christian From stanc at al.com.au Wed Jan 30 22:01:30 2008 From: stanc at al.com.au (Astan Chee) Date: Thu, 31 Jan 2008 14:01:30 +1100 Subject: small problem with re.sub Message-ID: <47A13A0A.3010607@al.com.au> Hi, I have a html text stored as a string. Now I want to go through this string and find all 6 digit numbers and make links from them. Im using re.sub and for some reason its not picking up the previously matched condition. Am I doing something wrong? This is what my code looks like: htmlStr = re.sub('(?P\d{6})','(?P=id)',htmlStr) It seems that it replaces it alright, but it replaces it literally. Am I not escaping certain characters? Thanks again for the help. Cheers Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. From bignose+hates-spam at benfinney.id.au Wed Jan 23 16:32:14 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 24 Jan 2008 08:32:14 +1100 Subject: Module/package hierarchy and its separation from file structure References: Message-ID: <874pd49qjl.fsf@benfinney.id.au> Peter Schuller writes: > Let me just shoot down one possible suggestion right away, to show > you what I am trying to accomplish: > > I do *not* want to simply break out X into org.lib.animal.x, and > have org.lib.animal import org.lib.animal.x.X as X. Nevertheless, that seems the best (indeed, the Pythonic) solution to your problem as stated. Rather than just shooting it down, we'll have to know more about ehat actual problem you're trying to solve to understand why this solution doesn't fit. > While this naively solves the problem of being able to refer to X as > org.lib.animal.X, the solution is anything but consistent because > the *identity* of X is still org.lib.animal.x.X. The term "identity" in Python means something separate from this concept; you seem to mean "the name of X". > Examples of way this breaks things: > > * X().__class__.__name__ gives unexpected results. Who is expecting them otherwise, and why is that a problem? > * Automatically generated documentation will document using the > "real" package name. Here I lose all track of what problem you're trying to solve. You want the documentation to say exactly where the class "is" (by name), but you don't want the class to actually be defined at that location? I can't make sense of that, so probably I don't understand the requirement. -- \ "If it ain't bust don't fix it is a very sound principle and | `\ remains so despite the fact that I have slavishly ignored it | _o__) all my life." ?Douglas Adams | Ben Finney From JO3chiang at gmail.com Tue Jan 8 02:01:35 2008 From: JO3chiang at gmail.com (jo3c) Date: Mon, 7 Jan 2008 23:01:35 -0800 (PST) Subject: use fileinput to read a specific line References: <6f2db44c-2641-47cb-ab24-4177ccc96d6e@m77g2000hsc.googlegroups.com> <13o637afk4mql0c@corp.supernews.com> <44c28069-12bf-43c2-96f6-06b4c3923188@41g2000hsy.googlegroups.com> Message-ID: <84b55d6a-2bda-442a-8336-3175eb34ba45@i7g2000prf.googlegroups.com> On Jan 8, 2:08 pm, "Russ P." wrote: > > Given that the OP is talking 2000 files to be processed, I think I'd > > recommend explicit open() and close() calls to avoid having lots of I/O > > structures floating around... > > Good point. I didn't think of that. It could also be done as follows: > > for fileN in files: > > lnum = 0 # line number > input = file(fileN) > > for line in input: > lnum += 1 > if lnum >= 4: break > > input.close() > > # do something with "line" > > Six of one or half a dozen of the other, I suppose. this is what i did using glob import glob for files in glob.glob('/*.txt'): x = open(files) x.readline() x.readline() x.readline() y = x.readline() # do something with y x.close() From spaceoutlet at gmail.com Sat Jan 12 04:45:35 2008 From: spaceoutlet at gmail.com (Alex K) Date: Sat, 12 Jan 2008 10:45:35 +0100 Subject: paging in python shell Message-ID: Hello, Does anyone know if the python shell supports paging or if I should look into iPython? Thank you so much. Alex From peter.schuller at infidyne.com Tue Jan 29 07:51:58 2008 From: peter.schuller at infidyne.com (Peter Schuller) Date: Tue, 29 Jan 2008 06:51:58 -0600 Subject: Module/package hierarchy and its separation from file structure References: <04ab182a-5ecd-4d1b-89c5-ac321048f6f1@x69g2000hsx.googlegroups.com> Message-ID: > You can reassign the class's module: > > from org.lib.animal.monkey import Monkey > Monkey.__module__ = 'org.lib.animal' > > > (Which, I must admit, is not a bad idea in some cases.) Is there a sense whether this is truly a supported way of doing this, in terms of not running into various unintended side-effects? One example would be sys.modules that I mentioned in the previous post. Another, possibly related, might be interaction with the import keyword and its implementation. I will probably have to read up more on the semantics of __import__ and related machinery. -- / Peter Schuller PGP userID: 0xE9758B7D or 'Peter Schuller ' Key retrieval: Send an E-Mail to getpgpkey at scode.org E-Mail: peter.schuller at infidyne.com Web: http://www.scode.org From boblatest at yahoo.com Wed Jan 9 15:02:20 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 20:02:20 GMT Subject: How does unicode() work? References: <5ujt96F1i6h37U1@mid.dfncis.de> <1199888091.3474.9.camel@dot.uniqsys.com> Message-ID: <5uknicF1il028U2@mid.uni-berlin.de> John Machin wrote: > When mixing unicode strings with byte strings, Python attempts to > decode the str object to unicode, not encode the unicode object to > str. Thanks for the explanation. Of course I didn't want to mix Unicode and Latin in one string, my snippet just tried to illustrate the point. I'm new to Python -- I came from C, and C gives a rat's ass about encoding. It just dumps bytes and that's that. robert From jorgen.maillist at gmail.com Sat Jan 12 06:02:20 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Sat, 12 Jan 2008 12:02:20 +0100 Subject: where do my python files go in linux? Message-ID: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> Hi All, I am trying to make a debian package. I am following the tutorial by Horst Jens (http://showmedo.com/videos/video?name=linuxJensMakingDeb&fromSeriesID=37) and it is very informative. However one thing my app has and his doesn't, is multiple python files which need to be executed. For example {dir}/app app.py app.py calls a lot of modules in {dir}/app. Horst says the python file goes in /usr/bin/app.py which is ok with me, but I have multiple python files, and I decided to use an app.sh script to call my python files. In the /usr/bin I do not see subdirs so I assume that is not really desirable. Question 1. Where do I put the bulk of python scripts in a normal linux environment? Question 2. Should I use *.pyc rather then *.py files to speed up executing as the user cannot write to /usr/bin or any other dir in the system and everytime my app runs it will recompile it Thanks for any advice or maybe a good tutorial how to set up files in a linux environment With regards, - Jorgen From fredrik at pythonware.com Sat Jan 12 16:50:10 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Jan 2008 22:50:10 +0100 Subject: sqlite3 is it in the python default distro? In-Reply-To: References: Message-ID: Martin Marcher wrote: > I can see that sqlite is in the standard lib documentation: > http://docs.python.org/lib/module-sqlite3.html > > however debian and ubuntu (and gentoo according to the packages info) seem > _not_ to include it. http://packages.debian.org/python-sqlite From attn.steven.kuo at gmail.com Tue Jan 29 12:23:16 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Tue, 29 Jan 2008 09:23:16 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: Message-ID: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> On Jan 29, 8:34 am, William McBrine wrote: > Look at this -- from Python 2.5.1: > > >>> a = [1, 2, 3, 4, 5] > >>> for x in a: > > ... if x == 3: > ... a.remove(x) > ... print x > ... > 1 > 2 > 3 > 5 > > >>> a > [1, 2, 4, 5] > > Sure, the resulting list is correct. But 4 is never printed during the > loop! > (snipped) If you're going to delete elements from a list while iterating over it, then do it in reverse order: >>> a = [ 98, 99, 100 ] >>> last_idx = len(a) - 1 >>> for i, x in enumerate(a[::-1]): ... if x == 99: del(a[last_idx - i]) ... print x ... 100 99 98 >>> a [98, 100] -- Hope this helps, Steven From sjmachin at lexicon.net Wed Jan 9 15:01:30 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 9 Jan 2008 12:01:30 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> <962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.googlegroups.com> Message-ID: On Jan 10, 6:52 am, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of Fredrik Lundh > > Sent: Wednesday, January 09, 2008 2:39 PM > > To: python-l... at python.org > > Subject: Re: problem of converting a list to dict > > > Louis.Soni... at gmail.com wrote: > > > >> to see what's going on on your machine, try printing "a" after the > > >> split, but before you use it to populate the dictionary. > > > > 'print a' works > > > so what does it tell you? > > A bigger hint: > a=i.split('=') > print "'%s' splits into " % (i), a consider: (1) using %r instead of '%s' (2) omitting the redundant space after 'into' (3) losing the redundant () around i > assert len(a) == 2 > mydict[a[0]]=a[1] From wuhrrr at gmail.com Thu Jan 17 02:48:51 2008 From: wuhrrr at gmail.com (Hai Vu) Date: Wed, 16 Jan 2008 23:48:51 -0800 (PST) Subject: Parsing links within a html file. References: Message-ID: <34a13767-43de-46d0-9691-d3d267208bd9@s13g2000prd.googlegroups.com> On Jan 14, 9:59 am, Shriphani wrote: > Hello, > I have a html file over here by the name guide_ind.html and it > contains links to other html files like guides.html#outline . How do I > point BeautifulSoup (I want to use this module) to > guides.html#outline ? > Thanks > Shriphani P. Try Mark Pilgrim's excellent example at: http://www.diveintopython.org/http_web_services/index.html >From the above link, you can retrieve openanything.py which I use in my example: # list_url.py # created by Hai Vu on 1/16/2008 from openanything import fetch from sgmllib import SGMLParser class RetrieveURLs(SGMLParser): def reset(self): SGMLParser.reset(self) self.urls = [] def start_a(self, attributes): url = [v for k, v in attributes if k.lower() == 'href'] self.urls.extend(url) print '\t%s' % (url) # -------------------------------------------------------------------------------------------------------------- # main def main(): site = 'http://www.google.com' result = fetch(site) if result['status'] == 200: # Extracts a list of URLs off the top page parser = RetrieveURLs() parser.feed(result['data']) parser.close() # Display the URLs we just retrieved print '\nURL retrieved from %s' % (site) print '\t' + '\n\t'.join(parser.urls) else: print 'Error (%d) retrieving %s' % (result['status'], site) if __name__ == '__main__': main() From hniksic at xemacs.org Fri Jan 11 18:23:45 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 12 Jan 2008 00:23:45 +0100 Subject: Newbie Q: modifying SQL statements References: <20080111013206.GA18259@neptune.faber.nom> <20080110225352.2c112555@bhuda.mired.org> Message-ID: <87d4s8ndz2.fsf@mulj.homelinux.net> "Faber J. Fedor" writes: > On 10/01/08 22:53 -0500, Mike Meyer wrote: >> Personally, I think it would be more pythonic to not try and use two >> different APIs to walk the list of jobs (... One Way To Do it): >> >> def __call__(self, where=None): >> q = "select * from %s" % (self.name,) + ("" if not where else (" where %s" % where)) > > Does this '("" if not where...' syntax actually work? http://docs.python.org/whatsnew/pep-308.html From Russ.Paielli at gmail.com Mon Jan 28 02:56:16 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 23:56:16 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> <87lk6a8m8q.fsf@physik.rwth-aachen.de> <13pr24chv832660@corp.supernews.com> Message-ID: <00eb8dc1-6fd8-4090-8d0b-4e586d6e260d@s12g2000prg.googlegroups.com> On Jan 27, 11:47 pm, Steven D'Aprano wrote: > On Mon, 28 Jan 2008 08:04:05 +0100, Torsten Bronger wrote: > >> Are you referring to the alternate syntax or to the decorator? Either > >> way, you could be saving 4 or 5 or more lines, if you have enough > >> arguments. > > > Mostly, I write them in one or two lines, e.g. > > > def __init__(self, id, kind, person, feedname): > > self.id, self.kind, self.person = id, kind, person > > It's not the number of lines that is important, but the amount of > redundant code, and the amount of redundant code is identical whether you > write it in one line or three. > > The problem is that instance initialization frequently and regularly > breaks the principle "Don't Repeat Yourself". Whether you initialize your > code like this: > > self.id = id > self.kind = kind > self.person person > > or like this: > > self.id = id; self.kind = kind; self.person = person > > or like this: > > self.id, self.kind, self.person = id, kind, person > > you are repeating yourself. > > Unfortunately, without syntactical support, I don't think there is any > easy way to tell the compiler which arguments to auto-initialize and > which to skip. And Guido rightly is reluctant to create special syntax > for special cases, and something which happens only in __init__ (and > maybe __new__?) is certainly a special case. > > That leaves a decorator solution, married with a convention for names. > > Here's a thought... why assume that the convention is a prefix? What > about a suffix? > > @autoassign > def __init__(self, spam_, ham_, eggs): > pass > > A trailing underscore doesn't conflict with the conventions for leading > underscores. The only conflict is with the convention that if you want a > name that looks like a reserved word you put an underscore after it. > Since Python has very few reserved words, and they rarely make good > argument names, there should be far fewer conflicts with an underscore > suffix rather than a prefix. > > I'd still prefer compiler support, preferably with a leading & as syntax. > Since all the work would happen at compile time, it wouldn't effect the > runtime speed, and it wouldn't lead to any confusion with function > signatures. The class you get would be exactly the same as if you had > done the attribute initialization by hand, except the compiler did it. > > That's the ideal solution, but failing that, a decorator solution with a > trailing _ gets my vote. > > -- > Steven The problem with a trailing underscore is that it creates another valid name, so if someone used the name foo_, it would conflict with your convention. You need a character that is not part of a valid Python identifier or operator, such as &, $, %, @, !, ~, or ^. From larry.bates at websafe.com Fri Jan 25 11:27:06 2008 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 25 Jan 2008 10:27:06 -0600 Subject: is possible to get order of keyword parameters ? In-Reply-To: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> Message-ID: Keyword arguments are normally treaded as "order independent". Why do you think you need to find the order? What problem do you wish to solve? -Larry rndblnch wrote: > (sorry, draft message gone to fast) > > i.e. is it possible to write such a function: > > def f(**kwargs): > > return result > > such as : > f(x=12, y=24) == ['x', 'y'] > f(y=24, x=12) == ['y', 'x'] > > what i need is to get the order of the keyword parameters inside the > function. > any hints ? > > thanks, > > renaud From bladedpenguin at gmail.com Sat Jan 26 00:30:25 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 21:30:25 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> <45a8d4a7-d24d-461e-9783-59a7d697a041@q77g2000hsh.googlegroups.com> <499aaee4-7e8f-47fb-bedd-7db548b92a5c@i29g2000prf.googlegroups.com> Message-ID: <9ceb64c0-7c92-47c3-910d-a3b29221aaa1@k39g2000hsf.googlegroups.com> On Jan 25, 10:25 pm, petr.jakes.... at gmail.com wrote: > > I agree that SDL is probably the best choice but for the sake of > > completeness, Gtk can (at least in theory - I've never tried it) be > > built against directfb and run without X. > > from the Pygame Introduction: Pygame is a Python extension library > that wraps the SDL library and it's helpers. So you mean, Pygame can > run without X? > > BTW I have nothing against X, I just have not experiences on the GUI > field, so my feeling was it can run faster without X on the 500MHz AMD > Geode CPU. > > Petr The problem is not with x: you should be able to run x just fine with only 133MHZ and a few megs of ram. The performance issues on such a machine come from things like kde and gnome. use one of the simpler window managers. From timr at probo.com Thu Jan 10 01:49:43 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 10 Jan 2008 06:49:43 GMT Subject: Tracking colors References: Message-ID: <2ofbo3pu87j82uib3h25dhs0827elaei23@4ax.com> dongie.agnir at gmail.com wrote: > >I'm just getting started with Python, and I want to do a bit of color >tracking using VideoCapture. However, I've never worked with video or >images, so I'm a little at a loss. How would I use VideoCapture to >track a specified color, and its coordinates? There's really no easy way to do this. You'll have to convert the image to an array of pixels, then search through them to find a block of the color you're interested in. Remember that camera sensors are real-world devices, so the actual pixel values vary slightly from frame to frame. You'll have to look for a range. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From eieimemiv at gmail.com Tue Jan 1 07:13:07 2008 From: eieimemiv at gmail.com (eieimemiv at gmail.com) Date: Tue, 1 Jan 2008 12:13:07 +0000 (UTC) Subject: M-I,5`Persecution ` B ernard Levin expre sses hi s vie ws Message-ID: The article of which part. is reproduced below was penned by Bernard Levin for the. Features section of the Times on 21 September 1991. To my mind, it described the situation at the time and in particular a recent. meeting with a friend, during which I for the first time admitted to someone. other than my GP that I had. been subjected to a conspiracy of harassment over the previous year. and a half. >There is a madman running loose about. London, called David Campbell; I have >no reason to believe. that he is violent, but he should certainly be >approached with caution. You may. know him by the curious glitter in his >eyes and a persistent. trembling of his hands; if that does not suffice, you >will find him attempting to thrust no fewer than 48 books. into your arms, >all hardbacks, with a promise that, if you should return to the. same >meeting-place next year, he will heave. another 80 at you. > >If, by now, the police have arrived and are keeping a close watch on. him, >you may. feel sufficiently emboldened to examine the books. The jackets are >a. model of uncluttered typography, elegantly and simply laid out; there is >an unobtrusive colophon of. a rising sun, probably not picked at random. >Gaining confidence - the lunatic is smiling by now, and. the policemen, who >know about such things, have. significantly removed their helmets - you >could do. worse than take the jacket off the first book in the pile. The >only. word possible to describe the binding is sumptuous; real cloth in a >glorious shade of dark green, with the title and author in black. and gold >on. the spine. > >Look at it more closely; your eyes do not deceive you - it truly does. have >real top-bands and tail-bands, in yellow,. and, for good measure, a silk >marker ribbon in a lighter green. The. paper is cream-wove and acid-free, >and the book is sewn,. not glued. > >Throughout the encounter, I. should have mentioned, our loony has been >chattering away, although what he. is trying to say is almost impossible to >understand; after a time, however, he becomes sufficiently coherent to. make >clear that he. is trying to sell the books to you. Well, now, such quality >in. bookmaking today can only be for collectors' limited editions at a >fearsome price -. #30, #40, #50? > >No, no, he. says, the glitter more powerful than ever and the trembling of >his hands rapidly. spreading throughout his entire body; no, no - the books >are priced variously at. #7, #8 or #9, with the top price #12. > >At this, the policemen understandably put their helmets. back on; one of >them draws his truncheon and the. other can be heard summoning >reinforcements on his walkie-talkie. The madman. bursts into tears, and >swears it is all. true. > >And. it is. > >David Campbell has. acquired the entire rights to the whole of the >Everyman's. Library, which died a lingering and shameful death a decade or >so ago, and he proposes to start it. all over again - 48 volumes this >September. and 80 more next year, in editions I have described, at the >prices specified.. He proposes to launch his amazing venture simultaneously >in Britain and the. United States, with the massive firepower of Random >Century at his back in this country, and the dashing cavalry of. Knopf >across the water, and no. one who loves literature and courage will forbear >to. cheer. At the time this article was written I had believed for. some time that columnists in the Times and. other journalists had been making references to my situation. Nothing. unusual about this you may think, plenty of people have the same sort of ideas. and obviously the papers aren't writing about them, so why should my beliefs not be as false. as those of others? What makes this article. so extraordinary is that three or four days immediately preceding its publication, I had a meeting with. a friend, during the course of. which we discussed the media persecution, and in particular that by Times columnists. It seemed to. me, reading the article by Levin in Saturday?s. paper, that he was describing in some detail his "artist?s impression" of that. meeting. Most telling are the final sentences, when. he writes, "The madman bursts into tears, and swears it is all true. And it is." Although I did not "burst into tears" (he. seems to be using a bit of. poetic licence and exaggerating) I did try hard to convince my friend that it was all true; and. I am able to concur with Mr Levin, because, of. course, it is. At the beginning of the piece Levin reveals a. fear of being attacked by the "irrational" subject of his. story, saying "I have no reason to believe that he is violent, but. he should certainly be approached with caution". This goes back. to the xenophobic propaganda of "defence" against a "threat" which was seen at the very beginning of the harassment. The impression. of a "madman running loose" who needs to be controlled through. an agency which assigns to itself the mantle. of the "police" is also one which had been expressed. elsewhere. In the. final paragraph of this extract, his reference to Everyman?s Library as having "died a lingering and shameful death a decade or. so ago" shows clearly what sort of conclusion. they wish to their campaign. They want a permanent solution,. and as they are prevented from achieving that solution directly, they waste significant resources on. methods which have been repeatedly shown to be. ineffective for such a purpose. 5203 From Russ.Paielli at gmail.com Sun Jan 27 21:08:25 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 18:08:25 -0800 (PST) Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> Message-ID: <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> On Jan 27, 5:03 pm, Paddy > If static typing is optional then a program written in a dynamic > language that passes such an automated static analysis of source code > would have to be a simple program written in a simplistic way, and > also in a static style. Yes, but for safety-critical software you usually want the simplest possible solution. The last think you want is an unnecessarily "fancy" design. Unless there is a darn good reason to write a "non-static" program, you just don't do it. You might want to check into what the FAA allows in "flight-critical" code, for example. I am certainly not an expert in that area, but I've had a passing exposure to it. My understanding is that every possible branch of the code must be fully and meticulously analyzed and verified. Hence, the dynamic dispatching of ordinary object-oriented code is either prohibited or severely frowned upon. > Having used such formal tools on hardware designs that are expressed > using statically typed languages such as Verilog and VHDL, we don't > have the problem of throwing away run time typing, but we do get other > capacity problems with formal proofs that mean only parts of a design > can be formally prooved, or we can proof that an assertion holds only > as far as the engine has resources to expand the assertion. > We tend to find a lot of bugs in near complete designs by the random > generation of test cases and the automatic checking of results. In > effect, two (or more) programs are created by different people and > usually in different languages. One is written in say Verilog and can > be used to create a chip, another is written by the Verification group > in a 'higher level language' (in terms of chip testing), a tunable > randomized test generator then generates plausible test streams that > the Verification model validates. The test stream is applied to the > Verilog model and the Verilogs responses checked against the > Verification models output and any discrepancy flagged. Coverage > metrics (line coverage , statement coverage, expression coverage ...), > are gathered to indicate how well the design/program is being > exercised. > > I would rather advocate such random test generation methods as being > more appropriate for testing software in safety critical systems when > the programming language is dynamic. Random test generation methods can go a long way, and they certainly have their place, but I don't think they are a panacea. Coming up with a random set of cases that flush out every possible bug is usually very difficult if not impossible. That was the point of the quote in my original post. From jyoung79 at kc.rr.com Tue Jan 22 14:58:19 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Tue, 22 Jan 2008 13:58:19 -0600 Subject: question Message-ID: <6760762.631391201031899339.JavaMail.root@hrndva-web18-z01> I'm still learning Python and was wanting to get some thoughts on this. I apologize if this sounds ridiculous... I'm mainly asking it to gain some knowledge of what works better. The main question I have is if I had a lot of lists to choose from, what's the best way to write the code so I'm not wasting a lot of memory? I've attempted to list a few examples below to hopefully be a little clearer about my question. Lets say I was going to be pulling different data, depending on what the user entered. I was thinking I could create a function which contained various functions inside: def albumInfo(theBand): def Rush(): return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] def Enchant(): return ['A Blueprint of the World', 'Wounded', 'Time Lost'] ... The only problem with the code above though is that I don't know how to call it, especially since if the user is entering a string, how would I convert that string into a function name? For example, if the user entered 'Rush', how would I call the appropriate function --> albumInfo(Rush()) But if I could somehow make that code work, is it a good way to do it? I'm assuming if the user entered 'Rush' that only the list in the Rush() function would be stored, ignoring the other functions inside the albumInfo() function? I then thought maybe just using a simple if/else statement might work like so: def albumInfo(theBand): if theBand == 'Rush': return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] elif theBand == 'Enchant': return ['A Blueprint of the World', 'Wounded', 'Time Lost'] ... Does anyone think this would be more efficient? I'm not familiar with how 'classes' work yet (still reading through my 'Core Python' book) but was curious if using a 'class' would be better suited for something like this? Since the user could possibly choose from 100 or more choices, I'd like to come up with something that's efficient as well as easy to read in the code. If anyone has time I'd love to hear your thoughts. Thanks. Jay From eproust at gmail.com Mon Jan 21 05:05:11 2008 From: eproust at gmail.com (pythonewbie) Date: Mon, 21 Jan 2008 02:05:11 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <5vi1r8F1mjs0rU1@mid.uni-berlin.de> <5360e13d-215d-4d3e-9930-daa6cddd996a@f10g2000hsf.googlegroups.com> <5vj79dF1m2nmlU1@mid.uni-berlin.de> Message-ID: <2ba5fe9b-4a57-4147-bc18-22213b002297@d4g2000prg.googlegroups.com> On 21 jan, 10:34, "Diez B. Roggisch" wrote: > pythonewbie > > > > > Because the solution using distutils.sysconfig.get_python_lib() is > > very smart ! > > Depending on your goal. You said > > """ > My goal is to verify if an/several extension(s) are installed and to > automatically install the missing ones on Linux or Win32. > """ > > This goal can't be reached with only the site-packages - because I can > install packages somewhere else (matter of factly, this happens on debian > for example, they've split the install-dirs and created a bunch of dirs > under /usr/share) > > So having a method that gives you the installation root doesn't help much > here. > > Diez To John Machin, >>> sys.path ['', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/ python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/ python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/ usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/ Numeric', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/ python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0', '/usr/lib/python2.5/site- packages/wx-2.8-gtk2-unicode'] From python.list at tim.thechases.com Sun Jan 27 23:30:45 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 27 Jan 2008 22:30:45 -0600 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <479D5A75.5040704@tim.thechases.com> > This is neat. :) Could that maybe be extended to only assign selected > args to the instance and let others pass unchanged. So that, for instance: > > @autoassign("foo", "bar") > def __init__(self, foo, bar, baz): > super(baz) I've seen some folks import inspect/functools, but from my testing, the __init__ method in question has a .func_code object that already has the varnames in it. However, as you suggest, a version below allows for named defaults, and letting others go un-defaulted. I'm not sure about naming conventions for class-style decorators--start with a cap, like a class should ("AutoAssign") or because it behaves like a function, use "auto_assign", or any of a number of other variants. Anyways... class auto_assign(object): def __init__(self, *varnames): self.args = set(varnames) def __call__(self, fn): autoassign = self def wrapper(self, *args, **kwargs): for argname, argvalue in zip( fn.func_code.co_varnames[1:], args): if argname in autoassign.args: setattr(self, argname, argvalue) for argname in autoassign.args: if argname in kwargs: setattr(self, argname, kwargs[argname]) fn(self, *args, **kwargs) return wrapper class Foo(object): @auto_assign('foo', 'baz', 'fred') def __init__(self, foo, bar, baz, *args, **kwargs): pass f = Foo('hello', 42, 3.14, fred='wilma', barney='betty') try: print f.foo except AttributeError: print "Could not print f.foo" try: print f.bar except AttributeError: print "Could not print f.bar" try: print f.baz except AttributeError: print "Could not print f.baz" try: print f.fred except AttributeError: print "Could not print f.fred" try: print f.barney except AttributeError: print "Could not print f.barney" -tkc From Dom.Rout at gmail.com Tue Jan 8 14:51:21 2008 From: Dom.Rout at gmail.com (Dom Rout) Date: Tue, 8 Jan 2008 11:51:21 -0800 (PST) Subject: Peer To Peer File Sharing... Message-ID: <652595fc-071c-410e-b2fc-59c16495bc00@s8g2000prg.googlegroups.com> Hello. Well, this is my first post on any USENET group anywhere, so I hope I get it right. Basically, I just want to get some opinions on a plan of mine for a new project. I want to produce a small, peer to peer, file sharing network for the use of myself and some of my friends. The purpose of this is basically to allow us to share files conveniently without relying on technology such as Windows Live Messenger (Yuck). I have a VPS which I would like to dedicate to the task of acting as a tracker, so I can run a server application written in python on it. I will also write the first client in python, although I may go for a different language for the client in the final version, for performance. For now, Python is perfect because of the ease of use that it offers and the fact that I already know a bit about socket programming using it. Also concerning architecture, I will also have a number of peers that connect to the tracker and also to other peers, via an IP address provided by the server, as necessary to download the files. The files themselves should be split up into "Chunks" of fixed length, which will be given an index and tracked by the server. The server should know which clients have which chunks of a file, and when a client needs to download a file the server should look for other clients that have chunks from that file and give the IP address to the client, which should then for a connection to this peer and download the parts of the file that are available. When managing the chunks of a file, I will need to use a mutex to allow reading and writing of them. I should provide a getter and setter method in each file to allow chunks to be placed into it more conveniently. The getter and setter should both use mutex's to allow multiple threads of uploads and downloads at the same time. I will need to implement a username and password system, to restrict the users of the system to people that I trust. To uniquely identify a file, I would like to use a file path. There should be a theoretical directory that contains all shared files, although the client should be given the option of which files from the directory to download. This directory should look like: "Global/" "Global/Images/" "Global/Music/" "Users//" It would be nice if it was possible to subscribe to certain directories, and download new files from them as need be. Well, these are my ideas so far. Is anything drastically obviously wrong, and can anyone suggest to me any best practices when implementing this sort of design? Thanks, Dominic Rout. From lists at cheimes.de Sun Jan 20 06:20:32 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 20 Jan 2008 12:20:32 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt In-Reply-To: References: Message-ID: pythonewbie wrote: > I am stucked on creating a function to get the Python install > directory (and site-packages directory) with a 100% reliable method... Only one method is 100% reliable: try: import yourextension except ImportError: available = False else: available = True Christian From sjmachin at lexicon.net Tue Jan 8 06:31:05 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 8 Jan 2008 03:31:05 -0800 (PST) Subject: Open a List of Files References: Message-ID: <5c89f461-1c29-404c-bfe3-4572311c717f@d70g2000hsb.googlegroups.com> On Jan 8, 10:03 pm, Fredrik Lundh wrote: > BJ Swope wrote: > > given a list such as > > > ['messages', 'recipients', 'viruses'] > > > how would I iterate over the list and use the values as variables and > > open the variable names a files? > > > I tried > > > for outfile in ['messages', 'recipients', 'viruses']: > > filename = os.path.join(Host_Path, outfile) > > outfile = open(filename, 'w') > > > But it's not working. > > the code looks ok. please define "not working". > To me, it looks bad. He's rebinding "outfile" inside the loop, which is not good style, makes the reader slow down, back up, read the code again ... however this doesn't stop this small code fragment from opening the 3 files for write access -- assuming an import, and suitable contents for "Host_Path". From Scott.Daniels at Acm.Org Thu Jan 10 00:28:15 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 09 Jan 2008 21:28:15 -0800 Subject: Structure of packages In-Reply-To: References: Message-ID: <13obaunlh9pl94@corp.supernews.com> Ben Fisher wrote: > I am trying to learn the best way to do intra-package references. My > package looks like this: ... > I had thought that "from PackageName.b import *" would work.... In an attempt to hand oyu a net, rather than an answer: Try using command line: python -v whatever.py You can see all the imports that are done and in what order. Also realize that import a file executes it, so you can sprinkle prints at points where you are confused. --Scott David Daniels Scott.Daniels at Acm.Org From mimvev at gmail.com Tue Jan 1 03:52:51 2008 From: mimvev at gmail.com (mimvev at gmail.com) Date: Tue, 1 Jan 2008 08:52:51 +0000 (UTC) Subject: M-I,5`Persecu tion ` buggi ng an d counter-surveillan ce Message-ID: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -= MI5: bugging. and counter-surveillance -= -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- PO: >Did. you ever look for the bugs in your house ? If not, why not ? I mean if PO: >I thought that was happening. to me, I'd search the place from top to bottom, PO: >I mean. I live there I would know if anything was out of place. If I was PO: >really suspicious, I would call in one of those bug detection. teams which PO: >have those machines that pick up the transmitted radio. waves. This PO:. >reminds me of BUGS, that new programme on BBC1 on That's exactly what we did. We went to. a competent, professional detective agency in London, paid them over 400 quid to debug our house.. They used scanner devices which go to over 1. GHz and would pick up any nearby transmitter in that range, they also checked. the phones and found nothing... but if the tap was at the exchange, then. they wouldn't find anything,. would they? CS: >Doesn't this suggest. to you that there are, in fact, no bugs to be found? You can assume that they've done this sort of. thing to other people in more "serious" cases, where they would know the targets. would suspect the presence of electronic. surveillance. So they will have developed techniques and devices which are not readily detectable either by. visual inspection or by. electronic means. What those techniques might be, I couldn't guess. In this case,. the existence of bugging devices was clear from the beginning, and they "rubbed it in" with what was said by. the boy on the coach. It was almost. as if they wanted counter-surveillance people to be called in, who they knew. would fail to detect the bugging devices, causing loss of credibility to the other things I would have. to say relating to the harassment. I did all the things someone in my situation would do to try. to find the bugs. In addition to calling in professional help using. electronic counter-surveillance, I made a close. visual inspection of electrical equipment, plus any points where audio or video. surveillance devices might have been concealed. Of course, I found nothing.. Normal surveillance "mini-cameras" are quite noticeable. and require visible supporting circuitry. It seems to me the best place to. put a small video surveillance device. would be additional to a piece of electronic equipment such as a TV or video. It would be necessary to physically break in to a property. to fit such a. device. 2773 From gowricp at gmail.com Fri Jan 11 19:13:07 2008 From: gowricp at gmail.com (Gowri) Date: Fri, 11 Jan 2008 16:13:07 -0800 (PST) Subject: converting JSON to string Message-ID: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> Hello, I actually have two questions: 1. Are there any libraries which convert XML to JSON? 2. I am currently doing the above using the DOM parser and creating a JSON array for node in doc.getElementsByTagName("book"): isbn = node.getAttribute("isbn") titleNode = (node.getElementsByTagName("title") [0]).childNodes[0] title = titleNode.data primarykeys.append({'isbn': isbn, 'title': title}) return primarykeys I want to send primarykeys as a response to my client. i use mod_python and apache. The problem is, I have not been able to figure out how to convert my JSON output to a string. Could someone please help me? Thanks in advance From jzgoda at o2.usun.pl Tue Jan 15 05:42:38 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 15 Jan 2008 11:42:38 +0100 Subject: MySQL-python-1.2.2 install with no mysql In-Reply-To: References: Message-ID: washakie napisa?(a): > I need to install the MySQL-python-1.2.2 connector in order to access a db > on another machine. In the install it asks for the location of the > mysql_config file, and if I leave it as the default I get: > > [root at lars MySQL-python-1.2.2]# python setup.py build > sh: mysql_config: command not found > Traceback (most recent call last): > File "setup.py", line 16, in ? > metadata, options = get_config() > File "/opt/MySQL-python-1.2.2/setup_posix.py", line 43, in get_config > libs = mysql_config("libs_r") > File "/opt/MySQL-python-1.2.2/setup_posix.py", line 24, in mysql_config > raise EnvironmentError, "%s not found" % mysql_config.path > EnvironmentError: mysql_config not found > [root at lars MySQL-python-1.2.2]# > > How can I install MySQL-python-1.2.2 without installing MySQL??? In short: without installing client libraries you cann't. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 29 12:05:59 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 29 Jan 2008 18:05:59 +0100 Subject: Python noob SOS (any [former?] Perlheads out there?) In-Reply-To: References: Message-ID: <479f5cf0$0$19801$426a74cc@news.free.fr> kj a ?crit : > For many months now I've been trying to learn Python, but I guess > I'm too old a dog trying to learn new tricks... For better or > worse, I'm so used to Perl when it comes to scripting, that I'm > just having a very hard time getting a hang of "The Python Way." > (snip) > > I'd written a Perl module to facilitate the writing of scripts. > It contained all my boilerplate code for parsing and validating > command-line options, generating of accessor functions for these > options, printing of the help message and of the full documentation, > testing, etc. > > Of course, for Python now I don't have any of this, so I must write > it all from scratch, Hem... What about the optparse module ? (nb: it's in the standard lib). From aisaac at american.edu Fri Jan 25 17:28:51 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 25 Jan 2008 22:28:51 GMT Subject: find minimum associated values In-Reply-To: <7xd4rpznl0.fsf@ruckus.brouhaha.com> References: <7xd4rpznl0.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > How about something like: > > kv_sorted = sorted(kv, key=lambda x: (id(x[0]), x[1])) You mean like this? #sort by id and then value kv_sorted = sorted(kv, key=lambda x: (id(x[0]),x[1])) #groupby: first element in each group is object and its min value d =dict( g.next() for k,g in groupby( kv_sorted, key=lambda x: x[0] ) ) Yes, that appears to be fastest and is pretty easy to read. Thanks, Alan From bignose+hates-spam at benfinney.id.au Sat Jan 26 18:47:52 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 27 Jan 2008 10:47:52 +1100 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> <87k5lx5v19.fsf@benfinney.id.au> <22c3fd21-2fe3-4893-89f4-b23e1703d083@y5g2000hsf.googlegroups.com> Message-ID: <877ihw5etz.fsf@benfinney.id.au> Carl Banks writes: > On Jan 25, 6:45 pm, Ben Finney > wrote: > > "Gabriel Genellina" writes: > > > You can also put, in animal/__init__.py: > > > from monkey import Monkey > > > and now you can refer to it as org.lib.animal.Monkey, but keep the > > > implementation of Monkey class and all related stuff into > > > .../animal/monkey.py > > > > This (as far as I can understand) is exactly the solution the > > original poster desired to "shoot down", for reasons I still don't > > understand. > > The solution is to modify the class's __module__ attribute as well as > importing it, as I've already pointed out: > > from org.lib.animal.monkey import Monkey > Monkey.__module__ = 'org.lib.animal' Thanks, that makes it clear. > This should be enough to satisfy the OP's requirements, at least for > classes, without softening the one-to-one module-to-file > relationship, or using "hacks". > > In fact, I'd say this is good practice. I've not seen that before, but it seems an elegant way to address what the OP is asking for. -- \ "Madness is rare in individuals, but in groups, parties, | `\ nations and ages it is the rule." -- Friedrich Nietzsche | _o__) | Ben Finney From python at rcn.com Thu Jan 17 03:49:54 2008 From: python at rcn.com (Raymond Hettinger) Date: Thu, 17 Jan 2008 00:49:54 -0800 (PST) Subject: Replace stop words (remove words from a string) References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> Message-ID: On Jan 17, 12:25?am, BerlinBrown wrote: > if I have an array of "stop" words, and I want to replace those values > with something else; > mystr = > kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsld?fsd; > if I have an array stop_list = [ "[BAD]", "[BAD2]" ] > I want to replace the values in that list with a zero length string. Regular expressions should do the trick. Try this: >>> mystr = 'kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsld?fsd;' >>> stoplist = ["[BAD]", "[BAD2]"] >>> import re >>> stoppattern = '|'.join(map(re.escape, stoplist)) >>> re.sub(stoppattern, '', mystr) 'kljsldkfjksjdfjsdjflkdjslkfKkjkkkkjkkjkLSKJFKSFJKSJF;Lkjsld\xadfsd;' Raymond From rrasss at gmail.com Tue Jan 1 22:55:45 2008 From: rrasss at gmail.com (Rick) Date: Tue, 1 Jan 2008 21:55:45 -0600 Subject: Simple server using asyncore/asynchat Message-ID: <414fb3c30801011955t2ea6be7ch72f6f7a7652dea12@mail.gmail.com> Hey folks. I'm trying to create a (fairly) simple server that listens for connections and when it receives one sends a message to the client and then waits for a response (and would continue to do that). My problem is, every time my client connects, the server doesn't send the text and then immediately closes the connection with the client, but DOES print that the client was connected. Anyone know why? Here's my code: # conn.py import socket import asyncore import asynchat import string host = 'localhost' #socket.gethostname () port = 8017 buf = 1024 class ConnChannel (asynchat.async_chat): def __init__(self, conn): self.conn = conn def handle_connect(): self.send(self.conn, "Hello, Welcome to BasicMUD.\r\n") # it doesn't do thise self.numberclients = self.numberclients + 1 # or this self.send(self.conn, "There are " + self.numberclients + " players online.") # or this print "Client connected!" # it prints this def handle_read(self): print self.recv(8192) def handle_write(self): print "sending" class ConnTube (asyncore.dispatcher): def __init__(self, hostd, portd): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM ) self.bind ( ( hostd , portd ) ) self.listen ( 5 ) self.numberclients = 0 def handle_accept(self): channel, addr = self.accept() ConnChannel(channel) connTube = ConnTube(host, port) asyncore.loop() Thanks everyone! Rick -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Tue Jan 1 06:28:29 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 01 Jan 2008 12:28:29 +0100 Subject: pdf library. References: <133097f4-de83-4e13-93f1-1404213333a4@l6g2000prm.googlegroups.com> Message-ID: >>>>> Shriphani (S) wrote: >S> I tried pyPdf for this and decided to get the pagelinks. The trouble >S> is that I don't know how to determine whether a particular page is the >S> first page of a chapter. Can someone tell me how to do this ? AFAIK PDF doesn't have the concept of "Chapter". If the document has an outline, you could try to use the first level of that hierarchy as the chapter starting points. But you don't have a guarantee that they really are chapters. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From kyosohma at gmail.com Wed Jan 23 10:49:14 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 23 Jan 2008 07:49:14 -0800 (PST) Subject: Processing XML that's embedded in HTML References: <6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> <47972624.2050002@web.de> Message-ID: <58d2add2-147e-435e-9214-278689321feb@z17g2000hsg.googlegroups.com> John and Stefan, On Jan 23, 5:33 am, Stefan Behnel wrote: > Hi, > > Mike Driscoll wrote: > > I got lxml to create a tree by doing the following: > > > from lxml import etree > > from StringIO import StringIO > > > parser = etree.HTMLParser() > > tree = etree.parse(filename, parser) > > xml_string = etree.tostring(tree) > > context = etree.iterparse(StringIO(xml_string)) > > No idea why you need the two steps here. lxml 2.0 supports parsing HTML in > iterparse() directly when you pass the boolean "html" keyword. I don't know why I have 2 steps either, now that I look at it. However, I don't do enough XML parsing to get real familiar with the ins and outs of Python parsing either, so it's mainly just my inexperience. And I also got lost in the lxml tutorials... > > > However, when I iterate over the contents of "context", I can't figure > > out how to nab the row's contents: > > > for action, elem in context: > > if action == 'end' and elem.tag == 'relationship': > > # do something...but what!? > > # this if statement probably isn't even right > > I would really encourage you to use the normal parser here instead of iterparse(). > > from lxml import etree > parser = etree.HTMLParser() > > # parse the HTML/XML melange > tree = etree.parse(filename, parser) > > # if you want, you can construct a pure XML document > row_root = etree.Element("newroot") > for row in tree.iterfind("//Row"): > row_root.append(row) > > In your specific case, I'd encourage using lxml.objectify: > > http://codespeak.net/lxml/dev/objectify.html > > It will allow you to do this (untested): > > from lxml import etree, objectify > parser = etree.HTMLParser() > lookup = objectify.ObjectifyElementClassLookup() > parser.setElementClassLookup(lookup) > > tree = etree.parse(filename, parser) > > for row in tree.iterfind("//Row"): > print row.relationship, row.StartDate, row.Priority * 2.7 > > Stefan I'll give your ideas a go and also see if what the others posted will be cleaner or faster. Thank you all. Mike From george.sakkis at gmail.com Mon Jan 21 00:41:39 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 20 Jan 2008 21:41:39 -0800 (PST) Subject: object scope References: <13p8803q11tm32d@corp.supernews.com> Message-ID: On Jan 21, 12:16 am, "J. Peng" wrote: > Dennis Lee Bieber ??: > > > The scope of "name" is the entire function; lacking a "global name" > > statement, AND being on the left side of an assignment, it is a function > > local name. > > Thank you. Does python have so-called 'block scope' object? No, it doesn't; in most cases that you may care, a name's scope is either local or global*. > or if you can,please show me the doc for python's object scope. http://www.network-theory.co.uk/docs/pytut/PythonScopesandNameSpaces.html George * There is also class scope and lexical closures but most likely you don't have to worry about them for now. From serilanimi at gmail.com Fri Jan 11 15:01:16 2008 From: serilanimi at gmail.com (serilanimi at gmail.com) Date: Fri, 11 Jan 2008 12:01:16 -0800 (PST) Subject: opensg or openscenegraph References: <40zfj.33787$lD6.31634@newssvr27.news.prodigy.net> Message-ID: <88ef87d8-d63b-4a7e-96db-07bc2a7a1fc9@s19g2000prg.googlegroups.com> On Jan 4, 3:08?pm, yomgui wrote: > Hi, > > I need to use a scengraph for my python/opengl application > but I have trouble finding out which one I should use. > > opensg or openscenegraph (OSG) ? > > I suppose the quality of the python bindings will make the decision. > > any advice ? > > thanks > > yomgui Hi yomgui, I am considering either of these as well for writing a simulation game. The Python Bindings I have found to date are: For OpenSG: https://realityforge.vrsource.org/trac/pyopensg For OSG (there seems to be several variations of these): http://code.astraw.com/projects/pyosg I suppose you could also use something like Py++ to create your own. I too, am having a hard time deciding. I was leaning towards OpenSceneGraph because it seems to be better supported. If you make a decision, please let me know which one you decided on and your reasons. Regards, serilanimi From http Thu Jan 31 17:15:58 2008 From: http (Paul Rubin) Date: 31 Jan 2008 14:15:58 -0800 Subject: Naive idiom questions References: Message-ID: <7x4pctmyjl.fsf@ruckus.brouhaha.com> Terran Melconian writes: > I want to be able to accumulate a string with +=, not by going > through an intermediate list and then doing ''.join(), because I > think the latter is ugly. There are also times when I'd like to use > the string as a modifiable buffer. See the StringIO, cStringIO, and array modules. > l=[[None]*5 for i in range(5)] This is the usual way. > * Is there a way to get headings in docstrings? I think this is normally not done. From kyosohma at gmail.com Tue Jan 22 16:41:35 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 22 Jan 2008 13:41:35 -0800 (PST) Subject: get the size of a dynamically changing file fast ? References: <198fd91f-912b-4f56-a840-af96225125a7@c23g2000hsa.googlegroups.com> Message-ID: <197576d1-ab36-45f2-9648-3cfab6d3a814@j20g2000hsi.googlegroups.com> On Jan 22, 3:35 pm, Stef Mientki wrote: > Mike Driscoll wrote: > > On Jan 17, 3:56 pm, Stef Mientki wrote: > > >> hello, > > >> I've a program (not written in Python) that generates a few thousands > >> bytes per second, > >> these files are dumped in 2 buffers (files), at in interval time of 50 msec, > >> the files can be read by another program, to do further processing. > > >> A program written in VB or delphi can handle the data in the 2 buffers > >> perfectly. > >> Sometimes Python is also able to process the data correctly, > >> but often it can't :-( > > >> I keep one of the files open en test the size of the open datafile each > >> 50 msec. > >> I have tried > >> os.stat ( ....) [ ST_SIZE] > >> os.path.getsize ( ... ) > >> but they both have the same behaviour, sometimes it works, and the data > >> is collected each 50 .. 100 msec, > >> sometimes 1 .. 1.5 seconds is needed to detect a change in filesize. > > >> I'm using python 2.4 on winXP. > > >> Is there a solution for this problem ? > > >> thanks, > >> Stef Mientki > > > Tim Golden has a method to watch for changes in a directory on his > > website: > > >http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_fo... > > > This old post also mentions something similar: > > >http://mail.python.org/pipermail/python-list/2007-October/463065.html > > > And here's a cookbook recipe that claims to do it as well using > > decorators: > > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/426620 > > > Hopefully that will get you going. > > > Mike > > thanks Mike, > sorry for the late reaction. > I've it working perfect now. > After all, os.stat works perfectly well, > the problem was in the program that generated the file with increasing > size, > by truncating it after each block write, it apperently garantees that > the file is flushed to disk and all problems are solved. > > cheers, > Stef Mientki I almost asked if you were making sure you had flushed the data to the file...oh well. Mike From lasses_weil at klapptsowieso.net Tue Jan 29 18:38:47 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Wed, 30 Jan 2008 00:38:47 +0100 Subject: optional static typing for Python In-Reply-To: <70c4064a-a65d-4fd5-b39c-38e6a3fb567b@i7g2000prf.googlegroups.com> References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> <479e0225$0$36389$742ec2ed@news.sonic.net> <70c4064a-a65d-4fd5-b39c-38e6a3fb567b@i7g2000prf.googlegroups.com> Message-ID: <479fb907$0$25376$9b4e6d93@newsspool4.arcor-online.net> > Python has a JIT right no > You mean in the Java-sense (outputting native machine code)? /W From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Jan 5 05:53:07 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 05 Jan 2008 11:53:07 +0100 Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> Message-ID: <5u95sjF1etf0nU1@mid.individual.net> MartinRinehart at gmail.com wrote: > Jeroen Ruigrok van der Werven wrote: >> self.startLoc = start >> self.stopLoc = stop > > Thanks! Of course it should. Old Java habits die slowly. That's not really a Java habit. In Java and C++, personally I like to write this.startLoc = start this.stopLoc = stop It makes much clearer what a field and what a "normal" variable is in those languages. Regards, Bj?rn -- BOFH excuse #294: PCMCIA slave driver From NikitaTheSpider at gmail.com Fri Jan 11 11:23:47 2008 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Fri, 11 Jan 2008 11:23:47 -0500 Subject: Detecting OS platform in Python References: Message-ID: In article , Mike Meyer wrote: > On Thu, 10 Jan 2008 18:37:59 -0800 (PST) Devraj wrote: > > > Hi everyone, > > > > My Python program needs reliably detect which Operating System its > > being run on, infact it even needs to know which distribution of say > > Linux its running on. The reason being its a GTK application that > > needs to adapt itself to be a Hildon application if run on devices > > like the N800. > > I don't think it can be done. [...] > ...trying to figure out what features you have > available by guessing based on the platform type is generally the > wrong way to approach this kind of problem - only in part because you > wind up reduced to a series of heuristics to figure out the > platform. And once you've done that, you could wind up being wrong. > > Generally, you're better of probing the platform to find out if it has > the facilities you're looking for. For python, that generally means > trying to import the modules you need, and catching failures; or > possibly looking for attributes on modules if they adopt to the > environment around them. Much agreed. I just went through this with my SHM module. Compilation was failing because of a variation in ipc_perm in ipc.h on various platforms. I didn't feel confident at all that I could compile a list of all of the variations let alone keep it accurate and updated. The clincher was when I found that OS X >= 10.4 has two flavors of ipc_perm and which gets used depends on a compile flag, so identifying the OS would not have been useful in that case. OP, I don't know what a Hildon or N800 is, but is it possible that the same OS fingerprint could show up on different devices? If so then you're really out of luck. I think you'll be much better off if you focus less on the OS and more on the features it offers. Good luck -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From paddy3118 at googlemail.com Sun Jan 20 23:16:18 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 20 Jan 2008 20:16:18 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: On Jan 21, 3:15 am, Albert Hopkins wrote: > This issue may have been referred to in > but I didn't > entirely understand the explanation. Basically I have this: > > >>> a = float(6) > >>> b = float('nan') > >>> min(a, b) > 6.0 > >>> min(b, a) > nan > >>> max(a, b) > 6.0 > >>> max(b, a) > nan > > Before I did not know what to expect, but I certainly didn't expect > this. So my question is what is the min/max of a number and NaN or is it > not defined (for which I would have expected either an exception to be > raised or NaN returned in each case). > > As a corrollary would I be able to rely on the above behavior or is it > subject to change (to fix a bug in min/max perhaps :-)? I am definitely NOT a floating point expert, but I did find this: http://en.wikipedia.org/wiki/IEEE_754r#min_and_max P.S. What platform /Compiler are you using for Python? - Paddy. From cwitts at gmail.com Fri Jan 18 01:13:18 2008 From: cwitts at gmail.com (Chris) Date: Thu, 17 Jan 2008 22:13:18 -0800 (PST) Subject: too long float References: Message-ID: <4fe99e03-4ffd-4b1a-b9cc-5df8a11feed4@i29g2000prf.googlegroups.com> On Jan 18, 7:55 am, "J. Peng" wrote: > hello, > > why this happened on my python? > > >>> a=3.9 > >>> a > > 3.8999999999999999 > > I wanted 3.9 but got 3.89................ > How to avoid it? thanks. > > this is my python version: > > >>> sys.version > > '2.3.4 (#1, Feb 6 2006, 10:38:46) \n[GCC 3.4.5 20051201 (Red Hat 3.4.5-2)]' >>> 3.9 3.8999999999999999 >>> 3.9 == 3.8999999999999999 True http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm From Lie.1296 at gmail.com Sat Jan 5 05:27:03 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 5 Jan 2008 02:27:03 -0800 (PST) Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <13nn9k48n7ohr95@corp.supernews.com> <69337707-ff18-4b39-af0a-78cf0a14b667@1g2000hsl.googlegroups.com> Message-ID: > I mean, really, I've been using web-mail and various varieties of > remote > storage for over a decade. ?What is *new* about the concept? ?(I see > some > hints above, but it's mixed in with a lot of other stuff...) In essence, you're correct, this concept of cloud computing actually have existed for some time, but there is a difference between the "classic" cloud computing and "new" cloud computing. The classic cloud computing is rather limited emails, bbs, newsgroup, etc while the new cloud computing also refers to the newly available scope such as word processing, image processing, and even video editing. In essence they're the same, you store your files on their server, and you used a webbased tools to access your file, but nowadays people wouldn't consider the classic cloud computing a cloud computing anymore, as they've become too "normal". It's not a completely meaningless marketing buzz phrase, the concept has existed for some time, but the word is new. Another way to look at this is: "classic" cloud computing are cloud computing that is done because it can't be done the other way (what use is an email address if you could only receive emails if your desktop is always on, what use is a newsgroup if people could only post if they are physically in front of the computer hosting the newsgroup). While the "new" cloud computing refers to applications that previously exist as desktop applications, but now ported to become web-based applications, meaning the application could be usable without the "cloud", but some features like universal availability could not be used. From fredrik at pythonware.com Thu Jan 10 16:13:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 22:13:27 +0100 Subject: Python too slow? In-Reply-To: <13od12b23hfv772@corp.supernews.com> References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <13od12b23hfv772@corp.supernews.com> Message-ID: Ed Jensen wrote: > The only question that remains is if you were being accidentally > misleading or purposefully misleading. oh, please. it was perfectly clear for anyone with the slightest clue what Bruno was talking about (especially if they'd read the post he was replying to), so the only question that remains is why you didn't understand it. From r.grimm at science-computing.de Mon Jan 7 02:33:15 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Sun, 6 Jan 2008 23:33:15 -0800 (PST) Subject: python interfaces References: <96b70141-f872-413a-a433-08b217cecb27@e4g2000hsg.googlegroups.com> Message-ID: On Jan 6, 11:01 am, Fredrik Lundh wrote: > r.gr... at science-computing.de wrote: > > Interfaces are a extremly smart Design Principle in static typed > > languages like Java and C++. > > that's somewhat questionable in itself, and even more questionable as an > argument for interfaces in Python. > > I'd recommend anyone who thinks that they cannot program without formal > interfaces to try using Python as Python for a while, before they try > using it as something else. you might be surprised over how easy it is > to build robust stuff without having to add lots of extra constraints to > your code. > > Hallo, I argued, that Interface and multiple inheritance are different things and especially, that Interfaces are very useful in staticially typed languages. In such languages like Java and C++ you need a formalismen to guide the user. You may call it extension point, pure virtual function or abstract methode. Sorry for the misunderstanding, I argued for Interface in heavyweight static typed languages and nor for lightweight dynamic typed languages like python. They aren't pointless and a hack. Greetings Rainer From mail at timgolden.me.uk Thu Jan 24 06:20:31 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jan 2008 11:20:31 +0000 Subject: wxpython In-Reply-To: <0d5fbbaf-aff3-46eb-a8ff-ef0247262fcc@i29g2000prf.googlegroups.com> References: <77cc3d61-5dd0-4878-b436-b6d07e40de4d@i7g2000prf.googlegroups.com> <0d5fbbaf-aff3-46eb-a8ff-ef0247262fcc@i29g2000prf.googlegroups.com> Message-ID: <4798747F.9090005@timgolden.me.uk> [Tim Golden] >> wxPython is trying to interpret your byte stream as a Unicode >> text stream encoded as cp1252. But it's not, so it gives up >> in a heap. One solution is to pass the repr of file_content. >> Another solution is for you to prefilter the text, replacing >> non-printables by their hex value or by some marker. Not much >> in it, really. >> >> >> import random >> file_content = "".join ( >> chr (random.randint (0, 255)) for i in range (1000) >> ) >> munged_text = "".join ( >> c if 32 <= ord (c) <= 126 else hex (ord (c)) for c in file_content >> ) >> >> print repr (file_content) >> print munged_text >> >> >> TJG [joe jacob] > If I open an exe file in notepad, I can see some junk characters. I'm > trying to develop a program like an editor which can encrypt a file > opened by it. I need to open files like exe or jpeg etc in the editor > and after encryption the encrypted data should be displayed in the > editor. I developed the editor but when I tried to open an windows exe > file in it I am getting the above mentioned error as the characters > contained in it are non unicode. Hi, Joe. I've copied this back to the list (and I encourage you to do the same when replying) since the more people see the issue, the more chances you've got of a useful answer! To try to address what you're saying here: notepad.exe makes some choice or other when confronted by the byte stream in a file which you open. I don't know what that choice is, or how it tries to cope with encoded unicode text, but whatever it does by the choice of its developers. The "some junk characters" are one of several possible representations of the not-ordinary-characters which your file contains. If you're writing your own editor or file display, you have to make similar choices, which includes understanding what possibilities are offered by the toolset you're employing -- in this case, wxPython. The wxPython wx.TextCtrl expects to be fed with Unicode text. If you pass it a string instead, it tries to decode it according to the system's default encoding, here cp1252. If it can't, it doesn't display "junk characters": it just gives an error. If you want junk characters, then you'll either have to explicitly pass in the characters you want displayed or do the kind of thing I suggested above to indicate their hex value, or find another control (or an option of the wx.TextCtrl) which will attempt to do the work for you when displaying raw bytes. I'm afraid I'm not a wxPython expert so maybe someone else has suggestions. But the most important thing is that you understand what's happening here and why you can't just say "I want it to do what Notepad does". TJG From pavlovevidence at gmail.com Thu Jan 31 20:51:49 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 31 Jan 2008 17:51:49 -0800 (PST) Subject: Naive idiom questions References: Message-ID: On Jan 31, 4:30 pm, Terran Melconian wrote: > * Why are there no real mutable strings available? > > I found MutableString in UserString, but further research indicates > that it is horribly inefficient and actually just wraps immutable > strings for the implementation. > > I want to be able to accumulate a string with +=, not by going > through an intermediate list and then doing ''.join(), because I > think the latter is ugly. If it's just the weird spelling, you can always write str.join("",acc) > There are also times when I'd like to use > the string as a modifiable buffer. array module has already been mentioned. You can also use an mmap (pass it a file handle of -1 I believe to get an anonymous buffer), or even a numpy array of type character if you're feeling frisky. Python 3.0 is scheduled to have a mutable buffer type. (BTW, originally there was going to be a mutable bytes type, but this proved to cause many inconveniences so bytes is now an immutable, and buffer is a now a lessened version of what bytes would have been.) > Is the python idiom that this is actually the Right Thing for > reasons I'm not seeing? Is there a fundamental reason it would be > hard to implement a mutable string in cpython? It might seem a little weird for someone coming from Perl, but Python isn't the sort of language that implements every possible feature that isn't "fundamentally hard". Python carefully considers the benefits and drawbacks of adding something, and if there is too much drawback it won't be added, no matter how obvious or basic it seems. In practice, very few string operations really need the benefit of mutability. (How large are most strings, really?) OTOH, the drawbacks of mutability are severe: once you allow string buffer data to change, then the language has to take defensive steps in case string values are mutated. Strings could no longer be keys for dicts, for instance, which would be unfortunate since that's how Python looks up global variables and attributes. Python wisely made the built-in string type immutable--saving all kinds of grief for the most typical usages--while providing modules such as cStringIO, array, and mmap to handle the special cases where you really need a mutable type. > * What's the best way to initialize a list of lists? > > I keep wanting to do this: > > l=[[None]*5]*5 > > as do many other Python novices, but of course it quickly becomes > apparent why this is a bad idea as soon as one modifies a value. > The best I've found is: > > l=[[None]*5 for i in range(5)] > > I don't particularly like it, though. It bothers me to have to > explain list comprehensions, which are a moderately advanced feature > conceptually, just to initialize an array. We could get around this > if we had a defaultlist, but we don't. Is there a more elegant > solution here? No. Since 2D arrays aren't commonplace, since listcomps work passably here, and since there's a popular thrid-party library (numpy) that handles multidimensional arrays, it's unlikely that Python would add any means to do this more elegantly. You can put it in a function and forget about how it's implemented if you don't like the listcomps. def create_empty_2d_list(rows,cols): return [[None]*cols for i in xrange(rows)] > * Is there a way to get headings in docstrings? > > I want to create my own sections, like "OVERVIEW", "EXAMPLES", > "AUTHORS", "BUGS", etc. I can't figure out any way to do this. In > perldoc, I can easily use =head1, but I can't figure out the Python > equivalent. At first I thought I could use (re)structuredtext, but > then it became apparent that pydoc(1) does not parse any of this > markup. Am I missing something, or is it just not possible to > achieve this effect other than by writing separate, independent > manpages? Not a big expert on docstrings (they seem so superfluous...) but perhaps there are third-party packages that let you specify meta- documentation with function decorators. For example: @overview("Blah blah blah") @authors("So and so") def some_function(): pass Try looking on PyPI (cheeseshop.python.org). Python's in-code documentation is pretty basic; I think Python is happy to outsource more elaborate schemes to third party packages. Carl Banks From kyosohma at gmail.com Thu Jan 3 14:07:11 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 3 Jan 2008 11:07:11 -0800 (PST) Subject: PyOpenGL, wxPython weird behaviour References: <71ae5a6b-31e9-41e9-a39e-919138dc4a03@l6g2000prm.googlegroups.com> Message-ID: On Jan 3, 11:50 am, Adeola Bannis wrote: > Hi everyone, > > I'm doing a project using wxPython and pyopengl, and I seem to have a > problem rendering textures. This is code that worked before my hard > drive had a meltdown, but not since I re-installed everything. > > I've determined the problem is in the OpenGL part of my program. I do > some calculations to generate a 2D numpy array that holds the image > data, and pylab.imshow() shows me the image as it is meant to be. I > used the same algorithm in Octave and MATLAB, and all are giving me > the right picture. > > However, using pyOpenGL and the numpyhandler functions (http://cours- > info.iut-bm.univ-fcomte.fr/docs/python/OpenGL/ > OpenGL.arrays.numpymodule.NumpyHandler-class.html) doesn't seem to > work. I get a garbled screen pocked with black pixels. I am including > my openGL code below. What am I doing wrong? > > And yes, I did make the dtype of my array 'float32'. > > -------code snippets------ > > import wx > from wx.glcanvas import GLCanvas > > from OpenGL.GLU import * > from OpenGL.GL import * > from OpenGL.arrays.numpymodule import NumpyHandler > > PC = 1 > RI = 0 > > class myGLCanvas(GLCanvas): > def __init__(self, parent): > GLCanvas.__init__(self, parent,-1) > wx.EVT_PAINT(self, self.OnPaint) > self.init = 0 > self.mode = -1 > # making a texture for the range image > self.texture = glGenTextures(1) > # making a spot for the point cloud points > self.cloud = None > return > > def OnPaint(self,event): > dc = wx.PaintDC(self) > self.SetCurrent() > if not self.init: > self.InitGL() > self.init = 1 > self.OnDraw() > return > > def OnDraw(self): > glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) > if self.mode == RI: > self.drawRange() > elif self.mode == PC: > self.drawCloud() > > def InitGL(self): > glClearColor(0.0, 0.0, 0.0, 0.0); > glClearDepth(1.0) > glEnable(GL_DEPTH_TEST) > glDepthFunc(GL_LEQUAL) > glClear(GL_COLOR_BUFFER_BIT) > > glPixelStorei(GL_UNPACK_ALIGNMENT, 1) > glPixelStorei(GL_PACK_ALIGNMENT, 1) > > #NTSC colour scales... > glPixelTransferf(GL_RED_SCALE, 0.299); > glPixelTransferf(GL_GREEN_SCALE, 0.587); > glPixelTransferf(GL_BLUE_SCALE, 0.114); > > glMatrixMode(GL_PROJECTION) > glLoadIdentity() > glOrtho(0.0,1.0,0,1.0,-1.0,1.0) > glMatrixMode(GL_MODELVIEW) > glLoadIdentity() > > return > > def rangeImage(self, image): > > glBindTexture(GL_TEXTURE_2D, self.texture) > glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) > > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, > GL_LINEAR) > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) > > # flatten it into a list so the OpenGL calls work > n = NumpyHandler() > fI = image.flatten() > flatImage = n.dataPointer(n.contiguous(fI)) > > print n.contiguous(fI) > > gluBuild2DMipmaps(GL_TEXTURE_2D, 1, image.shape[0]+1, > image.shape[1]+1, > GL_LUMINANCE, GL_FLOAT, flatImage) > self.mode = RI > self.OnDraw() > > def drawRange(self): > ''' Controls the actual drawing of the range image''' > > glMatrixMode(GL_MODELVIEW) > glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) > > glColor3f(1.0,1.0,1.0) > glEnable(GL_TEXTURE_2D) > glBindTexture(GL_TEXTURE_2D, self.texture) > glBegin(GL_TRIANGLE_FAN) > glTexCoord2d(1,1); glVertex3f(0.0, 0.0, 0.0) > glTexCoord2d(1,0); glVertex3f(0.0, 1.0, 0.0) > glTexCoord2d(0,0); glVertex3f(1.0, 1.0, 0.0) > glTexCoord2d(0,1); glVertex3f(1.0, 0.0, 0.0) > glEnd() > self.SwapBuffers() > > --------end snippet----------- I've never messed with pyOpenGL, but it seems that they have their own user's group, which would probably be better at answering your question: http://sourceforge.net/mail/?group_id=5988 Of course, it could be that you upgraded your wxPython to the latest version and as I recall, they were discussing some subtle differences in DCs, blitting, paint events and other things that I just don't understand at this point in my "Pythoneering". You might ask them at their group, which is usually very helpful: wxPython.org Mike From steven.bethard at gmail.com Fri Jan 25 15:06:07 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 25 Jan 2008 13:06:07 -0700 Subject: is possible to get order of keyword parameters ? In-Reply-To: References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> <5b6e2bc6-8136-4e3a-8bf2-bb6d689d6110@s8g2000prg.googlegroups.com> Message-ID: Steven Bethard wrote: > rndblnch wrote: >> my goal is to implement a kind of named tuple. >> idealy, it should behave like this: >> p = Point(x=12, y=13) >> print p.x, p.y >> but what requires to keep track of the order is the unpacking: >> x, y = p >> i can't figure out how to produce an iterable that returns the values >> in the right order. >> relying on a "natural" order of the key names is not possible: x, and >> y are alphabetically sorted but the following example should also >> work: >> size = Point(width=23, height=45) >> w, h = size > > There are a couple of recipes for named tuples: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261 > > The latter of these will be in Python 2.6. Using that recipe, and your > example, you would write:: > > Point = namedtuple('Point', 'x y') > p = Point(x=12, y=13) > x, y = p > > Point = namedtuple('Point', 'width', 'height') Sorry, typo here. This should have read Point = namedtuple('Point', 'width height') > size = Point(width=23, height=45) > w, h = size STeVe From goon12 at gmail.com Sat Jan 12 14:43:14 2008 From: goon12 at gmail.com (Joe Riopel) Date: Sat, 12 Jan 2008 14:43:14 -0500 Subject: where do my python files go in linux? In-Reply-To: <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> <20080112113759.GJ75977@nexus.in-nomine.org> <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> Message-ID: <6a2ccd190801121143m54e4209dh9cd778bbf4e0c65f@mail.gmail.com> On Jan 12, 2008 10:13 AM, Jorgen Bodde wrote: > I thought about that too. I just wonder why /usr/local/bin is always > empty and every .deb I install from a source (if it's from Ubuntu or > not) installs files in /usr/bin .. So I looked further and noticed > that most python files do reside in /usr/share/{appname} This link might explain why your /usr/local/bin is empty: http://www.pathname.com/fhs/pub/fhs-2.3.html#THEUSRHIERARCHY From konrad.hinsen at laposte.net Tue Jan 1 15:06:18 2008 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Tue, 1 Jan 2008 21:06:18 +0100 Subject: parallel processing in standard library Message-ID: <38B8E51E-E56F-4C01-A13E-E9BB939E2398@laposte.net> Emin.shopper Martinian.shopper wrote: > Is there any hope of a parallel processing toolkit being > incorporated into the python standard library? I've seen a wide > variety of toolkits each with various features and limitations. > Unfortunately, each has its own API. For coarse-grained > parallelism, I suspect I'd be pretty happy with many of the > existing toolkits, but if I'm going to pick one API to learn and > program to, I'd rather pick one that I'm confident is going to be > supported for a while. I don't think that parallel computing is mature enough to allow the standardization of APIs, except within a given and well specified parallel computing model such as message passing. The Python Wiki has an impressive list of parallel processing options for Python (see http://wiki.python.org/moin/ParallelProcessing). With the exception of the various MPI interfaces, I don't think that any two of them are based on the same parallel computing model. I don't expect this situation to change any time soon, as parallel computing is still very much experimental. Whereas sequential computing has well-tested software engineering techniques, reliable libraries that can be combined into programs, and ever improving testing techniques, none of these exist for parallel computing. For an overview of parallel computing models and for a more detailed description of one of them as implemented in Python, please see my recent article in "Computing in Science and Engineering": http://www.computer.org/portal/site/cise/index.jsp? pageID=cise_level1&path=cise/2007/n6&file=sci.xml&xsl=article.xsl Konrad. From reed at reedobrien.com Tue Jan 8 21:02:24 2008 From: reed at reedobrien.com (Reed O'Brien) Date: Tue, 8 Jan 2008 21:02:24 -0500 Subject: [Tutor] Spaces and tabs messing up code In-Reply-To: <20080109004941.GA25990@ayn.mi.celestial.com> References: <20080109004941.GA25990@ayn.mi.celestial.com> Message-ID: <8863C706-200A-41CE-AAE9-739C7328C9E8@reedobrien.com> On Jan 8, 2008, at 7:49 PM, Bill Campbell wrote: > On Tue, Jan 08, 2008, mobiledreamers at gmail.com wrote: >> >> my friend uses vim Small editors for small minds;) >> >> and i use xemacs >> >> so our shared python code is a mix of tabs and spaces and it is >> hard >> for him to edit it in vim >> >> any idea on how to make it clean >> >> convert it all to 4 spaces? > > Do that, and in his ~/.vimrc file, add a line ``set expandtab'' Tell him to use emacs. > > (Friends don't let friends use emacs :-). > > Bill > -- > INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC > URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way > FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) > 236-1676 > > Giving money and power to government is like giving whiskey and car > keys to > teenage boys -- P.J. O'Rourke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From asmodai at in-nomine.org Sat Jan 5 05:37:51 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 5 Jan 2008 11:37:51 +0100 Subject: Basic inheritance question In-Reply-To: References: Message-ID: <20080105103751.GU82115@nexus.in-nomine.org> -On [20080105 11:36], MartinRinehart at gmail.com (MartinRinehart at gmail.com) wrote: >class code: > def __init__( self, start, stop ): > startLoc = start > stopLoc = stop Shouldn't this be: self.startLoc = start self.stopLoc = stop ? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Open your Heart and push the limits... From arnodel at googlemail.com Wed Jan 23 14:18:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 11:18:10 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <90cfc1f7-8792-4e28-9466-6a1bf77c87c5@q77g2000hsh.googlegroups.com> Message-ID: <34616e6a-3cd7-47c6-9fb5-885f527b80af@f47g2000hsd.googlegroups.com> On Jan 23, 7:06?pm, George Sakkis wrote: > The OP wanted an answer to a simple question, not a lecture on good > software engineering principles. I wholeheartedly agree. -- Arnaud From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jan 11 15:24:54 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 11 Jan 2008 21:24:54 +0100 Subject: Help needed References: <9f5efc14-0101-45f4-a896-0811b60f1709@l32g2000hse.googlegroups.com> Message-ID: <5uq1kmF1jge26U1@mid.individual.net> Devraj wrote: > Sorry to diverge from the topic, but is there a reason you need to > develop something like again? It's obvious, isn't it? > On Jan 11, 1:15 pm, tijo wrote: >> I dont know how to check the rest like how many bytes send or how >> much time taken since this is part of my course work could >> someone please help me thanks in advance. Homework. Regards, Bj?rn -- BOFH excuse #183: filesystem not big enough for Jumbo Kernel Patch From edreamleo at charter.net Sun Jan 27 13:27:21 2008 From: edreamleo at charter.net (Edward K Ream) Date: Sun, 27 Jan 2008 12:27:21 -0600 Subject: ANN: Leo 4.4.6 final released Message-ID: Leo 4.4.6 final is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo 4.4.6 fixes several recently reported bugs, all minor. Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.6: ---------------------------- - Fixes all known bugs. - Added @auto importers for javascript and xml files. - Added find-next-clone and toggle-sparse-move commands. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From martin at v.loewis.de Mon Jan 14 18:23:23 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 15 Jan 2008 00:23:23 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801150055.07699.donn.ingle@gmail.com> References: <200801141802.56353.donn.ingle@gmail.com> <478BD8AC.6050404@v.loewis.de> <200801150055.07699.donn.ingle@gmail.com> Message-ID: <478BEEEB.4020207@v.loewis.de> > Ah. Can one call it after the full call has been done: > locale.setlocale(locale.LC_ALL,'') > locale.setlocale(locale.LC_ALL) > Without any issues? If you pass LC_ALL, then some systems will give you funny results (semicolon-separated enumerations of all the categoryies). Instead, pick a specific category, e.g. LC_CTYPE. >>> I need that two-letter code that's hidden in a >>> typical locale like en_ZA.utf8 -- I want that 'en' part. > Okay, I need it because I have a tree of dirs: en, it, fr and so on for the > help files -- it's to help build a path to the right html file for the > language being supported. Ok - taking the first two letters should then be fine, assuming all your directories have two-letter codes. >> Not sure why you want that. Notice that the locale name is fairly system >> specific, in particular on non-POSIX systems. It may be >> "English_SouthAfrica" on some systems. > Wow, another thing I had no idea about. So far all I've seen are the > xx_yy.utf8 shaped ones. > > I will have some trouble then, with the help system. If you have "unknown" systems, you can try to use locale.normalize. This has a hard-coded database which tries to deal with some different spellings. For "English", it will give you en_EN.ISO8859-1. OTOH, if your software only works on POSIX systems, anyway, I think it is a fair assumption that they use two-letter codes for the languages (the full language name is only used on Windows, AFAIK). Notice that xx_yy.utf8 definitely is *not* the only syntactical form. utf8 is spelled in various ways (lower and upper case, with and without dash), and there may be other encodings (see the en_EN example above), or no encoding at all in the locale name, and their may be "modifiers": aa_ER at saaho (saaho dialect in Eritrea) be_BY at latin (as opposed to the Cyrillic be_BY locale) likewise for sr_RS de_DE at euro (as opposed to the D-Mark locale); likewise for other members of the Euro zone ca_ES.UTF-8 at valencia (Valencian - Southern Catalan) (no real difference to ca_ES at euro, but differences in message translations) gez_ER at abegede (Ge'ez language in Eritrea with Abegede collation) tt_RU at iqtelif.UTF-8 (Tatar language written in IQTElif alphabet) uz_UZ at cyrillic (as opposed to latin uz_UZ) There used to be a @bokmal modifier for Norwegian (as opposed to the Nynorsk grammar), but they have separate language codes now (nb vs. nn). Regards, Martin Regards, Martin From fredrik at pythonware.com Sat Jan 12 14:33:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Jan 2008 20:33:50 +0100 Subject: Simple List division problem In-Reply-To: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> Message-ID: marcstuart wrote: > How do I divide a list into a set group of sublist's- if the list is > not evenly dividable ? consider this example: > > x = [1,2,3,4,5,6,7,8,9,10] > y = 3 # number of lists I want to break x into > z = y/x > > what I would like to get is 3 sublists > > print z[0] = [1,2,3] > print z[2] = [4,5,6] > print z[3] = [7,8,9,10] > > obviously not even, one list will have 4 elements, the other 2 will > have 3., here's one way to do it: # chop it up n = len(x) / y z = [x[i:i+n] for i in xrange(0, len(x), n)] # if the last piece is too short, add it to one before it if len(z[-1]) < n and len(z) > 1: z[-2].extend(z.pop(-1)) From martin at marcher.name Wed Jan 23 06:23:15 2008 From: martin at marcher.name (Martin Marcher) Date: Wed, 23 Jan 2008 12:23:15 +0100 Subject: UDP Client/Server References: Message-ID: Guilherme Polo wrote: >> >>> class FooRequestHandler(BaseRequestHandler): >> ... def handle(self): >> ... data, addr_info = self.request[1].recvfrom(65534) > > Your FooReceiveServer subclasses UDPServer, it already handled the > recvfrom for you, so, this is wrong. > hmm then why do I receive every second request, shouldn't then no data at all come up? Also the next thing that would be a problem would be if I do data = self.request[0] I do get the data but where would I get the info from to which endpoint I need to send the answer? martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From rzantow at gmail.com Sat Jan 26 11:22:24 2008 From: rzantow at gmail.com (rzed) Date: Sat, 26 Jan 2008 16:22:24 +0000 Subject: Doesn't know what it wants References: <0104616d-87be-4250-b3ef-7a77ac39664a@u10g2000prn.googlegroups.com> Message-ID: Tim Rau wrote in news:0104616d-87be-4250-b3ef- 7a77ac39664a at u10g2000prn.googlegroups. com: > On Jan 26, 1:41 am, John Machin wrote: >> On Jan 26, 4:20 pm, Tim Rau wrote: >> >> >> >> > Traceback (most recent call last): >> > File "C:\Documents and Settings\Owner\My Documents\NIm's >> > code\sandbox >> > \sandbox.py", line 242, in >> > player = ship() >> > File "C:\Documents and Settings\Owner\My Documents\NIm's >> > code\sandbox >> > \sandbox.py", line 121, in __init__ >> > self.phyInit() >> > File "C:\Documents and Settings\Owner\My Documents\NIm's >> > code\sandbox >> > \sandbox.py", line 147, in phyInit >> > moi = cp.cpMomentForCircle(self.mass, .2, 0, >> > vec2d((0,0))) >> > ArgumentError: argument 4: : >> > expected vec2d instance instead of vec2d >> >> > As far as I can tell, It's getting a vec2d, and it wants a >> > vec2d. I't seems like it doesn't know what it wants, but I >> > thought only teenagers did that, no programming languages. >> >> It possibly means that it is expecting an instance of a class >> whose name is "vec2d" but you have given it an instance of >> some *other* class whose name just happens to be "vec2d". >> >> > clearly, Im missing something. >> >> Yes, some information: >> 1. what is vec2d, class or function? >> 2. what do you believe vec2d((0, 0)) should return? >> 3. what is this belief based on? >> 4. what has it actually returned this time? >> 5. what do you believe that cp.cpMomentForCircle expects as >> argument 4? >> 6. what is this belief based on? >> >> The ArgumentError exception is raised by ctypes "when a foreign >> function call cannot convert one of the passed arguments". >> Based on guessin'n'googlin' the cp thing is a set of Python >> bindings to a library written in C++ ... have you considered >> asking the author of the bindings? > > 1. vec2d is a class, designed to hold and manipulte 2d vectors > 2. it should return a vector with x=0 and y=0 > 3. That's what it's done before. > 4. trying it in the interpreter seems to show that it returns a > vec2d with zero length. as it should. > 5.cp.cpMomentForCircle seems to expect a vec2d. I'm baseing that > on a functioning demo that uses the exact same line. > > I guess that the vec2d I've got is not the one it wants. How do > I tell the difference? I'll go look at all the imports. > Are you passing the class or an instance of the class? I'd bet the former, but it should be the latter. -- rzed From fredrik at pythonware.com Mon Jan 7 03:06:21 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 09:06:21 +0100 Subject: whats wrong with this In-Reply-To: <869955.87550.qm@web45515.mail.sp1.yahoo.com> References: <869955.87550.qm@web45515.mail.sp1.yahoo.com> Message-ID: mpho raborife wrote: > I'm trying to rum gmmtrain within my pthon program like this: > > Input -l List -t inittype -e traintype > -m mixture -d dimension -v vfloor -n number -p percent -r results -c cycle) > > But i keep on getting an error. it helps if you include the actual error message in your post, so we don't have to guess. the line you quoted should give you a "SyntaxError: invalid syntax" message; the "os.system" call takes a Python string object, so the correct syntax is: os.system("gmmtrain -o output -i /etc.../") if that doesn't help, please post the *entire* traceback; also see: http://effbot.org/pyfaq/tutor-i-need-help-im-getting-an-error-in-my-program-what-should-i-do.htm From python-url at phaseit.net Mon Jan 21 11:20:54 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 21 Jan 2008 16:20:54 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jan 21) Message-ID: QOTW: "I'd say Java was never sexy, but dressed up in expensive lingerie by marketing maniacs..." - Diez B. Roggisch http://groups.google.com/group/comp.lang.python/msg/ae0463c921077f7f "I must say that the richness that list comprehensions, generators and iterators have brought to Python are well nigh immeasurable." - Uche Ogbuji Four newbie questions: * What are __new__ and __init__?: http://groups.google.com/group/comp.lang.python/browse_thread/thread/3fcb1673e25cdfe8/ * call-by-object and assignment explained (two threads): http://groups.google.com/group/comp.lang.python/browse_thread/thread/6acd8387adbbb7f2/ http://groups.google.com/group/comp.lang.python/browse_thread/thread/f113debd4032c712/ * Why the name "list" is used instead of "array"? http://groups.google.com/group/comp.lang.python/browse_thread/thread/d95bae7bd6c73670/ * Useful comments about a simple program: counting repeated numbers from a file: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b3ded6d0f494d06/ A short explanation about Unicode and encodings, by Martin L?wis: http://groups.google.com/group/comp.lang.python/browse_thread/thread/983f2f84f1f70320/ Computing all combinations from multiple lists - several alternatives discussed: http://groups.google.com/group/comp.lang.python/browse_thread/thread/998a10a65128c96e/ APyB[1], the Brazilian Python Association, proudly announces that the upcoming International Free Software Forum[2], one of the biggest FLOSS events in the world, with more than 5 thousand participants in 2007, will have a dedicated Python track this year, with 14 talks[3] related to Python and 3 training sessions: [1] http://associacao.pythonbrasil.org/ [2] http://fisl.softwarelivre.org/ [3] http://www.pythonbrasil.com.br/moin.cgi/PropostasFISL9 Pairing two lists: from simple to rather complex answers: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9fe4347ae4f0b4ac/ Tips to find memory leaks: http://groups.google.com/group/comp.lang.python/browse_thread/thread/7249eee28515bb92/ Python playes games, and more: http://www.mechanicalcat.net/richard/log/Python/pyglet_1_0_is_out Arguments in a function call are evaluated before checking its number - a missing comma is very significant! http://groups.google.com/group/comp.lang.python/browse_thread/thread/1fa85946f0947023/ Django is available for Jython, if you use the right branches: http://jython.svn.sourceforge.net/viewvc/jython/ Much the same is true for TurboGears ... ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From workitharder at gmail.com Fri Jan 4 12:29:50 2008 From: workitharder at gmail.com (bukzor) Date: Fri, 4 Jan 2008 09:29:50 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: On Jan 4, 9:08 am, Sion Arrowsmith wrote: > Hrvoje Niksic wrote: > > >BTW if you're using C++, why not simply use std::set? > > Because ... how to be polite about this? No, I can't. std::set is > crap. The implementation is a sorted sequence -- if you're lucky, > this is a heap or a C array, and you've got O(log n) performance. > But the real killer is that requirement for a std::set is that > T::operator< exists. Which means, for instance, that you can't > have a set of complex numbers.... > > -- > \S -- si... 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 Why cant you implement < for complex numbers? Maybe I'm being naive, but isn't this the normal definition? a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) How do you implement a set without sorting? Are you expecting better than O(log n)? --Buck From basilisk96 at gmail.com Wed Jan 9 22:17:21 2008 From: basilisk96 at gmail.com (Basilisk96) Date: Wed, 9 Jan 2008 19:17:21 -0800 (PST) Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> Message-ID: <0a00b023-5cd0-41c3-82f8-96910cf0f515@d70g2000hsb.googlegroups.com> On Jan 9, 9:49 pm, erik gartz wrote: > The loop performs some actions with web services. The particular > iteration I'm on isn't important to me. It is only important that I > attempt the web services that number of times. If I succeed I > obviously break out of the loop and the containing function (the > function which has the loop in it) returns True. If all attempts fail > the containing loop returns False. Do you think you could apply something like this: def foo():print "fetching foo..." actions = (foo,)*5 for f in actions: f() fetching foo... fetching foo... fetching foo... fetching foo... fetching foo... ..but not knowing your specific implementation, I may be off the wall here. Cheers, -Basilisk96 From fredrik at pythonware.com Mon Jan 7 17:47:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 23:47:51 +0100 Subject: Open source English dictionary to use programmatically w/ python In-Reply-To: References: Message-ID: dgoldsmith_89 wrote: > Can anyone point me to a downloadable open source English dictionary > suitable for programmatic use with python: I'm programming a puzzle > generator, and I need to be able to generate more or less complete > lists of English words, alphabetized. Thanks! DG here's one: http://www.dcs.shef.ac.uk/research/ilash/Moby/ From http Sat Jan 12 15:25:50 2008 From: http (Paul Rubin) Date: 12 Jan 2008 12:25:50 -0800 Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> Message-ID: <7xprw6g59t.fsf@ruckus.brouhaha.com> marcstuart writes: > what I would like to get is 3 sublists > > print z[0] = [1,2,3] > print z[2] = [4,5,6] > print z[3] = [7,8,9,10] Are you SURE you want that? In almost every situation I've seen, print z[0] = [1,2,3] print z[2] = [4,5,6] print z[3] = [7,8,9] print z[4] = [10] is preferable. From Matthew_WARREN at bnpparibas.com Wed Jan 23 12:46:17 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Wed, 23 Jan 2008 17:46:17 +0000 Subject: pairs from a list In-Reply-To: Message-ID: I'm just fiddling with this, am no great expert, but I added def pairs5(x): o=[] for n in zip(x[::2],x[1:2]): o.append(n) return o I dont know if that breaks any constraints placed on the problem, but I get the following output 0.07158942896 0.266009705575 0.21342143313 0.0537146193457 0.0107680502972 does that make it faster than pairs(4) or am I breaking some constraints on the problem? Matt. Internet aisaac at american.edu To python-list Sent by: cc python-list-bounces+matthew.warren=uk.bnpparibas.com@ python.org Subject Re: pairs from a list 22/01/2008 18:09 Arnaud Delobelle wrote: > pairs4 wins. Oops. I see a smaller difference, but yes, pairs4 wins. Alan Isaac import time from itertools import islice, izip x = range(500001) def pairs1(x): return izip(islice(x,0,None,2),islice(x,1,None,2)) def pairs2(x): xiter = iter(x) while True: yield xiter.next(), xiter.next() def pairs3(x): for i in range( len(x)//2 ): yield x[2*i], x[2*i+1], def pairs4(x): xiter = iter(x) return izip(xiter,xiter) t = time.clock() for x1, x2 in pairs1(x): pass t1 = time.clock() - t t = time.clock() for x1, x2 in pairs2(x): pass t2 = time.clock() - t t = time.clock() for x1, x2 in pairs3(x): pass t3 = time.clock() - t t = time.clock() for x1, x2 in pairs4(x): pass t4 = time.clock() - t print t1, t2, t3, t4 Output: 0.317524154606 1.13436847421 1.07100930426 0.262926712753 -- 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 deets at nospam.web.de Mon Jan 21 04:34:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Jan 2008 10:34:37 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <5vi1r8F1mjs0rU1@mid.uni-berlin.de> <5360e13d-215d-4d3e-9930-daa6cddd996a@f10g2000hsf.googlegroups.com> Message-ID: <5vj79dF1m2nmlU1@mid.uni-berlin.de> pythonewbie > > Because the solution using distutils.sysconfig.get_python_lib() is > very smart ! Depending on your goal. You said """ My goal is to verify if an/several extension(s) are installed and to automatically install the missing ones on Linux or Win32. """ This goal can't be reached with only the site-packages - because I can install packages somewhere else (matter of factly, this happens on debian for example, they've split the install-dirs and created a bunch of dirs under /usr/share) So having a method that gives you the installation root doesn't help much here. Diez From http Wed Jan 30 08:20:49 2008 From: http (Paul Rubin) Date: 30 Jan 2008 05:20:49 -0800 Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> Message-ID: <7xwsprxxe6.fsf@ruckus.brouhaha.com> "Neil Cerutti" writes: > Or one can put on his bellbottoms, horn-rimmed glasses, and wear a mullet: > > i = 0 > while i < len(a): > if a[i] == 99: > del a[i] > else: > i += 1 Quadratic time!! Yowch!! Back to the future: def rocket_science(xs): for x in xs: if x != 99: yield x a[:] = list(rocket_science(a)) ;-) From sromero at gmail.com Fri Jan 11 08:06:21 2008 From: sromero at gmail.com (Santiago Romero) Date: Fri, 11 Jan 2008 05:06:21 -0800 (PST) Subject: Converting a bidimensional list in a bidimensional array References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> <005679e9-c355-4e0a-872c-e0dae3181fd0@x69g2000hsx.googlegroups.com> Message-ID: <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> > > - Speed Performance: Do you think that changing from list to Array() > > would improve speed? I'm going to do lots of tilemap[y][x] checks (I > > mean, player jumping around the screen, checking if it's falling over > > a non-zero tile, and so). > First of all: if you have enough memory to use a python list, then I > suggest you to use a list. > > Often python lists are faster than array.array (maybe because python > lists actually contain pyobjects). My problem is that, in my game, each screen is 30x20, and I have about 100 screens, so my tilemap contains 32*20*100 = 60000 python objects (integers). If each integer-python-object takes 16 bytes, this makes 60000 * 16 = almost 1MB of memory just for the tilemaps... Using array of type H (16 bits per item = 2 bytes), my maps take just 60000*2 = 120KB of memory. After that, I just will access tilemap data for reading (i.e. value = tilemap.GetTile(x,y)) ... Do you think I should still go with lists instead of an H-type array? From terry at jon.es Wed Jan 23 16:55:56 2008 From: terry at jon.es (Terry Jones) Date: Wed, 23 Jan 2008 22:55:56 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 13:23:46 on Wednesday, 23 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> <457550e3-f5e1-4fad-b553-c3e5e400dbb1@u10g2000prn.googlegroups.com> Message-ID: <18327.47084.736074.304302@jon.es> >>>>> "Arnaud" == Arnaud Delobelle writes: >> >> Ha - you can't have it both ways Arnaud! You don't want the computation to >> go negative... doesn't that (and my "proof") have something to do with the >> inverse nature of add and sub? :-) Arnaud> I think I can have it both ways, here's why: the "big then small" Arnaud> and "no negatives" rules are applied indiscriminately by the Arnaud> algorithm: it doesn't need to know about the history of operations Arnaud> in order to make a decision depending on their nature. OTOH, Arnaud> identifying (a + b) - c and a + (b - c) for example, requires Arnaud> inspection of the stack/tree/ calculation history. It is an Arnaud> *informed* decision made by the algorithm But this is having it both ways too :-) The reason the algorithm can do it indiscriminately is because *you* know that it always applies, and *you* figure out and implement the algorithm that way. The algorithm doesn't have a mind of its own, after all. BTW, there are some very important issues here. One is about representation (thinking about representation is one of my pet vices). When you try to solve some real-world problem with a computer, you must choose a representation. What many people seem to fail to recognize is that in so doing you've already begun to solve the problem. If you pick a better representation, your algorithm can potentially be much dumber and still be hugely faster than a brilliant algorithm on a terrible representation. In maintaining an A > B invariant in operations A + B and A * B, you're using insight into the problem to influence representation. With that better representation, your algorithm doesn't have to do so much work. I wrote some more about this a while ago at http://www.fluidinfo.com/terry/2007/03/19/why-data-information-representation-is-the-key-to-the-coming-semantic-web/ Arnaud> Note that disallowing 0 and disallowing x - x are equivalent, as Arnaud> the only way to get your first 0 is by doing x - x. That depends. I allow negative numbers in the input, and also 0 (I just don't let you use it :-)) Arnaud> Thanks for the discussion, it's made me realise more clearly what I Arnaud> was doing. Me too! Thanks. Terry From revuesbio at gmail.com Fri Jan 18 09:21:27 2008 From: revuesbio at gmail.com (revuesbio) Date: Fri, 18 Jan 2008 06:21:27 -0800 (PST) Subject: MySQLdb and compatibility with vista 64 bits References: <3bb34edc-2c2c-4ff5-8042-dc94c7fadc4f@s19g2000prg.googlegroups.com> Message-ID: <7c69d9b4-313e-4130-83ec-6cbb40d04efe@y5g2000hsf.googlegroups.com> On 5 jan, 20:00, revuesbio wrote: > Hello, > I try to installmysqldbon windows vista 64bits but there is a > failure when i try to importmysqldbin python 2.5 : > "DLL load failed with error code 193" > > Is there a solution to this problem ? > Thank you is there another solution to interact mysql and python with vista x64 ? From pavlovevidence at gmail.com Sat Jan 5 16:15:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 5 Jan 2008 16:15:16 -0500 Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> Message-ID: <41solf.jf2.ln@127.0.0.1> On Sat, 05 Jan 2008 08:14:46 -0800, caca wrote: > On Jan 5, 5:07 pm, c... at mailinator.com wrote: >> Hello, Paul and Arnaud. >> While I think about your answers: do you think there is any way to >> avoid shuffle? >> It may take unnecessary long on a long list most of whose elements have >> the property. > > Umm... > You provide nice answers in the case many elements are picked from the > same list. > Any ideas for the case when the picker is called many times on a > program, but never twice with the same list? ISTM the best thing would be to reimplement the shuffle algorithm, but to stop shuffling as soon as you get a hit. The drawback is that it's a destructive operation, but that doesn't sound like it's an issue for you. Here's something for starters: def random_element_with_property(x,test_property_func): for i in xrange(len(x)-1): j = random.randrange(i+1,len(x)) tmp = x[j] if test_property_func(tmp): return tmp x[j] = x[i] x[i] = tmp return None Then, for example, use it like this: def odd(i): return i&1 e = random_element_with_property(range(20),odd) Carl Banks From bearophileHUGS at lycos.com Tue Jan 15 11:32:54 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 15 Jan 2008 08:32:54 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> <478c868a$0$7040$426a34cc@news.free.fr> <5c0a472a-5ed6-4b34-9685-42f9a0a4145e@k39g2000hsf.googlegroups.com> Message-ID: cokofree... at gmail.com: > A lecturer gave me the perfect answer to the question of speed. > "You have two choices when it comes to programming. Fast code, or fast > coders." I don't believe that anymore, ShedSkin compiles slowly and it has limitations still, but it shows that it's possible to create a language with simple short syntax and high running speed at the same time. Bye, bearophile From arkanes at gmail.com Fri Jan 11 14:06:02 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 11 Jan 2008 13:06:02 -0600 Subject: Strange problem: MySQL and python logging using two separate cursors In-Reply-To: <13oa2dqgt7c0oac@corp.supernews.com> References: <13oa2dqgt7c0oac@corp.supernews.com> Message-ID: <4866bea60801111106q5a3b888le734c5b1bd2d1278@mail.gmail.com> On Jan 9, 2008 11:52 AM, Dennis Lee Bieber wrote: > On Wed, 9 Jan 2008 10:11:09 +0100, Frank Aune > declaimed the following in comp.lang.python: > > > The only clue I have so far, is that the cursor in task 1 seems to be unable > > to "register" any new entries in the log table produced by task 2 as soon as > > task 1 perform an SQL query of some kind. > > > How often do you issue a commit? For some DB-API adapters (I forget > which database -- think it was SQLite) a select query does not complete > until the last data has been fetched from it -- meaning the transaction > (the DB-API spec is that auto-commit is OFF) is still open and "other > transaction changes" will not be seen. {I do find it perplexing that > transactions are started by cursor actions, but committed by the > connection!} > > > Im contemplating using the same cursor for task 1 and 2, but I think keeping > > them separate is a better design - if it only worked :) > > > I'd probably suggest using a separate connection and cursor -- with > liberal usage of conn.commit() to ensure that transaction "views" are > flushed/refreshed. The MySql api doesn't have a concept of a cursor, only connections. If you want truly separate cursors in MySql you need to use individual connections. From donn.ingle at gmail.com Sun Jan 13 13:48:08 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 20:48:08 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A4F8A.5010108@v.loewis.de> References: <200801131928.54459.donn.ingle@gmail.com> <478A4F8A.5010108@v.loewis.de> Message-ID: <200801132048.08966.donn.ingle@gmail.com> Well, that didn't take me long... Can you help with this situation? I have a file named "M?gul.pog" in this directory: /home/donn/.fontypython/ I set my LANG=C Now, I want to open that file from Python, and I create a path with os.path.join() and an os.listdir() which results in this byte string: paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] I *think* that the situation is impossible because the system cannot resolve the correct filename (due the locale being ANSI and the filename being other) but I am not 100% sure. So, I have been trying combinations of open: 1. f = codecs.open( paf, "r", "utf8" ) I had hopes for this one. 2. f = codecs.open( paf, "r", locale.getpreferredencoding()) 3. f = open( paf, "r") But none will open it - all get a UnicodeDecodeError. This aligns with my suspicions, but I wanted to bounce it off you to be sure. It does not really mesh with our previous words about opening all files as bytestrings, and admits failure to open this file. Also, this codecs.open(filename, "r", ) function: 1. Does it imply that the filename will be opened (with the name as it's type : i.e. bytestring or unicode ) and written *into* as 2. Imply that filename will be encoded via and written into as It's fuzzy, how is the filename handled? \d -- He has Van Gogh's ear for music. -- Billy Wilder Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From pavlovevidence at gmail.com Wed Jan 9 22:44:53 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 9 Jan 2008 22:44:53 -0500 Subject: for loop without variable References: Message-ID: On Wed, 09 Jan 2008 14:25:36 -0800, erik gartz wrote: > Hi. I'd like to be able to write a loop such as: for i in range(10): > pass > but without the i variable. The reason for this is I'm using pylint and > it complains about the unused variable i. I can achieve the above with > more lines of code like: > i = 0 > while (i != 10): > i += 1 > Is there a concise way to accomplish this without adding extra lines of > codes? Thanks in advance for your help. IIRC, in pylint you can turn off checking for a particular symbol. I had to edit a .pylintrc file (location may vary on Windows) and there was a declaration in the file that listed symbols to ignore. Last time I bothered running it, I added "id" to that list, since I use it often (bad habit) and almost never use the builtin id, but still wanted shadowing warnings for other symbols. Carl Banks From deets at nospam.web.de Tue Jan 15 16:49:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 Jan 2008 22:49:53 +0100 Subject: searching an XML doc In-Reply-To: <327368a7-694f-4f30-8f76-db0569ed4a5c@k2g2000hse.googlegroups.com> References: <327368a7-694f-4f30-8f76-db0569ed4a5c@k2g2000hse.googlegroups.com> Message-ID: <5v4o44F1l2oshU1@mid.uni-berlin.de> Gowri schrieb: > Hello, > > I've been reading about ElementTreee and ElementPath so I could use > them to find the right elements in the DOM. Unfortunately neither of > these seem to offer XPath like capabilities where I can find elements > based on tag, attribute values etc. Are there any libraries which can > give me XPath like functionality? lxml does that. Diez From cameronwong88 at gmail.com Fri Jan 4 14:56:11 2008 From: cameronwong88 at gmail.com (cameronwong88 at gmail.com) Date: Fri, 4 Jan 2008 11:56:11 -0800 (PST) Subject: Question on os.tempnam() vulnerability Message-ID: Hello, Does any one know what kind of security risk these message are suggesting? >>> f = os.tempnam() __main__:1: RuntimeWarning: tempnam is a potential security risk to your program >>> f '/tmp/filed4cJNX' >>> g = os.tmpnam() __main__:1: RuntimeWarning: tmpnam is a potential security risk to your program >>> g '/tmp/fileENAuNw' Thanks, ~cw From oweston at earthlink.net Thu Jan 3 09:45:56 2008 From: oweston at earthlink.net (wes) Date: Thu, 03 Jan 2008 06:45:56 -0800 Subject: problem with global var In-Reply-To: References: Message-ID: <13npt8kotgm0964@corp.supernews.com> Bruno Ferreira wrote: > Hi, > > I wrote a very simple python program to generate a sorted list of > lines from a squid access log file. > > Here is a simplified version: > > ################################## > 1 logfile = open ("squid_access.log", "r") > 2 topsquid = [["0", "0", "0", "0", "0", "0", "0"]] > 3 > 4 def add_sorted (list): global topsquid > 5 for i in range(50): > 6 if int(list[4]) > int(topsquid[i][4]): > 7 topsquid.insert(i,list) > 8 break > 8 # Max len = 50 > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > 12 > 13 while True: > 14 logline = logfile.readline() > 15 linefields = logline.split() > 16 > 17 if logline != "": > 18 add_sorted (linefields) > 19 else: > 20 break > 21 > 22 for i in range (len(topsquid)): > 23 print topsquid[i][4] > #################################### > > When I execute the program _without_ the lines 10 and 11: > > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > > it runs perfectly. > > But if I execute the program _with_ those lines, this exception is thrown: > > bruno at ts:~$ python topsquid.py > Traceback (most recent call last): > File "topsquid.py", line 20, in > add_sorted (linefields) > File "topsquid.py", line 6, in add_sorted > if int(list[4]) > int(topsquid[i][4]): > UnboundLocalError: local variable 'topsquid' referenced before assignment > > > Note that now the error shown is not related with the lines 10 and 11, > but wiht a line prior to them. > > Any hints? > Try line 4 add. From pavlovevidence at gmail.com Sat Jan 12 14:16:38 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 12 Jan 2008 14:16:38 -0500 Subject: where do my python files go in linux? References: Message-ID: On Sat, 12 Jan 2008 12:02:20 +0100, Jorgen Bodde wrote: > I am trying to make a debian package. I am following the tutorial by > Horst Jens > (http://showmedo.com/videos/video? name=linuxJensMakingDeb&fromSeriesID=37) > and it is very informative. However one thing my app has and his > doesn't, is multiple python files which need to be executed. For example > > {dir}/app > app.py > > app.py calls a lot of modules in {dir}/app. Horst says the python file > goes in /usr/bin/app.py which is ok with me, but I have multiple python > files, and I decided to use an app.sh script to call my python files. In > the /usr/bin I do not see subdirs so I assume that is not really > desirable. > > Question 1. Where do I put the bulk of python scripts in a normal linux > environment? > Question 2. Should I use *.pyc rather then *.py files to speed up > executing as the user cannot write to /usr/bin or any other dir in the > system and everytime my app runs it will recompile it > > Thanks for any advice or maybe a good tutorial how to set up files in a > linux environment On a Debian system: I would put app.py in /usr/local/bin. I would create the directory /usr/local/lib/app, and put all other *.py and *.pyc files there. At the top of app.py, I'd add the following line so that I could import files directly from /usr/local/lib/app: sys.path.insert(0,'/usr/local/lib/app') Alternatively, using your app.sh approach, I'd put app.sh in /usr/local/bin/, and all *.py and *.pyc files in /usr/local/lib/app. I'd invoke Python something like this: PYTHONPATH=/usr/local/lib/app:$PYTHONPATH python -m app (The -m switch searches the Python path for a module to run.) If it's more of a library than an application (maybe there is a command line script, but users could want to import the modules directly), then I'd stick all the modules in /usr/local/lib/python2.x/site-packages, and the command line scripts in /usr/local/bin. Yes, install the *.pyc files. I recommend putting *.py files there as well, so users can refer to it if there are any problems, but you don't have to. The Python module compileall is your friend here. Carl Banks From sjmachin at lexicon.net Wed Jan 23 14:10:16 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 11:10:16 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> Message-ID: On Jan 24, 5:50 am, ryan k wrote: > Hello. I have a string like 'LNAME > PASTA ZONE'. I want to create a list of those words and > basically replace all the whitespace between them with one space so i > could just do lala.split(). Thank you! > > Ryan Kaskel So when you go to the Python interactive prompt and type firstly lala = 'LNAME PASTA ZONE' and then lala.split() what do you see, and what more do you need to meet your requirements? From rrr at ronadam.com Sun Jan 13 23:02:39 2008 From: rrr at ronadam.com (Ron Adam) Date: Sun, 13 Jan 2008 22:02:39 -0600 Subject: time.time or time.clock In-Reply-To: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> References: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> Message-ID: <478ADEDF.2070306@ronadam.com> John Machin wrote: > On Jan 14, 7:05 am, Ron Adam wrote: >> I'm having some cross platform issues with timing loops. It seems >> time.time is better for some computers/platforms and time.clock others, but > > Care to explain why it seems so? > >> it's not always clear which, so I came up with the following to try to >> determine which. >> >> import time >> >> # Determine if time.time is better than time.clock >> # The one with better resolution should be lower. >> if time.clock() - time.clock() < time.time() - time.time(): >> clock = time.clock >> else: >> clock = time.time >> >> Will this work most of the time, or is there something better? >> > > Manual: > """ > clock( ) > > On Unix, return the current processor time as a floating point number > expressed in seconds. The precision, and in fact the very definition > of the meaning of ``processor time'', depends on that of the C > function of the same name, but in any case, this is the function to > use for benchmarking Python or timing algorithms. > > On Windows, this function returns wall-clock seconds elapsed since the > first call to this function, as a floating point number, based on the > Win32 function QueryPerformanceCounter(). The resolution is typically > better than one microsecond. > [snip] > > time( ) > > Return the time as a floating point number expressed in seconds since > the epoch, in UTC. Note that even though the time is always returned > as a floating point number, not all systems provide time with a better > precision than 1 second. While this function normally returns non- > decreasing values, it can return a lower value than a previous call if > the system clock has been set back between the two calls. > """ > > AFAICT that was enough indication for most people to use time.clock on > all platforms ... before the introduction of the timeit module; have > you considered it? I use it to time a Visual Python loop which controls frame rate updates and set volocities according to time between frames, rather than frame count. The time between frames depends both on the desired frame rate, and the background load on the computer, so it isn't constant. time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't high enough resolution on windows. I do use timeit for bench marking, but haven't tried using in a situation like this. > It looks like your method is right sometimes by accident. func() - > func() will give a negative answer with a high resolution timer and a > meaningless answer with a low resolution timer, where "high" and "low" > are relative to the time taken for the function call, so you will pick > the high resolution one most of the time because the meaningless > answer is ZERO (no tick, no change). Some small fraction of the time > the low resolution timer will have a tick between the two calls and > you will get the wrong answer (-big < -small). If the difference is between two high resolution timers then it will be good enough. I think the time between two consectutive func() calls is probably low enough to rule out low resolution timers. In the case of two > "low" resolution timers, both will give a meaningless answer and you > will choose arbitrarily. In the case of two low resolution timers, it will use time.time. In this case I probably need to raise an exception. My program won't work correctly with a low resolution timer. Thanks for the feed back, I will try to find something more dependable. Ron From stephane at harobed.org Thu Jan 10 06:02:42 2008 From: stephane at harobed.org (=?iso-8859-1?q?KLEIN_St=E9phane?=) Date: Thu, 10 Jan 2008 11:02:42 +0000 (UTC) Subject: Do you know mirror repository of PyUMLGraph, what do you thinks about this tools ? Message-ID: Hi, I've looked http://www.umlgraph.org/ tools. I think it's great to generate UML Diagram from source code and comment's. I read there are "Python version" of this tools : PyUMLGraph (http://pypi.python.org/pypi/ PyUMLGraph/0.1.10). Unfortunately, repository of this tools is down :( My questions : * do you know a mirror repository of this tools ? * have you used this tools ? What do you thinks about ? I thinks this can be a great tools in agility programming context. Thanks for your informations Stephane From python.list at tim.thechases.com Wed Jan 9 09:40:33 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 09 Jan 2008 08:40:33 -0600 Subject: Open a List of Files In-Reply-To: <18308.56071.859777.102224@terry.local> References: <874pdomrrd.fsf@mulj.homelinux.net> <18308.12959.742868.758136@terry.local> <18308.56071.859777.102224@terry.local> Message-ID: <4784DCE1.3090602@tim.thechases.com> > You don't need "for fn in open_files.keys():", you can just use "for fn in > open_files:", but simpler than that is to just use the dictionary values: > > for fn in open_files.values(): > fn.close() This can also work for standard variable names: for f in (messages, deliveries, actions, parts, recipients, viruses, esp_scores): f.close() -tkc From PrinceOfDataMining at gmail.com Thu Jan 17 16:18:41 2008 From: PrinceOfDataMining at gmail.com (Samuel) Date: Thu, 17 Jan 2008 13:18:41 -0800 (PST) Subject: ANN:proxysocket(socks4,socks5)v0.1 Message-ID: <7228288b-cb34-40ba-8483-a2dc57115511@d21g2000prf.googlegroups.com> http://code.google.com/p/proxysocket/downloads/list From haraldarminmassa at gmail.com Wed Jan 23 07:28:54 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Wed, 23 Jan 2008 04:28:54 -0800 (PST) Subject: translating Python to Assembler...sorry if this is duplicated...it's unintentional References: Message-ID: <57c1047c-1646-458c-b20a-76b06991837f@h11g2000prf.googlegroups.com> > My expertise, if any, is in assembler. I'm trying to understand Python > scripts and modules by examining them after they have been > disassembled in a Windows environment. Maybe you could also profit from diassembling Pythons bytecode into MNEmonics of the Python Virtual Machine ? http://docs.python.org/lib/module-dis.html Because "disassembling python scripts" with any other disassembler will not likely lead to something usefull: a) the .pyc and pyo files are in Python Bytecode, that is "assembler for the Python Virtual Machine Processor", disassemble with the mentioned module b) python2x.dll is in i386-Assembler, but contains the virtual machine. Understanding that will you will learn a lot of great programming concepts from some of the most brilliant minds on this planet; but will give you no hint to understand Python scripts, as they are running on top of that VM. Like disassembling the Hybrid Power Drive of a Lexus GS450h will teach you nothing about navigating from Berlin to Paris. Best wishes, Harald From deets at nospam.web.de Sun Jan 20 14:59:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 20 Jan 2008 20:59:33 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt In-Reply-To: References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> Message-ID: <5vhnheF1meri9U1@mid.uni-berlin.de> pythonewbie schrieb: > On 20 jan, 19:50, "Diez B. Roggisch" wrote: >> pythonewbie schrieb: >> >> >> >>> On 20 jan, 12:20, Christian Heimes wrote: >>>> pythonewbie wrote: >>>>> I am stucked on creating a function to get the Python install >>>>> directory (and site-packages directory) with a 100% reliable method... >>>> Only one method is 100% reliable: >>>> try: >>>> import yourextension >>>> except ImportError: >>>> available = False >>>> else: >>>> available = True >>>> Christian >>> Hi Christian, >>> OK thanks, interesting to detect if an extension is available or not. >>> But for different reasons I also want to get the absolute path of >>> Python install directory (not only the executable under Linux) and >>> site-packages directory. >>> How could I proceed ? >> Maybe sys.path is a starter? >> >> Diez > > Yes, it is, but my problem is that I am not sure to find the > information I need at the same position of the list generated by > sys.path. > > I explain, for Win32, I find install directory using sys.path[6] and > site-package directory using sys.path[7], for Linux I find install > directory using sys.path[2] and site-package directory using > sys.path[6]. > > For my tests, I have used XP Pro and Ubuntu Gutsy. > > I am not sure to find these information at the same position in the > sys.path list using Win9x, Win2k, Ubuntu Dapper, Redhat FC6, FreeBSD > and using Python v2.1 2.2 2.3 etc ? > > This why I'm asking experienced programmers of this usenet group for > advices. Sorry, I missed your first post. However, I don't see what your problem actually is. If you want to look for any extension, you need to consider whatever can be seen in the sys.path. So what do you care about the order of them? Diez From lefevrol at yahoo.com Mon Jan 28 14:29:52 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Mon, 28 Jan 2008 20:29:52 +0100 Subject: read and readline hanging In-Reply-To: <605nnmF1oc8dvU2@mid.uni-berlin.de> References: <5vuv9iF1o6ambU2@mid.uni-berlin.de> <605nnmF1oc8dvU2@mid.uni-berlin.de> Message-ID: > The buffering behavior at the interactive prompt is very often different > from connections via pipes. I hadn't thought of that. I will ask on the Octave list. Thanks, -- O.L. From JO3chiang at gmail.com Tue Jan 1 21:32:30 2008 From: JO3chiang at gmail.com (jo3c) Date: Tue, 1 Jan 2008 18:32:30 -0800 (PST) Subject: parse text files in a directory? Message-ID: hi everybody im a newbie in python, i have a question how do u parse a bunch of text files in a directory? directory: /dir files: H20080101.txt , H20080102.txt,H20080103.txt,H20080104.txt,H20080105.txt etc...... i already got a python script to read and insert a single text files into a postgres db. is there anyway i can do it in a batch, cause i got like 2000 txt files. thanks in advance joe From http Thu Jan 31 17:09:20 2008 From: http (Paul Rubin) Date: 31 Jan 2008 14:09:20 -0800 Subject: char string 2 hex string References: Message-ID: <7xfxwd3awf.fsf@ruckus.brouhaha.com> Antonio Chay writes: > "AAA" should be "414141" 'AAA'.encode('hex') From google at mrabarnett.plus.com Sun Jan 27 20:28:33 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 27 Jan 2008 17:28:33 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> <479d1616$0$9100$9b4e6d93@newsspool2.arcor-online.net> <13pqabbsrvkgn6f@corp.supernews.com> Message-ID: On Jan 28, 1:01 am, Steven D'Aprano wrote: > On Mon, 28 Jan 2008 00:39:02 +0100, Wildemar Wildenburger wrote: > > Dustan wrote: > >>> Well, you save one or two lines per class. Not enough in my opinion. > > >> Are you referring to the alternate syntax or to the decorator? Either > >> way, you could be saving 4 or 5 or more lines, if you have enough > >> arguments. > > > OK, but then again, every decent IDE should give you the tools to write > > an automation for that. Not that I don't like the idea of > > auto-assignment, but, you know ... > > You know, not everybody uses a "decent IDE", by choice or necessity, and > even if they did, having what is essentially a macro to type for you > doesn't solve the essential problem that you're writing the same thing > THREE TIMES instead of once. And then you have to keep it all in sync > through who knows how many code revisions and refactorings. > > class Parrot(object): # after many revisions... > def __init__(self, genus, species, variety, name, age, colours, > wingspan, beaksize, healthstate, language, vocabulary): > self.wingspan = wingspan > self.beaksize = beaksize > self.name = name > self.age = age > self.binomial_name = (genus, species) > self.breed = variety > self.colour = colour > self.language = language > self.state = get_state(healthstate) > self.words = vocabulary > self.colors = colours > > What IDE will spot the error(s) in the above? > > Here's another version, assuming syntax support for auto-assignment for > names starting with an ampersand: > > class Parrot(object): # after many revisions... > def __init__(self, genus, species, variety, &name, &age, &colours, > &wingspan, &beaksize, healthstate, &language, vocabulary): > self.binomial_name = (genus, species) > self.breed = variety > self.state = get_state(healthstate) > self.words = vocabulary > > See how much easier it is to keep the attributes synced with the > arguments? Don't Repeat Yourself in action. > > I think the biggest minus on this proposal is that it creates new syntax > that is only meaningful in the __init__ method of a class. "Special cases > aren't special enough to break the rules." I'd vote for it, but > conditionally. What should this do? > > def foo(x, y, &z): > pass > > Create foo.z perhaps? > Well, if: def __init__(self, &foo): pass does: def __init__(self, foo): self.foo = foo then: def foo(x, y, &z): pass does: def foo(x, y, &z): x.z = z Don't think that's useful, though... From steve at REMOVE-THIS-cybersource.com.au Thu Jan 24 16:27:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 24 Jan 2008 21:27:50 -0000 Subject: object vs class oriented -- xotcl References: Message-ID: <13pi0mmk525f325@corp.supernews.com> On Thu, 24 Jan 2008 12:35:44 -0800, William Pursell wrote: > Basically, you can > instantiate an object A of class Foo, and later change A to be an object > of class Bar. Does Python support this type of flexibility? As I > stated above, I've been away from Python for awhile now, and am a bit > rusty, but it seems that slots or "new style" objects might provide > this type of behavior. If you think slots are a candidate for this functionality, I think you have misunderstood what slots actually are. Slots don't define what class the object has, they are a memory optimization for when you need vast numbers of instances and don't need arbitrary attributes. > The ability to have an object change class is > certainly (to me) a novel idea. Can I do it in Python? Yes, mostly. Example: >>> class Spam(object): ... def whatami(self): ... return "I am a delicious and tasty processed meat product" ... >>> class Parrot(object): ... def whatami(self): ... return "I am a colourful bird with a large vocabulary" ... >>> >>> s = Spam() >>> s.whatami() 'I am a delicious and tasty processed meat product' >>> s.__class__ = Parrot >>> s.whatami() 'I am a colourful bird with a large vocabulary' If you actually play around with this, you'll soon find the limitations. For instance: >>> s.__class__ = int Traceback (most recent call last): File "", line 1, in TypeError: __class__ assignment: only for heap types -- Steven From peng.kyo at gmail.com Thu Jan 17 22:23:18 2008 From: peng.kyo at gmail.com (J. Peng) Date: Fri, 18 Jan 2008 11:23:18 +0800 Subject: array and list Message-ID: <18c1e5f20801171923q73e7830dj85b80d086ccbbb8f@mail.gmail.com> what's the difference between an array and a list in python? I see list has all features of array in C or perl. so please tell me.thanks. From pablo at decode.com.ar Wed Jan 23 18:05:01 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Wed, 23 Jan 2008 21:05:01 -0200 Subject: Increment Variable Name In-Reply-To: <56455F14-760D-4FE0-863B-949F863AD083@gmail.com> References: <56455F14-760D-4FE0-863B-949F863AD083@gmail.com> Message-ID: <4797C81D.4070105@decode.com.ar> Hi David, David Brochu wrote: > I know the length of a list and I want to pass each element of a list > to a unique variable, thus I want to increment variable names. If the > list length = 4, i want to have the following variables: var1, var2, > var3, var4. yuck... no, believe me, you probably don't want to do that. Why don't you tell us what you are actually trying to achieve instead? (I mean, the problem, not the solution) if you are REALLY sure that you want is what you asked: >>> for var in enumerate(['welcome', 'to', 'php']): ... exec "var%s=%r"% var ... >>> vars() {'var1': 'to', 'var0': 'welcome', 'var2': 'php', '__builtins__': , 'var': (2, 'php'), '__name__': '__main__', '__doc__': None} (I'm assuming that you have builtin objects in your list) This is completely unsafe and error prone. IOW horrible. HTH, Pablo From Frank.Aune at broadpark.no Tue Jan 22 07:18:03 2008 From: Frank.Aune at broadpark.no (Frank Aune) Date: Tue, 22 Jan 2008 13:18:03 +0100 Subject: MySQLdb and DictCursor Message-ID: <200801221318.03990.Frank.Aune@broadpark.no> Hi, Im using a MySQLdb connection with a DictCursor, and to me it seems the wrapping to dictionaries only prepend column names when there is an actual conflict in the keywords. I would like the cursor to always prepend table names no matter what. Is this possible? Thanks, -Frank From musiccomposition at gmail.com Mon Jan 14 22:26:35 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 14 Jan 2008 19:26:35 -0800 (PST) Subject: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net> Message-ID: <57518348-4d34-404c-8ec2-f97ac407510b@f47g2000hsd.googlegroups.com> On Jan 14, 6:26 pm, John Nagle wrote: > I passed a dict for the "env" variable to Popen with Unicode strings > for the dictionary values. > > Got: > > File "D:\Python24\lib\subprocess.py", line 706, in _execute_child > TypeError: environment can only contain strings > > It turns out that the strings in the "env" parameter have to be ASCII, > not Unicode, even though Windows fully supports Unicode in CreateProcess. > > John Nagle From danb_83 at yahoo.com Sun Jan 6 18:59:51 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 6 Jan 2008 15:59:51 -0800 (PST) Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <5u95sjF1etf0nU1@mid.individual.net> Message-ID: <42aeef02-a0a9-4e29-9a5d-7a0785997666@v67g2000hse.googlegroups.com> On Jan 5, 4:53 am, Bjoern Schliessmann wrote: > MartinRineh... at gmail.com wrote: > > Jeroen Ruigrok van der Werven wrote: > >> self.startLoc = start > >> self.stopLoc = stop > > > Thanks! Of course it should. Old Java habits die slowly. > > That's not really a Java habit. In Java and C++, personally I like > to write > > this.startLoc = start > this.stopLoc = stop > > It makes much clearer what a field and what a "normal" variable is > in those languages. My employer has us use the "m_" convention. I wonder why Bjarne made "this->" optional in the first place. From eddie at holyrood.ed.ac.uk Thu Jan 31 06:01:18 2008 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 31 Jan 2008 11:01:18 +0000 (UTC) Subject: Online Debugging References: Message-ID: Yansky writes: >I'm trying to debug a script on my server and it's taking forever >using print to find the error. I've tried to use the debugging >examples on this page http://webpython.codepoint.net/debugging but >they don't seem to be working for me. >Is there an easier/better way to debug online scripts? I was hoping >there might be something similar to php where it gives some error info >and the line code. One simple method might be something along these lines: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215 which I came across yesterday. Eddie From paddy3118 at googlemail.com Fri Jan 11 11:00:28 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 11 Jan 2008 08:00:28 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <41548a0d-eb74-4cd5-94b7-0ca11e691204@f3g2000hsg.googlegroups.com> <1199925201.586849@www.vif.com> <13oe3ijtbad01e4@corp.supernews.com> <05193522-df52-47d1-b9a0-b9e903b75222@k39g2000hsf.googlegroups.com> Message-ID: On Jan 11, 9:31 am, cokofree... at gmail.com wrote: > evenOrOdd = True > s1, s2 = "hi_cat_bye_dog_foo_bar_red", "" > > for i in s1: > if i == '_': > s2 += ':' if evenOrOdd else ',' > evenOrOdd = not evenOrOdd > else: > s2 += i > > print s2 > > Presently I cannot work out how to use .join instead of += ... Do s2 = [] then later: s2.append(i) and at the end: print ''.join(s2) - Paddy. > While I realise this is producing a new string (and I believe += > rebuilds it a lot?) how much slower > is this going to be over the others? From aaron.watters at gmail.com Tue Jan 1 16:26:13 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 1 Jan 2008 13:26:13 -0800 (PST) Subject: cloud computing (and python)? Message-ID: So, in between skiing runs I noticed a Business Week cover story on "cloud computing". The article had lots of interesting information in it like about how somebody's mom used to be an airline stewardess and the interior decor of various office spaces. It was a truly excellent piece of journalism. However it gave me no idea what "cloud computing" is and how it could be used to solve a computational problem. Could anyone on this list which usually has highly informed readers give me a clue at some level of technical detail what cloud computing is about and how it could be used. Bonus points if you mention Python in the response! An actual example would be great, if it's not web scraping and searching. - Aaron Watters == http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=snow From brkict at gmail.com Mon Jan 21 14:52:16 2008 From: brkict at gmail.com (glomde) Date: Mon, 21 Jan 2008 11:52:16 -0800 (PST) Subject: is it possible to set namespace to an object. References: <27529efd-b8d8-4a8e-b72d-379a607366b7@i7g2000prf.googlegroups.com> <4794dd6c$0$27198$9b4e6d93@newsspool1.arcor-online.net> <62e9433b-4f04-4020-b1e6-581496ba3f3e@s19g2000prg.googlegroups.com> <9b656006-3b97-4ee8-b992-ff06b970904b@q77g2000hsh.googlegroups.com> Message-ID: <6e6d0820-d7e1-4042-a75d-c193d133970b@u10g2000prn.googlegroups.com> On 21 Jan, 20:16, George Sakkis wrote: > On Jan 21, 1:56 pm, glomde wrote: > > > > > On 21 Jan, 18:59, Wildemar Wildenburger > > > wrote: > > > glomde wrote: > > > > Hi, > > > > > is it somehow possible to set the current namespace so that is in an > > > > object. > > > > [snip] > > > > set namespace testObj > > > > Name = "Test" > > > > > Name would set testObj.Name to "Test". > > > > > [snip] > > > > > Is the above possible? > > > > Don't know, sorry. But let me ask you this: Why do you want to do this? > > > Maybe there is another way to solve the problem that you want to solve. > > > The reason is that I do not want to repeat myself. It is to set up XML > > type like > > trees and I would like to be able to do something like. > > > with ElemA(): > > Name = "Top" > > Description "Blahaha..." > > with ElemB(): > > Name = "ChildA" > > Description "Blahaha..." > > .... > > > This would be the instead of. > > with ElemA() as node: > > node.Name = "Top" > > node.Description "Blahaha..." > > with ElemB() as node: > > node.Name = "ChildA" > > node.Description "Blahaha..." > > .... > > > So to save typing and have something that I think looks nicer. > > ... and more confusing for anyone reading the code (including you > after a few weeks/months). If you want to save a few keystrokes, you > may use 'n' instead of 'node' or use an editor with easy auto > completion. > > By the way, is there any particular reason for generating the XML > programmatically like this ? Why not have a separate template and use > one of the dozen template engines to populate it ? > > George I am not using it for XML generation. It was only an example. But the reason for using it programmatically is that you mix power of python with templating. Using for loops and so on. XIST(www.livinglogic.de) is doing something similar. But I would like the namespace thing. The above was only an example. And yes it might be confusing if you read the code. But I still want to do it, the question is it possible? From r.grimm at science-computing.de Sat Jan 5 05:06:21 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Sat, 5 Jan 2008 02:06:21 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: On Jan 4, 6:08 pm, Sion Arrowsmith wrote: > Hrvoje Niksic wrote: > > >BTW if you're using C++, why not simply use std::set? > > Because ... how to be polite about this? No, I can't. std::set is > crap. The implementation is a sorted sequence -- if you're lucky, > this is a heap or a C array, and you've got O(log n) performance. > But the real killer is that requirement for a std::set is that > T::operator< exists. Which means, for instance, that you can't > have a set of complex numbers.... > > -- Hallo and Sorry for being OT. As Arnaud pointed out, you must only overload the < Operator for the requested type. Something like bool operator < ( const Type& fir, const Type& sec ).... similar to python with __lt__ . The rest of magic will be done by the compiler/interpreter. Assoziative Arrays (set,map,multi_set,multi_map) in the classical STL are implemented as binary trees. Therefore the keys must be comparable and the access time is O(log n ). To get a dictionary with O(1), the most STL implementation support a extension called hash_set. The new standard TR1 support unsorted_set ... . You can download it from www.boost.org. Newer gcc runtimes also including the new subnamespace tr1. There is no need to implement set in c++ to get O(1). Greetings Rainer From meesters at uni-mainz.de Mon Jan 28 10:10:10 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Mon, 28 Jan 2008 16:10:10 +0100 Subject: extending Python - passing nested lists Message-ID: Hi, I would like to write a C-extension function for an application of mine. For this I need to pass a nested list (like: [[a, b, c], [d, e, f], ...], where all letters are floats) to the C-function. Now, with the code I have the compiler is complaining: "subscripted value is neither array nor pointer". Can somebody tell me what's wrong? Here a code snippet to reproduce this problem: static PyObject *_foo(PyObject *self, PyObject *args) { int i; long lenght; float ax, ay, az; PyObject *dummy_list; if (!PyArg_ParseTuple(args, "O", &dummy_list)) return NULL; dummy_list = PySequence_Fast(dummy_list, "argument must be iterable"); lenght = PyObject_Length(dummy_list); for (i=0; i < lenght; i++) { // part which does not work: ax = dummy_list[i][0]; ay = dummy_list[i][1]; az = dummy_list[i][2]; } return 0; } TIA Christian From ryszard.szopa at gmail.com Tue Jan 15 15:54:11 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Tue, 15 Jan 2008 12:54:11 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> <478D044D.1040406@skynet.be> Message-ID: <87846c00-1f44-4362-add1-54e5cfc094e9@u10g2000prn.googlegroups.com> On Jan 15, 8:06 pm, Helmut Jarausch wrote: > Unfortunately the links [2], [3] and [4] are not given, Luckily, there's Google :) [2] Article about MRO: http://www.python.org/download/releases/2.3/mro/ [3] Descriptor HowTo: http://users.rcn.com/python/download/Descriptor.htm [4] Articles about metaclasses (second one relevant to super): * http://www.ibm.com/developerworks/linux/library/l-pymeta.html, * http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/?S_TACT=105AGX03&S_CMP=ART, * http://www.ibm.com/developerworks/linux/library/l-pymeta3.html?S_TACT=105AGX03&S_CMP=ART Of course, it would be very nice if the article was updated to include the links. HTH, -- Richard From deets at nospam.web.de Tue Jan 15 04:47:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 Jan 2008 10:47:53 +0100 Subject: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net> <5v2cudF1k5a1oU1@mid.individual.net> <478c551a$0$36354$742ec2ed@news.sonic.net> Message-ID: <5v3dq9F1k2577U1@mid.uni-berlin.de> John Nagle wrote: > Benjamin wrote: >> On Jan 14, 6:26 pm, Bjoern Schliessmann > mail-0306.20.chr0n... at spamgourmet.com> wrote: >>> John Nagle wrote: >>>> It turns out that the strings in the "env" parameter have to be >>>> ASCII, not Unicode, even though Windows fully supports Unicode in >>>> CreateProcess. That's of course nonsense, they don't need to be ascii, they need to be byte-strings in whatever encoding you like. >>> Are you sure it supports Unicode, not UTF8 or UTF16? Probably using >>> something like u"thestring".encode("utf16") will help. >> Otherwise: bugs.python.org John's understanding of the differences between unicode and it's encodings is a bit blurry, to say the least. > Whatever translation is necessary should be done in "popen", which > has cases for Windows and POSIX. "popen" is supposed to be cross-platform > to the extent possible. I think it's just something that didn't get fixed > when Unicode support went in. Sure thing, python will just magically convert unicode to the encoding the program YOU invoke will expect. Right after we introduced the solve_my_problem() built-in-function. Any other wishes? If I write this simple program ------ test.py ------- import os import sys ENCODDINGS = ['utf-8', 'latin1'] os.env["MY_VARIABLE"].encode(ENCODINGS[int(sys.argv[1])]) ------ test.py ------- how's python supposed to know that suprocess.call("python test.py 0", env=dict(MY_VARIABLE=u'foo')) needs to be UTF-8? Diez From aahz at pythoncraft.com Wed Jan 2 23:29:57 2008 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2008 20:29:57 -0800 Subject: Two candies References: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com> Message-ID: In article <78662711-83fe-47ae-9dfa-d55d710bcdac at i3g2000hsf.googlegroups.com>, wrote: > >2) When I use MatchObjects I have to look at the docs to remember the >difference between group() and groups() etc. So I suggest to add a >__getitem__ method to MatchObject, so this: > >mo[3] > >Equals to: > >mo.group(3) Patches are wonderful, but if not, please post this RFE to the bug tracker. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From lasses_weil at klapptsowieso.net Wed Jan 30 09:18:32 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Wed, 30 Jan 2008 15:18:32 +0100 Subject: optional static typing for Python In-Reply-To: References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> <479e0225$0$36389$742ec2ed@news.sonic.net> <70c4064a-a65d-4fd5-b39c-38e6a3fb567b@i7g2000prf.googlegroups.com> <479fb907$0$25376$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <47a08738$0$9108$9b4e6d93@newsspool2.arcor-online.net> Kay Schluehr wrote: > On Jan 30, 12:38 am, Wildemar Wildenburger > wrote: >>> Python has a JIT right no >> You mean in the Java-sense (outputting native machine code)? >> >> /W > > Sure. > > http://psyco.sourceforge.net/ > Oh, switcheroo! :) /W From theller at ctypes.org Tue Jan 22 08:42:43 2008 From: theller at ctypes.org (Thomas Heller) Date: Tue, 22 Jan 2008 14:42:43 +0100 Subject: ctypes CDLL - which paths are searched? In-Reply-To: <4795E88F.7050406@igpm.rwth-aachen.de> References: <4794d573$0$2980$ba620e4c@news.skynet.be> <4795E88F.7050406@igpm.rwth-aachen.de> Message-ID: Helmut Jarausch schrieb: > Thomas Heller wrote: >> Helmut Jarausch schrieb: >>> Hi, >>> >>> how can I specify the paths to be searched for a dynamic library >>> to be loaded by ctypes' CDLL class on a Linux system. >>> >>> Do I have to set os.environment['LD_LIBRARY_PATH'] ? >>> >> >> ctypes passes the argument given to CDLL(path) straight to >> the dlopen(3) call, so your system documentation should tell you. >> > > Thanks, > > but then it's difficult to use CDLL. Setting > os.environ['LD_LIBRARY_PATH'] within the script which > calls CDLL is too late. > What other methods are possible rather than put an explicit > export LD_LIBRARY_PATH=... > before running the script, if I don't want to put the dynamic > library into a standard system library. I guess you can also use an absolute pathname (but the dlopen(3) manpage should tell you more. I'm not too familiar with linux). Thomas From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 21 13:19:59 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 19:19:59 +0100 Subject: Default attribute values pattern In-Reply-To: <41f8394c-342c-42dc-9bf2-a737b572aff9@c4g2000hsg.googlegroups.com> References: <4794697f$0$16980$426a74cc@news.free.fr> <41f8394c-342c-42dc-9bf2-a737b572aff9@c4g2000hsg.googlegroups.com> Message-ID: <4794e206$0$4429$426a74cc@news.free.fr> cokofreedom at gmail.com a ?crit : >> Grab(argdict, key, default) is argdict.pop(key, default) > > "pop() raises a KeyError when no default value is given and the key is > not found." Then use it with a default value !-) >> def grab(kw, key, default=None): >> try: >> return kw.pop(key) >> except KeyError: >> return default > > So Bruno's technique seems to me to be the correct one as it catches > the KeyError. Note that I cancelled the message (too bad, doesn't work everywhere). I totally agree with Arnaud on this, and should sometimes re-read the doc for stuff I use so often I think I know them. From gagsl-py2 at yahoo.com.ar Wed Jan 23 16:14:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 19:14:00 -0200 Subject: HTML parsing confusion References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> <50269e4a-af44-4d73-b6cb-c42af6b5164d@e10g2000prf.googlegroups.com> <5vmkiiF1nadr7U1@mid.uni-berlin.de> <38176c81-a9b1-40dc-8bbe-25c5b3f4a75a@p69g2000hsa.googlegroups.com> Message-ID: En Wed, 23 Jan 2008 10:40:14 -0200, Alnilam escribi?: > Skipping past html validation, and html to xhtml 'cleaning', and > instead starting with the assumption that I have files that are valid > XHTML, can anyone give me a good example of how I would use _ htmllib, > HTMLParser, or ElementTree _ to parse out the text of one specific > childNode, similar to the examples that I provided above using regex? The diveintopython page is not valid XHTML (but it's valid HTML). Assuming it's property converted: py> from cStringIO import StringIO py> import xml.etree.ElementTree as ET py> tree = ET.parse(StringIO(page)) py> elem = tree.findall('//p')[4] py> py> # from the online ElementTree docs py> http://www.effbot.org/zone/element-bits-and-pieces.htm ... def gettext(elem): ... text = elem.text or "" ... for e in elem: ... text += gettext(e) ... if e.tail: ... text += e.tail ... return text ... py> print gettext(elem) The complete text is available online. You can read the revision history to see what's new. Updated 20 May 2004 -- Gabriel Genellina From ram.rachum at gmail.com Wed Jan 23 09:10:07 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Wed, 23 Jan 2008 06:10:07 -0800 (PST) Subject: A GUI framework for running simulations Message-ID: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com> Hello! I am currently working on writing a simulation engine for special relativity physics. I'm writing it in Python, of course. I'm doing fine with the engine, but I want a GUI framework in which I could use it conveniently, and test different setups on it. I'm not so strong with GUI programming. I looked at Tkinter, I looked at WxPython, I looked at PythonCard. It all looks pretty daunting. My question is, does there exist a GUI package that is intended specifically for simulations? I saw a program called Golly, which is a simulation for Conway's Game of Life. Its GUI had most of the features I needed. For example, you can load a setup, there are "play" and "stop" buttons, you can change a setup and save it, etc. So does anyone know of a general GUI framework for running simulations? From marekjed at pobox.INVALID.com Mon Jan 28 06:48:57 2008 From: marekjed at pobox.INVALID.com (marek jedlinski) Date: Mon, 28 Jan 2008 12:48:57 +0100 Subject: Can xml.sax NOT process the DTD? Message-ID: I'm using xml.sax to extract certain content from xml files. (Background: my job is software localization; these are bilingual xml files, from which I need to extract translated text, e.g. for spellchecking). It works fine, unless a particular file has a doctype directive that specifies a DTD. The parser then bails out, because the dtd is not available (IOError, file not found). Since I don't have the DTDs, I need to tell the SAX parser to ignore the doctype directive. Is this possible, please? I've noticed that I can eliminate the error if I create 0-byte dtd files and put them where the parser expects to find them, but this is a little tedious, since there are plenty of different DTDs expected at different locations. Or is there another SAX parser for Python I could use instead? Kind thanks for any suggestions, .marek -- No ads, no nags freeware: http://www.tranglos.com From walterbyrd at iname.com Wed Jan 30 15:27:16 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 30 Jan 2008 12:27:16 -0800 (PST) Subject: Trying to understand Python web-development References: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com> <2bb822db-0a33-4c47-bdd1-f4980a73fc00@m34g2000hsf.googlegroups.com> Message-ID: <85a24948-9e59-4b74-95e8-6d9c75e9bff7@e23g2000prf.googlegroups.com> Thanks for all that posts. This thread has been helpful. I have seen a lot of posts about the importance of decoupling the deployment technologies from the framework technologies. This is how I have done that in PHP. I develop on my home box. When I get something working the way I want, I ftp those files to the remote server. To me, that seems to make more sense that trying to run two different web servers on the same system. My PHP system involves no monkeying with special config files, or running special servers to couple the different environments, or setting special ports, or paths. For PHP development, I don't even need ssh access. > I think that this (the ease of PHP application deployment) is one of the things that keeps Python framework developers up at night I think you may have something there. For $10 a year I can get an account at dollar-hosting.net, copy some php files there, and that's all there to it. I have been beating my brains out trying to get anything working with a python framework, and I have not been able to do it. I even bought VPS hosting just for the sake of python development. But, I still can not seem to make the quantum leap of getting something that works locally, to work remotely. BTW: with the VPS hosting, I had to install and configure my own web-hosting and PHP, including setting up lighttpd with fastcgi and php modules - and I still found that much easier than getting anything to work with python. From rick.arnett at gmail.com Mon Jan 28 11:15:01 2008 From: rick.arnett at gmail.com (the_ricka) Date: Mon, 28 Jan 2008 08:15:01 -0800 (PST) Subject: SMTP Sending Mail Problem Message-ID: <9b00a5f5-277d-4d23-be82-60c2aafc4227@c23g2000hsa.googlegroups.com> Hi all, I'm fairly new to python, but very excited about it's potential. I'm trying to write a simple program that will accept input from a command line and send email. The parameters I used on the command line are for From address, To addresses, Subject and Body. For the body, I thought it would be better to read the input from a file so I could allow someone to nicely format the body with newlines in a text editor and just read it into a string and send it. However, whenever I try to read more than one line from the file, the email is not being delivered. The only reason I know this is because I tried just reading in the first line of the text file, and the email sent fine. Right now I believe this must have something to do with new line characters at the end of each line, but it doesn't quite make sense to me why this is a problem, as I have also used the same script and just created a string in it with multiple lines (\r\n) and sent it and the email sends fine. To complicate the issue further, I have turned used the set_debuglevel method so I can see the output from the SMTP server, and it appears that the message was Queued for mail delivery. The SMTP server we are using is Exchange if that matters. I have listed the code below, along with output from the SMTP server. Any help would be much appreciated. (Note, I don't typically read in the file with a range(n) iterator, but that is how I have noticed that I can send only one line, but not send multiple lines. As soon as I change the range value to 1, the email will successfully send the first line of the text file). import sys,smtplib if len(sys.argv) != 5: print """ Usage: sendmail FROM RECIPIENTS SUBJECT BODY RECIPIENTS should be a semicolon delimited list of email addresses. BODY should be a file where the message to send is stored Use double quotes to surround the SUBJECT element if it is more than one word """ exit() fromaddr = sys.argv[1] toaddrs = sys.argv[2].split(";") subject = sys.argv[3] body = "" print toaddrs print type(toaddrs) try: infile = open(sys.argv[4], 'r') for i in range(4): body = body + infile.readline() except IOError: print "Can't open the given file, please try again" exit() headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs), subject) msg = headers + body server = smtplib.SMTP('##############') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() Output: send: 'ehlo hplaptopr.############.com\r\n' reply: '250-################.com Hello [10.#.#.#]\r\n' reply: '250-SIZE 20971520\r\n' reply: '250-DSN\r\n' reply: '250-VRFY\r\n' reply: '250-AUTH GSSAPI NTLM LOGIN\r\n' reply: '250-AUTH=LOGIN\r\n' reply: '250 OK\r\n' reply: retcode (250); Msg: ################.com Hello [10.#.#.#] SIZE 20971520 DSN VRFY AUTH GSSAPI NTLM LOGIN AUTH=LOGIN OK send: 'mail FROM:<######@######.com> size=116\r\n' reply: '250 2.1.0 #######@######.com....Sender OK\r\n' reply: retcode (250); Msg: 2.1.0 ######@######.com....Sender OK send: 'rcpt TO:<######@######.com>\r\n' reply: '250 2.1.5 ######@######.com \r\n' reply: retcode (250); Msg: 2.1.5 #######@######.com send: 'data\r\n' reply: '354 Start mail input; end with .\r\n' reply: retcode (354); Msg: Start mail input; end with . data: (354, 'Start mail input; end with .') send: 'From: #######@######.com\r\nTo: ######@######.com\r\nSubject: Test1\r\n\ r\nThis is from the file\r\nThis concludes our test\r\n\r\n\r\n.\r\n' reply: '250 2.6.0 <############@###############.com> Qu eued mail for delivery\r\n' reply: retcode (250); Msg: 2.6.0 <##########@n#########.com> Queued mail for delivery data: (250, '2.6.0 <########@################.com> Q ueued mail for delivery') send: 'quit\r\n' reply: '221 2.0.0 ################.com Service closing transmission cha nnel\r\n' reply: retcode (221); Msg: 2.0.0 #################.com Service closing t ransmission channel From deets at nospam.web.de Sun Jan 27 12:50:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jan 2008 18:50:06 +0100 Subject: REALLY simple xml reader In-Reply-To: References: Message-ID: <603uikF1npdtkU1@mid.uni-berlin.de> Simon Pickles schrieb: > Hi > > Can anyone suggest a really simple XML reader for python? I just want to > be able to do something like this: > > xmlDoc = xml.open("file.xml") > element = xmlDoc.GetElement("foo/bar") > > ... to read the value of: > > > 42 > Since python2.5, the ElementTree module is available in the standard lib. Before 2.5, you can of course install it. Your code then would look like this: import xml.etree.ElementTree as et doc = """ 42 """ root = et.fromstring(doc) for bar in root.findall("bar"): print bar.text Diez From peterbe at gmail.com Wed Jan 16 19:13:41 2008 From: peterbe at gmail.com (Peter Bengtsson) Date: Wed, 16 Jan 2008 16:13:41 -0800 (PST) Subject: ElementTree and namespaces in the header only References: <2c769fe0-8add-4aa1-9657-b8ee5f76cb91@k39g2000hsf.googlegroups.com> Message-ID: <078052fc-ca12-4528-9113-5add7979c446@1g2000hsl.googlegroups.com> On Jan 15, 5:22 pm, Fredrik Lundh wrote: > Peter Bengtsson wrote: > > root = Element('feed', xmlns='http://www.w3.org/2005/Atom') > > root.set('xmlns:se', NS_URL) > > entry = SubElement(root, 'entry') > > SubElement(root, 'title').text = 'Title' > > SubElement(entry, SEN('category')).text = 'Category' > > But surely the xmlns:se attribute on the tag is > > excessive since the namespace (by the URI) is already defined in the > > tag. How do I set non-default namespace tags in elements > > without the automatic xmlns:se attribute repeated each time? > > ET 1.2's standard serializer doesn't take explicitly setnamespacesinto > account. If you want full control over namespace generation, you have > to do it yourself: > > http://effbot.org/zone/element-namespaces.htm#explicitly-setting-name... > > ET 1.3 provides a default_namespace option for this specific case (but > you still have to use universal names for everything that should go into > the default namespace). > > That's perfect Fredrik. Exactly what I was looking for. From arnodel at googlemail.com Thu Jan 24 02:27:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 23:27:17 -0800 (PST) Subject: Creating new types and invoking super References: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> <9eeb9667-f362-4ce2-971a-42ef639c8f86@c4g2000hsg.googlegroups.com> Message-ID: <185eb303-f233-4fcc-a45b-f2680618bb11@z17g2000hsg.googlegroups.com> On Jan 24, 7:19?am, Arnaud Delobelle wrote: Oops again > > Change this line to: > ? ? ? ? ? ? ? getattr(super.cls, obj), self.f.__name__)() I mean getattr(super(self.cls, obj), self.f.__name__)() -- Arnaud From matiassurdi at gmail.com Thu Jan 10 10:11:42 2008 From: matiassurdi at gmail.com (Matias Surdi) Date: Thu, 10 Jan 2008 16:11:42 +0100 Subject: importing module conflict In-Reply-To: <8763y1izrj.fsf@benfinney.id.au> References: <8763y1izrj.fsf@benfinney.id.au> Message-ID: Ben Finney escribi?: > Matias Surdi writes: > >> Suppose I've a module named "urllib" and from it I need to import >> the urllib module from the python standart library. > > What you want is the "absolute import" behaviour, described in PEP 328 > and implemented in > Python 2.5 . > Thanks a lot. That was exactly what I was looking for.Excellent. From dima.hristov at gmail.com Mon Jan 21 07:56:29 2008 From: dima.hristov at gmail.com (DHR) Date: Mon, 21 Jan 2008 04:56:29 -0800 (PST) Subject: Q: paramiko/SSH/ how to get a remote host_key References: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> Message-ID: I am connecting from a WindowsXP SP2 machine. When using Putty as an SSH client, if you connect for the first time then you get somethign like this: ''' The server's host key is not cached in the registry. You have no guarantee that the server is the computer you think it is. The server's rsa2 key fingerprint is: ssh-rsa 1024 7b:e5:6f:a7:f4:f9:81:62:5c:e3:1f:bf:8b:57:6c:5a If you trust this host, hit Yes to add the key to PuTTY's cache and carry on connecting. If you want to carry on connecting just once, without adding the key to the cache, hit No. If you do not trust this host, hit Cancel to abandon the connection. ''' If I get it correctly, Putty is using such a command to recieve the host_key the first time it connects to a remote SSH server. Then it stores it into the registry. The question is how can I do it from Python? Guilherme Polo wrote: > 2008/1/21, DHR : > > I'm trying to run the simpliest example form paramiko readme(Homepage: > > http://www.lag.net/paramiko/), and > > cannot find out how to get the remote SSH server host_key. > > > > > > This is the code. It is supposed to connect to a remote SSH host and > > execute an 'ls' command: > > > > import paramiko, base64 > > > > key = paramiko.RSAKey(data=base64.decodestring('AAA...')) > > client = paramiko.SSHClient() > > client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key) > > client.connect('227.112.168.273', username='uname', password='pass') > > stdin, stdout, stderr = client.exec_command('ls') > > for line in stdout: > > print '... ' + line.strip('\n') > > > > client.close() > > > > Now, if I understand it correctly I need to get somehow the host_key > > from the server and > > write it insted of the 'AAA...' thing. Is there a command to get the > > host_key from a remote SSH > > server? > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > You need a key to connect to that server, so you should want this: > > keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) > > Then keys[hostname] should contain a RSAKey object that you are looking for > > > -- > -- Guilherme H. Polo Goncalves From rndblnch at gmail.com Fri Jan 25 08:49:40 2008 From: rndblnch at gmail.com (rndblnch) Date: Fri, 25 Jan 2008 05:49:40 -0800 (PST) Subject: is possible to get order of keyword parameters ? Message-ID: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> (sorry, draft message gone to fast) i.e. is it possible to write such a function: def f(**kwargs): return result such as : f(x=12, y=24) == ['x', 'y'] f(y=24, x=12) == ['y', 'x'] what i need is to get the order of the keyword parameters inside the function. any hints ? thanks, renaud From roy at panix.com Sun Jan 27 20:41:59 2008 From: roy at panix.com (Roy Smith) Date: Sun, 27 Jan 2008 20:41:59 -0500 Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: In article , ajaksu wrote: > On Jan 27, 10:32 pm, Paddy wrote: > > I would value the opinion of fellow Pythoneers who have also > > contributed to Wikipedia, on the issue of "Is Python Standardized". > > Specifically in the context of this table: > > http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Gene... > > (Comparison of programming languages) > > And this entry in the talk page > > http://en.wikipedia.org/wiki/Talk:Comparison_of_programming_languages... > > (Talk:Comparison of programming languages#Standardized Python?) > > > > - Thanks. > > Hmmm. Seems to me that "Is X Standardized" in the given context means > having a formal, published standard issued by some Standards > organization. That's exactly what it means. For example, if I'm buying a C++ compiler, I can specify in the contract, "Must comply with ISO 14882", and everybody will know what I'm talking about. On the other side of the fence, if I'm a free-lance C++ developer, I can specify to my customers that the code I write will work properly when compiled with a compiler that meets ISO 14882. Whether such a compiler actually exists, is besides the point :-) Python has no such standard. Sure, there's the stuff on docs.python.org, but it's kind of hard to write a contract which says, "Must comply with the stuff on docs.python.org", and have it be meaningful in a legal sense. So, I think the "No" in the "Standardized?" column for python is exactly right. That's not to say you can't have something good which isn't standardized. Sometimes standards committees even go off into left field and field break stuff in the process of standardizing it. Some things have so many different standards (i.e. the pletora of unix standards), it's almost worthless to say it's standardized. But, as it stands, the Wikipedia article is correct. From wdraxinger at darkstargames.de Sat Jan 19 18:19:24 2008 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sun, 20 Jan 2008 00:19:24 +0100 Subject: HTTP POST uploading large files Message-ID: I'm thinking about writing a script to upload videos to sites like YouTube or Google Video, which is usually done by a HTTP POST. The problem is, that videos, by nature are rather big files, however urllib2 wants it's Request objects being prepared beforehand, which would mean to first load the whole file to memory. I looked into pycURL, knowing that cURL can POST send files directily from the file system, however pycURL doesn't expose the neccesary functions yet. Am I just blind for some urllib2/httplib feature, or some other library? Or do I really have to fiddle around with sockets myself (I hope not...). Thanks in advance Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From icarr at compx.com Wed Jan 2 14:11:07 2008 From: icarr at compx.com (Israel Carr) Date: Wed, 2 Jan 2008 14:11:07 -0500 Subject: database query - logic question Message-ID: <6A85AD3923D6C348AF108B4A8F459EA201BEFD3B@CIXMX1.compxnet.com> Thanks for anyone who takes the time to read this. If I posted to the wrong list, I apologize and you can disregard. I need help with a script to pull data from a postgres database. I'm ok with the database connection just not sure how to parse the data to get the results I need. I'm running Python 2.4.4. For what it's worth, once I can get my logic correct I'll be publishing the reports mentioned below via zope for web clients. Here is a small sample of the records in the table: name date time status machine1 01/01/2008 13:00:00 system ok machine1 01/01/2008 13:05:00 system ok machine1 01/01/2008 13:10:00 status1 machine1 01/01/2008 13:10:30 status1 machine1 01/01/2008 13:11:00 system ok machine1 01/01/2008 13:16:30 status2 machine1 01/01/2008 13:17:00 status2 machine1 01/01/2008 13:17:30 status2 machine1 01/01/2008 13:18:00 status2 machine1 01/01/2008 13:18:30 status2 machine1 01/01/2008 13:19:00 system ok machine1 01/01/2008 13:24:00 status2 machine1 01/01/2008 13:24:30 status2 machine1 01/01/2008 13:25:00 system ok I need to report from this data. The detail report needs to be something like: machine1 01/01/2008 13:10:00 status1 00:01:30 machine1 01/01/2008 13:16:30 status2 00:02:30 machine1 01/01/2008 13:24:00 status2 00:01:00 and the summary needs to be machine1 01/01/2008 total 'status1' time = 00:01:30 machine1 01/01/2008 total 'status2' time = 00:03:30 _____ machine1 01/01/2008 total 'non-OK' time = 00:05:00 #this is the sum of status1 and status2 times The 'machine1' system is periodically checked and the system status is written to the database table with the machinename/date/time/status. Everything that isn't a 'system ok' status is bad. For me to determine the amount of time a machine was in a bad status I'm taking the first time a machine has a 'system ok' status after a bad status and subtracting from that time the time that a machine first went into that bad status. From my table above: machine1 went into 'status2' status at 13:16:30 and came out of 'status2' to a 'system ok' status at 13:19:00. So the downtime would be 13:19:00 - 13:16:30 = 00:02:30 I'm not sure how to query when a 'bad' status is found to find the next 'good' status and calculate based on the times. Essentially, I need help creating the reports mentioned above. Your questions may also help clarify my fuzzy description. Thanks for any help. Reply with questions. Israel From bdesth.quelquechose at free.quelquepart.fr Mon Jan 7 15:08:07 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 07 Jan 2008 21:08:07 +0100 Subject: TIOBE declares Python as programming language of 2007! In-Reply-To: <5uempsF1gt5cbU1@mid.uni-berlin.de> References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> <5uempsF1gt5cbU1@mid.uni-berlin.de> Message-ID: <478286a2$0$23176$426a74cc@news.free.fr> Diez B. Roggisch a ?crit : > Berco Beute schrieb: > >> Cool! We knew it would happen one day :) >> What could be the reason? Python 3? Jython 2.2? Java's loss of >> sexiness? > > > I'd say Java was never sexy, but dressed up in expensive lingerie by > marketing maniacs... +2 QOTW > Diez From richie at entrian.com Fri Jan 4 04:34:48 2008 From: richie at entrian.com (Richie Hindle) Date: Fri, 04 Jan 2008 09:34:48 +0000 Subject: urllib2 disable proxy In-Reply-To: <200801022303.53722.jimis@gmx.net> References: <200801022303.53722.jimis@gmx.net> Message-ID: Hi Dimitris, > I've been looking for a way to explicitly disable the use of proxies with > urllib2, no matter what the environment dictates. Unfortunately I can't find > a way [...] Would changing the environment work? Like this: >>> del os.environ['http_proxy'] >>> do_stuff_with_urllib2() -- Richie Hindle richie at entrian.com From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 22 04:23:32 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 22 Jan 2008 10:23:32 +0100 Subject: Trouble writing to database: RSS-reader In-Reply-To: <92b8934d-7b8b-4ca0-bcdd-1b4cd4853f1f@p69g2000hsa.googlegroups.com> References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> <4794e0f9$0$4429$426a74cc@news.free.fr> <739742b0-7d3d-4039-b793-ccefae4be721@1g2000hsl.googlegroups.com> <47951982$0$2681$426a74cc@news.free.fr> <92b8934d-7b8b-4ca0-bcdd-1b4cd4853f1f@p69g2000hsa.googlegroups.com> Message-ID: <4795b5c8$0$20146$426a74cc@news.free.fr> MRAB a ?crit : > On Jan 21, 9:15 pm, Bruno Desthuilliers > wrote: >> Arne a ?crit : (snip) >>> So, I shouldn't use this techinicke (probably wrong spelled) >> May I suggest "technic" ?-) > > That should be "technique"; just ask a Francophone! :-) My bad :( From nick at craig-wood.com Thu Jan 24 04:30:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 24 Jan 2008 03:30:05 -0600 Subject: A GUI framework for running simulations References: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com> Message-ID: Martin Manns wrote: > If you want to keep things simple, pygame could be an alternative for > visualizing simulations and setting parameters even though it does not > provide all these fancy widgets around. I'd second that. pygame will give you a window you can draw on which you can plot the result of your simulation. You can draw a few buttons (like play and stop) and detect clicks in them very easily. If you want loads of parameters then you'll either need to reach for a GUI toolkit or roll your own menuing system for pygame (which isn't that hard). -- Nick Craig-Wood -- http://www.craig-wood.com/nick From robin at NOSPAMreportlab.com Sun Jan 20 14:18:34 2008 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sun, 20 Jan 2008 19:18:34 +0000 Subject: bitmap problem In-Reply-To: <47935374.3010203@jessikat.plus.net> References: <47935374.3010203@jessikat.plus.net> Message-ID: <47939E8A.8080207@jessikat.plus.net> Robin Becker wrote: > I'm having trouble with defining a completely transparent bitmap > for use as a stipple in a canvas > > ....... after a bit of searching I find that stipples cannot be created with the tk image command; for non-standard stipples you need to use a file. -- Robin Becker From bronger at physik.rwth-aachen.de Tue Jan 15 16:01:59 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 15 Jan 2008 22:01:59 +0100 Subject: ElementTree and namespaces in the header only References: <2c769fe0-8add-4aa1-9657-b8ee5f76cb91@k39g2000hsf.googlegroups.com> Message-ID: <87sl0y7qgo.fsf@physik.rwth-aachen.de> Hall?chen! Fredrik Lundh writes: > Peter Bengtsson wrote: > >> root = Element('feed', xmlns='http://www.w3.org/2005/Atom') >> root.set('xmlns:se', NS_URL) >> entry = SubElement(root, 'entry') >> SubElement(root, 'title').text = 'Title' >> SubElement(entry, SEN('category')).text = 'Category' > >> But surely the xmlns:se attribute on the tag is >> excessive since the namespace (by the URI) is already defined in the >> tag. How do I set non-default namespace tags in elements >> without the automatic xmlns:se attribute repeated each time? > > ET 1.2's standard serializer doesn't take explicitly set namespaces > into account. If you want full control over namespace generation, > you have to do it yourself: > > http://effbot.org/zone/element-namespaces.htm#explicitly-setting-namespace-attributes > > ET 1.3 provides a default_namespace option for this specific case > (but you still have to use universal names for everything that > should go into the default namespace). I've worked with Saxon for a couple of years, and it tries to generate the "minimal" (well, sort of) XML file possible: It uses the prefixes given in the source XSLT file rather than generating something, and detects implicitly set namespaces, thus avoiding spitting them out again. Wouldn't this be an option for ET, too? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From paul.hankin at gmail.com Tue Jan 22 17:33:43 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 22 Jan 2008 14:33:43 -0800 (PST) Subject: difflib confusion References: Message-ID: <07ba2b13-31ff-4ba9-8f6f-2fd1e11dcd59@d70g2000hsb.googlegroups.com> On Jan 22, 6:57?pm, "krishnakant Mane" wrote: > hello all, > I have a bit of a confusing question. > firstly I wanted a library which can do an svn like diff with two files. > let's say I have file1 and file2 where file2 contains some thing which > file1 does not have. ?now if I do readlines() on both the files, I > have a list of all the lines. > I now want to do a diff and find out which word is added or deleted or changed. > and that too on which character, if not at least want to know the word > that has the change. > any ideas please? Have a look at difflib in the standard library. -- Paul Hankin From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 18:21:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 11 Jan 2008 23:21:48 -0000 Subject: python recursive function References: <01c6fa55-3836-4d92-aaf4-02fec7fa529c@l6g2000prm.googlegroups.com> Message-ID: <13ofugcsm9msa6f@corp.supernews.com> On Fri, 11 Jan 2008 06:30:04 -0600, Nick Craig-Wood wrote: > HYRY wrote: >> def bears (n): >> if n==42: >> return True ... >> return False > > Almost but you missed a case... Why are you people doing the OP's homework for him? And then DEBUGGING it as well? Haven't you got something better to do than to help create a new generation of incompetent, under-educated programmers? -- Steven From george.sakkis at gmail.com Tue Jan 15 16:45:59 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 15 Jan 2008 13:45:59 -0800 (PST) Subject: Perl Template Toolkit: Now in spicy new Python flavor References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> Message-ID: <13a75830-5416-4fe3-9460-018e1240e6e6@e32g2000prn.googlegroups.com> On Jan 15, 3:15 pm, Joshua Kugler wrote: > eef... at gmail.com wrote: > > I'd like to inform the Python community that the powerful and popular > > Template Toolkit system, previously available only in its original > > Perl implementation, is now also available in a beta Python > > implementation: > > >http://tt2.org/python/index.html > > > I created this port both as a fun programming project, and for use in > > environments where Perl is not available, for reasons technical, > > cultural, or otherwise. The extensive Perl test suites have also been > > ported, and most templates require no or very little modification. > > I must say...wow. That would have saved me some time and hassle about a > year ago, but of course, I wouldn't have fell in love with pure XML > templates either. :) As someone who has used Template Toolkit quite a bit, > I must say that is is quite cool. Congrats on a job well done! > > j How does it compare with other "mainstream" Python template engines such as Cheetah, Mako, etc. ? Unless I missed it, the documentation covers the Perl version only. George From mraborife at yahoo.com Mon Jan 7 08:57:17 2008 From: mraborife at yahoo.com (mpho raborife) Date: Mon, 7 Jan 2008 05:57:17 -0800 (PST) Subject: python syntax Message-ID: <606127.72912.qm@web45504.mail.sp1.yahoo.com> I need help with the following: os.system("gmmscore"+"-i" + Input + "-l" + List + "-t" + str(modeltype) + "-m" + str(mixture) + "-d" + str(dimension) + "-v" + str(vfloor) + "-n" + str(number) + "-r" + results) --------------------------------- Never miss a thing. Make Yahoo your homepage. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Sat Jan 19 02:02:42 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 19 Jan 2008 07:02:42 +0000 Subject: What is a shortcut to the Default home directory in Windows In-Reply-To: References: <1f85750e-a85a-4bb5-8f20-cbb5939f89a3@p69g2000hsa.googlegroups.com> <1fddf38d-e6a2-416f-a8f8-020560970ab5@z17g2000hsg.googlegroups.com> Message-ID: <4791A092.7090704@timgolden.me.uk> Christian Heimes wrote: > Mike Driscoll wrote: >> I personally use Tim Golden's excellent win32 API wrapper, the >> winshell script. You can find it here: >> >> http://timgolden.me.uk/python/winshell.html > > Yeah. Tim's winshell is fine but it's not using the official win32 api. Umm... Is it not? The only thing I'm aware of doing is retaining backwards compat. by using SHGetPathFromIDList on the SHGetSpecialFolderLocation because I was writing against Win9x at the time. Or are you saying something else? (Admit I haven't checked all the docs since I wrote it to see what's been "deprecated" this week). TJG From bernhard.merkle at googlemail.com Fri Jan 4 08:24:40 2008 From: bernhard.merkle at googlemail.com (Bernhard Merkle) Date: Fri, 4 Jan 2008 05:24:40 -0800 (PST) Subject: pydepend (checking dependencies like jdepend) ? References: <1969e240-9e80-4df1-b085-7956dfa4f7ae@t1g2000pra.googlegroups.com> Message-ID: <71a1c5ae-2051-44ff-998e-a342fa88ffab@e25g2000prg.googlegroups.com> On Jan 4, 1:57 pm, "Stefan Schukat" wrote: > Hi, > > try to look at py2exe. This module scans all dependencies to pack them > into one executable. my intention is to _know_ (or display or list or whatever) the dependencies. (see also my original posting). The aim is to control and have a view on modularization and e.g. avoid unnecessary bidirectional dependencies etc. does py2.exe display such information ? Berni. From fredrik at pythonware.com Thu Jan 3 03:44:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 09:44:30 +0100 Subject: shelve and nested dictionaries In-Reply-To: References: Message-ID: Matthew Schibler wrote: > I'm a newbie to Python, with some experience using perl (where I used > nested arrays and hashes extensively). I am building a script in > python for a MUD I play, and I want to use the shelve module to store > persistent information between script executions. The following code > does not work for me, > > import shelve, sys, os, string > db = shelve.open(os.path.abspath(os.path.dirname(sys.argv[0])) + '/' + > 'sandbox.dat', 'c') > db['JustSomeVariable'] = 'apple' > db['subdb'] = {} > db['subdb']['anotherdict'] = {} > db['subdb']['anotherdict']['bleh'] = 'hello world' > db.close() > > of course, that's just a working example but it illustrates the > problem i'm having. I think shelve objects act like dictionaries in a > way, at least they seem to have dictionary keys beneath them. the shelve module only tracks changes to the shelf itself (i.e. db[key]), not changes to to mutable objects stored in the shelve). to change a mutable object, you have to fetch it, modify it, and then write it back: value = db[key] ... update value ... db[key] = value in Python 2.3 and later, the shelve can help you with this, to some extent; from the help page: To avoid the problem with mutable entries, you may pass the keyword argument writeback=True in the call to shelve.open. When you use: d = shelve.open(filename, writeback=True) then d keeps a cache of all entries you access, and writes them all back to the persistent mapping when you call d.close(). This ensures that such usage as d[key].append(anitem) works as intended. However, using keyword argument writeback=True may consume vast amount of memory for the cache, and it may make d.close() very slow, if you access many of d's entries after opening it in this way: d has no way to check which of the entries you access are mutable and/or which ones you actually mutate, so it must cache, and write back at close, all of the entries that you access. You can call d.sync() to write back all the entries in the cache, and empty the cache (d.sync() also synchronizes the persistent dictionary on disk, if feasible). From paul.hankin at gmail.com Wed Jan 9 08:22:55 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 9 Jan 2008 05:22:55 -0800 (PST) Subject: flatten sequences in a dictionary References: Message-ID: On Jan 9, 1:16 pm, ajcpp... at gmail.com wrote: > Hi > > I wondering if someone could give me a pointer. I have a dictionary > with the following structure: > > testDict = dict(foo=((1,2,3),(1,4,3)), bar=((3,2,1),(9,8,7,)), > mumble=((1,2,3),)) > > I am trying to create a list of the the 3 element tuples using > itertools (just for a bit of fun). I'm trying this: > > list(itertools.chain(testDict.itervalues()) Close! Try: list(itertools.chain(*testDict.itervalues()) -- Paul Hankin From MartinRinehart at gmail.com Fri Jan 25 13:14:27 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Fri, 25 Jan 2008 10:14:27 -0800 (PST) Subject: Operator overloading Message-ID: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com> If it were my choice, the plus sign would do this: def itemadd( i1, i2 ): if ( type(i1) == str ) or ( type(i2) == str ): return str(i1) + str(i2) else: return i1 + i2 I'd like to redefine it so it works my way but operator overloading seems strictly confined to classes I create. Is there a way? Or do I just have to grump, "Even a kludge like Perl ..."? From kyosohma at gmail.com Wed Jan 2 09:25:07 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 2 Jan 2008 06:25:07 -0800 (PST) Subject: wxpython application ( problem ? ) References: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> Message-ID: <1d8d6374-fbd0-4292-a5d3-82e8791bd9a3@e6g2000prf.googlegroups.com> On Jan 2, 5:24 am, vedrandeko... at gmail.com wrote: > Hello, > > Here is sample of my simple script with wxpython and modules: > subprocess,threading, directpython....... > > Code sample: > > import wx > import wx.aui > app=wx.App() > frame=wx.Frame(None,title="New project") > > #There is also part with wx.aui > > frame.Show() > app.MainLoop() > > After a few minutes wx application does destroy. Any ides why? I highly recommend reading this wxPython wiki entry about using threads in wxPython: http://wiki.wxpython.org/LongRunningTasks I've found it quite helpful in my own programming. Mike From gagsl-py2 at yahoo.com.ar Mon Jan 21 14:38:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 17:38:10 -0200 Subject: Bug in __init__? References: <88580064-3590-471e-8036-a631dd5a38b4@i3g2000hsf.googlegroups.com> <50ed76e4-f865-4821-935f-310c96b0ecb9@e23g2000prf.googlegroups.com> Message-ID: En Mon, 21 Jan 2008 05:59:38 -0200, escribi?: > Is there no way of adding a possible warning message (that obviously > could be turned off) to warn users of possible problems linked to > using mutable types as parameters? > > Seems to me this could save users a few minutes/hours of headaches and > headscratching. (The biggest issue affecting new programmers these > days!) Most objects are mutable, such warning would happen so often that would become useless. The only immutable objects are numbers, strings, tuples, None and a few esoteric types; all other instances, including instances of all user defined classes, are mutable unless explicitely their attributes are read-only. -- Gabriel Genellina From pnemeth at fit.edu Wed Jan 30 12:16:08 2008 From: pnemeth at fit.edu (Peter Nemeth) Date: Wed, 30 Jan 2008 12:16:08 -0500 (EST) Subject: event handling Message-ID: Hi , I am working on a stellar spectral analysis pipeline in Python. My OS is Suse 10.0, and i use Python 2.5 . I have found difficulties with keyboard event handling. My code communicates with the user through an xterm window and shows graphs in a Gnuplot window. At a certain point i start an infinite loop in order to select multiple spectral regions by mouse-clicks over the Gnuplot graph. I would like to terminate this loop by a single keystroke, but i can not get it done. I use 'thread' to run this process in the background waiting for a keystroke. I don't want to use tkinter, widgets or pygame because those require a popup surface to work in and i already have the gnuplot window. I tried a C like getch() function, but that pauses the code waiting for key press instead of scanning the event queue. Is there any other means for general event handling in Python? Any help would be greatly appreciated. Sincerely, Peter From bignose+hates-spam at benfinney.id.au Thu Jan 31 08:40:01 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 01 Feb 2008 00:40:01 +1100 Subject: REALLY simple xml reader References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> Message-ID: <87tzkujeq6.fsf@benfinney.id.au> Steve Holden writes: > Diez B. Roggisch wrote: > > Ricardo Ar?oz schrieb: > >> doc = """ > >> > > > > It's not allowed to have a newline before the > > > > Put it on the line above, and things will work. > > > If you don't think that looks pretty enough just escape the first > newline in the string constant to have the parser ignore it: 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. > doc = """\ > This is fine. -- \ "True greatness is measured by how much freedom you give to | `\ others, not by how much you can coerce others to do what you | _o__) want." ?Larry Wall | Ben Finney From bsneddon at yahoo.com Wed Jan 9 15:28:39 2008 From: bsneddon at yahoo.com (bsneddon) Date: Wed, 9 Jan 2008 12:28:39 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> Message-ID: <49d262c8-492c-4f68-a145-27e84d3f7694@q39g2000hsf.googlegroups.com> On Jan 9, 3:12 pm, Tim Chase wrote: > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] > > > I'd like to remove the first and the last item as they are irrevalent, > > and convert it to the dict: > > {'tom':'boss','mike':'manager','paul':'employee'} > > > I tried this but it didn't work: > > > mydict={} > > for i in mylist[1:-1]: > > a=i.split('=') # this will disect each item of mylist into a 2-item > > list > > mydict[a[0]]=a[1] > > > and I got this: > > File "srch", line 19, in > > grab("a/tags1") > > File "srch", line 15, in grab > > mydict[mylist[0]]=mylist[1] > > IndexError: list index out of range > > This can be rewritten a little more safely like > > mydict = dict(pair.split('=',1) > for pair in mylist > if '=' in pair) > > Some of John Machin's caveats still apply: > (2) a[0] is empty or not what you expect (a person's name) > (3) a[1] is empty or not what you expect (a job title) > (consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = ' > boss') > (4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...] > > to which I'd add > > (5) what happens if you have more than one equals-sign in your > item? ("bob=robert=manager" or "bob=manager=big-cheese") > > #2 and #3 can be ameliorated a bit by > > import string > mydict = dict( > map(string.strip,pair.split('=',1)) > for pair in mylist > if '=' in pair) > > which at least whacks whitespace off either end of your keys and > values. #4 and #5 require a clearer definition of the problem. > > -tkc This seemed to work for me if you are using 2.4 or greater and like list comprehension. >>> dict([ tuple(a.split("=")) for a in mylist[1:-1]]) {'mike': 'manager', 'paul': 'employee', 'tom': 'boss'} should be faster than looping From benedict.verheyen at gmail.com Mon Jan 28 09:24:19 2008 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Mon, 28 Jan 2008 15:24:19 +0100 Subject: starting programs from python script on windows In-Reply-To: <479DB03A.9060801@timgolden.me.uk> References: <479DB03A.9060801@timgolden.me.uk> Message-ID: Tim Golden schreef: > OK. You've got a few misunderstandings in there. Nothing too major, > but it's worth sorting them out. > > 1) If you just want to kick off a program and that's it, say as part of > some kind of startup process, then you can just use the subprocess.call > convenience function. The business with stdout=PIPE is for communicating > with (usually console-based) programs which read and write to the > console. > > 2) The optional PYTHONPATH env var is used *internally* to Python as > one way of determining the path to search for Python modules *after > you've got Python running*. To run Python itself, you either need > to ensure the python.exe is already in the standard PATH env var, > or look for it in its conventional place: c:\python25\python.exe. > (Or make some other arrangement according to local convention etc.) > > There was a thread here recently about using Python as part of a > login script -- which is what I think you're doing here. I think, > because of the uncertain interaction between the Workstation in > effect when you're logging in as opposed to the Workstation which > owns the user's desktop, you might do better to have some technique > for adding to the [Startup] entry on the Start Menu if all you want > to do is to start programs. > > All that said, here's some sample code which just kicks off a > batch of programs. Note that I'm use os.startfile because that > will use ShellExecute which honours app path shortcuts, making > common things like MS Office apps much easier. You could > equivalently use subprocess.call but then you either have > to hardcode application paths or use FindExectable against an > arbitrary associated doc to find the right place. > > > import os > > programs = [ > "outlook.exe", > "cmd.exe", > "winword.exe", > "c:/temp/helpfile.pdf" > ] > for program in programs: > os.startfile (program) > > > > The last entry -- helpfile.pdf -- is to illustrate that os.startfile > can "start" documents as well as executable programs. > > TJG Tim, that seems to work ok. I will do some more testing but it looks good, Thanks! Benedict From paul.hankin at gmail.com Sat Jan 5 15:50:43 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 5 Jan 2008 12:50:43 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> Message-ID: <617182dc-3ca1-4cf5-b1ca-1779dd8d6550@i3g2000hsf.googlegroups.com> On Jan 5, 5:12?pm, Paul Hankin wrote: > On Jan 5, 4:14?pm, c... at mailinator.com wrote: > > > On Jan 5, 5:07 pm, c... at mailinator.com wrote: > > > > Hello, Paul and Arnaud. > > > While I think about your answers: do you think there is any way to > > > avoid shuffle? > > > It may take unnecessary long on a long list most of whose elements > > > have the property. > > You could generate a random shuffle of range(len(seq)) lazily, and use > that to iterate over your sequence. > > import random > import itertools > > def randxrange(n): > ? ? "Generate the numbers 0 to n-1 in a random order" > ? ? x = range(n) > ? ? for i in xrange(n): > ? ? ? ? r = random.randrange(n - i) > ? ? ? ? yield x[r] > ? ? ? ? x[r] = x[n - i - 1] > > def shuffled(seq): > ? ? "Generate the elements of seq in a random order" > ? ? return (seq[i] for i in randxrange(len(seq))) > > def pick_random(seq, prop): > ? ? return itertools.ifilter(prop, shuffled(seq)).next() At the risk of filling this thread with my posts, here's a much simplified and faster version of this code that uses no extra storage. import random def pick_random(seq, prop): L = len(seq) for i in xrange(L): r = random.randrange(L - i) if prop(seq[r]): return seq[r] seq[r] = seq[L - i - 1] -- Paul Hankin From fitzpatrick.dominic at googlemail.com Fri Jan 11 09:46:51 2008 From: fitzpatrick.dominic at googlemail.com (Fidtz) Date: Fri, 11 Jan 2008 06:46:51 -0800 (PST) Subject: python recursive function References: Message-ID: On 11 Jan, 08:30, Tom_chicollegeboy wrote: > here is what I have to do: > > This question involves a game with teddy bears. The game starts when I > give you some bears. You then start giving me back some bears, but you > must follow these rules (where n is the number of bears that you > have): > > If n is even, then you may give back exactly n/2 bears. (Hint: To test > whether n is even, use the expression ((n % 2) == 0).) > If n is divisible by 3 or 4, then you may multiply the last two digits > of n and give back this many bears. (By the way, the last digit of n > is n%10, and the next-to-last digit is (n%100)/10; this rule may not > be used if either of the last two digits is 0.) > > If n is divisible by 5, then you may give back exactly 42 bears. > The goal of the game for you is to end up with EXACTLY 42 bears. > > For example, suppose that you start with 250 bears. Then you could > make these moves: > > Start with 250 bears. > Since 250 is divisible by 5, you may return 42 of the bears, leaving > you with 208 bears. > Since 208 is even, you may return half of the bears, leaving you with > 104 bears. > Since 104 is even, you may return half of the bears, leaving you with > 52 bears. > Since 52 is divisible by 4, you may multiply the last two digits > (resulting in 10) and return these 10 bears. This leaves you with 42 > bears. > You have reached the goal! > Now, you are to write a program that, if I give you n bears, returns > true if it is at all possible for you to win the game. Your program > must use recursion to check all possible ways in which you can apply > the rules. > > Usage: > > >>> bears(42) > True > >>> bears(250) > True > >>> bears(50) > False > >>> bears(84) > True > >>> bears(41) > > False > > As you see my program must use recursion. > > I came up with this idea but I am not sure if its right or are there > any minor errors that I can easily fix: > > def bears (n): > if n==42: > return True > if n%5==0: > bears(n-42) > if n%2==0: > bears(n/2) > if n%3==0 or n%4==0: > one = (n%10) > two = ((n%100)/10) > if one!=0 and two!=0: > bears(n-(one*two)) > return False > > If a game hits 42 it should return True, otherwise False. If program > never hits 42 and return True, then it returns False. I figured out > base case, but I still get False when I enter bears(250). Any help > would be very appreciated! May != Must and Could != Should From paul.hankin at gmail.com Sat Jan 5 12:12:52 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 5 Jan 2008 09:12:52 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> Message-ID: On Jan 5, 4:14?pm, c... at mailinator.com wrote: > On Jan 5, 5:07 pm, c... at mailinator.com wrote: > > > Hello, Paul and Arnaud. > > While I think about your answers: do you think there is any way to > > avoid shuffle? > > It may take unnecessary long on a long list most of whose elements > > have the property. You could generate a random shuffle of range(len(seq)) lazily, and use that to iterate over your sequence. import random import itertools def randxrange(n): "Generate the numbers 0 to n-1 in a random order" x = range(n) for i in xrange(n): r = random.randrange(n - i) yield x[r] x[r] = x[n - i - 1] def shuffled(seq): "Generate the elements of seq in a random order" return (seq[i] for i in randxrange(len(seq))) def pick_random(seq, prop): return itertools.ifilter(prop, shuffled(seq)).next() -- Paul Hankin From sjmachin at lexicon.net Sat Jan 26 01:41:32 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 22:41:32 -0800 (PST) Subject: Doesn't know what it wants References: Message-ID: On Jan 26, 4:20 pm, Tim Rau wrote: > Traceback (most recent call last): > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > \sandbox.py", line 242, in > player = ship() > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > \sandbox.py", line 121, in __init__ > self.phyInit() > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > \sandbox.py", line 147, in phyInit > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) > ArgumentError: argument 4: : expected > vec2d instance instead of vec2d > > As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't > seems like it doesn't know what it wants, but I thought only teenagers > did that, no programming languages. It possibly means that it is expecting an instance of a class whose name is "vec2d" but you have given it an instance of some *other* class whose name just happens to be "vec2d". > clearly, Im missing something. Yes, some information: 1. what is vec2d, class or function? 2. what do you believe vec2d((0, 0)) should return? 3. what is this belief based on? 4. what has it actually returned this time? 5. what do you believe that cp.cpMomentForCircle expects as argument 4? 6. what is this belief based on? The ArgumentError exception is raised by ctypes "when a foreign function call cannot convert one of the passed arguments". Based on guessin'n'googlin' the cp thing is a set of Python bindings to a library written in C++ ... have you considered asking the author of the bindings? From steve at REMOVE-THIS-cybersource.com.au Wed Jan 23 16:48:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 21:48:19 -0000 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> Message-ID: <13pfdh31k2bp8eb@corp.supernews.com> On Wed, 23 Jan 2008 10:39:25 -0800, George Sakkis wrote: > On Jan 23, 4:37 am, Steven D'Aprano > wrote: >> On Tue, 22 Jan 2008 23:33:00 -0800, George Sakkis wrote: >> > As I mentioned already, I consider the seeking of the most efficient >> > solution a legitimate question, regardless of whether a "dumb" >> > solution is fast enough for an application. Call it a "don't be >> > sloppy" principle if you wish. >> >> Sure, by why do you limit "efficient" and "don't be sloppy" to mean >> "write the fastest executing code you can, regardless of every other >> trade-off"? > > I explicitly didn't limit sloppiness to inefficiency and mentioned it's > a tradeoff: Of course you did, and I was being sloppy. The "you" was meant more as a generic you than you yourself. Sorry for the confusion. As for your other points, I think we're actually very much in agreement, except for your tolerance of random posters asking what I believe is an incoherent question: "what's the fastest way to do ...?". It seems to me you're willing to give them the benefit of the doubt that they've done their profiling and considered their trade-offs, or at the very worst are asking from purely intellectual curiosity. Call me cynical if you like, but I think that in the absence of any direct evidence supporting those things, the most likely possibility is the opposite. -- Steven From stefan.behnel-n05pAM at web.de Wed Jan 23 06:03:27 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 12:03:27 +0100 Subject: Problem with processing XML In-Reply-To: References: <13pbudgks88rcf3@corp.supernews.com> Message-ID: <47971EFF.8070701@web.de> Hi, Paul Boddie wrote: > People will, of course, tell you that you shouldn't use a DOM for > anything and that the "consensus" is to use ElementTree or lxml (see > above), but I can't help feeling that this has a damaging effect on > the XML situation for Python: some newcomers would actually benefit > from the traditional APIs, may already be familiar with them from > other contexts, and may consider Python lacking if the support for > them is in apparent decay. It requires a degree of motivation to > actually attempt to maintain software providing such APIs (which was > my solution to the problem), but if someone isn't totally bound to > Python then they might easily start looking at other languages and > tools in order to get the job done. I had a discussion with Java people lately and they were all for Ruby, Groovy and similar languages, "because they have curly braces and are easy to learn when you know Java". My take on that is: Python is easy to learn, full-stop. It's the same for DOM: when you know DOM from (usually) the Java world, having a DOM-API in Python keeps you from having to learn too many new things. But when you get your nose kicked into ElementTree, having to learn new things will actually help you in understanding that what you knew before did not support your way of thinking. http://www.python.org/about/success/esr/ So, there is a learning curve, but it's much shorter than what you already invested to learn 'the wrong thing'. It's what people on this list tend to call their "unlearning curve". Stefan From martin at v.loewis.de Wed Jan 16 14:54:27 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 16 Jan 2008 20:54:27 +0100 Subject: Creating unique combinations from lists In-Reply-To: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> Message-ID: <478E60F3.5000509@v.loewis.de> > I could do nested for ... in loops, but was looking for a Pythonic way > to do this. Ideas? I find nested for loops very Pythonic. Explicit is better than implicit, and simple is better than complex. Regards, Martin From jarausch at skynet.be Tue Jan 15 14:06:53 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 15 Jan 2008 20:06:53 +0100 Subject: super, decorators and gettattribute In-Reply-To: <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> Message-ID: <478D044D.1040406@skynet.be> Michele Simionato wrote: > I really need to publish this one day or another, since these > questions > about super keeps coming out: > > http://www.phyast.pitt.edu/~micheles/python/super.html Unfortunately the links [2], [3] and [4] are not given, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From shore.cloud at gmail.com Sun Jan 27 11:21:20 2008 From: shore.cloud at gmail.com (Mr Shore) Date: Mon, 28 Jan 2008 00:21:20 +0800 Subject: is it a bug? Message-ID: import threading import time class timer(threading.Thread): def __init__(self,no,interval): threading.Thread.__init__(self) self.no=no self.interval=interval def run(self): while True: print 'Thread Object (%d), Time:%s'%(self.no,time.ctime()) time.sleep(self.interval) def test(): threadone=timer(1,1) threadtwo=timer(2,3) threadone.start() threadtwo.start() print 'main thread' if __name__=='__main__': test() when I run the above programme,an error comes out but ignored Exception exceptions.AttributeError: '_shutdown' in ignored -------------- next part -------------- An HTML attachment was scrubbed... URL: From cthedot at gmail.com Tue Jan 8 15:24:46 2008 From: cthedot at gmail.com (Christof Hoeke) Date: Tue, 08 Jan 2008 21:24:46 +0100 Subject: Javascript parser Message-ID: hello, is there any Javascript (not just JSON) parser for Python? I saw http://wwwsearch.sourceforge.net/python-spidermonkey/ which seems to be from 2003 and unmaintained and seems to be quite complicated to get to work anyway :( Using Rhino from Jython is not really an option as I'd like to work in (C)Python only. thanks for any hint Christof From hanke at brailcom.org Wed Jan 23 08:30:22 2008 From: hanke at brailcom.org (Hynek Hanke) Date: Wed, 23 Jan 2008 14:30:22 +0100 Subject: pythonic backtrace with gdb Message-ID: <4797416E.3020005@brailcom.org> Hello, please, I'm trying to obtain a pythonic backtrace via gdb to be able to debug deadlock situations in a multi-threaded program by attaching to the running process. I'm running the program under python2.4-dbg, When I try to load the .gdbinit script obtained at http://wiki.python.org/moin/DebuggingWithGdb , gdb crashes however with the following error (full session listing): (gdb) attach 10753 Attaching to program: /usr/bin/python, process 10753 warning: no loadable sections found in added symbol-file system-supplied DSO at 0x7fff575fd000 0x00002b33537177fb in ?? () from /lib64/ld-linux-x86-64.so.2 (gdb) pystack /tmp/buildd/gdb-6.6.dfsg.90.20070912/gdb/regcache.c:164: internal-error: register_type: Assertion `regnum >= 0 && regnum < descr->nr_cooked_registers' failed. A problem internal to GDB has been detected, further debugging may prove unreliable. Quit this debugging session? (y or n) [answered Y; input not from terminal] /tmp/buildd/gdb-6.6.dfsg.90.20070912/gdb/regcache.c:164: internal-error: register_type: Assertion `regnum >= 0 && regnum < descr->nr_cooked_registers' failed. A problem internal to GDB has been detected, further debugging may prove unreliable. Create a core file of GDB? (y or n) [answered Y; input not from terminal] Ne?sp??n? ukon?en (SIGABRT) I've also tried to use the backtrace script here http://mashebali.com/?Python_GDB_macros:The_Macros:Backtrace But I get a different error: (gdb) pbt Invalid type combination in ordering comparison. I'm using GDB version 6.6.90. Could you please suggest what can I do to be able to get the backtrace? Thank you, Hynek Hanke From mr.cerutti at gmail.com Fri Jan 4 15:47:11 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 4 Jan 2008 15:47:11 -0500 Subject: fastest method to choose a random element In-Reply-To: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> Message-ID: <51302a8c0801041247jc9a6c8ej10e346b8357bacdc@mail.gmail.com> On Jan 4, 2008 2:55 PM, wrote: > Hello, > This is a question for the best method (in terms of performance > only) to choose a random element from a list among those that satisfy > a certain property. I would automatically use random.choice(filter(pred_func, a_list)). You just have to catch the possible IndexError. This is the setting: I need to pick from a list a random element > that satisfies a given property. All or none of the elements may have > the property. Most of the time, many of the elements will satisfy the > property, and the property is a bit expensive to evaluate. Chance of > having the property are uniform among elements. > > A simple approach is: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > > Returns None if no element has the property > ''' > random.shuffle(a_list) > for i in a_list: > if property(i): return i I'm pretty sure you don't want to use a destructive random_pick function. You'll have to shuffle a copy instead to avoid that problem. > > but that requires to shuffle the list every time. > > A second approach, that works if we know that at least one element of > the list has the property, is: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > > Loops forever if no element has the property > ''' > while 1: > i=random.choice(a_list) > if property(i): return i > > which is more efficient (on average) if many elements of the list have > the property and less efficient if only few elements of the list has > the property (and goes crazy if no element has the property) That's awful. Here's another linear time idea, returning the nearest element that satisfies the predicate. offset = random.randrange(len(a_list)) for n in xrange(len(a_list)): ix = (offset + n) % len(a_list) if predicate(a_list[ix]): return a_list[ix] raise ValueError('no element has the property') The possible problem is that large strings of elements in a row that don't match the predicate greatly increase the odds of getting the following element that *does* match the predicate. Worst case is two predicate matched elements in a row, surrounded by a bunch of non-matched elements. > Yet another one: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > ''' > b_list=[x for x in a_list if property(x)] > try: > return random.choice(b_list) > finally: return None > > but this one checks the property on all the elements, which is no > good. Is it really expensive to check the property? That would mitigate against the filter solution and for the other one I posted. This seems to be a case of trying to solve a data problem functionally. It'd be better to store your data differently if this will be a frequent operation and you simply can't afford to call the predicate on all the elements. Incidentally, try not to shadow builtin names like 'property'. -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Thu Jan 3 18:14:29 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 3 Jan 2008 15:14:29 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: Message-ID: <066ade7e-fd6f-45e0-878a-3eacd90efdde@u10g2000prn.googlegroups.com> On Jan 4, 9:56 am, "Reedick, Andrew" wrote: > As a Perl monkey in the process of learning Python, I just stepped on > the "'1' (string) is not the same as 1 (integer) in regards to keys for > dictionaries/hashes" landmine. Congratulations. You have just stepped off the "'1' (string) is the same as 1 (integer) in regards to several purposes" landmine. Welcome to the awk-free world :-) > Is there a good way to ensure that > numbers represented as strings or ints do not get mixed up as keys? > > Example of the problem: > >>> h2 = { 1 : ''} > >>> print h2.has_key(1) > True > >>> print h2.has_key('1') > False > > The problem occurred because a method used to generate keys was > returning a string instead of a number without an explicit conversion > taking place. And since I was using hash.get(i, default_value) to avoid > having to pair every key lookup with a hash.has_key(), no exception was > thrown when the key wasn't found. has_key is a has_been ... use "key in dict" instead of "dict.has_key(key)" > It's fugly to wrap every key reference in str(), ex: > foo[str(some_func(i))]. Fugliness is in the eye of the beholder. From python.list at tim.thechases.com Mon Jan 28 11:23:14 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 28 Jan 2008 10:23:14 -0600 Subject: Encryption Recommendation In-Reply-To: <606aj3F1pa0tfU1@mid.uni-berlin.de> References: <6b40b773-8554-4e9c-838f-e6934212d16e@n20g2000hsh.googlegroups.com> <606aj3F1pa0tfU1@mid.uni-berlin.de> Message-ID: <479E0172.6030903@tim.thechases.com> > Usually, one doesn't store clear-text passwords. Instead, use a > hash-algorithm like md5 or crypt (the former is in the standard lib, don't > know of the other out of my head) and hash the password, and store that > hash. Python offers md5, and SHA modules built-in. (yay, python!) http://docs.python.org/lib/module-md5.html http://docs.python.org/lib/module-sha.html It does also offer access to the crypt() function on Unix-like OS'es but not Win32: http://docs.python.org/lib/module-crypt.html but it's based on DES which is no longer considered particularly secure. From what I've seen, even MD5 is being phased out in favor of SHA. > If a user enters the password, use the same algorithm, and compare the > resulting hashes with the stored one. Generally one adds a "salt" to the mix, a random piece of data that's stored with the password, so that if two users use the same password, the salt makes them the appear like different passwords: import sha import string from random import choice SALT_CHAR_COUNT = 5 salt_chars = string.letters + string.numbers + string.punctuation def is_valid(username, password): correct_hash, salt = get_hash_and_salt(username) test_hash = sha.new(salt + password).hexdigest() return test_hash == correct_hash def set_password(username, password): salt = ''.join([random.choice(salt_chars) for _ in xrange(SALT_CHAR_COUNT)]) hash = sha.new(salt + password) save_user(username, salt, hash) Implementing get_hash_and_salt() and save_user() (and perhaps tweaking the desired set of salt_chars) are left as an exercise to the reader, using whatever persistent storage mechanism suits. -tkc From asmodai at in-nomine.org Wed Jan 2 07:44:08 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 2 Jan 2008 13:44:08 +0100 Subject: dbus-python for windows In-Reply-To: <194e7fee-728a-48eb-9f51-1e272ecca838@j20g2000hsi.googlegroups.com> References: <194e7fee-728a-48eb-9f51-1e272ecca838@j20g2000hsi.googlegroups.com> Message-ID: <20080102124408.GD67953@nexus.in-nomine.org> -On [20080102 13:41], est (electronixtar at gmail.com) wrote: >I am trying to port Scribes to Windows, but I could not find a package >named dbus-python for windows. There is a windbus sourceforge.net/projects/windbus/> but it not for Python, so how could >I install dbus module for Windows Python 2.5 ? Well, I assume using the source from http://dbus.freedesktop.org/releases/dbus-python/ and trying to build it fails on Windows? (I readily admit I have little clue how much of dbus is platform-specific.) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Resolve to find thyself; and to know that he who finds himself, loses his misery... From gagsl-py2 at yahoo.com.ar Wed Jan 30 21:22:37 2008 From: gagsl-py2 at yahoo.com.ar (gagsl-py2 at yahoo.com.ar) Date: Wed, 30 Jan 2008 23:22:37 -0300 (ART) Subject: Python UML Metamodel In-Reply-To: <754577.12877.qm@web90503.mail.mud.yahoo.com> Message-ID: <40690.87155.qm@web32813.mail.mud.yahoo.com> --- sccs cscs escribi?: > Gabriel Genellina a ?crit : > En Tue, 29 Jan 2008 21:25:26 -0200, sccs cscs > escribi?: > > > I find an OPEN SOURCE tool > (http://bouml.free.fr/) that Recently > > generates Python code from UML model. > > Does it keep the model synchronized when you modify > the Python code? > > =>No, not for the moment because the Python code > generator is brand new, but the tool's author and > i are specifying the reverse tool for a next > version. I do not have found another Open Source > Tool that generates Python code from UML better like > that. Ok, that's important. If the model cannot reflect changes in the code it becomes less and less useful. > > I like to model the Python language metamodel > himself, with it, e.g the > > model of the language: I need that to better > understand the language > > constraint of the language. > > [...] > > -a class "class" has 0..n attributes and 0..n > method > > Just attributes. Methods are created on-the-fly when > the corresponding > function attribute is retrieved from the instance. > And remember that instances are not restricted to > what their class define. > You can add or remove any attribute (even methods!) > to any instance of a > user-defined class at any time. (This doesn't apply > to most builtin types, > but *does* apply if you inherit from it) > > > =>You're Right but I will also model that dynamic > aspect . However i think it is possible and the > relevant to make a static metamodel of Python, as > if there was no possibility of changing dynamic an > instance. But Python *is* a dynamic language. You have to capture that into the model somehow. > A lot of person do not understand nothing > to Python on many aspects, because there is no > graphical representation of the relation of concepts > : may a module have more than on class definition ? > a mix of class and global fonction? etc... A graphical representation may be useful, but it must be acurate too - else people may incorrectly deduce that something can't be done because it's not expressed in the graph. > > Does anyone know a document that describes it > already, because I think > > it is complicated to find this information in the > documentation of > > Python. > > See section 2 "Data Model" and section 3 "Execution > Model" in the Python > Language Reference http://docs.python.org/ref/ > > => > Thank you, it's pretty standard but somewhat > indigestible. However, by studying line by line, I > would have to be filled into a UML model Yes, sure, it's hard to follow. As the subtitle says, it's "for language lawyers" :) > > - a class "method" can contains nested "method", > but what is the way to > > get a list of internal methods, without use ? Can > i just write: > > "myNestedMethodList = method.nestedMethodList" > > Are you talking about nested functions? > => Yes > > You can't enumerate them from outside the container > function: Python is a > dynamic language, those inner functions are created > when the def statement > is *executed*. If you have an if statement around > the def, the function > may not even exist. > > => OK, it is diffcult to model: but possible: for > example, by using a composition (a method may have > 0..n inner function). The dynamic aspect may be > described into a UML note or constraints for example Anyway it doesn't look right. Inner functions are not attributes of the enclosing one, like local variables are not attributes of the enclosing function. -- Gabriel Genellina Los referentes m?s importantes en compra/ venta de autos se juntaron: Demotores y Yahoo! Ahora comprar o vender tu auto es m?s f?cil. Vist? ar.autos.yahoo.com/ From jarausch at skynet.be Tue Jan 15 14:00:36 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 15 Jan 2008 20:00:36 +0100 Subject: Benchmark [was Re: common problem - elegant solution sought] In-Reply-To: <7xbq7ngdge.fsf@ruckus.brouhaha.com> References: <5v3gg1F1kkla5U1@mid.dfncis.de> <478ccc9e$0$29264$ba620e4c@news.skynet.be> <7xbq7ngdge.fsf@ruckus.brouhaha.com> Message-ID: <478d02d4$0$22319$ba620e4c@news.skynet.be> Paul Rubin wrote: > Helmut Jarausch writes: >> def del_by_key(L,key) : >> for pos, (k,d) in enumerate(L): >> if k == key : >> del L[pos] >> break > > This looks very dangerous, mutating L while iterating over it. No, as Bruno Desthuilliers has pointed out, because one breaks out of the loop immediately. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From duncan.booth at invalid.invalid Wed Jan 9 10:53:49 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jan 2008 15:53:49 GMT Subject: stupid/style/list question References: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Duncan Booth: >> I tried to measure this with timeit, and it looks like the 'del' is >> actually quite a bit faster (which I find suprising). > > Yes, it was usually faster in my benchmarks too. Something similar is > true for dicts too. I think such timings are influenced a lot by the > garbage collector. > That may come into it, but I made the obvious change I mentioned (to avoid dereferncing a pointer every time through the loop) and got about an 8% speed-up on my test. I don't think that explains all of the speed difference though, so the garbage collector may come into it too: I'll see if I can do some more experimentation before submitting a patch. From kay.schluehr at gmx.net Sun Jan 6 02:20:55 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 5 Jan 2008 23:20:55 -0800 (PST) Subject: How a smart editor could make "Postfix type declarations PEP3117" in Python3000 more readable References: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> <477F1EAF.4070105@animats.com> Message-ID: <01c42c8e-baf2-43eb-9e87-ee4e5c0e34d6@v67g2000hse.googlegroups.com> On Jan 5, 7:07 am, John Nagle wrote: > Python doesn't really need explicit type declarations. > They're not needed for correctness, and they're not needed for > performance. Take a look at Shed Skin, which is able to hard-compile Python > using type inference without explicit type declarations. ShedSkin is not Python. From rridge at caffeine.csclub.uwaterloo.ca Sun Jan 27 10:04:06 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Sun, 27 Jan 2008 10:04:06 -0500 Subject: Using a dict as if it were a module namespace References: <13podkpqqvef674@corp.supernews.com> Message-ID: Steven D'Aprano writes: >(1) Import the test and grab the values needed from it: > > setup = """from __main__ import myfunc, test >x, y = test['x'], test['y']""" > > >I don't like this one. It doesn't seem very elegant to me, and it gets >unwieldy as the complexity increases. Every item I need from test has to >be named twice, violating the principle Don't Repeat Yourself. If the >tests change, the setup string has to be explicitly changed also. I think this is the way to go as it follows the principle of "say what you mean." You can however simplify it, and repeat yourself less, by using the extended call syntax: expr = "myfunc(**test)" setup = """from __main__ import myfunc, test""" ... >I don't like this one. It looks hackish, and I worry about conflicts and >side-effects. If it works (and I haven't tested it) it relies on an >implementation detail of timeit.Timer.__init__, namely the line >"exec code in globals(), ns". Worst of all, it pollutes or even mangles >the global namespace of the calling code, not the code being tested. It wouldn't work because the timeit module's "globals" are different from the __main__ module's globals. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From castironpi at gmail.com Sat Jan 12 09:04:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 06:04:19 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> Message-ID: On Jan 11, 5:26 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > 1. Put a single thread in charge of the list, and communicate with it > by message passing through Queues. To get X out of the list, you'd > send the mutator thread a message asking for removal. The mutator > thread would loop reading and processing messages from the queue, > blocking when no requests are pending. This is sort of the preferred > Python style and is pretty simple to get correct, but if there are > many such objects you can end up with more threads than you really > want. I've heard this called 'fire and forget'. You can insure that mutations are honored one-at-a-time and in the order received. How do you make a -read- operation; wait for queued mutations, that is lock for a turn on the queue? Can you optionally read whatever the state is, regardless of what's happened in the meantime? Thing is, one thread needs its -own- preceding operations completed before a reading operation. From mario at ruggier.org Wed Jan 2 03:45:15 2008 From: mario at ruggier.org (mario) Date: Wed, 2 Jan 2008 00:45:15 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> Message-ID: <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> On Jan 2, 9:30 am, "Martin v. L?wis" wrote: > Use "mbcs" in the second call, not "mcbs". Ooops, sorry about that, when i switched to test it in the interpreter I mistyped "mbcs" with "mcbs". But remark I did it consistently ;-) I.e. it was still teh same encoding, even if maybe non-existant.. ? If I try again using "mbcs" consistently, I still get the same error: $ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> unicode('', 'mbcs') u'' >>> unicode('', 'mbcs').encode('mbcs') Traceback (most recent call last): File "", line 1, in LookupError: unknown encoding: mbcs >>> mario From rridge at caffeine.csclub.uwaterloo.ca Wed Jan 23 09:57:36 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 23 Jan 2008 09:57:36 -0500 Subject: subprocess and & (ampersand) References: Message-ID: Tim Golden wrote: >but this doesn't: > > >"c:\Program Files\Mozilla Firefox\firefox.exe" "%*" > > > >import subprocess > >cmd = [ >r"c:\temp\firefox.bat", >"http://local.goodtoread.org/search?word=tim&cached=0" >] >subprocess.Popen (cmd) > > You need to use double quotes both in the .BAT file and in the string you pass to subprocess.Popen(). Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From mail at microcorp.co.za Wed Jan 16 02:10:36 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 16 Jan 2008 09:10:36 +0200 Subject: Interesting Thread Gotcha References: Message-ID: <00c701c85810$95d8e600$03000080@hendrik> "Dan" wrote: > >>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) > > Needs to be > >>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) > > Commas are important! > > -Dan Absolutely! - well spotted! As the first correct respondent, you win the freedom to spend a week in Naboomspruit at your own expense. It would have been nice, however, to have gotten something like: TypeError - This routine needs a tuple. instead of the silent in line calling of the routine in question, while failing actually to start a new thread. It seems to act no different from plain old: kbd_driver (port_q,kbd_q) Is it worth the trouble of learning how to submit a bug report? - Hendrik From arkanes at gmail.com Thu Jan 24 12:26:59 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 24 Jan 2008 11:26:59 -0600 Subject: translating Python to Assembler In-Reply-To: <5vroakF1o4jkvU1@mid.individual.net> References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <5vroakF1o4jkvU1@mid.individual.net> Message-ID: <4866bea60801240926t3db87f4fsaff6f725064fa5ab@mail.gmail.com> On Jan 24, 2008 9:14 AM, Bjoern Schliessmann wrote: > Tim Roberts wrote: > > Bjoern Schliessmann > > >> So, how do processors execute Python scripts? :) > > > > Is that a rhetorical question? > > A little bit. > > > Grant is quite correct; Python scripts (in the canonical CPython) > > are NOT compiled into assembly language. Scripts are compiled to > > an intermediate language. Processors execute Python scripts when > > the interpreter, written in a high-level language and compiled to > > assembly, interprets the intermediate language created by the > > Python "compiler". > > So in the end, the program defined in the Python script _is_ > compiled to the CPU's language. But never mind, it depends on how > you define "compile" in the end. > This is true if and only if you would agree that Powerpoint presentations, Word documents, and PNG images are likewise compiled to machine code. From arnodel at googlemail.com Wed Jan 30 06:57:50 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 30 Jan 2008 03:57:50 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> Message-ID: <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> On Jan 29, 10:59?pm, Paul Hankin wrote: > If I really had to modify it in place (and the condition wasn't really > x == 99), how about: > bad_indices = [i for i, x in enumerate(a) if x == 99] > for bad_index in reversed(bad_indices): > ? ? del a[bad_index] Or one could use the trick of counting from the right (untested): n = len(a) for i, x in enumerate(a): if x == 99: del a[i-n] -- Arnaud From pofuk at mzm.hr Wed Jan 23 10:25:38 2008 From: pofuk at mzm.hr (SMALLp) Date: Wed, 23 Jan 2008 16:25:38 +0100 Subject: Python printing! Message-ID: Hy. How to use printer in python. I goggled little i I found only some win32 package which doesn't look processing for cross platform application. (I'm using USB printer and I tried to f=open("dev/...") usb port but i couldn't fond where printer is! Tnx! SMALLp From pupeno at pupeno.com Sat Jan 26 09:10:03 2008 From: pupeno at pupeno.com (=?UTF-8?B?Si4gUGFibG8gRmVybsOhbmRleg==?=) Date: Sat, 26 Jan 2008 14:10:03 +0000 Subject: Replacing a package with another Message-ID: Hello, Is it possible to replace one package with another at runtime, that is, I have package a.blah which I want instead of b.blah, so I can "inject" functionality in an existing package? Thanks. -- J. Pablo Fern?ndez (http://pupeno.com) From dg.google.groups at thesamovar.net Mon Jan 14 13:47:42 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Mon, 14 Jan 2008 10:47:42 -0800 (PST) Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> <1ec2c39c-ce88-4e4b-bab8-7bfcee8c6d10@s13g2000prd.googlegroups.com> Message-ID: Hi R?diger, Thanks for your message. I liked your approach and I've been trying something along exactly these sorts of lines, but I have a few problems and queries. The first problem is that the id of the frame object can be re-used, so for example this code (where I haven't defined InstanceTracker and getInstances, but they are very closely based on the ideas in your message): class A(InstanceTracker): gval = 0 def __init__(self): self.value = A.gval # each time you make a new object, give A.gval += 1 # it a value one larger def __repr__(self): return str(self.value) def f2(): a = A() # objects 0 and 2 return getInstances(A) def f3(): a = A() # object 1 return f2() inst2 = f2() inst3 = f3() print inst2 print inst3 The output is: [0] [0, 2] The A-variable with value 0 is not being garbage collected because it's saved in the variable inst2, but it's also being returned by the second call to getInstances because the frame of f2 is the same each time (which makes sense, but may be implementation specific?). The same problem doesn't exist when you use the stack searching method because from f2's point of view, the only bound instance of A is the one in that particular call of f2. If you had at the end instead of the inst2, inst3 stuff: print f2() print f3() The output is: [0] [2] Again, I guess this because A with value 0 is being garbage collected between print f2() and print f3(), but again I think this is implementation specific? You don't have a guarantee that this object will be garbage collected straight away do you? So my concern here is that this approach is actually less safe than the stack based approach because it depends on implementation specific details in a non-straightforward way. That said, I very much like the fact that this approach works if I write: a = [A()] a = [[A()]] etc. To achieve the same thing with the stack based approach you have to search through all containers to (perhaps arbitrary) depth. I also have another problem which is that I have a function decorator which returns a callable object (a class instance not a function). Unfortunately, the frame in which the callable object is created is the frame of the decorator, not the place where the definition is. I've written something to get round this, but it seems like a bit of a hack. Can anyone suggest an approach that combines the best of both worlds, the instance tracking approach and the stack searching approach? Or do I need to just make a tradeoff here? Thanks again for all your help everyone, Dan Goodman From nma at 12000.org Mon Jan 21 21:36:34 2008 From: nma at 12000.org (Nasser Abbasi) Date: Mon, 21 Jan 2008 18:36:34 -0800 Subject: newbie question: On installation of additional packages to Python Message-ID: hello; I have not used Python before directly, but I am interested in trying it. I've read some good things about it. ( I am mainly interested in trying it for some scientific applications and simulation.) I am running on windowz. I have downloaded and installed 2.5.1 Python. my question is on installing additional packages. What is the easiest way to do that? I read about python 'eggs' (like jar files for Java), and easyInstall script, and such. Is there some automated way to install Python packages? a manual/document I could read that describes step by step how to do that? Browsing the documentation, there does not seem to be something specific there (other than saying download this tar file and install it). I like how one can install additional packages in 'R' . In 'R' one can do all that from the user interface for R by a pull-down menu, then one selects a mirror site, then one can see all the packages available, then select the package to download, and the rest is done automatically. (The package is downloaded, installed, etc...) Anything like that exists for Python? Btw, I have VM running on windowz, and so I can run Python on Ubuntu linux on that VM, would be easier to install additional Python packages there, may be using that nice GUI based Ubuntu package manager to do that? thanks, Nasser From lasses_weil at klapptsowieso.net Mon Jan 21 12:59:05 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 21 Jan 2008 18:59:05 +0100 Subject: is it possible to set namespace to an object. In-Reply-To: <27529efd-b8d8-4a8e-b72d-379a607366b7@i7g2000prf.googlegroups.com> References: <27529efd-b8d8-4a8e-b72d-379a607366b7@i7g2000prf.googlegroups.com> Message-ID: <4794dd6c$0$27198$9b4e6d93@newsspool1.arcor-online.net> glomde wrote: > Hi, > > is it somehow possible to set the current namespace so that is in an > object. > [snip] > set namespace testObj > Name = "Test" > > Name would set testObj.Name to "Test". > > [snip] > > Is the above possible? > Don't know, sorry. But let me ask you this: Why do you want to do this? Maybe there is another way to solve the problem that you want to solve. /W From kirby.urner at gmail.com Thu Jan 10 13:38:30 2008 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: Thu, 10 Jan 2008 10:38:30 -0800 (PST) Subject: What is "lambda x=x : ... " ? References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> Message-ID: You're talking about syntax from the bad old days when the scope rules were different. If not too archeological for your tastes, download and boot a 1.5 and see what happens. Less empirically, here're some key references: http://www.python.org/doc/2.2.3/whatsnew/node9.html http://www.python.org/dev/peps/pep-0227/ The change came in 2.2 with from __future__ support in 2.1. Kirby 4D On Jan 10, 11:25 am, "zsl... at gmail.com" wrote: > I'm reading this page:http://www.ps.uni-sb.de/~duchier/python/continuations.html > and I've found a strange usage of lambda: > > #################### > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ################### > > What does "y=y" and "c=c" mean in the lambda function? > I thought it bounds the outer variables, so I experimented a little > bit: > > ################# > x = 3 > y = lambda x=x : x+10 > > print y(2) > ################## > > It prints 12, so it doesn't bind the variable in the outer scope. From bakermi at cbc.ca Fri Jan 18 15:40:52 2008 From: bakermi at cbc.ca (bakermi at cbc.ca) Date: Fri, 18 Jan 2008 12:40:52 -0800 (PST) Subject: IRC bot threading dilemma Message-ID: Hello, I have coded an IRC bot in Python. Each inbound packet is parsed, and once the bot decides whether it is a command directed at the bot or not, it will either discard the packet or make a function call to an access control checker function. If the invoking user is found to have sufficient access to run this command, another function call is made. This function call depends on what command the user in question has invoked. Try to imagine making one of these functions send out a WHOIS query to the server, and wait for the burst of WHOIS-response packets from it. How would this function wait? Yes, I know, I am going to have to create another thread to loop while it waits for this reply packet. The problem is, I can't simply tell my command function to loop until the "waiter thread" raises a flag to say that it has received the packet. During this looping time, program flow would be stuck here, thus preventing the bot from replying to any vital duties such as "pingponging" (server verifies that you are still there by sending "PING" and expects a "PONG" in return.) For this reason I was thinking: do you think I should run a new thread whenever a new command is invoked by a user? And have the thread delete itself when it's completed execution? This way the bot would *always* be free to do its duties. Any help is much appreciated. M. Baker From mwm at mired.org Fri Jan 11 11:17:00 2008 From: mwm at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 11:17:00 -0500 Subject: Learning Python via a little word frequency program In-Reply-To: <7x63y0ins2.fsf@ruckus.brouhaha.com> References: <205c99df-2550-47b0-9c82-020b99ed3122@l1g2000hsa.googlegroups.com> <7x63y0ins2.fsf@ruckus.brouhaha.com> Message-ID: <20080111111700.01febeee@mbook.mired.org> On 11 Jan 2008 03:50:53 -0800 Paul Rubin <"http://phr.cx"@NOSPAM.invalid> wrote: > rent writes: > > keys = freq.keys() > > keys.sort(key = freq.get, reverse = True) > > for k in keys: > > print "%-10s: %d" % (k, freq[k]) > > I prefer (untested): > > def snd((x,y)): return y # I wish this was built-in What's wrong with operator.itemgetter? > sorted_freq = sorted(freq.iteritems(), key=snd, reverse=True) (still untested) from operator import itemgetter sorted_freq = sorted(freq.iteritems(), key=itemgetter(2), reverse=True) http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From gagsl-py2 at yahoo.com.ar Sun Jan 27 12:45:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 15:45:24 -0200 Subject: Exceptions on delete in pysqlite References: <479a7b0c$0$9119$9b4e6d93@newsspool2.arcor-online.net> Message-ID: En Fri, 25 Jan 2008 22:12:57 -0200, Wildemar Wildenburger escribi?: > Using pysqlite, I'd like to check if some dataset that I removed has > been in the database at all. Ideally I'd like pysqlite to raise an > Exception if deleting does nothing. Is that possible? I don't think so. It isn't an error, like a SELECT which returns an empty set isn't an error either. > Codewise, I'd like the following, but without me checking for and > raising the exception myself: > > cur = con.execute("""DELETE FROM SomeTable WHERE id=? AND name=?""", > (ID, NAME)) > if cur.rowcount == 0: > raise Exception Write a function to do that. -- Gabriel Genellina From mr.cerutti at gmail.com Thu Jan 17 10:28:50 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 17 Jan 2008 10:28:50 -0500 Subject: Is this a bug, or is it me? In-Reply-To: <51302a8c0801170723p35097f2avcb1b19964ef28dd9@mail.gmail.com> References: <51302a8c0801170723p35097f2avcb1b19964ef28dd9@mail.gmail.com> Message-ID: <51302a8c0801170728w76904efua3742e4d313e83c9@mail.gmail.com> On Jan 17, 2008 10:23 AM, Neil Cerutti wrote: > You cannot access a class's class variables in it's class-statement > scope, since the name of the type is not bound until after the class > statement is completed. Arrgh! I hate making the "its" error. But I wanted to add that this property of Python's class statement bothers me only when I think it would be good to use class variables as default method argument values. Luckily, I don't think very often. ;) -- Neil Cerutti From kw at codebykevin.com Thu Jan 10 10:42:21 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 10 Jan 2008 10:42:21 -0500 Subject: Problem with Tkinter.PhotoImage In-Reply-To: References: Message-ID: <47863CDD.9060200@codebykevin.com> C?dric Lucantis wrote: > Hi, > > I can only load gif images with Tkinter.PhotoImage and none with BitmapImage. > I tried png, jpg, bmp and xpm and always got this errors : > That's because Tk only supports the gif format natively. You need to install an additional photo library to support additional images (Tk has an Img extension, and Python Image Library is also very good). -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bs866806 at 163.com Thu Jan 3 01:53:01 2008 From: bs866806 at 163.com (bs866806 at 163.com) Date: Wed, 2 Jan 2008 22:53:01 -0800 (PST) Subject: How To Yell At Employees Message-ID: Dallas, TX - Madmanager.com, officially launches its web based management advice site, featuring expert management help on topics such as "How To Yell At Employees?" Solutions cost as little as $1.00 and feature results oriented answers to tough management questions. Situations madmanager can help with are "How to motivate a losing team?" "How to improve lagging sales?" "How to get rude employees to provide excellent customer service?" There are no canned responses and each problem is responded to with a solution tailored to the manager's unique situation. Founder Darryl Gee, a.k.a the madmanager has 18 years of sales and management experience. Sales trainer, Operations Manager, Store Manager and District Leader are titles he has held. He started madmanager.com to provide low cost, instant access to expert management advice. Easily accessed from any PC, the site is home to dozens of management articles, links and a management message board. Advice is offered privately, anonymously and judgement free. Any manager, any where in the world can access madmanager.com. The basic service, 1 solution for $4.99 or 3 for $8.99, is delivered via a simple click and submit form. The more advanced, high value $21 monthly subscription, is 21 questions, with 21 solutions, administered via a simple message board. It's just $1 per question. The site is targeted to assistant managers, new managers, sales managers and retailers who want to achieve phenomenal results such as, consistent sales increases, exceptional profit growth, and stellar customer service. Users will work closely with madmanager to develop goals, business strategies and sales tactics - for as little as $1. Add madmanager to the list of things you can get for $1.00 - A hamburger, a Sunday paper, a song for your ipod ... and now management advice. Managers and Business Owners who wish to use the service, access featured articles and access the free forums can visit Madmadmanger.com. Madmadmanger.com is a Dallas, TX based sole proprietorship, founded by Darryl Gee. You can find management related articles written by Darryl Gee at this link http://isnare.com/?s=author&a=Darryl+Gee CONTACT: Darryl Gee 2828 LaClede Ave. Suite 188 Dallas, TX 75204 dagee at madmanager.com (214) 764-6972 http://cncarrental.cn/html/Death/20060925/9596.html From marek.rocki at wp.pl Mon Jan 28 12:43:43 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Mon, 28 Jan 2008 09:43:43 -0800 (PST) Subject: validate string is valid maths References: Message-ID: <2ac8fb9c-2e6b-4967-a641-7f6addc5f97c@v29g2000hsf.googlegroups.com> I decided to play with it a little bit, but take a different approach than Steven. This seems actually one of the problems where regexp might be a good solution. import re re_signednumber = r'([-+]?\d+)' re_expression = '%s(?:([-+/*])[-+/*]*?%s)*' % (re_signednumber, re_signednumber) for test_case in ('3++++++8', '3++--*-9', '3++*/-9', '45--/**/+7', '55/-**+-6**'): print re.match(re_expression, test_case).groups() Now you have two problems ;-) One question: you write "in cases where multiple symbols conflict in meaning (as '3++--*-9' the earliest valid symbols in the sequence should be preserved". Aren't '++' the earliest valid symbols (operation and sign)? It seems, instead, that in your test cases the sign is always immediately preceding the number. My regexp accommodates for that. Regards, Marek From svenn.bjerkem at googlemail.com Sat Jan 12 09:19:46 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Sat, 12 Jan 2008 06:19:46 -0800 (PST) Subject: executing newgrp from python in current shell possible? References: <755e7fd2-5e4a-4a4b-b848-a5e4ca756087@l6g2000prm.googlegroups.com> Message-ID: On Jan 9, 9:18 pm, Zentrader wrote: > On Jan 9, 5:56 am, Svenn Are Bjerkem > wrote: > > >I have been looking for a way to execute this command > > as a part of a script, but it seems that the changes are only valid in > > the context of the script and when the script exits, the current shell > > still have the original "users" group setting. > > I don't think you would want it any other way. Would you want a user > to be able to change the group and have it remain permanently? Who's > going to remember whether they were last in "A" or "B", and it opens > up oportunities for the practical joker when you go to the restroom > and leave the terminal on. Put the "change the group" code into a > separate function in a separate file (with only you as the owner) and > call it whenever you want to change groups. I am trying to create a script that make it easy for users in a design team to create files that belong to the same group, but retain the users uid. In order to make it visible that the user is creating files with a different gid, the script will change the prompt to indicate so. In a tcl solution I have now, the users home is changed to the design area as some tools are reading and writing setup files into $HOME. I have not found a way to change the gid in tcl so I turned to python in hope that this scripting language could do so. The tcl solution spawns a new tcsh after setting several environment variables and works quite well except for not being able to change gid. And it is also a wish from my side to port this script to python. Is your suggestion to put "newgrp design" into a new file and then exec this file in my python script? What happens to the group id of the shell that called the python script in this case? I would try to avoid spawning a new tcsh as this make execution of tools on a remote computer difficult as the handover of command line arguments does not seem to be handed over to the newly spawned shell. I may be understanding something wrongly here. -- Svenn From jairtrejo at yahoo.com.mx Wed Jan 2 14:19:57 2008 From: jairtrejo at yahoo.com.mx (Jair Trejo) Date: Wed, 2 Jan 2008 13:19:57 -0600 (CST) Subject: PyCairo, PIL and StringIO In-Reply-To: Message-ID: <782391.65282.qm@web52202.mail.re2.yahoo.com> > > De: Fredrik Lundh > A: python-list at python.org > Fecha: Wed, 02 Jan 2008 15:39:11 +0100 > Asunto: Re: PyCairo, PIL and StringIO > > Jair Trejo wrote: > > > I'm doing some image processing in PIL, and I want > to > > display the results in a GTK window using PyCairo, > so > > I create a Cairo image surface from the PIL Image > like > > this: > > data > > mfile = StringIO.StringIO() > > final.save(mfile, format="PNG") > > ima = > > cairo.ImageSurface.create_from_png(mfile) > > mfile.close() > > return ima > > > > Where final is a PIL image. The problem is, I get > a > > IOError: error while reading from Input Stream. > > > > ?Any idea of why is this happening? > > "save" leaves the file pointer at an undefined > position (usually at the > end), so my guess is that you have to rewind the > file before you pass it > to the next function: > > final.save(mfile, format="PNG") > mfile.seek(0) # rewind > > also note that compressing and decompressing will > introduce unnecessary > overhead; chances are that you might get a lot > better performance if you > just shuffle the raw pixels. I haven't used PyCairo > myself, but from a > quick look at the ImageSurface documentation, > something like this should > work (untested): > > if final.mode != "RGB": > final = final.convert("RGB") > w, h = final.size > data = final.tostring() # get packed RGB buffer > ima = cairo.ImageSurface.create(data, > FORMAT_RGB24, w, h, w*3) > > (tweak as necessary) > > Thank, you, it worked! I tried rewinding the file, and it worked OK. But you were right about performance issues, so I tweaked your code and left it as: from array import array ... w,h = final.size data=array('c') data.fromstring(final.tostring()) ima=cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32,w,h,w*4) return ima Which is around 10 times faster. The problem is, it swaps the R and B bands. I could probably write my own Image.tostring(), but i found it more convenient to swap the channels before processing, and it worked just fine. ____________________________________________________________________________________ ?Capacidad ilimitada de almacenamiento en tu correo! No te preocupes m?s por el espacio de tu cuenta con Correo Yahoo!: http://correo.yahoo.com.mx/ From mfefe at gmail.com Tue Jan 1 07:56:47 2008 From: mfefe at gmail.com (mfefe at gmail.com) Date: Tue, 1 Jan 2008 12:56:47 +0000 (UTC) Subject: M I-5'Per secution Be rnard Levi n ex presses hi s views Message-ID: The article of which part is reproduced below. was penned by Bernard Levin for the Features section of the Times on 21 September 1991. To my. mind, it described the situation at the time. and in particular a recent meeting with a friend,. during which I for the first time admitted to someone other than my GP that I had been subjected to a conspiracy of. harassment over the previous. year and a half. >There is a madman running loose about London, called David. Campbell; I have >no reason to believe that he is. violent, but he should certainly be >approached with caution. You. may know him by the curious glitter in his >eyes and a. persistent trembling of his hands; if that does not suffice, you >will find. him attempting to thrust no fewer than 48 books into your arms, >all hardbacks, with a promise that, if. you should return to the same >meeting-place next. year, he will heave another 80 at you. > >If, by now, the police have arrived and are keeping a close watch. on him, >you may feel. sufficiently emboldened to examine the books. The jackets are >a model of uncluttered typography,. elegantly and simply laid out; there is >an unobtrusive colophon of. a rising sun, probably not picked at random. >Gaining confidence - the lunatic is smiling by now,. and the policemen, who >know about such things, have significantly. removed their helmets - you >could do worse than take the jacket off the first book in the. pile. The >only word possible to describe the binding is sumptuous; real cloth in. a >glorious shade of dark green,. with the title and author in black and gold >on the. spine. > >Look at it more closely; your eyes do not deceive. you - it truly does have >real top-bands and tail-bands,. in yellow, and, for good measure, a silk >marker ribbon in a lighter green. The paper is cream-wove and. acid-free, >and the book is. sewn, not glued. > >Throughout the encounter, I should have mentioned,. our loony has been >chattering away, although what he is trying to. say is almost impossible to >understand;. after a time, however, he becomes sufficiently coherent to make >clear that he is trying to sell the books to you. Well,. now, such quality >in bookmaking today can only be for collectors' limited editions at. a >fearsome price - #30, #40,. #50? > >No, no, he says, the glitter more powerful than ever. and the trembling of >his hands rapidly spreading throughout his. entire body; no, no - the books >are priced variously. at #7, #8 or #9, with the top price #12. > >At this, the policemen understandably put their helmets back on; one. of >them draws his truncheon and the other can be. heard summoning >reinforcements on. his walkie-talkie. The madman bursts into tears, and >swears it is. all true. > >And it. is. > >David Campbell has acquired the entire rights to the whole. of the >Everyman's Library, which. died a lingering and shameful death a decade or >so ago, and he proposes to start it all over again. - 48 volumes this >September and 80 more next year, in editions I have described, at. the >prices. specified. He proposes to launch his amazing venture simultaneously >in Britain and. the United States, with the massive firepower of Random >Century at his back in this country,. and the dashing cavalry of Knopf >across the water, and no one who loves. literature and courage will forbear >to. cheer. At the time this article was written I had. believed for some time that columnists in the Times. and other journalists had been making references to my situation. Nothing unusual about this you may think,. plenty of people have the same sort of. ideas and obviously the papers aren't writing about them, so why should my beliefs not be as false as those. of others? What makes this article so extraordinary is that three or. four days immediately preceding. its publication, I had a meeting with a friend, during the course of which. we discussed the media persecution, and in particular that by Times. columnists. It seemed to me, reading the article by Levin in Saturday?s paper, that he. was describing in some detail his "artist?s impression" of that meeting. Most telling are. the final sentences, when he writes, "The madman bursts into tears,. and swears it is all true. And it is." Although I did not "burst into tears". (he seems to be using a bit of poetic licence and exaggerating). I did try hard to convince my friend that it was all true;. and I am able to concur with Mr Levin, because,. of course, it is. At the beginning of. the piece Levin reveals a fear of being attacked by the "irrational" subject of his story, saying "I have no reason to. believe that he is. violent, but he should certainly be approached with caution". This goes back to the xenophobic. propaganda of "defence" against a "threat" which was seen at the very beginning. of the harassment. The impression of a "madman running loose" who needs to be. controlled through an agency which assigns to itself the mantle of. the "police" is also one which had been expressed. elsewhere. In. the final paragraph of this extract, his reference to Everyman?s Library as. having "died a lingering and shameful death a decade or so ago" shows clearly what sort of. conclusion they wish to their campaign. They want a permanent solution, and as they are prevented from achieving. that solution directly, they waste. significant resources on methods which have been repeatedly shown to be ineffective for such. a purpose. 343 From george.sakkis at gmail.com Sat Jan 26 02:48:24 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 25 Jan 2008 23:48:24 -0800 (PST) Subject: Pickling dynamically generated classes Message-ID: <17d87139-dff6-4182-a7bb-c243ba5f43c4@d21g2000prf.googlegroups.com> The Fine Manual mentions that pickle works for classes that are defined at the top level of a module. Is there a way to extend this behavior so that I can pickle and unpickle instances of dynamically generated classes ? Longer version: I have a function RecordTypeFactory(fields, ...) that dynamically generates and caches a record-like class based on the passed fields and other info (or returns the cached class if it has been created before). Although I am able to pickle instances of the various generated classes (records) by writing the gen. class in globals(), I cannot unpickle them from a different process unless RecordTypeFactory is called with the same arguments so that "the same" class is generated in the other process as well. Essentially what I'm missing is a hook to call RecordTypeFactory with the same fields when an instance of the gen. class is to be unpickled. George From sjmcarter at gmail.com Tue Jan 15 14:29:58 2008 From: sjmcarter at gmail.com (SJ Carter) Date: Tue, 15 Jan 2008 11:29:58 -0800 (PST) Subject: Perl Template Toolkit: Now in spicy new Python flavor References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> Message-ID: Congrats. This will no doubt prove valuable to any Python programmer. From cjw at sympatico.ca Tue Jan 15 10:54:10 2008 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 15 Jan 2008 10:54:10 -0500 Subject: Why this apparent assymetry in set operations? In-Reply-To: <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: Neil Cerutti wrote: > On Jan 15, 2008 10:10 AM, wrote: >> I've noticed that I can update() a set with a list but I can't extend a set >> with a list using the |= assignment operator. >> >> >>> s = set() >> >>> s.update([1,2,3]) >> >>> s >> set([1, 2, 3]) >> >>> s |= [4,5,6] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: unsupported operand type(s) for |=: 'set' and 'list' >> >>> s |= set([4,5,6]) >> >>> s >> set([1, 2, 3, 4, 5, 6]) >> >> Why is that? Doesn't the |= operator essentially map to an update() call? > > No, according to 3.7 Set Types, s | t maps to s.union(t). > If the RHS is a set then it works OK: *** Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32. *** >>> import sets >>> s1= sets.Set([2, 4, 5]) Set([2, 4, 5]) >>> s1= sets.Set([2, 4, 5]) >>> s2= sets.Set([4, 5, 6]) >>> s1|s2 Set([2, 4, 5, 6]) >>> s1|=s2 >>> s1 Set([2, 4, 5, 6]) >>> It could be modifies to handle any iterable on the RHS. Colin W. From oliver at obeattie.com Sat Jan 26 08:16:03 2008 From: oliver at obeattie.com (Oliver Beattie) Date: Sat, 26 Jan 2008 05:16:03 -0800 (PST) Subject: Custom class to a dictionary? References: <5025a3f7-9dcf-49d7-876c-df5c8d8a8df5@e6g2000prf.googlegroups.com> <13pm89n9avfl146@corp.supernews.com> Message-ID: <1ac0a4b2-2966-4e44-99ce-6172ea8d4baf@d4g2000prg.googlegroups.com> On Jan 26, 12:01?pm, Steven D'Aprano wrote: > On Sat, 26 Jan 2008 03:35:18 -0800, Oliver Beattie wrote: > > Just wondering if it is possible to pass a custom class instance > > instance to dict() by way of using methods like you can for iterators > > (__iter__, __getitem__ etc.) I see there is no __dict__ -- is there > > anything else I can use to achieve this? > > Just write a method to return (key, value) pairs, and call that: > > >>> class Parrot(object): > > ... ? ? def __init__(self): > ... ? ? ? ? ? ? self.keys = [1, 2, 3, 4] > ... ? ? ? ? ? ? self.values = ["one", "two", "three", "four"] > ... ? ? def generate_tuples(self): > ... ? ? ? ? ? ? for k,v in zip(self.keys, self.values): > ... ? ? ? ? ? ? ? ? ? ? yield (k,v) > ...>>> p = Parrot() > >>> p.generate_tuples() > > >>> dict(p.generate_tuples()) > > {1: 'one', 2: 'two', 3: 'three', 4: 'four'} > > Here's another way: > > >>> class Foo(object): > > ... ? ? def __getitem__(self, i): > ... ? ? ? ? ? ? if i > 4: > ... ? ? ? ? ? ? ? ? ? ? raise IndexError > ... ? ? ? ? ? ? return (i, 'foo %d' % i) > ...>>> dict(Foo()) > > {0: 'foo 0', 1: 'foo 1', 2: 'foo 2', 3: 'foo 3', 4: 'foo 4'} > > Bonus marks if you can explain why they both work :) > > (Hint: consider the "sequence protocol" and the "iterator protocol".) > > -- > Steven Sure, I get what you're saying here and thanks for the advice; but I don't want the keys as the iterator indices -- They should have custom names (latitude, longitude and elevation). Is this possible (outside of the custom method to generate two-tuples?) Sorry to be a pain! The class looks like the below; I just whipped this up real quick but it can generate the iterators it should -- just the dictionaries should be different -- {'latitude': 0.0, 'longitude': 0.0, 'elevation': 0.0} or whatever): class Coordinates(object): """Basic object for storing co-ordinate data.""" latitude = 0.0 longitude = 0.0 elevation = 0.0 def __unicode__(self): return u'Coordinate (%s, %s, %s)' % (self.latitude, self.longitude, self.elevation) def __repr__(self): return '' % (self.latitude, self.longitude, self.elevation) def __iter__(self): return iter((self.latitude, self.longitude, self.elevation)) I guess it's just easier to have a dict() method to this end; just wondered if there was a more 'Pythonic' way to do this. From robin at alldunn.com Fri Jan 25 11:54:52 2008 From: robin at alldunn.com (Robin Dunn) Date: Fri, 25 Jan 2008 08:54:52 -0800 Subject: [wxPython-users] Issue with docking wx.listctrl window In-Reply-To: References: <4798D1B1.7020908@alldunn.com> Message-ID: <479A145C.40802@alldunn.com> tarun wrote: > Thanks a lot Robin. > > I tried using self.log and instead of self.log.list. *Code is attached.* > But this gives me a panel and listctrl in it. The extra blank space > around the listctrl in window1 is something that I don't need. Use a sizer to manage the layout of the listctrl. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From paddy3118 at googlemail.com Sat Jan 5 09:09:06 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 5 Jan 2008 06:09:06 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> Message-ID: <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> On Jan 4, 3:50 pm, "Reedick, Andrew" wrote: > > From: Stephen Hansen [mailto:apt.shan... at gmail.com] > > Sent: Thursday, January 03, 2008 7:39 PM > > To: Reedick, Andrew > > Cc: python-l... at python.org > > Subject: Re: dictionary/hash and '1' versus 1 > > > Well one important thing to learn while learning Python is that while the > > language is dynamically typed-- it is also /strongly/ typed. Every piece > > of data has an explicit type and it doesn't change unless you change it. > > Meh, mixing dynamic and strong typing is a mixed blessing. You don't find out that you screwed up the data types until the code block is actually executed. Reminds me of Nostradamus. He may have predicted the future[1], but the predictions are so vague/convoluted that you can only figure out the predictions in hindsight. > > > It relies on duck typing a lot, and doesn't care if you mix and match > > (even partially) compatible types as long as the operations are there, > > but one type will always be distinct and remain that type until you > > explicitly convert it. > > > A single integer is distinctly different from a sequence of characters in > > some encoding that may just happen to contain representations of a > > number.... so they'll hash differently :) > > Depends on the context. The machine encoding may be different, but in human terms they "should" be the same. Perl managed to achieve an impressive blend of presenting data as human friendly or as machine bits when it made sense to do so. So much so, that Perl is probably the only language I've used that will do what you mean instead of what you say. Nice, but frightening in some ways. There are many character strings that contain numeric characters that are not necessarily to be interpreted as an int or a float, such as string representations of IP addresses, or numbers to other bases than ten, complex numbers, telephone numbers, ... You need to validate your input and convert and pass around the correct type of data. Perl inherited this automatic conversion between strings and numbers from simple shell scripting and the AWK language that was around before Perl. I find that the follow-on need to have separate comparisons for numbers or strings to be awkward in Perl. > > > One type will basically never implicitly convert into another type. > > > To me, this sounds like the function should have converted the type > > explicitly on return. Or maybe you need to convert it explicitly on > > receipt. > > Type casting is easy, IFF you remember to do so. The problem was that I missed the fact that one (important) function was returning a string instead of an int, and since Python supports heterogenous data structures, the human has to remember to keep the key's data type homongenous. > That and Perl does so much automatic type conversion in such a sensible way, that I stopped worrying about mixing data types, which is making the Python transition a tad more error prone. Because of Perl, I almost consider automatic type casting to be the next "you don't have to manage your own memory" that people loved about Java. =O Not really, it seems to me to be going the exact opposite way with languages with automatic type conversions being seen as not suited for larger programs. > > > But if you are in a use-case where you really don't care and only > > want to hash strings, you can create a dict subclass easily that > > overrides __setitem__ to always str() the input. Check out the > > UserDict class. > > UserDict looks like it could be useful. Thanks for the info. > > > A similar method lets you make 'case-insensitive' dicts, for example. > > > Were such a thing to happen automagically, you could get some > > weird situations, such as "assert (key in dict) == (key in dict.keys())" > > failing. > > I'm assuming that you would just need to overload the 'in' operator and .keys() method to be case insensitive also. > > [1] No, he didn't. > From steven at REMOVE.THIS.cybersource.com.au Sun Jan 6 16:56:58 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 06 Jan 2008 21:56:58 -0000 Subject: Delete lines containing a specific word References: Message-ID: On Sun, 06 Jan 2008 13:33:52 -0800, Francesco Pietra wrote: > Steven: > Thanks. See below please (of very marginal interest) > > --- Steven D'Aprano wrote: > >> On Sun, 06 Jan 2008 09:21:33 -0800, Francesco Pietra wrote: >> >> > Please, how to adapt the following script (to delete blank lines) to >> > delete lines containing a specific word, or words? >> >> That's tricky, because deleting lines from a file isn't a simple >> operation. No operating system I know of (Windows, Linux, OS X) has a >> "delete line" function. > > As I am at Debian Linux, I do that with grep -v grep doesn't delete lines. grep matches lines. If you want to delete them, you still have to do the rest of the job yourself. >> Secondly, you might want the script to write its output to a file, >> instead of printing. So, instead of the line "print line", you want it >> to write to a file. > > may be cumbersome, though I use 2>&1 | tee output file.pdb so that I > can see what happens on the screen and have the modified file. Yes, matching lines and sending them to stdout is a better solution than trying to delete them from a file. -- Steven From cjw at sympatico.ca Wed Jan 16 08:14:15 2008 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 16 Jan 2008 08:14:15 -0500 Subject: Why this apparent assymetry in set operations? In-Reply-To: <13oq9uo2rjruhb6@corp.supernews.com> References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> <13oq9uo2rjruhb6@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Tue, 15 Jan 2008 11:25:25 -0500, Colin J. Williams wrote: > >> I'm sorry, there appears to be a bug: # tSet.py >> import sets >> s1= sets.Set([1, 2, 3]) >> s1.union_update([3, 4,5]) >> print(s1) >> s2= sets.Set([6, 7, 8]) >> s1 |+ s2 # This fails: >> exceptions.TypeError: bad operand type for unary +: 'Set' > > And so it should fail. Did you mean |= instead of |+ ? > > Thanks, keyboard error. Colin W. From paddy3118 at googlemail.com Fri Jan 11 15:03:08 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 11 Jan 2008 12:03:08 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <0d29626d-886d-46ea-b387-879e24f41110@t1g2000pra.googlegroups.com> Message-ID: <8c7a77e4-e32b-4459-b7b5-693bf201a063@q39g2000hsf.googlegroups.com> On Jan 11, 9:54 am, Chris wrote: > On Jan 9, 12:34 pm, cesco wrote: > > > Hi, > > > say I have a string like the following: > > s1 = 'hi_cat_bye_dog' > > and I want to replace the even '_' with ':' and the odd '_' with ',' > > so that I get a new string like the following: > > s2 = 'hi:cat,bye:dog' > > Is there a common recipe to accomplish that? I can't come up with any > > solution... > > > Thanks in advance > > Cesco > > A simple list comprehension is all that is needed. > > input_string = 'hi_cat_bye_dog'.split('_') > output_string = ','.join([':'.join(input_string[i:i+2]) for i in > xrange(0,len(input_string),2)]) I tried your example with my extended input cases to get: def altrep6(s): input_string = s.split('_') return ','.join([':'.join(input_string[i:i+2]) for i in xrange(0,len(input_string),2)]) altrep6.author="Chris" Giving output: ## Program by: Chris '' RETURNS '' '1' RETURNS '1' '2_' RETURNS '2:' '3_4' RETURNS '3:4' '5_6_' RETURNS '5:6,' '7_8_9' RETURNS '7:8,9' '10_11_12_' RETURNS '10:11,12:' '13_14_15_16' RETURNS '13:14,15:16' '17_18_19_20_' RETURNS '17:18,19:20,' '_' RETURNS ':' '_21' RETURNS ':21' '_22_' RETURNS ':22,' '_23_24' RETURNS ':23,24' '_25_26_' RETURNS ':25,26:' '_27_28_29' RETURNS ':27,28:29' '_30_31_32_' RETURNS ':30,31:32,' '_33_34_35_36' RETURNS ':33,34:35,36' '__' RETURNS ':,' '___' RETURNS ':,:' '____' RETURNS ':,:,' '_____' RETURNS ':,:,:' - Paddy. From rupert.thurner at gmail.com Sun Jan 20 06:51:17 2008 From: rupert.thurner at gmail.com (rupert.thurner) Date: Sun, 20 Jan 2008 03:51:17 -0800 (PST) Subject: finding memory leak in edgewall trac 0.11 References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> <0c6fc35d-91d2-4767-968d-e6eb56096eba@z17g2000hsg.googlegroups.com> Message-ID: <4f9304e4-3847-41ee-8064-b881f7b9e073@f47g2000hsd.googlegroups.com> On Jan 20, 12:40?pm, "rupert.thurner" wrote: > On Jan 19, 10:31?pm, Christian Heimes wrote: > > > > > > > Jeroen Ruigrok van der Werven wrote: > > > > Hi Christian, > > > > -On [20080119 16:16], Christian Heimes (li... at cheimes.de) wrote: > > >> I forgot one important point in my reply. The GC module contains some > > >> useful methods for debugging. Check gc.garbage. It should be empty. > > > > Yeah, we're messing around with that stuff as well as many other ways of > > > trying to track issues, but it can really be looking for a needle in a > > > haystack to be honest. > > > There's so much output that, I guess, make sense only when you're semi-deep > > > into the Python internals to even make heads or tails out of it. =\ > > > And even third-party code is not helping much to reduce the clutter and > > > provide insight. > > > Under normal circumstances gc.garbage should be an empty list. In > > general it's a bad sign if gc.garbage contains lots of objects. > > > I found several potential leaks in trac: > > > $ find -name \*.py | xargs grep __del__ > > ./trac/versioncontrol/svn_fs.py: ? ?def __del__(self): > > ./trac/versioncontrol/svn_fs.py: ? ?def __del__(self): > > ./trac/db/pool.py: ? ?def __del__(self): > > > $ find -name \*.py | xargs grep frame > > ./trac/web/main.py: > > [...] > > ./trac/core.py: ? ? ? ?frame = sys._getframe(1) > > ./trac/core.py: ? ? ? ?locals_ = frame.f_locals > > > I recommend that you either replace __del__ with a weak reference > > callback or to remove it. Referencing a frame, traceback or f_locals is > > going to leak, too. You *must* explicitly del every frame and locals > > variable. > > > Christian > > many thanks! as the main change was replacing clearsilver with genshi, > this means one could do the same thing with genshi,http://genshi.edgewall.org/? > > $ find -name \*.py | xargs grep frame > ./genshi/filters/html.py: ? ? ? ?'dir', 'disabled', 'enctype', 'for', ... > > - Show quoted text - i forgot to mention that i cannot see any explicit sys._getframe(), or __del__ in the genshi code, while the ones in trac-core seemed to be there in 0.10.4. rupert From bborcic at gmail.com Wed Jan 30 08:45:08 2008 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 30 Jan 2008 14:45:08 +0100 Subject: find nearest time in datetime list In-Reply-To: References: Message-ID: <47a07fa6$1_1@news.bluewin.ch> washakie wrote: > Hello, > > I have a list of datetime objects: DTlist, I have another single datetime > object: dt, ... I need to find the nearest DTlist[i] to the dt .... is > there a simple way to do this? There isn't necessarily an exact match... > > Thanks! > .john > min(DTlist,key=lambda date : abs(dt-date)) From aawood at gmail.com Thu Jan 10 16:46:39 2008 From: aawood at gmail.com (Adrian Wood) Date: Thu, 10 Jan 2008 21:46:39 +0000 Subject: Newbie question on Classes Message-ID: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> Hi al! I'm new to the list, and reasonably new to Python, so be gentle. Long story short, I'm having a hard time finding a way to call a function on every object of a class at once. Example: I have a class Person, which has a function state(). This prints a basic string about the Person (position, for example). In the program, I have created two objects of class Person, called man and woman. I can call man.state() and then woman.state() or Person.state(man) and Person.state(woman) to print the status of each. This takes time and space however, and becomes unmanageable if we start talking about a large number of objects, and unworkable if there is an unknown number. What I'm after is a way to call the status of every instance of Man, without knowing their exact names or number. I've gone through the relevant parts of the online docs, tried to find information elsewhere online, and looked for code samples, but the ionformation either isn't there, or just isn't clicking with me. I've tried tracking the names of each object in a list, and even creating each object within a list, but don't seem to be able to find the right syntax to make it all work. I'd appreciate anyone who could help, especially if they could include a short sample. My apologies if I'm not following the etiquette of the group in some way my making this request. Thank you, Adrian From Lie.1296 at gmail.com Sun Jan 20 17:37:56 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 20 Jan 2008 14:37:56 -0800 (PST) Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> <478e1e3e$0$18054$426a74cc@news.free.fr> Message-ID: <34aa1a1f-2034-471d-91ee-2a758dab555b@f47g2000hsd.googlegroups.com> On Jan 16, 9:23 pm, Bjoern Schliessmann wrote: > Lie wrote: > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > >> I used to systematically use it - like I've always systematically > >> used 'this' in C++ and Java. > > > And that is what reduces readability. > > IMHO not, IOPHO not. This is the nth time (n >> 1) this discussion > comes up here. If I have learned one thing from those very lengthy > discussions, it's that Python's "self" handling is not going to > change. And ah... yes, I don't wish it go away either. In VB, excessive Me reduces readability, but in Python it doesn't. > > A proficient VB/C/Java programmer would frown upon the extra, > > unneeded garbage as they thought it was clear already that the > > variable refers to a class-level variable. > > C programmers surely have no opinion concerning C because it has no > native classes. C-family, ok? Please stop taking my words to its letters. > Personally, I've seen many C++ programs with complex class designs > where it definitely helps to consistently use "this->". I cannot > remember all local (and global) variables in bigger methods. In that case, you have the _option_ to do it. > > There is one major positive point: convenience and shorter code. > > (isn't that two?) > > Shorter code is not per se positive, neither is it convenient. If it > was, everyone would use perl. Not always, but sometimes it do help not to be obliged to use the class name especially in short, simple programs (as opposed to big projects that requires hundreds of thousands of lines of code) that is changed frequently (being in heavy development). A good real-life example for this would be for new learner of programming or the language, they would write a lot of ten liners that is changed a LOT of times due to their (yet) incomplete understanding of the concepts. > >> it's the first argument of the function - which usually happens to be > >> the current instance when the function is used as a method. > > > And that's the point, self (or anything you name it) is almost always > > the current instance > > # this is a plain function. In this function, > # 'obj' can be whatever that happens to have a (numeric) > # 'stuff' attribute > def func(obj, arg): > ? ?return (obj.stuff + arg) / 2.0 > > # this is a class with an instance attribute 'stuff' > class Foo(object): > ? ? def __init__(self, bar): > ? ? ? self.stuff = bar + 42 > > # this is another (mostly unrelated) class > # with a class attribute 'stuff' > class Bar(object): > ? ?stuff = 42 > > # this is a dummy container class: > class Dummy(object): pass > > # now let's play: > import new > > d = Dummy() > d.stuff = 84 > print func(d, 1) > > d.baaz = new.instancemethod(func, d, type(d)) > print d.baaz(2) > > f = Foo(33) > print func(f, 3) > Foo.baaz = func > f.baaz(4) > > print func(Bar, 5) > Bar.baaz = classmethod(func) > Bar.baaz(6) > > > ?and that makes it functionally the same as Me and > > this in VB and Java. > > Depends on the context, cf above !-) Please again, stop taking letters to the words, I don't meant them to be exactly the same, rather the same would meant that they generally can be considered equal, exceptions exists of course. And btw, I don't understand what you meant by your example, they seemed to be a completely OK program for me, even though it's a bit confusing to follow[2]. [2] btw, the reason it's a bit confusing to follow is one of my points: It is a Bad Thing(tm) to use the same name for different variables even in a language like Python that enforce explicit naming of classes > >>> Most other languages > >>> 1) automatically assign the containing class' object > >> s/containing class' object/current instance/ > > >>> in a keyword > >>> (Java: this, VB: Me) behind the screen, > > >> That's not very far from what a Python method object does - > >> automatically assign the current instance to something. The difference > >> is that Python uses functions to implement methods (instead of having > >> two distinct contructs), so the only reliable way to "inject" the > >> reference to the current instance is to pass it as an argument to the > >> function (instead of making it pop from pure air). > > > It isn't very far, but Python makes it obvious about the assignment > > (not behind the screen). > > Exactly. And given both the simplicity of the solution and what it let > you do, that's a *very* GoodThing(tm) IMHO. I agree, it's a Good Thing but it doesn't make the point less pointy, the difference between Me/this and self is just the explicit assignment. Other things that is possible because of the explicit assignment is just a "coincidence" of design choice. > >>> and 2) automatically searches > >>> variable name in both the local variable table and the containing > >>> class variable table ?(so to refer to a class variable named var from a > >>> method inside the class, we only need to write var, not self.var as in > >>> python). > >> This - as you know - cannot work well with Python's scoping rules and > >> dynamicity. Anyway, implicit object reference is definitively a > >> BadThing(tm) wrt/ readbility, specially with multiparadigm languages > >> (like Python or C++). Why do you think soooo many C++ shops impose the > >> m_something naming scheme ? > > > Implicit object reference for the containing class has little harm, if > > a class is so complex that there are more than 10 class-level > > variable, then it is obvious that that class needs to be fragmented to > > smaller classes. > > Not necessarily. There are general rules (like 'keep your classes small > and focused', which I wholefully agree with), there are guidelines (like > 'more than 10 member variables might smell like refactoring), and > there's real life, where one very often faces classes that have much > more than 10 member variables and still are as small and focused as > possible. I'd add "whenever possible" then. I don't consider 10 as a guideline, but rather as a large number I randomly picked for an example, because in most project 10 is A LOT for number of variables, and I'm sure that most well designed program would have less than 10 variables per class (except in cases where it is just impossible to fragment the class any further). > > Remembering less than 10 variable and avoiding naming > > collision among just 10 variable is not hard (and 10 is really too > > many, most classes should only use 2-4 variables), > > I really doubt you'll be able to write any working non-trivial software > trying to strictly follow this rule. In what way have I said that the rule is strict? No rule is ever strict in my book, ALL rules are meant to be bend in exceptional cases and ALL exceptions are meant to be excepted themselves (applying the definition recursively). > > especially if you > > have a good IDE that employs Intellisense-like technology (IDLE has > > it). > > IDLE is certainly not a "good IDE" in my book. What you've just said actually enforce the sentence, even a bad IDE like IDLE have Intellisense-like feature :) I agree that IDLE isn't a good IDE, but it is an example that I could use since it is the only Python IDE I have ever used (although I'm interested to find another, the demand isn't that high ...yet... to _have_ to find another IDE) > > And it is always a Bad Thing(tm) to use the same name for two > > variable in the class and in function (which is the main and only > > source of possible ambiguity) in ANY language, even in Python. > > Ho, yes.... Like, this would be bad ? > > class Person(object): > ? ?def __init__(self, firstname, lastname, birthdate, gender): > ? ? ?self.firstname = firstname > ? ? ?self.lastname = lastname > ? ? ?self.birthdate = birthdate > ? ? ?self.gender = gender > > C'mon, be serious. It's often hard enough to come with sensible names, > why would one have to find synonyms too ? Try to come with something > more readable than the above, and let us know. Seriously, this braindead > rule about ?"not using the same name for an attribute and a local var" > obviously comes from languages where the "this" ref is optional, and > FWIW it's obviously the wrong solution to a real problem (the good > solution being, of course, to use the fully qualified name for > attributes so there's no possible ambiguity). The code fragment you've given way above (about the Foo, Bar, bazz, and func) also suffers from the bad habits of using the same name for different variables. And it's not a "braindead" rule (even though I used the word always, it still isn't a braindead always without exceptions) The example you've given IS the most readable form since the function is _simple_, consider a function that have complex codes, possibly calculations instead of simply assigning initial values I'm sure you'd slip up between the self.* variables and the * variables once or twice, possibly becoming the source of hard-to-find bugs. In other hand in a _complex_ function, if you thought of a new name, like initialfirstname, etc you'd know what is what and what is where immediately And in languages that doesn't enforce explicit naming of classes, when there is the two or more same names, the one with the smallest scope is picked, so in _simple_ functions, the trick of using full qualified names and overloaded local names is still possible and feasible. In complex functions, the trick fails even in Python, because even if Python and our full-concentration-brain is aware of the difference between self.* and *, our spreaded-concentration-brain that is scanning the code for the source of bugs might get stumbled on the confusing use of self.* and *. > >> Anyway, I actually know 3 languages (4 if C# works the same) that has > >> this implicit 'this' (or whatever the name) 'feature', and at least 5 > >> that don't. So I'm not sure that the "most other languages" qualifier > >> really applies to point 2 !-) > > > What's this 5 languages? > > Smalltalk, Python, PHP, javascript, Ruby. I don't remember how Scheme, > CLOS and OCaml handle the case. Among all them, only Javascript is considerably mainstream. Javascript, being virtually the only web-based scripting language that is supported by most browsers. > > Are they a mainstream, high-level languages > > or lesser known, low-level languages? C-family, Java, and Basic are > > the Big Three of high-level programming language. > > None of C, C++, Java nor Basic qualify as "hi-level". C is the lowest > possible level above assembly, C++ is often refered to as an "object > oriented assembler", Java is way too static, crippled, verbose an > unexpressive to qualify as "hi-level" (even if it suffers from some > problems usually associated with higher level languages). I won't even > comment on basic (is that really a language at all ?). Your criteria on being high-level is simply just odd. The rest of the world recognizes C-family, Java, and Basic as high-level languages. I agree C is a lower-level language compared to C++, C#, Basic, and Python, but standing by itself, it still qualifies as high-level language. If I have to say it, Python is actually lower level than Basic. While Java is just below Python and C and C++ is just below Java. Why do I consider Basic the highest-level? Because it is the cleanest to scan (no confusing symbols, i.e. no curly braces, no confusing use of parens (Python uses (), [], and {}, VB only use ()[3]), and that is also the reasons of some of its warts. In what way C++ resembles an assembler? Have you ever programmed in assembly? How hard is it to create a simple program in assembly? And how hard is it to create a complex program in C++ (which AFAIK is used by hundreds of mega projects including CPython)? And have you ever used Basic at all? Some programmers would instantly frown upon Basic, simply because they don't know that Basic is "just another language". Apart from a syntax that is very different from most languages (absence of curly braces, the minimal use of non-alphabet characters in the syntax, minimal use of short keywords, opting for keywords that is (hopefully) understandable to non VBers[4]), and apart from the quality of the implementation, the language itself isn't a bad language. Sure they may have some warts, but I dare to say "Python have no warts". [3] In fact the new VB.NET 2008 adds a syntax that uses curly braces to VB, but it's only for a syntax sugar, in Python, the difference between the different kind of parentheses is significant. [4] The only significant exception to, a (hopefully) understandable keyword names to non-VBers, is probably the most important keyword, "Dim" for variable declaration. > >>> In VB, Me is extremely rarely used, > >> I used to systematically use it - like I've always systematically used > >> 'this' in C++ ?and Java. > > > And that is what reduces readability. A proficient VB/C/Java > > programmer > > There are quite a few proficient C/C++/Java programmers here. As far as > I'm concerned, I would not pretend being one - I just have a good enough > knowledge of C, Java and (alas) VB to be able to get up to speed in a > reasonnable time frame. > > As a side note, the problem just doesn't exists in C, which has > absolutely no support for OO. When I said C, it might mean C and C-family, so please stop misunderstanding me. As a side note, the conversation we're just having is a real life example of using the name C when it means C-family, your mindset instantly protest that C doesn't have objects, while my mindset says "C" can't have meant C as a language since I don't state C++ and C# too while I should have, and knowing the fact that C in C-family doesn't have objects would make it clear that it is an exception. I'm not saying my mindset is better than yours (it have its positives and negatives), in fact I apologize for getting you confused. > > would frown upon the extra, unneeded garbage as they > > thought it was clear already that the variable refers to a class-level > > variable. > > In C++, the canonical way to make this "clear" is to use the m_name > convention. There must be some reason C++ programmers feel a need for > this "extra, unneeded garbage" ?-) In some cases, an extremely complex class that can't be fragmented any further, the m_ convention is surely useful, but in most cases you could skip them out. And the canonical way to make this "clear" is not the m_ convention, it's the name itself. A well-designed class would choose names that is recognizable instantly from the name itself, even without the pseudo-name appended to it (or prepended). btw you must have been memorizing names braindeadly, because the only way you could stumble on that is by memorizing names braindeadly. Names shouldn't be memorized, it should be inferred and memorized. For example, when you met a variable name firstname and lastname inside a class called Person, you'd immediately realize that it is Class Level variable because you know that the function you're currently working on use the name initialfirstname and initiallastname. > > It is a different story if, like Python, the use of self is > > enforced by the language, the self wouldn't be viewed as extra > > unnecessary garbage. > >>> in Python, self is all > >>> over the place. Well, there is positive and negative to both sides, > >>> convenience in VB, and flexibility in Python. > >> As far as I'm concerned, there's *no* positive point in implicit object > >> reference, and there has never been (and before some paranoid nutcase > >> around accuse me of overzealous biggotry : I already held this very same > >> opinion years before I discovered Python). > > > There is one major positive point: convenience and shorter code. > > (isn't that two?) > > These are not rated as "positive" in my book. That's perhaps why Python > is so far MFL ? Not in _your_ book. Different languages have been devised throughout the world to solve various problems, some of which are convenience in using the language itself. > > As I've pointed out, there is little harm in class-level variable's > > implicit reference. > > Have some working experience on any non-trivial C++ project ? No (you could say I'm a student so I've never "worked"[1]). But I've done some medium-sized projects in other languages. [1] If you understand the irony, you'd realized I was deliberately misunderstanding you > >>> Compare the following codes: > >>> VB.NET: > >>> Public Class A > >>> ? ? Dim var > >>> ? ? Public Function aFunction() > >>> ? ? ? ? return var > >> Add three levels of inheritence and a couple globals and you'll find out > >> that readability count !-) > > > It's the mental model that have to be adapted here, if the current > > class is inheriting from another class, you've got to think it as > > names from parent class as it is a native names, so you don't actually > > need to know where the variable comes from > > In C++ (and VB IIRC), it might as well be a global So sorry but yes, I > have to know where it comes from. How many times would you use globals, it is a Bad Thing(tm) to use globals in the first case. In some exceptional cases globals might be unavoidable, but it is trivial to work out that you have to reduce the amount of globals to a minimum, in almost any cases to a number you can use a hand to count with. And applying the hacks mentioned, why don't you use the m_ convention for globals, and retains the convenience of m_-free variables in your class variable. You use class variable much more often than globals, and in most projects class- level variable is used just as often as local-variable. > > since knowing where it > > comes from is breaking the encapsulation > > Nope, it's knowing what you're doing and how the piece of software at > hand is working. And FWIW, while data hiding is one possible mean of > encapsulation, it's by no way a synonym for encapsulation. I agree that knowing an underlying class's implementation is useful (in fact, very useful) but what I'm talking is about should-ness, we shouldn't _need_ to know the underlying implementation, but if we know it, it's fine and it's great, since you can do tricks that you couldn't do otherwise (at your own risks). No it's not synonym, but one way of encapsulation. > > (which, in Python is very > > weakly implemented, which favors flexibility in many cases[1]). > > > [1] In Python, it is impossible to create a completely private > > variable, which is the reason why the mental model of these other > > languages doesn't fit Python. > > Never heard about the infamous '#define private public' hack in C++ ? > And don't worry, there are also ways to get at so called 'private' vars > in Java. No, but it's violating the language's rule. Python OTOH, provides formal ways to got to private vars. > >> In any non-trivial piece of C++ code, and unless the author either used > >> the explicit 'this' reference or the 'm_xxx' naming convention, you'll > >> have hard time figuring out where a given name comes from when browsing > >> a function's code. > > > If you're used to the implicit naming scheme it's easy to know where a > > variable came from, if not the current scope, it's the class' scope > > You forgot the global scope. How many global variables do you have in your projects on average? If you always have a pageful list of globals in your projects, then you should consider unlearning and relearning the basic programming concepts. It's easy to keep track of globals, as you shouldn't have a lot of them even in a huge project. > > As a final note: > > I don't think implicit class reference is superior to explicit class > > reference, neither > > ... I'm sure you don't believe it since I'm talking on implicit's side, but that's the fact, I just pointed you out that implicits do have its positive side (even if you don't consider them positive in _your_ book) but that doesn't meant I believe it is better than the other. To clear things up: As a final note: I don't think implicit class reference is superior to explicit class reference, but I don't think the vice versa is true either. I consider they have their own positive and negative sides and different languages have different "better" definition, for Python it is explicit, for C/Java/Basic it's implicit. From arkanes at gmail.com Fri Jan 18 14:04:36 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 18 Jan 2008 13:04:36 -0600 Subject: strange syntax rules on list comprehension conditions In-Reply-To: References: Message-ID: <4866bea60801181104w46fd2b5cgf7fb436d6aad03e3@mail.gmail.com> On Jan 18, 2008 12:53 PM, Nicholas wrote: > I was quite delighted today, after extensive searches yielded nothing, to > discover how to place an else condition in a list comprehension. > Trivial mask example: > >>> [True if i <5 else False for i in range(10)] # A > [True, True, True, True, True, False, False, False, False, False] > > I then experimented to drop the else statement which yields an error > >>> [i if i>3 for i in range(10)] > Traceback ( File "", line 1 > this syntax works of course > >>> [i if i>3 else i for i in range(10)] > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > Does anybody else find this lack of symmetry odd? > "x if y else x" is an expression - it's the Python equivalent of C's ternary operator. The mechanism for filtering in a list comp is [x for x in y if x]. Your stumbling upon the ternary expression was a happy accident, and your confusing comes from trying to generalize the wrong operation. From pavloutefkros at gmail.com Mon Jan 28 13:10:17 2008 From: pavloutefkros at gmail.com (pavloutefkros at gmail.com) Date: Mon, 28 Jan 2008 10:10:17 -0800 (PST) Subject: referer url References: <0e7fb40e-809c-4979-bbb8-0cd9a7e816c2@t1g2000pra.googlegroups.com> Message-ID: <10f8327e-4348-436e-a771-c075afed559e@e25g2000prg.googlegroups.com> Thanks for that! i found the variable in "ALL_HTTP" and it's working now. Thanks again.. From george.sakkis at gmail.com Thu Jan 17 00:50:44 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 16 Jan 2008 21:50:44 -0800 (PST) Subject: next line (data parsing) References: <13otnvakq8kc6a3@corp.supernews.com> Message-ID: On Jan 17, 12:42 am, George Sakkis wrote: > On Jan 17, 12:01 am, Scott David Daniels > wrote: > > > > > robleac... at gmail.com wrote: > > > Hi there, > > > I'm struggling to find a sensible way to process a large chuck of > > > data--line by line, but also having the ability to move to subsequent > > > 'next' lines within a for loop. I was hoping someone would be willing > > > to share some insights to help point me in the right direction. This > > > is not a file, so any file modules or methods available for files > > > parsing wouldn't apply. > > > > I can iterate over each line by setting a for loop on the data object; > > > no problem. But basically my intension is to locate the line "Schedule > > > HOST" and progressively move on to the 'next' line, parsing out the > > > pieces I care about, until I then hit "Total", then I resume to the > > > start of the for loop which locates the next "Schedule HOST". > > > if you can do: > > > for line in whatever: > > ... > > > then you can do: > > > source = iter(whatever) > > for intro in source: > > if intro.startswith('Schedule '): > > for line in source: > > if line.startswith('Total'): > > break > > process(intro, line) > > > --Scott David Daniels > > Scott.Dani... at Acm.Org > > Or if you use this pattern often, you may extract it to a general > grouping function such ashttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877: Sorry, google groups fscked up with the auto linewrapping (is there a way to increase the line length?); here it is again: import re for line in iterblocks(source, start = lambda line: line.startswith('Schedule HOST'), end = lambda line: re.search(r'^\s*Total',line), skip_delim = False): process(line) George From martin at v.loewis.de Wed Jan 2 15:34:22 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Jan 2008 21:34:22 +0100 Subject: unicode(s, enc).encode(enc) == s ? In-Reply-To: <1310677e-51ec-49f2-9709-196dcc4e1ac9@e4g2000hsg.googlegroups.com> References: <5e49e7e6-f2b3-4c9f-9dec-e5f01f12d59a@e4g2000hsg.googlegroups.com> <4773f0de$0$15825$9b622d9e@news.freenet.de> <7cb20641-ab33-4818-a911-80c684cb9792@q77g2000hsh.googlegroups.com> <4775AC6B.8070109@v.loewis.de> <1310677e-51ec-49f2-9709-196dcc4e1ac9@e4g2000hsg.googlegroups.com> Message-ID: <477BF54E.7090000@v.loewis.de> > Thanks a lot Martin and Marc for the really great explanations! I was > wondering if it would be reasonable to imagine a utility that will > determine whether, for a given encoding, two byte strings would be > equivalent. But that is much easier to answer: s1.decode(enc) == s2.decode(enc) Assuming Unicode's unification, for a single encoding, this should produce correct results in all cases I'm aware of. If the you also have different encodings, you should add def normal_decode(s, enc): return unicode.normalize("NFKD", s.decode(enc)) normal_decode(s1, enc) == normal_decode(s2, enc) This would flatten out compatibility characters, and ambiguities left in Unicode itself. > But I think such a utility will require *extensive* > knowledge about many bizarrities of many encodings -- and has little > chance of being pretty! See above. > In any case, it goes well beyond the situation that triggered my > original question in the first place, that basically was to provide a > reasonable check on whether round-tripping a string is successful -- > this is in the context of a small utility to guess an encoding and to > use it to decode a byte string. This utility module was triggered by > one that Skip Montanaro had written some time ago, but I wanted to add > and combine several ideas and techniques (and support for my usage > scenarios) for guessing a string's encoding in one convenient place. Notice that this algorithm is not capable of detecting the ISO-2022 encodings - they look like ASCII to this algorithm. This is by design, as the encoding was designed to only use 7-bit bytes, so that you can safely transport them in Email and such (*) If you want to add support for ISO-2022, you should look for escape characters, and then check whether the escape sequences are among the ISO-2022 ones: - ESC ( - 94-character graphic character set, G0 - ESC ) - 94-character graphic character set, G1 - ESC * - 94-character graphic character set, G2 - ESC + - 94-character graphic character set, G3 - ESC - - 96-character graphic character set, G1 - ESC . - 96-character graphic character set, G2 - ESC / - 96-character graphic character set, G3 - ESC $ - Multibyte ( G0 ) G1 * G2 + G3 - ESC % - Non-ISO-2022 (e.g. UTF-8) If you see any of these, it should be ISO-2022; see the Wiki page as to what subset may be in use. G0..G3 means what register the character set is loaded into; when you have loaded a character set into a register, you can switch between registers through ^N (to G1), ^O (to G0), ESC n (to G2), ESC o (to G3) (*) > http://gizmojo.org/code/decodeh/ > > I will be very interested in any remarks any of you may have! >From a shallow inspection, it looks right. I would have spelled "losses" as "loses". Regards, Martin (*) For completeness: ISO-2022 also supports 8-bit characters, and there are more control codes to shift between the various registers. From sromero at gmail.com Thu Jan 10 03:14:42 2008 From: sromero at gmail.com (Santiago Romero) Date: Thu, 10 Jan 2008 00:14:42 -0800 (PST) Subject: How to get memory size/usage of python object References: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> Message-ID: <257fa40e-5a6d-4e1d-aefd-9439a182391c@f47g2000hsd.googlegroups.com> > Would you care to precisely define "REAL size" first? Consider: > > >>> atuple = (1, 2) > >>> mylist = [(0, 0), atuple] > > Should sizeof(mylist) include sizeof(atuple) ? No, I'm talking about "simple" lists, without REFERENCES to another objects into it. I mean: lists = [ 0, 1, 2, 3, 4, (1,2), 3] or array = [ [0,0,0,0,0,0,0], [1,1,1,1,2,1,2], ... ] Maybe I can "pickle" the object to disk and see the filesize ... :-? From PurpleServerMonkey at gmail.com Tue Jan 29 21:40:40 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Tue, 29 Jan 2008 18:40:40 -0800 (PST) Subject: Web Interface Recommendations References: <45040839-8b1f-40af-9ef5-1be274c6e95f@z17g2000hsg.googlegroups.com> <80d6ce9f-6c8b-412d-a261-cfe480bd0c3b@e10g2000prf.googlegroups.com> Message-ID: On Jan 30, 12:55 pm, Graham Dumpleton wrote: > On Jan 30, 12:00 pm, PurpleServerMonkey > wrote: > > > > > Looking for suggestions on the best framework to use for an > > applications web interface. > > > The user interface doesn't need immediate feedback and will be cross > > platform so a web interface is a good solution especially since it > > operates as a client\server system and not standalone. > > > However there's just so many frameworks to choose from it's very > > confusing. After a lot of reading it sounds like OSE or Cherrypy might > > be good options but I don't have any real world experience with these > > frameworks to go by. > > > Basically the interface won't be the application, it's used to input > > data and have the application act on it. It's going to have a > > Postgresql database and a number of service\daemon processes that do > > the actual work. It will also contain some form based information for > > keeping track of requests etc. and grow to a fair number of screens > > over time. > > > Given the above what framework would you recommend? > > Surprised you even looked at OSE. Although OSE has some features for > building HTML based web interfaces, they are very basic and not really > intended for building major stuff. OSE can still be useful for writing > backend applications, but would very much suggest you use just the XML- > RPC interfaces it provides to talk into its distributed messaging > system and service agent framework. > > If you use the XML-RPC interfaces then you can use a proper web > application framework for doing the actual HTML based user interface > front end. At that point you can choose any of the major frameworks, > such as Django, Pylons, TurboGears, CherryPy or web.py. > > Splitting the front end from the backend like this also means that > backend itself could be swapped out. Thus, instead of using OSE in the > backend, you could use simpler XML-RPC enabled Python applications, or > even use Pyro. In other words, you avoid intertwining code for front > end and backend too much, thus perhaps making it easier to change and > adapt as it grows. > > Graham Thanks Graham, decoupling the user interface and backend logic makes sense and definitely the way I want to go. Out of the major frameworks is there one that stands out as being particularly well suited for what I'm trying to do? Django and CherryPy are on the short list so I'll give them a detailed look although Pylons does sound rather interesting as well. From winterbeef at gmail.com Wed Jan 30 12:04:26 2008 From: winterbeef at gmail.com (beef) Date: Wed, 30 Jan 2008 09:04:26 -0800 (PST) Subject: MySQLdb and column names Message-ID: <38210bf5-afa4-4e5f-a66b-a6682278251e@l1g2000hsa.googlegroups.com> Hello all, I am using MySQLdb 1.2.2 and have a question about the construction of the dictionary keys of a result set. Here is an example query, from which you may intuit some of the structure of the tables: SELECT shots.*, users.*, sequences.*, jobs.* FROM shots LEFT JOIN users ON users.id=shots.user_id INNER JOIN sequences ON sequences.id=shots.sequence_id INNER JOIN jobs AS j ON j.id=sequences.job_id WHERE shots.id=%s 1. The 'users' table has a column named 'id', as do all the other tables. 2. I define my cursor as a 'DictCursor' so that my results are dictionaries 3. The 'shots' id has the key name of 'id', while all the -other- 'id's have key names of the form: ".id" I would prefer to have the key names consistent, so that event the "shots" fields have key names of the form "
.id" Is this possible? Thanks in advance! -- Wellington From grante at visi.com Sat Jan 26 00:02:43 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 26 Jan 2008 05:02:43 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <13plfnjgsfspr48@corp.supernews.com> On 2008-01-26, over at thepond.com wrote: > Once a python py file is compiled into a pyc file, I can disassemble > it into assembler. No you can't. It's not native machine code. It's byte code for a virtual machine. > Assembler is nothing but codes, which are combinations of 1's > and 0's. You can't read a pyc file in a hex editor, but you > can read it in a disassembler. NO YOU CAN'T. > It doesn't make a lot of sense to me right now, That's because IT'S NOT MACHINE CODE. > but if I was trying to trace through it with a debugger, That wouldn't work. > the debugger would disassemble it into assembler, > not python. You can "disassemble" random bitstreams into assembler. That doesn't make it a useful thing to do. [Honestly, I think you're just trolling.] -- Grant Edwards grante Yow! Yow! Is this sexual at intercourse yet?? Is it, visi.com huh, is it?? From steve at REMOVE-THIS-cybersource.com.au Fri Jan 18 17:43:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 18 Jan 2008 22:43:17 -0000 Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> <7xve5ruiam.fsf@ruckus.brouhaha.com> Message-ID: <13p2as5plhbpm74@corp.supernews.com> On Fri, 18 Jan 2008 09:58:57 -0800, Paul Rubin wrote: > David Sanders writes: >> The data files are large (~100 million lines), and this code takes a >> long time to run (compared to just doing wc -l, for example). > > wc is written in carefully optimized C and will almost certainly run > faster than any python program. However, wc -l doesn't do the same thing as what the Original Poster is trying to do. There is little comparison between counting the number of lines and building a histogram, except that both tasks have to see each line. Naturally the second task will take longer compared to wc. ("Why does it take so long to make a three-tier wedding cake? I can boil an egg in three minutes!!!") -- Steven From charles_hans at yahoo.com Wed Jan 30 16:40:35 2008 From: charles_hans at yahoo.com (Charles_hans) Date: Wed, 30 Jan 2008 13:40:35 -0800 (PST) Subject: Q: paramiko/SSH/ how to get a remote host_key In-Reply-To: References: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> <9077ed27-e9b1-47ca-b30e-918e3b50d517@e4g2000hsg.googlegroups.com> <15189222.post@talk.nabble.com> Message-ID: <15192764.post@talk.nabble.com> Thank you, Guilherme. I was running demo_sftp.py included in paramiko download. It seems that '.ssh/known_hosts' should be the path of a key file on my working directory on local PC. (Right?) I replaced this with 'test_rsa.key' in C:\paramiko-1.7.2\demos and this did not generate error. But the returned host_keys is empty. I traced the code to 'hostkeys.py' and found that the line e = HostKeyEntry.from_line(line) always retuned None. This means that my remote host name should have been in this key file. (Right?) I am very new to paramiko. How to create such a key file (with my remote host name)? Should I also load this key file into the remote server? Please advise. Thanks! Charles 1/30 2008/1/30, Charles_hans : > > I tried to get what host_key has been aquired after AutoPolicy is set. I > added the following code just before client.close() in rosty's final code: > > try: > host_keys = > paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) > except IOError: > try: > host_keys = > paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) > except IOError: > print '*** Unable to open host keys file' > > I still got 'Unable to open host keys file'. Can you tell me how to get > the > remote host_key under this situation? Thanks! > > Charles > 1/30/2008 Hey Charles, If you take a look on your code, you will see that you are catching IOError. So the problem you are noticing is related to I/O failing such as non-existent file. Be sure to check if '~/.ssh/known_hosts' exists, if the first try fails, check if "~/ssh/known_hosts" exists then (since you are trying to access that file). Cheers, > by rosty Jan 21, 2008; 08:43am : > > Thank you! Now it works and the code looks like this: > > import paramiko > import base64 > from paramiko import AutoAddPolicy, SSHClient > > client = paramiko.SSHClient() > client.set_missing_host_key_policy(AutoAddPolicy()) > client.connect('hostIP', username='uname', password='pass') > stdin, stdout, stderr = client.exec_command('ls') > for line in stdout: > print '... ' + line.strip('\n') > > client.close() -- View this message in context: http://www.nabble.com/Q%3A-paramiko-SSH--how-to-get-a-remote-host_key-tp14996119p15192764.html Sent from the Python - python-list mailing list archive at Nabble.com. From 42flicks at gmail.com Thu Jan 31 17:23:50 2008 From: 42flicks at gmail.com (Mike D) Date: Fri, 1 Feb 2008 11:23:50 +1300 Subject: Design question - Sharing of single object by multiple processes In-Reply-To: References: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> <47A1AC61.7080007@holdenweb.com> <2b54d4370801311206j457ef51cm33d2a2420b11e688@mail.gmail.com> <2b54d4370801311208s4af458cdp8cea665a04c3bd7a@mail.gmail.com> Message-ID: <2b54d4370801311423y52904ed9o1e26ac98dced45c6@mail.gmail.com> Steve, You raise some very good (and obvious) issues I did'nt consider. I'll look further into this sort of implementation as I'm quite interested. I suppose a compromise could be to load the objects from a pickle, that may have issues in terms of updating the pickle perhaps, though it would be much safer. I'll continue to investigate, thanks for your input. On Feb 1, 2008 11:00 AM, Steve Holden wrote: > Mike D wrote: > > Steve, > > > > Thanks for the response. My question really comes down to, as you > > suggested, premature optimization. > > > > It is more for my own understanding than a current practical use. > > > > If an object is loaded into memory and other threads(or processes) can > > recieve a pointer to this location, would this not be more efficient > > than to load a new one for every unique request? Wouldn't a method such > > as this prevent bottle necks in a read heavy environment? > > > In theory, yes. In practice there are problems, since modern operating > systems are explicitly designed to place barriers between the address > spaces of different processes. > > Even supposing you could access another Python process's space freely > you would then have issues like: > * does a reference from a foreign process add to an > object's reference count? > * if so, what happens if the foreign process terminates > without decrementing the reference count > * otherwise waht happens if the owning process disposes of > the object while the foreign process stil wants to refer > to it. > > I don't wish to be unkind, but these are well-known issues of > inter-process information sharing, and while superficial solutions can > seem easy, the more you think about and work on them the more obvious it > becomes that these are hard problems in the general case. > > Which will hopefully at least encourage you that you are addressing the > real issues of computing, even though there's a lot to do. > > > [...] > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lasses_weil at klapptsowieso.net Thu Jan 17 16:28:11 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 17 Jan 2008 22:28:11 +0100 Subject: bags? 2.5.x? In-Reply-To: References: <478bbae6$0$25383$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <478fc86f$0$25382$9b4e6d93@newsspool4.arcor-online.net> Dan Stromberg wrote: > The author of the bag class said that he was planning to submit bags for > inclusion in 2.5 - is there a particular reason why they didn't go in? > I wouldn't know. Not enough convincing use cases, I guess. Fools ;) > I keep finding a need for bags. In the past, I've done this sort of > thing with dictionaries, but it's much nicer to have a bag class, and of > course it's better to have it in the standard library than to slurp it > into this, that and the other project. > Then again, it is only one class. Also, if I may be so bold, why wouldn't a simple list fit your needs (other than performance, of course)? /W From tdelaney at avaya.com Thu Jan 10 17:49:30 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 11 Jan 2008 06:49:30 +0800 Subject: ISO Python example projects (like in Perl Cookbook) In-Reply-To: Message-ID: You know you've been working at a large company for too long when you see that subject and think "ISO-certified Python?" Tim Delaney From bkasterm at gmail.com Wed Jan 30 17:01:25 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Wed, 30 Jan 2008 14:01:25 -0800 (PST) Subject: Fw: Undeliverable Message References: Message-ID: On Jan 25, 5:05?am, Matthew_WAR... at bnpparibas.com wrote: > Hallo pyPeople, > > I wrote a little snippet of code that takes a list representing some > 'digits', and according to a list of symbols, increments the digits through > the symbol list. > > so for example, > > digits=["a","a","a"] > symbols=["a","b","c"] > > increment(digits,symbols) repeatedly would return digits as > > aab > aac > aba > abb > abc > aca > > etc.. > > Heres the code > > def increment(digits,symbols): > ? ? ? ? overflow=True > ? ? ? ? digitpos=-1 > ? ? ? ? while overflow and -digitpos<=len(digits): > ? ? ? ? ? ? ? ? digitsymbolindex=symbols.index(digits[digitpos]) > ? ? ? ? ? ? ? ? if digitsymbolindex==len(symbols)-1: > ? ? ? ? ? ? ? ? ? ? ? ? overflow=True > ? ? ? ? ? ? ? ? ? ? ? ? digits[digitpos]=symbols[0] > ? ? ? ? ? ? ? ? ? ? ? ? digitpos=digitpos-1 > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? digits[digitpos]=symbols[digitsymbolindex+1] > ? ? ? ? ? ? ? ? ? ? ? ? overflow=False > ? ? ? ? return digits > > Now, this works. All good. It's nice and simple. ?I'm just wondering how > anyone else might approach it? I (not an expert at all) have only minor comments and one question: comments: why keep setting overflow to True, if you do not touch it will not change. digitpos -= 1 is easier to read in my mind question: Why first extract the indices and then compare (in your if statement), and why do you not just compare the symbols? Best, Bart From faber at linuxnj.com Fri Jan 11 22:36:05 2008 From: faber at linuxnj.com (Faber J. Fedor) Date: Fri, 11 Jan 2008 22:36:05 -0500 Subject: Newbie Q: modifying SQL statements In-Reply-To: <87d4s8ndz2.fsf@mulj.homelinux.net> References: <20080111013206.GA18259@neptune.faber.nom> <20080110225352.2c112555@bhuda.mired.org> <87d4s8ndz2.fsf@mulj.homelinux.net> Message-ID: <20080112033605.GC24213@neptune.faber.nom> On 12/01/08 00:23 +0100, Hrvoje Niksic wrote: > "Faber J. Fedor" writes: > > Does this '("" if not where...' syntax actually work? > > http://docs.python.org/whatsnew/pep-308.html C'mon! I'm in Day Two of learning Python. You can't expect me to be reading "What's New" docs already! :-) I did find it interesting that the page mentioned said "Guido van Rossum eventually chose a surprising syntax:". When I first saw the construct I thought "Oh, they borrowed that from Perl". :-) (Although you can't do the else part in Perl, it is a natural extension, IMO.) -- Regards, Faber Fedor -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From gagsl-py2 at yahoo.com.ar Sat Jan 26 13:21:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 26 Jan 2008 16:21:10 -0200 Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <690cb460-fa8a-49a1-a6fa-69cdf480a918@i3g2000hsf.googlegroups.com> <7xir1hznuu.fsf@ruckus.brouhaha.com> Message-ID: En Fri, 25 Jan 2008 17:50:17 -0200, Paul Rubin <"http://phr.cx"@NOSPAM.invalid> escribi?: > Nicko writes: >> # The next line is order O(n) in the number of chunks >> (line, fileindex) = min(mergechunks) > > You should use the heapq module to make this operation O(log n) instead. Or forget about Python and use the Windows sort command. It has been there since MS-DOS ages, there is no need to download and install other packages, and the documentation at http://technet.microsoft.com/en-us/library/bb491004.aspx says: Limits on file size: The sort command has no limit on file size. Better, since the OP only intents to extract lines starting with "zz", use the findstr command: findstr /l /b "zz" filename.exe would do the job. Why doing things more complicated than that? -- Gabriel Genellina From nyamatongwe+thunder at gmail.com Fri Jan 11 17:18:22 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 11 Jan 2008 22:18:22 GMT Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: Marty: > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) Another way to write this is data_out = [[]] * len(data_in) Neil From xena-die-kriegerprinzessin at gmx.de Fri Jan 25 10:16:34 2008 From: xena-die-kriegerprinzessin at gmx.de (Heiko Niedermeyer) Date: Fri, 25 Jan 2008 15:16:34 +0000 (UTC) Subject: How to create graphs an embed them in GUI? References: Message-ID: This is just a brief summary, how I'm trying to do it now. In case somone ever encouters a problem like this... For the 2D part, I'm going with matplotlib, which seems to do, what I want. The 3D is currently donw be vpython, which is not great, but sufficient... Maybe I will switch when I find something better... ;) Thanks anyway. From bignose+hates-spam at benfinney.id.au Wed Jan 30 00:33:23 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jan 2008 16:33:23 +1100 Subject: ISO with timezone References: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Message-ID: <87tzkvdgik.fsf@benfinney.id.au> "Nicholas F. Fabry" writes: > The constructor for class datetime has a method, .now() that returns > the current date and time, as a naive datetime object (i.e. no > tzinfo attached). It's not "the constructor for class 'datetime'" that has that method; rather, the class 'datetime' has that method. (If anything is "the constructor for class 'datetime'", it's the '__new__' method -- or, some might argue, the '__init__' method -- and that doesn't fit what you say above.) > Dates and Times are a bit ugly in Python. Don't be discouraged, but > you do need to understand them quite well to get bug-free code that > plays with them. This is unfortunately true. Native datetime support is improving, but slowly. -- \ "[T]he speed of response of the internet will re-introduce us | `\ to that from which our political systems have separated us for | _o__) so long, the consequences of our own actions." -- Douglas Adams | Ben Finney From duncan.booth at invalid.invalid Tue Jan 29 15:17:42 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Jan 2008 20:17:42 GMT Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> Message-ID: Berteun Damman wrote: > On Tue, 29 Jan 2008 09:23:16 -0800 (PST), attn.steven.kuo at gmail.com > wrote: >> If you're going to delete elements from >> a list while iterating over it, then do >> it in reverse order: > > Why so hard? Reversing it that way creates a copy, so you might as > well do: >>>> a = [ 98, 99, 100 ] >>>> for i, x in enumerate(a[:]): > ... if x == 99: del(a[i]) > ... print x Why so hard? >>> a = [ 98, 99, 100, 98, 99, 100 ] >>> for i, x in enumerate(a[:]): if x == 99: del(a[i]) >>> a [98, 100, 98, 99] oops! But: >>> a = [ 98, 99, 100, 98, 99, 100 ] >>> last_idx = len(a) - 1 >>> for i, x in enumerate(a[::-1]): if x == 99: del(a[last_idx - i]) >>> a [98, 100, 98, 100] Reversing it works. Your code doesn't. From deets at nospam.web.de Wed Jan 16 10:36:36 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jan 2008 16:36:36 +0100 Subject: list classes in package References: <5cff1706-3bb1-4a54-bccb-175ff384788c@q77g2000hsh.googlegroups.com> Message-ID: <5v6mk4F1kbh4nU1@mid.uni-berlin.de> Dmitry wrote: > Hi All, > > I've trying to develop one Python application, and > neet to solve one problem. I need to list all classes defined in one > package (not module!). > > Could anybody please show me more convinient (correct) way to > implement this? Look at the module inspect and it's predicates. Something like for name in dir(module_or_package): if inspect.isclass(getattr(module_or_package, name)): print "%s is a class" % name Diez From mr.cerutti at gmail.com Fri Jan 4 15:53:06 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 4 Jan 2008 15:53:06 -0500 Subject: fastest method to choose a random element In-Reply-To: <51302a8c0801041247jc9a6c8ej10e346b8357bacdc@mail.gmail.com> References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <51302a8c0801041247jc9a6c8ej10e346b8357bacdc@mail.gmail.com> Message-ID: <51302a8c0801041253q5fd2e2c8tf301d037ad118e01@mail.gmail.com> On Jan 4, 2008 3:47 PM, Neil Cerutti wrote: > On Jan 4, 2008 2:55 PM, wrote: > > > Hello, > > This is a question for the best method (in terms of performance > > only) to choose a random element from a list among those that satisfy > > a certain property. > > > > A simple approach is: > > > > import random > > def random_pick(a_list,property): > > '''Returns a random element from a list that has the property > > > > Returns None if no element has the property > > ''' > > random.shuffle(a_list) > > for i in a_list: > > if property(i): return i > > > I'm pretty sure you don't want to use a destructive random_pick function. > You'll have to shuffle a copy instead to avoid that problem. > I thought of another one based on combining the above with the linear search idea, minimizing the calls to the predicate function. indexes = range(len(a_list)) random.shuffle(indexes) for ix in indexes: if predicate(a_list[ix]) return a_list[ix] raise ValueError('no matching element in list') -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Jan 21 03:53:10 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Jan 2008 09:53:10 +0100 Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> Message-ID: Santiago Romero wrote: > I'm trying to sort both lists so that they end like this: > > preferences = [10, 20, 30] > hosts = [ "mx1.domain.com", "mx2.domain.com", > "anotherhost.domain.com" ] > > I want to sort hosts list depending on the numeric order of > "preferences". The following relies on undocumented (I hope) behaviour: >>> preferences = [10, 30, 20] >>> hosts = [ "mx1.domain.com", "anotherhost.domain.com", "mx2.domain.com"] >>> hosts.sort(key=lambda x, p=iter(preferences).next: p()) >>> preferences.sort() >>> hosts ['mx1.domain.com', 'mx2.domain.com', 'anotherhost.domain.com'] >>> preferences [10, 20, 30] Don't do it, use a list of tuples as already suggested. Peter From fredrik at pythonware.com Fri Jan 4 09:17:22 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 15:17:22 +0100 Subject: how to build a dict including a large number of data In-Reply-To: References: Message-ID: wanzathe wrote: > i have a binary file named test.dat including 9600000 records. > the record format is int a + int b + int c + int d > i want to build a dict like this: key=int a,int b values=int c,int d > i choose using bsddb and it takes about 140 seconds to build the dict. you're not building a dict, you're populating a persistent database. storing ~70000 records per second isn't that bad, really... > what can i do if i want to make my program run faster? > or is there another way i can choose? why not just use a real Python dictionary, and the marshal module for serialization? From fredrik at pythonware.com Thu Jan 10 15:20:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 21:20:42 +0100 Subject: XML+Logs to Latex. XSLT? In-Reply-To: References: Message-ID: Florencio Cano wrote: > I'm thinking about implementing a script in Python to do this task. I > have a XML log and logs from other programs. My aim is to do a report > about all this information. I'm thinking in using Python to transform > the plain logs to XML and combine them with the XML document I have > and later use some kind of XSLT to transform the whole XML document to > Latex. What do you think about that? I have not worked with XSLT > before and I don't know if this would be a correct use. > How will you do the job? why not do it all in Python? From dwbear75 at gmail.com Wed Jan 16 22:12:08 2008 From: dwbear75 at gmail.com (DwBear75) Date: Wed, 16 Jan 2008 19:12:08 -0800 (PST) Subject: examples of logger using smtp Message-ID: I am hoping to find some simple examples of how to create a logger instance using smtphandler. I don't want to create a separate ini file. I just want to sent the smtphost, from, to right in the code when I instantiate the logger. I can't seem to find simple code on how to do this. Any pointers ? From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 19:11:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 00:11:23 -0000 Subject: encrypting python modules References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> Message-ID: <13og1dbe4qcfs2b@corp.supernews.com> On Fri, 11 Jan 2008 10:44:36 +0100, Paul Sijben wrote: > Hello, > > this question has come by repeatedly in several guises over the past > years but has never been solved in this forum as far as I have been able > to Google. > > However since so many people are asking the question, I hope someone has > made a solution and is willing to share it. > > The problem: I have a client-server app written in python. I want to > make sure that the client is not: > 1) destabilized by users accidentally or on purpose dropping python > files in the path (after which calling the helpdesk will not be useful) > 2) extended with "new features" without me knowing about it (again > resulting in calls to my helpdesk...) How often do these things *actually* happen? Of those that actually do it, how many are clueless enough that when they run into problems they blame you for it? (And remember that you won't even find out about the non-clueless ones.) -- Steven From bernard.desnoues at univ-paris1.fr Mon Jan 21 09:24:34 2008 From: bernard.desnoues at univ-paris1.fr (Bernard Desnoues) Date: Mon, 21 Jan 2008 15:24:34 +0100 Subject: stdin, stdout, redmon In-Reply-To: References: <4794a5e3$0$9014$426a74cc@news.free.fr> Message-ID: <4794ab22$0$19179$426a74cc@news.free.fr> Rolf van de Krol a ?crit : > According to various tutorials this should work. > > > |import sys > data = sys.stdin.readlines() > print "Counted", len(data), "lines."| > > > Please use google before asking such questions. This was found with only > one search for the terms 'python read stdin' > > Rolf > > Bernard Desnoues wrote: >> Hi, >> >> I've got a problem with the use of Redmon (redirection port monitor). >> I intend to develop a virtual printer so that I can modify data sent >> to the printer. >> Redmon send the data flow to the standard input and lauchs the Python >> program which send modified data to the standard output (Windows XP >> and Python 2.5 context). >> I can manipulate the standard output. >> >> "import sys >> sys.stdout.write(data)" >> >> it works. >> But how to manipulate standard input so that I can store data in a >> string or in an object file ? There's no "read" method. >> >> "a = sys.stdin.read()" doesn't work. >> "f = open(sys.stdin)" doesn't work. >> >> I don't find anything in the documentation. How to do that ? >> Thanks in advance. >> >> Bernard Desnoues >> Librarian >> Biblioth?que de g?ographie - Sorbonne Hello Rolf, I know this code because I have search a solution ! Your google code doesn't work ! No attribute "readlines". >>> import sys >>> data = sys.stdin.readlines() Traceback (most recent call last): File "", line 1, in data = sys.stdin.readlines() AttributeError: readlines From pyth0nc0d3r at gmail.com Sat Jan 19 14:12:17 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Sat, 19 Jan 2008 13:12:17 -0600 Subject: Okay I got a question regarding Tkinter and Labels Message-ID: Okay I've created a script and basically when I loop through a folder it is supposed to change the Label everytime it updates a file then again it doesn't do nothing but shows the last file edited, whats the best way to loop through files and display that file name in a Label's text without skipping to the last one when the loop is finished? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Mon Jan 28 06:52:01 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 28 Jan 2008 13:52:01 +0200 Subject: Using a dict as if it were a module namespace. Message-ID: <001001c861a4$48e42060$03000080@hendrik> On Sunday 27 January 2008 09:45, Steven D'Aprano wrote: > I have a problem which I think could be solved by using a dict as a > namespace, in a similar way that exec and eval do. > > When using the timeit module, it is very inconvenient to have to define > functions as strings. A good alternative is to create the function as > normal, and import it: > > def myfunc(x, y): > return x+y > > timeit.Timer("myfunc(59, 60)", "from __main__ import myfunc").timeit() > > > Not only is this an easy idiom to follow, but myfunc can live in another > module: just replace __main__ with the module name. > > Now, I'm trying to build a suite of tests to use with timeit. I have a > bunch of tests which I've created as dicts: > > test_suite= [dict(x=59, y=60), dict(x=-1, y=-2)] This is probably the wrong answer: test_suite = [(59,60),(-1,-2)] for test in test_suite: x,y = test Then do the magic with x and y - Hendrik From tenax.raccoon at gmail.com Mon Jan 21 09:55:40 2008 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 21 Jan 2008 06:55:40 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: On Jan 21, 12:00 am, Albert Hopkins wrote: > On Sun, 20 Jan 2008 20:16:18 -0800, Paddy wrote: > > I am definitely NOT a floating point expert, but I did find this: > >http://en.wikipedia.org/wiki/IEEE_754r#min_and_max > > > P.S. What platform /Compiler are you using for Python? > > Linux with GCC 4 > > -a Please note that NaN's are very funky and platform dependent. They depend on their underlying platform's C library for creation and display. On windows, "float('nan')" will cause an exception, as there are no valid string representations of NAN that can be converted to the special floating point value. Also, if you manage to create a nan under Windows, it displays as "1.#QNAN". Infinite values are also problematic. In almost all cases, it is far better to avoid infinite and NaN values. --Jason From paddy3118 at googlemail.com Wed Jan 9 16:25:47 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 13:25:47 -0800 (PST) Subject: alternating string replace: Extended input (Long). References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <3a5c974a-676f-4401-a8bb-06a537b1015c@v4g2000hsf.googlegroups.com> Message-ID: <59decf52-d923-4433-bcad-8c41fc1e13d3@v4g2000hsf.googlegroups.com> On Jan 9, 8:47 pm, bearophileH... at lycos.com wrote: > Donald 'Paddy' McCarthy: > > [... lots and lots and lots of tests...] > > C'mon Paddy, where are the timings too? Are you becoming lazy > lately? ;-) > > Bear bugs, > bearophile Get it right before you get it fast. But what is 'right'. From israelu at elbit.co.il Sun Jan 20 05:51:21 2008 From: israelu at elbit.co.il (iu2) Date: Sun, 20 Jan 2008 02:51:21 -0800 (PST) Subject: Hebrew in idle ans eclipse (Windows) References: <478ee0c0$0$4589$9b622d9e@news.freenet.de> <86ea4c94-f4b3-4bc3-9b2a-bc9b5c182264@i12g2000prf.googlegroups.com> <478FBC1A.4080201@v.loewis.de> Message-ID: <65cc5058-efd1-43bf-91ea-1062daa1fa62@v46g2000hsv.googlegroups.com> On Jan 17, 10:35?pm, "Martin v. L?wis" wrote: > > import pymssql > > > con = > > pymssql.connect(host='192.168.13.122',user='sa',password='',database='tempd?b') > > cur = con.cursor() > > cur.execute('select firstname, lastname from [users]') > > lines = cur.fetchall() > > > print lines > > > or > > > print lines[0] > > > 'lines' is a list containing tuples of 2 values, for firstname and > > lastname. The names areHebrewand their code looks different when I'm > > runnig it fromIDLEthan when running it from Windows shell or > >eclipse, as I described in my first post. > > Ok. Please understand that there are different ways to represent > characters as bytes; these different ways are called "encodings". > > Please also understand that you have to make a choice of encoding > every time you represent characters as bytes: if you read it from a > database, and if you print it to a file or to the terminal. > > Please further understand that interpreting bytes in an encoding > different from the one they were meant for results in a phenomenon > called "moji-bake" (from Japanese, "ghost characters"). You get > some text, but it makes no sense (or individual characters are incorrect). > > So you need to find out > a) what the encoding is that your data have in MySQL > b) what the encoding is that is used when printing inIDLE > c) what the encoding is that is used when printing into > ? ?a terminal window. > > b) and c) are different on Windows; the b) encoding is called > the "ANSI code page", and c) is called the "OEM code page". > What the specific choice is depends on your specific Windows > version and local system settings. > > As for a: that's a choice somebody made when the database > was created; I don't know how to figure out what encoding > MySQL uses. > > In principle, rather than doing > > ? print lines[0] > > you should do > > ? print lines[0].decode("").encode("") > > when printing to the console. Furtenately, you can also write > this as > > ? print lines[0].decode("") > > as Python will figure out the console encoding by itself, but > it can't figure out the MySQL encoding (or atleast doesn't, > the way you use MySQL). > > Regards, > Martin- Hide quoted text - > > - Show quoted text - Thanks for the detailed explanation. I'll try that. From bignose+hates-spam at benfinney.id.au Wed Jan 23 19:14:32 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 24 Jan 2008 11:14:32 +1100 Subject: Increment Variable Name References: <87myqw87lt.fsf@benfinney.id.au> Message-ID: <87abmw84gn.fsf@benfinney.id.au> Pablo Ziliani writes: > Ben Finney wrote: > > This has a very bad code smell (...) > > > > \ `\ _o__) Ben Finney > > That is forcefulness. > (sorry, couldn't resist) I suspect that's a comment on my online nickname, "bignose", and talking about code smells. Nevertheless, it's probably a good opportunity to point out that "code smell" is a term with a specific, useful meaning in programming. -- \ "[Freedom of speech] isn't something somebody else gives you. | `\ That's something you give to yourself." -- _Hocus Pocus_, Kurt | _o__) Vonnegut | Ben Finney From ian at neustyle.com Mon Jan 7 11:13:12 2008 From: ian at neustyle.com (Soviut) Date: Mon, 7 Jan 2008 08:13:12 -0800 (PST) Subject: list property fires get on append References: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com> <930rlf.mc3.ln@127.0.0.1> Message-ID: <04953c5a-dd24-4e80-aed6-0fbb18218759@v4g2000hsf.googlegroups.com> On Jan 6, 11:36 am, Carl Banks wrote: > On Sun, 06 Jan 2008 00:31:13 -0800, Soviut wrote: > > I figured that an append would be treated as a set since I'm adding to > > the list. But what you say makes sense, although I can't say I'm happy > > with the behaviour. Is there any way I can get the append to fire a > > set? I'm thinking of properties from my C# background where i believe > > that manipulation such this would be considered a set. > > You'd have to have to hook into the container object itself to detect the > modification. This might be pretty workable for you since it's an > internal object. Basically, instead of using a list, use a special list- > like object that notifies it's owner when it changes. Here's a simple > example to point you in the right direction: > > class NotifierList(list): > def __init__(self,*args,**kwargs): > super(NotifierList,self).__init__(*args,**kwargs) > self.watchers = [] > def add_watcher(self,watcher): > self.watchers.append(watcher) > def _notify_watchers(self): > for watcher in self.watchers: > watcher.object_changed(self) > def append(self,value): > super(NotifierList,self).append(value) > self._notify_watchers() > # override all other mutating calls, including __setitem__ > # left as exercise > > class Hierarchy(object): > def __init__(self): > self.children = NotifierList() > self.children.add_watcher(self) > def object_changed(self,obj): > print "self.children modified" > # no need to make children a property then > # unless you want to trap rebinding it to new object also > > A couple other minor suggestions: > > print is a statement, not a function. You should write > > print "GETTING" > > not > > print("GETTING") > > The latter works, but it will cease to work if you want to print more > than one thing. Note that print is scheduled to become a function in > Python 3.0, but for now it's a statement. > > Based on the name of your class and typical usage, I'm guessing that you > probably want _children to be an instance attribute rather than a class > attribute, so I redid it that way, but .) > > P.S. Is calling a method called "firing" in C#? > > Carl Banks Thanks for the help, there's a lot to digest there but I realized that I was having issues with _children being a class attribute when I noticed every single instance had the same _children list. I've since moved things into my __init__ method. Basically the reason I needed to use a property was to run a private helper method that sets references to the parent and root nodes of my hierarchy. Since I was simply appending to my children list, there was no callback to tell the container to process the children. And no, calling a method is not necessarily called "firing", but I've been using the term a lot recently when dealing with events so it seemed appropriate. From mayasmith1 at gmail.com Sat Jan 19 06:20:42 2008 From: mayasmith1 at gmail.com (mayasmith1 at gmail.com) Date: Sat, 19 Jan 2008 03:20:42 -0800 (PST) Subject: All about DOGS Message-ID: Hi How much do you know about Dogs? http://www.dogsinfos.com From cokofreedom at gmail.com Wed Jan 23 04:03:14 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 23 Jan 2008 01:03:14 -0800 (PST) Subject: HTML parsing confusion References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> <50269e4a-af44-4d73-b6cb-c42af6b5164d@e10g2000prf.googlegroups.com> <5vmkiiF1nadr7U1@mid.uni-berlin.de> <6cc92ad4-4448-4254-8c01-a04b0c035117@d21g2000prf.googlegroups.com> Message-ID: > The pages I'm trying to write this code to run against aren't in the > wild, though. They are static html files on my company's lan, are very > consistent in format, and are (I believe) valid html. Obvious way to check this is to go to http://validator.w3.org/ and see what it tells you about your html... From cokofreedom at gmail.com Wed Jan 16 12:14:50 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 16 Jan 2008 09:14:50 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> <478c868a$0$7040$426a34cc@news.free.fr> <5c0a472a-5ed6-4b34-9685-42f9a0a4145e@k39g2000hsf.googlegroups.com> <13osdhmkb1jpvd9@corp.supernews.com> Message-ID: <1a1ed037-9af0-4b43-a46a-ed91c9bb205f@q77g2000hsh.googlegroups.com> On Jan 16, 5:52 pm, Ed Jensen wrote: > cokofree... at gmail.com wrote: > > A lecturer gave me the perfect answer to the question of speed. > > > "You have two choices when it comes to programming. Fast code, or fast > > coders." > > "You're either with us, or against us." > > George W. Bush > > My understanding is that while CPython performance won't be winning > any awards anytime soon, Jython and IronPython are pretty impressive > performers. > > Disclaimer: I haven't personally used Jython or IronPython. Indeed, it is as Paul Rudin said; "It's more a continuum than that suggests. The tricky bit is deciding in each situation where you should be on the continuum." From robert.kern at gmail.com Tue Jan 22 03:09:39 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 22 Jan 2008 02:09:39 -0600 Subject: what's this instance? In-Reply-To: <47959D11.3040806@block.duxieweb.com> References: <47959D11.3040806@block.duxieweb.com> Message-ID: J. Peng wrote: > def safe_float(object): > try: > retval = float(object) > except (ValueError, TypeError), oops: > retval = str(oops) > return retval > > x=safe_float([1,2,3,4]) > print x > > > The code above works well.But what's the instance of "oops"? where is it > coming from? I'm totally confused on it.thanks. The line except (ValueError, TypeError), oops: will trap ValueError and TypeError exceptions. The actual exception object will be assigned to the name "oops". -- 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 python.list at tim.thechases.com Fri Jan 18 13:06:56 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 18 Jan 2008 12:06:56 -0600 Subject: Efficient processing of large nuumeric data file In-Reply-To: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <4790EAC0.2000800@tim.thechases.com> > for line in file: The first thing I would try is just doing a for line in file: pass to see how much time is consumed merely by iterating over the file. This should give you a baseline from which you can base your timings > data = line.split() > first = int(data[0]) > > if len(data) == 1: > count = 1 > else: > count = int(data[1]) # more than one repetition Well, some experiments I might try: try: first, count = map(int, data) except: first = int(data[0]) count = 1 or possibly first = int(data[0]) try: count = int(data[1]) except: count = 0 or even # pad it to contain at least two items # then slice off the first two # and then map() calls to int() first, count = map(int,(data + [1])[:2]) I don't know how efficient len() is (if it's internally linearly counting the items in data, or if it's caching the length as data is created/assigned/modifed) and how that efficiency compares to try/except blocks, map() or int() calls. I'm not sure any of them is more or less "pythonic", but they should all do the same thing. > if first in hist: # add the information to the histogram > hist[first]+=count > else: > hist[first]=count This might also be written as hist[first] = hist.get(first, 0) + count > Is a dictionary the right way to do this? In any given file, there is > an upper bound on the data, so it seems to me that some kind of array > (numpy?) would be more efficient, but the upper bound changes in each > file. I'm not sure an array would net you great savings here, since the upper-bound seems to be an unknown. If "first" has a known maximum (surely, the program generating this file has an idea to the range of allowed values), you could just create an array the length of the span of numbers, initialized to zero, which would reduce the hist.get() call to just hist[first] += count and then you'd iterate over hist (which would already be sorted because it's in index order) and use those where count != 0 to avoid the holes. Otherwise, your code looks good...the above just riff on various ways of rewriting your code in case one nets you extra time-savings per loop. -tkc From Max_Abrahams at brown.edu Thu Jan 31 14:34:48 2008 From: Max_Abrahams at brown.edu (Abrahams, Max) Date: Thu, 31 Jan 2008 14:34:48 -0500 Subject: best(fastest) way to send and get lists from files Message-ID: <4A1A35F8C85B294296F1911569C1137D034B5B57@MAIL2.AD.Brown.Edu> I've looked into pickle, dump, load, save, readlines(), etc. Which is the best method? Fastest? My lists tend to be around a thousand to a million items. Binary and text files are both okay, text would be preferred in general unless there's a significant speed boost from something binary. thanks From hniksic at xemacs.org Fri Jan 11 09:41:20 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 11 Jan 2008 15:41:20 +0100 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> Message-ID: <877iiga0hb.fsf@mulj.homelinux.net> Bruno Desthuilliers writes: > fact 1: CPython compiles source code to byte-code. > fact 2: CPython executes this byte-code. > fact 3: Sun's JDK compiles source code to byte-code. > fact 4: Sun's JDK executes this byte-code. > > Care to prove me wrong on any of these points ? Don't bother: you > can't. Fact 4 is misleading because it is only one option available to Sun's JDK. Sun's JDK is also capable of transforming the byte-code to native code and letting the processor execute that instead of the original byte code, and that is where the most significant speed increase comes from. Most importantly, it does so automatically, by default, with no programmer intervention or configuration, and with 100% compatibility, so it doesn't compare well to Python accelerators like psyco. From grflanagan at yahoo.co.uk Fri Jan 18 07:32:36 2008 From: grflanagan at yahoo.co.uk (grflanagan) Date: Fri, 18 Jan 2008 04:32:36 -0800 (PST) Subject: How to detect a remote webpage is accessible? (in HTTP) References: Message-ID: On Jan 18, 6:22 am, "??" wrote: > Howdy, all, > I want to use python to detect the accessibility of website. > Currently, I use urllib > to obtain the remote webpage, and see whether it fails. But the problem is that > the webpage may be very large; it takes too long time. Certainly, it > is no need to download > the entire page. Could you give me a good and fast solution? > Thank you. > -- > ShenLei http://groups.google.com/group/comp.lang.python/browse_frm/thread/bbac82df3d64d48e/da75e45a8da2f6c1 From dannox at gmail.com Tue Jan 22 01:46:03 2008 From: dannox at gmail.com (whatazor) Date: Mon, 21 Jan 2008 22:46:03 -0800 (PST) Subject: Calculate net transfer rate without dummy file Message-ID: Hi, how can I calulate transfer rate to a host , without using a file ? can ping module (written by Jeremy Hylton) be useful ? From workitharder at gmail.com Wed Jan 2 21:20:01 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 2 Jan 2008 18:20:01 -0800 (PST) Subject: Information about including module? References: Message-ID: <211fd5f6-c2c6-43ee-9ce3-56eeba3583fc@h11g2000prf.googlegroups.com> On Jan 2, 4:52 pm, bukzor wrote: > Is there any way to print the docstring of the including module? I'd > like to be able to do something like the following > > file one.py: > > "some docstring" > include two > > file two.py: > from magicmodule import getincluder > print getincluder().__doc__ > > Running one.py would print the docstring. > > Thanks! > Buck Answered my own question: def getimporter(): from inspect import stack for info in stack(): text = info[4][0].split() if 'import' in text and text[0] in ('from', 'import'): return info[0].f_locals print getimporter()['__doc__'] This is a simplified version of the recipe here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473823 From guptaabhishek1983 at gmail.com Sat Jan 12 02:31:03 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Fri, 11 Jan 2008 23:31:03 -0800 (PST) Subject: Successfully created installer for python2.5 compiled code under .net2005 Message-ID: Hi group i have created an installer for python 2.5 compiled under .NET 2005. Any one looking for help on doing this feel free to contact me at abhishek at medspheretech.com or guptaabhishek1983 at gmail.com From musiccomposition at gmail.com Thu Jan 3 13:38:08 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 3 Jan 2008 10:38:08 -0800 (PST) Subject: reassign to builtin possible !? References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> Message-ID: On Jan 3, 7:04 am, Bernhard Merkle wrote: > Hi there, > > I am reading Learning Python 3e from Mark Lutz and just found out that > reassigning to builtins is possible. > What is the reason, why Python allows this ? IMO this is very risky > and can lead to hard to find errors. I don't think it's a huge issue. In fact, I think it's a feature. For example, it'd be extremely issue to reassign open, if you wanted to implement a virtual file system, and you couldn't modify the module the used open. > (see also Learning Python 3e, Chapter 16, Page 315) > > >>> True > True > >>> False > False > >>> True = 1 > >>> True > 1 > >>> True = 0 > >>> True > > 0 > > TIA, > Berni From bj_666 at gmx.net Sun Jan 27 05:36:17 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jan 2008 10:36:17 GMT Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <690cb460-fa8a-49a1-a6fa-69cdf480a918@i3g2000hsf.googlegroups.com> <7xir1hznuu.fsf@ruckus.brouhaha.com> <13polidj792mi26@corp.supernews.com> Message-ID: <603551F1oh17aU2@mid.uni-berlin.de> On Sun, 27 Jan 2008 10:00:45 +0000, Grant Edwards wrote: > On 2008-01-27, Stefan Behnel wrote: >> Gabriel Genellina wrote: >>> use the Windows sort command. It has been >>> there since MS-DOS ages, there is no need to download and install other >>> packages, and the documentation at >>> http://technet.microsoft.com/en-us/library/bb491004.aspx says: >>> >>> Limits on file size: >>> The sort command has no limit on file size. >> >> Sure, since no-one can ever try it with more than 640k, it's >> easy to state that there is no limit. :) > > Huh? I used DOS sort to sort files much bigger than 640K. That was an allusion to a quote misattributed to Bill Gates about DOS: 640K ought to be enough for anybody. http://en.wikiquote.org/wiki/Bill_Gates#Misattributed Ciao, Marc 'BlackJack' Rintsch From gregturn at mindspring.com Tue Jan 8 18:39:04 2008 From: gregturn at mindspring.com (Goldfish) Date: Tue, 8 Jan 2008 15:39:04 -0800 (PST) Subject: Spring Python 0.3.2 is release! Message-ID: <758abcf7-43f4-4fc8-9dcb-57474563e14c@t1g2000pra.googlegroups.com> Spring Python (http://springpython.python-hosting.com) version 0.3.2 was released yesterday. It contains a patch to an error discovered 12/19/2007 in XmlApplicationContext, that broke when PROTOTYPE scoping was used. Test cases have been updated to detect this bug, and in turn the correction was made in released. Get it while its hot! From lasses_weil at klapptsowieso.net Sun Jan 27 18:39:02 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 28 Jan 2008 00:39:02 +0100 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> Message-ID: <479d1616$0$9100$9b4e6d93@newsspool2.arcor-online.net> Dustan wrote: >> Well, you save one or two lines per class. Not enough in my >> opinion. > > Are you referring to the alternate syntax or to the decorator? Either > way, you could be saving 4 or 5 or more lines, if you have enough > arguments. OK, but then again, every decent IDE should give you the tools to write an automation for that. Not that I don't like the idea of auto-assignment, but, you know ... /W From victorsubervi at gmail.com Fri Jan 4 10:17:09 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 4 Jan 2008 11:17:09 -0400 Subject: How Does This Static Variable Work? Message-ID: <4dc0cfea0801040717u9bc67ccr80447dc375502445@mail.gmail.com> Hi; I read this example somewhere, but I don't understand it <:-) Can someone please explain how static variables work? Or recommend a good how-to? import random def randomwalk_static(last=[1]): # init the "static" var(s) rand = random.random() # init a candidate value if last[0] < 0.1: # threshhold terminator return None # end-of-stream flag while abs(last[0]-rand) < 0.4: # look for usable candidate print '*', # display the rejection rand = random.random() # new candidate last[0] = rand # update the "static" var return rand TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From christopher.saunter at durham.ac.uk Fri Jan 25 07:04:45 2008 From: christopher.saunter at durham.ac.uk (c d saunter) Date: Fri, 25 Jan 2008 12:04:45 +0000 (UTC) Subject: Windows AVIFile problems Message-ID: Hi All, I'm trying to access individual video frames of an AVI file from within Python 2.4 or 2.5 under Windows XP. I have found this example code here for that does exactly what I want, using the windows avifile.dll but I am unable to find the AVIFile.h header... http://mail.python.org/pipermail/image-sig/2002-February/001748.html An alternative is to call into avifile.dll dynamically using ctypes, however under both Python 2.4 and 2.5 the following error happens: >>> from ctypes import * >>> windll.AVIFile Traceback (most recent call last): File "", line 1, in windll.AVIFile File "C:\Python25\lib\ctypes\__init__.py", line 415, in __getattr__ dll = self._dlltype(name) File "C:\Python25\lib\ctypes\__init__.py", line 340, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 193] %1 is not a valid Win32 application or WinDLL('c:/windows/system/AVIFILE.DLL') # same for .../system32/AVI... Traceback (most recent call last): File "", line 1, in windll.AVIFile File "C:\Python25\lib\ctypes\__init__.py", line 415, in __getattr__ dll = self._dlltype(name) File "C:\Python25\lib\ctypes\__init__.py", line 340, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 193] %1 is not a valid Win32 application This suggests that the dll is corrupt? However if I download and run the exe's from this example of a VB program calling the DLL, they work: http://www.shrinkwrapvb.com/avihelp/avihelp.htm I'm open to suggestions about the specific problems above or other ways of getting at the frames. I've tried pymedia but it also has issues. Regards Chris Saunter From ask at me Thu Jan 17 14:30:19 2008 From: ask at me (alf) Date: Thu, 17 Jan 2008 13:30:19 -0600 Subject: how django discovers changed sources In-Reply-To: References: <18udndZmKMfMNhLanZ2dnUVZ_rzinZ2d@comcast.com> Message-ID: <18udndFmKMfgMRLanZ2dnUVZ_rzinZ2d@comcast.com> Jeff wrote: > That is the behavior of the development server. When you are writing > your application, you don't want to have to manually restart the > server every time you change a file. On apache it obviously doesn't > do that. thx for clarification, but still I am curious how it is done under the hood. it really impressed me ... From electronixtar at gmail.com Thu Jan 17 15:26:20 2008 From: electronixtar at gmail.com (est) Date: Thu, 17 Jan 2008 12:26:20 -0800 (PST) Subject: dbus-python for windows References: <194e7fee-728a-48eb-9f51-1e272ecca838@j20g2000hsi.googlegroups.com> Message-ID: <553d4985-fd94-4556-9cfa-e09ecc7227a7@s19g2000prg.googlegroups.com> There exists a pre-compiled binary for dbus it was primary wirtten for deluge win32 port http://www.slurdge.org/deluge-on-windows There exists a pre-compiled binary for dbus it was primary wirtten for deluge win32 port http://www.slurdge.org/deluge-on-windows On Jan 15, 9:14?pm, Suraj Barkale wrote: > est gmail.com> writes: > > > I am trying to port Scribes to Windows, > > Hi there like minded fellow > > > sourceforge.net/projects/windbus/? but it not for Python, so how could > > I install dbus module for Windows Python 2.5 ? > > I have also started to dabble in windbus-python for the sake of Scribes. I have > following observations: > 1. I don't have Visual Studio 2003 (required for compiling Python 2.x modules) > so alternative is to use MinGW. Follow instructions athttp://js.cx/~justin/mingwYou can skip the GtkGLExt part. > 2. Checkout windbus from sourceforge, apply the patch (patch.exe doesn't work on > Vista. Rename it to p4tch.exe) > 3. Follow the windows build instructions for windbus. It gets compiled correctly > :). > 4. dbus-python has dependency on dbus AND dbus-glib. But all my attempts of > getting dbus-glib to build have failed so for. > 5. dbus-python looks at wrong place for python headers, this is very easy to > connect and if we can get dbus-glib to build then we are there :) > > I will keep banging my head & let you know once I have cracked it (or the > dbus-python :) > > P.S. Please CC me in your reply as I am not on the list. > > Regards, > Suraj From pavlovevidence at gmail.com Fri Jan 11 00:34:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 11 Jan 2008 00:34:07 -0500 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: On Thu, 10 Jan 2008 22:36:56 -0500, Marty wrote: > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) > > This caused me to wonder why Python does not have a "foreach" statement > (and also why has it not come up in this thread)? I realize the topic > has probably been beaten to death in earlier thread(s), but does anyone > have the short answer? Most languages that have "foreach" use it the same way Python uses "for". The reason they use "foreach" instead of plain "for" is often because they have a separate for statement that mimic C's for. Perhaps you're wondering why there is no syntax for looping a given number of times. (Languages that have this feature, e.g., Ada, often to use "repeat" as the keyword.) 1. Looping a fixed number of times is quite uncommon. 2. A syntax for it buys you almost nothing. Carl Banks From marek.rocki at wp.pl Sun Jan 20 15:06:57 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sun, 20 Jan 2008 12:06:57 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Message-ID: Nice challenge! I came up with something like this: def find_repr(target, numbers): org_reprs = dict((number, str(number)) for number in numbers) curr_reprs = org_reprs while target not in curr_reprs: old_reprs, curr_reprs = curr_reprs, {} for x in old_reprs: for y in org_reprs: repr_x, repr_y = old_reprs[x], old_reprs[y] curr_reprs[x + y] = '(%s)+(%s)' % (repr_x, repr_y) curr_reprs[x - y] = '(%s)-(%s)' % (repr_x, repr_y) curr_reprs[x * y] = '(%s)*(%s)' % (repr_x, repr_y) if y <> 0 and x % y == 0: curr_reprs[x // y] = '(%s)/(%s)' % (repr_x, repr_y) curr_reprs.update(old_reprs) return curr_reprs[target] print '21 =', find_repr(21, [2, 3, 5]) print '923 =', find_repr(923, [7, 8, 50, 8, 1, 3]) Unfortunately, this yields solutions that are a bit lispish (as in 'lots of superfluous parentheses' in the result). Nothing a simple regex or two wouldn't fix ;-) And the solution found would be minimal not with respect to the string length, but rather to the number of operations to be performed. Apart from that, I find it quite elegant. I'd like to know if it has any flaws. Regards, Marek From mwm-keyword-python.b4bdba at mired.org Fri Jan 11 02:19:38 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 02:19:38 -0500 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <20080111021938.69734ca4@bhuda.mired.org> On Fri, 11 Jan 2008 01:48:43 -0500 Marty wrote: > Mike Meyer wrote: > >> This caused me to wonder why Python does not have a "foreach" statement (and > >> also why has it not come up in this thread)? I realize the topic has probably > >> been beaten to death in earlier thread(s), but does anyone have the short answer? > > > > But I'm curious - what's the difference between the "foreach" you have > > in mind and the standard python "for"? > For example, I thought the python "equivalent" of perl's foreach might be: No, python's equivalent of Perl's foreach is "for". I.e. foreach $var (@list) does the same thing as Python's for var in list (except Perl gets the scoping right). Maybe you're thinking of Perls "default variable" feature (I don't know what else to call it), which implicitly uses $_ as a variable in any number of places if you fail to provide a variable? So that you can say: foreach (@list) and apparently not have to use a variable, except it implicitly uses $_. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From nagle at animats.com Thu Jan 17 14:28:26 2008 From: nagle at animats.com (John Nagle) Date: Thu, 17 Jan 2008 11:28:26 -0800 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. Message-ID: <478FAC5A.50206@animats.com> It's possible to use "pickle" for interprocess communication over pipes, but it's not straightforward. First, "pickle" output is self-delimiting. Each dump ends with ".", and, importantly, "load" doesn't read any characters after the "." So "pickle" can be used repeatedly on the same pipe, and one can do repeated message-passing this way. This is a useful, but undocumented, feature. It almost works. Pickle's "dump" function doesn't flush output after dumping, so there's still some data left to be written. The sender has to flush the underlying output stream after each call to "dump", or the receiver will stall. The "dump" function probably ought to flush its output file. It's also necessary to call Pickle's "clear_memo" before each "dump" call, since objects might change between successive "dump" calls. "Unpickle" doesn't have a "clear_memo" function. It should, because if you keep reusing the "Unpickle" object, the memo dictionary fills up with old objects which can't be garbage collected. This creates a memory leak in long-running programs. Then, on Windows, there's a CR LF problem. This can be fixed by launching the subprocess with proc = subprocess.Popen(launchargs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) Failure to do this produces the useful error message "Insecure string pickle". Binary "pickle" protocol modes won't work at all in this situation; "universal newline" translation is compatible, not transparent. On Unix/Linux, this just works, but the code isn't portable. Incidentally, in the subprocess, it's useful to do sys.stdout = sys.stderr after setting up the Pickle objects. This prevents any stray print statements from interfering with the structured Pickle output. Then there's end of file detection. When "load" reaches an end of file, it properly raises EOFError. So it's OK to do "load" after "load" until EOFerror is raised. "pickle" and "cPickle" seem to be interchangeable in this application, so that works. It's a useful way to talk to a subprocess, but you need to know all the issues above to make it work. John Nagle From paddy3118 at googlemail.com Sun Jan 20 23:21:50 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 20 Jan 2008 20:21:50 -0800 (PST) Subject: dynamic type variable References: Message-ID: <7814f8ab-4a3d-4a0d-901e-3ff4a7d8e050@c4g2000hsg.googlegroups.com> On Jan 21, 2:37 am, "J. Peng" wrote: > Python's variable is dynamic type,is it? > But why this can't work? > > >>> 3 + 'a' > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > So I see the number 3 can't be converted to string type automacially. Hi, You are probably confusing Dynamic typing with Weak typing. Python is both dynamically and strongly typed. Perl is both dynamically and weakly typed. It is Perls weak typing that allows automatic conversion between dissimilar types. See: http://en.wikipedia.org/wiki/Type_system - Paddy. From gherzig at fmed.uba.ar Mon Jan 28 12:59:42 2008 From: gherzig at fmed.uba.ar (gherzig at fmed.uba.ar) Date: Mon, 28 Jan 2008 15:59:42 -0200 (ARST) Subject: sharing objects between classes In-Reply-To: <479e0c3b$0$1158$426a74cc@news.free.fr> References: <606aolF1pa0tfU2@mid.uni-berlin.de> <479e0c3b$0$1158$426a74cc@news.free.fr> Message-ID: <28425.190.55.98.232.1201543182.squirrel@www.webmail.fmed.uba.ar> > Diez B. Roggisch a ?crit : >> Gerardo Herzig wrote: >> >>> Hi all. Im wondering the way to share a database connection between >>> some >>> classes: >>> >>> So far, i came up with a simple class schema, where each class means >>> each different relation, i mean i have the follow classes >>> >>> class Database(object): >>> ## make the connection >>> self.conn = make_conn(....) >>> >>> class Table(object): >>> def get_fields: >>> .... >>> > (snip) >> >> Take a look at the sources of e.g. SQLObject and how they do it (in SO, >> the >> concept is called "HUB") >> > And while you're at it, take a look at SQLAlchemy too, and ask yourself > if you really need to roll your own solution !-) Yes, i dont need to reinvent the wheel, i know, it just seems like a pattern i will have to deal with, not just in this case. SQLObject seems like a big peace of code to read. At least to me (not that good programmer). I will take a look at SQLAlchemy, and see a little more. Thanks! Gerardo From http Sun Jan 20 12:13:20 2008 From: http (Paul Rubin) Date: 20 Jan 2008 09:13:20 -0800 Subject: HTTP POST uploading large files References: Message-ID: <7xwsq4zahb.fsf@ruckus.brouhaha.com> Wolfgang Draxinger writes: > Am I just blind for some urllib2/httplib feature, or some other > library? Or do I really have to fiddle around with sockets > myself (I hope not...). I did something like that by just opening a socket and writing the stuff with socket.sendall. It's only about 5 lines of code and it's pretty straightforward. From ggpolo at gmail.com Wed Jan 30 14:04:38 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 30 Jan 2008 17:04:38 -0200 Subject: Q: paramiko/SSH/ how to get a remote host_key In-Reply-To: <15189222.post@talk.nabble.com> References: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> <9077ed27-e9b1-47ca-b30e-918e3b50d517@e4g2000hsg.googlegroups.com> <15189222.post@talk.nabble.com> Message-ID: 2008/1/30, Charles_hans : > > I tried to get what host_key has been aquired after AutoPolicy is set. I > added the following code just before client.close() in rosty's final code: > > try: > host_keys = > paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) > except IOError: > try: > host_keys = > paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) > except IOError: > print '*** Unable to open host keys file' > > I still got 'Unable to open host keys file'. Can you tell me how to get the > remote host_key under this situation? Thanks! > > Charles > 1/30/2008 Hey Charles, If you take a look on your code, you will see that you are catching IOError. So the problem you are noticing is related to I/O failing such as non-existent file. Be sure to check if '~/.ssh/known_hosts' exists, if the first try fails, check if "~/ssh/known_hosts" exists then (since you are trying to access that file). Cheers, > > by Guilherme Polo Jan 21, 2008; 09:08am : > > 2008/1/21, DHR : > > Very nice =) > > Just an advice, you dont need to import base64. Method decode of > strings allows you to specify encoding as 'base64' to perform needed > operations. > > > by rosty Jan 21, 2008; 08:43am : > > Thank you! Now it works and the code looks like this: > > import paramiko > import base64 > from paramiko import AutoAddPolicy, SSHClient > > client = paramiko.SSHClient() > client.set_missing_host_key_policy(AutoAddPolicy()) > client.connect('hostIP', username='uname', password='pass') > stdin, stdout, stderr = client.exec_command('ls') > for line in stdout: > print '... ' + line.strip('\n') > > client.close() > -- > View this message in context: http://www.nabble.com/Q%3A-paramiko-SSH--how-to-get-a-remote-host_key-tp14996119p15189222.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From arnodel at googlemail.com Sat Jan 19 20:01:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 19 Jan 2008 17:01:03 -0800 (PST) Subject: Default attribute values pattern References: Message-ID: <12f1bfa5-09ec-4a4e-a21c-53250369f1a8@v29g2000hsf.googlegroups.com> On Jan 19, 11:02?pm, "David Tweet" wrote: > def Grab(argdict, key, default): > ? """Like argdict.get(key, default), but also deletes key from argdict.""" > ? if key in argdict: > ? ? retval = argdict["key"] > ? ? del(argdict[key]) > ? else: > ? ? retval = default > ? return retval > Dictionaries already have a method for this. It's called pop. It's a good idea to have a look at methods of builtin types before reimplementing the wheel! Grab(argdict, key, default) is argdict.pop(key, default) -- Arnaud From arkanes at gmail.com Fri Jan 11 10:40:49 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 11 Jan 2008 09:40:49 -0600 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> <478732db$0$19250$426a74cc@news.free.fr> <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> <4787762b$0$18777$426a74cc@news.free.fr> Message-ID: <4866bea60801110740o52aacdbdp89f3bf1222e135d7@mail.gmail.com> On Jan 11, 2008 9:10 AM, George Sakkis wrote: > On Jan 11, 8:59 am, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > George Sakkis a ?crit : > > > > > > > > > On Jan 11, 4:12 am, Bruno Desthuilliers > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > > > >> George Sakkis a ?crit : > > > > >>> On Jan 10, 3:37 am, Bruno Desthuilliers wrote: > > >>>> I fail to see how the existence of JIT compilers in some Java VM changes > > >>>> anything to the fact that both Java (by language specification) and > > >>>> CPython use the byte-code/VM scheme. > > >>> Because these "some Java VMs" with JIT compilers are the de facto > > >>> standard used by millions; > > >> Repeating an argument doesn't make it more true nor more relevant. Once > > >> again, this doesn't change anything to the fact exposed above. > > > > >>> the spec is pretty much irrelevant > > >> I mentionned this because this kind of choice is usually not part of the > > >> language spec but of a specific implementation. Java is AFAIK the only > > >> language where this implementation stuff is part of the spec. > > > > >>> (unless > > >>> you're a compiler writer or language theorist). > > >> I thought it was quite clear and obvious that I was talking about points > > >> relating to these fields. > > > > > No it wasn't, > > > > """ > > > or is Python just too slow > > > as an interpreted language > > > > Being "interpreted" is a quality of an implementation, not of a language. > > """ > > If that isn't clear enough what I'm talking about, then sorry but I > > can't help. > > Pedantic once again. For languages with a single (or practically > single) implementation such as Python, the average user couldn't care > less about the distinction. Your point might have more merit if > PyPy or IronPython or Jython enter the same league with CPython in > terms of usage. > > > > and besides the OP is most likely interested in these as > > > a simple user so the distinction between a spec and a de facto > > > standard implementation (such as JDK for Java and CPython for Python) > > > are almost pedantic if not misleading. > > > > I can live with being called "pedantic" - even I'm not sure whether > > correcting a wrong statement about CPython's execution model is pedantic > > or not. But I *still* fail to see how it could be "misleading", and > > *you* still fail to explain in which way it could be misleading. > > > > If your point is that saying that CPython uses a byte-code/VM scheme > > "just like Java" necessarily implies JIT compilation just because some > > JVM support this feature, then it would be time you pay more attention > > to what is effectively written. > > What three different people in this thread have been trying to tell > you but you seem to miss is that claiming CPython's VM "is just like > Java" is comparable to saying "a Yugo's car engine is just like a > BMW's" (or "humans are just like chimpanzees"), which for some value > of "just like" is technically correct but it's not what most people > would call an accurate statement. > The statement was in response to a claim that Python was slow because it is interpreted. This is a little like correcting someone who says that a Yugo is slow because it has a steam engine by telling that no, it's internal combustion, just like the BMW has. It's possible for this a claim like this to lead to a clarifying and informative discussion about JIT technology and how it improves Javas performance, and the use of corresponding techniques in Python. What we got instead was someone who felt some sort of juvenile urge to jump all over a what he thought of as a claim that Python is as fast as Java (which, of course, it sometimes is - the issue is more complicated than a sound bite). > > > We're not Lisp (yet ;-)), with > > > five major implementations and a dozen of minor ones. > > > > And ? In which way does it make the distinction between a language and a > > language implementation less true ? > > In the way that most plain users care (or not) about. Not that I think any of you care about anything except your e-penis at this point, but there is no reason to proscribe discussion to only what "plain users" want, even if the OP was such a person. From rndblnch at gmail.com Fri Jan 25 14:52:44 2008 From: rndblnch at gmail.com (rndblnch) Date: Fri, 25 Jan 2008 11:52:44 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> Message-ID: On Jan 25, 8:43 pm, petr.jakes.... at gmail.com wrote: > This means NO X-windows, NO GTK/Gnome, NO > computer mouse, on my machine (AMD Geode 500MHz CPU, VGA output). > > I would like to write some really light weighted GU interface. My > concept is to have just few user screens (about 10) controlled via 4 > or 5 HW buttons connected to the GPIO pins they are available on the > motherboard (the HW design and the SW concept of reading this buttons > is already solved). what you are looking for is curse :) http://docs.python.org/lib/module-curses.html http://www.ibm.com/developerworks/linux/library/l-python6.html renaud From bearophileHUGS at lycos.com Fri Jan 18 19:37:49 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 18 Jan 2008 16:37:49 -0800 (PST) Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> <54efb87e-5a54-42a4-adcc-3d05e03a4859@s8g2000prg.googlegroups.com> Message-ID: <2f5524f1-2a9b-4d04-8b37-15d20940da72@v4g2000hsf.googlegroups.com> Matt: > from collections import defaultdict > > def get_hist(file_name): > hist = defaultdict(int) > f = open(filename,"r") > for line in f: > vals = line.split() > val = int(vals[0]) > try: # don't look to see if you will cause an error, > # just cause it and then deal with it > cnt = int(vals[1]) > except IndexError: > cnt = 1 > hist[val] += cnt > return hist But usually in tight loops exceptions slow down the Python code, so this is quite faster (2.5 times faster with Psyco, about 2 times without, with about 30% of lines with a space in it): import psyco from collections import defaultdict def get_hist(file_name): hist = defaultdict(int) for line in open(file_name): if " " in line: pair = line.split() hist[int(pair[0])] += int(pair[1]) else: hist[int(line)] += 1 return hist psyco.bind(get_hist) It doesn't work if lines may contain spurious spaces... Bye, bearophile From python.list at tim.thechases.com Wed Jan 16 17:51:39 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 16 Jan 2008 16:51:39 -0600 Subject: Creating unique combinations from lists In-Reply-To: <001640bd-7759-423b-ad74-275b27e5d5d6@v4g2000hsf.googlegroups.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> <13osvl1j4pvka15@corp.supernews.com> <001640bd-7759-423b-ad74-275b27e5d5d6@v4g2000hsf.googlegroups.com> Message-ID: <478E8A7B.7020505@tim.thechases.com> >> for a in range(5): > ... >> for z in range(5): > > means the inner loop runs 5**26 times so perhaps it's not only > unpythonic but also uncomputable... only if you're impatient ;) yes, it was a contrived pessimal example. It could be range(2) to generate boolean-number sequences. I've done 2**26 loops in code before (well, it was on the way to 2**32, just to see how long it took to roll over and hit an error condition). The main emphasis was to show that there was a pattern unfolding that should have been translated into more pythonic code than just hard-coding nested loops. -tkc From ricaraoz at gmail.com Thu Jan 31 06:38:51 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 31 Jan 2008 08:38:51 -0300 Subject: REALLY simple xml reader In-Reply-To: References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> Message-ID: <47A1B34B.4090006@bigfoot.com> Ivan Illarionov wrote: >>>> from xml.etree import ElementTree as et >>>> from decimal import Decimal >>>> >>>> root = et.parse('file/with/your.xml') >>>> debits = dict((debit.attrib['category'], Decimal(debit.find('amount').text)) for debit in root.findall('debit')) >>>> >>>> for cat, amount in debits.items(): > ... print '%s: %s' % (cat, amount) > ... > food: 24.30 > car: 909.56 > medical: 188.20 > savings: 25 > withdrawal: 40 > supplies: 10.58 > clothes: 31.19 > Thanks Ivan, it seems a elegant API, and easy to use. I tried to play a little with it but unfortunately could not get it off the ground. I kept getting >>> root = et.fromstring(doc) Traceback (most recent call last): File "", line 1, in File "E:\Python25\lib\xml\etree\ElementTree.py", line 963, in XML parser.feed(text) File "E:\Python25\lib\xml\etree\ElementTree.py", line 1245, in feed self._parser.Parse(data, 0) ExpatError: XML or text declaration not at start of entity: line 2, column 0 But it's probably my lack of knowledge on the subject. Well, I guess there is no free ride and I'll take a look at ElementTree as soon as I have some spare time, looks promising. One last question. Am I right to believe "debit" would be an "et" object of the same class as "root"? THX From piet at cs.uu.nl Wed Jan 30 03:00:13 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 30 Jan 2008 09:00:13 +0100 Subject: starting programs from python script on windows References: Message-ID: >>>>> Benedict Verheyen (BV) wrote: >BV> Hi, >BV> i want to automate starting programs on my windows machine and i want >BV> to do it with windows. >BV> This is a sample script: >BV> from subprocess import Popen, PIPE >BV> import time >BV> print " Starting app 1" >BV> time.sleep(1) >BV> try: >BV> p1 = Popen(["C:\Program Files\Microsoft Office\OFFICE11\OUTLOOK.EXE"], Use raw strings or escape the \'s. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From mwm-keyword-python.b4bdba at mired.org Thu Jan 10 22:53:52 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 22:53:52 -0500 Subject: Newbie Q: modifying SQL statements In-Reply-To: <20080111013206.GA18259@neptune.faber.nom> References: <20080111013206.GA18259@neptune.faber.nom> Message-ID: <20080110225352.2c112555@bhuda.mired.org> On Thu, 10 Jan 2008 20:32:06 -0500 "Faber J. Fedor" wrote: > Hi all, > > I'm in the process of learning Python by writing a job queue program. > Nothing fancy, mind you, just read from a table, shell out to a program, > write back to the table. > > I'm working off of the tutorial listed here (amongst many places): > http://www.devx.com/dbzone/Article/22093 > > In my Jobs class I have: > > def __iter__(self): > "creates a data set, and returns an iterator (self)" > q = "select * from %s" % (self.name) > self._query(q) > return self # an Iterator is an object > # with a next() method > > def next(self): > "returns the next item in the data set, > or tells Python to stop" > r = self.dbc.fetchone() > if not r: > raise StopIteration > return r > > which works well, but what if I want to modify the __iter__ query? I > want to be able to do something like this (and I know this is not the > right syntax but you'll get my drift): > > > for job in jobs: print job # which the above code does > for job in jobs("status = running"): print job > for job in jobs("jobid = 4"): print job > > What's the pythonic way of doing this? Part of evaluating a for loop is that the expression in the for loop is evaluated, and it's __iter__ method is called. In your first line, the initial evaluation returns the jobs object, whose __iter__ method is then called, giving you the effect you want. For the second and third lines, the first evaluation tries to call the jobs object with the query as an argument. This fails, unless your jobs object is callable. If that returns the jobs object, __iter__ will be called - and thus use the query you want to avoid. So you need to have a __call__ method that leaves a token for __iter__ so it uses the proper query. This will do that, but I'm not sure I'd call it pythonic: _where = "" def __iter__(self): if not self._working: q = "select * from %s" % (self.name + where,) self._query(q) return self def __call__(self, where): self._where = " where %s" % (where,) return self def next(self): ... self._where = self.__class__._where # Put back class default raise StopIteration return r Personally, I think it would be more pythonic to not try and use two different APIs to walk the list of jobs (... One Way To Do it): def __call__(self, where=None): q = "select * from %s" % (self.name,) + ("" if not where else (" where %s" % where)) self._query(q) for r in self.dbc.iterresults() # I assume it has something like this yield r This should cause your first line to fail (possibly, depends on the exact nature of the class); it needs to be "for job in jobs(): print job". http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From google at mrabarnett.plus.com Wed Jan 9 18:45:59 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 9 Jan 2008 15:45:59 -0800 (PST) Subject: Learning Python via a little word frequency program References: <4784bbea$0$17616$426a74cc@news.free.fr> Message-ID: <01ff5c64-994f-4eb3-b634-55e64f3d01cb@k2g2000hse.googlegroups.com> On Jan 9, 12:19 pm, Bruno Desthuilliers wrote: > Andrew Savige a ?crit : > > > > > I'm learning Python by reading David Beazley's "Python Essential Reference" > > book and writing a few toy programs. To get a feel for hashes and sorting, > > I set myself this little problem today (not homework, BTW): > > > Given a string containing a space-separated list of names: > > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > > > produce a frequency table of names, sorted descending by frequency. > > then ascending by name. For the above data, the output should be: > > > kevin : 3 > > jock : 2 > > andrew : 1 > > bill : 1 > > fred : 1 > > freddy : 1 > > > Here's my first attempt: > > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > > freq = {} > > for name in names.split(): > > freq[name] = 1 + freq.get(name, 0) > > deco = zip([-x for x in freq.values()], freq.keys()) > > deco.sort() > > for v, k in deco: > > print "%-10s: %d" % (k, -v) > > > I'm interested to learn how more experienced Python folks would solve > > this little problem. > > For a one-shot Q&D script: > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > freqs = [(- names.count(name), name) for name in set(names.split())] > print "\n".join("%-10s : %s" % (n, -f) for f, n in sorted(freqs)) > [snip] That actually prints: kevin : 3 fred : 2 jock : 2 andrew : 1 bill : 1 freddy : 1 It says that "fred" occurs twice because of "freddy". names = "freddy fred bill jock kevin andrew kevin kevin jock" name_list = names.split() freqs = [(- name_list.count(name), name) for name in set(name_list)] print "\n".join("%-10s : %s" % (n, -f) for f, n in sorted(freqs)) From asmodai at in-nomine.org Sat Jan 12 17:12:22 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 12 Jan 2008 23:12:22 +0100 Subject: where do my python files go in linux? In-Reply-To: <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> <20080112113759.GJ75977@nexus.in-nomine.org> <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> Message-ID: <20080112221222.GL75977@nexus.in-nomine.org> Hi Jorgen, -On [20080112 16:14], Jorgen Bodde (jorgen.maillist at gmail.com) wrote: >I thought about that too. I just wonder why /usr/local/bin is always >empty and every .deb I install from a source (if it's from Ubuntu or >not) installs files in /usr/bin .. So I looked further and noticed >that most python files do reside in /usr/share/{appname} Well, it always seemed that many Linux distributions had to do things different from a file/directory hierarchy point of view and I never fully understood why. It always seemed a bit inspired by NIH-syndrome. But like I said, whatever works for you. >I would agree but it is not a site package I am trying to distribute, >but a wxPython application. I would not think my app belongs in the >python site packages dir. Mmm, I guess Python does not have a wonderful solution for this kind of scenario to be honest. The site-packages solution is one of the cleanest I can think of. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Only I can change my life. No one can do it for me... From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 10 08:05:29 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 10 Jan 2008 14:05:29 +0100 Subject: importing module conflict In-Reply-To: References: Message-ID: <47861812$0$8324$426a74cc@news.free.fr> Matias Surdi a ?crit : > Hi, > > Suppose I've a module named "urllib" and from it I need to import the > urllib module from the python standart library. > > ?how can I do this? > > The problem I found is that when I do: > > > import urrlib > > The imported module is itself, and not the one from the stdlib. > > Any idea? Yes : don't name your module 'urllib' !-) Else, you can play with sys.path before importing the std urllib, etc, etc... From tijotomjoy at gmail.com Thu Jan 10 21:15:56 2008 From: tijotomjoy at gmail.com (tijo) Date: Thu, 10 Jan 2008 18:15:56 -0800 (PST) Subject: Help needed Message-ID: Hi mate i need o do a python program to connect 2 systems using TCP/IP and UDP. Also i need to check the performance of these two protocols (how many bytes received and how much time took). I havent worked in python earlier and have no idea of this. Could someone pls help me. I created a program which can connect between 2 systems using these UDP and TCP/ IP protocols. I dont know how to check the rest like how many bytes send or how much time taken since this is part of my course work could someone please help me thanks in advance. tijo From paul.zorn at gmail.com Tue Jan 29 19:23:28 2008 From: paul.zorn at gmail.com (paul.zorn at gmail.com) Date: Tue, 29 Jan 2008 16:23:28 -0800 (PST) Subject: Telnet Program References: <777d417c-6016-4a44-8d5e-8de6bf604e9a@e6g2000prf.googlegroups.com> <87zluo77qr.fsf@merkury.smsnet.pl> Message-ID: On Jan 29, 12:27 pm, Rob Wolfe wrote: > "paul.z... at gmail.com" writes: > > I am having some issues writing a telnet program, using telnetlib. I > > am not sure if it is the telnet on the connections end or it is my > > program. > > > A little background, when I log in straight from the Linux Command > > prompt. The only thing I get is a blinking cursor. Then I type in my > > command 'FOO' enter then screen on the very next line returns 'OK', > > Then automatically puts the blinking cursor on the next line. Then > > when I want to quit the telnet session I hit CTRL+Z that takes me to > > telnet> then i type quit. > > > My Program currently looks like it connects. Because the last string > > that I get back that is not blank says: "Logged in successfully". > > > So my problem is that when I issue the command through tn.write("FOO > > \n"). Then do a tn.read_until('OK\n', 10). It gets returned nothing. I > > have also added tn.read_until('OK\n', 10).splitlines(). That is also > > returned blank. > > > I have tried various different newlines \n \r \r\n. All the > > documentation for telnet program that I am logging into says, use > > Carriage Return after each command. Nothing seems to get back the > > data. I am not sure if the Python telnet is looking for more of true > > command line like telnet>. > > Have you tried: tn.set_debuglevel(1) ? > > HTH, > Rob Thank You for the response. I did set the debugging level. I get back this. Telnet(192.168.2.75,5000): recv 'Password: ' Telnet(192.168.2.75,5000): send '*****\n' Telnet(192.168.2.75,5000): recv '\r\x00\r\nlogged in successfully\r\n' Telnet(192.168.2.75,5000): send '\n\n' Telnet(192.168.2.75,5000): Sending AT Telnet(192.168.2.75,5000): send 'AT\r\n' Telnet(192.168.2.75,5000): recv '\r\x00' So I on this command I should be getting back a 'OK' or 'ERROR'. But I am not seeing it. I feel like I am missing something. Not sure what would be the or is it the telnet application itself. Thanks, Paul From paddy3118 at googlemail.com Wed Jan 9 11:15:59 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 08:15:59 -0800 (PST) Subject: Collecting Rich Data Structures for students References: Message-ID: <8b4e7954-b666-4515-9ae2-821d979ebd7f@m34g2000hsf.googlegroups.com> On Jan 9, 6:52 am, Paddy wrote: > On Jan 9, 2:19 am, "kirby.ur... at gmail.com" > wrote: > > > > > Greetings Pythoneers -- > > > Some of us over on edu-sig, one of the community actives, > > have been brainstorming around this Rich Data Structures > > idea, by which we mean Python data structures already > > populated with non-trivial data about various topics such > > as: periodic table (proton, neutron counts); Monty Python > > skit titles; some set of cities (lat, long coordinates); types > > of sushi. > > > Obviously some of these require levels of nesting, say > > lists within dictionaries, more depth of required. > > > Our motivation in collecting these repositories is to give > > students of Python more immediate access to meaningful > > data, not just meaningful programs. Sometimes all it takes > > to win converts, to computers in general, is to demonstrate > > their capacity to handle gobs of data adroitly. Too often, > > a textbook will only provide trivial examples, which in the > > print medium is all that makes sense. > > > Some have offered XML repositories, which I can well > > understand, but in this case we're looking specifically for > > legal Python modules (py files), although they don't have > > to be Latin-1 (e.g. the sushi types file might not have a > > lot of romanji). > > > If you have any examples you'd like to email me about, > > kirby.ur... at gmail.com is a good address. > > > Here's my little contribution to the mix:http://www.4dsolutions.net/ocn/python/gis.py > > > Kirby Urner > > 4D Solutions > > Silicon Forest > > Oregon > > I would think there was more data out there formatted as Lisp S- > expressions than Python data-structures. > Wouldn't it be better to concentrate on 'wrapping' XML and CSV data- > sources? > > - Paddy. The more I think on it the more I am against this- data should be stored in programming language agnostic forms but which are easily made available to a large range of programming languages. If the format is easily parsed by AWK then it is usually easy to parse in a range of programming languages. - Paddy. From skip at pobox.com Thu Jan 3 18:10:32 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 3 Jan 2008 17:10:32 -0600 Subject: ctypes - pointer to array of structs? Message-ID: <18301.27496.174107.113205@montanaro.dyndns.org> (Is this the right place to ask ctypes questions? There's a mailing list but the last post to it seems to have been in November 2006.) Using ctypes I reference a structure which contains a pointer to an array of another structure: class SYMBOL(Structure): _fields_ = [("symbol", c_char_p), ("num", c_int), ("units", c_int), ("baseprice", c_int), ("active", c_int)] SYMBOL_PTR = POINTER(SYMBOL) class TABLE(Structure): _fields_ = [("map", SYMBOL_PTR), ("nsymbols", c_uint), ...] Effectively, TABLE.map is an array of TABLE.nsymbols SYMBOLS. How to I reference elements in that array? In C I would just treat TABLE.map like an array and index into it (for i=0; i< TABLE.nsymbols; i++) ...). This is data returned from a C library, not something I'm building in Python to pass into C. Thx, Skip From nyamatongwe+thunder at gmail.com Tue Jan 1 20:12:35 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 02 Jan 2008 01:12:35 GMT Subject: cloud computing (and python)? In-Reply-To: <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> Message-ID: <7yBej.30029$CN4.18224@news-server.bigpond.net.au> Cloud computing is mostly about scalability. You do not need to be concerned so much about low level infrastructure details such as purchasing servers, configuring and maintaining them, hiring space in data centres, linking up data centres, etc. It converts a lot of fixed costs into lower recurring costs so makes it easier for a start up with limited capital to start operating. There are Python libraries for accessing some of the cloud computing services and you can also host Python application code on some services that allow code execution. This includes services that can run arbitrary code on virtual machines such as EC2 and more restricted computational services like Hadoop which can run Jython. Neil From bj_666 at gmx.net Sat Jan 5 06:48:16 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 5 Jan 2008 11:48:16 GMT Subject: Point Object References: <4673edc3-b76c-4c6e-98f0-4f2becee930e@j20g2000hsi.googlegroups.com> Message-ID: <5u9940F1gsfmuU1@mid.uni-berlin.de> On Sat, 05 Jan 2008 03:37:33 -0800, pjmulla at googlemail.com wrote: > I am nes to python and need some help. Can anyone lead me in the > right direction to create and print a Point object, and then use id to > print the object's unique identifier. Translate the hexadecimal form > into decimal and confirm that they match. The right direction would be the tutorial in the docs I guess: http://docs.python.org/tut/tut.html What do you mean by the "hexadecimal form"? `id()` returns ordinary `int`\s and not strings. Ciao, Marc 'BlackJack' Rintsch From Russ.Paielli at gmail.com Mon Jan 28 05:42:31 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jan 2008 02:42:31 -0800 (PST) Subject: optional static typing for Python References: <479da584$0$25625$426a74cc@news.free.fr> Message-ID: <69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com> On Jan 28, 1:51 am, Bruno Desthuilliers wrote: > Russ P. a ?crit :> A while back I came across a tentative proposal from way back in 2000 > > for optional static typing in Python: > > (snip) > > > In any case, optional static typing in Python would help tremendously > > here. The hardest part of automated conversion of Python to a > > statically typed language is the problem of type inference. If the > > types are explicitly declared, that problem obviously goes away. > > (snip) > > > Note also that, while "static" type checking would be ideal, > > "explicit" typing would be a major step in the right direction > > Lord have mercy(tm). What is that supposed to mean? Oh, I almost forgot. I'm supposed to sit here and be polite while clueless dolts make wise cracks. Sorry, but I haven't yet mastered that level of self-control. I would just like to thank you for reminding me about what losers hang out perpetually on sites like this one, thinking they are in some kind of real "community." Being reminded of that will help prevent me from becoming such a loser myself. No, I didn't say that all the "regulars" here are losers, but you most certainly are. Do you have a job? How about a life? Have you ever been "with" a woman? How in the world is it that every time I come to this site, I see your sorry ass hanging around yet again? I can't even imagine how "pointless" your life must be if you have that much time to spend "hanging around" on comp.lang.python -- and being an a--hole to boot. Yeah, Lord have mercy -- on losers like you. And thanks for reminding me to quit wasting so much time here. I've been doing way too much of that lately. From martin at marcher.name Sun Jan 6 16:42:47 2008 From: martin at marcher.name (Martin Marcher) Date: Sun, 06 Jan 2008 22:42:47 +0100 Subject: Delete lines containing a specific word References: <183075.69960.qm@web57604.mail.re1.yahoo.com> Message-ID: On Sunday 06 January 2008 21:25 Francesco Pietra wrote: >> yes lines starting with a "#" are comments in python but that shouldn't >> be of concern for your input data. I don't quite get what you want >> here... > > Leaving the lines commented out would permit to resume them or at least > remeber what was suppressed. During trial and error set up of a > calculation one never knows exactly the outcome Ah I get it. To clarify: The character python uses as a comment has nothing to do with the character your data file uses as a comment. So you could of course use the "#" sign (which makes sense) You could also use "//" (C-Style) or whatever you like class CommentHelper(object): """Provides the necessary methods to comment or uncomment a line of text. """ # Yes I know this docstring is badly formatted but # I thought it's nicer to keep the indentation. def __init__(self, commentStr=None): if commentStr: self.commentStr = commentStr else: self.commentStr = "MY_SUPER_COMMENT_STRING" def commentLine(line): """Comments a line with the initialized comment string. """ return self.commentStr + " " + line def uncommentLine(line): """Uncomments a line iff it is preceded by the comment string. """ if line.startsWith(self.commentStr): return line[len(self.commentStr)].lstrip() raise Exception("Can't uncomment Line with no comment") You want to read up about: * (new style) classes * parameters with default values * docstrings * Exceptions That code is untested and may contain errors. I'll let the debugging be your task :) hope it points you to the right topics to read up about: http://docs.python.org/ http://docs.python.org/tut/tut.html http://www.diveintopython.org/ martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From ryszard.szopa at gmail.com Sat Jan 19 07:01:48 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Sat, 19 Jan 2008 04:01:48 -0800 (PST) Subject: writing Python in Emacs Message-ID: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> Hi All, I am a devoted Emacs user and I write a lot in Python. However, I never managed to get my Emacs configuration right for this purpose. There were some discussions on this, but the threads that show if I search the group are either old or not so relevant. I need the following features: 0) Of course, syntax coloring and so on... But this works good enough ootb in the two most popular python-modes. 1) Tab completion, ideally Slime like. That is, when there's not enough letters to unambiguously complete a symbol, I want it to show a buffer (w/o taking the focus) w/ the possible completions. In an ideal world, it would be able to complete fo.ba to foo.bar. I imagine this would require quite tight Emacs-Python integration. 2) Sending the toplevel definition (class or function) to the Python buffer. 3) Hints on function/method arguments. IDLE has this done nearly right, but the hints are a bit too intrusive for me. I would like to see them in the minibuffer. 4) (optional) I would like to see the definition of a function function or class by hitting M-. on its name. (I understand that this may be impossible for methods, as Emacs would have to automagically infer the type of the object). I have tried a couple of times both python-modes (the one shipped w/ Python and the one shipped w/ Emacs), pymacs and stuff like that... And, as I said, never got it right. But, maybe I just cannot find the way to configure it, and some configuration hints will be enough... As for other editors, I have tried Eclipse and Komodo... But I cannot get used to them. As for non-emacs stuff, the most comfortable for me has been IDLE. Cheers and thanks in advance, -- Richard From haraldarminmassa at gmail.com Tue Jan 8 10:33:54 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Tue, 8 Jan 2008 07:33:54 -0800 (PST) Subject: Intranet Project - Rad Or Waterfall References: <53490824-d95a-43ab-a405-e1249d4b396f@s12g2000prg.googlegroups.com> Message-ID: <82b745a7-875e-4368-b1a0-eee412892620@e10g2000prf.googlegroups.com> > Option 1 - Waterfall I recommend to google "waterfall". First hit after those beatifull pictures will be: http://en.wikipedia.org/wiki/Waterfall_model Within the first paragraph there is: """Ironically, Royce was actually presenting this model as an example of a flawed, non-working model.(Royce 1970)""" So I cannot fight the feeling of seeing the realisation of a xkcd- strip when reading about waterfall models... Harald From jpcc at nowhere.org Tue Jan 22 09:11:54 2008 From: jpcc at nowhere.org (John Carlyle-Clarke) Date: Tue, 22 Jan 2008 14:11:54 +0000 Subject: Problem with processing XML Message-ID: <13pbudgks88rcf3@corp.supernews.com> Hi. I'm new to Python and trying to use it to solve a specific problem. I have an XML file in which I need to locate a specific text node and replace the contents with some other text. The text in question is actually about 70k of base64 encoded data. I wrote some code that works on my Linux box using xml.dom.minidom, but it will not run on the windows box that I really need it on. Python 2.5.1 on both. On the windows machine, it's a clean install of the Python .msi from python.org. The linux box is Ubuntu 7.10, which has some Python XML packages installed which can't easily be removed (namely python-libxml2 and python-xml). I have boiled the code down to its simplest form which shows the problem:- import xml.dom.minidom import sys input_file = sys.argv[1]; output_file = sys.argv[2]; doc = xml.dom.minidom.parse(input_file) file = open(output_file, "w") doc.writexml(file) The error is:- $ python test2.py input2.xml output.xml Traceback (most recent call last): File "test2.py", line 9, in doc.writexml(file) File "c:\Python25\lib\xml\dom\minidom.py", line 1744, in writexml node.writexml(writer, indent, addindent, newl) File "c:\Python25\lib\xml\dom\minidom.py", line 814, in writexml node.writexml(writer,indent+addindent,addindent,newl) File "c:\Python25\lib\xml\dom\minidom.py", line 809, in writexml _write_data(writer, attrs[a_name].value) File "c:\Python25\lib\xml\dom\minidom.py", line 299, in _write_data data = data.replace("&", "&").replace("<", "<") AttributeError: 'NoneType' object has no attribute 'replace' As I said, this code runs fine on the Ubuntu box. If I could work out why the code runs on this box, that would help because then I call set up the windows box the same way. The input file contains an block which is what actually causes the problem. If you remove that node and subnodes, it works fine. For a while at least, you can view the input file at http://rafb.net/p/5R1JlW12.html Someone suggested that I should try xml.etree.ElementTree, however writing the same type of simple code to import and then write the file mangles the xsd:schema stuff because ElementTree does not understand namespaces. By the way, is pyxml a live project or not? Should it still be used? It's odd that if you go to http://www.python.org/ and click the link "Using python for..." XML, it leads you to http://pyxml.sourceforge.net/topics/ If you then follow the download links to http://sourceforge.net/project/showfiles.php?group_id=6473 you see that the latest file is 2004, and there are no versions for newer pythons. It also says "PyXML is no longer maintained". Shouldn't the link be removed from python.org? Thanks in advance! From robin at NOSPAMreportlab.com Sun Jan 20 08:58:12 2008 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sun, 20 Jan 2008 13:58:12 +0000 Subject: bitmap problem Message-ID: <47935374.3010203@jessikat.plus.net> I'm having trouble with defining a completely transparent bitmap for use as a stipple in a canvas import Tkinter Tkinter._default_root.tk.call('image','create', 'bitmap', 'gray0', '-background', '', '-data', '#define gray0_width 1\n#define gray0_height 1\nstatic char gray0_bits[] = {\n0x0\n};') print 'image names', self.tk.call('image','names') print 'image type', self.tk.call('image','type','gray0') self.canv.create_rectangle("10i", "10i", "13.5i", "13.5i", fill="blue",activestipple='gray0') the prints seem to indicate that the bitmap is defined, but the canvas create_rectangle fails image names gray0 image type bitmap Traceback (most recent call last): File "C:\Tmp\test.py", line 67, in main() File "C:\Tmp\test.py", line 62, in main top = PDFMU() File "C:\Tmp\test.py", line 59, in __init__ self.createWidgets() File "C:\Tmp\test.py", line 44, in createWidgets self.canv.create_rectangle("10i", "10i", "13.5i", "13.5i", fill="blue",activestipple='gray0') File "C:\Python\lib\lib-tk\Tkinter.py", line 2166, in create_rectangle return self._create('rectangle', args, kw) File "C:\Python\lib\lib-tk\Tkinter.py", line 2145, in _create *(args + self._options(cnf, kw)))) _tkinter.TclError: bitmap "gray0" not defined if I change gray0 to one of the predefined names eg gray12 then the create_rectangle succeeds. The tk manual seems to suggest I should be able to do this, but it doesn't seem to work even in tk. Is there a way to define a stipple without a file? -- Robin Becker From sipickles at hotmail.com Sat Jan 19 14:46:59 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Sat, 19 Jan 2008 19:46:59 +0000 Subject: del self? Message-ID: Hi, Just curious... What are the implications of a class member calling: del self is that what the __del__ method calls anyway? Thanks Simon -- Linux user #458601 - http://counter.li.org. From stanc at al.com.au Mon Jan 14 22:02:28 2008 From: stanc at al.com.au (Astan Chee) Date: Tue, 15 Jan 2008 14:02:28 +1100 Subject: Restart crashing modules in windows Message-ID: <478C2244.8040102@al.com.au> Hi, I have a python module that keeps on crashing with various windows errors (not BSOD but the less lethal windows XP popup ones). Now these are intentional and rather sporadic so I cant really solve it by attempting to fix the crash; rather what Im trying to do is make another module outside it that restarts this module every time it crashes. Is this possible? How do I do this? Or does one windows crash in one python module crash python entirely and I have to resort in an external program to restart python everytime it crashes? Thanks again for all the help. Astan From fredrik at pythonware.com Mon Jan 7 11:23:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 17:23:42 +0100 Subject: python syntax In-Reply-To: <633886.19582.qm@web45510.mail.sp1.yahoo.com> References: <633886.19582.qm@web45510.mail.sp1.yahoo.com> Message-ID: mpho raborife wrote: > Please help me get this syntax right: > > os.system("HCopy -T 1 -C" 'os.path.join(conf_dir, "/hcopy.conf")' "-S" > 'os.path.join(list_dir, "hcopy_list.txt")') instead of attempting to get your program working by random trial and error process, maybe you should spend an hour or two working through the examples in a nice tutorial? I'd recommend the first few chapters of Swaroop's "A Byte of Python". Make sure you read at least "Basics" and "Operators and Expressions" before returning to the task at hand: http://www.ibiblio.org/swaroopch/byteofpython/read/ From ggpolo at gmail.com Wed Jan 16 12:11:36 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 16 Jan 2008 15:11:36 -0200 Subject: paramiko In-Reply-To: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> Message-ID: 2008/1/16, Tarun Kapoor : > > > > > I am using paramiko to do an SFTP file transfer? I was able to connect to > the remote server using an SFTP client I have just to make sure that > username and password are working.. This is the code. > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > connection > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > sock.connect((hostname, port)) > > > > t = paramiko.Transport(sock) > > event = threading.Event() > > t.start_client(event) > > > > event.wait(15) > > > > if not t.is_active(): > > print 'SSH negotiation failed.' > > sys.exit(1) > > else: > > print "SSH negotiation sucessful" > > > > event.clear() > > > > t.auth_password(username=username, password=password,event=event) > > > > if not t.is_authenticated(): > > print "not authenticated" > > output: > > SSH negotiation successful > > not authenticated > > > > > > > > Tarun > > > > Waterstone Capital Management > > 2 Carlson Parkway, Suite 260 > > Plymouth, MN 55447 > > > > Direct: 952-697-4123 > > Cell: 612-205-2587 > Disclaimer This e-mail and any attachments is confidential and intended > solely for the use of the individual(s) to whom it is addressed. Any views > or opinions presented are solely those of the author and do not necessarily > represent those of Waterstone Capital Management, L.P and affiliates. If you > are not the intended recipient, be advised that you have received this > e-mail in error and that any use, dissemination, printing, forwarding or > copying of this email is strictly prohibited. Please contact the sender if > you have received this e-mail in error. You should also be aware that > e-mails are susceptible to interference and you should not assume that the > contents of this e-mail originated from the sender above or that they have > been accurately reproduced in their original form. Waterstone Capital > Management, L.P. and affiliates accepts no responsibility for information, > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > please verify the authenticity with the sender. > -- > http://mail.python.org/mailman/listinfo/python-list > You are missing an event.wait() after t.auth_password. Also, why are you passing this magic value "15" to event.wait() ? That parameter is passed to class _Verbose to indicate if debug messages should be displayed or not, so typical values would be 0/1 or False/True. -- -- Guilherme H. Polo Goncalves From sjmachin at lexicon.net Sat Jan 19 07:20:08 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jan 2008 04:20:08 -0800 (PST) Subject: Excess whitespace in my soup References: <48eb8853-91b3-4c43-8014-a0c624e4c6e7@t1g2000pra.googlegroups.com> Message-ID: On Jan 19, 11:00 pm, Fredrik Lundh wrote: > John Machin wrote: > > I'm happy enough with reassembling the second item. The problem is in > > reliably and correctly collapsing the whitespace in each of the above > > > fiveelements. The standard Python idiom of u' '.join(text.split()) > > won't work because the text is Unicode and u'\xa0' is whitespace > > > and would be converted to a space. > > would this (or some variation of it) work? > > >>> re.sub("[ \n\r\t]+", " ", u"foo\n frab\xa0farn") > u'foo frab\xa0farn' > > Yes, partially. Leading and trailing whitespace has to be removed entirely, not replaced by one space. Cheers, John From d.l.goldsmith at gmail.com Mon Jan 7 18:10:57 2008 From: d.l.goldsmith at gmail.com (dgoldsmith_89) Date: Mon, 7 Jan 2008 15:10:57 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python References: Message-ID: On Jan 7, 2:54 pm, "mensana... at aol.com" wrote: > On Jan 7, 4:37 pm, dgoldsmith_89 wrote: > > > Can anyone point me to a downloadable open source English dictionary > > suitable for programmatic use with python: I'm programming a puzzle > > generator, and I need to be able to generate more or less complete > > lists of English words, alphabetized. Thanks! DG > > www.puzzlers.orghas numerous word lists & dictionarys in text > format that can be downloaded. I recommend you insert them into > some form of database. I have most of them in an Access db and > it's 95 MB. That's a worse case as I also have some value-added > stuff, the OSPD alone would be a lot smaller. > > Sorry for my ignorance: I can query an Access DB w/ standard SQL queries (and this is how I would access it w/ Python)? DG From jimgardener at gmail.com Mon Jan 28 00:56:59 2008 From: jimgardener at gmail.com (jimgardener) Date: Sun, 27 Jan 2008 21:56:59 -0800 (PST) Subject: getting values from cache References: <480b367b-e5c4-4018-a968-8c146555dbdd@v29g2000hsf.googlegroups.com> Message-ID: <5fedf077-5f0c-42f6-98fc-eac2c9643496@u10g2000prn.googlegroups.com> > > I'd try to avoid duplicating the calculation code. > > Also, if you split the data in two, you can just read the filename list > alone: thanx G those were good suggestions gordon From steve at REMOVE-THIS-cybersource.com.au Mon Jan 28 10:43:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 28 Jan 2008 15:43:10 -0000 Subject: validate string is valid maths References: Message-ID: <13pru0etgp7joc1@corp.supernews.com> On Mon, 28 Jan 2008 15:10:54 +0000, Matthew_WARREN wrote: > Hi pythoners. > > I am generating strings of length n, randomly from the symbols > > +-/*0123456789 > > What would be the 'sensible' way of transforming the string, for example > changing '3++++++8' into 3+8 That's easy: replace pairs of + into a single +, repeatedly until there's nothing left to replace. And so forth. Here's an untested function. It's probably not even close to optimal, but for playing around it is probably fine. def rationalise_signs(s): while "++" in s or "+-" in s or "-+" in s or "--" in s: s = s.replace("++", "+") s = s.replace("--", "+") s = s.replace("+-", "-") s = s.replace("-+", "-") return s > or '3++--*-9' into '3+-9' such that eval(string) will always return a > number? > > in cases where multiple symbols conflict in meaning (as '3++--*-9' the > earliest valid symbols in the sequence should be preserved You have four symbols, so there are just 4*4=16 sets of two symbols. Probably the easiest way is to just list them and their replacements out in a table: table = {"++": "+", "+-": "-", "+*": "+", "+/": "+", "-+": "-", "--": "+", "-*": "-", "-/": "-", "*+": "*", "**": "*", "*/": "*", "/+": "/", "/*": "/", "//": "/", } Notice that both *- and /- don't get changed. # Untested. def rationalise_signs(s): prev = '' while s != prev: prev = s for key, value in table.items(): s = s.replace(key, value) return s -- Steven From grante at visi.com Thu Jan 31 16:48:53 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 31 Jan 2008 21:48:53 -0000 Subject: Naive idiom questions References: Message-ID: <13q4gi56jajqk51@corp.supernews.com> On 2008-01-31, Terran Melconian wrote: > * Why are there no real mutable strings available? [...] > I want to be able to accumulate a string with +=, not by going > through an intermediate list and then doing ''.join(), So what's stopping you? >>> s = "one" >>> s += " two" >>> s 'one two' >>> > because I think the latter is ugly. Then don't do it. :) > There are also times when I'd like to use the string as a > modifiable buffer. That would be an array of characters or bytes: http://docs.python.org/lib/module-array.html > Is the python idiom that this is actually the Right Thing for > reasons I'm not seeing? I'm not sure what you're asking. AFAIK, the main reason that strings are immutable is so they can be used as dict keys. > Is there a fundamental reason it would be hard to > implement a mutable string in cpython? What problem would a mutable string solve that an array of chars won't? > * What's the best way to initialize a list of lists? Hmm. I guess I never need to do that. > * Is there a way to get headings in docstrings? Docstrings? Real Men Don't Write Docstrings! -- Grant Edwards grante Yow! Now, let's SEND OUT at for QUICHE!! visi.com From cbmeeks at gmail.com Mon Jan 7 15:13:05 2008 From: cbmeeks at gmail.com (cbmeeks) Date: Mon, 7 Jan 2008 12:13:05 -0800 (PST) Subject: Any interest in an SQS alternative??? Message-ID: <6d0b8524-e45c-43d4-9c55-ac3e87eead8f@d4g2000prg.googlegroups.com> I'm a big fan of Amazon's SQS web services. However, I think their SQS is simply too expensive. I was doing some tests in python using SQS and created 1,513 messages in just a few minutes. Then I looked at my bill. It was $0.15 not counting the S3 fee. $0.15 seems like a lot to me for the application I was writing. The application was designed to create MANY MANY small messages. SQS allows you to store up to 256k in one message which is pretty cool. But my app only needed to store URL's. They were all under 64 bytes. Granted, I assume most people take that 256k and intelligently handle many messages in one. For example, a photo sharing site would probably store the ID's to maybe 10-50 pictures in one message and another server would process those pictures as one job. But surely, I'm not the only one out there that would rather create 10,000 messages that are very small vs 1,000 messages that are larger? Or am I? So anyway, I wrote my own message passing class that works pretty well. It is "my" message passing system...as in, message passing for what I need. But maybe others need too? I am seriously thinking of putting it live and let people play around with it...as an experiment. I hope this post doesn't come across as spam or "trolley" because I will probably ask the PHP and Ruby guys too. My goal for "myself" would be to create a system that is at least half of what SQS charges. I know I can't compete with the giant Amazon but who knows... Anyway, if anyone has any interest please let me know. If no one cares, then I guess I will use it all for myself. hahaha Feel free to email me directly too. cbmeeks [AT] gmail.com From steven at REMOVE.THIS.cybersource.com.au Wed Jan 23 04:37:03 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 09:37:03 -0000 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> Message-ID: On Tue, 22 Jan 2008 23:33:00 -0800, George Sakkis wrote: > As I mentioned already, I consider the seeking of the most efficient > solution a legitimate question, regardless of whether a "dumb" solution > is fast enough for an application. Call it a "don't be sloppy" principle > if you wish. Sure, by why do you limit "efficient" and "don't be sloppy" to mean "write the fastest executing code you can, regardless of every other trade-off"? Because there are trade-offs: * execution time * compilation time * memory use at run-time * size of source code on disk * size of compiled code on disk * ease of writing it in the first place * ease of maintenance * correctness * fragility in the face of malformed data * readability and ease of comprehension * elegance (however you judge that!) * making sure the usage of various resources never exceed some set of upper bounds etc. Some of these are relatively unimportant (e.g. the size of the source code), but others are extremely important and far too often ignored (e.g. readability and even correctness). In fact, "fastest" isn't even a meaningful attribute. Does it mean: * the worst-case is fastest * the best-case is fastest * the average-case is fastest * fastest on typical data * all of the above etc. What counts as "typical" data? How do you average all the cases? Asking "what's the fastest" without considering these issues is a good sign that the person asking is being sloppy, something you should be against. > It's the same reason I always use xrange() instead of > range() for a loop, although in practice the difference is rarely > measurable. Well, that's (now) a no-brainer. Once upon a time, range() used to be faster for small enough lists, and whatever difference there is in readability is insignificant except for utter newbies, so there's no real trade-off to make unless you care about the extra "x". But... do you write list.__len__() instead of len(list) to save a few nanoseconds? If you do, you're guilty of pessimization instead of optimization: for built-in lists, len() is actually faster, by a lot. It's only an optimization -- and a significant one -- for custom classes. So, do you write this: if isinstance(alist, list): value = len(alist) # optimize for lists else: value = alist.__len__() # optimize for classes every time you want the length of an arbitrary sequence? If you did, you'd be pessimizing again. That code runs nearly twice as slowly as just calling the built-in len(). Optimizing the parts doesn't mean you have optimized the whole. -- Steven From mr.cerutti at gmail.com Fri Jan 4 10:10:41 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 4 Jan 2008 10:10:41 -0500 Subject: Details about pythons set implementation In-Reply-To: References: Message-ID: <51302a8c0801040710s22e7a094i473a3e46fbfc2cca@mail.gmail.com> On Jan 4, 2008 9:54 AM, Achim Domma wrote: > Hi, > > I'm interested in details about how sets are implemented in python. > They seem to be quite fast and I found some remarks who state, that > the implementation is highly optimized. I need to implemented sets in > C/C++ and need a starting point on how to do it right. Could somebody > give me a starting point? #include -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Fri Jan 4 04:27:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 10:27:57 +0100 Subject: C++ equivalent of comp.lang.python? In-Reply-To: <005550c8-00f6-42b2-b804-2d2baea0b60e@s8g2000prg.googlegroups.com> References: <60597295-1493-493c-969c-a14dd7da98a3@s19g2000prg.googlegroups.com> <005550c8-00f6-42b2-b804-2d2baea0b60e@s8g2000prg.googlegroups.com> Message-ID: Russ P. wrote: >> make sense either. As an example, I was recently trying to get >> information about writing cross-platform code for dynamic linking, but >> I couldn't find anywhere appropriate to ask about it. > > Well, if the good folks at comp.lang.c++ can't even direct you to an > appropriate forum on C++, then I doubt the folks at comp.lang.python > can. I suggest you abandon C++ and try Python, Java, or Ada. note that for his specific example, we would of course direct him to the relevant portions of the CPython source code. From rvtol+news at isolution.nl Mon Jan 28 15:00:55 2008 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Mon, 28 Jan 2008 21:00:55 +0100 Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> <13ps95mg8am3l37@corp.supernews.com> Message-ID: Greg Bacon schreef: > #! /usr/bin/perl > > use warnings; > use strict; > > use constant { > MATCH => 1, > NO_MATCH => 0, > }; > > my @tests = ( > [ "winter tire", => MATCH ], > [ "tire", => MATCH ], > [ "retire", => MATCH ], > [ "tired", => MATCH ], > [ "snowbird tire", => MATCH ], > [ "tired on a snow day", => MATCH ], > [ "snow tire and regular tire", => MATCH ], > [ " tire" => MATCH ], > [ "snow tire" => NO_MATCH ], > [ "snow tire" => NO_MATCH ], > [ "some snowtires" => NO_MATCH ], > ); > [...] I negated the test, to make the regex simpler: my $snow_tire = qr/ snow [[:blank:]]* tire (?!.*tire) /x; my $fail; for (@tests) { my($str,$want) = @$_; my $got = $str !~ /$snow_tire/; my $pass = !!$want == !!$got; print "$str: ", ($pass ? "PASS" : "FAIL"), "\n"; ++$fail unless $pass; } print "\n", (!$fail ? "PASS" : "FAIL"), "\n"; __END__ -- Affijn, Ruud "Gewoon is een tijger." From arnodel at googlemail.com Tue Jan 29 08:45:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 29 Jan 2008 05:45:27 -0800 (PST) Subject: extending Python - passing nested lists References: <3ddeaf07-3f4b-4d68-a176-9205fa4d234b@k39g2000hsf.googlegroups.com> Message-ID: On Jan 29, 1:22?pm, Christian Meesters wrote: > Thanks. Point is that all such approaches would require lots(!) of calls to > the Python API - a way by which I won't gain the desired speed. You didn't mention speed in your original post. What about using array.array? Unless I am mistaken, these are just a thin wrapper around normal C arrays. Anyway you could always convert your list into a c array, do lots and lots of fast calculations, then convert it back again to a list. -- Arnaud From stargaming at gmail.com Thu Jan 31 15:05:44 2008 From: stargaming at gmail.com (Stargaming) Date: 31 Jan 2008 20:05:44 GMT Subject: helper function in a class' namespace References: <47a226bb$0$2982$ba620e4c@news.skynet.be> Message-ID: <47a22a17$0$8306$9b622d9e@news.freenet.de> On Thu, 31 Jan 2008 20:51:23 +0100, Helmut Jarausch wrote: > Hi, > > the following code works fine > > def Helper(M) : > return 'H>'+M String concatenation is generally considered unpythonic, better use string interpolation:: 'H> %s' % (M,) > class A(object): > def __init__(self,Msg) : > print Helper(Msg) > > B=A('ZZ') Watch out your names -- they could confuse other Python programmers introspecting your namespaces! Names bound to objects should generally be lowercase (argument ``msg``, object ``b``, argument ``m``, function ``helper``). For details on what the Python community has agreed on is "good style," see the `Style Guide `_. > but the Helper function is in the module's namespace. Where's the problem? If it is "I don't want Helper to be visible", just use this convention: "Names beginning with an underscore are private. Better keep your fingers off." > I'd like to put it into class A's namespace. Note, the Helper function > doesn't need access to any instance attributes. > > The first variant > > class A(object): > def Helper(M) : > return 'H>'+M > def __init__(self,Msg) : > print Helper(Msg) > > doesn't work since Python is looking for a global function Helper (why?) Because in the scope of the ``__init__`` function, the name ``Helper`` is not bound. It then jumps out to the global scope. > The alternative > > class A(object): > def Helper(M) : > return 'H>'+M > def __init__(self,Msg) : > print A.Helper(Msg) > > doesn't work either since now the first argument to A.Helper must be > 'A'. > > So, isn't it possible to have a helper function in the namespace of a > class without (the overhead of) passing a 'self' or a 'cls' parameter? Of course it is! You can decorate certain functions with the `staticmethod `_ wrapper, which will do exactly what you wanted:: class A(object): @staticmethod def helper(m): return 'H>%s' % (m,) def __init__(self, msg): print A.helper(msg) # or self.helper HTH, From python-url at phaseit.net Mon Jan 28 13:06:36 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 28 Jan 2008 18:06:36 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jan 28) Message-ID: QOTW: "The nice thing with Pyrex is that you can use the Python interpreter, or not use it, more or less depending on your way to declare things and your way to code. So, in a way, you have full control over the compromise between speed and facility. The temptation is always strong to use Python facilities, but I guess that with enough discipline, you can displace and put the equilibrium wherever you want." - Francois Pinard "If you don't ever need or have the chance to debug it, you probably aren't doing programming." - Peter Hansen Early-bird registration for PyCon 2008 continues through 20 February: http://us.pycon.org/2008/registration/ Proposal: auto-assignment to self of some constructor arguments: http://groups.google.com/group/comp.lang.python/browse_thread/thread/32b421bbe6caaeed/ Looking for self-evaluating strings, such that eval(s)==s: http://groups.google.com/group/comp.lang.python/browse_thread/thread/11a74d45d713faef/ Four small problems, with several answers and timings: Find the minimum value from those associated to keys in a dict: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c852ac37c28311cb/ Find the index of the maximum element in a list: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d5ff990a1be73846/ Same but minimum element instead: http://groups.google.com/group/comp.lang.python/browse_thread/thread/284094fd1ac25f69/ Take pairs sequentially from a list: http://groups.google.com/group/comp.lang.python/browse_thread/thread/cf5ab4fab83f7988/ Countdown game solver: combine a few numbers with +-*/() to obtain a given result. Several, very different solutions: http://groups.google.com/group/comp.lang.python/browse_thread/thread/64442b609d99a4ba/ Another game: Sudoku, several approaches too, some incredibly short: http://groups.google.com/group/comp.lang.python/browse_thread/thread/99e43f326aaf93e5/ A guy *really* trying to make sense of Python bytecode disassembled as if it were actual 80x86 code (still LOLAROTF!!!): http://groups.google.com/group/comp.lang.python/browse_thread/thread/df14a32d10432940/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From babycode at gmail.com Sat Jan 12 14:41:15 2008 From: babycode at gmail.com (babycode at gmail.com) Date: Sat, 12 Jan 2008 11:41:15 -0800 (PST) Subject: Great Python books for the beginner References: Message-ID: <1a4d8dae-4722-4a10-a638-ac1b2d85227a@i72g2000hsd.googlegroups.com> On Jan 12, 2:03?am, Landon wrote: > I was wondering if anyone had any opinions on what other titles I > could look into since this one seems from a glance at reviews to be > teaching mainly through game programming (a topic I'm not too > interested in) or if this one is a quality book by itself. http://www.diveintopython.org/ From paul.hankin at gmail.com Thu Jan 24 07:35:34 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 24 Jan 2008 04:35:34 -0800 (PST) Subject: Increment Variable Name References: <9e9714f6-24d8-46fe-908f-205d223574cd@p69g2000hsa.googlegroups.com> Message-ID: On Jan 24, 12:02 pm, janislaw wrote: > On Jan 23, 11:45 pm, David Brochu wrote: > > > This is probably really trivial but I'm stumped.... :-( > > > Does anyone know how to increment a variable name? > > > For example: > > > I know the length of a list and I want to pass each element of a list > > to a unique variable, thus I want to increment variable names. If the > > list length = 4, i want to have the following variables: var1, var2, > > var3, var4. > > > Thanks > > Do you want to do this?: > locals()['var'+str(1)] = "spam" As I recently learnt in this newsgroup, that's not guaranteed to work. >From http://docs.python.org/lib/built-in-funcs.html Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. -- Paul Hankin From over at thepond.com Tue Jan 22 17:27:59 2008 From: over at thepond.com (over at thepond.com) Date: Tue, 22 Jan 2008 22:27:59 GMT Subject: Anyone into Paimei?? Need some help. Message-ID: <1arcp3ltqatcge08e56oaniutd3e2us9lp@4ax.com> Hi. I have been trying to get Paimei running on Windoze but find it very inconsistent. It works on certain apps really well, like Notepad, but fails on other apps, especially those written in languages like Delphi. There isn't a lot out there on Paimei and the author's site is very terse on the app. From hrochonwo at googlemail.com Tue Jan 22 14:04:21 2008 From: hrochonwo at googlemail.com (hrochonwo) Date: Tue, 22 Jan 2008 11:04:21 -0800 (PST) Subject: printing escape character References: Message-ID: <5524d3c2-e206-40bb-9e57-d860ed9c6cea@e10g2000prf.googlegroups.com> On Jan 22, 7:58 pm, "Jerry Hill" wrote: > On Jan 22, 2008 1:38 PM, hrochonwo wrote: > > > Hi, > > > I want to print string without "decoding" escaped characters to > > newline etc. > > like print "a\nb" -> a\nb > > is there a simple way to do it in python or should i somehow use > > string.replace(..) function ? > >>> print 'a\nb'.encode('string_escape') > > a\nb > > -- > Jerry thank you, jerry From petr.jakes.tpc at gmail.com Fri Jan 25 15:36:34 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Fri, 25 Jan 2008 12:36:34 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> Message-ID: <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> > > is already solved). > > what you are looking for is curse :) > http://docs.python.org/lib/module-curses.html > http://www.ibm.com/developerworks/linux/library/l-python6.html > > renaud Renaud, thanks for your reply. I think I was not specific/clear enough in my first posting. I know the curses library ( http://pyncurses.sourceforge.net ). It AFIK provides TUI (short for: Text User Interface or Textual User Interface). My needs are GUI, I mean "a nice VGA pictures" on the VGA LCD 10" display. Petr From doug.farrell at gmail.com Thu Jan 17 12:50:22 2008 From: doug.farrell at gmail.com (writeson) Date: Thu, 17 Jan 2008 09:50:22 -0800 (PST) Subject: handlers.SocketHandler and exceptions References: <02de2e9c-331d-45c0-afaa-578ddad55664@j78g2000hsd.googlegroups.com> Message-ID: Vinay, Thanks for your reply, very interesting. We're currently running Python2.3 (though we are getting ready to move to Python2.5), so I'm guessing the code you're showing comes from Python2.5? I'm wondering if I can edit the handlers.py code in my Python2.3 installation, make the changes you show above, and have things work? Any thoughts on this? Thanks for the help!! Doug From te_rem_ra_ove_an_forspam at consistent.org Thu Jan 31 16:30:09 2008 From: te_rem_ra_ove_an_forspam at consistent.org (Terran Melconian) Date: Thu, 31 Jan 2008 15:30:09 -0600 Subject: Naive idiom questions Message-ID: * Why are there no real mutable strings available? I found MutableString in UserString, but further research indicates that it is horribly inefficient and actually just wraps immutable strings for the implementation. I want to be able to accumulate a string with +=, not by going through an intermediate list and then doing ''.join(), because I think the latter is ugly. There are also times when I'd like to use the string as a modifiable buffer. Is the python idiom that this is actually the Right Thing for reasons I'm not seeing? Is there a fundamental reason it would be hard to implement a mutable string in cpython? * What's the best way to initialize a list of lists? I keep wanting to do this: l=[[None]*5]*5 as do many other Python novices, but of course it quickly becomes apparent why this is a bad idea as soon as one modifies a value. The best I've found is: l=[[None]*5 for i in range(5)] I don't particularly like it, though. It bothers me to have to explain list comprehensions, which are a moderately advanced feature conceptually, just to initialize an array. We could get around this if we had a defaultlist, but we don't. Is there a more elegant solution here? * Is there a way to get headings in docstrings? I want to create my own sections, like "OVERVIEW", "EXAMPLES", "AUTHORS", "BUGS", etc. I can't figure out any way to do this. In perldoc, I can easily use =head1, but I can't figure out the Python equivalent. At first I thought I could use (re)structuredtext, but then it became apparent that pydoc(1) does not parse any of this markup. Am I missing something, or is it just not possible to achieve this effect other than by writing separate, independent manpages? Thanks for any suggestions or thoughts. From stef.mientki at gmail.com Thu Jan 17 16:56:16 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 17 Jan 2008 22:56:16 +0100 Subject: get the size of a dynamically changing file fast ? Message-ID: <478FCF00.8060308@gmail.com> hello, I've a program (not written in Python) that generates a few thousands bytes per second, these files are dumped in 2 buffers (files), at in interval time of 50 msec, the files can be read by another program, to do further processing. A program written in VB or delphi can handle the data in the 2 buffers perfectly. Sometimes Python is also able to process the data correctly, but often it can't :-( I keep one of the files open en test the size of the open datafile each 50 msec. I have tried os.stat ( ....) [ ST_SIZE] os.path.getsize ( ... ) but they both have the same behaviour, sometimes it works, and the data is collected each 50 .. 100 msec, sometimes 1 .. 1.5 seconds is needed to detect a change in filesize. I'm using python 2.4 on winXP. Is there a solution for this problem ? thanks, Stef Mientki From teddyber at gmail.com Fri Jan 11 17:35:38 2008 From: teddyber at gmail.com (teddyber) Date: Fri, 11 Jan 2008 14:35:38 -0800 (PST) Subject: split parameter line with quotes References: <37fac828-20ec-4cb9-8ea7-a85cce7d3e91@k39g2000hsf.googlegroups.com> Message-ID: here's the solution i have for the moment : t = shlex.shlex(data) t.wordchars = t.wordchars + "/+.-" r='' while 1: token = t.get_token() if not token: break if not token==',': r = r+token else: r = r + ' ' self.DEBUG(r,'ok') for pair in r.split(' '): key,value=pair.split('=', 1) print(key+':'+value) i know this is not perfect still but i'm coming a long way from very bad php habits! :o) and thanks for your help! On 11 jan, 23:30, teddyber wrote: > wow! that's perfect this shlex module! thanks for pointing this! > > On 11 jan, 20:36, Joshua Kugler wrote: > > > teddyber wrote: > > > first i'm a newbie to python (but i searched the Internet i swear). > > > i'm looking for some way to split up a string into a list of pairs > > > 'key=value'. This code should be able to handle this particular > > > example string : > > > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > > > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > > > i know i can do that with some regexp (i'm currently trying to learn > > > that) but if there's some other way... > > > Take a look at the shlex module. You might be able to fiddle with the shlex > > object and convince it to split on the commas. But, to be honest, that > > above would be a lot easier to parse if the dividing commas were spaces > > instead. > > > j From brkict at gmail.com Tue Jan 29 10:48:58 2008 From: brkict at gmail.com (glomde) Date: Tue, 29 Jan 2008 07:48:58 -0800 (PST) Subject: runscript module, where are the docs... Message-ID: <1fbdde0d-ae09-4b6a-8f08-0713de94cc0b@j78g2000hsd.googlegroups.com> Hi! I am going through some code and found import runscript BUT I cant find and information about this module. I searched Google did a grep in the /usr/lib/python directory. What is the purpose of this module and where can I find information about it. Or the source. Best regards, Toni From azam.farooq3 at gmail.com Sat Jan 26 01:53:33 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Fri, 25 Jan 2008 22:53:33 -0800 (PST) Subject: Mobile Phones, iPods EQ100 www.enmac.com.hk Message-ID: <4def7add-dc5e-4325-a54a-3c1408912e57@i29g2000prf.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 guptaabhishek1983 at gmail.com Thu Jan 3 08:48:16 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Thu, 3 Jan 2008 05:48:16 -0800 (PST) Subject: Trying to build python2.5.msi Message-ID: <8091fa48-7c38-4502-84c9-5527586a6568@i3g2000hsf.googlegroups.com> Hello Group, I have compile the python source code using MSVC 8 (a.k.a VS .NET 2005) . Can i create an MSI ?? similar to one provided by the official python website. What can be the possible procedure to achieve this. I have looked into Tools/msi folder. But i dont know how it works. Thank you Abhishek From terry at jon.es Mon Jan 21 06:54:22 2008 From: terry at jon.es (Terry Jones) Date: Mon, 21 Jan 2008 12:54:22 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 03:27:45 on Monday, 21 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <5a26081c-8bcd-440c-bffa-6d730e38ff59@s12g2000prg.googlegroups.com> Message-ID: <18324.34798.714387.580378@terry.local> >>>>> "Arnaud" == Arnaud Delobelle writes: Arnaud> Sorry I gave an incorrect example to illustrate my question last Arnaud> night (I blame this on baby-induced sleep deprivation ;), so I'll Arnaud> have another go: Arnaud> Say I have 2, 3, 4, 100 and I want to make 406. AFAICS there is only Arnaud> one way: (2*3)+(4*100), i.e. in postfix notation: Arnaud> 2 3 * 4 100 * + Arnaud> It seemed to me that your function wouldn't generate that sort of Arnaud> solution (as you always extend partialSolution by [num, op] making Arnaud> the subsequence [mul, add] impossible). Am I wrong? No, you're right. I actually started out with a stack solution, and then switched to something simpler (too simple). I'm going to redo it, but maybe not right now... Thanks! Terry From levilista at gmail.com Thu Jan 10 17:55:18 2008 From: levilista at gmail.com (zslevi@gmail.com) Date: Thu, 10 Jan 2008 14:55:18 -0800 (PST) Subject: adding methods at runtime Message-ID: <940fcb28-764e-46ab-a627-aff513e009e1@j78g2000hsd.googlegroups.com> Can I access the class attributes from a method added at runtime? (My experience says no.) I experimented with the following code: class myclass(object): myattr = "myattr" instance = myclass() def method(x): print x instance.method = method instance.method("hello world") inst2 = myclass() #inst2.method("inst2") def meth2(x): print x.myattr myclass.ujmeth = meth2 inst2 = myclass() inst2.ujmeth() ############ The output: ########## hello world myattr ################ So it seems to me, if you add a method to an instance, the method will not get "self" as parameter. From sergio.correia at gmail.com Wed Jan 30 22:38:55 2008 From: sergio.correia at gmail.com (Sergio Correia) Date: Wed, 30 Jan 2008 22:38:55 -0500 Subject: Fwd: small problem with re.sub In-Reply-To: References: <47A13A0A.3010607@al.com.au> Message-ID: See this: http://www.regular-expressions.info/python.html (the Search and Replace part) You are referring to the group as "(?P=id)", when you should be using r"\g". HTH, Sergio On Jan 30, 2008 10:01 PM, Astan Chee wrote: > Hi, > I have a html text stored as a string. Now I want to go through this > string and find all 6 digit numbers and make links from them. > Im using re.sub and for some reason its not picking up the previously > matched condition. Am I doing something wrong? This is what my code > looks like: > htmlStr = re.sub('(?P\d{6})',' href=\"http://linky.com/(?P=id).html\">(?P=id)',htmlStr) > It seems that it replaces it alright, but it replaces it literally. Am I > not escaping certain characters? > Thanks again for the help. > Cheers > > Animal Logic > http://www.animallogic.com > > Please think of the environment before printing this email. > > This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From michele.simionato at gmail.com Tue Jan 15 00:13:51 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 14 Jan 2008 21:13:51 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> <65cfbd40-6612-4bd5-aa5c-a1338da0f5a7@n20g2000hsh.googlegroups.com> Message-ID: <30c8bfe6-ef36-4f98-b281-f03f62f3d17e@k2g2000hse.googlegroups.com> On Jan 14, 11:47 pm, Richard Szopa wrote: > Could you tell me what are the pros and cons of the two approaches > (i.e. writing a decorator function and a decorator descriptor class)? I prefer to use a class for introspection sake, since there is no way to get information about an inner function in a closure, whereas your users can introspect classes pretty well. > super_object = super(self.__class__, self) Notice that using super(self.__class__, self) is a common mistake: the pitfalls with inheritance were discussed very recently in this same newsgroup, you should be able to find the post. What you need is super(class_where_the_method_is_defined, self) which is in general different from super(self.__class__, self) There is no clean way to determine the current class in Python < 3.0 (Python 3.0 does it automatically); if you want to see a hackish way involving bytecode tricks see http://groups.google.com/group/comp.lang.python/browse_frm/thread/a6010c7494871bb1/62a2da68961caeb6?hl=en&lnk=gst&q=currentClass#62a2da68961caeb6 (and notice that this is really not recommended). Michele Simionato From http Tue Jan 15 13:14:03 2008 From: http (Paul Rubin) Date: 15 Jan 2008 10:14:03 -0800 Subject: Dynamical scoping References: <1a3243ef-13f6-40d6-97eb-198b8742ac3d@d4g2000prg.googlegroups.com> <7xabn7hovr.fsf@ruckus.brouhaha.com> Message-ID: <7xfxwzgdn8.fsf@ruckus.brouhaha.com> Kay Schluehr writes: > On 15 Jan., 02:13, Paul Rubin wrote: > > George Sakkis writes: > > > What's the best way to simulate dynamically scoped variables ala Lisp ? > > > > Ugh.... check the docs for the python 2.5 "with" statement, which > > gives you sort of a programmable unwind-protect (more powerful than > > try/except). You'd have an environment dictionary and use the "with" > > statement to maintain a stack of shallow-binding cells like in an > > old-time lisp system, automatically unwinding when the "with" suite > > finishes. The whole concept sounds hopelessly crufty--I think nobody > > even does it that way in Lisp any more, you're better off passing an > > environment around explicitly. If there were a lot of variables, this > > could be a good application for functional maps, which I've been wanting > > to implemetn for python. Kay, did you have something to add? You quoted the above two posts and then your message stopped. From pinch13 at verizon.net Sun Jan 20 10:24:39 2008 From: pinch13 at verizon.net (BJ) Date: Sun, 20 Jan 2008 07:24:39 -0800 (PST) Subject: Homework Helper and College Companion Websites Message-ID: In 1996 I started BJ Pinchbeck's Homework Helper at www.bjpinchbeck.com which became quite popular among young students throughout the country. Now that I am 20 years old and attending Drexel University in Philadelphia, Pennsylvania, I decided it was time to start a new site, BJ Pinchbeck's College Companion at www.bjpinchbeck.net that could help students prepare for and survive the college experience. College has been a very positive experience for me, but it would have been nice to have more materials readily available to me prior to attending college. Please feel free to link to either site. Thank you BJ Pinchbeck From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 23 12:16:29 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 23 Jan 2008 18:16:29 +0100 Subject: Bug in __init__? In-Reply-To: References: <4795b788$0$11545$426a34cc@news.free.fr> Message-ID: <4797761a$0$4430$426a74cc@news.free.fr> Bart Ogryczak a ?crit : > On 2008-01-22, citizen Bruno Desthuilliers testified: >>> from copy import copy >>> ### see also deepcopy >>> self.lst = copy(val) >> What makes you think the OP wants a copy ? > > I?m guessing he doesn?t want to mutate original list, while changing > contents of self.lst. Once again: what makes you think so ? This is a design choice depending on the concrete use case and context - which we don't know zilch about - and by no mean the default behaviour. From rbonvall at gmail.com Sun Jan 13 01:34:49 2008 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Sat, 12 Jan 2008 22:34:49 -0800 (PST) Subject: Elementary string-formatting References: Message-ID: On Jan 12, 10:15 pm, Odysseus wrote: > P.S. Is there a preferable technique for forcing floating-point division > of two integers to that used above, multiplying by "100.0" first? Put this at the beginning of your program: from __future__ import division This forces all divisions to yield floating points values: >>> 1/3 0 >>> from __future__ import division >>> 1/3 0.33333333333333331 >>> HTH, -- Roberto Bonvallet From ruivaldo at gmail.com Thu Jan 10 09:21:59 2008 From: ruivaldo at gmail.com (rui) Date: Thu, 10 Jan 2008 11:21:59 -0300 Subject: I'm searching for Python style guidelines In-Reply-To: References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: Thanks Caleb. Really liked some points. On Jan 10, 2008 11:20 AM, Caleb wrote: > MartinRinehart at gmail.com wrote: > > > Anything written somewhere that's thorough? Any code body that should > > serve as a reference? > > 1. Don't use tabs (use spaces). > 2. Study "import this" > 3. Use lists and dictionaries as much as you possibly can > 4. Use comprehensions and generators as much as you possibly can > 5. Use the standard library for everything you possibly can > 6. As much as you possibly can, when starting a new project, postpone > setting up classes for everything (start with functions). In some > projects, you might never need the overhead at all. > > It will be difficult to go far wrong regarding style if you do a lot of > what's in this list. This list is not mine. I jotted these points > down, but this information is continually repeated by the actual wise > people (not me) in this newsgroup. > > Caleb > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Rui http://rui.tumblr.com "Rubi? Aquela novela do SBT?" ~ Carla Perez sobre Ruby "Em Python, tudo ? objeto, al?m de lindo e maravilhoso." ~ Caetano Veloso sobre Python From sjmachin at lexicon.net Fri Jan 25 04:28:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 01:28:51 -0800 (PST) Subject: Python ADO Date Time database fields References: Message-ID: On Jan 25, 10:55 am, goldtech wrote: > Hi, > > Given an MS-Access table with a date type field with a value of: > 12:00:00 AM - just"12:00:00 AM", there's nothing else in the field. > > I want to print exactly what's in the field, ie. "12:00:00 AM". What I > get printed is: 12/30/0/ 00:00:00 > > I try: [snip] > print oRS.Fields(dt).Value # print here try this: val = oRS.Fields(dt).Value print type(val) print float(val) If the last one gives you 0.0, then you have got exactly what's in the database -- stored as a fraction of a day. Six AM would give you 0.25. Converting that to 24 hour clock is easy: >>> val = 0.12345 >>> seconds = int(round(val * 60 * 60 * 24)) >>> minutes, second = divmod(seconds, 60) >>> hour, minute = divmod(minutes, 60) >>> '%02d:%02d:%02d' % (hour, minute, second) '02:57:46' >>> ((((46/60.)+57)/60.)+2)/24. # checking 0.12344907407407407 If you don't get 0.0, let us know what you did get. HTH, John From bdesth.quelquechose at free.quelquepart.fr Sun Jan 6 14:43:42 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 06 Jan 2008 20:43:42 +0100 Subject: python interfaces In-Reply-To: References: Message-ID: <47812f6b$0$17701$426a74cc@news.free.fr> Sion Arrowsmith a ?crit : > hyperboreean wrote: > >>Why doesn't python provide interfaces trough its standard library? > > > Because they're pointless. (snip rant about Java's "interfaces") Hem... Zope3's "interface" system is not exactly the same thing as Java's one. From elind at spamcop.net Mon Jan 14 14:25:29 2008 From: elind at spamcop.net (Erik Lind) Date: Mon, 14 Jan 2008 14:25:29 -0500 Subject: help with slicing/replacing matrix sections. Message-ID: <478bb75f$0$5001$4c368faf@roadrunner.com> I see a more complicated thread on a similar sounding question, but my question is simpler, I hope. I have a large numpy matrix, initially created as: Mat = zeros((a,b), int) and a smaller array with other data Sub = [1,2,3,4,5],[6,7,8,9,0] I want to replace a section of Mat matrix with Sub matrix without having to loop through each cell in each matrix individually. I thought index/slice assignments, should be able to do that, but I can only get it to work (as per book examples) with simple arrays. Every syntax combination I have tried gives one error or another, typically "can't broadcast an object....", but intuitively it seems there should be a simple solution. In short, how do I insert the data in the two (or any number of) rows in Sub[0:2] into any part of Mat starting at Mat[x,y] without using "for" loops ? From mensanator at aol.com Fri Jan 18 16:21:55 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 18 Jan 2008 13:21:55 -0800 (PST) Subject: Bit Scan Forward and Reverse References: Message-ID: On Jan 18, 2:01?pm, Thomas Dybdahl Ahle wrote: > Hi, I'm writing an app in python, and I'm storing some a lot of data in > bitmaps. > I need a way to find the first or latest set bit in a 64bit number, and > for that I've implemented a small routine. > > Thing is that this routine is not as fast as I'd wish. I know most > processors implement BSF and BSR calls to do this efficiently. > Is there anyway to access those calls from python? > > I'd still have my routine as a fallback on nonsupporting architectures. Get a copy of the gmpy module. Help on module gmpy: NAME gmpy FILE c:\program files\pygtk\python\lib\site-packages\gmpy.pyd DESCRIPTION gmpy 1.04 - General Multiprecision arithmetic for PYthon: exposes functionality from the GMP 4 library to Python 2.{2,3,4}. Allows creation of multiprecision integer (mpz), float (mpf), and rational (mpq) numbers, conversion between them and to/from Python numbers/strings, arithmetic, bitwise, and some other higher-level mathematical operations; also, pretty good-quality linear-congruential random number generation and shuffling. mpz has comparable functionality to Python's builtin longs, but can be faster for some operations (particularly multiplication and raising-to-power) and has many further useful and speedy functions (prime testing and generation, factorial, fibonacci, binary-coefficients, gcd, lcm, square and other roots, ...). mpf and mpq only offer basic arithmetic abilities, but they do add the ability to have floating-point numbers ensuring at least a predefined number of bits' worth of precision (and with potentially-huge or extremely-tiny magnitudes), as well as unlimited-precision rationals, with reasonably-fast operations, which are not built-in features of Python. FUNCTIONS (selected operations for binary use) getbit(...) getbit(x,n): returns 0 or 1, the bit-value of bit n of x; n must be an ordinary Python int, >=0; x is an mpz, or else gets coerced to one. hamdist(...) hamdist(x,y): returns the Hamming distance (number of bit- positions where the bits differ) between x and y. x and y must be mpz, or else get coerced to mpz. lowbits(...) lowbits(x,n): returns the n lowest bits of x; n must be an ordinary Python int, >0; x must be an mpz, or else gets coerced to one. popcount(...) popcount(x): returns the number of 1-bits set in x; note that this is 'infinite' if x<0, and in that case, -1 is returned. x must be an mpz, or else gets coerced to one. scan0(...) scan0(x, n=0): returns the bit-index of the first 0-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 0-bits are in x at or above bit-index n (which can only happen for x<0, notionally extended with infinite 1-bits), None is returned. x must be an mpz, or else gets coerced to one. scan1(...) scan1(x, n=0): returns the bit-index of the first 1-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 1-bits are in x at or above bit-index n (which can only happen for x>=0, notionally extended with infinite 0-bits), None is returned. x must be an mpz, or else gets coerced to one. setbit(...) setbit(x,n,v=1): returns a copy of the value of x, with bit n set to value v; n must be an ordinary Python int, >=0; v, 0 or ! =0; x must be an mpz, or else gets coerced to one. These work quite nicely. I use scan1() in the following idiom which removes all factors of 2 in one fell swoop. n = 3*n + 1 # always even, but how even? f = gmpy.scan1(n) # bit position of LS 1-bit n = n >> f # ...which is number of 0-bits > > -- > Med venlig hilsen, > Best regards, > Thomas From jamon.ben at gmail.com Wed Jan 9 15:07:16 2008 From: jamon.ben at gmail.com (Ben Fisher) Date: Wed, 9 Jan 2008 15:07:16 -0500 Subject: Structure of packages Message-ID: <741fd030801091207h720ecc2cya4fb543db29ddabc@mail.gmail.com> I am trying to learn the best way to do intra-package references. My package looks like this: PackageName __init__.py /a __init__.py a.py ... /b __init__.py ... /c __init__.py ... /d __init__.py ... I have layered the dependencies so that a depends on b, b depends on c, and c depends on d. There are no circular references. Now I would like to be able to refer to the subpackage b from inside the subpackage a. In effect, I would like to say "from '../b' import *" I had thought that "from PackageName.b import *" would work. This works for a file in the directory /PackageName, but not for a file in the directory /PackageName/a. It's like when you are running a Python file in the directory /PackageName/a it doesn't know about PackageName - No module named "PackageName". Is there a solution to this, or a better way to structure the directories? From nicogrubert at gmail.com Thu Jan 10 05:23:20 2008 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 10 Jan 2008 11:23:20 +0100 Subject: Rebuild list of objects with redundancies on objects' attribute Message-ID: <4785F218.3020905@gmail.com> Hi there I have a list of dummy objects which have the attributes 'location', 'name', 'gender'. Now I want to rebuild this list in order to avoid redundancies on objects with the same 'location'. Example: #------------------------------------------------------------------ class Dummy: pass a = Dummy() a.location = 'tokio' a.name = 'john' a.gender = 'm' b = Dummy() b.location = 'tokio' b.name = 'peter' b.gender = 'm' c = Dummy() c.location = 'madrid' c.name = 'susan' c.gender = 'f' d = Dummy() d.location = 'london' d.name = 'alex' d.gender = 'm' persons = [a, b, c, d] print "loc name gender" print "---------------------" for obj in persons: print "%s - %s - %s" % (obj.location, obj.name, obj.gender) #------------------------------------------------------------------ The output reads like this: loc name gender --------------------- tokio john m tokio peter m madrid susan f london alex m I want to create this list (where name and gender are lists): loc name gender ----------------------------- tokio [john, peter] [m] madrid [susan] [f] london [alex] [m] How can I do this? Thanks in advance. Nico From lists at cheimes.de Thu Jan 3 11:38:52 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 03 Jan 2008 17:38:52 +0100 Subject: How do you pass compiler option to setup.py install? In-Reply-To: <32e43bb70801030824p7099da66s6ffb4ee0ea58b311@mail.gmail.com> References: <32e43bb70801030824p7099da66s6ffb4ee0ea58b311@mail.gmail.com> Message-ID: <477D0F9C.7000507@cheimes.de> Emin.shopper Martinian.shopper wrote: > Dear Experts, > > How do you pass the -c option to setup.py install? Specifically, when I try > to install zope.interfaces version 3.3 from source on a windows machine, I > get a message about using "-c mingw32". That works fine for setup.py build, > but it does not work for "setup.py install". python setup.py build -c mingw32 install You can also change the distutils.cfg file to set mingw32 as the default compiler. Please refer to the documentation for more information. Christian From afriere at yahoo.co.uk Wed Jan 23 02:16:16 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 22 Jan 2008 23:16:16 -0800 (PST) Subject: Removing objects References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> Message-ID: <27c8e3c8-3766-499c-9c62-82b03fa583d6@e23g2000prf.googlegroups.com> On Jan 23, 5:59 pm, bladedpeng... at gmail.com wrote: > I am writing a game, and it must keep a list of objects. I've been > representing this as a list, but I need an object to be able to remove > itself. It doesn't know it's own index. If I tried to make each object > keep track of it's own index, it would be invalidated when any object > with a lower index was deleted. The error was that when I called > list.remove(self), it just removed the first thing in hte list with > the same type as what I wanted, rather than the object I wanted. The > objects have no identifying charachteristics, other than thier > location in memory > > So my question: How do I look something up in a list by it's location > in memory? does python even support pointers? > > Is there a better way? How about adding an id attribute to your objects, which will contain a unique identifier, override __eq__ to use that id to compare itself to others and then simply pop off the object using object_list.pop(object_list.index(self)). Something like this: >>> class Spam (object) : def __init__ (self, id) : self.id = id def __eq__ (self, other) : try : return self.id == other.id except AttributeError : return False >>> >>> a,b,c = Spam(1), Spam(2), Spam(3) >>> x = [a,b,c] >>> x.pop(x.index(c)) <__main__.Spam object at 0x885e5ac> Except your object would be telling the list to pop self of course, and you'd need someway of insuring the uniqueness of your IDs. From jeffrey at fro.man Fri Jan 18 09:27:02 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Fri, 18 Jan 2008 06:27:02 -0800 Subject: Cannot catch _mysql_exceptions.OperationalError References: <5f435c88-ef42-4ca9-921a-675393824ccc@k39g2000hsf.googlegroups.com> Message-ID: <13p1dpnq6icdh0e@corp.supernews.com> Bob wrote: > Here's the code that did not work: > > import _mysql_exceptions > from _mysql_exceptions import OperationalError > > try: > database_code() > except (_mysql_exceptions.OperationalError, OperationalError), e: > error_handling() Both of the above forms work fine here, as does using MySQLdb.OperationalError: ------------------------------------------------ >>> import MySQLdb >>> try: ... db = MySQLdb.connect(user='jeffrey', host='localhost') ... except MySQLdb.OperationalError: ... print 'caught' ... caught >>> import _mysql_exceptions >>> try: ... db = MySQLdb.connect(user='jeffrey', host='localhost') ... except _mysql_exceptions.OperationalError: ... print 'caught' ... caught >>> from _mysql_exceptions import OperationalError >>> try: ... db = MySQLdb.connect(user='jeffrey', host='localhost') ... except OperationalError: ... print 'caught' ... caught >>> MySQLdb.OperationalError is _mysql_exceptions.OperationalError True >>> MySQLdb.__version__ '1.2.2' ------------------------------------------------ Jeffrey From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 08:59:20 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 14:59:20 +0100 Subject: Python too slow? In-Reply-To: <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> <478732db$0$19250$426a74cc@news.free.fr> <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> Message-ID: <4787762b$0$18777$426a74cc@news.free.fr> George Sakkis a ?crit : > On Jan 11, 4:12 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > >> George Sakkis a ?crit : >> >>> On Jan 10, 3:37 am, Bruno Desthuilliers wrote: >>>> I fail to see how the existence of JIT compilers in some Java VM changes >>>> anything to the fact that both Java (by language specification) and >>>> CPython use the byte-code/VM scheme. >>> Because these "some Java VMs" with JIT compilers are the de facto >>> standard used by millions; >> Repeating an argument doesn't make it more true nor more relevant. Once >> again, this doesn't change anything to the fact exposed above. >> >>> the spec is pretty much irrelevant >> I mentionned this because this kind of choice is usually not part of the >> language spec but of a specific implementation. Java is AFAIK the only >> language where this implementation stuff is part of the spec. >> >>> (unless >>> you're a compiler writer or language theorist). >> I thought it was quite clear and obvious that I was talking about points >> relating to these fields. > > No it wasn't, """ > or is Python just too slow > as an interpreted language Being "interpreted" is a quality of an implementation, not of a language. """ If that isn't clear enough what I'm talking about, then sorry but I can't help. > and besides the OP is most likely interested in these as > a simple user so the distinction between a spec and a de facto > standard implementation (such as JDK for Java and CPython for Python) > are almost pedantic if not misleading. I can live with being called "pedantic" - even I'm not sure whether correcting a wrong statement about CPython's execution model is pedantic or not. But I *still* fail to see how it could be "misleading", and *you* still fail to explain in which way it could be misleading. If your point is that saying that CPython uses a byte-code/VM scheme "just like Java" necessarily implies JIT compilation just because some JVM support this feature, then it would be time you pay more attention to what is effectively written. > We're not Lisp (yet ;-)), with > five major implementations and a dozen of minor ones. And ? In which way does it make the distinction between a language and a language implementation less true ? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 28 10:00:25 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 28 Jan 2008 16:00:25 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <60357uF1perd0U1@mid.individual.net> Message-ID: <60690aF1otfruU1@mid.individual.net> over at thepond.com wrote: > Bjoern Schliessmann wrote: >> over at thepond.com wrote: >>> That's not the point, however. I'm trying to say that a >>> processor cannot read a Python script, and since the Python >>> interpreter as stored on disk is essentially an assembler file, >> >> It isn't; it's an executable. > > I appreciated the intelligent response I received from you > earlier, now we're splitting hairs. :-) Not at all. Assembly source is ASCII text. An executable commonly consists of a binary header (which contains various information => man elf) as well as code and data segments. Normally, you're only guaranteed to find machine language inside the code segments. > Assembler, like any other higher level language Assembler is _no_ high level language, though there are some assembly languages striving for resembling HLLs. http://webster.cs.ucr.edu/AsmTools/HLA/index.html > is written as a source file and is compiled to a binary. BMPs are binaries, too. Assembly code is compiled to object code files. > An executable is one form of a binary, as is a dll. When you view > the disassembly of a binary, there is a distinct difference > between C, C++, Delphi, Visual Basic, DOS, I don't think so. How a HLL source is translated to machine code depends on the compiler, and there are cross compilers. > or even between the different file types like PE, NE, MZ, etc. Yes. > But they all decompile to assembler. No. They all _contain_ code segments (which contain machine code), but also different data. > While they are in the binary format, they are exactly > that...binary. http://en.wikipedia.org/wiki/Binary_data > Who would want to interpret a long string of 1's and 0's. Binaries > are not stored in hexadecimal on disk nor are they in hexadecimal > in memory. But, all the 1's and 0's are in codes when they are > instructions or ASCII strings. No -- they're voltages or magnetic fields. (I never saw "0"s or "1"s in a memory chip or on a hard disk.) The representation of this data is up to the viewing human being to choose. > No other high level language has the one to one relationship that > assembler has to machine code, the actual language of the > computer. Yes. That's why Assembly language is not "high level", but "low level". > All the ASCIi strings end with 0x74 in the disassembly. *sigh* > I have noted that Python uses a newline as a line feed/carriage > return. (The means of line separation is not chosen just like this by Python users. It's convention depending on the OS and the application.) > Now I'm getting it. It could all be disassembled with a hex > editor, but a disassembler is better for getting things in order. Argl. A hex editor just displays a binary file as hexadecimal numbers, it does _not_ disassemble. "Disassembly" refers to _interpreting_ a file as machine instructions of one particular architecture. This, of course, only makes sense if this binary file actually contains machine instructions that make sense, not if it's really a picture or a sound file. Regards, Bj?rn -- BOFH excuse #130: new management From tarundevnani at gmail.com Sun Jan 6 08:04:38 2008 From: tarundevnani at gmail.com (tarun) Date: Sun, 6 Jan 2008 18:34:38 +0530 Subject: Killing worker threads Message-ID: Hello All, Can anyone help me with a simple code through which the main thread can kill the worker thread it started. Thanks & Regards, Tarun Devnani -------------- next part -------------- An HTML attachment was scrubbed... URL: From bg_ie at yahoo.com Fri Jan 25 07:05:37 2008 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Fri, 25 Jan 2008 04:05:37 -0800 (PST) Subject: The dimensions of a tuple References: <19d605ab-86de-44ec-8864-864554ffebc1@d21g2000prf.googlegroups.com> Message-ID: <2f6f696c-2914-4e6f-bf6d-584103bcb907@j78g2000hsd.googlegroups.com> On 25 Jan, 12:03, John Machin wrote: > On Jan 25, 9:26 pm, bg... at yahoo.com wrote: > > > Hi, > > > I wish to pass an argument to a function which will inset rows in a > > db. I wish to have the follow possibilities - > > > ("one","two") > > (("one","two"),("three","four")) > > > The first possibility would mean that one row is added with "one and > > "two" being its column values. The second possibility means that two > > rows are added. > > > So to do this I need to establish the dimension of the duple. Is it a > > one dimentional or two dimentional. How do I do this? > > isinstance(arg[0], tuple) > > ... but I wouldn't do it that way. I'd use a list of tuples, not a > tuple of tuples, to allow for ease of building the sequence with > list.append, and two functions: > > insert_one(("one", "two")) > insert_many([("one", "two")]) > insert_many([("one", "two"), ("three", "four")]) > > Which of those 2 functions calls the other depends on which you'd use > more often. > > HTH, > John Thanks for the tip regarding the list of tuples! From gagsl-py2 at yahoo.com.ar Mon Jan 28 11:58:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Jan 2008 08:58:46 -0800 (PST) Subject: SMTP Sending Mail Problem References: <9b00a5f5-277d-4d23-be82-60c2aafc4227@c23g2000hsa.googlegroups.com> Message-ID: On 28 ene, 14:15, the_ricka wrote: > However, whenever I try to read more than one line from the file, the > email is not being delivered. ?The only reason I know this is because > I tried just reading in the first line of the text file, and the email > sent fine. ?Right now I believe this must have something to do with > new line characters at the end of each line, but it doesn't quite make > sense to me why this is a problem, as I have also used the same script > and just created a string in it with multiple lines (\r\n) and sent it > and the email sends fine. ?To complicate the issue further, I have > turned used the set_debuglevel method so I can see the output from the > SMTP server, and it appears that the message was Queued for mail > delivery. Your code is fine, and the message was queued as you noticed. Maybe the recipient has some sort of black list, didn't like the sender, the message was classified as spam, or something like that. I'd look for problems elsewhere, not in the code. > send: 'From: #######@######.com\r\nTo: ######@######.com\r\nSubject: > Test1\r\n\ > r\nThis is from the file\r\nThis concludes our test\r\n\r\n\r\n.\r\n' > reply: '250 2.6.0 <############@###############.com> Qu > eued mail for delivery\r\n' > reply: retcode (250); Msg: 2.6.0 <##########@n#########.com> Queued > mail for delivery > data: (250, '2.6.0 <########@################.com> Q > ueued mail for delivery') > send: 'quit\r\n' > reply: '221 2.0.0 ################.com Service closing transmission > cha > nnel\r\n' > reply: retcode (221); Msg: 2.0.0 #################.com Service closing > t > ransmission channel -- Gabriel Genellina From petr.jakes.tpc at gmail.com Fri Jan 25 22:25:18 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Fri, 25 Jan 2008 19:25:18 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> <45a8d4a7-d24d-461e-9783-59a7d697a041@q77g2000hsh.googlegroups.com> Message-ID: <499aaee4-7e8f-47fb-bedd-7db548b92a5c@i29g2000prf.googlegroups.com> > I agree that SDL is probably the best choice but for the sake of > completeness, Gtk can (at least in theory - I've never tried it) be > built against directfb and run without X. from the Pygame Introduction: Pygame is a Python extension library that wraps the SDL library and it's helpers. So you mean, Pygame can run without X? BTW I have nothing against X, I just have not experiences on the GUI field, so my feeling was it can run faster without X on the 500MHz AMD Geode CPU. Petr From deets at nospam.web.de Sat Jan 19 11:10:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 19 Jan 2008 17:10:35 +0100 Subject: Ruby Programming In-Reply-To: <5b554594-158f-4efe-9cd2-1fb66d150781@d4g2000prg.googlegroups.com> References: <5b554594-158f-4efe-9cd2-1fb66d150781@d4g2000prg.googlegroups.com> Message-ID: <5velo2F1m688bU1@mid.uni-berlin.de> LinkExchange.AB at gmail.com schrieb: > iTechArt has specialized in Ruby on Rails (ROR) development and > provides a complete software outsourcing services for web development > solutions based on Ruby. We suggest use Ruby framework for developing > database-backed web applications with Ajax on front-end because it's a > great fit for practically any type of web application: collaboration, > community, e-commerce, content management and statistics. > > Ruby development environment and technologies: > > * Ruby On Rails development framework > * MySQL, PostgreSQL, SQLite, Oracle, MS SQL Server, DB2 > * RadRails IDE, ActionWebservice for Ruby > * Linux, Apache, lighttpd > * OOP and software development > * Search engines optimization > > > > http://itechart.is.stupid/foo.aspx Funny. Either rails isn't so good for the company's own website - which I doubt - or they don't know as much about it as they claim.... link changed to prevent proper indexing ... Diez From yhvh2000 at googlemail.com Tue Jan 15 20:44:08 2008 From: yhvh2000 at googlemail.com (yhvh) Date: Tue, 15 Jan 2008 17:44:08 -0800 (PST) Subject: error/warning color customization in interactive console? Message-ID: Is it possible to output error messages in a different color? I'm using Terminal on Gnome. From horacius.rex at gmail.com Tue Jan 8 09:29:58 2008 From: horacius.rex at gmail.com (Horacius ReX) Date: Tue, 8 Jan 2008 06:29:58 -0800 (PST) Subject: Look for a string on a file and get its line number References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <03a301c851e1$4f211a00$0203a8c0@MOUSE> Message-ID: <39901b17-8ac2-4c04-8e71-3e27fc795efc@i3g2000hsf.googlegroups.com> Hi, thanks for the help. Then I got running the following code; #!/usr/bin/env python import os, sys, re, string, array, linecache, math nlach = 12532 lach_list = sys.argv[1] lach_list_file = open(lach_list,"r") lach_mol2 = sys.argv[2] # name of the lachand mol2 file lach_mol2_file = open(lach_mol2,"r") n_lach_read=int(sys.argv[3]) # Do the following for the total number of lachands # 1. read the list with the ranked lachands for i in range(1,n_lach_read+1): line = lach_list_file.readline() ll = string.split (line) #print i, ll[0] lach = int(ll[0]) # 2. for each lachand, print mol2 file # 2a. find lachand header in lachand mol2 file (example; kanaka) # and return line number line_nr = 0 for line in lach_mol2_file: line_nr += 1 has_match = line.find('kanaka') if has_match >= 0: print 'Found in line %d' % (line_nr) # 2b. print on screen all the info for this lachand # (but first need to read natoms and nbonds info) # go to line line_nr + 1 ltr=linecache.getline(lach_mol2, line_nr + 1) ll=ltr.split() #print ll[0],ll[1] nat=int(ll[0]) nb=int(ll[1]) # total lines to print: # header, 8 # at, na # b header, 1 # n # lastheaders, 2 # so; nat + nb + 11 ntotal_lines = nat + nb + 11 # now we go to the beginning of the lachand # and print ntotal_lines for j in range(0,ntotal_lines): print linecache.getline(lach_mol2, line_nr - 1 + j ) which almost works. In the last "for j" loop, i expected to obtain an output like: sdsdsdsdsdsd sdsdsfdgdgdgdg hdfgdgdgdg but instead of this, i get: sdsdsdsdsdsd sdsdsfdgdgdgdg hdfgdgdgdg and also the program is very slow. Do you know how could i solve this ? thanks Tim Chase wrote: > >> I have to search for a string on a big file. Once this string > >> is found, I would need to get the number of the line in which > >> the string is located on the file. Do you know how if this is > >> possible to do in python ? > > > > This should be reasonable: > > > >>>> for num, line in enumerate(open("/python25/readme.txt")): > > if "Guido" in line: > > print "Found Guido on line", num > > break > > > > > > Found Guido on line 1296 > > Just a small caveat here: enumerate() is zero-based, so you may > actually want add one to the resulting number: > > s = "Guido" > for num, line in enumerate(open("file.txt")): > if s in line: > print "Found %s on line %i" % (s, num + 1) > break # optionally stop looking > > Or one could use a tool made for the job: > > grep -n Guido file.txt > > or if you only want the first match: > > sed -n '/Guido/{=;p;q}' file.txt > > -tkc From ivlenin at gmail.com Thu Jan 24 00:51:20 2008 From: ivlenin at gmail.com (I V) Date: Thu, 24 Jan 2008 05:51:20 GMT Subject: Problems getting Python scripts to run on server References: <83ae0f82-e9af-433e-936d-d5b5600a315e@j20g2000hsi.googlegroups.com> Message-ID: On Wed, 23 Jan 2008 19:41:17 -0800, Yansky wrote: > Hi, I'm having a lot of problems getting any Python scripts to run on my > website. I have put them in the cgi-bin directory and chmodded both the > directory and files to 755. But when I try to access the script, I get a > 404 error: http://forboden.com/cgi-bin/wp.py Note that you don't get a 404 error _from the web server_ - you get it from wordpress (or at least, I do when I look at your page). So what I think is happening is that either the server, or wordpress, doesn't see a file at the URL "/cgi-bin/wp.py", and so it thinks your are trying to access a wordpress post, and http://forboden.com/cgi-bin/wp.py is getting translated to http://forboden.com/index.php/cgi-bin/wp.py . I suspect the problem is in the rewrite rules in the .htaccess in your root directory. My wordpress installation has these rewrite rules: RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d Which, as I understand it mean "not a file" and "not a directory" respectively. If your cgi-bin is not in your document root, presumably cgi-bin/wp.py will indeed show up as not being a file or directory. I'm no mod_rewrite wizard, but looking at the docs[1], maybe you could replace those two lines above with: RewriteCond %{REQUEST_URI} !-U (thought the docs say this "can impact your server's performance!") I'm just guessing at the cause of your problem, but I hope this helps. [1] http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html From ggpolo at gmail.com Mon Jan 7 08:30:52 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 11:30:52 -0200 Subject: How to refer to the current module? In-Reply-To: References: Message-ID: 2008/1/7, Mike : > I want to do something like the following (let's pretend that this is > in file 'driver.py'): > > #!/bin/env python > > import sys > > def foo(): > print 'foo' > > def bar(arg): > print 'bar with %r' % arg > > def main(): > getattr(driver, sys.argv[1])(*sys.argv[2:]) > > if __name__=='__main__': > main() > > > Essentially what I'm trying to get at here is dynamic function > redirection, like a generic dispatch script. I could call this as > > python driver.py foo > > or > > python driver.py bar 15 > > and at any time later I can add new functions to driver.py without > having to update a dispatch dict or what-have-you. > > The problem is, 'driver' doesn't exist in main() line 1. If I 'import > driver' from the command line, then getattr(driver, ...) works, but > it's not bound here. > > Is there any way around this? Can I somehow scope the 'current > module' and give getattr(...) an object that will (at run time) have > the appropriate bindings? globals() =) > > Thanks in advance for all advice! > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From ckimyt at gmail.com Fri Jan 4 09:13:13 2008 From: ckimyt at gmail.com (Mike) Date: Fri, 4 Jan 2008 06:13:13 -0800 (PST) Subject: Strange varargs issue References: Message-ID: <5d2f89f7-58bb-48c1-bde1-6dfddfb67cac@41g2000hsy.googlegroups.com> You know, every once in a while, self really bites me. (I program in Java too much) Thanks for everyone who replied quickly. Mike wrote: >> [ a bunch of crap because I forgot self, nevermind sorry ] From B.Ogryczak at addr.in.reply-to.invalid Tue Jan 22 16:20:14 2008 From: B.Ogryczak at addr.in.reply-to.invalid (Bart Ogryczak) Date: Tue, 22 Jan 2008 21:20:14 +0000 (UTC) Subject: Bug in __init__? References: <4795b788$0$11545$426a34cc@news.free.fr> Message-ID: On 2008-01-22, citizen Bruno Desthuilliers testified: >> from copy import copy >> ### see also deepcopy >> self.lst = copy(val) > > What makes you think the OP wants a copy ? I?m guessing he doesn?t want to mutate original list, while changing contents of self.lst. bart -- "ch?opcy dali z siebie wszystko, z czego tv pokaza?a g??wnie bebechy" http://candajon.azorragarse.info/ http://azorragarse.candajon.info/ From jr9445 at ATT.COM Thu Jan 10 17:27:03 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 10 Jan 2008 16:27:03 -0600 Subject: Newbie question on Classes In-Reply-To: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> References: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.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 Adrian Wood > Sent: Thursday, January 10, 2008 4:47 PM > To: python-list at python.org > Subject: Newbie question on Classes > > > I can call man.state() and then woman.state() or Person.state(man) and > Person.state(woman) to print the status of each. This takes time and > space however, and becomes unmanageable if we start talking about a > large number of objects, and unworkable if there is an unknown number. > What I'm after is a way to call the status of every instance of Man, > without knowing their exact names or number. > How about searching the garbage collector? import gc from random import random class Person: def __init__(self): self.data= random() * 1000 + 1 def WhoAmI(self): return self.data a = Person() b = Person() for i in gc.get_objects(): try: # classes have __class__ and __dict__ defined according to the docs if i.__class__ and i.__dict__ : print i.__class__ if str(i.__class__) == '__main__.Person': print "\tI am", i.WhoAmI() except: pass ***** 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. GA622 From mr.cerutti at gmail.com Thu Jan 10 09:03:34 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 10 Jan 2008 09:03:34 -0500 Subject: docstrings style question In-Reply-To: <13obcbumpitbe23@corp.supernews.com> References: <13obcbumpitbe23@corp.supernews.com> Message-ID: <51302a8c0801100603o7f893392s3d83070f313c4ddf@mail.gmail.com> On Jan 10, 2008 12:47 AM, Steve Brown wrote: > I've got a series of modules which look like this: > > #************ > # > # Temperature Sense Test > # > #************ > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > > I don't like the duplicated information: But the comment is attractive, and > the docstring self.__doc__ is already in use in the test log. I've read that > all modules and classes should have docstrings, but I don't really have > anything else to say, and each module contains only one class. I don't think > that > > """Temperature Sense Test""" > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > would be a real improvement. > > What do you think? I recommend a careful reading of PEP 257. You shouldn't waste your time creating (at best) decorative comments, like: #************ # # Temperature Sense Test # #************ class Test3(ar_test.AR_TEST): """Temperature Sense Test"" Remember that comments have to maintained along with the rest of the code, so unnecessary ones just create more work for you. Any time you can replace a comment with self-explanatory code, you should. Here's a vast improvement: class TemperatureSenseTester(ar_test.AR_TEST): -- Neil Cerutti From bignose+hates-spam at benfinney.id.au Fri Jan 4 18:13:07 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 05 Jan 2008 10:13:07 +1100 Subject: MRO Error on Multiple Inheritance? References: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> Message-ID: <87prwhp4l8.fsf@benfinney.id.au> Ming writes: > I'm working through Wesley Chun's CPP2e and got this error on 13.11.1, > pp 548 where his interpreter snippet shows no problems: I don't know what a "CPP2e" is. Is it a book? Can you give the ISBN? > ActivePython 2.5.1.1 (ActiveState Software Inc.) b > Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [ > win32 > Type "help", "copyright", "credits" or "license" f > >>> class A(object): pass > ... > >>> class B(A): pass > ... > >>> class C(B): pass > ... > >>> class D(A, B): pass > ... > Traceback (most recent call last): > File "", line 1, in > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases A, B > > (I submitted the problem to the author but I'm not sure I'll ever hear > back.) I'm guessing that this kind of diamond inheritance is > prohibited by the interpreter, and that his lack of error messages > from the interpretation is due to actually leaving out the "class > B(A): pass" Can someone shed light? Thanks. That's not an example of diamond inheritance because classes A and B are not distinct classes with a *common* base. Instead, they're in a direct parent-child relationship. So there's no sense in defining class D to inherit from both A *and* B. To get a descendent of both those classes, inheriting from B is sufficient. It should rather be:: class D(B): pass -- \ "Pinky, are you pondering what I'm pondering?" "Uh, I think so, | `\ Brain, but we'll never get a monkey to use dental floss." -- | _o__) _Pinky and The Brain_ | Ben Finney From bbxx789_05ss at yahoo.com Thu Jan 24 11:13:16 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 24 Jan 2008 08:13:16 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <5vr1ekF1njt09U2@mid.uni-berlin.de> Message-ID: <0b93cf6e-0f55-4421-afde-9246093a5d65@v17g2000hsa.googlegroups.com> On Jan 24, 1:44?am, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote: > > My second question is: is there any one who has tested very long mbcs > > decode? I tried to decode a long(20+MB) xml yesterday, which turns out > > to be very strange and cause SAX fail to parse the decoded string. > > That's because SAX wants bytes, not a decoded string. ?Don't decode it > yourself. > encode() converts a unicode string to a regular string. decode() converts a regular string to a unicode string. So I think what Marc is saying is that SAX needs a regular string(i.e. bytes) not a decoded string(i.e. a unicode string). From peng.kyo at gmail.com Wed Jan 16 02:18:52 2008 From: peng.kyo at gmail.com (J. Peng) Date: Wed, 16 Jan 2008 15:18:52 +0800 Subject: no pass-values calling? In-Reply-To: <13orb15pqgk4h96@corp.supernews.com> References: <13or6esikdrqa33@corp.supernews.com> <13orb15pqgk4h96@corp.supernews.com> Message-ID: <18c1e5f20801152318o3f5fda3dqabca86b351053637@mail.gmail.com> On Jan 16, 2008 3:03 PM, Dennis Lee Bieber wrote: > On Wed, 16 Jan 2008 13:59:03 +0800, "J. Peng" > declaimed the following in comp.lang.python: > > > > How to modify the array passed to the function? I tried something like this: > > > > >>> a > > [1, 2, 3] > > >>> def mytest(x): > > ... x=[4,5,6] > > x is unqualified (in my terms), so you have just disconnected it > from the original argument and connected it to [4,5,6] > Ok, thanks. But there is a following question,when we say, >>> x=[1,2,3] we create a list.then we say, >>> x=[4,5,6] we create a new list and assign it to x for future use. How to destroy the before list [1,2,3]? does python destroy it automatically? From Luke.Visinoni at gmail.com Tue Jan 15 14:11:17 2008 From: Luke.Visinoni at gmail.com (Luke) Date: Tue, 15 Jan 2008 11:11:17 -0800 (PST) Subject: Data mapper - need to map an dictionary of values to a model References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com> <05398cdb-4c75-499b-bb52-d5de627a0906@j20g2000hsi.googlegroups.com> Message-ID: <49753620-df70-4f1a-95bc-7b23667d9edc@s13g2000prd.googlegroups.com> On Jan 15, 1:53 am, bearophileH... at lycos.com wrote: > Luke: > > >What design patterns would you use here?< > > What about "generator (scanner) with parameters"? :-) > > Bye, > bearophile I'm not familiar with this pattern. I will search around, but if you have any links or you would like to elaborate, that would be wonderful. :) From cp02sdh02 at sneakemail.com Mon Jan 7 17:13:41 2008 From: cp02sdh02 at sneakemail.com (C Martin) Date: 7 Jan 2008 22:13:41 -0000 Subject: Tkinter variable trace problem Message-ID: <17687-68562@sneakemail.com> What am I doing wrong in this code? The callback doesn't work from the Entry widget. ##start code import Tkinter tk = Tkinter.Tk() var = Tkinter.StringVar() print var._name def cb(name, index, mode): print "callback called with name=%r, index=%r, mode=%r" % (name, index, mode) varValue = tk.getvar(name) print " and variable value = %r" % varValue var.trace('w', cb) var.set('test') entry = Tkinter.Entry(tk, textvariable=var) entry.pack() tk.mainloop() ##end code It produces the following output. The first three lines appear right away, and the exception occurs when you type in the entry widget: >test.py PY_VAR0 callback called with name='PY_VAR0', index='', mode='w' and variable value = 'test' callback called with name='PY_VAR0', index='', mode='w' Exception in Tkinter callback Traceback (most recent call last): File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) File "D:\APCC\Projects\Utilities\VisualData\test.py", line 9, in cb varValue = tk.getvar(name) File "C:\Python25\lib\lib-tk\Tkinter.py", line 421, in getvar return self.tk.getvar(name) TclError: can't read "PY_VAR0": no such variable > -------------------------------------- Protect yourself from spam, use http://sneakemail.com From simon at simonwillison.net Thu Jan 3 08:31:46 2008 From: simon at simonwillison.net (Simon Willison) Date: Thu, 3 Jan 2008 05:31:46 -0800 (PST) Subject: Treating a unicode string as latin-1 Message-ID: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Hello, I'm using ElementTree to parse an XML file which includes some data encoded as cp1252, for example: Bob\x92s Breakfast If this was a regular bytestring, I would convert it to utf8 using the following: >>> print 'Bob\x92s Breakfast'.decode('cp1252').encode('utf8') Bob's Breakfast But ElementTree gives me back a unicode string, so I get the following error: >>> print u'Bob\x92s Breakfast'.decode('cp1252').encode('utf8') Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/encodings/cp1252.py", line 15, in decode return codecs.charmap_decode(input,errors,decoding_table) UnicodeEncodeError: 'ascii' codec can't encode character u'\x92' in position 3: ordinal not in range(128) How can I tell Python "I know this says it's a unicode string, but I need you to treat it like a bytestring"? Thanks, Simon Willison From sturlamolden at yahoo.no Thu Jan 17 12:21:16 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 17 Jan 2008 09:21:16 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <1966c5b2-09fc-4523-b957-54815d0bd10f@m34g2000hsb.googlegroups.com> On 17 Jan, 14:38, Sacred Heart wrote: > Okey, so if my array1 is has 4 elements, and array2 has 6, it won't > loop trough the last 2 in array2? How do I make it do that? In that case your problem is the data. You'll either have to truncate one array and/or pad the other. Or is this what you want? n = len(array1) if len(array1) < len(array2) else len(array2) for number,letter in zip(array1[:n],array2[:n]): print "%s %s" % (number,letter) reminder = array1[n:] if len(array1) > len(array2) else array2[n:] for x in reminder: print x From sbrown at skyesystems.com Thu Jan 31 12:37:52 2008 From: sbrown at skyesystems.com (Stephen Brown) Date: Thu, 31 Jan 2008 19:37:52 +0200 Subject: pyExcelerator - Can I read and modify an existing Excel-WorkBook? Message-ID: <47A20770.7010900@skyesystems.com> Yes indeed, pyExcelerator does support reading data from excel spreadsheets. An example of how to do this is included in the file xls2csv-gerry.py under the directory ... pyExcelerator/examples/tools Syntax is pretty straight forward. extract_all = parse_xls(filename, CP = None) where CP is the encoding format used within tht file. Uses same codes that xlrd uses, ie 'cp437' = US English. All you need is the "parse_xls" command and simply let it iterate through your spreadsheet file. EXAMPLE: fname = "D:\\Directory\\myfile.xls" # an example filename for sheet_name, values in parse_xls(fname ): # parse_xls(arg) -- default encoding print " name of sheet is = ", sheet_name, Alternatively you can extract everything in one go... extract_all = parse_xls(fname) From gagsl-py2 at yahoo.com.ar Tue Jan 22 20:14:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 Jan 2008 23:14:14 -0200 Subject: Using utidylib, empty string returned in some cases References: <69c38011-4af7-4305-95fb-c824019c1550@v4g2000hsf.googlegroups.com> Message-ID: En Tue, 22 Jan 2008 15:35:16 -0200, Boris escribi?: > I'm using debian linux, Python 2.4.4, and utidylib (http:// > utidylib.berlios.de/). I wrote simple functions to get a web page, > convert it from windows-1251 to utf8 and then I'd like to clean html > with it. Why the intermediate conversion? I don't know utidylib, but can't you feed it with the original page, in the original encoding? If the page itself contains a "meta http-equiv" tag stating its content-type and charset, it won't be valid anymore if you reencode the page. -- Gabriel Genellina From http Mon Jan 28 02:21:58 2008 From: http (Paul Rubin) Date: 27 Jan 2008 23:21:58 -0800 Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <7xbq76pva9.fsf@ruckus.brouhaha.com> <7x1w82xymd.fsf@ruckus.brouhaha.com> Message-ID: <7xsl0iwh2h.fsf@ruckus.brouhaha.com> Paddy writes: > > Fair enough. My main issue was against the notion that random testing > > is the only thing necessary. > > Sorry Paul if I may have given that impression, its just that when you > bring in random testing to a design that until then had only directed > tests you can see the bug rate jump up! Sure, I agree with that as well, what I should have said was I have an issue with the notion that testing (of any sort) is all that is needed to reach high assurance. Directed and random tests BOTH failed to catch the FDIV bug. You need methods that demonstrate the absence of defects, not just fail to demonstrate their presence. From arnodel at googlemail.com Mon Jan 28 17:44:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 28 Jan 2008 14:44:27 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> Message-ID: On Jan 28, 10:27 pm, Tim Chase wrote: > > I've modified my little decorator (see Test1, Test2, Test3 for > > usage). I'll post it later on the cookbook if there seems to be no > > bugs and noone raises valid point against it:) > > One other area that was mentioned obliquely: preservation of > docstrings (and other function attributes) I think @wraps(...) does this (definitely copies __doc__). -- Arnaud From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 05:49:16 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 11:49:16 +0100 Subject: python recursive function In-Reply-To: References: <47872e94$0$29356$426a74cc@news.free.fr> Message-ID: <478749a0$0$22238$426a34cc@news.free.fr> Duncan Booth a ?crit : > Bruno Desthuilliers > wrote: > >> You want: >> return bears(n - 42) > > Actually, no he doesn't. He needs to explore all options when the first > attempt fails. Possibly - I didn't bother checking the algorithm correctness, just pointed out an obvious newbie programming error. > But I'm not going to write his homework for him. Nor do I. From gherzig at fmed.uba.ar Mon Jan 7 08:48:20 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Mon, 07 Jan 2008 10:48:20 -0300 Subject: dealing with binary files Message-ID: <47822DA4.9020401@fmed.uba.ar> Hi all. Im trying to read a binary data from an postgres WAL archive. If i make a xfile = open('filename', 'rb').xreadlines() line = xfile.next() i see this sort of thing: ']\xd0\x03\x00\x01\x00\x00\x00\r\x00\x00\x00\x00\x00\x00JM//DI+,D\x00\x00\x00\x01$\x00\x00\x00\x7f\x06\x00\x00y\r\t\x00\x02\x0f\t\x00\x00\x00\x10\x00)\x00\x01\x00\x12\x08 \x00^\xc2\x0c\x00\x08\x00\x00\x003001({\xe8\x10\r\x00\x00\x00\xe4\xff\xffI\x10?l\x01@\x00\x00\x00$\x00\x00\x00\x00\n' This file suppose to have some information about database activity, but at this point i cant do more than this, because i cant figure out what to do in order to have some 'readable' text. Im guessing is some C code, im reading the struct module to see if it helps, but im not into C programming, and im lost at the start of my problem. Can someone point me out some advice? Thanks! Gerardo From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 17 11:57:24 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 17 Jan 2008 17:57:24 +0100 Subject: Perl Template Toolkit: Now in spicy new Python flavor In-Reply-To: References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> <13a75830-5416-4fe3-9460-018e1240e6e6@e32g2000prn.googlegroups.com> Message-ID: <478f88c3$0$23530$426a74cc@news.free.fr> eefacm at gmail.com a ?crit : > On Jan 15, 1:45 pm, George Sakkis wrote: >>> eef... at gmail.com wrote: >>>> I'd like to inform the Python community that the powerful and popular >>>> Template Toolkit system, previously available only in its original >>>> Perl implementation, is now also available in a beta Python >>>> implementation: >>>> http://tt2.org/python/index.html >>>> I created this port both as a fun programming project, and for use in >>>> environments where Perl is not available, for reasons technical, >>>> cultural, or otherwise. The extensive Perl test suites have also been >>>> ported, and most templates require no or very little modification. > >> How does it compare with other "mainstream" Python template engines >> such as Cheetah, Mako, etc. ? > > I can't claim a comprehensive familiarity with Python template > offerings, but all of the packages approved for use at my previous > workplace left me cold. The most popular were ClearSilver and Django, > and both felt horribly limiting compared to the Template Toolkit, ClearSilver is not a Python templating system, but a C templating system with bindings for various languages including Python. Being (by design) language-agnostic, it's indeed *very* limited (and that's an understatement). wrt/ Django templates, it indeed imposes severe limitations on what can be simply expressed when you are familiar with Python. This is by design - since it has been designed to be safe to use for non-programmers. Now while not my cup of tea, it has proven to be fairly usable, quite less limiting that what I feared at first, and really easy to use for our web designer/integrator. Now there are way more flexible/expressive templating systems in Python, either XML oriented (genshi) or more generic (my favorite one so far being Mako). But anyway, I'm not the one that will complain with Perl templating systems being ported to Python - FWIW, Mako was born from it's author previous experience with porting Mason to Python !-) From lists at cheimes.de Fri Jan 25 07:07:45 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 25 Jan 2008 13:07:45 +0100 Subject: Minimum Requirements for Python In-Reply-To: References: Message-ID: justinrob at gmail.com wrote: > Can someone tell me the minimum requitements for Python as I can't > find it anwhere on the site. I have 3 PC's which are only 256mb RAM, > wanted to know if this was sufficenent. Python runs even on mobile phones with far less memory. However the memory consumption depends on the application. Christian From nick.fabry at coredump.us Tue Jan 29 23:50:18 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Tue, 29 Jan 2008 23:50:18 -0500 Subject: ISO with timezone In-Reply-To: References: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Message-ID: On Jan 29, 2008, at 13:56, nik wrote: > Thanks, > that does help and now I have: > >>>> from datetime import datetime, tzinfo, timedelta >>>> import time >>>> class TZ(tzinfo): > ... def utcoffset(self,dt): return timedelta(seconds=time.timezone) > ... >>>> print datetime(2008,2,29,15,30,11,tzinfo=TZ()).isoformat() > 2008-02-29T15:30:11+8:00 > > > But what I want to know now it how to get the actual time into the > expression instead of typing the 2008,2,29,15.... > So something like: >>> print > datetime(time.gmtime(),tzinfo=TZ()).isoformat(), but that doesn't > work. > > I realize that I could do: >>>> t = time.gmtime() >>>> print >>>> datetime(t[0],t[1],t[2],t[3],t[4],t[5],tzinfo=TZ()).isoformat() > > but I imagine there might be a cleaner way of doing this. > > Thanks, > Nik > No need for the ugliness! The constructor for class datetime has a method, .now() that returns the current date and time, as a naive datetime object (i.e. no tzinfo attached). Since you want an aware datetime object (one with a tzinfo object attached), you can do it simply by feeding .now the tzinfo object you want attached, as below: >>> print datetime.now(TZ()).isoformat('T') 2008-01-29T23:43:16.809049-05:00 See PSL, Sect. 5.1.4 Dates and Times are a bit ugly in Python. Don't be discouraged, but you do need to understand them quite well to get bug-free code that plays with them. Nick Fabry > > On Jan 28, 9:10 pm, "Nicholas F. Fabry" > wrote: >> Hello, nik. >> >> On Jan 28, 2008, at 21:03, nik wrote: >> >> >> >>> Hi, >> >>> How does one express the time in ISO format with the timezone >>> designator? >> >>> what I want is YYYY-MM-DDThh:mm:ss.sTZD >> >>>> From the documentation I see: >>>>>> from datetime import tzinfo, timedelta, datetime >>>>>> class TZ(tzinfo): >>> ... def utcoffset(self, dt): return timedelta(minutes=-399) >>> ... >>>>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') >>> '2002-12-25 00:00:00-06:39' >> >>> and I've also figured out: >>>>>> datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3] >>> '2008-01-23T11:22:54.130' >> >>> But can't figure out how to fit them together. >> >> There is nothing there to 'fit together' - in the first example >> given, >> the datetime object has no time component specified, so it fills in >> default vaules of zero. The following should make this clear: >> >>>>> your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ()) >>>>> print your_time >> 2008-02-29 15:30:11-05:00 >>>>> print your_time.isoformat('T') >> 2008-02-29T15:30:11-05:00 >> >> If you wish to append the NAME of the tzinfo object instead of its >> offset, that requires a bit more playing around (along with a >> properly >> defined tzinfo object - check out dateutil or pytz for a concrete >> implementation of tzinfo subclasses (i.e. timezones)), but the >> following would work: >> >>>>> print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z') >> 2008-02-29T15:30:11 EST >> >> For details on how the .strftime method works, see Python Standard >> Library, Section 14.2. >> >> I hope this helps! >> >> Nick Fabry >> >>> Thank you, >>> Nik >>> -- >>> http://mail.python.org/mailman/listinfo/python-list > >> > -- > http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Sun Jan 20 18:09:17 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jan 2008 15:09:17 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> Message-ID: On Jan 21, 8:58 am, pythonewbie wrote: > I just would like to know if I would ALWAYS find the install directory > in sys.path[6] and site-packages directory in sys.path[7] on any Win32 > platform and sys.path[2] and site-packages directory in sys.path[6] on > any Linux platform. > > If the reply is : "YES you can be sure of it !" No, you can't be sure of any such thing. In general in computing assuming a fixed position in a variable-length list is a nonsense. Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> from pprint import pprint as pp >>> pp([(x, p) for x, p in enumerate(sys.path)]) [(0, ''), (1, 'c:\\python25\\lib\\site-packages\\setuptools-0.6c3-py2.5.egg'), (2, 'C:\\WINDOWS\\system32\\python25.zip'), (3, 'c:\\python25\\DLLs'), (4, 'c:\\python25\\lib'), (5, 'c:\\python25\\lib\\plat-win'), (6, 'c:\\python25\\lib\\lib-tk'), (7, 'c:\\python25'), (8, 'c:\\python25\\lib\\site-packages'), (9, 'c:\\python25\\lib\\site-packages\\win32'), (10, 'c:\\python25\\lib\\site-packages\\win32\\lib'), (11, 'c:\\python25\\lib\\site-packages\\Pythonwin')] >>> Something like this might be more reliable: >>> import sys, re >>> for p in sys.path: ... m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p) ... if m: ... print m.group(1, 0) ... break ... else: ... raise Exception('Huh?') ... ('c:\\python25', 'c:\\python25\\lib\\site-packages') >>> > > All would be great for me and I would be ready to create a script to > detect with a reliable manner the installation dir. et site-packages > dir. for all my Linux/Win32 Python apps. You mentioned Python versions back to 2.1 earlier. However you evidently haven't bothered to start up Python 2.1 and look at sys.path: C:\junk>\python21\python Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import sys; sys.path ['', 'C:\\junk', 'C:\\python21\\DLLs', 'C:\\python21\\lib', 'C:\ \python21\\lib\\ plat-win', 'C:\\python21\\lib\\lib-tk', 'C:\\python21'] >>> Before you rush out and re-invent the wheel, have a look at this: http://www.python.org/community/sigs/current/distutils-sig/ You may like to re-ask your questions on the distutils mailing list. HTH, John From ivlenin at gmail.com Sun Jan 27 01:08:47 2008 From: ivlenin at gmail.com (I V) Date: Sun, 27 Jan 2008 06:08:47 GMT Subject: how to make format operator % work with unicode as expected References: <13po55nc0q0s06@corp.supernews.com> Message-ID: On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: > Yes, it is true that %s already support unicode, and I did not > contradict that. But it counts the number of bytes instead of > characters, and makes things like %-20s out of alignment. If you don't > understand my assertion, please don't argue back and I am only > interested in answers from those who are qualified. What version of python are you using? On python 2.4 and 2.5 on linux, %-20s counts the characters, not the bytes, or, I think it does. when I run: >>> print u'%-20s|\n%-20s|' % (u'foo bar', u'foo b?r') the output is: foo bar | foo b?r | From timr at probo.com Sat Jan 12 00:49:19 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 12 Jan 2008 05:49:19 GMT Subject: FindWindowById returns None..... ? References: Message-ID: Soren wrote: > >I'm trying to split my GUI into several files since its beginning to >become a bit large.. I've placed a panel class inside gui2.py, but it >needs some information from a panel in gui1.py... if I import gui1 in >gui2 and try to find the panel by its ID, (using the Id generated in >gui1) I get a None value returned?? using findwindowbyid in gui1 on >the same ID works fine.. > >I'm guessing i'm doing this the wrong way, can anyone comment on this? Post enough code so we can see how you are doing it. Your description isn't specific enough; there are several ways to do it, some right, some wrong... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From namesagame-usenet at yahoo.com Thu Jan 10 18:22:59 2008 From: namesagame-usenet at yahoo.com (gamename) Date: Thu, 10 Jan 2008 15:22:59 -0800 (PST) Subject: Win32+Cygwin+ActiveState Python+SCons Message-ID: <84d7b056-f46b-4f31-845d-2e27f676ce07@t1g2000pra.googlegroups.com> Hi, I just installed scons on win32 that has cygwin but uses ActiveState python. If I do "import SCons", the lib isn't found. The win32 installer seemed very complete, but the scons lib doesn't seem to be in any dir python knows about. Is there another install step I need to do? TIA, -T From bazwal at googlemail.com Mon Jan 7 16:18:19 2008 From: bazwal at googlemail.com (Baz Walter) Date: Mon, 7 Jan 2008 21:18:19 +0000 (UTC) Subject: Does Python cache the startup module? References: <3c346bb2-c84a-4268-9e7b-b0c601fe9710@s12g2000prg.googlegroups.com> Message-ID: John Machin lexicon.net> writes: > If you execute that stuff inside a function (see below) instead of in > global scope, do you get the same effect? Thanks for your reply. No, running it inside a function means I can't rely on python to garbage collect, so there will be widgets left over whether I've changed names or not. See Frederik Lundh's last message to see what's really happening. From toby at tobiah.org Thu Jan 17 14:43:08 2008 From: toby at tobiah.org (Tobiah) Date: Thu, 17 Jan 2008 11:43:08 -0800 Subject: import from question In-Reply-To: References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> <478d04d4$0$26042$88260bb3@free.teranews.com> <87tzleb2st.fsf@benfinney.id.au> <478E658A.9070003@tobiah.org> <87prw1bftx.fsf@benfinney.id.au> <478e87f6$0$26054$88260bb3@free.teranews.com> Message-ID: <478fa3d1$0$26058$88260bb3@free.teranews.com> >> Ok, I get it. I was locally importing a pointer to an integer > > Really? What language were you using? Python doesn't have pointers. What term do you prefer? Reference? Object id holder? -- Posted via a free Usenet account from http://www.teranews.com From Lie.1296 at gmail.com Sat Jan 5 13:12:19 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 5 Jan 2008 10:12:19 -0800 (PST) Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> Message-ID: <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> On Jan 5, 5:40?pm, MartinRineh... at gmail.com wrote: > Jeroen Ruigrok van der Werven wrote: > > > Shouldn't this be: > > > self.startLoc = start > > self.stopLoc = stop > > Thanks! Of course it should. Old Java habits die slowly. No, seriously it isn't Java habits only, most other languages wouldn't need explicit calling of class name. From rdrink at gmail.com Sat Jan 26 22:02:38 2008 From: rdrink at gmail.com (Robb Lane (SL name)) Date: Sat, 26 Jan 2008 19:02:38 -0800 (PST) Subject: file write question Message-ID: <62b96f11-1a81-4be8-9dcb-348ee38ebe16@f10g2000hsf.googlegroups.com> I have written a script which: - opens a file - does what it needs to do, periodically writing to the file... for a few hours - then closes the file when it's done So my question is: Would it be better to 'open' and 'close' my file on each write cycle? e.g. def writeStuff(content): myFile = open('aFile.txt', 'a+') myFile.write(content) myFile.close() ... or just leave it till it's done? I don't need to use the file contents until the script is done (although it would be nice... just to check it while it's working), so just curious what people think is the better method. - rd From thunder54007 at gmail.com Wed Jan 23 04:46:30 2008 From: thunder54007 at gmail.com (thunder54007 at gmail.com) Date: Wed, 23 Jan 2008 01:46:30 -0800 (PST) Subject: what's wrong with the wmi.Terminate() method? Message-ID: hi, here is my script: import win32con import time import wmi c = wmi.WMI() for process in c.Win32_Process(name = "notepad.exe"): print process.ProcessId, process.Name process.Terminate () when I have only one notepad.exe process in my system, this works fine, but when I have more than one notepad.exe , after terminal the first notepad.exe, the Terminate() for the second notepad.exe process will generate the following error: 3156 notepad.exe 6100 notepad.exe Traceback (most recent call last): File "F:\thunder\python\program\wmi \create_terminal_notepad.py", line 16, in module> process.Terminate () File "C:\Python25\Lib\site-packages\wmi.py", line 376, in __call__ handle_com_error (error_info) File "C:\Python25\Lib\site-packages\wmi.py", line 188, in handle_com_error raise x_wmi, "\n".join (exception_string) wmi.x_wmi: -0x7ffdfff7 - ????(ps: exception happened)? Error in: SWbemObjectEx -0x7ffbeffe - ???(ps:Can not found) I don't know why this happend, is there somebody could give me a hand? From josepharmbruster at gmail.com Tue Jan 8 13:47:42 2008 From: josepharmbruster at gmail.com (josepharmbruster at gmail.com) Date: Tue, 8 Jan 2008 10:47:42 -0800 (PST) Subject: Python or PowerShell ? Message-ID: I am all about using the right tool for the right purposes, which is why I have started reading the GettingStarted guide to PowerShell. I am curious if any other pythoneers have ventured into the world of PowerShell. Mostly, I am interested in grabbing perspectives on the differences noticed from those that have working experience with using both. I dug up one article from Google that talked about comparison but that was about it. http://www.simple-talk.com/sql/database-administration/comparing-python-and-powershell-dba-scripting-/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 21 04:45:41 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 10:45:41 +0100 Subject: Default attribute values pattern In-Reply-To: References: Message-ID: <4794697f$0$16980$426a74cc@news.free.fr> David Tweet a ?crit : (please, don't top-post) > > def Grab(argdict, key, default): cf pep08 for naming conventions... > """Like argdict.get(key, default), but also deletes key from argdict.""" > if key in argdict: > retval = argdict["key"] > del(argdict[key]) > else: > retval = default > return retval def grab(kw, key, default=None): try: return kw.pop(key) except KeyError: return default (snip) From hetileva69812 at hotmail.com Wed Jan 16 13:41:33 2008 From: hetileva69812 at hotmail.com (hetileva69812) Date: Wed, 16 Jan 2008 13:41:33 -0500 Subject: Current Special Vicoden Message-ID: Living in Pain. We can help Pain Meds Online discoveyamazing.com From shansen at advpubtech.com Fri Jan 4 11:54:45 2008 From: shansen at advpubtech.com (Stephen Hansen) Date: Fri, 4 Jan 2008 08:54:45 -0800 Subject: dictionary/hash and '1' versus 1 In-Reply-To: References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> Message-ID: <7a9c25c20801040854t73054af4pac8ce07b31d85c8f@mail.gmail.com> > > > A single integer is distinctly different from a sequence of characters > in > > some encoding that may just happen to contain representations of a > > number.... so they'll hash differently :) > > Depends on the context. The machine encoding may be different, but > in human terms they "should" be the same. Perl managed to achieve an > impressive blend of presenting data as human friendly or as machine bits > when it made sense to do so. So much so, that Perl is probably the only > language I've used that will do what you mean instead of what you say. > Nice, but frightening in some ways. Frightening is the word I'd use-- nice is not ;-) For me, the thought that "assert (1 == '1') is True" should pass is alien and alarming to the point of rising to, "That's obviously wrong." Of course, I know other languages do things their own way .. so to each their own :) Python's philosophy of "explicit is better then implicit" is one that I appreciate and have found to be a saving grace in maintaining huge systems over the last few years. I could so see myself learning perl and sending the exact inverse message to a perl mailing list; I actually /have/ code which relies upon the exact case of numbers and strings never being implicitly converted to compare to each-other. :) Different starting point in mindset, is all. Type casting is easy, IFF you remember to do so. The problem was > that I missed the fact that one (important) function was returning a string > instead of an int, and since Python supports heterogenous data structures, > the human has to remember to keep the key's data type homongenous. > This is true; there does need to be a more aware/complete understanding of the input/output API of the code you're using. That and Perl does so much automatic type conversion in such a > sensible way, that I stopped worrying about mixing data types, which is > making the Python transition a tad more error prone. Because of Perl, I > almost consider automatic type casting to be the next "you don't have to > manage your own memory" that people loved about Java. =O Heathen. ;-) I prescribe meditation, green leaf tea, and continual chanting of the sacred scroll provided by "import this" until this unwholesome adoration of black magic practices has been cleansed from your mind. In all seriousness, I can see the appeal; but prefer the strongly typed world. Partly because of where I use it, when we do a LOT of CORBA communication (which is massively strongly typed in and of itself), protocols and careful data management/conversion. Partly habit. I don't ever worry about mixing data types; I'm just aware of what type things are (although often in vague trusting ways such as 'I am sure you are a file; please do not disappoint me'). In the end I highly doubt requiring explicit conversions has a notable negative on productivity or makes the code/logic much bigger or more complicated... whereas not having to manage one's own memory is a fairly huge savings :) > A similar method lets you make 'case-insensitive' dicts, for example. > > > > Were such a thing to happen automagically, you could get some > > weird situations, such as "assert (key in dict) == (key in dict.keys())" > > failing. > > I'm assuming that you would just need to overload the 'in' operator > and .keys() method to be case insensitive also. > For my case-insensitive dict I didn't need to modify keys at all. I wasn't interested in it being "case-preserving"; all keys were lower cased on insert(via .update, __setitem__, or .setdefault), and the 'check' value when testing or fetching was lowercased for comparison (via __contains__, __getitem__, and .get) For example, a less functional version: class caseinsensitivedict(dict): def __contains__(self, key): return dict.__contains__(self, key.lower()) def __getitem__(self, key): return dict.__getitem__(self, key.lower()) def __setitem__(self, key, value): return dict.__setitem__(self, key.lower(), value) >>> cid = caseinsensitivedict() >>> cid['This'] = 5 >>> cid {'this': 5} >>> cid.keys() ['this'] >>> print 'THIS' in cid: True I could do a case-preserving one, but it wasn't needed for the solution. --Stephen -------------- next part -------------- An HTML attachment was scrubbed... URL: From loupgaroublond at gmail.com Fri Jan 4 21:19:05 2008 From: loupgaroublond at gmail.com (Yaakov Nemoy) Date: Fri, 4 Jan 2008 21:19:05 -0500 Subject: Memory Leaks and Heapy In-Reply-To: <477E6525.3010805@egenix.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> <477E5A73.9070400@egenix.com> <7f692fec0801040823q14d16429y370ffceaf046a6f3@mail.gmail.com> <477E6525.3010805@egenix.com> Message-ID: <7f692fec0801041819r675e2137i293084baeae4954f@mail.gmail.com> On Jan 4, 2008 11:56 AM, M.-A. Lemburg wrote: > > The most common answer I heard was possible fragmentation, meaning > > there are no or few completely empty blocks to be found. If there are > > no 'leaks' in the VM, then it's probably related to how memory is > > freed. > > You can check for this by using a special build of Python > with disabled PyMalloc - Python will then use the standard > OS malloc for all object allocations. It still uses free lists > for a couple of object types, but those won't cause major > leak problems. How do I go about setting this up? > Alternatively, try to tune the PyMalloc implementation (see > objmalloc.c), e.g. enable WITH_MEMORY_LIMITS. > > >> This could be caused by interned strings which are kept in a special > >> pool dictionary to speed up string comparisons. > > > > That's quite possible, a majority of the code is a huge number of SQL > > connections and code. All string based. > > Note that strings are normally *not* interned. However, you can > write code in a way that causes Python to intern more strings > than needed, e.g. if you dynamically compile code in your app, > which then causes all identifiers in the compiled code to be > interned. > > The interned dictionary is not exposed in Python, but you can > access it using a debugger via Objects/stringobject.c:interned. That's going a bit more low level detail than I think I can handle. I'm not much for C programming, and i'll have a hard time sifting through the noise to find the signal. > >> However, the first thing to check is whether any of the C extension > >> modules you are using is leaking memory. Python itself is usually > >> well tested for memory leaks, but this is less so for C extension > >> modules and it's easy to mis a few Py_DECREFs (decrementing a > >> Python object's reference count), causing objects to live forever. > > > > I'll try to track it down, but AFAIK, most of the code is python, and > > the only C code there would be is the MySQL container. How can I > > debug the VM though, to determine where the leak lies? Heapy wasn't > > able to tell me this, and this is the important aspect. I'm wondering > > how most people go about determining the causes of leaks like these, > > so I can provide some accurate bug information. > > Building Python in debug mode provides some help with this. > You can then detect whether objects get properly freed. Again, what's the best way to go about doing this? > Doing explicit garbage collection via the gc module also > helps in narrowing down the leak. Adding an explicit gc.collect() statement at the end of the offending function didn't do much to solve matters much. It slowed the rate that garbage piled up, but it's not a solution. Thanks for all the help. From mwilson at the-wire.com Wed Jan 16 10:52:08 2008 From: mwilson at the-wire.com (Mel) Date: Wed, 16 Jan 2008 10:52:08 -0500 Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> Message-ID: J. Peng wrote: > Sounds strange. > In perl we can modify the variable's value like this way: > > $ perl -le ' >> $x=123; >> sub test { >> $x=456; >> } >> test; >> print $x ' > 456 Not all that strange. The Python equivalent is x=123 sub test() global x x=456 test() print x Python assignment works by binding an object with a name in a namespace. I suspect that perl does something similar, and the differences are in the rules about which namespace to use. Mel. From nicola.jean at gmail.com Thu Jan 31 06:03:20 2008 From: nicola.jean at gmail.com (Nicola Jean) Date: Thu, 31 Jan 2008 12:03:20 +0100 Subject: dl module Message-ID: <11ed47ab0801310303w44b173a1sacfb317bb2737b3@mail.gmail.com> Hi everyone, I'm having a problem compiling Python2.4.4 on a 64 bits machine. It looks like I cannot compile the dl module. When I run test_dl.py I get the following error message: SystemError: module dl requires sizeof(int) == sizeof(long) == sizeof(char*) Do I need to put any special flag when I run the configure script? Cheers N.Jean From paul at boddie.org.uk Mon Jan 28 05:28:55 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 28 Jan 2008 02:28:55 -0800 (PST) Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: <200aa7ec-de64-41ac-8453-6e97fa867a51@q21g2000hsa.googlegroups.com> On 28 Jan, 02:05, ajaksu wrote: > > Hmmm. Seems to me that "Is X Standardized" in the given context means > having a formal, published standard issued by some Standards > organization. While you can discuss the meaning of some so-called > standards (like W3C's 'recommendations', RFCs, etc.), Python, IMHO, > doesn't fit the label. There is no "Standard" to reference that is > implementation, documentation and core-dev's opinion independent to a > reasonable degree. > > I guess MilesAgain gives the best arguments regarding this issue. Agreed. The supposed definition of Python is decided by the developers of CPython, which is why every other implementation has to chase behind that group making changes as the language definition shifts. You could argue that Java is in a similar situation: a controlling body with their own implementations, albeit with a process for suggesting changes and arguably more complete documentation. Looking at the table of languages, we see that Java is indeed categorised as not having a standard. Of course, one could contend that languages like C# aren't really standardised either, since everyone knows that ECMA standardisation is just a convenient rubber-stamping process, as we have seen with the adoption of "Office Open XML" (OOXML) as a standard by ECMA, whilst the ISO standardisation attempt for OOXML was sunk (despite Microsoft ballot-stuffing) due to glaring flaws in that so-called standard. As I probably pointed out before, people have advocated a standard for Python, such as a presenter at EuroPython 2006 who had been alarmed that features such as lambda which his team used extensively were at one point scheduled for removal from the language. Unfortunately, there hasn't been significant scope for differentiation between implementations of Python, so one could argue that demand for a standard hasn't yet reached a critical level, but I imagine that some kind of independent documentation of what Python (or a subset of Python) is may eventually emerge in some form or other. Paul From steveo at syslang.net Wed Jan 9 13:47:30 2008 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 9 Jan 2008 13:47:30 -0500 (EST) Subject: Another dumb scope question for a closure. Message-ID: So sorry because I know I'm doing something wrong. 574 > cat c2.py #! /usr/local/bin/python2.4 def inc(jj): def dummy(): jj = jj + 1 return jj return dummy h = inc(33) print 'h() = ', h() 575 > c2.py h() = Traceback (most recent call last): File "./c2.py", line 10, in ? print 'h() = ', h() File "./c2.py", line 5, in dummy jj = jj + 1 UnboundLocalError: local variable 'jj' referenced before assignment I could have sworn I was allowed to do this. How do I fix it? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From fredrik at pythonware.com Sun Jan 13 15:18:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 13 Jan 2008 21:18:37 +0100 Subject: Manually installing PIL In-Reply-To: References: <001001c84dda$23d26760$2000a8c0@depid.local> Message-ID: j igisbert.etra-id wrote: > this. I have download Imaging-1.1.6 source code, and I found PIL folder, > but not binary file. If I download windows exe installer, it works > great, but I want to install manually for installing it on my PDA.... as the name implies, the source code distribution contains source code only. to turn that into a binary component, you need a working compiler for your target platform. what OS does your PDA run? From ajaksu at gmail.com Wed Jan 30 20:31:10 2008 From: ajaksu at gmail.com (ajaksu) Date: Wed, 30 Jan 2008 17:31:10 -0800 (PST) Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! References: Message-ID: <832c7add-b222-46d7-a151-45f02444d520@s19g2000prg.googlegroups.com> On Jan 30, 10:40 pm, "Blubaugh, David A." wrote: > I do not understand why no one has answered the following question: > > Has anybody worked with Gene Expression Programming???? > > David Blubaugh I see. You don't understand. That's a fact. I'm sure there are free online resources about the best way to understand why no one answered your question in particular, or why people don't answer some questions in a more comparative way. See? That's as far as this rude message will get you. Thanks for the laugh, though. (On a more useful note, try visiting http://groups.google.com/group/comp.lang.python/ and thinking real hard for a minute or fifty: why?) From bborcic at gmail.com Thu Jan 24 08:09:34 2008 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 24 Jan 2008 14:09:34 +0100 Subject: sudoku solver in Python ... In-Reply-To: <222A1E46-A1C1-4793-A91E-9E0785463278@gmail.com> References: <43b2a56b-c8eb-4851-a9f6-10aa7e32e3ce@i29g2000prf.googlegroups.com> <222A1E46-A1C1-4793-A91E-9E0785463278@gmail.com> Message-ID: Shawn Milochik wrote: > On Jan 23, 2008, at 10:02 PM, Derek Marshall wrote: > >> This is just for fun, in case someone would be interested and because >> I haven't had the pleasure of posting anything here in many years ... >> >> http://derek.marshall.googlepages.com/pythonsudokusolver >> >> Appreciate any feedback anyone who takes the time to have a look would >> want to give ... >> >> Yours with-too-much-time-to-kill-on-the-train'ly, >> Derek >> -- >> http://mail.python.org/mailman/listinfo/python-list > > For those interested in this topic, here's another (much shorter) one: > > http://norvig.com/sudoku.html > > I'm not making any judgements here, though. If anyone takes the time > to actually review them, I'd be interested in hearing any educated > comparisons. > > Shawn So would I. Below is the "winner" of my hacking for an as fast as possible 110% pure python (no imports at all!) comprehensive sudoku solver under 50 LOCs, back in 2006. Performance is comparable to the solver you advertize - numbers are slightly better, but platform differences could easily absorb that - eg (not counting module initialization and not using psyco) it takes 9.3 ms average on the "AI escargot" problem linked to in Norwig's page, 5.6 ms/problem on some standard "top1465" list of hard problems, and 3.4 ms/problem on the first 1000 on some other "top50000" list of relatively hard problems. This on my 2GHz Intel Centrino '05 laptop. Psyco reduces times by about 50%. Dropping performance requirements by half allows reducing LOC count in proportion. OTOH, the code although short is nearly unreadable, sorry; should probably feature/comment it on some web page, like the two already proposed in the thread. Will do if/for reviewer. Interface is calling sudoku99(problem) with 'problem' a standard 81 character string with '0' or '.' placeholder for unknowns. Returns same with values filled in. Beware that although in practice it solved all well-formed human-solvable problems I could find, it is not guaranteed to deal properly (or even terminate?) for underdetermined problems or determined problems that would require exploring choicepoints with more than 2 possibilities (if such exist). Cheers, Boris w2q = [[n/9,n/81*9+n%9+243,n%81+162,n%9*9+n/243*3+n/27%3+81] for n in range(729)] q2w = (z[1] for z in sorted((x,y) for y,s in enumerate(w2q) for x in s)) q2w = map(set,zip(*9*[q2w])) w2q2w = [set(w for q in qL for w in q2w[q] if w!=w0) for w0,qL in enumerate(w2q)] empty = set(range(729)).copy def sudoku99(problem) : givens = set(9*j+int(k)-1 for j,k in enumerate(problem) if '0' vmax : ixmax = ix if v >=thres : break vmax = v w0s.add(w0) else : continue break except : pass w0,w1 = q2w[ixmax]&free try : w0s.clear() w0s.add(w0) return search(w0s,q2nw[:],free.copy()) except ValueError : w0s.clear() w0s.add(w1) From socyl at 987jk.com.invalid Fri Jan 25 08:47:59 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 25 Jan 2008 13:47:59 +0000 (UTC) Subject: Text-based data inspector for Python? References: <6398ab68-da01-408e-902b-0b488310e9b0@e10g2000prf.googlegroups.com> Message-ID: In <6398ab68-da01-408e-902b-0b488310e9b0 at e10g2000prf.googlegroups.com> Paddy writes: >I tend to do the following at the python prompt: > from pprint import pprint as pp Thanks, that's a good one to know, but isn't there a way to automate it??? I looked around, but I couldn't find the name of any *rc-type file that would hold interpreter customizations. The closest I found was ~/.pythonrc.py, but that still requires doing "import user" at every interpreter session. (As annoyances go, this is certainly a minor one, but with me the psychological effects of such small annoyances gets magnified in proportion to how unnecessary they seem.) Plus, I'm not sure that it'd be such a great idea to execute code intended to customize the interpreter every time that the user module gets loaded... kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From carsten at uniqsys.com Thu Jan 3 22:11:26 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 03 Jan 2008 22:11:26 -0500 Subject: Cursors in a Loop In-Reply-To: References: <3da337d8-2de0-4fdb-8c38-2f6fcd8348ac@i72g2000hsd.googlegroups.com> Message-ID: <1199416286.3319.19.camel@localhost.localdomain> On Thu, 2008-01-03 at 17:25 -0800, t_rectenwald wrote: > On Jan 3, 7:47 pm, t_rectenwald wrote: > > I have a python script that uses the cx_Oracle module. I have a list > > of values that I iterate through via a for loop and then insert into > > the database. This works okay, but I'm not sure whether I can use one > > cursor for all inserts, and define it outside of the loop, or > > instantiate and close the cursor within the loop itself. For example, > > I have: > > > > for i in hostlist: > > cursor = connection.cursor() > > sql= "insert into as_siebel_hosts_temp values('%s')" % (i) > > cursor.execute(sql) > > cursor.close() > > > > And I've also tried: > > > > cursor = connection.cursor() > > for i in hostlist: > > sql= "insert into as_siebel_hosts_temp values('%s')" % (i) > > cursor.execute(sql) > > cursor.close() > > > > Both work fine, and execute in the same amount of time. I'm just > > trying to understand what is the "correct" approach to use. Actually, the correct approach would be "neither." You should NEVER use string formatting to fill values into an SQL query. (Doing so causes security vulnerabilities and performance problems. See, for example, http://informixdb.blogspot.com/2007/07/filling-in-blanks.html for detailed explanations.) Instead, you should use a parametrized query. With a parametrized query, your code becomes this: cursor = connection.cursor() for i in hostlist: cursor.execute("insert into as_siebel_hosts_temp values(?)", (i,) ) cursor.close() Since this will save the database engine from having to re-parse the query every time, it will run much faster if the list is long. Even better would be to use executemany: cursor = connection.cursor() cursor.executemany("insert into as_siebel_hosts_temp values(?)", [(i,) for i in hostlist] ) cursor.close() Depending on whether cx_Oracle allows this, the list comprehension in that example could be replaced by the generator expression ((i,) for i in hostlist), but I don't know if cx_Oracle allows executemany with an arbitrary iterable. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From bignose+hates-spam at benfinney.id.au Wed Jan 9 17:53:46 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 10 Jan 2008 09:53:46 +1100 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <87fxx6k3ut.fsf@benfinney.id.au> Christian Heimes writes: > dongie.agnir at gmail.com wrote: > > [...] after running the code with the included sample input file, > > it seems quite slow (1-2 seconds from start to finish to do the > > 800 by 600 gif image). > > Have you profiled your application? Do you know the bottle necks and > the reason for the bottle necks? Is your application IO, memory or > CPU bound? Have you considered rewriting the bottle necks in C? All good questions. Another important one: Is the startup time of the Python process (i.e. before executing any of the actual statements in the program) a significant part of the total time in this case? -- \ "In the long run, the utility of all non-Free software | `\ approaches zero. All non-Free software is a dead end." ?Mark | _o__) Pilgrim | Ben Finney From socyl at 987jk.com.invalid Fri Jan 25 10:42:47 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 25 Jan 2008 15:42:47 +0000 (UTC) Subject: Text-based data inspector for Python? References: <6398ab68-da01-408e-902b-0b488310e9b0@e10g2000prf.googlegroups.com> <98d4d552-20d6-42f4-9d50-2c9ca1b3a4d0@e25g2000prg.googlegroups.com> Message-ID: In <98d4d552-20d6-42f4-9d50-2c9ca1b3a4d0 at e25g2000prg.googlegroups.com> Paddy writes: >python -h gives me: > ... > Other environment variables: > PYTHONSTARTUP: file executed on interactive startup (no default) > ... Sweet. Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From fredrik at pythonware.com Fri Jan 4 15:12:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 21:12:58 +0100 Subject: MRO Error on Multiple Inheritance? In-Reply-To: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> References: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> Message-ID: Ming wrote: > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases A, B > > (I submitted the problem to the author but I'm not sure I'll ever hear > back.) I'm guessing that this kind of diamond inheritance is > prohibited by the interpreter, and that his lack of error messages > from the interpretation is due to actually leaving out the "class > B(A): pass" or, alternatively, leaving out the (object) in the first class definition: >>> class A: pass ... >>> class B(A): pass ... >>> class D(A, B): pass ... >>> From salgerman at gmail.com Tue Jan 15 13:01:02 2008 From: salgerman at gmail.com (gsal) Date: Tue, 15 Jan 2008 10:01:02 -0800 (PST) Subject: Open existing Word document, modify and save. Message-ID: <1ab91596-e868-4b28-9fe3-34f9129a114f@s8g2000prg.googlegroups.com> New to Python and new to Win32. Help please. O.k., so this might seem like one of those "can you do my homework" kind of postings, except that is not homework, it is officework. I have been reading the Core Python book and I am really excited about starting my next project with Python, instead of tcl/tk/Fortran/C. While I can see how to use it for scientific computing and have gone with the NumPy and SciPy tutorials, I am having a hard time with Win32. Attempted to read some of the documentation for Win32 and while the basic stuff talks about creating a document, I did not see how to open an existing document and modify certain parts of it...and then it seems that it got very complicated (for me) really quick. Sure, it seems powerful, but all I need is a small part of it, I think. Here is the thing. Here at the office, we have computer programs to generate spec data and the Applications people have MS-Word documents in a very specific format where they would like to put such spec data. Initially, I was using merge fields and VB macros, until they stopped working when newer (non-backwards-compatible) versions came along; then, I switched to generating *.xml out of the original *.doc file, breaking it appart, modifying it and gluing back together...this is very laborious task and I have to go through the whole exercise, should the application people modify the original *.doc So, basically, I am looking for a way to work directly with the original *.doc, assuming I know everything about it...which I do; in fact, I have it and can also modify it, should I need to bookmark it or otherwise modify as needed. How to go about it? What's the python code to open an existing document, modify it and save it back? how does the Word document needs to be bookmarked/formatted so that it can be modified? For example, after the computer program has been run and the new, say, "machine rating" calculated, I need to deposit such value in a very specific spot in the Word document. I presume somebody out there already does this and is willing to provide some code?. Thank you very much in advance. gsal From gagsl-py2 at yahoo.com.ar Tue Jan 1 19:13:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Jan 2008 22:13:01 -0200 Subject: Catching external program exceptions References: <25qdnZuc2dn0WOfanZ2dnUVZ_gWdnZ2d@wideopenwest.com> Message-ID: En Tue, 01 Jan 2008 20:57:44 -0200, Marty escribi?: > I need to catch exceptions thrown by programs started by the os.system > function, > as indicated by a non-zero return code (e.g. the mount utility). For Notice that these are two different things. You can wait until the external program ends, and get its return code; and you can sometimes read a message from its stderr. But none of these things by itself throws an exception in Python. > example, > if I get the following results in a bash shell: > > $mount test > mount: can't find /home/marty/test in /etc/fstab or /etc/mtab > > then I want to catch the same exception from the corresponding > os.system() call, > i.e. "os.system('mount test')", but it doesn't work as expected: Perhaps it doesn't work as *you* expected, but it does work as specified. From the os.system description at http://docs.python.org/lib/os-process.html "On Unix, the return value is the exit status of the process encoded in the format specified for wait(). [...] [That return value] is system-dependent." Later on the same page, describing the wait function, says that the return value is "a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero)" So os.system does NOT raise an exception when the executed program ends with a non-zero exit code. > I get the same results with popon, popen2, popen3, etc. Apparently > these also > work only when the program does not generate an exception. An external program cannot generate an exception inside the Python program. Only Python itself can do that. > Is there any way to > catch the return code. or if not, a workaround? From the description above, you could do some math to obtain the exit code looking at the os.system return value. But perhaps it's easier to use subprocess.check_call, see "Convenience functions" at http://docs.python.org/lib/module-subprocess.html -- Gabriel Genellina From bblais at bryant.edu Wed Jan 9 09:40:20 2008 From: bblais at bryant.edu (Brian Blais) Date: Wed, 9 Jan 2008 09:40:20 -0500 Subject: problem building simple package with extensions in Windows, but not OS X Message-ID: <947247E2-B9F8-4DAD-AEB1-87574E3BE64A@bryant.edu> Hello, I am trying to build a package of mine, and for some reason the build process with distutils is failing in Windows, but not in OS X (and I imagine also in Linux, but I haven't tested it). I am not sure if this is a Pyrex problem, a distutils problem, or me doing something stupid problem. :) I boiled it down to the simplest package that still fails. My setup.py is: from distutils.core import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name = 'myproject', version='0.0.1', description="Here is a description", author="Brian Blais", ext_modules=[ Extension("myproject/train",["myproject/train.pyx"]), ], packages=['myproject'], cmdclass = {'build_ext': build_ext} ) and my project has one directory, myproject, with two files. train.pyx is: def func(blah): print blah and an __init__.py, which has the single line: import train So, in OS X, I can do python setup.py build and the build goes through. In windows, with the same basic setup (version numbers all below), I get: [Desktop\test]|5> !python setup.py build running build running build_py creating build creating build\lib.win32-2.5 creating build\lib.win32-2.5\myproject copying myproject\__init__.py -> build\lib.win32-2.5\myproject running build_ext building 'myproject/train' extension creating build\temp.win32-2.5 creating build\temp.win32-2.5\Release creating build\temp.win32-2.5\Release\myproject c:\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Ic:\python25\include -Ic:\pytho n25\PC -c myproject/train.c -o build\temp.win32-2.5\Release\myproject \train.o writing build\temp.win32-2.5\Release\myproject\train.def c:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.5 \Release\myproje ct\train.o build\temp.win32-2.5\Release\myproject\train.def -Lc: \python25\libs - Lc:\python25\PCBuild -lpython25 -lmsvcr71 -o build\lib.win32-2.5 \myproject/train .pyd Cannot export initmyproject/train: symbol not defined collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 On both the Mac and the PC I have: Python 2.5.1 Pyrex version 0.9.5.1a distutils 2.5.1 am I doing something wrong? thanks, Brian Blais -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From sanjeetsanju at gmail.com Sat Jan 5 02:03:15 2008 From: sanjeetsanju at gmail.com (sanjeet) Date: Fri, 4 Jan 2008 23:03:15 -0800 (PST) Subject: mail Message-ID: hi all, I am facing problem to fetch mail from internet mail server. Plz help me, how can do this? thanks , sanjeet From grante at visi.com Sun Jan 6 14:15:10 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 06 Jan 2008 19:15:10 -0000 Subject: Delete lines containing a specific word References: <489729.25110.qm@web57603.mail.re1.yahoo.com> Message-ID: <13o2a5ucddj913e@corp.supernews.com> On 2008-01-06, Matt Nordhoff wrote: >> Please, how to adapt the following script (to delete blank lines) to delete >> lines containing a specific word, or words? > If you're on Linux, why not just use grep? > > $ grep -v theword output.pdb And if you're on Windows, install Cygwin, and then use grep. Or install any of about a half-dozen native Win23 implementations of grep. -- Grant Edwards grante Yow! I'm having a BIG BANG at THEORY!! visi.com From http Sun Jan 27 06:42:33 2008 From: http (Paul Rubin) Date: 27 Jan 2008 03:42:33 -0800 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> <7xy7acsx2l.fsf@ruckus.brouhaha.com> <8ddebd68-43dc-4320-86e1-887aadff4af3@d70g2000hsb.googlegroups.com> <7xmyqs722t.fsf@ruckus.brouhaha.com> <13pnbp9l8lk1j8b@corp.supernews.com> Message-ID: <7xzlur336e.fsf@ruckus.brouhaha.com> Arnaud Delobelle writes: > def simple_posmax(l, key=None): > if key: > return l.index(max(l, key=key)) > else: > return l.index(max(l)) def simple_posmax(l, **kw): return l.index(max(l, **kw)) > simple_posmax is more than 3x faster on my machine. It's not > surprising as even though the list is walked twice, it is all done in > C and no new objects have to be created. Then only non-C bit is when > the result of max(l) is fed to l.index(). It does expose a slight danger in that the list might somehow self-mutate during the first traversal. From lists at cheimes.de Fri Jan 4 11:27:59 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 04 Jan 2008 17:27:59 +0100 Subject: Memory Leaks and Heapy In-Reply-To: <20080104153441.GO82115@nexus.in-nomine.org> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> <20080104153441.GO82115@nexus.in-nomine.org> Message-ID: <477E5E8F.7070503@cheimes.de> Jeroen Ruigrok van der Werven wrote: > Aside from that (rant), I seriously dislike Python's memory management and > even more the fairly arcane ways people have to go about > debugging/troubleshooting some 600 MB to 2-3 GB(!) of resident memory use by > Python. > > Personally I consider this the weakest point of Python. Given the fact there > is a garbage collector this sort of keeping track of memory seems a bit > contradictory to the concept of garbage collection. You are welcome to join the team and improve the memory management. We are constantly looking for new developers and way to enhance Python. If you feel so strong about the memory management please provide patches and benchmarks. Christian From pavlovevidence at gmail.com Fri Jan 18 20:25:55 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 18 Jan 2008 17:25:55 -0800 (PST) Subject: I don't understand what is happening in this threading code References: Message-ID: <0c86b828-883a-4b80-ac11-a5eddea7825c@e4g2000hsg.googlegroups.com> On Jan 18, 7:43 pm, Matthew Wilson wrote: > In this code, I tried to kill my thread object by setting a variable on it > to False. > > Inside the run method of my thread object, it checks a different > variable. > > I've already rewritten this code to use semaphores, but I'm just curious > what is going on. > > Here's the code: > > import logging, threading, time > logging.basicConfig(level=logging.DEBUG, > format="%(threadName)s: %(message)s") > > class Waiter(threading.Thread): > def __init__(self, hot_food): > super(Waiter, self).__init__() > self.should_keep_running = True > self.hot_food = hot_food > > def run(self): > while self.should_keep_running: > logging.debug("Inside run, the id of should_keep_running is %s." > % id(self.should_keep_running)) > self.hot_food.acquire() > > def cook_food(hot_food): > i = 5 > while i >= 0: > logging.debug("I am cooking food...") > time.sleep(1) > hot_food.release() > logging.debug("Andiamo!") > i -= 1 > > def main(): > > hot_food = threading.Semaphore(value=0) > > chef = threading.Thread(name="chef", target=cook_food, args=(hot_food, )) > chef.start() > > w = Waiter(hot_food) > logging.debug("Initially, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > w.start() > logging.debug("After start, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > > # Wait for the chef to finish work. > chef.join() > > # Now try to kill off the waiter by setting a variable inside the waiter. > w.should_keep_running = False > logging.debug("Now, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > > if __name__ == "__main__": > main() It looks like your program's hanging while the waiter is waits to acquire another plate of hot food. Quick and dirty solution is to have waiter timeout at intervals while waiting for the chef and check the clock to see if his shift has ended. Better solution is to rewrite the logic, which you did. Carl Banks From bronger at physik.rwth-aachen.de Thu Jan 10 03:39:51 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 10 Jan 2008 09:39:51 +0100 Subject: Conventions for dummy name References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de> <873at6k2qt.fsf_-_@benfinney.id.au> Message-ID: <87sl1613c8.fsf@physik.rwth-aachen.de> Hall?chen! Ben Finney writes: > "Diez B. Roggisch" writes: > >> The underscore is used as "discarded" identifier. So maybe >> >> for _ in xrange(10): >> ... > > The problem with the '_' name is that it is already well-known and > long-used existing convention for an entirely unrelated purpose: > in the 'gettext' i18n library, the '_' function to get the > locally-translated version of a text string. Right, that's because I've used "__" where not all returning values are interesing to me such as a, b, __ = function_that_returns_three_values(x, y) However, in loops, I prefer real names, even if the loop variable isn't used outside. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From adonisv at REMOVETHISearthlink.net Fri Jan 11 20:21:03 2008 From: adonisv at REMOVETHISearthlink.net (Adonis Vargas) Date: Fri, 11 Jan 2008 20:21:03 -0500 Subject: converting JSON to string In-Reply-To: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> References: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> Message-ID: <13og5g06rvrtefa@corp.supernews.com> Gowri wrote: > Hello, > > I actually have two questions: > 1. Are there any libraries which convert XML to JSON? > 2. I am currently doing the above using the DOM parser and creating a > JSON array > > > for node in doc.getElementsByTagName("book"): > isbn = node.getAttribute("isbn") > titleNode = (node.getElementsByTagName("title") > [0]).childNodes[0] > title = titleNode.data > primarykeys.append({'isbn': isbn, 'title': title}) > return primarykeys > > I want to send primarykeys as a response to my client. i use > mod_python and apache. The problem is, I have not been able to figure > out how to convert my JSON output to a string. > > Could someone please help me? > > Thanks in advance do: return str(primarykeys) Also there are Python modules for just this. Here is the very first link from Google: http://pypi.python.org/pypi/python-json I have used this one personally and have been very satisfied with it. There is another one (CJSON?) which is similar, but written in C, for when performance may be an issue. Hope this helps. Adonis From deets at nospam.web.de Fri Jan 25 14:16:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jan 2008 20:16:52 +0100 Subject: Operator overloading In-Reply-To: <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> References: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com> <5vuob3F1nd2bhU1@mid.uni-berlin.de> <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> Message-ID: <5vuqt8F1olnneU1@mid.uni-berlin.de> MartinRinehart at gmail.com schrieb: > > Diez B. Roggisch wrote: >> No, there is no way. You would change general interpreter behavior if >> you could set arbitrary operators for predefined types. >> >> Start grumping... > > Thank you, Diez. > > If I ever design a language, please remind me that complete, easy, > well-documented access to the working of the internals (and the > ability to change same) would be very, uh, what's the right word? > Pythonic? As you say - it's a question of design & thus taste. Python has chosen to _not_ allow to change (all) inner workings of itself in favor of not introducing subtle bugs that arise from somebody (accidentially or not) altering behavior of builtins that might effect code he'd never intended to touch. But you _can_ create subclasses of these builtins and adapt their behavior. I for once like it that way. If you don't - to bad for you. It won't change, so either you live with it, or start working on your lex/yacc skillz and create your own language. Or switch to Ruby, which allow for what you desire (AFAIK, not entirely sure though) Diez From http Sat Jan 12 13:26:04 2008 From: http (Paul Rubin) Date: 12 Jan 2008 10:26:04 -0800 Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> <354c74f6-6e56-4e41-a686-56239aa4cea9@f47g2000hsd.googlegroups.com> Message-ID: <7x8x2uj3yb.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > 2) List is referenced by others; concurrent modifications may be going > on; can not replace it. Can I make asynchronous modifications and > merge the changes, SCM-style? Nothing else should have direct access to the list. > 3) Dictionary returns non-static order; order is important. Create a > int-func tuple and sort dictionary results? Perhaps. That's sounding > pretty good. If the list is not too long, that is reasonable. If it -is- long, the remove operations can be slow, but that's ok if there's not too many. If the list is long -and- there's a lot of adds/removes, maybe you want something like an AVL tree. From sndive at gmail.com Wed Jan 16 17:44:36 2008 From: sndive at gmail.com (Squat'n Dive) Date: Wed, 16 Jan 2008 14:44:36 -0800 (PST) Subject: -fno-strict-aliasing turned off when cross compiling Message-ID: <66c2d5b4-c84f-47d9-aa4a-1cca3ae594b2@q39g2000hsf.googlegroups.com> Does anyone have an idea why -fno-strict-aliasing is turned off when cross compiling? in configure generated for 2.4.4: case $GCC in yes) # Python violates C99 rules, by casting between incompatible # pointer types. GCC may generate bad code as a result of that, # so use -fno-strict-aliasing if supported. echo "$as_me:$LINENO: checking whether $CC accepts -fno-strict- aliasing" >&5 echo $ECHO_N "checking whether $CC accepts -fno-strict-aliasing... $ECHO_C" >&6 ac_save_cc="$CC" CC="$CC -fno-strict-aliasing" if test "$cross_compiling" = yes; then ac_cv_no_strict_aliasing_ok=no ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ why? else From hyperboreean at nerdshack.com Fri Jan 4 09:59:34 2008 From: hyperboreean at nerdshack.com (hyperboreean) Date: Fri, 04 Jan 2008 16:59:34 +0200 Subject: python interfaces Message-ID: <477E49D6.1090506@nerdshack.com> Hi, Probably it has been asked before, but I'll still ask. Why doesn't python provide interfaces trough its standard library? Or it was ever proposed to be included in the language? Zope's implementation seems pretty flexible and straightforward. Thanks. From mathewbrown at fastmail.fm Wed Jan 9 10:17:44 2008 From: mathewbrown at fastmail.fm (Mrown) Date: Wed, 9 Jan 2008 07:17:44 -0800 (PST) Subject: subprocess.Popen spawning cmd shells Message-ID: Hi, I'm currently writing a python program that relies on a CLI program. What I'm currently doing is using subprocess.Popen on Python 2.5.1. Here's the line that I'm currently running: child = subprocess.Popen(["c:\app.exe", node, "-w", str(tmpTime * 1000), '-n', str(1), '-l'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) The problem is that although the above works, a CMD shell is spawned and becomes visible for each time I run the above. I thought that by redircting stdin, stdout and stderr, no CMD shell should pop-up. Is something wrong in the way I'm using subprocess? Thanks for your help. From rw at smsnet.pl Sun Jan 20 10:42:38 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Sun, 20 Jan 2008 16:42:38 +0100 Subject: writing Python in Emacs References: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> Message-ID: <87r6gc5wr5.fsf@merkury.smsnet.pl> Terry Jones writes: >>>>>> "Richard" == Richard Szopa writes: I don't see Richard's original post, so I reply to Terry. > > Richard> I am a devoted Emacs user and I write a lot in Python. > > Me too. The good news is that I managed to configure completion for Python in Emacs using pymacs, python-mode.el, pycomplete.el and pycomplete.py. For contents of my pycomplete.el, pycomplete.py and necessary settings in .emacs see below. > > Richard> I need the following features: > > Richard> 1) Tab completion, ideally Slime like. That is, when there's not > Richard> enough letters to unambiguously complete a symbol, I want it to > Richard> show a buffer (w/o taking the focus) w/ the possible > Richard> completions. In an ideal world, it would be able to complete > Richard> fo.ba to foo.bar. I imagine this would require quite tight > Richard> Emacs-Python integration. Works for me. [...] > Richard> 2) Sending the toplevel definition (class or function) to the Python > Richard> buffer. That feature is defined in python-mode.el: "\e\C-x" 'py-execute-def-or-class "\C-c|" 'py-execute-region [...] > Richard> 3) Hints on function/method arguments. IDLE has this done nearly > Richard> right, but the hints are a bit too intrusive for me. I would like to > Richard> see them in the minibuffer. Works for me, but only for pure python functions (`inspect.getargspec` constraint). [...] > Richard> I have tried a couple of times both python-modes (the one shipped w/ > Richard> Python and the one shipped w/ Emacs), pymacs and stuff like that... > Richard> And, as I said, never got it right. But, maybe I just cannot find the > Richard> way to configure it, and some configuration hints will be enough... I mixed solutions found around the net and finally got it working: - hitting TAB complete function/method name - f1 shows description of object at point - hitting '(' and ',' shows function parameters Copy `pycomplete.py` on your PYTHONPATH (e.g. /usr/lib/python2.5/site-packages) and `pycomplete.el` on your Emacs load_path (e.g. /usr/share/emacs/site-lisp). Copy my settings to your `.emacs` file and hopefully it will work. ;) My files: # .emacs (require 'pycomplete) (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) (autoload 'python-mode "python-mode" "Python editing mode." t) (autoload 'pymacs-load "pymacs" nil t) (autoload 'pymacs-eval "pymacs" nil t) (autoload 'pymacs-apply "pymacs") (autoload 'pymacs-call "pymacs") (setq interpreter-mode-alist(cons '("python" . python-mode) interpreter-mode-alist)) (setq python-mode-hook '(lambda () (progn (set-variable 'py-python-command "/usr/bin/python2.5") (set-variable 'py-indent-offset 4) (set-variable 'py-smart-indentation nil) (set-variable 'indent-tabs-mode nil)))) # end of .emacs # pycomplete.el (require 'pymacs) (require 'python-mode) (pymacs-load "pycomplete") ;;check if prev character is blank-type (defun char-before-blank () (save-excursion (forward-char -1) (looking-at "[\n\t\r]"))) (defun py-complete () (interactive) (let ((pymacs-forget-mutability t)) (if (and (and (eolp) (not (bolp)) (not (char-before-blank)))) (insert (pycomplete-pycomplete (py-symbol-near-point) (py-find-global-imports))) (indent-for-tab-command)))) (defun py-find-global-imports () (save-excursion (let ((imports nil)) (goto-char (point-min)) (while (re-search-forward "\\(import \\|from \\([A-Za-z_][A-Za-z_0-9\\.]*\\) import \\).*" nil t) (setq imports (append imports (list (buffer-substring (match-beginning 0) (match-end 0)))))) imports))) (defun py-complete-python-dotexpr-begin nil (interactive) (re-search-backward "[^a-zA-Z_0-9\\.]") (forward-char)) (defun py-complete-python-dotexpr-end nil (interactive) (re-search-forward "[a-zA-Z_0-9\\.]*")) (put 'python-dotexpr 'beginning-op 'py-complete-python-dotexpr-begin) (put 'python-dotexpr 'end-op 'py-complete-python-dotexpr-end) (defun py-complete-show (string) (display-message-or-buffer string "*PythonHelp*")) (defun py-complete-help (string) "get help on a python expression" (let ((help-string (pycomplete-pyhelp string (py-find-global-imports)))) (if (and help-string (> (length help-string) 300)) (with-output-to-temp-buffer "*Python Help*" (print help-string)) (py-complete-show help-string)))) (defun py-complete-help-thing-at-point nil (interactive) (require 'thingatpt) (let ((sym (thing-at-point 'python-dotexpr))) (if sym (py-complete-help sym)))) (set 'py-complete-current-signature nil) (defun py-complete-signature (function) "get signature of a python function or method" (interactive) (set 'py-complete-current-signature (pycomplete-pysignature function))) (defun py-complete-signature-show nil (interactive) (require 'thingatpt) (let ((sym (thing-at-point 'python-dotexpr))) (if sym (progn (py-complete-show (py-complete-signature sym)))))) (defun py-complete-signature-expr nil (interactive) (require 'thingatpt) (let ((dotexpr (read-string "signature on: " (thing-at-point 'python-dotexpr)))) (if dotexpr (py-complete-show (py-complete-signature dotexpr))))) (defun py-complete-electric-lparen nil "electricly insert '(', and try to get a signature for the stuff to the left" (interactive) (py-complete-signature-show) (self-insert-command 1)) (defun py-complete-electric-comma nil "electricly insert ',', and redisplay latest signature" (interactive) (self-insert-command 1) (if py-complete-current-signature (py-complete-show (format "%s" py-complete-current-signature)))) (define-key py-mode-map "\M-\C-i" 'py-complete) (define-key py-mode-map "\t" 'py-complete) (define-key py-mode-map [f1] 'py-complete-help-thing-at-point) (define-key py-mode-map "(" 'py-complete-electric-lparen) (define-key py-mode-map "," 'py-complete-electric-comma) (define-key py-mode-map [f2] 'py-complete-signature-expr) (provide 'pycomplete) # end of pycomplete.el # pycomplete.py import sys import inspect from StringIO import StringIO import os.path try: x = set except NameError: from sets import Set as set else: del x from Pymacs import lisp sys.path.append('.') def pycomplete(s, imports=None, debug=False): """Display completion in Emacs window""" completions = _get_all_completions(s, imports) dots = s.split(".") result = os.path.commonprefix([k[len(dots[-1]):] for k in completions]) if result == "": if completions: if debug: width = 80 else: width = lisp.window_width() - 2 column = width / 20 white = " " * 20 msg = "" counter = 0 for completion in completions : if len(completion) < 20 : msg += completion + white[len(completion):] counter += 1 else : msg += completion + white[len(completion) - 20:] counter += 2 if counter >= column: counter = 0 msg += '\n' else: msg = "no completions!" if debug: print msg else: lisp.message(msg) return result def pyhelp(s, imports=None): """Return object description""" _import_modules(imports, globals(), None) return _getdoc(s) def pysignature(s): """Return info about function parameters""" f = None try: f = eval(s) except Exception, ex: return "%s" % ex if inspect.ismethod(f): f = f.im_func if not inspect.isfunction(f): return '' (args, varargs, varkw, defaults) = inspect.getargspec(f) return('%s: %s' % (f.__name__, inspect.formatargspec(args,varargs,varkw,defaults))) def _getdoc(s): """Return string printed by `help` function""" obj = None try: obj = eval(s) except Exception, ex: return "%s" % ex out = StringIO() old = sys.stdout sys.stdout = out help(obj) sys.stdout = old return out.getvalue() def _import_modules(imports, dglobals, dlocals): """If given, execute import statements""" if imports is not None: for stmt in imports: try: exec stmt in dglobals, dlocals except TypeError: raise TypeError, 'invalid type: %s' % stmt except: continue def _get_all_completions(s, imports=None): """Return contextual completion of s (string of >= zero chars)""" dlocals = {} _import_modules(imports, globals(), dlocals) dots = s.split(".") if not s or len(dots) == 1: keys = set() keys.update(dlocals.keys()) keys.update(globals().keys()) import __builtin__ keys.update(dir(__builtin__)) keys = list(keys) keys.sort() if s: return [k for k in keys if k.startswith(s)] else: return keys sym = None for i in range(1, len(dots)): s = ".".join(dots[:i]) try: sym = eval(s, globals(), dlocals) except NameError: try: sym = __import__(s, globals(), dlocals, []) except ImportError: return [] if sym is not None: s = dots[-1] return [k for k in dir(sym) if k.startswith(s)] def _test(): print ' ->', pycomplete('', debug=True) print 'sys.get ->', pycomplete('sys.get', debug=True) print 'settr ->', pycomplete('settr', debug=True) print 'settr (plat in context) ->', print pycomplete('settr', imports=['from sys import settrace'], debug=True) print 'foo. ->', pycomplete('foo.', debug=True) print 'Enc (email * imported) ->', print pycomplete('Enc', imports=['from email import *'], debug=True) print 'E (email * imported) ->', print pycomplete('E', imports=['from email import *'], debug=True) print 'Enc ->', pycomplete('Enc', debug=True) print 'E ->', pycomplete('E', debug=True) if __name__ == "__main__": _test() # end of pycomplete.py HTH, Rob From apardon at forel.vub.ac.be Fri Jan 25 02:57:13 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Jan 2008 07:57:13 GMT Subject: When is min(a, b) != min(b, a)? References: <13pi8fiiqgljdb5@corp.supernews.com> Message-ID: On 2008-01-24, Steven D'Aprano wrote: > On Thu, 24 Jan 2008 13:34:56 +0000, Antoon Pardon wrote: > >> On 2008-01-21, Steven D'Aprano >> wrote: >>> On Sun, 20 Jan 2008 21:15:02 -0600, Albert Hopkins wrote: >>> >>> According to the IEEE-754 standard the usual trichotomy of "x is less >>> than y, x is equal to y, or x is greater than y" has to be extended to >>> include "x and y are unordered". Comparisons with NaNs are unordered, >>> and so expressions like "x < nan" should signal an exception. >> >> That doesn't follow. The problem is not that x < nan returns False >> because that is correct since x isn't smaller than nan. > > Comparisons between things which are not comparable risk being terribly > misleading, and depend very much on how you define "less than" and > "greater than". If you insist that everything must have a boolean yes/no > answer ("Does the colour red have a better chance of becoming President > than a kick to the head?") then False is not an entirely unreasonable > result to return. > > But if you consider that having "x is not smaller than y" be equivalent > to "x is greater than or equal to y" is more important than forcing a > boolean answer in the first place, then you need something to signal > Undefined, and an exception is the right solution unless you have multi- > valued logic system (True, False, Maybe, Undefined, ...) Why should we consider that? The world is full of partial orders. In python we have sets and a partial order is perfectly mathematically sound. > SANE (Standard Apple Numerics Environment) explicitly states that it > signals an exception when doing ordered comparisons against NaNs because > to return False would be misleading. Apple went on to use the same rule > in their PowerPC Numerics. That's straight out of the Zen: Practicality > Beats Purity. What is misleading and what is not depends on the context. One could argue that if comparisons against NaN should signal an exception that the exception comes late and should already have been signaled at the moment the NaN was produced because producing a NaN is already misleading. It gives the impression you have a (meaningfull) result until you later try to do something with it that is illegal for a NaN but for legal for a float. If you allow NaN's as a result then you have extended the floats to a mathematical set that is now only partially ordered. I see nothing wrong in having the comparion operators give the result that belongs to such a partial order. -- Antoon Pardon From http Tue Jan 15 13:22:34 2008 From: http (Paul Rubin) Date: 15 Jan 2008 10:22:34 -0800 Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> <5a3ace63-a8cf-4970-a95e-4243226fbac7@j20g2000hsi.googlegroups.com> Message-ID: <7x3aszgd91.fsf@ruckus.brouhaha.com> Chris M writes: > precludes error-prone constructions like set('abc') & 'cbs' in favor > of the more readable set('abc').intersection('cbs')." set('abc') & set('cbs') From terry at jon.es Sat Jan 19 11:51:50 2008 From: terry at jon.es (Terry Jones) Date: Sat, 19 Jan 2008 17:51:50 +0100 Subject: writing Python in Emacs In-Reply-To: Your message at 04:01:48 on Saturday, 19 January 2008 References: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> Message-ID: <18322.10918.59701.913455@terry.local> >>>>> "Richard" == Richard Szopa writes: Richard> I am a devoted Emacs user and I write a lot in Python. Me too. Richard> I need the following features: Richard> 1) Tab completion, ideally Slime like. That is, when there's not Richard> enough letters to unambiguously complete a symbol, I want it to Richard> show a buffer (w/o taking the focus) w/ the possible Richard> completions. In an ideal world, it would be able to complete Richard> fo.ba to foo.bar. I imagine this would require quite tight Richard> Emacs-Python integration. I know this is not what you want, but I use hippie expand (M-/) to cycle through possible completions. It's not Python aware, but it is of some use. Richard> 2) Sending the toplevel definition (class or function) to the Python Richard> buffer. I switched to IPython to have better interaction with a spawned Python. To use IPython you need to use the Python mode that is NOT the one from (endorsed?) by the FSF. It gives you some completion (at least in the *Python* buffer) and you can send pieces of the buffer to the python process, via py-send-region (C-c |), py-execute-def-or-class (M-C-x), etc. Richard> 3) Hints on function/method arguments. IDLE has this done nearly Richard> right, but the hints are a bit too intrusive for me. I would like to Richard> see them in the minibuffer. I don't have this. Richard> 4) (optional) I would like to see the definition of a function Richard> function or class by hitting M-. on its name. (I understand that Richard> this may be impossible for methods, as Emacs would have to Richard> automagically infer the type of the object). This is just an emacs tag file need. Have you googled for something like emacs tags python? The issue of methods might be overcome by just moving through tags with the same name. Yes, that requires _you_ to know when you've hit the right thing. That's not optimal, but it's better than nothing. Ideally you could send the definition to IPython, ask it for the class info, and use that to jump to the right tag. Richard> I have tried a couple of times both python-modes (the one shipped w/ Richard> Python and the one shipped w/ Emacs), pymacs and stuff like that... Richard> And, as I said, never got it right. But, maybe I just cannot find the Richard> way to configure it, and some configuration hints will be enough... If you have the time, please summarize your findings. The emacs/python world has always seemed quite amorphous to me too. Terry From patrick.waldo at gmail.com Sat Jan 19 08:46:42 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Sat, 19 Jan 2008 05:46:42 -0800 (PST) Subject: pyExcelerator: writing multiple rows Message-ID: <3b2b19a9-f0b6-487d-887b-064ad4039091@v67g2000hse.googlegroups.com> Hi all, I was just curious if there was a built-in or a more efficient way to do take multiple rows of information and write them into excel using pyExcelerator. This is how I resolved the problem: from pyExcelerator import * data = [[1,2,3],[4,5,'a'],['','s'],[6,7,'g']] wb=pyExcelerator.Workbook() test = wb.add_sheet("test") c=1 r=0 while r Message-ID: <8b3d7751-9bfe-47f8-a15d-e73ac3a34b41@s8g2000prg.googlegroups.com> On Jan 9, 3:52 pm, Waldemar Osuch wrote: > On Jan 9, 11:47 am, "Steven W. Orr" wrote: > > > > > So sorry because I know I'm doing something wrong. > > > 574 > cat c2.py > > #! /usr/local/bin/python2.4 > > > def inc(jj): > > def dummy(): > > jj = jj + 1 > > return jj > > return dummy > > > h = inc(33) > > print 'h() = ', h() > > 575 > c2.py > > h() = > > Traceback (most recent call last): > > File "./c2.py", line 10, in ? > > print 'h() = ', h() > > File "./c2.py", line 5, in dummy > > jj = jj + 1 > > UnboundLocalError: local variable 'jj' referenced before assignment > > > I could have sworn I was allowed to do this. How do I fix it? > > I have seen this approach on ActiveState Cookbook but can not find a > reference to it right now. > > >>> def inc(jj): > > ... def dummy(): > ... dummy.jj += 1 > ... return dummy.jj > ... dummy.jj = jj > ... return dummy > ...>>> h = inc(33) > >>> h() > 34 > >>> h() > 35 > >>> i = inc(12) > >>> i() > 13 > >>> i() > > 14 > > Waldemar Here it is: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474122 From p at ulmcnett.com Fri Jan 25 01:03:19 2008 From: p at ulmcnett.com (Paul McNett) Date: Thu, 24 Jan 2008 22:03:19 -0800 Subject: Terminology: "script" versus "program" In-Reply-To: <13pid16l607s065@corp.supernews.com> References: <1666950d-e9a5-4b7c-a614-5bba90e5b4ca@y5g2000hsf.googlegroups.com> <87ir1j7r9k.fsf_-_@benfinney.id.au> <13pid16l607s065@corp.supernews.com> Message-ID: <47997BA7.9090309@ulmcnett.com> Steven D'Aprano wrote: > Linux/Unix/Mac admins may be excused for saying that they've never come > across a .BAT file at all. > > $ locate .bat | wc -l > 14 > $ locate .sh | wc -l > 606 $ locate .bat | wc -l 115 $ locate .sh | wc -l 763 $ locate .py | wc -l 44030 Hmmm... that matched all the .pyo and .pyc files, too. Not fair. $ locate -r '\.py$' | wc -l 17425 $ locate -r '\.sh$' | wc -l 278 $ locate -r '\.bat$' | wc -l 49 Still a bit unbelievable, although I do have all the branches and tags checked out of my main projects, and I tend to make lots of little .py files so most of that 17,425 number is probably me. Paul -- http://paulmcnett.com From dongie.agnir at gmail.com Wed Jan 9 15:46:12 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Wed, 9 Jan 2008 12:46:12 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: Thanks for the clarification. Though I was hoping someone could give me a definitive answer. I was quite excited about this project initially, but seeing the actual execute times was a big downer. Seeing that the original laser marker by GRL Vienna is done in Processing which from what I know is built on Java, I was hoping that Python would be up to a similar task. From bs866806 at 163.com Tue Jan 8 07:22:35 2008 From: bs866806 at 163.com (bs866806 at 163.com) Date: Tue, 8 Jan 2008 04:22:35 -0800 (PST) Subject: =?ISO-8859-1?Q?Intranet_Project_-_Rad_Or_Waterfall??= Message-ID: <53490824-d95a-43ab-a405-e1249d4b396f@s12g2000prg.googlegroups.com> I have often used the analogy of building a bridge to explain to business colleagues the difference between Rapid Application Development (RAD) and Waterfall. Let's say that we are in the middle ages and the Mayor of Kingston- upon-Thames is evaluating whether or not to build a bridge over the river to the north side, to replace the current ferry. The whole area has been growing rapidly and a bridge at Kingston should give his town a lead against competing local towns like Ham and Richmond (who also have their own ferries). However, building a bridge presents problems. Firstly, the bedrock north and south of the river are very different. Secondly, the river is still tidal at this point and its path continues to vary across the floodplain. Finally - and perhaps most importantly - there is no guarantee that the projected growth in cross-river traffic will indeed materialise - or that people will wish to cross at this precise point, rather than further up, or down, river. A new bridge could prove an expensive white elephant and divert much-needed town resources away from other projects. The increased local taxes required could also scare the very businesses he is hoping to attract away to other local towns. Option 1 - Waterfall Waterfall, as a methodology, is all about building reliable systems. At each stage of the lifecycle, the results are correct. The Mayor's engineer believes that - when building a bridge - the result needs to be safe, sound and capable of lasting for decades. He recommends a design phase, which includes thoroughly testing the bedrock by driving piles and developing ways to limit the future variance of the river's course. During the build phase, the bridge would be tested to ensure it can take the loads that will be placed upon it and to deal with high winds or flood conditions. The engineer confirms that each stage would only start once the previous stage had been proved correct beyond reasonable doubt. The stone bridge will take five whole years to build (with a high upfront cost commitment). If the project were ever stopped, the value tied up in phases to date would be lost. The engineer reminds the Mayor that a collapsed bridge would not help his place in history! Option 2 - RAD RAD, as a methodology is all about building relevant systems. The argument runs that it is better to be there quickly with 80% of the functionality in 20% of the time, so as to take full advantage of the business opportunity. The Mayor's political advisors recommend the RAD option; to lay a pontoon bridge first alongside the existing ferry. This can be achieved in just three months, using a series of boats with a makeshift road surface and swing bridge lock for river vessels to navigate. The pontoon bridge allows the business model to be tested very quickly; If the expected benefits materialise, then further iterations of the bridge can be constructed later on. Sounds good, but of course (overall) the costs will be higher than waterfall if a full, stone bridge is ultimately required. In the meantime, if the river changes course, or floods impact the area, then the pontoon bridge will be washed away. His chief advisor reminds him that a bridge five years from now would not help his re-election prospects two years hence! The Mayor's selected option Hmm. Interesting, isn't it. Not a clear-cut decision. There are good arguments for either approach. The Mayor's decision will ultimately depend on (a) how sure he is of his own vision, (b) his financial and time constraints and (c) how changeable these factors are likely to be over time. In short, he has a trade-off decision of relevance vs. reliability. Turning the analogy onto Intranet Projects In chapter 16 of my Intranet Portal Guide, I explore these concepts in a bit more depth.However - put simply - the answer for you will depend largely on how sure you are of your vision, the support of stakeholders, the availability of resources and the degree of change in your organisation and it's requirements. If you are operating in a stable business environment and are well funded and supported, then waterfall offers real benefits. You could establish an Intranet Portal that is well founded, scalable and secure. If not, then RAD could offer you the means to make some progress now at low cost and use the results of your early work to build a stronger case for future investment. It also allows you to vary the approach - or begin again - should circumstances or requirements change. Most Intranet evangelists will find themselves perhaps in a mixed situation, where there is support and funding but there is also the risk of rapid changes to the underlying business environment and requirements. Here, I would recommend a mixed approach: Use a waterfall project to establish the underlying portal infrastructure (as this platform will be the bedrock on which you will build and needs to stand the test of time). Then use a RAD method to build the content and applications (developing solutions that are timely and relevant to businesses operating in a fast-moving and competitive environment). http://cncarrental.cn/html/Internet/20060929/31828.html From mani.agape at gmail.com Tue Jan 29 22:54:18 2008 From: mani.agape at gmail.com (Manikandan R) Date: Wed, 30 Jan 2008 09:24:18 +0530 Subject: How to collect all the IP address of the system connected in network? Message-ID: Hai, I am working with python 2.4. I am new to python, I need to collect all the ipaddress of the systems connected in the network for my project. While browsing I come accross Ur link. I think U peoples can help me. Can U please send me the code and guide me to get it. I am in dead line so can U make it fast ................ Thank's and Regard's, R.Manikandan. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Jan 23 03:12:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 06:12:29 -0200 Subject: python24 symbol file...pyhon24.pdb References: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> Message-ID: En Wed, 23 Jan 2008 05:04:35 -0200, escribi?: > I've seen a few references on the net to a python24.pdb file. I assume > it's a symbol file along the lines of the pdb files issued by > microsoft for their products. Maybe I'm wrong. > > Has anyone seen such an animal? I don't get why you care so much about that file. It's useful to debug a crash in python.exe, but I can't see any other useful purpose (if you only have the python executable and the .pdb available). > Also, is there source code available for python24 for Windoze? I have > seen reference to source code but not in a package for Windows. There is a single source package shared by all platforms. You can download and compile it, and you'll get your own version of python.pdb if you like. -- Gabriel Genellina From lefevrol at yahoo.com Mon Jan 28 14:34:04 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Mon, 28 Jan 2008 20:34:04 +0100 Subject: read and readline hanging In-Reply-To: References: Message-ID: >> Yes, that has since occurred to me. I need to echo some magic string >> after each command to know that I reached the end of the answer to >> the previous command. In interactive mode the prompt fulfills that >> role. > > And hope that that "magic string" does not occur somewhere within > the response... In a numerical setting there are strings you can be pretty sure will not occur, esp. alone on their own line. It might be harder if you were dealing with arbitrary text but I'm not. > I think you would be better off looking into the correctly spelled > 'threading' module rather than the misspelled 'trheading' module. :-) That was a just a copy-and-paste from the original reply. It would not have caused me to segfault not to find a module named 'trhreading': I'm a human, not a 'puter ;-) -- O.L. From ricaraoz at gmail.com Mon Jan 14 13:09:07 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 14 Jan 2008 15:09:07 -0300 Subject: split parameter line with quotes In-Reply-To: References: <37fac828-20ec-4cb9-8ea7-a85cce7d3e91@k39g2000hsf.googlegroups.com> Message-ID: <478BA543.7030508@bigfoot.com> teddyber wrote: > here's the solution i have for the moment : > > t = shlex.shlex(data) > t.wordchars = t.wordchars + "/+.-" > r='' > while 1: > token = t.get_token() > if not token: > break > if not token==',': r = r+token > else: r = r + ' ' > self.DEBUG(r,'ok') > for pair in r.split(' '): > key,value=pair.split('=', 1) > print(key+':'+value) > > i know this is not perfect still but i'm coming a long way from very > bad php habits! :o) > and thanks for your help! > > On 11 jan, 23:30, teddyber wrote: >> wow! that's perfect this shlex module! thanks for pointing this! >> >> On 11 jan, 20:36, Joshua Kugler wrote: >> >>> teddyber wrote: >>>> first i'm a newbie to python (but i searched the Internet i swear). >>>> i'm looking for some way to split up a string into a list of pairs >>>> 'key=value'. This code should be able to handle this particular >>>> example string : >>>> qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, >>>> 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess >>>> i know i can do that with some regexp (i'm currently trying to learn >>>> that) but if there's some other way... >>> Take a look at the shlex module. You might be able to fiddle with the shlex >>> object and convince it to split on the commas. But, to be honest, that >>> above would be a lot easier to parse if the dividing commas were spaces >>> instead. >>> j > Maybe you like : >>> x = 'qop = "auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess' >>> dict(zip([k[-1].strip() for k in (j.split(',') for j in ''.join(i for i in x if i != '"').split('='))][:-1], [k[:-1] or k for k in (j.split(',') for j in ''.join(i for i in x if i != '"').split('='))][1:])) {'maxbuf': ['1024'], 'cipher': ['rc4-40', 'rc4-56', 'rc4', 'des', ' 3des'], 'charset': ['utf-8'], 'algorithm': ['md5-sess'], 'qop': [' auth', 'auth-int', 'auth-conf']} From martin at marcher.name Tue Jan 8 05:01:03 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 08 Jan 2008 11:01:03 +0100 Subject: Look for a string on a file and get its line number References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <20080108083302.GD75977@nexus.in-nomine.org> Message-ID: Jeroen Ruigrok van der Werven wrote: > -On [20080108 09:21], Horacius ReX (horacius.rex at gmail.com) wrote: >>I have to search for a string on a big file. Once this string is >>found, I would need to get the number of the line in which the string >>is located on the file. Do you know how if this is possible to do in >>python ? > > (Assuming ASCII, otherwise check out codecs.open().) > > big_file = open('bigfile.txt', 'r') > > line_nr = 0 > for line in big_file: > line_nr += 1 > has_match = line.find('my-string') > if has_match > 0: > print 'Found in line %d' % (line_nr) > > Something to this effect. apart from that look at the linecache module. If it's a big file it could help you with subsequent access to the line in question hth martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From bignose+hates-spam at benfinney.id.au Mon Jan 14 06:18:44 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 14 Jan 2008 22:18:44 +1100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: <87prw4fyej.fsf@benfinney.id.au> "A.T.Hofkamp" writes: > while you think you are doing "Person('me', 'here', 31)", you are in > reality executing "Person.__init__(self, 'me', 'here', 31)", where > 'self' is refers to a shiny new, empty object created for you. This is misleading, and founders on many discrepancies, not least of which is that '__init__' always returns None, yet the 'Person()' call returns the new instance. So it's quite untrue to say that one is "in reality" calling the '__init__' method. What one is "in reality" calling is the '__new__' method of the Person class. That function, in turn, is creating a new Person instance, and calling the '__init__' method of the newly-created instance. Finally, the '__new__' method returns that instance back to the caller. -- \ "Probably the toughest time in anyone's life is when you have | `\ to murder a loved one because they're the devil." -- Emo | _o__) Philips | Ben Finney From gagsl-py2 at yahoo.com.ar Sun Jan 27 12:45:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 15:45:14 -0200 Subject: getting values from cache References: <480b367b-e5c4-4018-a968-8c146555dbdd@v29g2000hsf.googlegroups.com> Message-ID: En Sat, 26 Jan 2008 05:21:52 -0200, nodrogbrown escribi?: > hi > i am writing code to check a folder containing images and then process > thir vals using PIL and do some calc to create a matrix of values .if > the folder has any new imgs added the program will do all calc again > and dump the values into a cachefile.If the folder contents remain > unaltered the program should not do calc but load the vals from > cachefile..it is assumed that malicious alterations are not made on > the folder and so i wont be doing any thorogh check but just checking > if contents of folder have changed..i do something like this > > > def checkCache(self): > filenameslist=getfilenameslist() # made by parsing folder before > this > try: > f=open(cachefile) > > except IOError: > #no cache found ,do all calc > mynumpymatrix1,imgwdth,imght=docalculations() > f2=open(cachefile,"w") > #dump values as tuple > pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f2) > f2.close() > else: > #cache exists, need to check if folder contents changed > oldfilenameslist,wd,ht, mynumpymatrix1=pickle.load(f) > f.close() > > if(filenamelist==oldfilelist): > #if oldfilenamelst same,it means folder hasn't changed > #use the vals from cache..... > else: > #folder changed > mynumpymatrix1,imgwdth,imght=docalculations() > f3=open(cachefile,"w") > pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f3) > f3.close() > > this works and does what i need in my code..but i want to know if a > more elegant solution is possible > i am not worried about someone deliberately renaming files like > aaaa.jpeg to aaa.jped and a.jpeg to deceive the checking > since it is assumed that noone has permission to modify the folder > except a trusted admin/code > > will be grateful for your suggestions > tia I'd try to avoid duplicating the calculation code. get newfilenameslist update_cache = True try: f=open(cachefile) except IOError: pass else: read oldfilenameslist f.close() if oldfilenameslist==newfilenameslist: update_cache = False if update_cache: do calculations write file Also, if you split the data in two, you can just read the filename list alone: pickle.dump(filenameslist, f2) pickle.dump((imgwdth,imght,mynumpymatrix1),f2) -- Gabriel Genellina From mwm-keyword-python.b4bdba at mired.org Wed Jan 9 19:08:53 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Wed, 9 Jan 2008 19:08:53 -0500 Subject: Python too slow? In-Reply-To: References: <7115e305-429c-47d3-a942-8a0e2a0e846f@m34g2000hsf.googlegroups.com> Message-ID: <20080109190853.6fe75851@bhuda.mired.org> On Wed, 9 Jan 2008 15:45:41 -0800 (PST) "dongie.agnir at gmail.com" wrote: > Okay I profiled the code and here is the output: > > http://heightened.files.wordpress.com/2008/01/output.txt > > It seems that the function it spends the longest on is the red_points > function that he uses to find the points. Ok, so what's that look like? Python - used properly - can be quite fast. We process 1.5 billion rows a day through our python-based ETL system. The trick is to arrange things so that the cpu-intensive work gets done by C code. Preferably by tightly coded C written by very sharp people and extensively tweaked to make it go fast. In our case, the T part of our ETL system is handled by a custom C library that's been around - and being debugged and tweaked - for quite some time. Other examples include much of the code for python's builtins, and things like the Numpy extension library. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From steven.p.clark at gmail.com Sun Jan 27 19:01:49 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Sun, 27 Jan 2008 19:01:49 -0500 Subject: Python Genetic Algorithm In-Reply-To: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> References: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <663744510801271601g7f41d550w793c62bd79b3d78e@mail.gmail.com> Why not make chromosome itself a class? class BasicChromosome(object): def __init__(self, data): self.data = data def crossover(self): [stuff here] You can subclass this as needed, altering the crossover method as necessary. ...perhaps I didn't understand your question. -Steven On Jan 27, 2008 6:35 PM, Wildemar Wildenburger wrote: > Max wrote: > > In GAs, you operate on a Population of solutions. Each Individual from > > the Population is a potential solution to the problem you're > > optimizing, and Individuals have what's called a chromosome - a > > specification of what it contains. For example, common chromosomes are > > bit strings, lists of ints/floats, permutations...etc. I'm stuck on > > how to implement the different chromosomes. I have a Population class, > > which is going to contain a list of Individuals. Each individual will > > be of a certain chromosome. I envision the chromosomes as subclasses > > of an abstract Individual class, perhaps all in the same module. I'm > > just having trouble envisioning how this would be coded at the > > population level. Presumably, when a population is created, a > > parameter to its __init__ would be the chromosome type, but I don't > > know how to take that in Python and use it to specify a certain class. > > > I'm not sure I'm following you here. So a "chromosome" is bit of > functionality, right? So basically it is a function. So my advice would > be to write these functions and store it to the "indivuals"-list like so: > > class Population(object): > def __init__(self, *individuals): > self.individuals = list(individuals) > > Then you can say: > p = Population(indiv1, indiv2, indiv3) > for individual in p.individual: > individual(whatever_your_problem) > > (Don't know if this is the way GA's are supposed to work) > > You can also create callable classes (that is, classes that implement > the __call__ method), and use instances of these as the individuals. For > example you can create a Permutation class that returns a permutation > (defined in it's __init__()) when it's __call__ method is called. (Am I > making sense?) > > This is just generic advice, maybe this helps and maybe it doesn't at > all. :) > > > > > I'm doing something similar with my crossover methods, by specifying > > them as functions in a module called Crossover, importing that, and > > defining > > > > crossover_function = getattr(Crossover, "%s_crossover" % xover) > > > > Where xover is a parameter defining the type of crossover to be used. > > I'm hoping there's some similar trick to accomplish what I want to do > > with chromosomes - or maybe I'm going about this completely the wrong > > way, trying to get Python to do something it's not made for. Any help/ > > feedback would be wonderful. > > > This isn't too bad, but for such things dictionaries are your Go-To > datatype. Just have a dictionary of xover-functions handy and call the > thusly: > > crossover_function = Crossover.function[xover] > > > > Thanks, > > Max Martin > If that helps :) > > regards > /W > > -- > http://mail.python.org/mailman/listinfo/python-list > From bignose+hates-spam at benfinney.id.au Thu Jan 24 16:16:09 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 25 Jan 2008 08:16:09 +1100 Subject: Reporting Python bugs (was: Can someone explain this unexpected raw_input behavior?) References: <13ff90c7-60ee-4306-8459-890a2b2b178a@e25g2000prg.googlegroups.com> Message-ID: <8763xi7wme.fsf_-_@benfinney.id.au> Mike Kent writes: > A bug issue has been opened in the Python Trac system for this. Wouldn't it be better to report it in the official Python bug tracker , which is Roundup, not Trac? -- \ "The right to use [strong cryptography] is the right to speak | `\ Navajo." -- Eben Moglen | _o__) | Ben Finney From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 21 13:15:29 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 19:15:29 +0100 Subject: Trouble writing to database: RSS-reader In-Reply-To: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> Message-ID: <4794e0f9$0$4429$426a74cc@news.free.fr> Arne a ?crit : > Hi! > > I try to make a rss-reader in python just for fun, and I'm almost > finished. Bad news : you're not. > I don't have any syntax-errors, but when i run my program, > nothing happends. > > This program is supposed to download a .xml-file, save the contents in > a buffer-file(buffer.txt) and parse the file looking for start-tags. > When it has found a start tag, it asumes that the content (between the > start-tag and the end-tag) is on the same line, Very hazardous assumption. FWIW, you can more safely assule this will almost never be the case. FWIW, don't assume *anything* wrt/ newlines when it comes to XML - you can even have newlines between two attributes of a same tag... > so then it removes the > start-tag and the end-tag and saves the content and put it into a > database. > > The problem is that i cant find the data in the database! If i watch > my program while im running it, i can see that it sucsessfuly > downloads the .xml-file from the web and saves it in the buffer. > > But I dont think that i save the data in the correct way, so it would > be nice if someone had some time to help me. > > Full code: http://pastebin.com/m56487698 > Saving to database: http://pastebin.com/m7ec69e1b > Retrieving from database: http://pastebin.com/m714c3ef8 1/ you don't need to make each and every variable an attribute of the class - only use attributes for what constitute the object state (ie: need to be maintain between different, possibly unrelated method calls). In your update_sql method, for exemple, beside self.connection and _eventually_ self.cursor, you don't need any attribute - local variables are enough. 2/ you don't need these Stored variables at all - just reset title/link/description to None *when needed* (cf below), then test these variables against None. 3/ learn to use if/elif properly !-) 4/ *big* logic flaw (and probably the first cause of your problem): on *each* iteration, you reset your Stored flags to False - whether you stored something in the database or not. Since you don't expect to have all there data on a single line (another wrong assumption : you might get a whole rss stream as one single big line), I bet you never write anything into the database . 5/ other big flaw : either use an autoincrement for your primary key - and *dont* pass any value for it in your query - or provide (a *unique*) id by yourself. 6/ FWIW, also learn to properly use the DB api - don't build your SQL query using string formatting, but pass the argument as a tuple, IOW: # bad: cursor.execute( '''INSERT INTO main VALUES(null, %s, %s, %s)''' % title, link, description ) # good (assuming you're using an autoincrementing key for your id) : cursor.execute( "INSERT INTO main VALUES(, , )", (title, link, description) ) NB : replace with the appropriate placeholder for your database - cf your db module documentation (usually either '?' or '%s') This will make the db module properly escape and convert values. 7/ str.replace() doesn't modify the string in-place (Python strings are immutable), but returns a new string. so you want: line = line.replace('x', 'y') 8/ you don't need to explicitely call connection.commit on each and every statement, and you don't need to call it at all on SELECT statements !-) 9/ have you tried calling print_rss *twice* on the same instance ?-) 10/ are you sure it's useful to open the same 'buffer.txt' file for writing *twice* (once in __init__, the other in update_sql). BTW, use open(), not file(). 11/ are you sure you need to use this buffer file at all ? 12/ are you really *sure* you want to *destroy* your table and recreate it each time you call your script ? > And yes, I know that there is rss-parseres already built, but this is > only for learning. This should not prevent you from learning how to properly parse XML (hint: with an XML parser). XML is *not* a line-oriented format, so you just can't get nowhere trying to parse it this way. HTH From bruno.desthuilliers at gmail.com Sat Jan 12 12:08:40 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jan 2008 09:08:40 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: On 10 jan, 03:10, Steven D'Aprano wrote: > On Wed, 09 Jan 2008 21:26:05 +0100, Bruno Desthuilliers wrote: > > hint: how can a compiler safely optimize anything in a language so > > dynamic that even the class of an object can be changed at runtime ? > > Is that a trick question? > Nope. Just an observation about the tradeoffs of dynamism. From skip at pobox.com Tue Jan 15 11:07:07 2008 From: skip at pobox.com (Skip Montanaro) Date: Tue, 15 Jan 2008 16:07:07 +0000 (UTC) Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: > > Why is that? Doesn't the |= operator essentially map to an update() call? > > No, according to 3.7 Set Types, s | t maps to s.union(t). I was asking about the |= assignment operator which according to the docs *does* map to the update method. Skip From Russ.Paielli at gmail.com Fri Jan 11 16:02:58 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Fri, 11 Jan 2008 13:02:58 -0800 (PST) Subject: split parameter line with quotes References: <9dd22f5e-5fda-42b9-b812-abb79db973fd@v67g2000hse.googlegroups.com> Message-ID: On Jan 11, 12:53 pm, "Russ P." wrote: > On Jan 11, 10:50 am, teddyber wrote: > > > Hello, > > > first i'm a newbie to python (but i searched the Internet i swear). > > i'm looking for some way to split up a string into a list of pairs > > 'key=value'. This code should be able to handle this particular > > example string : > > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > > i know i can do that with some regexp (i'm currently trying to learn > > that) but if there's some other way... > > > thanks > > The problem is that you are using commas for delimiters at two > different levels. > > I would start by replacing the commas between quotation marks with > some other delimiter, such as spaces of semicolons. To do that, step > through each character and keep a count of quotation marks. While the > count is odd, replace each comma with the selected alternative > delimiter. While the count is even, leave the comma. [An alternative > would be to replace the commas outside the quotation marks.] > > Once that is done, the problem is straightforward. Split the string on > commas (using string.split(",")). Then split each item in the list by > "=". Use the [0] element for the key, and use the [1] element for the > value (first stripping off the quotation marks if necessary). If you > need to further split each of the values, just split on whatever > delimiter you chose to replace the commas. One more point. Whoever chose the structure of the string you are parsing didn't do a very good job. If you know that person, you should tell him or her to use different delimiters at the different levels. Use commas for one level, and spaces or semicolons for the other level. Then you won't have to "correct" the string before you parse it. From bj_666 at gmx.net Sun Jan 27 07:51:47 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jan 2008 12:51:47 GMT Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> Message-ID: <603d33F1oh17aU5@mid.uni-berlin.de> On Sun, 27 Jan 2008 10:55:20 +0000, over wrote: > On Sat, 26 Jan 2008 14:47:50 +0100, Bjoern Schliessmann > wrote: > > The script is essentially gone. I'd like to know how to read the pyc > files, but that's getting away from my point that there is a link > between python scripts and assembler. At this point, I admit the code > above is NOT assembler, but sooner or later it will be converted to > machine code by the interpreter and the OS and that can be > disassembled as assembler. No it will not be converted to assembler. The byte code is *interpreted* by Python, not compiled to assembler. If you want to know how this happens get the C source code of the interpreter and don't waste your time with disassembling `python.exe`. C is much easier to read and there are useful comments too. Ciao, Marc 'BlackJack' Rintsch From bignose+hates-spam at benfinney.id.au Wed Jan 30 20:31:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 31 Jan 2008 12:31:29 +1100 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> <13q1132200cf537@corp.supernews.com> Message-ID: <87abmmok5q.fsf@benfinney.id.au> Peter Schuller writes: > I *DON'T* want anything to depend on the physical location on disk. Importing the code in the first place will ? unavoidably, it seems to me ? depend on the file location from which to load the module. After that, nothing depends on the physical location on disk, unless it's buggy. Imported modules are available from 'sys.modules', and that's where subsequent 'import' statements will find them, with no reference to file locations. > That was exactly what I was after from the beginning; a total > separation of location on disk from the location in the module > hiearachy. As you say, the location of the source should be an > implementation detail. That is exactly what I am after. It *is* an implementation detail, once the module is loaded from disk. -- \ "Philosophy is questions that may never be answered. Religion | `\ is answers that may never be questioned." ?anonymous | _o__) | Ben Finney From bignose+hates-spam at benfinney.id.au Sat Jan 12 08:47:56 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 13 Jan 2008 00:47:56 +1100 Subject: Great Python books for the beginner References: Message-ID: <87fxx3gnoz.fsf@benfinney.id.au> Landon writes: > I was wondering if anyone had any opinions on what other titles I > could look into since this one seems from a glance at reviews to be > teaching mainly through game programming (a topic I'm not too > interested in) or if this one is a quality book by itself. The book "Learning Python" is currently proving very useful to an associate of mine. I'm watching his knowledge of Python grow substantially every week, from what was an essentially zero start. Learning Python, 3rd Edition Mark Lutz O'Reilly Looking through the text, it is very well structured, thoroughly teaching all the fundamentals of the language and types and idioms while referring back to already-learned material. The author makes a living training people in Python, and the third edition has benefited from his many years of experience finding effective ways to teach the language. -- \ "If you ever teach a yodeling class, probably the hardest thing | `\ is to keep the students from just trying to yodel right off. | _o__) You see, we build to that." -- Jack Handey | Ben Finney From Luke.Visinoni at gmail.com Thu Jan 17 11:18:15 2008 From: Luke.Visinoni at gmail.com (Luke) Date: Thu, 17 Jan 2008 08:18:15 -0800 (PST) Subject: working with a subversion repo Message-ID: <7f156399-d9ae-4f13-a80f-0ffe41d89427@s12g2000prg.googlegroups.com> I want to write a script that automatically generates a subversion repository and configures apache serve the svn repo. Is there a python module that will allow me to work with subversion? I am able to import a module named "svn" on my ubuntu machine, but this module is not available on windows. I also can't seem to find any documentation on it. Thanks! From fredrik at pythonware.com Thu Jan 3 03:53:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 09:53:57 +0100 Subject: Manually installing PIL In-Reply-To: <001001c84dda$23d26760$2000a8c0@depid.local> References: <001001c84dda$23d26760$2000a8c0@depid.local> Message-ID: Jose Ignacio Gisbert wrote: > Does somebody install PIL manually??, I mean, copy directories manually > without executing setup.py. I saw an identical message from Guirai, but > I didn?t see any response. Thanks in advance! PIL's just a bunch of modules in a single PIL directory; you can put that directory (or the modules themselves) wherever you want. (if you're on windows, unzip the EXE installer to get the files) From theller at ctypes.org Mon Jan 21 15:42:59 2008 From: theller at ctypes.org (Thomas Heller) Date: Mon, 21 Jan 2008 21:42:59 +0100 Subject: ctypes CDLL - which paths are searched? In-Reply-To: <4794d573$0$2980$ba620e4c@news.skynet.be> References: <4794d573$0$2980$ba620e4c@news.skynet.be> Message-ID: Helmut Jarausch schrieb: > Hi, > > how can I specify the paths to be searched for a dynamic library > to be loaded by ctypes' CDLL class on a Linux system. > > Do I have to set os.environment['LD_LIBRARY_PATH'] ? > ctypes passes the argument given to CDLL(path) straight to the dlopen(3) call, so your system documentation should tell you. Thomas From caca at mailinator.com Mon Jan 7 06:44:21 2008 From: caca at mailinator.com (caca at mailinator.com) Date: Mon, 7 Jan 2008 03:44:21 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> <617182dc-3ca1-4cf5-b1ca-1779dd8d6550@i3g2000hsf.googlegroups.com> Message-ID: <151627bb-8600-4552-b50d-29b04fab3094@l1g2000hsa.googlegroups.com> > Just for fun, I profiled my answer versus the final answer... This mailing list is awesome! PS:ajaksu, I have to leave now, I hope bukzor's answer was enough to you (at least for the moment) From bladedpenguin at gmail.com Fri Jan 25 02:04:42 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Thu, 24 Jan 2008 23:04:42 -0800 (PST) Subject: global/local variables References: <13pia51grjfo2ed@corp.supernews.com> Message-ID: <4d161c89-7e33-4ddc-851f-bc9beb537229@q21g2000hsa.googlegroups.com> On Jan 24, 7:09 pm, Steven D'Aprano wrote: > On Thu, 24 Jan 2008 15:37:09 -0800, Tim Rau wrote: > > What makes python decide whether a particular variable > > is global or local? > > For starters, if the line of code is not inside a class or function, that > is, it's at the top level of a module, it is global. > > More interesting is if it is inside a function or class. If you assign to > the name in the function, Python assumes it is local *unless* you have > defined it as global with the global statement. > > Otherwise, Python will treat it as global. > > > I've got a list and a integer, both defined at top level, no > > indentation, right next to each other: > > > allThings = [] > > nextID = 0 > > > and yet, in the middle of a function, python sees one and doesn't see > > the other: > > I've tried to run your code -- and it isn't easy, involving much > backwards-and-forwards copying and pasting, thanks to word-wrap in you > post -- and the error I get is: > > SyntaxError: invalid syntax > > because you left off the colon from the first if statement. > > I'm not especially inclined to start hunting through your code fixing any > other errors in order to find the error you think you're getting. How > about if you quote the exception traceback you actually get? > > > I don't think it's important, but the function is defined before > > the two globals. > > Nope, not important. What's important is whether the function is *called* > before or after the globals are created. That's been my experience so far. > > If you're using global variables in your code, you probably should stop. > As a general rule, global variables are poor programming practice for a > number of reasons. Google on "Global variables considered harmful" for > some examples. > > -- > Steven I'm sorry: I forgot to say what my problem was. Python seems to think that nextID is a local, and complains that it can't find it. THis is not the full text of the function, just the level that is causing errors. the lack of : on the if is a transcription error. Traceback (most recent call last): File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox \sandbox.py", line 248, in thing.step() File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox \sandbox.py", line 112, in step allThings[len(allThings)-1].id = nextID UnboundLocalError: local variable 'nextID' referenced before assignment I want to know why it says 'local variable' it never had a problem when just allThings was in there. as for the objection to global variable: If I didn't make them global, I'd make them part of a singleton class called gameVars that would get passed everywhere. It's unlikely that they'll get mixed in with anyhting else, as they fulfill a unique function. Also, I think it's more convenient, and I am, after all, my own employer when it comes to programming. From nikbaer at gmail.com Tue Jan 29 14:06:36 2008 From: nikbaer at gmail.com (nik) Date: Tue, 29 Jan 2008 11:06:36 -0800 (PST) Subject: ISO with timezone References: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Message-ID: <82906208-c7ad-49c3-a91f-851add8cd6cd@s19g2000prg.googlegroups.com> On Jan 29, 10:56 am, nik wrote: > Thanks, > that does help and now I have: > > >>> from datetime import datetime, tzinfo, timedelta > >>> import time > >>> class TZ(tzinfo): > > ... def utcoffset(self,dt): return timedelta(seconds=time.timezone) > ...>>> print datetime(2008,2,29,15,30,11,tzinfo=TZ()).isoformat() > > 2008-02-29T15:30:11+8:00 > > But what I want to know now it how to get the actual time into the > expression instead of typing the 2008,2,29,15.... > So something like: >>> print > datetime(time.gmtime(),tzinfo=TZ()).isoformat(), but that doesn't > work. > > I realize that I could do: > > >>> t = time.localtime() > >>> print datetime(t[0],t[1],t[2],t[3],t[4],t[5],tzinfo=TZ()).isoformat() > > but I imagine there might be a cleaner way of doing this. > > Thanks, > Nik > > On Jan 28, 9:10 pm, "Nicholas F. Fabry" > wrote: > > > Hello, nik. > > > On Jan 28, 2008, at 21:03, nik wrote: > > > > Hi, > > > > How does one express the time in ISO format with the timezone > > > designator? > > > > what I want is YYYY-MM-DDThh:mm:ss.sTZD > > > >> From the documentation I see: > > >>>> from datetime import tzinfo, timedelta, datetime > > >>>> class TZ(tzinfo): > > > ... def utcoffset(self, dt): return timedelta(minutes=-399) > > > ... > > >>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') > > > '2002-12-25 00:00:00-06:39' > > > > and I've also figured out: > > >>>> datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3] > > > '2008-01-23T11:22:54.130' > > > > But can't figure out how to fit them together. > > > There is nothing there to 'fit together' - in the first example given, > > the datetime object has no time component specified, so it fills in > > default vaules of zero. The following should make this clear: > > > >>> your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ()) > > >>> print your_time > > 2008-02-29 15:30:11-05:00 > > >>> print your_time.isoformat('T') > > 2008-02-29T15:30:11-05:00 > > > If you wish to append the NAME of the tzinfo object instead of its > > offset, that requires a bit more playing around (along with a properly > > defined tzinfo object - check out dateutil or pytz for a concrete > > implementation of tzinfo subclasses (i.e. timezones)), but the > > following would work: > > > >>> print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z') > > 2008-02-29T15:30:11 EST > > > For details on how the .strftime method works, see Python Standard > > Library, Section 14.2. > > > I hope this helps! > > > Nick Fabry > > > > Thank you, > > > Nik > > > -- > > >http://mail.python.org/mailman/listinfo/python-list From deets at nospam.web.de Tue Jan 22 07:18:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 13:18:05 +0100 Subject: possible to overide setattr in local scope? References: <9dac9675-992e-4dc5-b085-06f0811939ca@1g2000hsl.googlegroups.com> Message-ID: <5vm57tF1m6cucU1@mid.uni-berlin.de> glomde wrote: > In a class it is poosible to override setattr, so that you can decide > how you should > handle setting of variables. > > Is this possible to do outside of an class on module level. > > mysetattr(obj, var, value): > print "Hello" > > So that > > test = 5 > > > would print > Hello No, that's not possible. What you could do instead is to create a singlton that you use to store the values in, instead of the module directly. Like this (untested): class ModuleState(object): # borg pattern - why not... _shared_state = {} def __init__(self): self.__dict__ = ModuleState._shared_state def __setattr__(self, name, value): setattr(self, name, "hello") state = ModuleState() Then you do state.test = 5 Diez From deets at nospam.web.de Mon Jan 21 12:08:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Jan 2008 18:08:42 +0100 Subject: building psycopg2 on windows using mingw, "cannot find -lpq" References: Message-ID: <5vk1sqF1mal8qU1@mid.uni-berlin.de> GHUM wrote: > The compile works, BUT linking fails: > > 2.5\Release\psycopg\_psycopg.def -Lc:\python25\libs -Lc: > \python25\PCBuild -Lc:/p > ostgres/83RC2/lib -lpython25 -lpq -lws2_32 -ladvapi32 -o build > \lib.win32-2.5\psy > copg2\_psycopg.pyd > c:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: > cannot find -lpq > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 > > if I google for the error > > "ld.exe: cannot find -lpq" > > there is allways the information that the lib-dir of libpq is missing; > but : > > -Lc:/postgres/83RC2/lib > > is clearly in the commandline, and within c:/postgres/83RC2/lib > there is one libqp.lib > > What am I missing? any hints? Are you sure using forward slashes in the path works here? Diez From mobiledreamers at gmail.com Tue Jan 8 19:26:54 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Tue, 8 Jan 2008 16:26:54 -0800 Subject: Spaces and tabs messing up code Message-ID: my friend uses vim and i use xemacs so our shared python code is a mix of tabs and spaces and it is hard for him to edit it in vim any idea on how to make it clean convert it all to 4 spaces? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas.troeger.ext at siemens.com Thu Jan 10 08:10:05 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 10 Jan 2008 14:10:05 +0100 Subject: Embedding python code into text document question. Message-ID: Dear all, I've written a program that parses a string or file for embedded python commands, executes them and fills in the returned value. The input might look like this: process id: $$return os.getpid()$$ current date: $$return time.ctime()$$ superuser: $$ if os.geteuid(): return "Yes" else: return "No"$$ I've tried several solutions using eval, execfile or compile, but none of those would solve my problem. Does anyone have a solution that works? Any suggestions? Any help will be appreciated :) Regards, Thomas. From gagsl-py2 at yahoo.com.ar Thu Jan 24 02:29:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 Jan 2008 05:29:38 -0200 Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> Message-ID: En Thu, 24 Jan 2008 04:52:22 -0200, glacier escribi?: > According to your reply, what will happen if I try to decode a long > string seperately. > I mean: > ###################################### > a='???'*100000 > s1 = u'' > cur = 0 > while cur < len(a): > d = min(len(a)-i,1023) > s1 += a[cur:cur+d].decode('mbcs') > cur += d > ###################################### > > May the code above produce any bogus characters in s1? Don't do that. You might be splitting the input string at a point that is not a character boundary. You won't get bogus output, decode will raise a UnicodeDecodeError instead. You can control how errors are handled, see http://docs.python.org/lib/string-methods.html#l2h-237 -- Gabriel Genellina From apardon at forel.vub.ac.be Tue Jan 22 07:23:32 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 22 Jan 2008 12:23:32 GMT Subject: assigning values in python and perl References: <18c1e5f20801161934m69ff44edo1e35f5381f7d2928@mail.gmail.com> Message-ID: On 2008-01-17, Steven D'Aprano wrote: > On Thu, 17 Jan 2008 11:40:59 +0800, J. Peng wrote: > >> May I ask, python's pass-by-reference is passing the object's reference >> to functions, but perl, or C's pass-by-reference is passing the variable >> itself's reference to functions. So althought they're all called >> pass-by-reference,but will get different results.Is it? > > Python is not call by reference. > > Any book or person that says it is, is wrong to do so. > > Python's function call semantics are not the same as C, or Perl, or > Pascal. They are, however, similar to those of Lisp, Scheme, Emerald and > especially CLU. It is neither pass by reference, nor pass by value. I don't think it is the function call semantics that are so different as it is the assignment itself that is different. an assignment in C, doesn't bind a new object to the name, but stores new information in the object. Trying to explain the different behaviour of C and python of examples calling function that assign to a parameter, without explaining how the assignment works will IMO not give people enough to understand what is happening. -- Antoon Pardon From basilisk96 at gmail.com Fri Jan 11 01:56:18 2008 From: basilisk96 at gmail.com (Basilisk96) Date: Thu, 10 Jan 2008 22:56:18 -0800 (PST) Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <496d868e-09a5-4410-bbfc-b382ce6f0587@f10g2000hsf.googlegroups.com> On Jan 10, 10:36 pm, Marty wrote: > Hrvoje Niksic wrote: > > Mike Meyer writes: > > >> It sounds to me like your counter variable actually has meaning, > > > It depends how the code is written. In the example such as: > > > for meaningless_variable in xrange(number_of_attempts): > > ... > > > the loop variable really has no meaning. Rewriting this code only to > > appease pylint is exactly that, it has nothing with making the code > > more readable. > > >> you've hidden that meaning by giving it the meaningless name "i". If > >> you give it a meaningful name, then there's an obvious way to do it > >> (which you listed yourself): > > >> while retries_left: > > [...] > > > This loop contains more code and hence more opportunities for > > introducing bugs. For example, if you use "continue" anywhere in the > > loop, you will do one retry too much. > > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) > > This caused me to wonder why Python does not have a "foreach" statement (and > also why has it not come up in this thread)? I realize the topic has probably > been beaten to death in earlier thread(s), but does anyone have the short answer? But it does: data_in = (1,2,3,4,5) data_out = [] data_out += [[] for blah in data_in] print data_out [[], [], [], [], []] Cheers, -Basilisk96 From bladedpenguin at gmail.com Wed Jan 23 07:13:21 2008 From: bladedpenguin at gmail.com (bladedpenguin at gmail.com) Date: Wed, 23 Jan 2008 04:13:21 -0800 (PST) Subject: Removing objects References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> Message-ID: On Jan 23, 2:24 am, Robert Kern wrote: > bladedpeng... at gmail.com wrote: > > I am writing a game, and it must keep a list of objects. I've been > > representing this as a list, but I need an object to be able to remove > > itself. It doesn't know it's own index. If I tried to make each object > > keep track of it's own index, it would be invalidated when any object > > with a lower index was deleted. The error was that when I called > > list.remove(self), it just removed the first thing in hte list with > > the same type as what I wanted, rather than the object I wanted. The > > objects have no identifying charachteristics, other than thier > > location in memory > > By default, classes that do not implement the special methods __eq__ or __cmp__ > get compared by identity; i.e. "(x == y) == (x is y)". Double-check your classes > and their super-classes for implementations of one of these methods. > mylist.remove(x) will check "x is mylist[i]" first and only check "x == > mylist[i]" if that is False. > > In [1]: class A(object): > ...: def __eq__(self, other): > ...: print '%r == %r' % (self, other) > ...: return self is other > ...: def __ne__(self, other): > ...: print '%r != %r' % (self, other) > ...: return self is not other > ...: > ...: > > In [2]: As = [A() for i in range(10)] > > In [3]: As > Out[3]: > [<__main__.A object at 0xf47f70>, > <__main__.A object at 0xf47d90>, > <__main__.A object at 0xf47db0>, > <__main__.A object at 0xf47cb0>, > <__main__.A object at 0xf47eb0>, > <__main__.A object at 0xf47e70>, > <__main__.A object at 0xf47cd0>, > <__main__.A object at 0xf47e10>, > <__main__.A object at 0xf47dd0>, > <__main__.A object at 0xf47e90>] > > In [4]: A0 = As[0] > > In [5]: A0 > Out[5]: <__main__.A object at 0xf47f70> > > In [6]: As.remove(A0) > > In [7]: As > Out[7]: > [<__main__.A object at 0xf47d90>, > <__main__.A object at 0xf47db0>, > <__main__.A object at 0xf47cb0>, > <__main__.A object at 0xf47eb0>, > <__main__.A object at 0xf47e70>, > <__main__.A object at 0xf47cd0>, > <__main__.A object at 0xf47e10>, > <__main__.A object at 0xf47dd0>, > <__main__.A object at 0xf47e90>] > > In [8]: A0 > Out[8]: <__main__.A object at 0xf47f70> > > In [9]: A9 = As[-1] > > In [10]: As.remove(A9) > <__main__.A object at 0xf47d90> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47db0> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47cb0> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47eb0> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47e70> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47cd0> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47e10> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47dd0> == <__main__.A object at 0xf47e90> > > In [11]: As > Out[11]: > [<__main__.A object at 0xf47d90>, > <__main__.A object at 0xf47db0>, > <__main__.A object at 0xf47cb0>, > <__main__.A object at 0xf47eb0>, > <__main__.A object at 0xf47e70>, > <__main__.A object at 0xf47cd0>, > <__main__.A object at 0xf47e10>, > <__main__.A object at 0xf47dd0>] > > In [12]: A9 > Out[12]: <__main__.A object at 0xf47e90> > > If you cannot find an implementation of __eq__ or __cmp__ anywhere in your code, > please try to make a small, self-contained example like the one above but which > demonstrates your problem. > > > So my question: How do I look something up in a list by it's location > > in memory? does python even support pointers? > > If you need to keep an __eq__ that works by equality of value instead of > identity, then you could keep a dictionary keyed by the id() of the object. That > will correspond to its C pointer value in memory. > > In [13]: id(A9) > Out[13]: 16023184 > > In [14]: hex(_) > Out[14]: '0xf47e90' > > > Is there a better way? > > Possibly. It looks like you are implementing a cache of some kind. Depending on > exactly how you are using it, you might want to consider a "weak" dictionary > instead. A weak dictionary, specifically a WeakValueDictionary, acts like a > normal dictionary, but only holds a weak reference to the object. A weak > reference does not increment the object's reference count like a normal > ("strong") reference would. Consequently, once all of the "strong" references > disappear, the object will be removed from the WeakValueDictionary without your > having to do anything explicit. If this corresponds with when you want the > object to be removed from the cache, then you might want to try this approach. > Use "id(x)" as the key if there is no more meaningful key that fits your > application. > > http://docs.python.org/lib/module-weakref.html > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco So, in general, is it more efficient to use a dictionary or to override the __eq__ function? From guptaabhishek1983 at gmail.com Tue Jan 8 01:18:41 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Mon, 7 Jan 2008 22:18:41 -0800 (PST) Subject: web service between python and c# Message-ID: <12f6e713-392e-4fda-8354-51a8337d77dc@l6g2000prm.googlegroups.com> Hello group i need to make a web service to work between python and c# . Where python would server as backend (server) preferebly cherrypy (turbogears) and client would be on a c# appln. I have developed a webservice using TGWebServices package which runs on top of turbogears. but have no idea on how to interface it with c# client. Thank YOu From mwm at mired.org Fri Jan 11 11:57:03 2008 From: mwm at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 11:57:03 -0500 Subject: How to POST call and retrieve result page In-Reply-To: <16314edc0801110114t346bca6ek71660132de60b91e@mail.gmail.com> References: <16314edc0801110114t346bca6ek71660132de60b91e@mail.gmail.com> Message-ID: <20080111115703.16dbabd7@mbook.mired.org> On Fri, 11 Jan 2008 14:44:19 +0530 "suyash jape" wrote: > Hi all > i want to access a web page through python script, fillup the necessary > fields, > and press submit button (which does POST call) and retrieve the result page > and retrieve some values from it. > > Here is the script i have written till now. > > >import urllib2 > > # create array of name/value pairs > > self.params = urllib.urlencode({'seqname': 'BioSequence', 'sequence': > 'ATACATTATCCAAACATAAAAAGCATGGCTT'}) > > > > # send http-post > > request = urllib.urlopen("http://www.hydrazome.metazome.net/search.php", > params) > > > > # read back each line of reply > > line = request.read() > >print line > > This script fills up the correct values in the search.php page.But i am not > sure if it is doing the POST (submit call). > Beacause in 'line' varialble, i am getting the search.php page.Not the > result page which is blast_results.php. > > How to retrieve the result page? Sounds like you're not POSTing to the right page. The form on .../search.php lets you fill in values, but those values are not necessarily POSTed to search.php. In particular, the form element has an action attribute that has a URL to which the values on the page should be posted. If that points to .../blast_results.php, then that's the page you need to pass to urlopen with your data. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From ptmcg at austin.rr.com Wed Jan 2 03:50:15 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 2 Jan 2008 00:50:15 -0800 (PST) Subject: pyparsing question References: <8df809a0-1950-4250-a968-2d366f64cdb4@d21g2000prf.googlegroups.com> Message-ID: <8a68b387-01c9-4dc7-8a48-3fb146395ea7@n20g2000hsh.googlegroups.com> On Jan 1, 5:32?pm, hubritic wrote: > I am trying to parse data that looks like this: > > IDENTIFIER ? ?TIMESTAMP ? T ?C ? RESOURCE_NAME ? DESCRIPTION > 2BFA76F6 ? ? 1208230607 ? T ? S ? SYSPROC ? ? ? ? ? ? ? ? ? ?SYSTEM > SHUTDOWN BY USER > A6D1BD62 ? 1215230807 ? ? I > H ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Firmware Event > > The data I have has a fixed number of characters per field, so I could > split it up that way, but wouldn't that defeat the purpose of using a > parser? ? I think you have this backwards. I use pyparsing for a lot of text processing, but if it is not a good fit, or if str.split is all that is required, there is no real rationale for using anything more complicated. > I am determined to become proficient with pyparsing so I am > using it even when it could be considered overkill; thus, it has gone > past mere utility now, this is a matter of principle! > Well, I'm glad you are driven to learn pyparsing if it kills you, but John Machin has a good point. This data is really so amenable to something as simple as: for line in logfile: id,timestamp,t,c resource_and_description = line.split(None,4) that it is difficult to recommend pyparsing for this case. The sample you posted was space-delimited, but if it is tab-delimited, and there is a pair of tabs between the "H" and "Firmware Event" on the second line, then just use split("\t") for your data and be done. Still, pyparsing may be helpful in disambiguating that RESOURCE_NAME and DESCRIPTION text. One approach would be to enumerate (if possible) the different values of RESOURCE_NAME. Something like this: ident = Word(alphanums) timestamp = Word(nums,exact=10) # I don't know what these are, I'm just getting the values # from the sample text you posted t_field = oneOf("T I") c_field = oneOf("S H") # I'm just guessing here, you'll need to provide the actual # values from your log file resource_name = oneOf("SYSPROC USERPROC IOSUBSYS whatever") logline = ident("identifier") + timestamp("time") + \ t_field("T") + c_field("C") + \ Optional(resource_name, default="")("resource") + \ Optional(restOfLine, default="")("description") Another tack to take might be to use a parse action on the resource name, to verify the column position of the found token by using the pyparsing method col: def matchOnlyAtCol(n): def verifyCol(strg,locn,toks): if col(locn,strg) != n: raise ParseException(strg,locn,"matched token not at column %d" % n) return verifyCol resource_name = Word(alphas).setParseAction(matchOnlyAtCol(35)) This will only work if your data really is columnar - the example text that you posted isn't. (Hmm, I like that matchOnlyAtCol method, I think I'll add that to the next release of pyparsing...) Here are some similar parsers that might give you some other ideas: http://pyparsing.wikispaces.com/space/showimage/httpServerLogParser.py http://mail.python.org/pipermail/python-list/2005-January/thread.html#301450 In the second link, I made a similar remark, that pyparsing may not be the first tool to try, but the variability of the input file made the non-pyparsing options pretty hairy-looking with special case code, so in the end, pyparsing was no more complex to use. Good luck! -- Paul From richard at pyweek.org Thu Jan 31 16:11:34 2008 From: richard at pyweek.org (richard at pyweek.org) Date: Fri, 1 Feb 2008 08:11:34 +1100 Subject: PyWeek 6 is coming! Message-ID: <200802010811.34973.richard@pyweek.org> 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 at http://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/ From kyosohma at gmail.com Fri Jan 18 17:17:33 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jan 2008 14:17:33 -0800 (PST) Subject: Core Python Programming . . . References: <7xir1q29j5.fsf@ruckus.brouhaha.com> Message-ID: On Jan 18, 1:55 pm, Paul Rubin wrote: > FireNWater writes: > > 1) convert a 4-digit Integer (WXYZ) to an IP address (WWW.XXX.YYY.ZZZ) > > > or > > > 2) convert an 8-digit Integer (WWWXXXYYYZZZ) to (WWW.XXX.YYY.ZZZ) > > > Thanks for anyone with the clue!!! > > Without being able to see the exercise I suspect it's turn a 4-byte > string (i.e. 32 bits) into an IP address (int8.int8.int8.int8). > Or, it might be turn a 32-bit int into such an address. I've got the book and I think the OP may be referring to this: 6-11 Conversion. (a) Create a program that will convert from an integer to an Internet Protocol (IP) address in the four-octet format of WWW.XXX.YYY.ZZZ (b) Update your program to be able to do the vice verse of the above. It could be a 12 digit int...or it could be what you (Paul) are referring to. Mike From aisaac at american.edu Fri Jan 25 11:56:44 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 25 Jan 2008 16:56:44 GMT Subject: find minimum associated values Message-ID: I have a small set of objects associated with a larger set of values, and I want to map each object to its minimum associated value. The solutions below work, but I would like to see prettier solutions... Thank you, Alan Isaac =================================================================== import time, random from itertools import groupby from collections import defaultdict class Pass: pass # arbitrary setup keys = [Pass() for i in range(10)]*3 vals = [random.random() for i in range(30)] kv = zip(keys,vals) random.shuffle(kv) #OBJECTIVE: # find minimum val associated with each "key" in kv print "method 1: brute force" t=time.clock() d = dict() for k,v in kv: if k in d: if d[k] > v: d[k] = v else: d[k] = v print time.clock()-t print d print print "method 2: groupby" t=time.clock() d = dict() kv_sorted = sorted(kv, key=lambda x: id(x[0])) for k, g in groupby( kv_sorted, key=lambda x: x[0] ): d[k] = min(gi[1] for gi in g) print time.clock()-t print d print print "method 3: defaultdict" t=time.clock() d = defaultdict(list) for k,v in kv: d[k].append(v) for k in d: d[k] = min(d[k]) print time.clock()-t print d From workitharder at gmail.com Sat Jan 5 16:45:16 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 5 Jan 2008 13:45:16 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <477fba91$0$8348$9b622d9e@news.freenet.de> Message-ID: On Jan 5, 9:12 am, "Martin v. L?wis" wrote: > > Any other ideas? > > How about this: > > def random_pick(list, property): > L = len(list) > pos = start = random.randrange(L) > while 1: > x = list[pos] > if property(x): return x > pos = (pos + 1) % L > if pos == start: > raise ValueError, "no such item" > > Regards, > Martin I thought about this, but in the sequence "00012" (and property = bool) the 1 will be returned four times as often as the 2. Maybe that's ok... From fredrik at pythonware.com Sun Jan 27 13:27:19 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Jan 2008 19:27:19 +0100 Subject: python regex: misbehaviour with "\r" (0x0D) as Newline character in Unicode Mode In-Reply-To: <479C6B56.5030402@sanusi.de> References: <479C6B56.5030402@sanusi.de> Message-ID: Arian Sanusi wrote: > concerning to unicode, "\n", "\r "and "\r\n" (0x000A, 0x000D and 0x000D+0x000A) should be threatened as newline character the link says that your application should treat them line terminators, not that they should all be equal to a new line character. to split on Unicode line endings, use the splitlines method. for the specific characters you mention, you can also read the file in universal mode. From rschroev_nospam_ml at fastmail.fm Fri Jan 25 03:44:47 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 25 Jan 2008 08:44:47 GMT Subject: Test driven development In-Reply-To: <273268bb-421f-4228-a16b-a64ea38869b8@m34g2000hsf.googlegroups.com> References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> <53bae618-0a57-470e-b698-3f936ef7c0e7@s12g2000prg.googlegroups.com> <98f3ca4c-a7f0-4707-b09d-8012b86de96b@x69g2000hsx.googlegroups.com> <273268bb-421f-4228-a16b-a64ea38869b8@m34g2000hsf.googlegroups.com> Message-ID: <3khmj.45198$k72.3681428@phobos.telenet-ops.be> alex23 schreef: > On Jan 25, 5:44 am, Roel Schroeven > wrote: >> I guess I just need to try somewhat harder to use TDD in my daily >> coding. Apart from books, are there other resources that can help >> beginners with TDD? Mailing lists, forums, newsgroups possibly? > > There's the Testing-in-Python mailing list. It's pretty low traffic > but generally relevant: > > http://lists.idyll.org/listinfo/testing-in-python Thank you, I'll have a look at it. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From ejensen at visi.com Fri Jan 11 11:23:46 2008 From: ejensen at visi.com (Ed Jensen) Date: Fri, 11 Jan 2008 16:23:46 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> Message-ID: <13of60ikspqhh06@corp.supernews.com> Bruno Desthuilliers wrote: > fact 1: CPython compiles source code to byte-code. > fact 2: CPython executes this byte-code. > fact 3: Sun's JDK compiles source code to byte-code. > fact 4: Sun's JDK executes this byte-code. > > Care to prove me wrong on any of these points ? Don't bother: you can't. > So my first assertion that "CPython is compiled to byte-code, which is > then executed by a VM" is true, and since the same assertion also stands > for Java (ie: sun's JDK), then the "just like" qualifier is true too. > Period. #2 and #4 are wrong (or, at best, misleading). Here, I'll fix them for you: Fact 2: CPython interprets the bytecode. Fact 4: Sun's JVM does some interpretation of the bytecode, but also compiles some of the bytecode to native code and executes the resulting native code. These distinctions can be important and it's intellectually dishonest to gloss over them. From arnodel at googlemail.com Tue Jan 8 16:59:37 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 8 Jan 2008 13:59:37 -0800 (PST) Subject: mod-python on Mac OSX 10.5 References: <4782fe18$0$26015$88260bb3@free.teranews.com> Message-ID: <7f9cef14-6d94-4a6b-a843-58ee9e4e4f60@i3g2000hsf.googlegroups.com> On Jan 8, 5:27?am, Gnarlodious wrote: > I am trying to install mod_python on OSX 10.5, Intel version. > > sudo apachectl configtest tells me this: > > httpd: Syntax error on line 114 of /private/etc/apache2/httpd.conf: > Cannot load /usr/libexec/apache2/mod_python.so into server: > dlopen(/usr/libexec/apache2/mod_python.so, 10): no suitable image > found. Did find:\n\t/usr/libexec/apache2/mod_python.so: mach-o, but > wrong architecture > > I attempted to follow instructions found on these pages but it didn't work: > > > > > > Can > > anyone tell me what is causing this error? (Sorry no time to read the references you provide) This is because httpd is running in 64 bits (arch x86_64) but mod_python.so is only 32 bits by default. You need to modify this. what I did was: make the following changes to src/Makefile: * Add -arch x86_64 to the LDFLAGS line * Change the build line in mod_python.so to: $(APXS) $(INCLUDES) -c -Wc,"-arch x86_64" $(SRCS) $(LDFLAGS) $ (LIBS) Now that I look at this, I don' know if both are necessary... But it worked for me. There was a discussion to the mod_python mailing list in october 2007: http://www.modpython.org/pipermail/mod_python/2007-October/ -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 02:45:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 27 Jan 2008 07:45:29 -0000 Subject: Using a dict as if it were a module namespace Message-ID: <13podkpqqvef674@corp.supernews.com> I have a problem which I think could be solved by using a dict as a namespace, in a similar way that exec and eval do. When using the timeit module, it is very inconvenient to have to define functions as strings. A good alternative is to create the function as normal, and import it: def myfunc(x, y): return x+y timeit.Timer("myfunc(59, 60)", "from __main__ import myfunc").timeit() Not only is this an easy idiom to follow, but myfunc can live in another module: just replace __main__ with the module name. Now, I'm trying to build a suite of tests to use with timeit. I have a bunch of tests which I've created as dicts: test_suite= [dict(x=59, y=60), dict(x=-1, y=-2)] What I *think* I want to do is use the from ... import idiom to grab arguments from the dicts as if they were modules, but this doesn't work: expr = "myfunc(x, y)" for test in test_suite: setup = "from __main__ import myfunc; from test import x, y" t = timeit.Timer(expr, setup).timeit() Even if the Timer could see test, it is not a module and you can't import from it. Naturally. Alternatives that I have found: (1) Import the test and grab the values needed from it: setup = """from __main__ import myfunc, test x, y = test['x'], test['y']""" I don't like this one. It doesn't seem very elegant to me, and it gets unwieldy as the complexity increases. Every item I need from test has to be named twice, violating the principle Don't Repeat Yourself. If the tests change, the setup string has to be explicitly changed also. (2) Mess with the global namespace: globals().update(t) setup = "from __main__ import myfunc" I don't like this one. It looks hackish, and I worry about conflicts and side-effects. If it works (and I haven't tested it) it relies on an implementation detail of timeit.Timer.__init__, namely the line "exec code in globals(), ns". Worst of all, it pollutes or even mangles the global namespace of the calling code, not the code being tested. (3) Explicitly pass a namespace dict to the Timer class, possibly even getting rid of setup altogether: test['myfunc'] = myfunc t = timeit.Timer(expr, '', ns=test).timeit() This would be the most elegant solution, but at this time it is completely hypothetical. Timer does not have that functionality. (4) Dump the test data straight into the setup string: setup = "from __main__ import myfunc; x = %(x)s; y = %(y)s" % t Again, unwieldy and against DRY. The additional disadvantage is that there are many types of test data that can't be converted to and from strings like that. What do others think? Have I missed something? What other alternatives are there? -- Steven From pavlovevidence at gmail.com Mon Jan 14 19:38:56 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 14 Jan 2008 16:38:56 -0800 (PST) Subject: module naming conventions References: <7f39199a-3334-4bcc-a424-5102f042ed01@1g2000hsl.googlegroups.com> Message-ID: On Jan 14, 11:44 am, grackle wrote: > Obviously Java-style naming is a mistake in Python, since top-level > names have to be unique. Is there a standard naming convention to > facilitate mixing code from different sources, such as > mygroupname_modulename? Is there a best practices guide for module > naming? Not really. Try to pick a unique name for your project. <:\ Carl Banks From bronger at physik.rwth-aachen.de Wed Jan 2 02:15:34 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 02 Jan 2008 08:15:34 +0100 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au> <87bq85rp2d.fsf@physik.rwth-aachen.de> <87abnoc13h.fsf@benfinney.id.au> Message-ID: <87lk78hf55.fsf@physik.rwth-aachen.de> Hall?chen! Ben Finney writes: > Torsten Bronger writes: > >> [...] the width of a tab is nowhere defined. It really is a >> matter of the editor's settings. > > RFC 678 "Standard File Formats" > : > > Horizontal Tab > > [...] As far as I can see, this excerpt of a net standard has been neither normative nor influential on the behaviour of text editors. >> I, for example, dislike too wide indenting. I use four columns in >> Python and two in Delphi. However, there are Python projects >> using eight spaces for each indentation level. > > How many columns to indent source code is an orthogonal question > to how wide an ASCII TAB (U+0009) should be rendered. [...] I don't know what you want to say with this. Obviousy, it is impossible to indent four columns with 8-columns tabs. Anyway, my sentence was supposed just to lead to the following: >> If all Python code used tabs, everybody could use their own >> preferences, for both reading and writing code, and >> interoperability would be maintained nevertheless. > > Interoperability isn't the only criterion though. On the contrary, > source code is primarily for reading by programmers, and only > incidentally for reading by the compiler. Well, I, the programmer, want code snippets from different origins fit together as seemlessly as possible, and I want to use my editor settings for every piece of Python code that I load into it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From nagle at animats.com Sun Jan 20 22:32:52 2008 From: nagle at animats.com (John Nagle) Date: Sun, 20 Jan 2008 19:32:52 -0800 Subject: Is there a portable way to tell if data is available on a pipe? Message-ID: <47941112$0$36375$742ec2ed@news.sonic.net> I need some way to find out if a pipe has data available for a read without blocking if it does not. "select", unfortunately, doesn't work on pipes on Windows. I think there's something proposed for Python 3000, but that's not useful now. I'd like to avoid having a thread to manage each pipe, but if I have to, so be it. John Nagle From jzgoda at o2.usun.pl Tue Jan 15 06:43:39 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 15 Jan 2008 12:43:39 +0100 Subject: MySQL-python-1.2.2 install with no mysql In-Reply-To: References: <14836669.post@talk.nabble.com> Message-ID: washakie napisa?(a): > Okay, I've installed mysql then using yum... it installed the same version > running on another machine with identical python where all works well... but > now I get this error during build... thoughts?!?? mysql_config is there, and > the site.cfg file is pointing correctly to it... : You need to install -dev package too. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From steven at REMOVE.THIS.cybersource.com.au Wed Jan 16 21:35:39 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 17 Jan 2008 02:35:39 -0000 Subject: import from question References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> <478d04d4$0$26042$88260bb3@free.teranews.com> <87tzleb2st.fsf@benfinney.id.au> <478E658A.9070003@tobiah.org> <87prw1bftx.fsf@benfinney.id.au> <478e87f6$0$26054$88260bb3@free.teranews.com> Message-ID: On Wed, 16 Jan 2008 15:31:54 -0800, Tobiah wrote: >> Again, those aren't copies. There is only one instance of each value, >> referenced by multiple names. > > > Ok, I get it. I was locally importing a pointer to an integer Really? What language were you using? Python doesn't have pointers. Some *implementations* of Python (e.g. CPython) might have pointers *in the implementation*, but others (e.g. PyPy, Jython) don't. > which is > really the same object as the module name points to, but the assignment > changes that. The confusion for me centered around the fact that a local > name can be used to change values in mutables that are visible from > within the module. This however, does not include assignment to the > local name. If you haven't already done so, you should read: http://effbot.org/zone/python-objects.htm http://effbot.org/zone/call-by-object.htm and remember that imports are (more or less) equivalent to assignments. When you do this: >>> import module it is roughly equivalent to: >>> module = get_a_module_from_file_name('module') Alternatively: >>> from module import foo is roughly equivalent to: >>> temp = get_a_module_from_file_name('module') >>> foo = temp.foo >>> del temp (and the magic function "get_a_module_from_file_name" is actually called __import__ with double underscores.) -- Steven From python.list at tim.thechases.com Fri Jan 11 17:41:52 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 11 Jan 2008 16:41:52 -0600 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <4787F0B0.9060701@tim.thechases.com> >> I recently faced a similar issue doing something like this: >> >> data_out = [] >> for i in range(len(data_in)): >> data_out.append([]) > > Another way to write this is > data_out = [[]] * len(data_in) ...if you're willing to put up with this side-effect: >>> data_in = range(10) >>> data_out = [[]] * len(data_in) >>> data_out [[], [], [], [], [], [], [], [], [], []] >>> data_out[0].append('hello') >>> data_out [['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello']] For less flakey results: >>> data_out = [[] for _ in data_in] >>> data_out [[], [], [], [], [], [], [], [], [], []] >>> data_out[0].append('hello') >>> data_out [['hello'], [], [], [], [], [], [], [], [], []] -tkc From mwm-keyword-python.b4bdba at mired.org Thu Jan 10 14:50:24 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 14:50:24 -0500 Subject: for loop without variable In-Reply-To: <87fxx6p1nr.fsf@mulj.homelinux.net> References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <20080110145024.32b06514@bhuda.mired.org> On Thu, 10 Jan 2008 08:42:16 +0100 Hrvoje Niksic wrote: > Mike Meyer writes: > > It sounds to me like your counter variable actually has meaning, > It depends how the code is written. In the example such as: > > for meaningless_variable in xrange(number_of_attempts): > ... > > the loop variable really has no meaning. Rewriting this code only to > appease pylint is exactly that, it has nothing with making the code > more readable. Except in this case, the variable *has* a meaning. You've just chosen to obfuscate it. > > you've hidden that meaning by giving it the meaningless name "i". If > > you give it a meaningful name, then there's an obvious way to do it > > (which you listed yourself): > > > > while retries_left: > [...] > > This loop contains more code and hence more opportunities for > introducing bugs. For example, if you use "continue" anywhere in the > loop, you will do one retry too much. All correct - and I'm a big fan of minimizing code, as code you don't write has no bugs in it. But you can still show the meaning of this "meaningless" variable: for number_of_attempts in xrange(maximum_attempts): Of course, the OP's request is a better solution: since he doesn't actually need the variable, removing it completely means there's one less variable, which is one less thing you can set to the wrong value. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From donn.ingle at gmail.com Sun Jan 13 08:50:49 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 15:50:49 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A0F5D.3030906@v.loewis.de> References: <200801131427.54672.donn.ingle@gmail.com> <478A0F5D.3030906@v.loewis.de> Message-ID: <200801131550.50119.donn.ingle@gmail.com> > If you can all ls them, and if the file names come out right, then > they'll have the same encoding. Could it not be that the app doing the output (say konsole) could be displaying a filename as best as it can (doing the ignore/replace) trick and using whatever fonts it can reach) and this would disguise the situation? I don't think one can call any string a plain ascii string anymore. I have been looking for somewhere online that I can download files obviously in a non-ascii set (like japan someplace) but can't find anything easy. I want to see exactly how my system (Kubuntu 7.10) handles things. > I never heard before that font files use non-ASCII file names, They are files, named as any other file - those that are created by people get called whatever they want, under whatever locale they used. Still, I don't fully understand how this is all handled. > don't see the point in doing so - isn't there typically a font name > *inside* the font file as well, so that you'd rather use that for > display than the file name? Yes, but sometimes I can't reach that - segfaults and so forth. I also need to write the filename to a text file for logging. > Of course, *other* files (text files, images etc) will often use > non-ASCII file names. Same as font files - I am talking mainly about TTF files here. Mainly Arrr, pass the rum, matey fonts ;) (Which I don't use in designs, but have kept over the years.) > However, they won't normally have mixed > encodings - most user-created files on a single system should typically > have the same encoding (there are exceptions possible, of course). Well, if I am collecting fonts from all over the place then I get a mixed-bag. > > Meaning, I am led to assume, the LANG variable primarily? > Yes. Thanks. Good to know I'm on the right track. \d From sjmachin at lexicon.net Sat Jan 12 16:12:26 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 12 Jan 2008 13:12:26 -0800 (PST) Subject: Is unicode.lower() locale-independent? References: Message-ID: On Jan 12, 10:51 pm, Fredrik Lundh wrote: > Robert Kern wrote: > >> However it appears from your bug ticket that you have a much narrower > >> problem (case-shifting a small known list of English words like VOID) > >> and can work around it by writing your own locale-independent casing > >> functions. Do you still need to find out whether Python unicode > >> casings are locale-dependent? > > > I would still like to know. There are other places where .lower() is used in > > numpy, not to mention the rest of my code. > > "lower" uses the informative case mappings provided by the Unicode > character database; see > > http://www.unicode.org/Public/4.1.0/ucd/UCD.html of which the relevant part is """ Case Mappings There are a number of complications to case mappings that occur once the repertoire of characters is expanded beyond ASCII. For more information, see Chapter 3 in Unicode 4.0. For compatibility with existing parsers, UnicodeData.txt only contains case mappings for characters where they are one-to-one mappings; it also omits information about context-sensitive case mappings. Information about these special cases can be found in a separate data file, SpecialCasing.txt. """ It seems that Python doesn't use the SpecialCasing.txt file. Effects include: (a) one-to-many mappings don't happen e.g. LATIN SMALL LETTER SHARP S: u'\xdf'.upper() produces u'\xdf' instead of u'SS' (b) language-sensitive mappings (e.g. dotted/dotless I/i for Turkish (and Azeri)) don't happen (c) context-sensitive mappings don't happen e.g. lower case of GREEK CAPITAL LETTER SIGMA depends on whether it is the last letter in a word. > > afaik, changing the locale has no influence whatsoever on Python's > Unicode subsystem. > > From tim.arnold at sas.com Tue Jan 22 09:28:26 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Tue, 22 Jan 2008 09:28:26 -0500 Subject: docbook and xmlproc Message-ID: hi, I'm unable to get xmlproc to validate my docbook test file. This is new territory for me, so I'd appreciate any advice on what I'm doing wrong. Using python 2.4 on HPux10.20. The test file (testdb.xml) Test Chapter This is a test document. The python code: from xml.parsers.xmlproc import xmlproc from xml.parsers.xmlproc import xmlval print 'Validate without DTD' p0 = xmlproc.XMLProcessor() p0.set_application(xmlproc.Application()) p0.parse_resource('testdb.xml') print # print 'Validate with DTD' p1 = xmlval.XMLValidator() p1.set_application(xmlval.Application()) p1.parse_resource('testdb.xml') Of course it gets through the 'Validate without DTD' portion fine, but I get this error on the 'Validate with DTD' part: ----------------------- ERROR: Internal error: External PE references not allowed in declarations at /dept/app/doc/xml/DocBook/dbcentx.mod:308:10 TEXT: ' ]]> ]]> and these lines later on (307-9) : 307 The isoamsa.ent file is in the ent subdir relative to the dbcentx.mod file, so I'm at a loss. thanks, --Tim Arnold From martin at v.loewis.de Sun Jan 13 08:17:17 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jan 2008 14:17:17 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801131427.54672.donn.ingle@gmail.com> References: <200801131351.59005.donn.ingle@gmail.com> <4789FE1C.9000002@v.loewis.de> <200801131427.54672.donn.ingle@gmail.com> Message-ID: <478A0F5D.3030906@v.loewis.de> > I guess I'm confused by that. I can ls them, so they appear and thus have > characters displayed. I can open and cat them and thus the O/S can access > them, but I don't know whether their characters are strictly in ascii-limits > or drawn from a larger set like unicode. I mean, I have seen Japanese > characters in filenames on my system, and that can't be ascii. > > You see, I have a large collection of fonts going back over 10 years and they > came from usenet years ago and so have filenames mangled all to hell. If you can all ls them, and if the file names come out right, then they'll have the same encoding. > I can't always *type* some of their names and have to use copy/paste to, for > example, ls one of them. > > Again, it's working from ignorance (my own) : I assume filenames in different > countries will be in character sets that I have never (nor will I ever) see. I never heard before that font files use non-ASCII file names, and I don't see the point in doing so - isn't there typically a font name *inside* the font file as well, so that you'd rather use that for display than the file name? Of course, *other* files (text files, images etc) will often use non-ASCII file names. However, they won't normally have mixed encodings - most user-created files on a single system should typically have the same encoding (there are exceptions possible, of course). >> If the user has set up his machine correctly: yes. > Meaning, I am led to assume, the LANG variable primarily? Yes. Regards, Martin From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 02:42:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 27 Jan 2008 07:42:00 -0000 Subject: how to make format operator % work with unicode as expected References: <13po55nc0q0s06@corp.supernews.com> Message-ID: <13pode8n39n8ea8@corp.supernews.com> On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: > You didn't understand my question, but thanks any way. > > Yes, it is true that %s already support unicode, and I did not > contradict that. But it counts the number of bytes instead of > characters, and makes things like %-20s out of alignment. If you don't > understand my assertion, please don't argue back and I am only > interested in answers from those who are qualified. I understand your assertion. I think it is nonsense. >>> def test(): ... print "12345678901234567890 +" ... print "%-20s +" % "Plain ASCII" ... print u"%-20s +" % u"Les mis?rables-\320\321\322" ... >>> test() 12345678901234567890 + Plain ASCII + Les mis?rables-??? + -- Steven From martin at v.loewis.de Sat Jan 5 11:00:53 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 05 Jan 2008 17:00:53 +0100 Subject: Question on os.tempnam() vulnerability In-Reply-To: <13nv5m68qeknk1f@corp.supernews.com> References: <13nt81gftkfa32d@corp.supernews.com> <13nv5m68qeknk1f@corp.supernews.com> Message-ID: <477FA9B5.9050609@v.loewis.de> > I know. That's the point of my question: how do you do that > under Windows? When you create a new process, you have the option to inherit file handles to the new process. So the parent should open the file, and then inherit the handle to the new process. The new process will need to know what the file handle it should use. There are two basic options: a) pass the file handle number as a string on the command line b) make the handle either stdin or stdout of the new process, and have the new process ask for its stdin/stdout handle. IOW, it's the same approach as on Unix. Regards, Martin From alexandrov.dmitry at gmail.com Wed Jan 16 09:11:29 2008 From: alexandrov.dmitry at gmail.com (Dmitry) Date: Wed, 16 Jan 2008 06:11:29 -0800 (PST) Subject: list classes in package Message-ID: <5cff1706-3bb1-4a54-bccb-175ff384788c@q77g2000hsh.googlegroups.com> Hi All, I've trying to develop one Python application, and neet to solve one problem. I need to list all classes defined in one package (not module!). Could anybody please show me more convinient (correct) way to implement this? Thanks, Dmitry From lepto.python at gmail.com Fri Jan 4 05:38:27 2008 From: lepto.python at gmail.com (oyster) Date: Fri, 4 Jan 2008 18:38:27 +0800 Subject: Why python says "unexpected parameter 'mini.py'" for my code? Message-ID: <6a4f17690801040238s492a0299s60cf41c2e238081a@mail.gmail.com> The following is my pure-python wxwidgets test. It runs and give a frame, but soon python comes up to say "unexpected parameter 'mini.py'" and I have to close it. I cannot find the reason. Can somebody give me a hint to let it work well? Thanks http://pyguiviactypes.googlepages.com/mini.py From bazwal at googlemail.com Mon Jan 7 14:53:09 2008 From: bazwal at googlemail.com (Baz Walter) Date: Mon, 7 Jan 2008 19:53:09 +0000 (UTC) Subject: Does Python cache the startup module? References: Message-ID: Fredrik Lundh pythonware.com> writes: > > Baz Walter wrote: > > > It's hard to supply an example for this, since it is local to the machine I am > > using. The startup module would look something like this: > > would look, or does look? if it doesn't look like this, what else does > it contain? What I did was create a minimal version of the module which still exhibits the same behaviour (for me, that is). Basically, QWidget in the example below replaces my MainWindow class. > > #!/usr/local/bin/python > > > > if __name__ == '__main__': > > > > import sys > > from qt import QApplication, QWidget > > > > application = QApplication(sys.argv) > > mainwindow = QWidget() > > application.setMainWidget(mainwindow) > > mainwindow.show() > > sys.exit(application.exec_loop()) > > > > If I change the name 'mainwindow' to 'mainwidget', the widget it refers to does > > not get destroyed; when I change it back again, it does get destroyed. > > Otherwise, the program runs completely normally. > > I don't see any code in there that destroys the widget, and I also don't > see any code in there that creates more than one instance of the main > widget. Qt will try to destroy all widgets that are linked together in the object hierarchy. > what do you do to run the code, and how to you measure leakage? I run it with: python app.py -widgetcount The widgetcount switch is a Qt facility which counts how many widgets are created and how many destroyed. Before changing the name 'mainwindow' to 'mainwidget' it reports: Widgets left: 0 Max widgets: 2 Widgets left: 0 Max widgets: 149 (full program) Afterwards it reports: Widgets left: 1 Max widgets: 2 Widgets left: 146 Max widgets: 149 (full program) > is the name "mainwidget" used for some other purpose in your application? No From fredrik at pythonware.com Wed Jan 9 06:33:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 12:33:56 +0100 Subject: Learning Python via a little word frequency program In-Reply-To: <493158.64888.qm@web56406.mail.re3.yahoo.com> References: <493158.64888.qm@web56406.mail.re3.yahoo.com> Message-ID: Andrew Savige wrote: > Here's my first attempt: > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > freq = {} > for name in names.split(): > freq[name] = 1 + freq.get(name, 0) > deco = zip([-x for x in freq.values()], freq.keys()) > deco.sort() > for v, k in deco: > print "%-10s: %d" % (k, -v) > > I'm interested to learn how more experienced Python folks would solve > this little problem. Though I've read about the DSU Python sorting idiom, > I'm not sure I've strictly applied it above ... and the -x hack above to > achieve a descending sort feels a bit odd to me, though I couldn't think > of a better way to do it. sort takes a reverse flag in recent versions, so you can do a reverse sort as: deco.sort(reverse=True) in older versions, just do: deco.sort() deco.reverse() # this is fast! also note that recent versions also provide a "sorted" function that returns the sorted list, and both "sort" and "sorted" now allow you to pass in a "key" function that's used to generate a sort key for each item. taking that into account, you can simply write: # sort items on descending count deco = sorted(freq.items(), key=lambda x: -x[1]) simplifying the print statement is left as an exercise. > I also have a few specific questions. Instead of: > > for name in names.split(): > freq[name] = 1 + freq.get(name, 0) > > I might try: > > for name in names.split(): > try: > freq[name] += 1 > except KeyError: > freq[name] = 1 > > Which is preferred? for simple scripts and small datasets, always the former. for performance-critical production code, it depends on how often you expect "name" to be present in the dictionary (setting up a try/except is cheap, but raising and catching one is relatively costly). > Ditto for: > > deco = zip([-x for x in freq.values()], freq.keys()) > > versus: > > deco = zip(map(operator.neg, freq.values()), freq.keys()) using zip/keys/values to emulate items is a bit questionable. if you need to restructure the contents of a dictionary, I usually prefer items (or iteritems, where suitable) and tuple indexing/unpacking in a list comprehension (or generator expression, where suitable). > Finally, I might replace: > > for v, k in deco: > print "%-10s: %d" % (k, -v) > > with: > > print "\n".join("%-10s: %d" % (k, -v) for v, k in deco) why? From apardon at forel.vub.ac.be Thu Jan 24 08:34:56 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Jan 2008 13:34:56 GMT Subject: When is min(a, b) != min(b, a)? References: Message-ID: On 2008-01-21, Steven D'Aprano wrote: > On Sun, 20 Jan 2008 21:15:02 -0600, Albert Hopkins wrote: > > According to the IEEE-754 standard the usual trichotomy of "x is less > than y, x is equal to y, or x is greater than y" has to be extended to > include "x and y are unordered". Comparisons with NaNs are unordered, and > so expressions like "x < nan" should signal an exception. That doesn't follow. The problem is not that x < nan returns False because that is correct since x isn't smaller than nan. The problem is cmp(x, nan) returning 1, because that indicates that x is greater than nan and that isn't true. -- Antoon Pardon From martin at marcher.name Tue Jan 22 17:58:15 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 22 Jan 2008 23:58:15 +0100 Subject: UDP Client/Server Message-ID: Hello, I created a really simple udp server and protocol but I only get every 2nd request (and thus answer just every second request). Maybe someone could shed some light, I'm lost in the dark(tm), sorry if this is a bit oververbose but to me everything that happens here is black magic, and I have no clue where the packages go. I can't think of a simpler protocol than to just receive a fixed max UDP packet size and answer immediately (read an "echo" server). thanks martin ### server >>> from socket import * >>> import SocketServer >>> from SocketServer import BaseRequestHandler, UDPServer >>> class FooReceiveServer(SocketServer.UDPServer): ... def __init__(self): ... SocketServer.UDPServer.__init__(self, ("localhost", 4321), FooRequestHandler) ... >>> class FooRequestHandler(BaseRequestHandler): ... def handle(self): ... data, addr_info = self.request[1].recvfrom(65534) ... print data ... print addr_info ... self.request[1].sendto("response", addr_info) ... >>> f = FooReceiveServer() >>> f.serve_forever() request 0 ('127.0.0.1', 32884) request 1 ('127.0.0.1', 32884) request 2 ('127.0.0.1', 32884) request 2 ('127.0.0.1', 32884) request 2 ('127.0.0.1', 32884) ### client >>> target = ('127.0.0.1', 4321) >>> from socket import * >>> s = socket(AF_INET, SOCK_DGRAM) >>> for i in range(10): ... s.sendto("request " + str(i), target) ... s.recv(65534) ... 9 Traceback (most recent call last): File "", line 3, in KeyboardInterrupt >>> s.sendto("request " + str(i), target) 9 >>> str(i) '0' >>> for i in range(10): ... s.sendto("request " + str(i), target) ... s.recv(65534) ... 9 'response' 9 'response' 9 Traceback (most recent call last): File "", line 3, in KeyboardInterrupt >>> #this was hanging, why? ... >>> s.sendto("request " + str(i), target) 9 >>> s.recv(65534) 'response' >>> s.sendto("request " + str(i), target) 9 >>> s.recv(65534) Traceback (most recent call last): File "", line 1, in KeyboardInterrupt >>> s.sendto("request " + str(i), target) 9 >>> s.sendto("request " + str(i), target) 9 >>> s.recv(65534) 'response' >>> s.recv(65534) Traceback (most recent call last): File "", line 1, in KeyboardInterrupt >>> s.sendto("request " + str(i), target) 9 >>> -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From justin.mailinglists at gmail.com Wed Jan 16 00:38:44 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Tue, 15 Jan 2008 21:38:44 -0800 (PST) Subject: Image to browser References: <8c014bd1-7040-4ba3-9206-e1567c4a391a@n20g2000hsh.googlegroups.com> Message-ID: <1d223aa2-1297-4b01-854a-2a502f5f0ed1@l1g2000hsa.googlegroups.com> On Jan 16, 1:19 pm, danielatdavesch... at gmail.com wrote: > On Jan 16, 12:16 am, danielatdavesch... at gmail.com wrote: > > > Im using mod_python and apache2 using psp for output of page, i open a > > file and resize it with the following code > > > <% > > import Image, util > > > fields = util.FieldStorage(req) > > filename = fields.getlist('src')[0] > > > path = '/var/www/content/' + filename > > size = 128, 128 > > > im = Image.open(path) > > print im.resize(size, Image.ANTIALIAS) > > %> > > > so for one, I dont think print does much with psp as far as i can > > tell, i cant even do a print 'hello world', it has to be a > > req.write('hello world'), but i cant req.write the im.resize. The > > manual for im.resize states that its return can go ahead and be > > streamed via http but I get a blank page when im expecting to see > > image characters dumped to my screen. Python doesn't throw up any > > errors. Im not sure where else to look or what to do. > > > Thanks for any help, > > Daniel > > its worth noting that ive tried using > print "Content-Type: image/jpeg\n" > before the print im.resize and still no luck If you're using the Image module from PIL then im.resize(...) returns an Image instance. I have not used mod_python and psp, but try the following: >>> import Image >>> i = Image.open('server.JPG') >>> r = i.resize((32,32)) >>> from StringIO import StringIO >>> b = StringIO() >>> r.save(b, 'JPEG') >>> b.seek(0) >>> req.write("Content-Type: image/jpeg\r\n\r\n") >>> req.write(b.read()) There's a r.tostring(...) method but I don't see how to make that return a JPEG stream. From fredrik at pythonware.com Wed Jan 9 03:24:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 09:24:34 +0100 Subject: how to open a file in some application using Tkinter i am using TKINTER to create GUI application i want to know how to open a word document in open office or any other applicatio In-Reply-To: References: Message-ID: brindly sujith wrote: > i am using TKINTER to create GUI application > > i want to know how to open a word document in open office or any other > application > > please send me the tkinter coding for this reposting the reply you received when you posted this on another mailing list: --- on windows, you can use the "os.startfile" function: import os os.startfile("mydocument.doc") (this is the same as double-clicking on a document in the file explorer) on other platforms, use os.system() and specify what application to run: import os os.system("someapp mydocument.doc") --- From Graham.Dumpleton at gmail.com Tue Jan 8 18:08:09 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 8 Jan 2008 15:08:09 -0800 (PST) Subject: Python setup not working on Windows XP References: <661089ec-1725-43d1-b8b3-f5c07eb115ac@k39g2000hsf.googlegroups.com> Message-ID: <8e15b643-5ce8-44a6-8ba1-caf8b3494336@i29g2000prf.googlegroups.com> On Jan 8, 5:31?pm, Tim Roberts wrote: > Gowri wrote: > > >I am new to Python and am trying to setup Apache to serve Python using > >mod_python. I'm using a Windows XP box. here is a list of steps i > >followed for the installation: > > >1. Installed Apache 2.2.6 > >2. Installed Python 2.5.1 > >3. Installedmod_python3.3.1 > > >I then included the line > >LoadModule python_module modules/mod_python.so in httpd.conf > > >I had this one line python file (print "Hello") in htdocs of Apache. > > Did you put it in a file called "hello.py"? ?Did you create an AddHandler > for .py files? ?Did you create a PythonHandler referring to hello.py? And did you (OP) read the mod_python documentation enough to know that 'print "Hello" is in no way going to work with mod_python. You cannot just throw an arbitrary bit of Python code in a file using 'print' statements and it will somehow magically work. You need to write your code to the mod_python APIs. Graham From steve551979 at hotmail.com Wed Jan 23 21:13:25 2008 From: steve551979 at hotmail.com (steve551979 at hotmail.com) Date: Wed, 23 Jan 2008 18:13:25 -0800 (PST) Subject: os.system behavior when calling SQLPlus with spooling Message-ID: I'm trying to execute SQLPlus in python (on Redhat linux). when calling sqlplus, i'm referencing an sql file which spools results to a file, for e.g.: spool "/tmp/qctemp2.out"; SELECT %s FROM bug WHERE BG_BUG_ID = %s; spool off; exit; I'm noticing that when using: os.system("sqlplus -S -L %s @/tmp/qctemp3.sql" % qc_login) I'm able to execute fine, however, when I use: f = popen4(("sqlplus -S -L %s @/tmp/qctemp3.sql" % qc_login) print f.read() I get problems where occasionally, sqlplus is run, but has problems spooling results to a file, and python hangs on the print f.read() statement. I would prefer not to use os.system() since I want to analyze the results. Can anyone suggest how I should go about executing sqlplus in this case? Thanks for your help, Steve (note: please do not reply to my email address, only reply to this group) From fredrik at pythonware.com Wed Jan 2 09:56:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 02 Jan 2008 15:56:46 +0100 Subject: ElementTree should parse string and file in the same way In-Reply-To: <13njba091eipl6f@corp.supernews.com> References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > Fredrik, if you're reading this, I'm curious what your reason is. I don't > have an opinion on whether you should or shouldn't treat files and > strings the same way. Over to you... as Diez shows, it's all about use cases. and as anyone who's used my libraries or read my code knows, I'm a big fan of minimalistic but highly composable object API:s and liberal use of short helper functions to wire them up to fit the task at hand. kitchen sink API design is a really bad idea, for more reasons than I can fit in this small editor window. From kyosohma at gmail.com Fri Jan 25 08:54:22 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 25 Jan 2008 05:54:22 -0800 (PST) Subject: Python ADO Date Time database fields References: <30222931-7fa9-4dd5-bdc8-d1313c37a144@i3g2000hsf.googlegroups.com> Message-ID: On Jan 25, 7:48 am, goldtech wrote: > snip > > > > > try this: > > > val = oRS.Fields(dt).Value > > print type(val) > > this gives: > > > print float(val) > > yes, it gives 0.0 > > But there should be a way to print what is *actually in the field*. > When I open the DB table in Access I see: 12:00:00 AM. > > That's what I want - the value, and the form of the value, exactly as > seen in the field... > > As an aside, the roughly eqivalent code in Perl will print the > "12:00:00 AM" - (the trick for the date types in Perl is to add: "use > Win32::OLE::Variant;" > > There has to be a way:^) > > snip You could try posting to the PyWin32 group too. They would probably know. http://mail.python.org/mailman/listinfo/python-win32 Mike From bearophileHUGS at lycos.com Wed Jan 9 21:46:49 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 9 Jan 2008 18:46:49 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <41548a0d-eb74-4cd5-94b7-0ca11e691204@f3g2000hsg.googlegroups.com> <1199925201.586849@www.vif.com> Message-ID: <61d06e1a-c0c6-459d-92de-14968381be0f@v29g2000hsf.googlegroups.com> Gordon C: > This is very cool stuff but I suspect that the code is unreadable > to many readers, including me. Just for fun here is a complete program, > written in Turbo Pascal, circa 1982, that does the job. Readable > n'est pas? I think it's quite readable, especially if you indent it more correctly. Pascal is usually among the most readable languages, for not-too-much complex tasks. I don't mind its mutable strings too much. Bye, bearophile From bignose+hates-spam at benfinney.id.au Wed Jan 16 03:19:30 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jan 2008 19:19:30 +1100 Subject: import from question References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> <478d04d4$0$26042$88260bb3@free.teranews.com> Message-ID: <87tzleb2st.fsf@benfinney.id.au> Tobiah writes: > This is a little surprising. So "from mod import *" really copies > all of the scalars into new variables in the local namespace. No. Nothing is copied. All the objects (remembering that in Python, *everything* is an object) created by the code in module 'mod' are given names in the current namespace. > I always ASSumed that the two forms of import were equivalent, but > that one form did away with the need to be explicit about the > namespace: mod.thing Obviously this is far from the case. Yes. In fact the main difference is in what namespace the module's objects are made available. -- \ "The way to build large Python applications is to componentize | `\ and loosely-couple the hell out of everything." -- Aahz | _o__) | Ben Finney From ryan at ryankaskel.com Wed Jan 23 14:12:44 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 11:12:44 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> Message-ID: On Jan 23, 2:04 pm, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jan 2008 10:50:02 -0800, ryan k wrote: > > Hello. I have a string like 'LNAME > > PASTA ZONE'. I want to create a list of those words and > > basically replace all the whitespace between them with one space so i > > could just do lala.split(). Thank you! > > You *can* just do ``lala.split()``: Indeed you can thanks! > > In [97]: lala = 'LNAME PASTA ZONE' > > In [98]: lala.split() > Out[98]: ['LNAME', 'PASTA', 'ZONE'] > > Ciao, > Marc 'BlackJack' Rintsch From bigblueswope at gmail.com Tue Jan 8 21:03:08 2008 From: bigblueswope at gmail.com (BJ Swope) Date: Tue, 8 Jan 2008 21:03:08 -0500 Subject: Open a List of Files In-Reply-To: <874pdomrrd.fsf@mulj.homelinux.net> References: <874pdomrrd.fsf@mulj.homelinux.net> Message-ID: On Jan 8, 2008 7:22 AM, Hrvoje Niksic wrote: > Fredrik Lundh writes: > > > BJ Swope wrote: > > > >> the code looks ok. please define "not working". > >> > >> Yep, defining "not working" is always helpful! :) > >> > >> I want to have all 3 files open at the same time. I will write to > >> each of the files later in my script but just the last file is open > >> for writing. > > > > to keep more than one file open, you need more than one variable, or a > > variable that can hold more than one object. > > > > if the number of files may vary, put the file objects in a list. > > Or in a dict: > > open_files = {} > for fn in ['messages', 'recipients', 'viruses']: > open_files[fn] = open(getfilename(fn), 'w') > > # open_files['messages'] is the open file 'messages' etc. > -- > http://mail.python.org/mailman/listinfo/python-list > I decided that I was just trying to be "too smooth by 1/2" so I fell back to ... messages = open(os.path.join(host_path,'messages.txt'), 'wb') deliveries = open(os.path.join(host_path,'deliveries.txt'), 'wb') actions = open(os.path.join(host_path,'actions.txt'), 'wb') parts = open(os.path.join(host_path,'parts.txt'), 'wb') recipients = open(os.path.join(host_path,'recipients.txt'), 'wb') viruses = open(os.path.join(host_path,'viruses.txt'), 'wb') esp_scores = open(os.path.join(host_path,'esp_scores.txt'), 'wb') Thank you to everybody who answered. -------------- next part -------------- An HTML attachment was scrubbed... URL: From killerkiwi2005 at gmail.com Sun Jan 27 15:24:15 2008 From: killerkiwi2005 at gmail.com (Jason Taylor) Date: Mon, 28 Jan 2008 09:24:15 +1300 Subject: Klik2 Project, Python apps on linux In-Reply-To: <94dd8f6f0801262249v1c07cf3em2548c470a523291e@mail.gmail.com> References: <94dd8f6f0801262249v1c07cf3em2548c470a523291e@mail.gmail.com> Message-ID: <94dd8f6f0801271224h76485e91n56df5c32a6fcc287@mail.gmail.com> Perhaps this would help, heres a list of our error reports http://klik.atekon.de/feedback/details.php?e=ImportError On 27/01/2008, Jason Taylor wrote: > > Hi > > We've been working on klik2, http://code.google.com/p/klikclient/, which > implements OSX like application files on linux (with applications working on > all distros), In which every user desktop application is 1 file > > We've run into a bit of a problem with python apps, so while we can run a > complicated application like openoffice.org on ubuntu, fedora and suse > from a single file we cant run any python applications such as > > jokosher > gnome-specimen > angrydd > gausssum > pathological > quodlibet > webboard > istanbul > exaile > ccsm > bittornado > pessulus > labyrinth > wammu > accerciser > > > We'd like to fix this in a clean way with out resorting to nasty hacks > involving $PYTHON_PATH. > > If any one has any suggestions please email me or drop by #klik on > freenode > > Issue http://code.google.com/p/klikclient/issues/detail?id=144 > > Cheers > > Jason Taylor > > -- > "Why isn't my life like a situation comedy? Why don't I have a bunch of > friends with nothing better to do but drop by and instigate wacky > adventures? Why aren't my conversations peppered with spontaneous > witticisms? Why don't my friends demonstrate heartfelt concern for my well > being when I have problems? ...I gotta get my life some writers." - Calven -- "Why isn't my life like a situation comedy? Why don't I have a bunch of friends with nothing better to do but drop by and instigate wacky adventures? Why aren't my conversations peppered with spontaneous witticisms? Why don't my friends demonstrate heartfelt concern for my well being when I have problems? ...I gotta get my life some writers." - Calven -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Fri Jan 4 10:40:03 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 04 Jan 2008 15:40:03 -0000 Subject: choosing random dynamic port number References: <32e43bb70801031409o5d1dcd2at5a159339cd43ae52@mail.gmail.com> <3e6cca84-f8cf-4947-931c-18d6af748f13@l6g2000prm.googlegroups.com> Message-ID: <13nskqjrrgb9qd1@corp.supernews.com> On 2008-01-04, Giampaolo Rodola' wrote: >> ? ? def GenerateDynamicPortNumber(): >> ? ? ? ? return 0 >> >> (to get the actual number, use getsockname() on the socket after you've >> called "bind" on it) >> >> > > By using 0 as port number value you let kernel choose a free > unprivileged random port: The port number chosen isn't random on many OSes. If the OP really wants a random port number, he'll have to generate it himself. -- Grant Edwards grante Yow! Look! A ladder! at Maybe it leads to heaven, visi.com or a sandwich! From rrr at ronadam.com Sun Jan 13 23:02:39 2008 From: rrr at ronadam.com (Ron Adam) Date: Sun, 13 Jan 2008 22:02:39 -0600 Subject: time.time or time.clock In-Reply-To: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> References: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> Message-ID: <478ADEDF.2070306@ronadam.com> John Machin wrote: > On Jan 14, 7:05 am, Ron Adam wrote: >> I'm having some cross platform issues with timing loops. It seems >> time.time is better for some computers/platforms and time.clock others, but > > Care to explain why it seems so? > >> it's not always clear which, so I came up with the following to try to >> determine which. >> >> import time >> >> # Determine if time.time is better than time.clock >> # The one with better resolution should be lower. >> if time.clock() - time.clock() < time.time() - time.time(): >> clock = time.clock >> else: >> clock = time.time >> >> Will this work most of the time, or is there something better? >> > > Manual: > """ > clock( ) > > On Unix, return the current processor time as a floating point number > expressed in seconds. The precision, and in fact the very definition > of the meaning of ``processor time'', depends on that of the C > function of the same name, but in any case, this is the function to > use for benchmarking Python or timing algorithms. > > On Windows, this function returns wall-clock seconds elapsed since the > first call to this function, as a floating point number, based on the > Win32 function QueryPerformanceCounter(). The resolution is typically > better than one microsecond. > [snip] > > time( ) > > Return the time as a floating point number expressed in seconds since > the epoch, in UTC. Note that even though the time is always returned > as a floating point number, not all systems provide time with a better > precision than 1 second. While this function normally returns non- > decreasing values, it can return a lower value than a previous call if > the system clock has been set back between the two calls. > """ > > AFAICT that was enough indication for most people to use time.clock on > all platforms ... before the introduction of the timeit module; have > you considered it? I use it to time a Visual Python loop which controls frame rate updates and set volocities according to time between frames, rather than frame count. The time between frames depends both on the desired frame rate, and the background load on the computer, so it isn't constant. time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't high enough resolution on windows. I do use timeit for bench marking, but haven't tried using in a situation like this. > It looks like your method is right sometimes by accident. func() - > func() will give a negative answer with a high resolution timer and a > meaningless answer with a low resolution timer, where "high" and "low" > are relative to the time taken for the function call, so you will pick > the high resolution one most of the time because the meaningless > answer is ZERO (no tick, no change). Some small fraction of the time > the low resolution timer will have a tick between the two calls and > you will get the wrong answer (-big < -small). If the difference is between two high resolution timers then it will be good enough. I think the time between two consectutive func() calls is probably low enough to rule out low resolution timers. In the case of two > "low" resolution timers, both will give a meaningless answer and you > will choose arbitrarily. In the case of two low resolution timers, it will use time.time. In this case I probably need to raise an exception. My program won't work correctly with a low resolution timer. Thanks for the feed back, I will try to find something more dependable. Ron From jipksaman at gmail.com Thu Jan 24 04:12:17 2008 From: jipksaman at gmail.com (abdo911) Date: Thu, 24 Jan 2008 01:12:17 -0800 (PST) Subject: The Way to Paradise Message-ID: <673d9870-35d5-440f-a728-9dade02e6071@t1g2000pra.googlegroups.com> We are all in quest of true happiness. In this world, the idea of true/perfect happiness is not feasible because this world is inevitably doomed to total annihilation. True happiness is found only in dwelling upon Paradise, and enjoying its blessings. However, none would enter Paradise except the purified (those who are void of sins, void of an atom of grudge or malignance). Since Paradise is created only for the purified/pious, those who have evil looks (looking lustfully at strange women, and vice versa), who envy others, treat their fellowmen badly, hate mankind, or backbite cannot enter Paradise. To conclude, none can enter Paradise unless totally purified (sin-free). Those who indulge in illegal talk (backbiting, using indecent language, etc.), or have sinful hearts are denied entry to Paradise. Allah (The sublime) said: "And those who kept their duty to Lord (AL- Muttaquin) will be driven/led to Paradise in groups, and when they reach there, its gates will be opened (before their arrival for their reception) and its keepers will say: Salamun Alaikum (peace be upon you)! How blessed you are (being sin-free and having done well), enter here (Paradise) to abide therein eternally." Surat Az-Zumar/The Groups: 73. In another Surah, Allah says: "Those whose lives the angels take while they are in a pious state (pure from all evil, and worshipping none but only Allah) will be addressed as such: Salamun Alaikum (peace be upon you) enter Paradise due to that which you used to do (during your mortal life/in the world). Surat An-Nahl/The Bees: 32. The above-mentioned verses set the condition that, in order to enter Paradise, we have to be sin-free and void of an atom of guilt! One may argue that since we are all sinners, it seems that none can enter Paradise! Well, it is true that only the pious can enter Paradise, but, Allah (The Glorified), with His vast mercy, established eleven means to help us be purified: 4 in this world, 3 in the grave, and another 4 on the Day of Resurrection. These eleven means of purification aim at enabling us to cross/walk on the straight path rather than to slip and fall. This path is stretched over Hell fire and it is finer than a hair and sharper than the edge of a razor/sword! Knowing the nature of the straight path, one may question how people would tread on that path! Well, some will cross/walk on it as fast as the blink of an eye, others will be as fast as the light, others will be as fast as the wind, others will crawl, and others will cling to the path, then the angels will lead and/or encourage them onwards (lest they should fall into Hell fire), while others will be snatched by the hooks (attached to the path) to ensure/hasten their fall into Fire. 4 Means/Standpoints of Purification in this World 1. Repentance: Repentance is not limited to asking for forgiveness or invoking Allah's mercy, rather, it is one of the greatest religious rituals to win Allah's love/satisfaction and a means to get closer to Him. Allah (The Sublime) says: "Allah loves those who turn unto Him in repentance and loves those who purify themselves (by taking a bath and cleaning and washing thoroughly their private parts/bodies (in preparation for their prayers)". Surat AL-Baqarah/The Cow: 222. Repentance removes sins, as Allah (The Sublime) says: "And verily, I'm indeed forgiving to him who repents, believes in My Oneness, and associates none in worshipping with Me, did righteous good deeds, and then remained faithful to such belief and good deeds". Surat Ta-Ha: 82. Repentance changes evil deeds into good ones. Allah (The Glorified and The Exalted) said: "Except those who repented, believed in monotheism, and did righteous deeds; for those, Allah will change their sins into good deeds, and Allah is Oft-Forgiving, Most Merciful ". Surat AL-Furqan/The Criterion: 70. 2. Asking for Forgiveness: We (Moslems) should always ask Allah to forgive our sins (whether remembered or not). Allah's Messenger (PBUH), though being the most pious, endowed with the most knowledge of his Lord, and having had both his past and future guilt pardoned/forgiven (by Allah), he used to ask for Allah's forgiveness as many as a hundred times a day (an action that won't take more than a minute of your time). In this respect, the prophet (PBUH) says: "I swear by Allah, I do ask for Allah's forgiveness more than 70 times a day". This Hadith is quoted by AL- Bokhari. Also, Bin Omar (the son of Omar)-may Allah be content with them all- said: we used to count for the messenger of Allah (in one session and before leaving his place) as many as 100 times saying: "O Lord! Forgive me my sins and accept my repentance, you are the One Who accepts repentance, the Most Merciful". This Hadith is quoted by Abu Dawoud and AL-Turmuzi. 3. Good Deeds Remove Bad deeds: Change bad deeds with good ones because Abu Dhar Ibn Jundub and Abu abdulrahman Bin Muaz Bin Jabal (may Allah be content with them all) narrated that the Messenger of Allah said: "Fear Allah wherever you are and be keen to always change your bad deeds with good ones, and be nice to people." This Hadith is quoted by AL-Turmuzi. Allah also said: "And perform As-Salaah (the daily five prayers) at the two ends of the day and in some hours in the night. Verily, the good deeds remove the bad ones. That is a reminder to those who always remember Allah (in prayers, while standing, sitting, or lying down on their sides)". Surat Hud: 114. We must endeavor to do good deeds (no matter how simple they are). For example, we can replace "Hi" and/or "Bye" (even these two simple words are considered as "Good Deeds") with As-Salamu Alaikum and utilize our leisure time by always remembering Allah at all times (standing, sitting, eating, sleeping, working, driving, etc.). The Messenger of Allah (PBUH) had always the desire to do a lot of good deeds (on a daily basis). For example, he refused to accept a present (a camel as a means of transportation) from his best companion (Abu Bark) for free, and insisted that he share its cost, thus hoping to be worthy of winning the reward of AL-Hijra (immigration to Medina). We, likewise, need to do good deeds (not in quantity but in quality). Good deeds are best manifested in being wholly dedicated to your parents (especially in their old age) praying in the late hours of the night, praying in the early hours of dawn time, wearing the veil, and performing work perfectly. 4. Purifying Calamities: Allah puts His servants under severe tests (in this world) to have them purified from their sins and to enter Paradise sin-free. However, some people (not realizing the wisdom of such plights/tests) lament their destiny by saying; "O Lord, why have You ordained us (especially us) with such calamities?" Those who did not repent, did not ask for forgiveness, did not do good deeds, and/or were not put to tests (i.e., not purified) in this world still have another chance for purification and that will take place in their graves! Thus, missing purification in this world (while being alive) will be completed in one's grave (while lying dead)! And that shows how great this religion is, as you won't be left but sin-free (either in this world or while lying dead in your grave). To conclude, due to Allah's vast mercy and the simple demands for entering Paradise, we can say that none (of the Moslems) will enter Fire, (i.e., or more accurately, they will not abide there eternally). 3 Means/Standpoints of Purification in the Grave 5. The Funeral Prayer In this prayer, it is not the number of those standing behind the deceased (in a mosque) performing due funeral prayer that counts, instead it is the quality of the true believers who are present in this kind of prayer. The sincere supplications that come from such believers (in such congregations) will benefit the deceased. Though being dead, sincere supplication will greatly help the deceased to be purified for Paradise. 6. The Trial of the Grave Trial of the grave is best manifested in the questions asked by two angels (immediately after lying the dead in his grave): Who is your Lord? What is your religion? And what do you think about the man who was sent amongst you? (Referring to Allah's Messenger, PBUH). Other examples are: your fear facing these two angels, being alone in the grave (nobody there to support you), the darkness of the grave and, finally, your fear as you are enclosed therein. These trials are other means to remove all of our sins. Those who have already been purified (while alive in the world) will not be subject to other trials (while lying dead in their graves.) The prophet (PBUH) says: "A grave is either an orchard for Paradise or a pitfall for Hell". To conclude, a grave is not (as it is thought to be) a hideous dark place for beasts; on the contrary, it could be an orchard for Paradise! 7. Contribution of the Living to the Dead: When a Moslem dies, he can still have his sins removed by the good and sincere deeds dedicated to him by the living (especially from his relatives). The Ulamah (the religiously lectured of the nation) unanimously agree that all good deeds done by the living such as performing pilgrimage, Umrah (the visit to Al-Ka'ba in Makka), and sincere supplications do reach the dead only to purify them and then be sin-free. In this respect, Abu Hurairah (one of the prophet's, PBUH, companions) said: The Messenger of Allah (PBUH) said: "When the son of Adam dies, nothing will benefit him except one of the following three good righteous deeds: a non-stop Sadakah (charity), some kind of knowledge he left behind (useful to society), or a sincere supplication of his son." This Hadith is quoted by Moslim. Therefore, if someone (who is really dear to you) is dead, you can perform pilgrimage, do Umrah, or pay Sadakah on their behalf (so that they become sin-free). Remember that the more useful the Sadakah to society is, the more the reward is, (needless to say that you will have your share as well). To realize how merciful/great this religion is, it is important to know that somebody (while lying dead in his grave) can be freed from suffering/torment by the supplications of others who wish the deceased to be purified and sin-free for entry into Paradise. 4 Means/Standpoints of Purification on the Day of Resurrection 8. Horrors on the Day of Resurrection: Seeing the sun folded-up, the stars fall (after loosing their light), the seas blown-up, and the earth shaken with its (final) earthquake are all sin removers. 9. Standing Before Allah (The Glorified, The AL-Mighty): Another means to purify us from our sins is standing humbly before Allah in an attempt to answer/face His following questions/ blame: My servant, didn't I bestow you with My blessings? Didn't I give you wealth? Weren't I the Watchful when you had illegal looks (Men looking lustfully at women, and vice versa, or at whatever you shouldn't)? Weren't I the Watchful when you used indecent language (thus misusing communication with others? Allah then keeps addressing His servant as saying: My servant, you have underestimated the day when you stand before Me! Were you fearless of the notion that the time will come when you stand before Me! You have put on beautiful masks (before all people) only to come before Me with the worst in you! My servant, what made you fall into deception (ignoring that I Am the Watchful)? 10.Allah's Amnesty: This is the greatest means in purifying us from our sins. Just as the prophets have already interceded, as did His Messengers and as did the believers, Allah (The Glorified, the Sublime) says: Wouldn't I? Even knowing that we can all enter Paradise, there are still those who will fall off the path (for they deserve it). Others will not be purified even after passing through the above-mentioned eleven means of purification! They will fall into Fire, as they are sinful as well as guilty of committing foul/bad deeds, full of hatred and ever holding on to grudges. And the only way to purify such sinners is to let Fire do its job (similar to a piece of gold, which doesn't get its purity unless it is put into fire for the period required to make all other alloys vanish! In fact, the more it stays there, the greater its purity gets! Likewise, whoever eventually falls into Fire will stay there long enough to become purified (depending on how sinful he is). Immediately after being completely purified (after dwelling in Hell for some time), the angels will greet him saying: "Peace be upon you, dwell here (in Paradise) forever." In conclusion, in this world we own three of the means of the above- mentioned eleven purification standpoints: repentance, asking for forgiveness, and performing good deeds to remove the bad ones. Therefore, let's make as much use of them as we can (while we are still alive/before it is too late). Remember that if you are a true believer (paying duty to Allah, believing in monotheism and associating none with Allah in worshipping), you will not suffer the trials in your grave and/or the horrors of the Day of Resurrection. (May Allah Bless You All) From romo20350 at gmail.com Mon Jan 21 16:21:57 2008 From: romo20350 at gmail.com (romo20350 at gmail.com) Date: Mon, 21 Jan 2008 13:21:57 -0800 (PST) Subject: Help with cPAMIE References: Message-ID: <65036852-3cb2-4efe-bb96-8eb357af1689@d21g2000prf.googlegroups.com> On Jan 21, 11:09?am, romo20... at gmail.com wrote: > Hi, I'm in need of help with cPAMIE. I'm currently trying to submit > this form on a webpage: > >
>
> Submit Coupon >
>
>
> > >
> > > I can fill in the textboxes alright but I'm having trouble submitting > it. I've tried using: > ie.buttonClick('action') but It returns some thing about it being > hidden... > Ive also tried: > ie.buttonClick('Submit Coupon') but it says it can't find the string > anywhere... > Any help would be greatly appreciated! Thank you so much! Okay I kinda figured it out...I'm now trying to use formSubmit but it seems that the form has no name its just blank. So i tried ie.formSubmit("") but it didn't work. I'm a beginner so I really need some help :) Thanks! From hniksic at xemacs.org Thu Jan 10 02:42:16 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 10 Jan 2008 08:42:16 +0100 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> Message-ID: <87fxx6p1nr.fsf@mulj.homelinux.net> Mike Meyer writes: > It sounds to me like your counter variable actually has meaning, It depends how the code is written. In the example such as: for meaningless_variable in xrange(number_of_attempts): ... the loop variable really has no meaning. Rewriting this code only to appease pylint is exactly that, it has nothing with making the code more readable. > you've hidden that meaning by giving it the meaningless name "i". If > you give it a meaningful name, then there's an obvious way to do it > (which you listed yourself): > > while retries_left: [...] This loop contains more code and hence more opportunities for introducing bugs. For example, if you use "continue" anywhere in the loop, you will do one retry too much. From lizm at rcsltd.co.uk Thu Jan 24 09:17:37 2008 From: lizm at rcsltd.co.uk (LizzyLiz) Date: Thu, 24 Jan 2008 06:17:37 -0800 (PST) Subject: Which reportlab version for python 2.1.3? Message-ID: Hiya Probably me being thick but I can't find which version of reportlab I should use for python 2.1.3. Many thanks Liz From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Jan 6 18:33:36 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 07 Jan 2008 00:33:36 +0100 Subject: Delete lines containing a specific word References: Message-ID: <5ud6qgF1hlfdaU1@mid.individual.net> Steven D'Aprano wrote: > grep doesn't delete lines. grep matches lines. If you want to > delete them, you still have to do the rest of the job yourself. In which way does "grep -v mypattern myfile > myfile" not delete the lines matching mypattern? Regards, Bj?rn -- BOFH excuse #184: loop found in loop in redundant loopback From http Thu Jan 10 22:05:10 2008 From: http (Paul Rubin) Date: 10 Jan 2008 19:05:10 -0800 Subject: Fate of itertools.dropwhile() and itertools.takewhile() References: <7a86a421-089f-4634-8902-e9edfe139f03@e23g2000prf.googlegroups.com> <1a35dcbb-593c-45b8-a450-5245e75b1c9d@21g2000hsj.googlegroups.com> Message-ID: <7x3at5cba1.fsf@ruckus.brouhaha.com> Raymond Hettinger writes: > > I presume you did scans of > > large code bases and you did not find occurrences of > > takewhile and dropwhile, right? > > Yes. I think I have used them. I don't remember exactly how. Probably something that could have been done more generally with groupby. I remember a clpy thread about a takewhile gotcha, that it consumes an extra element: >>> from itertools import takewhile as tw >>> x = range(10) >>> z = iter(x) >>> list(tw(lambda i:i<5, z)) [0, 1, 2, 3, 4] >>> z.next() 6 I.e. I had wanted to use takewhile to split a list into the initial sublist satisfying some condition, and the rest of the list. This all by itself is something to at least warn about. I don't know if it's enough for deprecation. I've been cooking up a scheme for iterators with lookahead, that I want to get around to coding and posting. It's a harder thing to get right than it at first appears. From mwm-keyword-python.b4bdba at mired.org Thu Jan 10 22:59:07 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 22:59:07 -0500 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <20080110225907.19aa060d@bhuda.mired.org> On Thu, 10 Jan 2008 22:36:56 -0500 Marty wrote: > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) More succinctly: data_out = [] for _ in data_in: data_out.append([]) Or, as has already been pointed out: data_out = [[] for _ in data_in] > This caused me to wonder why Python does not have a "foreach" statement (and > also why has it not come up in this thread)? I realize the topic has probably > been beaten to death in earlier thread(s), but does anyone have the short answer? But I'm curious - what's the difference between the "foreach" you have in mind and the standard python "for"? http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From asmodai at in-nomine.org Wed Jan 9 12:42:27 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 9 Jan 2008 18:42:27 +0100 Subject: centre of mass of protein In-Reply-To: <22c5c6390801090913w6667560cv809a2e5fc8ad7e5b@mail.gmail.com> References: <22c5c6390801090913w6667560cv809a2e5fc8ad7e5b@mail.gmail.com> Message-ID: <20080109174227.GR75977@nexus.in-nomine.org> -On [20080109 18:15], smriti Sebastian (smriti.sebastuan at gmail.com) wrote: >Is there any script or module in python where we can find the centre of mass of >protein? Not sure, but perhaps http://biopython.org/ has something. And otherwise I am sure they would be more knowledgeable if something like that exists. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Only the wisest and the stupidest of men never change... From BjornSteinarFjeldPettersen at gmail.com Sun Jan 27 03:54:18 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 27 Jan 2008 00:54:18 -0800 (PST) Subject: file write question References: <62b96f11-1a81-4be8-9dcb-348ee38ebe16@f10g2000hsf.googlegroups.com> Message-ID: <5845751a-717e-4476-bdd5-4b7d09406fe4@j20g2000hsi.googlegroups.com> On Jan 27, 4:02 am, "Robb Lane (SL name)" wrote: > I have written a script which: > - opens a file > - does what it needs to do, periodically writing to the file... for a > few hours > - then closes the file when it's done > So my question is: > Would it be better to 'open' and 'close' my file on each write cycle? > e.g. > def writeStuff(content): > myFile = open('aFile.txt', 'a+') > myFile.write(content) > myFile.close() > > ... or just leave it till it's done? > I don't need to use the file contents until the script is done > (although it would be nice... just to check it while it's working), so > just curious what people think is the better method. > - rd Sounds like a classic case for a database to me (long running process producing sporadic output that you might want to tinker with as it's being produced). Python 2.5 comes with sqlite3 included... -- bjorn From bladedpenguin at gmail.com Fri Jan 25 06:28:05 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 03:28:05 -0800 (PST) Subject: global/local variables References: <13pia51grjfo2ed@corp.supernews.com> <4d161c89-7e33-4ddc-851f-bc9beb537229@q21g2000hsa.googlegroups.com> <13pjekb7r9jja4c@corp.supernews.com> Message-ID: <8d7caad9-fcc3-4bb5-bd7b-dd71e6bd6099@d4g2000prg.googlegroups.com> On Jan 25, 5:31 am, Steven D'Aprano wrote: > On Thu, 24 Jan 2008 23:04:42 -0800, Tim Rau wrote: > > UnboundLocalError: local variable 'nextID' referenced before assignment > > When you assign to a name in Python, the compiler treats it as a local > variable. So when you have a line like this: > > nextID += 1 # equivalent to nextID = nextID + 1 > > you are getting the value of the _local_ nextID before you have assigned > a value to it. > > > I want to know why it says 'local variable' it never had a problem when > > just allThings was in there. > > Because you don't assign to allThings, and therefore it is treated as > global. > Hmm.... so I can't assign to globals in a local environment? How do I make it see that I'm assigning to a global? > > as for the objection to global variable: If I didn't make them global, > > I'd make them part of a singleton class called gameVars that would get > > passed everywhere. > > *shrug* Or you could consider a different program structure completely. > > > It's unlikely that they'll get mixed in with anyhting > > else, as they fulfill a unique function. Also, I think it's more > > convenient, and I am, after all, my own employer when it comes to > > programming. > > Hey, it's your time and effort. If you want to, you can download the > Python "goto" module, and use goto and comefrom in your code. > > No, that's unfair. Globals aren't as harmful as goto. I'm not saying that > globals are verboten or that they have no place in 21st century > programming at all. Since I know nothing about your program, I can't > judge whether globals are the right way to go or not. But I am saying > that as a general rule, reliance on global variables often leads to > fragile code with hard-to-diagnose bugs. Your mileage may vary. > > -- > Steven Ha! Gotos I understand the evil of. Human beings don't think that way. Humans are not put together in terms of gotos. Human language does not normally contain gotos. Global, however, seem useful to me. It seems like there are a few things which EVERYONE should know. When you find something often used from a variety of different places, everyone should know about it. It saves time from developing lengthy argument passing chains to follow the passing chains of your program. It keeps the number of arguments low, and easily remembered. This may be more important in python, because python has no type, and where you would have had a type error for forgetting which arg goes where, you have some random thing. Also, My programming style tends towards a mongrel of functional and object oriented programming. I tend to use lone functions when they have no internal state, and objects when they have internal state, but it's not ironclad. It's just what makes sense to me at the time. I'm not defending myself, I'm just setting out my point of view. I'd like to see what you think of it. From ggpolo at gmail.com Mon Jan 7 13:47:07 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 16:47:07 -0200 Subject: Does Python cache the startup module? In-Reply-To: References: Message-ID: 2008/1/7, Baz Walter : > Hello > > I remember reading somewhere (probably this list) that python may cache the > module that starts a program (e.g. 'main.py'). Something like mod_python will do caching. > I'm asking because I have found > that this can sometimes cause problems when making small edits to the module. > For instance, in my current module I changed the name of the main gui widget. > When I ran the program, the program started to leak memory like a sieve. I then > changed the name back again, and the problem went away. This looks very much > like some sort of weird caching behaviour to me. Uhm.. this didn't make much sense. If you say the module is cached, then supposing you did a minor edit, and then supposing because it is cached your application wouldn't detect the change, then I don't see the connection with memory leak. Bring some concrete proof. > > I've tried deleting the .pyc file and even re-booting, but I can't make the > problem go away! > > Can anyone confirm that this caching happens? And if so, is it documented > anywhere? > > TIA > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From scrdhrt at gmail.com Thu Jan 17 07:21:55 2008 From: scrdhrt at gmail.com (Sacred Heart) Date: Thu, 17 Jan 2008 04:21:55 -0800 (PST) Subject: Loop in a loop? Message-ID: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Hi, I'm new to Python and have come across a problem I don't know how to solve, enter com.lang.python :) I'm writing some small apps to learn the language, and I like it a lot so far. My problem I've stumbled upon is that I don't know how to do what I want. I want to do a loop in a loop. I think. I've got two arrays with some random stuff in, like this. array1 = ['one','two','three','four'] array2 = ['a','b','c','d'] I want to loop through array1 and add elements from array2 at the end, so it looks like this: one a two b three c four c I'm stuck. I know how to loop through the arrays separatly and print them, but both at the same time? Hmmm. A push in the right direction, anyone? R, SH From joshuagilman at gmail.com Sun Jan 20 11:38:06 2008 From: joshuagilman at gmail.com (Joshua Gilman) Date: Sun, 20 Jan 2008 08:38:06 -0800 Subject: Looping through the gmail dot trick Message-ID: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> So I have a very interesting task ahead of me and it is to loop through an email using the 'gmail dot trick'. Essentially this trick puts periods throughout your email to make it look different. Even though it has periods gmail will replace them all and send it to that email. So blah at gmail.com is the same as bl.ah at gmail.com. My task is this: Loop through an email and create as many combinations of periods as possible. So all the combinations for blah would be: b.lah bl.ah bla.h b.l.ah b.la.h bl.a.h I'm still rather new to python so this is turning out to be rather tricky. My current code is as follows: for d in range(1, len(email)): > for i in range(1, len(email)): > y = i > temail = email > for x in range(d): > if email[y] == '.': break > temail = temail.replace(email[y], '.' + email[y]) > if not y > len(email) - 2: y += 1 > print temail > It's not looking too bad except for some reason it's making emails like bl..ah which is invalid. So can anyone help me out with getting this to work? Thanks. Cheers, Josh -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Sun Jan 13 09:46:33 2008 From: cwitts at gmail.com (Chris) Date: Sun, 13 Jan 2008 06:46:33 -0800 (PST) Subject: Exceptions - How do you make it work like built-in exceptions? References: <7888e20f-0775-46c4-a6e2-3fc3825c5145@e23g2000prf.googlegroups.com> Message-ID: On Jan 13, 4:14 pm, Lie wrote: > A built-in exceptions, when raised, would print traceback that points > out the offending code, like this: > > Traceback (most recent call last): > File "F:\dir\code.py", line 43, in > a = 1/0 <<<--- > ZeroDivisionError: integer division or modulo by zero > > a user-made exception, when raised, would print traceback that points > out the code that raises the exception > > Traceback (most recent call last): > File "F:\dir\code.py", line 48, in > raise SomeException('Some Exception Message') <<<--- > SomeException: Some Exception Message > > which is generally of little use (yeah, it's possible to trace the > code from the line number, but sometimes it might not be that easy, > cause the line number is (again) the line number for the raising code > instead of the offending code) > > The sample exception was generated from this code: > #### > class SomeException(Exception): > pass > > try: > a = 1/0 > except: > raise SomeException('Some Exception Message') > #### > > Is it possible to make the user-made exception points out the > offending code? from sys import exc_info try: a = 1/0 except: type, value, traceback = exc_info() raise SomeException(type) From petr.jakes.tpc at gmail.com Wed Jan 2 20:16:18 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Wed, 2 Jan 2008 17:16:18 -0800 (PST) Subject: Pivot Table/Groupby/Sum question References: <148c3214-77b9-47b0-a680-ffb85dd3efcd@e6g2000prf.googlegroups.com> <7f396128-2ce2-4dd6-bdc0-855bab8750c7@w38g2000hsf.googlegroups.com> <9f7b6dcc-216d-46a9-a9d5-022c00ee9d7d@d21g2000prf.googlegroups.com> <1caf93fd-3a50-4c77-87b0-5312cdebd35f@d21g2000prf.googlegroups.com> <63a5a87e-3385-4ef0-80a3-cd1a01eeeac3@w38g2000hsf.googlegroups.com> <276d150b-6b2a-4973-8569-bd8cad6df948@s19g2000prg.googlegroups.com> <018c37d5-67c0-4995-88e3-86f701580c26@e23g2000prf.googlegroups.com> <5d6721cc-1912-4adc-9e47-0afa21c51c89@21g2000hsj.googlegroups.com> Message-ID: <17de023b-8dfd-4478-8271-96e21968d489@s8g2000prg.googlegroups.com> > So the data comes in as a long list. I'm dealing with some > information on various countries with 6 pieces of information to > pivot. Just to make it simple it's like a video store database. The > data is like [Country, Category, Sub Category, Film Title, Director, > Number of Copies]. data = [['Italy', 'Horror', '70s', 'Suspiria', > 'Dario Argento', 4],['Italy', 'Classics', 'Neo-Realist', 'Otto e > Mezzo', 'Fellini', 3],['Italy', 'Horror', '70s', 'Profondo Rosso', > 'Dario Argento', 4],...]. So there are 4 copies of Suspiria and 3 of > 8 1/2. What I want is the total number of films for each country, > category and subcategory, ie there are 11 Italian films and 8 Italian > horror films from the 70s, etc...I will then output the data like this > | Horror | Classics ... > Total | 70s Slasher | Neo-Realist Western ... > Total > America 200 20 30 0 10 ... > Argentina 304 1 0 0 0 ... > .... > Italy 11 7 0 3 0 ... Did you mean your table has to look like the following? | Horror | Horror | Classics | Classics Total | 70s | Slasher | Neo-Realist | Western ... Total America 200 20 30 0 10 ... Argentina 304 1 0 0 0 ... .... From ptmcg at austin.rr.com Tue Jan 22 09:31:29 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 22 Jan 2008 06:31:29 -0800 (PST) Subject: HTML parsing confusion References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> Message-ID: On Jan 22, 7:44?am, Alnilam wrote: > ...I move from computer to > computer regularly, and while all have a recent copy of Python, each > has different (or no) extra modules, and I don't always have the > luxury of downloading extras. That being said, if there's a simple way > of doing it with BeautifulSoup, please show me an example. Maybe I can > figure out a way to carry the extra modules I need around with me. Pyparsing's footprint is intentionally small - just one pyparsing.py file that you can drop into a directory next to your own script. And the code to extract paragraph 5 of the "Dive Into Python" home page? See annotated code below. -- Paul from pyparsing import makeHTMLTags, SkipTo, anyOpenTag, anyCloseTag import urllib import textwrap page = urllib.urlopen("http://diveintopython.org/") source = page.read() page.close() # define a simple paragraph matcher pStart,pEnd = makeHTMLTags("P") paragraph = pStart.suppress() + SkipTo(pEnd) + pEnd.suppress() # get all paragraphs from the input string (or use the # scanString generator function to stop at the correct # paragraph instead of reading them all) paragraphs = paragraph.searchString(source) # create a transformer that will strip HTML tags tagStripper = anyOpenTag.suppress() | anyCloseTag.suppress() # get paragraph[5] and strip the HTML tags p5TextOnly = tagStripper.transformString(paragraphs[5][0]) # remove extra whitespace p5TextOnly = " ".join(p5TextOnly.split()) # print out a nicely wrapped string - so few people know # that textwrap is part of the standard Python distribution, # but it is very handy print textwrap.fill(p5TextOnly, 60) From steven at REMOVE.THIS.cybersource.com.au Mon Jan 21 04:21:32 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 09:21:32 -0000 Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> <479451D9.3060207@block.duxieweb.com> Message-ID: On Mon, 21 Jan 2008 16:23:50 +0800, J. Peng wrote: > J. Peng ??: > >> k = (i.split())[3] >> y = (i.split())[1] > > btw, why can't I write the above two into one statement? > > (k,y) = (i.split())[3,1] I don't know. What's "i"? I'm guessing "i" is a string (and what a horrible choice of a name for a string!) So i.split() will return a list. List indexing with multiple arguments isn't defined, which is why you can't write k, y = (i.split())[3,1] BTW, the outermost set of brackets is unnecessary. You can write: i.split()[3] instead of (i.split())[3] -- Steven From mail at timgolden.me.uk Tue Jan 22 04:58:33 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 22 Jan 2008 09:58:33 +0000 Subject: stdin, stdout, redmon In-Reply-To: <4795ba80$0$17176$426a74cc@news.free.fr> References: <4794a5e3$0$9014$426a74cc@news.free.fr> <4794ab22$0$19179$426a74cc@news.free.fr> <4795ba80$0$17176$426a74cc@news.free.fr> Message-ID: <4795BE49.5000708@timgolden.me.uk> Bernard Desnoues wrote: > Hello, > > I checked under linux and it works : > text.txt : > "first line of the text file > second line of the text file" > > test.py : > "import sys > a = sys.stdin.readlines() > x = ''.join(a) > x = x.upper() > sys.stdout.write(x)" > > >cat text.txt | python test.py > > But I reinstalled Python 2.5 under Windows XP and it doesn't work > anyway. Can you confirm that your script works with Win XP and Python 2.5 ? How are you invoking the script under WinXP? If you're using the standard file associations then stdin/stdout won't work correctly. However, they produce a specific error message: C:\temp>type test3.py import sys print sys.stdin.readlines () C:\temp> C:\temp>type test3.py | test3.py Traceback (most recent call last): File "C:\temp\test3.py", line 3, in print sys.stdin.readlines () IOError: [Errno 9] Bad file descriptor C:\temp>type test3.py | python test3.py ['import sys\n', '\n', 'print sys.stdin.readlines ()'] TJG From albert at spenarnc.xs4all.nl Sat Jan 19 13:16:59 2008 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 19 Jan 2008 18:16:59 GMT Subject: Details about pythons set implementation References: <13ntbv51tqcm7c@corp.supernews.com> <83b78deb-b7c4-4fa3-b9ad-1a40be4f9231@n22g2000prh.googlegroups.com> Message-ID: In article <83b78deb-b7c4-4fa3-b9ad-1a40be4f9231 at n22g2000prh.googlegroups.com>, bukzor wrote: >On Jan 4, 2:15 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 04 Jan 2008 09:29:50 -0800, bukzor wrote: >> > Why cant you implement < for complex numbers? Maybe I'm being naive, but >> > isn't this the normal definition? >> > a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) >> >> No, it is not. Ordered comparisons are not defined for complex numbers. Mathematically speaking, it depends what you require from ordering. Mostly (and what we need for fast lookup) we want transitivity: A>=B & B>=C => A>=C Requiring transitivity you are right with your concern about the OP's version of <. Although in mathematics you can define things as you like, a non-transitive < is frowned upon. >> Which is bigger, 4+2j or 2+4j? We can make a useful ordering by defining A<=B : if RE(A) /= RE(B) then RE(A) <= RE(B) else IM(A) <= IM(B) So for the OP's example: 4+2i is bigger. This is sufficient to put a bunch of complex numbers in an array, sort the array, and have a lookup using binary search. (Or a heap: a heap is better for frequent additions and deletions.) >> >> > How do you implement a set without sorting? >> >> With a hash table. >> >> Or if you are willing to limit yourself to sets of small integers, you >> can implement it using bit flipping. E.g. 5 is an element of the set if >> bit 5 is on. Or if you can live with O(n) implementations are trivial. >> >> > Are you expecting better than O(log n)? >> >> Sure. The same applies to sets of complex numbers the C++ way with the above definition of for < for complex numbers. >> >> -- >> Steven > >Good Answers! -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- like all pyramid schemes -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From deets at nospam.web.de Tue Jan 29 17:50:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jan 2008 23:50:23 +0100 Subject: Terse Syntax through External Methods In-Reply-To: References: <5vu9gaF1no9i1U1@mid.uni-berlin.de> Message-ID: <609otnF1phb32U2@mid.uni-berlin.de> Jens schrieb: > On Jan 25, 3:19 pm, "Diez B. Roggisch" wrote: >> Jens schrieb: >> >> >> >>> Hello Everyone >>> I'm newbie to Zope and i have a few questions regarding external >>> methods. What i wan't to do >>> is provide a terse syntax for converting urls to special tracking >>> urls: >>> >>> turns the provided url into something like >>> http://host/tracking?url=http%3A%2F%2Fmyurl%2F >>> in the output. >>> i've been trying to use a external procedure like this. >>> ## Script (Python) "track_link" >>> ##bind container=container >>> ##bind context=context >>> ##bind namespace=_ >>> ##bind script=script >>> ##bind subpath=traverse_subpath >>> ##parameters=self,url >>> ##title=track link >>> ## >>> return "%s%s" % (self.tracking_prefix, url_quote(url)) >>> This doesn't work because because the method doesn't have access to >>> the environment. Obviously I don't wan't to pass everything explicitly >>> into the function as this would defeat the purpose of the exercise, >>> namely to provide a terse syntax. >>> I have a background in other languages so I might be missing something >>> conceptually with regard Zope and DTML.. Is there a better was of >>> doing this, perhaps without using external methods? Currently im doing >>> the following which isn't very elegant: >>> in content document >>>
>> tracking>">link >>> ... >>> tracking: >>> >>> Appreciate any input you might have on this- >> Is it really needed to use an external method for this, or isn't a >> "normal" python script enough already? >> >> If it has to be an External method, you can't access such a context >> AFAIK. But then you can create a python script that _has_ this context, >> and passese it to the external method. Not the nicest solution, but >> should work. >> >> Diez > > Like I said i'm a newbie. I though the deal with Zope was that i > couldn't really do inline scripting (for security reasons) > like in php but had to use these external methods. how does one go > about creating a "normal" python script exactly and > how do I invoke it's functionality? Read the docs: http://www.zope.org/Documentation/Books/ZopeBook/2_6Edition/ScriptingZope.stx There's everything in there you need. Diez From sunilkrghai at gmail.com Wed Jan 2 09:57:09 2008 From: sunilkrghai at gmail.com (Sunil Ghai) Date: Wed, 2 Jan 2008 20:27:09 +0530 Subject: Network-Packets Message-ID: <52da23100801020657v2d6e001ck5a9e126db77eb511@mail.gmail.com> Hello guys, I know this is not the right place for asking about this but i am sure some of you must have an idea about this. I have a bit knowledge about networking and protocols. I would like to know what do we actually mean by "Bandwidth". As in if a person is allowed to download stuff of about 400MB than is it the size of all the Packets the system recieves? and if by some reason the operating system discards the packet it recieves and does not forward to the appropiate application through port number then that packet size gets include in the limited access of user or not? I am really in need to get clear this point. Thanks alot in advance.. -- Sunil Kumar Ghai -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Tue Jan 8 09:10:45 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 8 Jan 2008 06:10:45 -0800 (PST) Subject: windows service References: Message-ID: On Jan 7, 6:42 pm, Michael Chesterton wrote: > I'm trying to get a program that uses M2Crypto ThreadingSSLServer to > run in windows as a service. I have a few problem, it doesn't listen > on its port and I don't know how to debug it. > > I used the pipeservice example as a framework to get it running as a > service > > def SvcDoRun(self): > # Write an event log record - in debug mode we will also > # see this message printed. > servicemanager.LogMsg( > servicemanager.EVENTLOG_INFORMATION_TYPE, > servicemanager.PYS_SERVICE_STARTED, > (self._svc_name_, '') > ) > > daemonserver = do_daemon() > while 1: > daemonserver.handle_request() > > I think I need a way to break out of that while loop when a service > stop is sent, but not knowing what happening at that point I'm not > sure how. It's not even listening on its port. > > daemonserver is > > daemonserver = SSL.ThreadingSSLServer((host_ip_addr, int > (host_port_num)), TestRequestHandler, ctx) > > any help? > > -- > Michael Chestertonhttp://chesterton.id.au/blog/http://barrang.com.au/ > > -- > Michael Chestertonhttp://chesterton.id.au/blog/http://barrang.com.au/ Before you get it going as a service, test it as just a regular Python script. I've created local servers using CherryPy before and been able to test them. I recommend you do the same with yours before changing it to a service. If you have a firewall installed (which you should), you may need to allow your program access through it. I've occasionally had to allow localhost with some of the more stringent firewalls. I found this post on creating a Windows Service for Windows 2000, which can probably be modified for XP: http://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html There's also this one: http://essiene.blogspot.com/2005/04/python-windows-services.html They both sound different from the way you did it, but maybe I misunderstood. Mike From jeya.jpl62 at gmail.com Mon Jan 28 07:55:01 2008 From: jeya.jpl62 at gmail.com (jpl) Date: Mon, 28 Jan 2008 04:55:01 -0800 (PST) Subject: confidence your earning power Message-ID: <89cbb38b-d0e4-4d8e-9f23-07ed2d8266af@e6g2000prf.googlegroups.com> By increasing your earning power you may be able to get a better job and more pay. Many people suffer a money loss because of their lack in confidence and knowledge. There are several ways you can increase your earning power but the first way is to realize what you are really worth. Take a long hard look at yourself and figure out who you really are and what you really want to be. Have you done that? If you are ready to learn how to increase your earning power then continue to read. http://ingreasingyourearningsuccess.blogspot.com From bearophileHUGS at lycos.com Wed Jan 30 08:17:41 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jan 2008 05:17:41 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> Message-ID: <3afdfcbd-2624-4b67-9ffc-1d0aa5690aa1@i72g2000hsd.googlegroups.com> If you don't want to reinvent the wheel all the time you can use this one: def inplacefilter(pred, alist): """inplacefilter(pred, alist): filters the given list like filter(), but works inplace, minimizing the used memory. It returns None. >>> pr = lambda x: x > 2 >>> l = [] >>> inplacefilter(pr, l) >>> l [] >>> l = [1,2,2] >>> inplacefilter(pr, l) >>> l [] >>> l = [3] >>> inplacefilter(pr, l) >>> l [3] >>> l = [1,2,3,1,5,1,6,0] >>> r = filter(pr, l) # normal filter >>> r [3, 5, 6] >>> inplacefilter(pr, l) >>> r == l True """ slow = 0 for fast, item in enumerate(alist): if pred(item): if slow != fast: alist[slow] = alist[fast] slow += 1 del alist[slow:] If you use Psyco you can replace the enumerate() with a manually incremented counter to speed up the code a bit, like this (untested): def inplacefilter(pred, alist): slow = 0 fast = 0 for item in alist: if pred(item): if slow != fast: alist[slow] = alist[fast] slow += 1 fast += 1 del alist[slow:] Bye, bearophile From danielsson.lorenzo at gmail.com Fri Jan 25 16:06:57 2008 From: danielsson.lorenzo at gmail.com (Lorenzo E. Danielsson) Date: Fri, 25 Jan 2008 21:06:57 +0000 Subject: looking for a light weighted library/tool to write simple GUI above the text based application In-Reply-To: <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> Message-ID: <479A4F71.9060501@gmail.com> petr.jakes.tpc at gmail.com wrote: >>> is already solved). >> what you are looking for is curse :) >> http://docs.python.org/lib/module-curses.html >> http://www.ibm.com/developerworks/linux/library/l-python6.html >> >> renaud > > Renaud, thanks for your reply. > > I think I was not specific/clear enough in my first posting. I know > the curses library ( http://pyncurses.sourceforge.net ). It AFIK > provides TUI (short for: Text User Interface or Textual User > Interface). My needs are GUI, I mean "a nice VGA pictures" on the VGA > LCD 10" display. > > Petr What you need then is something like SVGAlib (http;//svgalib.org). Only really old people like myself know that it exists. I've never heard of any Python bindings for it, but that might be where you come in. I haven't looked at SVGAlib for years, and I'm not sure about the state of the video drivers. I suggest you look at that first. You could also look at GGI (http://ggi-project.org). GGI has different output targets. IIRC, one of them is directfb. To tell you the truth I've never really used GGI. There seems to be a python wrapper for GGI, although it is fairly old. Maybe you could look at the code for some ideas. You should also be able to compile SDL to be able to use directfb as a target. If your libSDL handles it, then that should apply to wrapper libraries as well, including pygame. I've never tried running SDL apps this way, but if it works well, that would probably be your 'best' option. Lorenzo From arnodel at googlemail.com Tue Jan 22 11:42:06 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 08:42:06 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: On Jan 22, 4:10?pm, Alan Isaac wrote: > > > fwiw, > Alan Isaac Thanks. So I guess I shouldn't take the code snippet I quoted as a specification of izip but rather as an illustration. -- Arnaud From andre.roberge at gmail.com Sun Jan 27 12:46:29 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 27 Jan 2008 09:46:29 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: Message-ID: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> On Jan 27, 1:06 pm, coldpizza wrote: > There is a pattern that occurs fairly often in constructors in Python > and other OOP languages. > > Let's take an example: > > class Server(object): > def __init__(self, host, port, protocol, bufsize, timeout): > self.host = host > self.port = port > self.protocol = protocol > self.bufsize = bufsize > self.maxthreads = maxthreads > self.timeout = timeout > > Imho, in the class above the assignment to instance fields does not > contain much programming logic and therefore can be safely 'abstracted > away' by the language itself with a syntax which would look something > like this: > > class Server(object): > def __init__(self, @host, @port, @protocol, @bufsize, @timeout): > pass > > This would be equivalent to the first example above, yet it does not > obfuscate the code in any way. Or does it? It does look much cleaner > to me. > > Of course, the ampersand is just an arbitrary choice and might have > bad connotations for those who read it as 'take address of' but @ has > some allusion to delegates which maybe is ok. > > I am not an experienced programmer and I am not sure if this is > necessarily a good idea, so I wanted to get some feedback from more > experienced Pythonistas before submitting it elsewhere. If you search on this list, you will find that there has been *many* proposals to remove self (which, I realize is slightly different than what yo propose) and that the main argument can be summarized as "Explicit is better than implicit." Personally, I like the idea you suggest, with the modification that I would use "." instead of "@", as in class Server(object): def __init__(self, .host, .port, .protocol, .bufsize, .timeout): pass Andr? From arnodel at googlemail.com Thu Jan 3 14:04:06 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 3 Jan 2008 11:04:06 -0800 (PST) Subject: Fate of itertools.dropwhile() and itertools.takewhile() References: <7a86a421-089f-4634-8902-e9edfe139f03@e23g2000prf.googlegroups.com> <33c108cb-4378-4f34-bc52-b179772a73cb@n20g2000hsh.googlegroups.com> Message-ID: <72039809-9ad0-486a-b2fc-a01221eda8b8@1g2000hsl.googlegroups.com> On Jan 3, 4:39?pm, "win... at gmail.com" wrote: > On Dec 29 2007, 11:10 pm, Raymond Hettinger wrote: > > > I'm considering deprecating these two functions and would like some > > feedback from the community or from people who have a background in > > functional programming. > > Well I have just this minute used dropwhile in anger, to find the next > suitable filename when writing database dumps using date.count names: > > ? ? filename = "%02d-%02d-%d" % (now.day, now.month, now.year) > ? ? if os.path.exists(filename): > ? ? ? ? candidates = ("%s.%d" % (filename, x) for x in count(1)) > ? ? ? ? filename = dropwhile(os.path.exists, candidates).next() > > Much clearer than the alternatives I think, please keep dropwhile and > takewhile in itertools ;) Wouldn't using ifilterfalse instead of dropwhile produce the same result? -- Arnaud From python at rcn.com Wed Jan 2 19:33:11 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 2 Jan 2008 16:33:11 -0800 (PST) Subject: Two candies References: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com> <736e51b5-d7f6-4523-89f1-df62256ce7c0@s19g2000prg.googlegroups.com> Message-ID: [Raymond] > >#3 is a fine choice. It is memory efficient -- the repeat() itertool takes-up only a few bytes. It doesn't need psyco, you already have to fast C routines talking to each other without having to go through the interpreter loop.< [bearophile] > In my code I have found otherwise, so to be more sure I have just done > few benchmarks on a Pentium3 CPU, 256 MB RAM, ActivePython 2.5.1.1, on > Win. I applaud your efforts to measure performance -- that is a reasonably good way to find-out the best approach (though you have to be very careful about what you measure, how you measure it, that the system state hasn't changed between measurements, and how your interpret the results). Here's a few thoughts based on knowing what's under-the-hood. * xrange() and repeat() objects only take-up a few bytes. * xrange() creates a new integer object for every iteration * repeat() will re-use the same object over and over * the counter for repeat() does not use integer objects * the list approach takes 4 bytes of memory per entry (pointers to a single object) * lists, xrange objects, and repeat objects all support the iteration protocol * lists and xrange objects also support the sequence protocol (getitem and len) * array_new has a special case for lists -- it uses the known length to pre-size the array and it uses the getitem protocol to access the elements * array_new handles repeat() and xrange() by using the iterator protocol and it grows the array one element at a time, with periodic resizing and over-allocation -- this is dog slow * in most apps (except for sparse arrays), the initialization time for an array is dominated by the time spent actually doing something useful with the array (iow, this is an odd place to be optimizing) * the array module could be made a little smarter by checking the iterators for a hint about their size (this would speed-up the xrange() and repeat() versions considerably). * the array module is not designed for speed -- it is all about storing data compactly * in contract, numpy and other numerical apps are more thoroughly optimized * memory consumption is very difficult to measure since the operating system has a say in the matter (ask for 1 byte of allocation and you may get an enormous chunk in return). That being said, I'll cut to the chase: * sometimes its easy to get so wrapped-up in thinking this though, that the obvious gets missed. * try adding this one to your test suite: a = array('l', [0]) * n Raymond From paul at boddie.org.uk Wed Jan 16 07:21:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 16 Jan 2008 04:21:17 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> Message-ID: <60b75f24-d33a-476e-932d-11dfb9880562@v4g2000hsf.googlegroups.com> On 16 Jan, 02:17, "Jaimy Azle" wrote: > > Wow, serious... what you've done was really, really cool... :) In practice, not that cool. ;-) > I was expect there are nobody willing to do to have python runs Java > Language (such as PyPy) over CPython. Perhaps your javaclass does not work > just like as PyPy, but really... it is damned cool to get CPython execute > java byte-code, congratulations... Well, the limitations that stopped me working on it are listed on the page I referenced, so it wasn't that cool in the end. In fact, the project grew out of just wanting to inspect .class files and pull out method signatures, but it was so tempting to see whether Java bytecodes could be rewritten and run in a CPython environment. I think the benefits of running Java on CPython are significantly less than those had by running Python on the Java VM (or another VM). Firstly, who wants to write statically typed code which then runs on a virtual machine that can't take advantage of the type declarations? Secondly, isn't it just better to use a virtual machine with just-in- time compilation and all sorts of security mechanisms if you're wanting to write the Java code that, when compiled, can take advantage of all that stuff? In other words: what makes CPython a compelling VM for the Java programmer? My perspective now is that it's a lot more interesting to target Python for virtual machines other than the CPython one because that's where the performance and functionality benefits are most likely to be found. And the most important motivation for this: I prefer writing Python, not Java. ;-) Paul From paddy3118 at googlemail.com Mon Jan 7 12:51:58 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 7 Jan 2008 09:51:58 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com><7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com><8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> <13o06hleh4dkj45@corp.supernews.com> Message-ID: On Jan 7, 5:09 pm, "Reedick, Andrew" wrote: > Bingo. Perl has specific operators to establish intent: > > Perl -e "'1' + 1" > > 2 > > Perl -e "'1' . 1" > > 11 > '+' is the operator for addition > '.' is the operator for string concatenation > > int and string comparisons also have specific operators: > $a == $b # compare as integers: ==, >, <, <=, >= > $a eq $b # compare as strings: eq, gt, lt, le, ge > > Which now morphs the conversation into the issue of how too much > operator overloading creates confusion and/or ambiguity. > Or how using different operators for similar operations on different types causes confusion. i.e. == versus eq; > versus gt If Perl had, for example, a complex number 'base' type would that need yet another set of operators? Well enough Perl vs Python. The thing is, that when writing in another programming language you have to use its idioms or you end up fighting the language in attempt to make it work like another language you are more familiar with. In Python strings won't ever automatically change to numbers. - Paddy. From mraborife at yahoo.com Tue Jan 8 02:21:17 2008 From: mraborife at yahoo.com (mpho raborife) Date: Mon, 7 Jan 2008 23:21:17 -0800 (PST) Subject: python syntax:urgent Message-ID: <645055.89441.qm@web45511.mail.sp1.yahoo.com> Anyone please help me get this syntax right subprocess.Popen(["gmmscore", "-i", Input, "-l", List, "-t", modeltype, > "-m", str(mixture), "-d", str(dimension), "-v", str(vfloor), "-n", str(number), "-r", str(results)]) --------------------------------- Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dpsanders at gmail.com Sat Jan 19 10:36:29 2008 From: dpsanders at gmail.com (David Sanders) Date: Sat, 19 Jan 2008 07:36:29 -0800 (PST) Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <2d7f8b3b-afc5-4948-9207-0f39de7d6a96@i12g2000prf.googlegroups.com> On Jan 18, 11:15 am, David Sanders wrote: > Hi, > > I am processing large files of numerical data. Each line is either a > single (positive) integer, or a pair of positive integers, where the > second represents the number of times that the first number is > repeated in the data -- this is to avoid generating huge raw files, > since one particular number is often repeated in the data generation > step. > > My question is how to process such files efficiently to obtain a > frequency histogram of the data (how many times each number occurs in > the data, taking into account the repetitions). My current code is as > follows: Many thanks to all for the very detailed and helpful replies. I'm glad to see I was on the right track, but more happy to have learnt some different approaches. Thanks and best wishes, David. From steven at REMOVE.THIS.cybersource.com.au Wed Jan 23 01:39:26 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 06:39:26 -0000 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Tue, 22 Jan 2008 18:32:22 -0800, George Sakkis wrote: > The OP didn't mention anything about the context; for all we know, this > might be a homework problem or the body of a tight inner loop. There is > this tendency on c.l.py to assume that every optimization question is > about a tiny subproblem of a 100 KLOC application. Without further > context, we just don't know. Funny. As far as I can tell, the usual assumption on c.l.py is that every tiny two-line piece of code is the absolute most critically important heart of an application which gets called billions of times on petabytes of data daily. Given the human psychology displayed involved, in the absence of definitive evidence one way or another it is a far safer bet to assume that people are unnecessarily asking for "the fastest" out of a misguided and often ignorant belief that they need it, rather than the opposite. People who actually need a faster solution usually know enough to preface their comments with an explanation of why their existing solution is too slow rather than just a context-free demand for "the fastest" solution. Fast code is like fast cars. There *are* people who really genuinely need to have the fastest car available, but that number is dwarfed by the vast legions of tossers trying to make up for their lack of self-esteem by buying a car with a spoiler. Yeah, you're going to be traveling SO FAST on the way to the mall that the car is at risk of getting airborne, sure, we believe you. (The above sarcasm naturally doesn't apply to those who actually do need to travel at 200mph in a school zone, like police, taxi drivers and stock brokers.) -- Steven From fredrik at pythonware.com Thu Jan 3 10:21:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 16:21:50 +0100 Subject: Treating a unicode string as latin-1 In-Reply-To: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> References: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Message-ID: Simon Willison wrote: > But ElementTree gives me back a unicode string, so I get the following > error: > >>>> print u'Bob\x92s Breakfast'.decode('cp1252').encode('utf8') > Traceback (most recent call last): > File "", line 1, in > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/encodings/cp1252.py", line 15, in decode > return codecs.charmap_decode(input,errors,decoding_table) > UnicodeEncodeError: 'ascii' codec can't encode character u'\x92' in > position 3: ordinal not in range(128) > > How can I tell Python "I know this says it's a unicode string, but I > need you to treat it like a bytestring"? ET has already decoded the CP1252 data for you. If you want UTF-8, all you need to do is to encode it: >>> u'Bob\x92s Breakfast'.encode('utf8') 'Bob\xc2\x92s Breakfast' From hanke at volny.cz Wed Jan 23 02:58:38 2008 From: hanke at volny.cz (hanke at volny.cz) Date: Wed, 23 Jan 2008 08:58:38 +0100 (CET) Subject: python2.4-dbg and C modules Message-ID: <3bd1fcabde7f9c96bd50d23e961c3b95@www1.mail.volny.cz> Hello, please, when I try to run my code under python2.4-dbg from Ubuntu, the interpreter complains that the Py_InitModule4 symbol is undefined in a C module I'm using (PyOpenAL): ImportError: /var/lib/python-support/python2.4/_openal.so: undefined symbol: Py_InitModule4 Google reveals that this problem is not specific just to PyOpenAL, but I couldn't find out what is the essence of the problem and how python-2.4dbg is different from python2.4 except for including debugging symbols, because in plain python2.4 the module works fine. Also, the same thing happens with python 2.5 (not the -dbg variant). Please, what is the problem and how to overcome it? Thank you, Hynek Hanke From ben at morrow.me.uk Fri Jan 25 22:37:53 2008 From: ben at morrow.me.uk (Ben Morrow) Date: Sat, 26 Jan 2008 03:37:53 +0000 Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> Message-ID: [newsgroups line fixed, f'ups set to clpm] Quoth Summercool : > On Jan 25, 5:16 pm, Summercool wrote: > > somebody who is a regular expression guru... how do you negate a word > > and grep for all words that is > > > > tire > > > > but not > > > > snow tire > > > > or > > > > snowtire > > i could think of something like > > /[^s][^n][^o][^w]\s*tire/i > > but what if it is not snow but some 20 character-word, then do we need > to do it 20 times to negate it? any shorter way? This is no good, since 'snoo tire' fails to match even though you want it to. You need something more like / (?: [^s]... | [^n].. | [^o]. | [^w] | ^ ) \s* tire /ix but that gets *really* tedious for long strings, unless you generate it. Ben From martin at marcher.name Thu Jan 10 05:11:15 2008 From: martin at marcher.name (Martin Marcher) Date: Thu, 10 Jan 2008 11:11:15 +0100 Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: Russ P. wrote: > On Jan 9, 9:47 pm, "Steve Brown" wrote: >> I've got a series of modules which look like this: >> >> #************ >> # >> # Temperature Sense Test >> # >> #************ >> class Test3(ar_test.AR_TEST): >> """Temperature Sense Test""" >> >> I don't like the duplicated information: But the comment is attractive, >> and the docstring self.__doc__ is already in use in the test log. I've >> read that all modules and classes should have docstrings, but I don't >> really have anything else to say, and each module contains only one >> class. I don't think that >> >> """Temperature Sense Test""" >> class Test3(ar_test.AR_TEST): >> """Temperature Sense Test""" >> >> would be a real improvement. >> >> What do you think? It's still duplicated information. > I tend to be a bit skimpy with one-line comments for classes and > methods, but I think a more complete (""" style) comment is often > appropriate for the top of the file. > > I'm sure you can think of more to say than "Temperature Sense Test." exactly my opinion > What temperature? What kind of temperature sensor? What kind of test > is it, and why are you doing it? That may all be obvious in context, > but you've provided no context in your post. Also, if the module is of > any significant size, you might want to provide a clue about who wrote > it. Then, if someone has a question about it later, they will know who > to ask. I tend to mention the main use cases for test classes (especially) and also a "human readable" description of what can happen (forgive me the missing line breaks). Something like this: class Test3(ar_test.AR_TEST): """Temperature Sense Test. This class assures that the connection to the hardware sensor can be established. It also checks a reference sensor that always reports a certain value so that one can be sure correct data values are reported. """ hth martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From george.sakkis at gmail.com Sat Jan 12 00:16:25 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 21:16:25 -0800 (PST) Subject: Import and execfile() References: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> Message-ID: <865225ff-d212-4b22-bd3f-85d0721e3346@f3g2000hsg.googlegroups.com> On Jan 11, 6:54 pm, Mitko Haralanov wrote: > On Fri, 11 Jan 2008 14:05:11 -0800 (PST) > > George Sakkis wrote: > > # trying to set the configuration: > > CFG = {} > > execfile('path/to/some_config.py', CFG) > > > Traceback (most recent call last): > > ... > > ImportError: No module named master_config > > > I understand why this fails but I'm not sure how to tell execfile() to > > set the path accordingly. Any ideas ? > > This might be overly simplistic but you could have a load_config > function which takes the path to the config file and the variable where > to load the config as arguments. > > In the load_config function, you could get the directory part of the > config file path, appending it to sys.path, load the config, and then > remove the newly added directory from sys.path. Thanks, that's basically what I did eventually and it works for my simple requirements. Another alternative would be to require the config files to be modules already in the path. In this case setConfig becomes almost trivial using __import__ instead of execfile(): import inspect def setConfig(configfile): return dict(inspect.getmembers(__import__(configfile, fromlist=True))) On the downside, the config files cannot be moved around as easily as with execfile. Also, if placed in directories that are not in the path, one or more ancestor directories may have to be populated with (empty) __init__.py files to denote them as Python packages. So generally speaking, when should execfile be preferred to __import__, or the other way around ? George From fredrik at pythonware.com Wed Jan 9 07:41:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 13:41:51 +0100 Subject: "Canonical" way of deleting elements from lists In-Reply-To: References: <5ujkbaF1e11ksU1@mid.dfncis.de> <87ejcri96v.fsf@mulj.homelinux.net> <87abnfi84i.fsf@mulj.homelinux.net> <5ujp20F1ehvg2U2@mid.dfncis.de> Message-ID: Nick Craig-Wood wrote: > Using keywords[:] stops the creation of another temporary list. in CPython, "list[:] = iter" actually creates a temporary list object on the inside, in case "iter" isn't already a list or a tuple. (see the implementation of PySequence_Fast() for details). From http Wed Jan 30 02:09:56 2008 From: http (Paul Rubin) Date: 29 Jan 2008 23:09:56 -0800 Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> Message-ID: <7xabmnbxh7.fsf@ruckus.brouhaha.com> Santiago Romero writes: > > >>> li = [1,2,3,4,5] > > >>> filter(lambda x: x != 3, li) > > [1, 2, 4, 5] > > I haven't measured it, but this should be the fast solution in all > the thread ... li.remove(3) is probably faster. From kyosohma at gmail.com Tue Jan 15 13:51:32 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 15 Jan 2008 10:51:32 -0800 (PST) Subject: Open existing Word document, modify and save. References: <1ab91596-e868-4b28-9fe3-34f9129a114f@s8g2000prg.googlegroups.com> Message-ID: On Jan 15, 12:01 pm, gsal wrote: > New to Python and new to Win32. Help please. > > O.k., so this might seem like one of those "can you do my homework" > kind of postings, except that is not homework, it is officework. > > I have been reading the Core Python book and I am really excited about > starting my next project with Python, instead of tcl/tk/Fortran/C. > While I can see how to use it for scientific computing and have gone > with the NumPy and SciPy tutorials, I am having a hard time with > Win32. > > Attempted to read some of the documentation for Win32 and while the > basic stuff talks about creating a document, I did not see how to open > an existing document and modify certain parts of it...and then it > seems that it got very complicated (for me) really quick. Sure, it > seems powerful, but all I need is a small part of it, I think. > > Here is the thing. Here at the office, we have computer programs to > generate spec data and the Applications people have MS-Word documents > in a very specific format where they would like to put such spec > data. > > Initially, I was using merge fields and VB macros, until they stopped > working when newer (non-backwards-compatible) versions came along; > then, I switched to generating *.xml out of the original *.doc file, > breaking it appart, modifying it and gluing back together...this is > very laborious task and I have to go through the whole exercise, > should the application people modify the original *.doc > > So, basically, I am looking for a way to work directly with the > original *.doc, assuming I know everything about it...which I do; in > fact, I have it and can also modify it, should I need to bookmark it > or otherwise modify as needed. > > How to go about it? > > What's the python code to open an existing document, modify it and > save it back? > > how does the Word document needs to be bookmarked/formatted so that it > can be modified? For example, after the computer program has been run > and the new, say, "machine rating" calculated, I need to deposit such > value in a very specific spot in the Word document. > > I presume somebody out there already does this and is willing to > provide some code?. > > Thank you very much in advance. > > gsal As I understand it, the only way to work with MS Word in Python is through COM in much the same manner as VB does. So if you know the COM model that MS Word uses, you shouldn't have too much trouble. I would recommend getting Hammond's and Robinson's book "Python Programming on Win32" though, as it explains using Python this way. They have a sample chapter here: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html It should be noted that Hammond is the author of the PyWin32 modules. ActiveState's website has a special version of Python that includes a COM browser and you can install it without harming your current installation. At least, I've had no problems. Other than that, you'll probably be spending a lot of time on MSDN. Mike From rhamph at gmail.com Tue Jan 15 12:23:53 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 15 Jan 2008 09:23:53 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> Message-ID: <88ef2477-78b7-48d4-9bf7-89ef8340ad33@d21g2000prg.googlegroups.com> On Jan 13, 5:51 am, Richard Szopa wrote: > On Jan 13, 8:59 am, Marc 'BlackJack' Rintsch wrote: > > > On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: > > > However, I am very surprised to learn that > > > > super_object.__getattr__(name)(*args, **kwargs) > > > > getattr(super_object, name)(*args, **kwargs) > > > > are not equivalent. This is quite odd, at least when with len() > > > and .__len__, str() and .__str__. Do you maybe know what's the > > > rationale behind not following that convention by getattr? > > > I think you are confusing `__getattr__` and `__getattribute__` here! > > `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's > > different. > > Well, in my code calling super_object.__getattr__(name)(*args, > **kwargs) and getattr(super_object, name)(*args, **kwargs) gives > *different* effects (namely, the latter works, while the former > doesn't). That kinda suggests that they don't map to each other :-). > And that makes me feel confused. Don't think of them as mappings. Think of them as a way for a class to hook into getattr's protocol, conveniently named similar to getattr (__getattr__ and __getattribute__). getattr() may call several methods, no methods at all, change the arguments, etc. Although len() may seem simple, many others are not so simple. -- Adam Olsen, aka Rhamphoryncus From martin at v.loewis.de Wed Jan 2 03:30:00 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Jan 2008 09:30:00 +0100 Subject: different encodings for unicode() and u''.encode(), bug? In-Reply-To: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> Message-ID: <477B4B88.6070207@v.loewis.de> > i stumbled on this situation, that is if I decode some string, below > just the empty string, using the mcbs encoding, it succeeds, but if I > try to encode it back with the same encoding it surprisingly fails > with a LookupError. This seems like something to be corrected? Indeed - in your code. It's not the same encoding. >>>> unicode(s, 'mcbs') > u'' >>>> unicode(s, 'mcbs').encode('mcbs') > Traceback (most recent call last): > File "", line 1, in > LookupError: unknown encoding: mcbs Use "mbcs" in the second call, not "mcbs". HTH, Martin From sipickles at hotmail.com Tue Jan 29 06:21:52 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Tue, 29 Jan 2008 11:21:52 +0000 Subject: refcount Message-ID: Hi, Is is possible to access the refcount for an object? Ideally, I am looking to see if I have a refcount of 1 before calling del Thanks Simon -- Linux Counter: User# 424693 From basilisk96 at gmail.com Thu Jan 10 19:03:22 2008 From: basilisk96 at gmail.com (Basilisk96) Date: Thu, 10 Jan 2008 16:03:22 -0800 (PST) Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87abneibc7.fsf@benfinney.id.au> Message-ID: On Jan 9, 10:55 pm, Ben Finney wrote: > erik gartz writes: > > The loop performs some actions with web services. The particular > > iteration I'm on isn't important to me. It is only important that I > > attempt the web services that number of times. If I succeed I > > obviously break out of the loop and the containing function (the > > function which has the loop in it) returns True. If all attempts > > fail the containing loop returns False. > > When you have iteration requirements that don't seem to fit the > built-in types (lists, dicts, generators etc.), turn to 'itertools' > in the standard > library. > > >>> from itertools import repeat > > >>> def foo(): > ... import random > ... print "Trying ..." > ... success = random.choice([True, False]) > ... return success > ... > >>> max_attempts = 10 > >>> for foo_attempt in repeat(foo, max_attempts): > ... if foo_attempt(): > ... break > ... > Trying ... > Trying ... > Trying ... > Trying ... > Trying ... > Trying ... > >>> > > Note that this is possibly more readable than 'for foo_attempt in > [foo] * max_attempts", and is more efficient for large values of > 'max_attempts' because 'repeat' returns an iterator instead of > actually allocating the whole sequence. > > > I guess based on the replies of everyone my best bet is to leave the > > code the way it is and suck up the warning from pylint. > > I think your intent -- "repeat this operation N times" -- is better > expressed by the above code, than by keeping count of something you > don't actually care about. > > > I don't want to turn the warning off because catching unused > > variables in the general is useful to me. > > Agreed. > > -- > \ "Dyslexia means never having to say that you're ysror." | > `\ --anonymous | > _o__) | > Ben Finney Neat! That is the best solution I've seen so far. I should definitely dig into the itertools module more often. Cheers, -Basilisk96 From asmodai at in-nomine.org Fri Jan 4 08:21:19 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jan 2008 14:21:19 +0100 Subject: Fortran to Python Message-ID: <20080104132119.GK82115@nexus.in-nomine.org> I got someone who asked me to make changes in an old Fortran program she is using for some calculations. The calculations are pretty standard aside from 2 calls to DLINCG (an IMSL numerical_libraries function to calculate an inverse matrix). What I wonder about, does anybody have a Fortran to Python conversion page somewhere to map some of the basic types to Python equivalents? What kind of speed difference should I expect? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ One often hears the most when everyone is silent... From martin at marcher.name Thu Jan 24 17:49:52 2008 From: martin at marcher.name (Martin Marcher) Date: Thu, 24 Jan 2008 23:49:52 +0100 Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <4798ec32$0$36333$742ec2ed@news.sonic.net> Message-ID: On Thursday 24 January 2008 20:56 John Nagle wrote: > Ira.Kovac at gmail.com wrote: >> Hello all, >> >> I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like >> to sort based on first two characters. > > Given those numbers, the average number of characters per line is > less than 2. Please check. which would be true if 1.599.999.999 had 2 chars and the rest of the lines just one :) (but yes that would be an interesting question how to sort a 1 character line based on the first 2 of that line) martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From bernhard.merkle at googlemail.com Fri Jan 4 03:18:42 2008 From: bernhard.merkle at googlemail.com (Bernhard Merkle) Date: Fri, 4 Jan 2008 00:18:42 -0800 (PST) Subject: reassign to builtin possible !? References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> <477CEB93.8000706@tim.thechases.com> Message-ID: <3ea5c5c2-0d7c-4dc2-a5b9-ea9b0c895a5f@i3g2000hsf.googlegroups.com> On Jan 3, 8:06 pm, "Chris Mellon" wrote: > In Py3k this will be a syntax error, like assigning to None is now. > Possibly also in 2.6. thanks. I feed much better with that :-) From yann.le_boulanger at u-paris10.fr Tue Jan 22 15:09:50 2008 From: yann.le_boulanger at u-paris10.fr (Yann Leboulanger) Date: Tue, 22 Jan 2008 21:09:50 +0100 Subject: PyGTK, Glade, and ComboBoxEntry.append_text() In-Reply-To: <4066a33f-6293-48e3-a48c-66af699d0eb9@i29g2000prf.googlegroups.com> References: <4066a33f-6293-48e3-a48c-66af699d0eb9@i29g2000prf.googlegroups.com> Message-ID: <47964d8b$0$963$426a74cc@news.free.fr> Greg Johnston wrote: > Hey all, > > I'm a relative newbie to Python (switched over from Scheme fairly > recently) but I've been using PyGTK and Glade to create an interface, > which is a combo I'm very impressed with. > > There is, however, one thing I've been wondering about. It doesn't > seem possible to modify ComboBoxEntry choice options on the fly--at > least with append_text(), etc--because they were not created with > gtk.combo_box_entry_new_text(). Basically, I'm wondering if there's > any way around this. > > Thank you, > Greg Johnston PyGTK mailing list: http://pygtk.org/feedback.html From jarausch at skynet.be Wed Jan 9 13:31:08 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 09 Jan 2008 19:31:08 +0100 Subject: asynchronous timer events - how to? In-Reply-To: References: <4784fd96$0$22305$ba620e4c@news.skynet.be> Message-ID: <478512EC.8000404@skynet.be> Fredrik Lundh wrote: > Helmut Jarausch wrote: > >> I'm using a web server (Karrigell) which is based on the asyncore module. >> I'd like to be able to checkpoint some data (e.g. pickled >> dictionaries) to disk >> from time to time. >> For that I would need to setup a timer which calls a Python >> object/function when its time interval has expired. While this >> function is running I need access to the variables of the server. > > the usual way to do that with asyncore is to add an outer control loop > that calls asyncore.loop with a count argument (or poll directly), and > checks a "task queue" at regular intervals. > > but in your case, it's probably easier to set up a cron job that does > a "wget" against your server with a "secret" URL, and have the server do > the checkpointing whenever that URL is fetched. Thanks for this ingenious idea, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From hniksic at xemacs.org Thu Jan 17 10:44:15 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 17 Jan 2008 16:44:15 +0100 Subject: Is this a bug, or is it me? References: Message-ID: <87myr4o3sg.fsf@mulj.homelinux.net> "Neil Cerutti" writes: > You cannot access a class's class variables in it's class-statement > scope, since the name of the type is not bound until after the class > statement is completed. But they are still available as locals, so you can access them using their names, like this: >>> class C: ... a = 1 ... b = 2 ... print a+b ... 3 The question is, why doesn't the OP's code snippet work? It seems that the generator expression can't read the surrounding locals(). But when you change the generator expression to a list comprehension using a pair of [] around it, it starts working. Compare: class C(object): d = {} for a in 1, 2, 3: ignore = list((a, b) for b in (4, 5, 6)) Traceback (most recent call last): File "", line 1, in File "", line 4, in C File "", line 4, in NameError: global name 'a' is not defined with: class C(object): d = {} for a in 1, 2, 3: ignore = [(a, b) for b in (4, 5, 6)] It seems that generator expressions and list comprehensions have subtly different scoping rules. Whether this is a bug or not is a good question. From eproust at gmail.com Sun Jan 20 16:58:13 2008 From: eproust at gmail.com (pythonewbie) Date: Sun, 20 Jan 2008 13:58:13 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> Message-ID: <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> On 20 jan, 20:59, "Diez B. Roggisch" wrote: > pythonewbie schrieb: > > > > > On 20 jan, 19:50, "Diez B. Roggisch" wrote: > >> pythonewbie schrieb: > > >>> On 20 jan, 12:20, Christian Heimes wrote: > >>>> pythonewbie wrote: > >>>>> I am stucked on creating a function to get the Python install > >>>>> directory (and site-packages directory) with a 100% reliable method... > >>>> Only one method is 100% reliable: > >>>> try: > >>>> import yourextension > >>>> except ImportError: > >>>> available = False > >>>> else: > >>>> available = True > >>>> Christian > >>> Hi Christian, > >>> OK thanks, interesting to detect if an extension is available or not. > >>> But for different reasons I also want to get the absolute path of > >>> Python install directory (not only the executable under Linux) and > >>> site-packages directory. > >>> How could I proceed ? > >> Maybe sys.path is a starter? > > >> Diez > > > Yes, it is, but my problem is that I am not sure to find the > > information I need at the same position of the list generated by > > sys.path. > > > I explain, for Win32, I find install directory using sys.path[6] and > > site-package directory using sys.path[7], for Linux I find install > > directory using sys.path[2] and site-package directory using > > sys.path[6]. > > > For my tests, I have used XP Pro and Ubuntu Gutsy. > > > I am not sure to find these information at the same position in the > > sys.path list using Win9x, Win2k, Ubuntu Dapper, Redhat FC6, FreeBSD > > and using Python v2.1 2.2 2.3 etc ? > > > This why I'm asking experienced programmers of this usenet group for > > advices. > > Sorry, I missed your first post. However, I don't see what your problem > actually is. If you want to look for any extension, you need to consider > whatever can be seen in the sys.path. So what do you care about the > order of them? > > Diez I just would like to know if I would ALWAYS find the install directory in sys.path[6] and site-packages directory in sys.path[7] on any Win32 platform and sys.path[2] and site-packages directory in sys.path[6] on any Linux platform. If the reply is : "YES you can be sure of it !" All would be great for me and I would be ready to create a script to detect with a reliable manner the installation dir. et site-packages dir. for all my Linux/Win32 Python apps. Thanks for your interest on this topic. From deets at nospam.web.de Fri Jan 4 08:50:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 04 Jan 2008 14:50:59 +0100 Subject: Strange varargs issue In-Reply-To: References: Message-ID: <5u6ru4F1gplq5U1@mid.uni-berlin.de> Mike schrieb: > I'm not sure if this is a bug or if I'm just not understanding > something correctly. I'm running the following (broken.py) on > ActivePython 2.5.1.1, based on Python 2.5.1 (r251:54863 5/1/2007) as > "python broken.py foo" (on Windows, of course): > > > #!/bin/env python > > import sys > > class foobar(object): > def func(arg): > print 'foobar.func: %r' % arg This needs to be def func(self, arg): .... And then of course for aclling, you need an instance of foobar as first argument. Either explicit, or implicit: unbound_m = foobar.func unbound_m(some_foobar, arg) bound_m = foobar().func bound_m(arg) Or you do @classmethod def func(cls, arg): ... Then you only need one argument, but beware: it's a classmethod, not an instancemethod anymore. Diez Diez From steve at holdenweb.com Wed Jan 30 11:13:09 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Jan 2008 11:13:09 -0500 Subject: Removing Pubic Hair Methods In-Reply-To: <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> Message-ID: Wildemar Wildenburger wrote: > Gerardo Herzig wrote: >> I will use genital().extend(), thats for shure ^^ > > Well, you never go wrong with apply(genital(), females), do you? > > /W That's enough genitalia [ed] -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From paul at boddie.org.uk Wed Jan 23 10:28:45 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 23 Jan 2008 07:28:45 -0800 (PST) Subject: Problem with processing XML References: <13pbudgks88rcf3@corp.supernews.com> <47971EFF.8070701@web.de> <6c291c78-7a11-4d6f-be15-c916017ccf60@s13g2000prd.googlegroups.com> <47974B47.5000509@web.de> Message-ID: <03f25aca-33ee-4dc4-8b67-9a9dbb9aa8e5@y5g2000hsf.googlegroups.com> On 23 Jan, 15:12, Stefan Behnel wrote: > > Paul Boddie wrote: > > I'm not disputing the benefits of the ElementTree approach, but one > > has to recall that the DOM is probably the most widely used XML API > > out there (being the one most client-side developers are using) and > > together with the other standards (XPath and so on) isn't as bad as > > most people like to make out. > > I didn't deny that it works in general. However, it does not fit into the > standard ways things work in Python. You're only one step away from using the magic word. I agree that writing getAttribute all the time instead of, say, using magic attributes (provided the characters employed are lexically compatible with Python - another thing that people tend to overlook) can be distressing for some people, but as usual the language comes to the rescue: you can assign the method to a shorter name, amongst other things. If you want to stray from the standards then with some APIs (as you know), you can override various classes and provide your own convenience attributes and methods, but the interoperability remains beneath. > > Furthermore, I don't think it does > > Python much good to have people "acting all Ruby on Rails" and telling > > people to throw out everything they ever did in order to suck up the > > benefits, regardless of the magnitude of those benefits; it comes > > across as saying that "your experience counts for nothing compared to > > our superior skills". Not exactly the best way to keep people around. > > I would have formulated it a bit different from my experience, which usually > is: people complain on the list that they can't manage to get X to work for > them. Others tell them: "don't use X, use Y", implicitly suggesting that you > may have to learn it, but it will help you get your problem done in a way that > you can /understand/ (i.e. that will fix your code for you, by enabling you to > fix it yourself). If people feel that they've solved 90% of the problem using tools they're become familiar with, I think it's somewhat infuriating to be told to forget about the last 10% and to use something else. We don't know how nasty the code is in the case of this particular inquirer, but I've seen nothing recently where the DOM specifically was obstructing anyone's comprehension. In one case, had PyXML or minidom been up-to-date, the solution would have been within easy reach (the textContent property), but with everyone being waved off to greener pastures, there's probably little gratitude to be had in doing the legwork to fix and enhance those implementations. [...] > > like the DOM stuff, if the support for standardised/ > > recognised technologies is perceived as deficient, and given the point > > above about glossing over what people themselves bring with them to > > solve a particular problem, then people are quite likely to gloss over > > Python than hear anyone's sermon about how great Python's other XML > > technologies are. > > It's not about "other XML technologies", it's only about making the standard > XML technologies accessible and usable. It's about designing interfaces in a > way that matches the tool people are using anyway, which in this case is Python. Well, the standard XML technologies include those covered by PyXML, like it or not, and whilst some APIs may be nicer than the variants of the standard APIs provided by PyXML, there's a lot of potential in those standards that hasn't been exploited in Python. Consider why the last Web browser of note written in Python was Grail, circa 1996, for example. Paul From castironpi at gmail.com Sat Jan 12 08:53:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 05:53:47 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> Message-ID: <354c74f6-6e56-4e41-a686-56239aa4cea9@f47g2000hsd.googlegroups.com> On Jan 12, 3:51 am, Fredrik Lundh wrote: > castiro... at gmail.com wrote: > > I'm writing an NxN observer pattern, mostly for my own personal > > exploration. Two threads -might- be calling 'Disconnect' at the same > > time, and I can't even guarantee that the function runs properly. > > > for emelem in [ e for e in emlist if e.func is func ]: > > try: > > emlist.remove( emelem ) > > except ValueError: > > pass > > so use a lock. it's a whopping two lines of code: > > creation: > > lock = threading.Lock() > > usage: > > with lock: > for emelem in ... > ... > > more here: > > http://effbot.org/zone/thread-synchronization.htm > > and btw, looping over a list to figure out what you want to remove from > that list is a bit pointless. better just create a new list: > > with lock: > # get rid of all func instances > emlist = [e for e in emlist if e.func is not func] > > an alternative approach would be to replace emlist with a dictionary, > keyed on func objects. that'll let you remove all items associated with > a given function with a single atomic operation: > > del emdict[func] > > -> so use a lock. it's a whopping two lines of code: Yes. 1) I'm wondering what the specifics are on [Rubin]: >>2. Associate a lock with the list. Anything wanting to access the list should acquire the lock, do its stuff, then release the lock. This gets confusing after a while.<< I considered these suggestions early on. They apply often but I ruled them out for reasons: 2) List is referenced by others; concurrent modifications may be going on; can not replace it. Can I make asynchronous modifications and merge the changes, SCM-style? 3) Dictionary returns non-static order; order is important. Create a int-func tuple and sort dictionary results? Perhaps. That's sounding pretty good. From lasses_weil at klapptsowieso.net Sun Jan 27 20:13:07 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 28 Jan 2008 02:13:07 +0100 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: <87d4rm93l1.fsf@benfinney.id.au> References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> Message-ID: <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> Ben Finney wrote: > "Andr?" writes: > >> Personally, I like the idea you suggest, with the modification that I >> would use "." instead of "@", as in >> >> class Server(object): >> def __init__(self, .host, .port, .protocol, .bufsize, .timeout): >> pass > > -1. > > That leading dot is too easy to miss when looking over the code. > class Server(object): def __init__(self, self.host, self.port, self.protocol, self.bufsize, self.timeout): pass ? /W From tdelaney at avaya.com Sun Jan 20 17:58:26 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 21 Jan 2008 06:58:26 +0800 Subject: Looping through the gmail dot trick In-Reply-To: <13p7i5qaihgte12@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > Postfix, I think, interpets "foo+bar" the same as "foo". Gmail does the same. It's quite useful - apart from using it to determine which site I signed up to has sent me mail, I also use it so I can have multiple Guild Wars accounts using the same email account e.g. +gw1 at gmail.com +gw2 at gmail.com All resolve to @gmail.com. I have a couple of spare accounts so when friends or relative visit we can all play together ... Tim Delaney From gagsl-py2 at yahoo.com.ar Tue Jan 29 14:57:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jan 2008 17:57:40 -0200 Subject: Zipfile content reading via an iterator? References: <475EEF96.2070203@tim.thechases.com> <475FF830.4070508@tim.thechases.com> <479F24C4.9000402@tim.thechases.com> Message-ID: En Tue, 29 Jan 2008 11:06:12 -0200, Tim Chase escribi?: > Just to follow up on this, I dropped the the 2.6 version of > zipfile.py in my project folder (where the machine is currently > running Python2.4), used the ZipFile.open() and it worked fine. > [...] > Anyways, thanks to Gabriel (and all the authors of Python > zipfile.py library) for the solution. I just bring attention to the upcoming feature. All credit should go to the patch author, Alan McIntyre. -- Gabriel Genellina From exarkun at divmod.com Tue Jan 22 09:34:33 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 22 Jan 2008 09:34:33 -0500 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <5vmc4fF1n9pk6U1@mid.uni-berlin.de> Message-ID: <20080122143433.15391.1130108145.divmod.quotient.1468@ohm> On Tue, 22 Jan 2008 15:15:43 +0100, "Diez B. Roggisch" wrote: >Jean-Paul Calderone wrote: > >> On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" >> wrote: >>>For a simple greenlet/tasklet/microthreading experiment I found myself in >>>the need to ask the question >>> >>> [snip] >> >> Why do you need a special case for generators? If you just pass the >> object in question to iter(), instead, then you'll either get back >> something that you can iterate over, or you'll get an exception for >> things that aren't iterable. > >Because - as I said - I'm working on a micro-thread thingy, where the >scheduler needs to push returned generators to a stack and execute them. >Using send(), which rules out iter() anyway. Sorry, I still don't understand. Why is a generator different from any other iterator? Jean-Paul From gagsl-py2 at yahoo.com.ar Wed Jan 23 16:27:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 19:27:39 -0200 Subject: A global or module-level variable? References: <7637fd0b-961e-4730-abd8-96e85c907082@i72g2000hsd.googlegroups.com> <7xwsq1tyts.fsf@ruckus.brouhaha.com> <63002d69-7738-4cae-bfb5-b933f16591b8@t1g2000pra.googlegroups.com> Message-ID: En Wed, 23 Jan 2008 11:58:05 -0200, Bret escribi?: > On Jan 22, 1:00 pm, Paul Rubin wrote: > >> If you have to do it that way, use: > > Is there a better way? A more Pythonic way? It's simple, clear and works fine, why make it more complicated? Unless you have additional requirements, like a multithreaded program. -- Gabriel Genellina From jpeng at block.duxieweb.com Mon Jan 21 22:00:53 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Tue, 22 Jan 2008 11:00:53 +0800 Subject: read files Message-ID: <47955C65.8080604@block.duxieweb.com> first I know this is the correct method to read and print a file: fd = open("/etc/sysctl.conf") done=0 while not done: line = fd.readline() if line == '': done = 1 else: print line, fd.close() I dont like that flag of "done",then I tried to re-write it as: fd = open("/etc/sysctl.conf") while line = fd.readline(): print line, fd.close() this can't work.why? From roy at panix.com Tue Jan 29 09:00:02 2008 From: roy at panix.com (Roy Smith) Date: Tue, 29 Jan 2008 09:00:02 -0500 Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> .1201577269.8966python-list@pyttttttttt 05C.23015128012208@70-1-84-166..rea1.spcsdns.neee Message-ID: In article , "Terry Reedy" wrote: > "Roy Smith" wrote in message > news:roy-3C105C.23015128012008 at 70-1-84-166.area1.spcsdns.net... > | But, surely Python has plenty of "implementation defined" aspects. > | Especially in the libraries. > > I personally do not consider the libraries as part of the language (as > opposed to the distribution) and was not referring to them. I realize that there is a difference between the core language and the libraries, but Python depends on the libraries more than a lot of other languages do. They are the "batteries included" part. Indeed, there is a lot of stuff in the "Python Library Reference" which in most languages would be considered part of the core. The description of boolean operations (and, or, not), for example. String, sequence, and dictionary methods. Where do you draw the line and say, "The core language ends here; the rest is just libraries"? From paul.hankin at gmail.com Wed Jan 9 05:29:14 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 9 Jan 2008 02:29:14 -0800 (PST) Subject: Open a List of Files References: <874pdomrrd.fsf@mulj.homelinux.net> <4f67337a-14ea-4552-8a5a-6de9703e58ff@d70g2000hsb.googlegroups.com> Message-ID: On Jan 9, 10:02 am, Fredrik Lundh wrote: > Paul Hankin wrote: > > This can be more cleanly written using locals() > > > for fn in filenames: > > locals()[fn] = open(os.path.join(host_path, fname + '.txt', 'wb') > > from the reference manual: > > locals() > > Update and return a dictionary representing the current > local symbol table. > > Warning: The contents of this dictionary should not be > modified; changes may not affect the values of local > variables used by the interpreter. Thanks Fredrik! I learnt something today. I wonder if there's a reason why it doesn't raise an exception when you try to write to it? That would seem better to me than having it sometimes update variables and sometimes not. -- Paul Hankin From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 05:51:40 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 11:51:40 +0100 Subject: what does **kw mean? In-Reply-To: <99cc3280-bffd-4004-a3ae-a06244a82759@e6g2000prf.googlegroups.com> References: <99cc3280-bffd-4004-a3ae-a06244a82759@e6g2000prf.googlegroups.com> Message-ID: <47874a30$0$22238$426a34cc@news.free.fr> zslevi at gmail.com a ?crit : > I've been reading the following example, and couldn't figure out, what > **kw mean. (It's an empty dictionary, but what's the semantics): Keyword varargs. And FWIW, *args is for positional varargs. From steven.klass at gmail.com Mon Jan 21 17:30:07 2008 From: steven.klass at gmail.com (rh0dium) Date: Mon, 21 Jan 2008 14:30:07 -0800 (PST) Subject: Prioritization function needed (recursive help!) Message-ID: <51180fda-304d-4f7e-812a-32032585675b@e23g2000prf.googlegroups.com> Hi all, I need some help on writing a recursive priority function Given a list = [ A, B, C, D] Where the following constraints are in place: A depends on [B, C] C depends on [B] Figure out real order that prioritizes these. Output [ B, C, A, D ] is valid. (Actually D could be anywhere in it as it doesn't matter..) I am really struggling on simply how to organize the data and write the corresponding function - I tried classes but I don't know if that's the best approach. See my other post on this. Thanks From fredrik at pythonware.com Wed Jan 9 05:30:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 11:30:41 +0100 Subject: "Canonical" way of deleting elements from lists In-Reply-To: References: <5ujkbaF1e11ksU1@mid.dfncis.de> Message-ID: Fredrik Lundh wrote: > creating a new list is always almost the right way to do things like message = message.replace("always almost", "almost always") From mathieu.malaterre at gmail.com Thu Jan 10 03:27:48 2008 From: mathieu.malaterre at gmail.com (mathieu) Date: Thu, 10 Jan 2008 00:27:48 -0800 (PST) Subject: PyGILState_Release produces a seg fault Message-ID: <11e94b09-c972-48d8-b6f0-c20a08b5face@j20g2000hsi.googlegroups.com> Hello and happy new year folks, I am experiencing a seg fault while using the python interface to the VTK library (debian oldstable, python 2.3). The VTK library is wrapped by a custom mechanism to provide a python API. In particular they implemented a way so that a python function can be called in response to an event(*). Basically all the code is doing is: { PyGILState_STATE state = PyGILState_Ensure(); // construct arglist from C++ args: ... // call python function: result = PyEval_CallObject(this->obj, arglist); PyGILState_Release(state); // crash happens here } However the event being triggered from the C++ layer is done from multiple threads. After reading : http://docs.python.org/api/threads.html I tought that the VTK-python layer was simply missing a call to : PyEval_InitThreads() just before Py_InitModule(), but now my python shell appears as hung ! The only solution I found is that if I comment out the function calls PyGILState_Ensure/PyGILState_Release then everything goes smoothly. Am I reading the docs backward ? I do need to keep the call to PyGILState_Ensure/PyGILState_Release, right ? I am also copying the log from valgrind (VTK lib untouched, no call to PyEval_InitThreads), UpdateProgress being the function called from multiple threads: ==20066== Thread 2: ==20066== Invalid read of size 4 ==20066== at 0x403232A: sem_post@@GLIBC_2.1 (in /usr/lib/debug/ libpthread-2.5.so) ==20066== by 0x80B0D53: PyEval_ReleaseLock (in /usr/bin/python2.4) ==20066== by 0x80DDB20: PyGILState_Release (in /usr/bin/python2.4) ==20066== by 0x45C7AB4: vtkPythonCommand::Execute(vtkObject*, unsigned long, void*) (vtkPythonUtil.cxx:2016) ==20066== by 0x483C0DF: vtkSubjectHelper::InvokeEvent(unsigned long, void*, vtkObject*) (vtkObject.cxx:547) ==20066== by 0x483C18E: vtkObject::InvokeEvent(unsigned long, void*) (vtkObject.cxx:713) ==20066== by 0x4E67E6A: vtkAlgorithm::UpdateProgress(double) (vtkAlgorithm.cxx:115) Thanks, -Mathieu Original post: http://public.kitware.com/pipermail/vtk-developers/2008-January/004890.html (*) See line 1906->2019 at: http://public.kitware.com/cgi-bin/viewcvs.cgi/Common/vtkPythonUtil.cxx?annotate=1.80 From george.sakkis at gmail.com Fri Jan 11 10:10:00 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 07:10:00 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> <478732db$0$19250$426a74cc@news.free.fr> <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> <4787762b$0$18777$426a74cc@news.free.fr> Message-ID: On Jan 11, 8:59 am, Bruno Desthuilliers wrote: > George Sakkis a ?crit : > > > > > On Jan 11, 4:12 am, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > >> George Sakkis a ?crit : > > >>> On Jan 10, 3:37 am, Bruno Desthuilliers wrote: > >>>> I fail to see how the existence of JIT compilers in some Java VM changes > >>>> anything to the fact that both Java (by language specification) and > >>>> CPython use the byte-code/VM scheme. > >>> Because these "some Java VMs" with JIT compilers are the de facto > >>> standard used by millions; > >> Repeating an argument doesn't make it more true nor more relevant. Once > >> again, this doesn't change anything to the fact exposed above. > > >>> the spec is pretty much irrelevant > >> I mentionned this because this kind of choice is usually not part of the > >> language spec but of a specific implementation. Java is AFAIK the only > >> language where this implementation stuff is part of the spec. > > >>> (unless > >>> you're a compiler writer or language theorist). > >> I thought it was quite clear and obvious that I was talking about points > >> relating to these fields. > > > No it wasn't, > > """ > > or is Python just too slow > > as an interpreted language > > Being "interpreted" is a quality of an implementation, not of a language. > """ > If that isn't clear enough what I'm talking about, then sorry but I > can't help. Pedantic once again. For languages with a single (or practically single) implementation such as Python, the average user couldn't care less about the distinction. Your point might have more merit if PyPy or IronPython or Jython enter the same league with CPython in terms of usage. > > and besides the OP is most likely interested in these as > > a simple user so the distinction between a spec and a de facto > > standard implementation (such as JDK for Java and CPython for Python) > > are almost pedantic if not misleading. > > I can live with being called "pedantic" - even I'm not sure whether > correcting a wrong statement about CPython's execution model is pedantic > or not. But I *still* fail to see how it could be "misleading", and > *you* still fail to explain in which way it could be misleading. > > If your point is that saying that CPython uses a byte-code/VM scheme > "just like Java" necessarily implies JIT compilation just because some > JVM support this feature, then it would be time you pay more attention > to what is effectively written. What three different people in this thread have been trying to tell you but you seem to miss is that claiming CPython's VM "is just like Java" is comparable to saying "a Yugo's car engine is just like a BMW's" (or "humans are just like chimpanzees"), which for some value of "just like" is technically correct but it's not what most people would call an accurate statement. > > We're not Lisp (yet ;-)), with > > five major implementations and a dozen of minor ones. > > And ? In which way does it make the distinction between a language and a > language implementation less true ? In the way that most plain users care (or not) about. George From paul at boddie.org.uk Thu Jan 17 12:29:42 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 17 Jan 2008 09:29:42 -0800 (PST) Subject: Perl Template Toolkit: Now in spicy new Python flavor References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> <13a75830-5416-4fe3-9460-018e1240e6e6@e32g2000prn.googlegroups.com> Message-ID: <18fdac42-b0fe-4e23-8c1f-2c5671bb3bf7@i12g2000prf.googlegroups.com> On 16 Jan, 21:01, "eef... at gmail.com" wrote: > > I can't claim a comprehensive familiarity with Python template > offerings, but all of the packages approved for use at my previous > workplace left me cold. There are a few offerings listed on this page: http://wiki.python.org/moin/Templating I suppose you could add Template Toolkit somewhere on that page, indicating where it fits into the bigger picture. Paul From support at wingware.com Mon Jan 21 19:52:32 2008 From: support at wingware.com (Wingware Support) Date: Mon, 21 Jan 2008 19:52:32 -0500 Subject: problem With Psyco on Wingide mac In-Reply-To: References: Message-ID: <47953E50.4030004@wingware.com> Arash Arfaee wrote: > I am trying to use psyco with wingide on mac. when I open Mac Python > shell I can import psyco, but not inside the wingide. Even python > shell on wingide cannot import psyco. > Can anybody help me to solvethis problem? I suspect Wing is finding a different Python installation than you want or expect it to. In Project Properties, you can set Python Executable to change this. Note, BTW, that running in the debugger w/ psyco may skip breakpoints in optimized code, or may not work at all. Hope that's helpful. - Stephan From ceccarelli.aldo at gmail.com Mon Jan 28 08:23:29 2008 From: ceccarelli.aldo at gmail.com (Aldo Ceccarelli) Date: Mon, 28 Jan 2008 05:23:29 -0800 (PST) Subject: Anybody has ported talib to Python via SWIG References: <6fa2a3e3-ab77-41dc-a01e-55770a764b0e@k39g2000hsf.googlegroups.com> Message-ID: <4db2f6dd-b007-44ef-81c9-cce03fb12b59@y5g2000hsf.googlegroups.com> On 26 Gen, 19:33, "Gabriel Genellina" wrote: > En Thu, 24 Jan 2008 20:49:33 -0200, Aldo Ceccarelli ? > escribi?: > > > Hi Everybody, > > TaLib (technical analysis package with function indicators coded in C/C > > ++,http://www.ta-lib.org) has a complete library with source in C/C+ > > +. > > > I am new to SWIG (wrapper interface generator) and would really > > appreciate any Python (.py) port of TaLib to be able to call and test > > TaLib's functions (f.i. MACD, Parabolic SAR and so on) in some Python > > (2.5) script. > > > Do you have idea whether TaLib Python package has already been > > generated and can be eventually downloaded anywhere? > > If Talib has a C API (not C++), the ctypes module can be used to call ? > those C functions, so there is no need to write a special SWIG wrapper. In ? > fact it may be much easier to do that way. > > ctypes is a standard module on Python 2.5, and is documented here:http://docs.python.org/lib/module-ctypes.html > > -- > Gabriel Genellina Many thanks a lot, Gabriel. I will study ctypes and its applicability to ta-lib in particular; in negative case I will go through ta-lib forum available (for registered users) at http://www.tadoc.org here I have just found several posts of people describing their path to ta-lib port via SWIG too. Again thanks and kindest regards:-) Aldo From jpeng at block.duxieweb.com Tue Jan 22 02:36:49 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Tue, 22 Jan 2008 15:36:49 +0800 Subject: what's this instance? Message-ID: <47959D11.3040806@block.duxieweb.com> def safe_float(object): try: retval = float(object) except (ValueError, TypeError), oops: retval = str(oops) return retval x=safe_float([1,2,3,4]) print x The code above works well.But what's the instance of "oops"? where is it coming from? I'm totally confused on it.thanks. From lists at cheimes.de Thu Jan 3 11:38:52 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 03 Jan 2008 17:38:52 +0100 Subject: How do you pass compiler option to setup.py install? In-Reply-To: <32e43bb70801030824p7099da66s6ffb4ee0ea58b311@mail.gmail.com> References: <32e43bb70801030824p7099da66s6ffb4ee0ea58b311@mail.gmail.com> Message-ID: <477D0F9C.7000507@cheimes.de> Emin.shopper Martinian.shopper wrote: > Dear Experts, > > How do you pass the -c option to setup.py install? Specifically, when I try > to install zope.interfaces version 3.3 from source on a windows machine, I > get a message about using "-c mingw32". That works fine for setup.py build, > but it does not work for "setup.py install". python setup.py build -c mingw32 install You can also change the distutils.cfg file to set mingw32 as the default compiler. Please refer to the documentation for more information. Christian From ggpolo at gmail.com Thu Jan 24 16:16:44 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 24 Jan 2008 19:16:44 -0200 Subject: object vs class oriented -- xotcl In-Reply-To: References: Message-ID: 2008/1/24, William Pursell : > > I've been away from Python for at least a year, and in the interim > have spent a little time looking at the XOTcl object framework for > Tcl. One of the interesting features of XOTcl is the ability for an > object to change class dynamically. The XOtcl documentation makes the > claim that this makes it object oriented, while most other languages > are "class oriented". Here's a snippet from the wiki, from a post to > the mailing list by Gustaf Neumann: (http://wiki.tcl.tk/1297) > > Class-oriented means: look at the class and you know exactly how all > of the instances look alike. The class is the first and primary > language construct; the class is well the place where you specify the > instance variables (there are no instance variables except those > specified in the class). The only kind of individualism left in the > objects is to let them differ by their state (the values of their > instance variables). Changing classes (class migration) is > conceptually quite hard for this setup. > > Object-oriented (in this distinction) means that the primary elements > are objects, which keep all instance variables. classes my be used to > specify the behavior of objects, they are container for methods and > they control the life-cycle of objects. Objects are like the facts, > and classes are like rules, that determine the behavior of the > objects. Since the connection between objects and classes is rather > loose, it is sufficient to define their relation through an > association. Therefore it is quite easy to change the relation between > objects and classes (and between classes and classes) dynamically. > Objects have arbitrary individualism, they may have variables never > used in any class, they may have private procs etc. > > I'm not sure that describes the method well. Basically, you can > instantiate an object A of class Foo, and later change A to be an > object of class Bar. Does Python support this type of flexibility? > As I stated above, I've been away from Python for awhile now, and am a > bit rusty, but it seems that slots or "new style" objects might > provide this type of behavior. The ability to have an object change > class is certainly (to me) a novel idea. Can I do it in Python? > -- > http://mail.python.org/mailman/listinfo/python-list > class A(object): pass class B(object): pass a = A() a.__class__ = B That ? Maybe you meant something else. -- -- Guilherme H. Polo Goncalves From david.hotham at blueyonder.co.uk Mon Jan 28 16:40:49 2008 From: david.hotham at blueyonder.co.uk (david.hotham at blueyonder.co.uk) Date: Mon, 28 Jan 2008 13:40:49 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <92b67efe-c437-40bc-89fc-bbdd85d6e718@s19g2000prg.googlegroups.com> Message-ID: <4ce44a0d-6745-4f55-b2fb-038cb2ea6c76@k39g2000hsf.googlegroups.com> I see I don't have as many columns as I'd expected. Here's a reformatted listing. from time import time from bisect import insort from sys import argv #--------------------------------------------------------------------- # Hash table is a global variable #--------------------------------------------------------------------- global hash_table #--------------------------------------------------------------------- # countdown.py # # Python script to solve the Countdown numbers game # # Remarks on optimization: # # - Without the hash table, the following all proved beneficial: # - Keep a list of numbers used so far, and never create a number # that you've already used # - Make sure only to return unique pairs from the generate_pairs # function # - Don't ever perform two consecutive substractions # - (Don't ever perform two consecutive divisions would also be # valid, though it's not something that happens a lot so the # benefit is small) # # - These tricks work by avoiding performing the same search more # than once # # - With only six seeds, it's possible to implement a perfect hash # table that remembers every list that we try to solve (and indeed # this is what the implementation here does) # # - With that hash table, the optimizations above become largely # redundant, so for the sake of simplicity I've removed them # # - Solving for larger numbers of seeds would require a smarter # approach, as it would soon become infeasible to maintain a # complete hash table. Then the tricks above might be useful # again. # #--------------------------------------------------------------------- #--------------------------------------------------------------------- # Returns all useful combinations of two numbers, and a string # representing the operation used to get there. #--------------------------------------------------------------------- def generate_combinations(higher_number, lower_number): #----------------------------------------------------------------- # Useful operations are: # - addition (always) # - subtraction (of the lower number from the higher number, so # long as they are not equal) # - multiplication (so long as not multiplying by one) # - division (if it's exact, and not by one) #----------------------------------------------------------------- yield "+", higher_number + lower_number if (higher_number != lower_number): yield "-", higher_number - lower_number if (lower_number != 1): yield "*", higher_number * lower_number if ((higher_number % lower_number) == 0): yield "/", higher_number / lower_number #--------------------------------------------------------------------- # Returns all pairs from a list of seeds. # # Pairs always have the first number lower than or equal to the second # number, provided that the list is ordered on entry (as it should # be). #--------------------------------------------------------------------- def generate_pairs(seeds): for ii in xrange(len(seeds)): for higher_num in seeds[ii+1:]: yield seeds[ii], higher_num #--------------------------------------------------------------------- # Solves a seed list. Takes pairs, combines them, and recursively # calls solve_list again with the new shorter list. # # Seeds should be sorted on entry. #--------------------------------------------------------------------- def solve_list(seeds, target, depth, solution_so_far): #----------------------------------------------------------------- # Loop through possible pairs. #----------------------------------------------------------------- for lower_num, higher_num in generate_pairs(seeds): #------------------------------------------------------------- # Make a copy of the list, and remove this pair. # # Taking a copy appears to be quicker than using the original # list and then reinstating the chosen pair later. #------------------------------------------------------------- new_seeds = seeds[:] new_seeds.remove(lower_num) new_seeds.remove(higher_num) #------------------------------------------------------------- # Try out all possible combinations of our pair. #------------------------------------------------------------- for operation, combination in generate_combinations( higher_num, lower_num): #--------------------------------------------------------- # If we hit our target, we're happy. # # Else if the list has gotten too short already, move on. # # Else make a new, shorter, list containing our new value. # # If we've already tried to solve the new list, there's no # point in trying again. # # Else try to solve the shorter list. #---------------------------------------------------------- if combination == target: print "made target!" print "%s%d %s %d = %d\n" % (solution_so_far, higher_num, operation, lower_num, combination) return(0) elif (depth > 0): insort(new_seeds, combination) seeds_tuple = tuple(new_seeds) if (seeds_tuple in hash_table): pass else: hash_table[seeds_tuple] = 1 new_soln_so_far = ("%s%d %s %d = %d\n" % (solution_so_far, higher_num, operation, lower_num, combination)) if (solve_list(new_seeds, target, depth - 1, new_soln_so_far) == 0): #--------------------------------------------- # Success! #--------------------------------------------- return(0) #----------------------------------------------------- # Remove the value that we made out of our number # pair, in preparation for the next try. #----------------------------------------------------- new_seeds.remove(combination) #----------------------------------------------------------------- # Didn't solve it. #----------------------------------------------------------------- return(1) #--------------------------------------------------------------------- # OK, let's go. Get the puzzle, and solve it. The last argument is # the target and the others are the seeds. #--------------------------------------------------------------------- original_seeds = map(int, argv[1:-1]) target = int(argv[-1]) start_time = time() failed = 1; if target in original_seeds: print "Target is amongst seeds!" else: original_seeds.sort() #----------------------------------------------------------------- # First look for one-step solutions, then for two-step solutions, # etc. That way we always get a shortest solution first. #----------------------------------------------------------------- for depth in xrange(len(original_seeds)): hash_table = {} failed = solve_list(original_seeds, target, depth, "") if (failed == 0): break if (failed != 0): print "No solution!" print "Took %.3f seconds" % (time() - start_time) From martin at marcher.name Thu Jan 24 17:41:57 2008 From: martin at marcher.name (Martin Marcher) Date: Thu, 24 Jan 2008 23:41:57 +0100 Subject: Email module, how to add header to the top of an email? References: <97c04812-3b66-4d84-9e92-21de72a3ca56@c23g2000hsa.googlegroups.com> Message-ID: On Thursday 24 January 2008 20:32 David Erickson wrote: > I have been using the Email module and Message class for awhile, > however I have been unable to find a way to add a header to the top of > the email similar to what is done with Received: headers... the > add_header method only appends to the bottom. ?Is there someway this > can be done? if by bottom you mean added as the "new last" header than you don't have to care, afaik email headers do not have a notion of order e.g To: bob at example.com From: alice at example.com is equal to From: alice at example.com To: bob at example.com if by bottom you mean it's appended to the body...well that is a problem :) hth martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From sjmachin at lexicon.net Mon Jan 21 04:16:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jan 2008 01:16:15 -0800 (PST) Subject: eucledian dist calculations References: <87aff9a8-a9d8-4236-8a86-66aa58417792@i72g2000hsd.googlegroups.com> Message-ID: <13c59b0c-534a-4a4a-bad3-f6f51721ab78@n20g2000hsh.googlegroups.com> On Jan 21, 6:44 pm, nodrogbrown wrote: > hi > i am using python to do some image data calculations..I use the > following numpy.ndarrays ,(i have given their shapes and ranks) > > weights=ndarray :shape(100,30),ndim=2 will have vals like > 2458121847.49 (of type 'numpy.float64') > input_weight=ndarray :shape(30,),ndim=1 (similar to above but diff > vals) > distance =ndarray :shape(30,),ndim=1 > mindistance==ndarray :shape(30,),ndim=1 > > now i am calculating the euclidian distance of 'input_weight' from > 'weight' > since this is the cumulative diff i do this in this way > > > for image in range(100): > temp=0.0 > for j in range(30): > distance[j]=abs(input_weight[j]-weights[image,j]) > > if(image==0): > #at the start copy from distance to mindistance > mindistance=distance.copy() > if (sum(mindistance) > sum(distance)): > imgindex=image # i use this later to access a list > mindistance=distance.copy() > > # now normalise the mindistance > array > if (max(mindistance) > 0.0): > mindistance=mindistance/(max(mindistance)) > > dist=sum(mindistance) > > > > this gives me the correct results Are you sure? What happens if the vector with the smallest sum(distance) is the first one? > but i am worried if this is a bit > unpythonish? > (been a java programmer for a long time..) i wd like to know if there > is a better way 1. 'temp' is not used 2. Lose the superfluous parentheses in 'if' statements 3. Put space around operators 4. I've never used any of numpy & friends, but: (a) Can't you replace the inner loop with something like this: distance = abs(input_weight - weights[image, :]) (b) I doubt that you need the .copy() 5. Lose the hard-wired numbers like 30 and 100 6. Put it inside a function and *TEST* it The word you were looking for is 'unpythonic', but the principles behind the above apply to any language. HTH, John From d.l.goldsmith at gmail.com Mon Jan 7 17:37:12 2008 From: d.l.goldsmith at gmail.com (dgoldsmith_89) Date: Mon, 7 Jan 2008 14:37:12 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python Message-ID: Can anyone point me to a downloadable open source English dictionary suitable for programmatic use with python: I'm programming a puzzle generator, and I need to be able to generate more or less complete lists of English words, alphabetized. Thanks! DG From deets at nospam.web.de Tue Jan 22 09:52:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 15:52:02 +0100 Subject: isgenerator(...) - anywhere to be found? References: Message-ID: <5vme8iF1mqjl6U1@mid.uni-berlin.de> Jean-Paul Calderone wrote: > On Tue, 22 Jan 2008 15:15:43 +0100, "Diez B. Roggisch" > wrote: >>Jean-Paul Calderone wrote: >> >>> On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" >>> wrote: >>>>For a simple greenlet/tasklet/microthreading experiment I found myself >>>>in the need to ask the question >>>> >>>> [snip] >>> >>> Why do you need a special case for generators? If you just pass the >>> object in question to iter(), instead, then you'll either get back >>> something that you can iterate over, or you'll get an exception for >>> things that aren't iterable. >> >>Because - as I said - I'm working on a micro-thread thingy, where the >>scheduler needs to push returned generators to a stack and execute them. >>Using send(), which rules out iter() anyway. > > Sorry, I still don't understand. Why is a generator different from any > other iterator? Because you can use send(value) on it for example. Which you can't with every other iterator. And that you can utizilize to create a little framework of co-routines or however you like to call it that will yield values when they want, or generators if they have nested co-routines the scheduler needs to keep track of and invoke after another. I'm currently at work and can't show you the code - I don't claim that my current approach is the shizzle, but so far it serves my purposes - and I need a isgenerator() Diez From mr.cerutti at gmail.com Mon Jan 14 09:32:16 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Mon, 14 Jan 2008 09:32:16 -0500 Subject: NotImplimentedError In-Reply-To: References: <882739.52486.qm@web63705.mail.re1.yahoo.com> Message-ID: <51302a8c0801140632h5ac589e5ya08c846ecaae61af@mail.gmail.com> On Jan 14, 2008 9:01 AM, George Sakkis wrote: > By the way, why do we need both NotImplementedError and the > NotImplemented singleton object ? Couldn't we have just one of them ? I think we need both because an unimplemented method is an error, while an unimplemented rich comparison between disparate types is (usually) not. It could be made to work with one object fulfilling both functions, but then the name would be wrong for one case or the other. -- Neil Cerutti From pavlovevidence at gmail.com Tue Jan 8 11:13:33 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 8 Jan 2008 08:13:33 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <7c77bd1c-3930-4078-b687-12cc7df849a9@d21g2000prf.googlegroups.com> On Jan 7, 6:29 pm, MRAB wrote: > On Jan 7, 5:40 pm, Martin Marcher wrote:> MartinRineh... at gmail.com wrote: > > > The best thing about Python is _______. > > > it's pythonicness. > > I think it sounds better as "its pythonicity". Mixing Greek and Latin suffixes usually works better than mixing Greek and Germanic, doesn't it. Carl Banks From asmodai at in-nomine.org Thu Jan 17 13:27:12 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 17 Jan 2008 19:27:12 +0100 Subject: working with a subversion repo In-Reply-To: <0e4caa20-1080-41fb-8e77-610c0e61af48@t1g2000pra.googlegroups.com> References: <7f156399-d9ae-4f13-a80f-0ffe41d89427@s12g2000prg.googlegroups.com> <0e4caa20-1080-41fb-8e77-610c0e61af48@t1g2000pra.googlegroups.com> Message-ID: <20080117182712.GO61556@nexus.in-nomine.org> -On [20080117 19:04], Luke (Luke.Visinoni at gmail.com) wrote: >Does that mean that libsvn and svn are not modules? If they are modules, >where can I find documentation for them? What do they do? They are modules, but not part of a standard install. Subversions uses a program called SWIG to generate APIs for various languages (perl, python, ruby for example). The libsvn/svn modules you see in site-packages are generated from Subversion's API by SWIG. So you need to install, for most operating systems, the Subversion-Python package in order to get these modules. I am sure the Subversion project has adequate documentation on this on their website. Just look for documentation on their (SWIG) bindings. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ I was searching through the Heavens and somehow I slipped... From secretquiet.423 at gmail.com Thu Jan 3 05:41:41 2008 From: secretquiet.423 at gmail.com (secretquiet.423 at gmail.com) Date: Thu, 3 Jan 2008 02:41:41 -0800 (PST) Subject: sexi girl Message-ID: sexi girl bollywood music video You can download latest videos of bollywood 2006. You may share your files with us. Adult contents shouldn't be there.Thanks ************************************************* http://www.geocities.com/lordsnile ************************************************* From arnodel at googlemail.com Fri Jan 4 06:19:44 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 4 Jan 2008 03:19:44 -0800 (PST) Subject: adding class functionality, nested scoping References: Message-ID: On Jan 4, 10:43?am, jh... at gmx.de wrote: > Hi, Hi [...] > # Does not work: all enhanced methods only call the last wrapped originial > # method. It seems the name 'method' in the surrounding scope of the > # def _(...) function definition only refers to the last loop value(?) > def ERRONEOUS_enhance_all_methods(cls, replacement): > ? ? for methodname in cls.__dict__: > ? ? ? ? if not methodname.startswith("__"): > ? ? ? ? ? ? method = getattr(cls, methodname) > ? ? ? ? ? ? def _f(*args, **kwargs): > ? ? ? ? ? ? ? ? return replacement(method, *args, **kwargs) > ? ? ? ? ? ? _f.__name__ = methodname > ? ? ? ? ? ? setattr(cls, methodname, types.MethodType(_f, None, cls)) > This is normal: After ERRONEOUS_enhance_all_methods is called, the value method is the one from the last iteration of the loop. All subsequent references to 'method' (in function _f) will return that last value. To solve this problem you need to fix the object 'method' is bound to in function _f: def enhance_all_methods(cls, replacement): # The following binds 'method' to its current value in _f def replace(method): def _f(*args, **kwargs): return replacement(method, *args, **kwargs) return _f for methodname in cls.__dict__: if not methodname.startswith("__"): _f = replace(getattr(cls, methodname)) _f.__name__ = methodname setattr(cls, methodname, types.MethodType(_f, None, cls)) Of course this looks more like your first version, which trims down to the following and is probably a better option: def enhance_all_methods(cls, replacement): for methodname in cls.__dict__: if not methodname.startswith("__"): enhance_method(cls, methodname, replacement) HTH -- Arnaud From rong.xian at gmail.com Thu Jan 24 01:52:22 2008 From: rong.xian at gmail.com (glacier) Date: Wed, 23 Jan 2008 22:52:22 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> Message-ID: On 1?24?, ??1?41?, Ben Finney wrote: > Ben Finney writes: > > glacier writes: > > > > I use chinese charactors as an example here. > > > > >>>s1='???' > > > >>>repr(s1) > > > "'\\xc4\\xe3\\xba\\xc3\\xc2\\xf0'" > > > >>>b1=s1.decode('GBK') > > > > My first question is : what strategy does 'decode' use to tell the > > > way to seperate the words. I mean since s1 is an multi-bytes-char > > > string, how did it determine to seperate the string every 2bytes > > > or 1byte? > > > The codec you specified ("GBK") is, like any character-encoding > > codec, a precise mapping between characters and bytes. It's almost > > certainly not aware of "words", only character-to-byte mappings. > > To be clear, I should point out that I didn't mean to imply static > tabular mappings only. The mappings in a character encoding are often > more complex and algorithmic. > > That doesn't make them any less precise, of course; and the core point > is that a character-mapping codec is *only* about getting between > characters and bytes, nothing else. > > -- > \ "He who laughs last, thinks slowest." -- Anonymous | > `\ | > _o__) | > Ben Finney- ??????? - > > - ??????? - thanks for your respoonse:) When I mentioned 'word' in the previous post, I mean character. According to your reply, what will happen if I try to decode a long string seperately. I mean: ###################################### a='???'*100000 s1 = u'' cur = 0 while cur < len(a): d = min(len(a)-i,1023) s1 += a[cur:cur+d].decode('mbcs') cur += d ###################################### May the code above produce any bogus characters in s1? Thanks :) From lefevrol at yahoo.com Sun Jan 27 13:58:27 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Sun, 27 Jan 2008 19:58:27 +0100 Subject: read and readline hanging In-Reply-To: <5vuv9iF1o6ambU2@mid.uni-berlin.de> References: <5vuv9iF1o6ambU2@mid.uni-berlin.de> Message-ID: > The `trheading` module is modeled after Java's threading API. OK. Thanks for the hint. However BufferedReader.readline() does not block in Java, so it is still difficult to transpose. >> But how can I find out *programmatically* that there is no more >> input? > > You can't. How do people handle this, then? Reading from a process that will block if you ask too much yet won't let you know how much there is to read right now has to be some kind of FAQ. > This doesn't answer if the interpreter doesn't flush its output buffer > after every line. I think it must otherwise you might get incomplete answers or no answers at the interactive prompt and that never happens. It may not flush its buffer after every line but it must flush them at the end of an answer. -- O.L. From mr.cerutti at gmail.com Wed Jan 16 09:42:33 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 16 Jan 2008 09:42:33 -0500 Subject: Python help for a C++ programmer In-Reply-To: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> References: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> Message-ID: <51302a8c0801160642r4b8f3fc1h88263863ab505849@mail.gmail.com> On Jan 16, 2008 9:23 AM, mlimber wrote: > I'm writing a text processing program to process some survey results. > I'm familiar with C++ and could write it in that, but I thought I'd > try out Python. I've got a handle on the file I/O and regular > expression processing, but I'm wondering about building my array of > classes (I'd probably use a struct in C++ since there are no methods, > just data). > > I want something like (C++ code): > > struct Response > { > std::string name; > int age; > int iData[ 10 ]; > std::string sData; > }; > > // Prototype > void Process( const std::vector& ); > > int main() > { > std::vector responses; > > while( /* not end of file */ ) > { > Response r; > > // Fill struct from file > r.name = /* get the data from the file */; > r.age = /* ... */; > r.iData[0] = /* ... */; > // ... > r.sData = /* ... */; > responses.push_back( r ); > } > > // Do some processing on the responses > Process( responses ); > } > > What is the preferred way to do this sort of thing in Python? It depends on the format of your data (Python provides lots of shortcuts for handling lots of kinds of data), but perhaps something like this, if you do all the parsing manually: class Response(object): def __init__(self, extern_rep): # parse or translate extern_rep into ... self.name = ... self.age = ... # Use a dictionary instead of parallel lists. self.data = {...} def process(self): # Do what you need to do. fstream = open('thedatafile') for line in fstream: # This assumes each line is one response. Response(line).process() -- Neil Cerutti From theller at ctypes.org Wed Jan 9 18:06:00 2008 From: theller at ctypes.org (Thomas Heller) Date: Thu, 10 Jan 2008 00:06:00 +0100 Subject: for loop without variable In-Reply-To: References: Message-ID: erik gartz schrieb: > Hi. I'd like to be able to write a loop such as: > for i in range(10): > pass > but without the i variable. The reason for this is I'm using pylint > and it complains about the unused variable i. Pychecker won't complain if you rename 'i' to '_', IIRC: for _ in range(10): pass Thomas From eefacm at gmail.com Mon Jan 14 18:00:52 2008 From: eefacm at gmail.com (eefacm at gmail.com) Date: Mon, 14 Jan 2008 15:00:52 -0800 (PST) Subject: Perl Template Toolkit: Now in spicy new Python flavor Message-ID: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> I'd like to inform the Python community that the powerful and popular Template Toolkit system, previously available only in its original Perl implementation, is now also available in a beta Python implementation: http://tt2.org/python/index.html I created this port both as a fun programming project, and for use in environments where Perl is not available, for reasons technical, cultural, or otherwise. The extensive Perl test suites have also been ported, and most templates require no or very little modification. Discussion of the Python implementation should be conducted on the main Template Toolkit developer mailing list; see the site above for details. From mr.cerutti at gmail.com Fri Jan 18 10:12:34 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 18 Jan 2008 10:12:34 -0500 Subject: Filtering two files with uncommon column In-Reply-To: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> Message-ID: <51302a8c0801180712m60c0019dk52a51d740416324c@mail.gmail.com> On Jan 18, 2008 4:23 AM, Madhur wrote: > I would like to know the best way of generating filter of two files > based upon the following condition As a bit of friendly advice, you'll get much more useful assistance if you post your code. If you don't have any code to show, write some. Unless it's a quine, a program won't write itself. -- Neil Cerutti From israelu at elbit.co.il Tue Jan 29 01:01:16 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 28 Jan 2008 22:01:16 -0800 (PST) Subject: A question about osyco References: <606hucF1p0rptU1@mid.uni-berlin.de> <4e8bd7b3-29d2-4fcc-baad-7e6ecfe829c4@v4g2000hsf.googlegroups.com> Message-ID: <2f24b4c6-0a62-4623-b96d-ea44f003eedd@m34g2000hsf.googlegroups.com> On Jan 29, 1:48?am, bearophileH... at lycos.com wrote: > Marc 'BlackJack' Rintsch: > > > Try calling the iterative one twice and measure the time of the second > > call. ?IIRC psyco needs at least one call to analyze the function, so the > > first call is not speed up. > > That's how Java HotSpot works, but Psyco is very different from > HotSpot, and I think you are wrong. > I don't exactly know the answer to the question of the OP, but I think > the two functions are different: in the second function most time > isn't spent in managing the xrange or in the assign, but in the sum > between long ints, and Psyco can't speed up that operation (you need > gmpy for that, and in certain tricky situations gmpy may even result > slower, maybe when you use small numbers). > > Bye, > bearophile Thanks, that's probably it I've tested >>> timeit.Timer('c+d', 'from __main__ import c, d').timeit(1000) 6.6209532214145383e-005 >>> timeit.Timer('a+b', 'from __main__ import a, b').timeit(1000) 0.10513989906537802 >>> where c and d are equal to 1, and a, b are very long integers (a=b=fib2(100000)) From gregcorradini at gmail.com Tue Jan 29 14:07:34 2008 From: gregcorradini at gmail.com (Greg Corradini) Date: Tue, 29 Jan 2008 11:07:34 -0800 (PST) Subject: Mx.ODBC insert error In-Reply-To: References: <15163149.post@talk.nabble.com> Message-ID: <15166795.post@talk.nabble.com> Thanks John. I now see it John Machin wrote: > > On Jan 30, 3:27 am, Greg Corradini wrote: >> Hello, >> I've never gotten this traceback error before using mx.ODBC. > > "traceback error"?? I see no problem with the traceback. > >> Any ideas about >> resolving this issue? The statement and the error it generates are listed >> below. > > The error was "generated" by you. The error message was generated by > "[Microsoft][ODBC Microsoft Access Driver]" > >> >> curse.execute("Insert into FHWA_StandSamp_2008(LRS_ID_NEW) >> values('0402000010') where LRS_ID = '0403700010'") >> >> Traceback (most recent call last): >> File "", line 1, in ? >> curse.execute("Insert into FHWA_StandSamp_2008(LRS_ID_NEW) values >> ('0402000010') where LRS_ID = '0403700010'") >> ProgrammingError: ('37000', -3516, '[Microsoft][ODBC Microsoft Access >> Driver] Missing semicolon (;) at end of SQL statement.', 4612) >> > > Like it says, ProgrammingError. > > Try > INSERT INTO table (columns) VALUES (values) > or > INSERT INTO table (columns) > SELECT stuff FROM somewhere [WHERE boolean_expression] .... > or perhaps even > UPDATE table SET column = expression WHERE boolean_expression > > Perhaps you could consider avoiding combining random fragments of SQL > or English and hoping for tolerant fuzzy parsing by the recipient :-) > > HTH, > John > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Mx.ODBC-insert-error-tp15163149p15166795.html Sent from the Python - python-list mailing list archive at Nabble.com. From steve at REMOVE-THIS-cybersource.com.au Fri Jan 4 21:30:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 05 Jan 2008 02:30:41 -0000 Subject: Questions about subclassing an int References: <38614926-19fe-49f8-aa08-fe68449aae70@f3g2000hsg.googlegroups.com> Message-ID: <13ntquhaucon89@corp.supernews.com> On Fri, 04 Jan 2008 15:36:27 -0800, Arnaud Delobelle wrote: > > Now it's no longer a syntax error but I don't see why it's different? > > Same as above, though I don't understand why you get a SyntaxError for T > and a TypeError for R. AFAICT both shoult give a TypeError. Probably because it was never a SyntaxError in the first place. If you execute the code given for T, it gives a TypeError, just as you would expect. Possibly the Original Poster had mistyped something at some point and got a SyntaxError, or more likely he's just using "syntax error" to mean "some exception which I haven't actually looked at". -- Steven From jatinpatni at gmail.com Wed Jan 9 10:28:51 2008 From: jatinpatni at gmail.com (jatin patni) Date: Wed, 9 Jan 2008 15:28:51 +0000 Subject: Re(Thanks...Re: Problem in the program flow...please help?) Message-ID: Thanks Jerry..For the link...I am looking into it... On Jan 9, 2008 2:36 PM, Jerry Hill wrote: > On Jan 9, 2008 7:44 AM, jatin patni wrote: > > I have a button(GUI) which when clicked, calls a function connect( ) > which > > takes around 5-20 seconds to complete(As I mentioned Earlier) > > The problem is, during this time the other part of the code is rendered > > useless, I cannot access other parts of the code, for example a cancel( > ) > > function to be called when cancel button is pressed, cannot be pressed > until > > the previous function is completed and moreover the GUI hangs(stops > > responding). > > See http://wiki.wxpython.org/LongRunningTasks for a discussion of some > of the ways you can deal with this. > > -- > Jerry > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Tue Jan 15 16:32:52 2008 From: nagle at animats.com (John Nagle) Date: Tue, 15 Jan 2008 13:32:52 -0800 Subject: "env" parameter to "popen" won't accept Unicode on Windows -minor Unicode bug In-Reply-To: <5v3qtsF1khn11U1@mid.uni-berlin.de> References: <478bfcb0$0$36378$742ec2ed@news.sonic.net><5v2cudF1k5a1oU1@mid.individual.net><478c551a$0$36354$742ec2ed@news.sonic.net> <5v3dq9F1k2577U1@mid.uni-berlin.de> <5v3qtsF1khn11U1@mid.uni-berlin.de> Message-ID: <478d2569$0$36379$742ec2ed@news.sonic.net> Diez B. Roggisch wrote: > Brian Smith wrote: > >> Diez B. Roggisch wrote: >>> Sure thing, python will just magically convert unicode to the >>> encoding the program YOU invoke will expect. Right after we >>> introduced the >>> >>> solve_my_problem() >>> >>> built-in-function. Any other wishes? >> There's no reason to be rude. > > If you'd know John, you'd know there is. ? >> Anyway, at least on Windows it makes perfect sense for people to expect >> Unicode to be handled automatically. popen() knows that it is running on >> Windows, and it knows what encoding Windows needs for its environment >> (it's either UCS2 or UTF-16 for most Windows APIs). At least when it >> receives a unicode string, it has enough information to apply the >> conversion automatically, and doing so saves the caller from having to >> figure out what exact encoding is to be used. > > > For once, the distinction between windows and other platforms is debatable. > I admit that subprocess contains already quite a few platform specific > aspects, but it's purpose is to abstract these away as much as possible. > > However, I'm not sure that just because there are wide-char windows apis > available automatically means that using UCS2/UTF-16 would succeed. A look > into the python sources (PC/_subprocess.c) reveals that someone already > thought about this, but it seems that just setting a > CREATE_UNICODE_ENVIRONMENT in the CreateProcess-function should have been > easy enough to do it if there weren't any troubles to expect. The problem is that only the NT-derived Microsoft systems talk Unicode. The DOS/Win16/Win9x family did not. But they did have CreateProcess. So the current code will handle Win9x, but not Unicode. When do we drop support for Win9x? It probably has to happen in Python 3K, since that's Unicode-everywhere. John Nagle From deets at nospam.web.de Thu Jan 24 04:36:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Jan 2008 10:36:22 +0100 Subject: Increment Variable Name In-Reply-To: <13pfkt53kq7jo7c@corp.supernews.com> References: <5vq0rjF1o724kU1@mid.uni-berlin.de> <13pfkt53kq7jo7c@corp.supernews.com> Message-ID: <5vr4gpF1nj41eU1@mid.uni-berlin.de> Grant Edwards schrieb: > On 2008-01-23, Diez B. Roggisch wrote: >> David Brochu schrieb: >>> This is probably really trivial but I'm stumped.... :-( >>> >>> Does anyone know how to increment a variable name? >>> >>> For example: >>> >>> I know the length of a list and I want to pass each element of a list to >>> a unique variable, thus I want to increment variable names. If the list >>> length = 4, i want to have the following variables: var1, var2, var3, var4. >>> >> Use a dictionary >> >> value_dict = {} >> >> for i, value in values: >> value_dict["var%i" % i] = value > > That assumes that the OPs "list" is actually a list of tumples: Tumples? :) I forgot the enumerate... Diez From arkanes at gmail.com Wed Jan 2 13:29:07 2008 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 2 Jan 2008 12:29:07 -0600 Subject: ElementTree should parse string and file in the same way In-Reply-To: References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> Message-ID: <4866bea60801021029s2f4b36b4s1e114e7ae5255844@mail.gmail.com> On Jan 2, 2008 8:56 AM, Fredrik Lundh wrote: > Steven D'Aprano wrote: > > > Fredrik, if you're reading this, I'm curious what your reason is. I don't > > have an opinion on whether you should or shouldn't treat files and > > strings the same way. Over to you... > > as Diez shows, it's all about use cases. > > and as anyone who's used my libraries or read my code knows, I'm a big > fan of minimalistic but highly composable object API:s and liberal use > of short helper functions to wire them up to fit the task at hand. > > kitchen sink API design is a really bad idea, for more reasons than I > can fit in this small editor window. > On that note, I really don't like APIs that take either a file name or a file object - I can open my own files, thanks. File objects are fantastic abstractions and open(fname) is even shorter than StringIO(somedata). My take on the API decision in question was always that a file is inherently an XML *document*, while a string is inherently an XML *fragment*. From gagsl-py2 at yahoo.com.ar Sun Jan 27 12:44:48 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 15:44:48 -0200 Subject: How to modify the content of an email References: <3f39a8c3-7e47-4971-84db-f26f03e0abae@d70g2000hsb.googlegroups.com> Message-ID: En Fri, 25 Jan 2008 20:59:41 -0200, escribi?: > Hello, I'm trying to make a python script that take an email in (raw) > text format, and add a footer to the text (or html) body of the email. > > I'm aware of the email and email.mime modules, but I can't figure out > how to identify 'the main text (or html) content' from the email, and > how to be sure that I don't incorrectly identify a txt (or html) > attach as the main content of the email. > By 'main text (or html) content' I mean the text (or html) that is > showed by a Mail User Agent when it display the email to the > recipient. I suggest you read or overview the MIME specification (RFC 2045 and a few others), or some introductory text, in order to understand the terminology and what the email package does. Simple messages have is_multipart()==False and get_payload() gives you the message text. Multipart messages (e.g. having attachments, or an html/plaintext alternative) have is_multipart()==False and get_payload() returns a list of its parts. The parts may be Messages too, and can be multipart also. HTML messages usually have Content-Type: multipart/alternative, coming first the text part and later the HTML part. You probably will have to modify both, because it's up to the MUA to decide which part to show. When you modify an existing part you have to *remove* some headers like Content-Transfer-Encoding if you don't honor them in the replaced part. By example, the original may have been encoded in base64 or quoted-printable (but you didn't notice that because Python decoded the part for you). -- Gabriel Genellina From timr at probo.com Sat Jan 12 00:51:27 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 12 Jan 2008 05:51:27 GMT Subject: Image/Video Processing in Python References: <68c3707e-1c37-470d-9408-80819103959a@e6g2000prf.googlegroups.com> Message-ID: <28lgo3t65s1ln6s2tlj1kbmpsh7arphcha@4ax.com> "dongie.agnir at gmail.com" wrote: > >Hello, I'm trying to work on a project in Python that involves the use >of a webcam to track a laser pointer. I found some example code here >http://janto.blogspot.com/2006/01/motion-capture-in-python.html, but >the problem is that it's quite slow (about a sec to process a 800 by >600 image). Can anyone who has experience with computer vision help >me? Are there any existing algorithms for finding a color in an image >and plotting its coordinates? It would help me very much. You're talking about raw number crunching. This is exactly the kind of case where you should write some C or C++ code and call it from Python. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From waldemar.osuch at gmail.com Wed Jan 9 17:52:09 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Wed, 9 Jan 2008 14:52:09 -0800 (PST) Subject: Another dumb scope question for a closure. References: Message-ID: On Jan 9, 11:47 am, "Steven W. Orr" wrote: > So sorry because I know I'm doing something wrong. > > 574 > cat c2.py > #! /usr/local/bin/python2.4 > > def inc(jj): > def dummy(): > jj = jj + 1 > return jj > return dummy > > h = inc(33) > print 'h() = ', h() > 575 > c2.py > h() = > Traceback (most recent call last): > File "./c2.py", line 10, in ? > print 'h() = ', h() > File "./c2.py", line 5, in dummy > jj = jj + 1 > UnboundLocalError: local variable 'jj' referenced before assignment > > I could have sworn I was allowed to do this. How do I fix it? > I have seen this approach on ActiveState Cookbook but can not find a reference to it right now. >>> def inc(jj): ... def dummy(): ... dummy.jj += 1 ... return dummy.jj ... dummy.jj = jj ... return dummy ... >>> h = inc(33) >>> h() 34 >>> h() 35 >>> i = inc(12) >>> i() 13 >>> i() 14 Waldemar From mani.agape at gmail.com Tue Jan 29 22:59:29 2008 From: mani.agape at gmail.com (Manikandan R) Date: Wed, 30 Jan 2008 09:29:29 +0530 Subject: Fwd: The results of your email commands In-Reply-To: References: Message-ID: Hai, I am working with python 2.4. I am new to python, I need to collect all the ipaddress of the systems connected in the network for my project. While browsing I come accross Ur link. I think U peoples can help me. Can U please send me the code and guide me to get it. I am in dead line so can U make it fast ................ Thank's and Regard's, R.Manikandan. -------------- next part -------------- An HTML attachment was scrubbed... URL: From finite.automaton at gmail.com Fri Jan 11 09:41:06 2008 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: Fri, 11 Jan 2008 06:41:06 -0800 (PST) Subject: Help with Windows build of Yapgvb Python extension Message-ID: I'm the author of Yapgvb, a Python binding for Graphviz. Yapgvb enjoys modest success, but for some time it has been in dire need of a Python 2.5 build for Windows. I'm posting this message in the hopes of finding someone who is interested in making this build. This is a relatively quick task for someone who is comfortable with building C extensions and has an operational Windows build environment for Python 2.5 (which I don't). Alternately, it's a great way to learn about these things, and to get involved with a small open source project. Technologies used: graphviz distutils boost.python boost.graph See: http://yapgvb.sourceforge.net From jr9445 at ATT.COM Wed Jan 9 10:02:13 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 9 Jan 2008 09:02:13 -0600 Subject: 'Borg' and multiple threads. In-Reply-To: <47829a95$0$26035$88260bb3@free.teranews.com> References: <47829a95$0$26035$88260bb3@free.teranews.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 Tobiah > Sent: Monday, January 07, 2008 5:24 PM > To: python-list at python.org > Subject: 'Borg' and multiple threads. > > I have a class that I call Borg that starts like this: > > class Borg(dict): > > static_state = {} > def __init__(self): > self.__dict__ = self.static_state > > > > My question is why this seems to work. I had the idea that > there was a class object that is created when the file containing > the definition is read, which actually contains the static > information that is later accessed by instances. Isn't this > done when the cherrypy app first loads, rather than each time > a browser hits the app? Otherwise, where is the individual data > stored for each of two simultaneous hits of the web page? > I had a similar question except mine was from a bug. (Thinking in c++ lead me to inadvertently create static class vars.) You can "print self" and use the id() function to get the memory addresses of the variables and see what's going on. In the code below, mem4 is equivalent to your static_state. count = 1 class Foo: mem4 = {} mem5 = {} def __init__(self): self.mem = {} global count count += 1 self.mem2 = count self.mem3 = "%x" % (id(self)) self.mem5 = {} print 'init count =', count def me(self): print "object: ", self print "\tid(self.mem) %x" % (id(self.mem)), " self.mem =", self.mem print "\tid(self.mem2) %x" % (id(self.mem2)), " self.mem2 =", self.mem2 print "\tid(self.mem3) %x" % (id(self.mem3)), " self.mem3 =", self.mem3 print "\tid(self.mem4) %x" % (id(self.mem4)), " self.mem4 =", self.mem4 print "\tid(self.mem5) %x" % (id(self.mem5)), " self.mem5 =", self.mem5 global count count += 1 print '\tcount =', count self.mem4[count] = count print "\tid(self.mem4) %x" % (id(self.mem4)), " self.mem4 =", self.mem4 #self.mem += count #print "\tid(self.mem) %x" % (id(self.mem)), " self.mem =", self.mem print a = Foo() b = Foo() c = Foo() a.me() b.me() c.me() From Frank.Aune at broadpark.no Tue Jan 15 08:59:00 2008 From: Frank.Aune at broadpark.no (Frank Aune) Date: Tue, 15 Jan 2008 14:59:00 +0100 Subject: Retrieving info from DBUS at application startup Message-ID: <200801151459.00794.Frank.Aune@broadpark.no> Hello, Detecting Hotpluggable hardware using DBUS works great, but usually peripherals are already connected when launching the application. How can I (preferably using DBUS) detect which USB printers for example are connected to the system at application launch without engaging in some insane probing activity? Thanks, Frank Aune From peter2 at hipson.net Sat Jan 12 19:18:05 2008 From: peter2 at hipson.net (PeterD) Date: Sat, 12 Jan 2008 19:18:05 -0500 Subject: *** American nationalism is FAKE and its MYTHS are LIES, YANK BASTARDS RAPED BY THEIR OWN MARINES - *** References: Message-ID: <32mio3hp9a8sj9hgbe1982rqs5t3vfro79@4ax.com> On Sat, 12 Jan 2008 11:50:07 -0800 (PST), thermate2 at india.com wrote: >THE YANK CHRISTIAN WHITE MARINE Recently in Chicago an Indian father killed his daughter, and and her two children... Why? Because she'd married without his permission. So that seems to make your and your countrymen so many steps below Americans that this becomes the stupidest thread of the year... Fortunately there are still 11 months to go for you to come wup with something better. Peter's Troll-o-Meter Not Troll Troll 0 1 2 3 4 5 6 7 8 9 10 / / / / / / / O (Pegged the needle!) From Russ.Paielli at gmail.com Mon Jan 7 23:10:58 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 7 Jan 2008 20:10:58 -0800 (PST) Subject: use fileinput to read a specific line References: Message-ID: <6f2db44c-2641-47cb-ab24-4177ccc96d6e@m77g2000hsc.googlegroups.com> On Jan 7, 7:15 pm, jo3c wrote: > hi everybody > im a newbie in python > i need to read line 4 from a header file > using linecache will crash my computer due to memory loading, because > i am working on 2000 files each is 8mb > > fileinput don't load the file into memory first > how do i use fileinput module to read a specific line from a file? > > for line in fileinput.Fileinput('sample.txt') > ???? Assuming it's a text file, you could use something like this: lnum = 0 # line number for line in file("sample.txt"): lnum += 1 if lnum >= 4: break The variable "line" should end up with the contents of line 4 if I am not mistaken. To handle multiple files, just wrap that code like this: for file0 in files: lnum = 0 # line number for line in file(file0): lnum += 1 if lnum >= 4: break # do something with "line" where "files" is a list of the files to be read. That's not tested. From socyl at 987jk.com.invalid Fri Jan 25 09:28:08 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 25 Jan 2008 14:28:08 +0000 (UTC) Subject: Text-based data inspector for Python? References: Message-ID: In Terry Jones writes: >>>>>> "kj" == kj writes: >You actually liked the perl debugger... gasp! Still do, in fact!. >OK, I used it too, but it >left a few things to be desired... I'd love to read your thoughts on the matter. My biggest complain about it is that its underlying code is very poorly designed and it's having a difficult time keeping up with the language. With each new version of Perl it springs new leaks, unfortunately. For example, it's much worse than Perl itself at dealing with Unicode. ...And its documentation is probably the worst of all of the core Perl docs. Let's see, what else...? Nothing else comes to mind at the moment. >I use M-x pydb to debug python from inside emacs. I like it more than the >straight pdb as it's a bit more like gdb. >In pydb (and pdb) there's p and pp to print and pretty print a python >object. They work pretty well & there's no need for the mouse. Thank you much for the tip. I just skimmed over its documentation and I'm looking forward to using it. The one thing I couldn't find, and would greatly miss if not available, is the ability to set breakpoints by inserting a particular indication right in the code. In the Perl debugger one can insert something like the following anywhere in the code: $DB::single = 1; When such a line executes, the debugger immediately switches to single-step mode. It's a very flexible technique, and I like it a lot more than setting breakpoints the "usual" way (i.e. "b [line] [condition]"). For example, for a conditional breakpoint one can do something like: $DB::single = some_boolean_test(); Or if one isn't sure exactly when one wants to stop at the location, one can just write: $DB::single = ( $::SOME_GLOBAL_VARIABLE || 0 ); (The "|| 0" is there so that the debugger won't complain over assigning an undefined RHS in the assignment.) If while stopped at some other breakpoint, and perhaps having inspected some data, we decide that it's time to stop at this line, we just assign 1 to the global, hit the old "c"(ontinue), and one's there. In fact, setting $DB::single is the only way I know to have a breakpoint in code that executes at compile time (such as anything in a BEGIN block and any top-level code in modules imported via the "use" directive). Setting a breakpoint with b at such points and restarting the program won't work. Extremely handy. Maybe something like this (or even better!) is already possible in pydb, but I couldn't find it. If it is, though, I'll be very psyched. kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From gagsl-py2 at yahoo.com.ar Mon Jan 28 19:15:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Jan 2008 22:15:56 -0200 Subject: post variable References: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> <87ir1dr8ms.fsf@mulj.homelinux.net> <0f634854-7d7a-4ad8-ba04-38d239ecf850@d70g2000hsb.googlegroups.com> Message-ID: En Mon, 28 Jan 2008 19:32:45 -0200, pavloutefkros at gmail.com escribi?: > 1. yes i've tried that technique but its annoying, the user can easily > stop the redirection and not "elegant". > > 2. yes i'm aware of that, however what i've mentioned above is just an > example, it's actually way more serious. See this sequence: User POSTs a form Web app processes the form. Web app updates its internal state. Web app don't output anything, and finishes the POST handling with a redirect (implicit GET) Browser receives the redirect and issues a GET request Web app returns content The important thing is that a POST request *never* returns content, always redirects. All content is retrieved using GET. -- Gabriel Genellina From tjreedy at udel.edu Mon Jan 28 22:27:33 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jan 2008 22:27:33 -0500 Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: "Paddy" wrote in message news:4dc87a25-1d90-4b66-8fa4-d0d41f48344e at i29g2000prf.googlegroups.com... |I would value the opinion of fellow Pythoneers who have also | contributed to Wikipedia, on the issue of "Is Python Standardized". Depends entirely on the operative meaning of standardized. Formal standards body? Obviously no. Specified in a standard-setting document? Yes. In fact, in someways, Python is better standardized that C, for instance, in that the Python standard usefully standardizes some things that the C standard leaved unstandardized as 'implementation defined'. Example 1. Order of evaluation of function arguments. Python: left to right. C: undefined (and unstandardized), I believe. Example 2: Strings for Infinity and Not-A-Number. Python: will standardize in 2.6 to hide the variation in C implementations (or is Microsoft just non-compliant here?). From paul at boddie.org.uk Wed Jan 30 18:59:00 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 30 Jan 2008 15:59:00 -0800 (PST) Subject: Trying to understand Python web-development References: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com> <2bb822db-0a33-4c47-bdd1-f4980a73fc00@m34g2000hsf.googlegroups.com> <85a24948-9e59-4b74-95e8-6d9c75e9bff7@e23g2000prf.googlegroups.com> Message-ID: On 30 Jan, 21:27, walterbyrd wrote: > Thanks for all that posts. This thread has been helpful. > > I have seen a lot of posts about the importance of decoupling the > deployment technologies from the framework technologies. This is how I > have done that in PHP. I develop on my home box. When I get something > working the way I want, I ftp those files to the remote server. To me, > that seems to make more sense that trying to run two different web > servers on the same system. My PHP system involves no monkeying with > special config files, or running special servers to couple the > different environments, or setting special ports, or paths. For PHP > development, I don't even need ssh access. Various solutions like WebStack or WSGI should permit you to choose Apache and/or other servers and hopefully not notice big differences in your application. Various WebStack examples should run out of the distribution, admittedly using their own server processes, and there's plenty of choice when it comes to configuration complexity across the supported server technologies (CGI, mod_python, Java Servlet, and so on). Perhaps the range of WSGI adapters offer a similar range of choices. In short, flexibility is definitely here for Python Web frameworks. I'd agree that PHP is usually configured to be as easy to deploy as possible, but I guess that's because the (admittedly straightforward) configuration is typically already done for users of shared hosting. I've just got into a shared hosting situation, and PHP is set up alongside CGI and static pages - you just drop the files into the directory and Apache serves them up according to their filename extensions. To configure mod_python isn't that much harder, but there are some tricky elements which often defeat people. However, some hosting providers (such as mine) do make it just as easy, but just not at less than $1 per month. > > I think that this (the ease of PHP application deployment) is one of > > the things that keeps Python framework developers up at night > > I think you may have something there. For $10 a year I can get an > account at dollar-hosting.net, copy some php files there, and that's > all there to it. I have been beating my brains out trying to get > anything working with a python framework, and I have not been able to > do it. I even bought VPS hosting just for the sake of python > development. I have to admit that I've only fairly recently had experiences with getting Django and MoinMoin working from scratch, and the latter is mostly set up on Ubuntu systems if you install the package and know how to add a site to the Apache configuration. My observation with regard to Django 0.96 (at least, and perhaps 1.0 is a bit better) is that there's a lot of stuff that I'm moderately comfortable with - setting up mod_python, for example - but I'd be really put off doing any of it if I hadn't had the experience of doing it (and troubleshooting it) before. MoinMoin seems to be easier: you just have to copy the files into the right places. It's a lot nicer than some other solutions, notably "old school" Perl applications, which need lots of Apache tweaking to avoid easily overlooked insecurity issues. Nevertheless, there's potential for making mistakes, having the wrong permissions, and so on. > But, I still can not seem to make the quantum leap of > getting something that works locally, to work remotely. BTW: with the > VPS hosting, I had to install and configure my own web-hosting and > PHP, including setting up lighttpd with fastcgi and php modules - and > I still found that much easier than getting anything to work with > python. System packages of Python frameworks should mostly leave you with only a bit of configuration file editing to do, perhaps with some database initialisation where necessary, but I suppose that some frameworks don't have up-to-date-enough packages. Even then, perhaps it's the last bit which causes the most problems - you'll have to remind us where you got stuck, I think. Paul From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 21:40:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 02:40:34 -0000 Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> <13og1lgcespv6c2@corp.supernews.com> Message-ID: <13oga52q3f2gg1c@corp.supernews.com> On Fri, 11 Jan 2008 17:36:10 -0800, Michael Tobis wrote: > On Jan 11, 6:15 pm, Steven D'Aprano cybersource.com.au> wrote: >> Your users are *scientists*, and you don't trust their intellectual >> ability to learn a programming language as simple as Python? >> >> Instead of spending time and effort writing, debugging and maintaining >> such a fragile approach, why not invest in a couple of introductory >> books on Python programming and require your scientists to go through >> the first few chapters? Or write out a one-page "cheat sheet" showing >> them simple examples. Or, and probably most effectively, make sure all >> your classes have doc strings with lots of examples, and teach them how >> to use help(). >> >> Some people problems are best dealt with by a technical solution, and >> some are not. >> >> -- >> Steven > > I am currently talking very similar trash on my blog, See > http://initforthegold.blogspot.com/2008/01/staying-geeky.html and > http://initforthegold.blogspot.com/2007/12/why-is-climate-modeling- stuck.html > > You seem to think that learning the simple language is equivalent to > grasping the expressive power that the language provides. I do? What did I say that led you to that conclusion? > Yes, users are scientists. Therefore they do not have the time or > interest to gain the depth of skill to identify the right abstractions > to do their work. I don't follow you. If they aren't learning the skills they need to do their work, what are they doing? Hammering screws in with a hacksaw? (Metaphorically speaking.) > There are many abstractions that could be useful in science that are > currently provided with awkward libraries or messy one-off codes. I'm sure you're right. Attempts to make elegant libraries and re-usable code should be encouraged. The OP's attempt to dumb-down his library strikes me as a step in the wrong direction. > The idea that a scientist should be expected to be able to write correct > and useful Python is reasonable. I and the OP are relying on it. Please go back and look at the example the OP gave. According to the example given, his users would find this too difficult to deal with: obj1 = Obj(params1) obj2 = Obj(params2) ... bigobj = Bigobj(objects=[obj1,obj2]) bigobj.run() That's not terribly complex code, thanks to Python's easy-to-use object model. Dropping the explicit construction of the Bigobj in favour of a mysterious, implicit auto-magic run() is a serious step in the wrong direction. Any scientist working with this can see exactly what is being run(), and not have to rely on hunting through the entire source code looking for Obj() calls he might have missed. As simple as the above is, it could be made simpler. Judging from the example given, the Bigobj constructor doesn't need a keyword argument, it could just as easily take an arbitrary number of arguments: bigobj = Bigobj(obj1, obj2, obj3, obj4...) > The idea that a scientist should be expected to identify and build > clever and elegant abstractions is not. But that's their job. That's what scientists do: identify and build clever and elegant abstractions, such as Newton's Laws of Motion, Special Relativity, Evolution by Natural Selection, the Ideal Gas Laws, and so on. Even climate change models are abstractions, and we would hope they are clever and elegant rather than stupid and ugly. > If you think every scientist can > be a really good programmer you underestimate at least one of what good > scientists do or what good programmers do or what existing high > performance scientific codes are called upon to do. Read the OP's post again. His (her?) users aren't expected to create the toolkit, merely to use it. To create good toolkits you need both a master programmer and an expert in the field. It is an advantage if they are the same person. But to use such a good toolkit, you shouldn't need to be a master programmer. -- Steven From ornto at nospam.org Fri Jan 18 06:04:57 2008 From: ornto at nospam.org (ornto) Date: Fri, 18 Jan 2008 12:04:57 +0100 Subject: [HELP] SMTPlib not sending my mail Message-ID: Hi, I'm trying to create an application which checks a dynamic web site and on certain events sends an email to me. My problem though is with the email task. By now I made this simple test code: #prova invio email smtpserver = smtplib.SMTP(mailserver) messaggio= "Messaggio di prova" print mail print messaggio smtpresult=smtpserver.sendmail("Watcher",mail,messaggio) if smtpresult: print smtpresult smtpserver.quit() "mailserver" and "mail" values are loaded from a ini file and they're correct. The call to smtpserver gives back no errors (smtpresult remains empty). The running enviroment gives no error. So, it looks like that the program works alloright, sending the mail- BUT, I receive no mail! I've tried to change the smtp server with another one which still works with my isp, with no luck. If I try a smtp which doesn't give me access, I correctly receive an error from the program. What might be the problem? From mensanator at aol.com Sat Jan 12 14:54:08 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Sat, 12 Jan 2008 11:54:08 -0800 (PST) Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> Message-ID: On Jan 12, 12:37?pm, marcstuart wrote: > How do I divide a list into a set group of sublist's- if the list is > not evenly dividable ? > consider this example: > > x = [1,2,3,4,5,6,7,8,9,10] > y = 3 ? ? ?# number of lists I want to break x into > z = y/x > > what I would like to get is 3 sublists > > print z[0] = [1,2,3] > print z[2] = [4,5,6] > print z[3] = [7,8,9,10] > > obviously not even, one list will have 4 elements, the other 2 will > have 3., > the overriding logic, is that I will get 3 lists and find a way for > python to try to break it evenly, if not one list can have a greater > amount of elements > > Would I use itertools ? How would I do this ? > > Thanks def list_split(x,y): dm = divmod(len(x),y) if dm[1] != 0: z = [x[i*y:i*y+y] for i in xrange(len(x)/y) if len(x[i*y:])>=2*y] z.append(x[(len(x)/y-1)*y:]) else: z = [x[i*y:i*y+y] for i in xrange(len(x)/y)] return z >>> list_split([1,2,3,4,5,6,7,8,9,10],3) [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] >>> list_split([1,2,3,4,5,6,7,8,9,10],5) [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] >>> list_split([1,2,3,4,5,6,7,8,9,10],4) [[1, 2, 3, 4], [5, 6, 7, 8, 9, 10]] >>> list_split([1,2,3,4,5,6,7,8,9,10],2) [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] From gagsl-py2 at yahoo.com.ar Sun Jan 20 15:14:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 20 Jan 2008 18:14:39 -0200 Subject: Looping through the gmail dot trick References: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> Message-ID: En Sun, 20 Jan 2008 14:38:06 -0200, Joshua Gilman escribi?: > My task is this: Loop through an email and create as many combinations of > periods as possible. So all the combinations for blah would be: > > b.lah > bl.ah > bla.h > b.l.ah > b.la.h > bl.a.h I'd use a recursive generator (the divide-and-conquer approach): def genalldots(txt): if len(txt)<=1: yield txt else: head, tail = txt[0], txt[1:] for item in genalldots(tail): yield head+item yield head+'.'+item print sorted(genalldots('blah')) (I got your six spellings above, plus 'blah' and 'b.l.a.h') > I'm still rather new to python so this is turning out to be rather > tricky. > My current code is as follows: > > for d in range(1, len(email)): >> for i in range(1, len(email)): >> y = i >> temail = email >> for x in range(d): >> if email[y] == '.': break >> temail = temail.replace(email[y], '.' + email[y]) >> if not y > len(email) - 2: y += 1 >> print temail The replace function is dangerous, in case a letter appears more than once, you are replacing all instances. Anyway, since you *know* you want to replace the y-th item, just do: temail = temail[:y] + '.' + temail[y:] -- Gabriel Genellina From nikolaskaralis at gmail.com Tue Jan 15 23:22:36 2008 From: nikolaskaralis at gmail.com (Nikolas Karalis) Date: Wed, 16 Jan 2008 06:22:36 +0200 Subject: reliable whois in python In-Reply-To: References: Message-ID: <85b2e0230801152022w5a6cdb86u133a4795f562becc@mail.gmail.com> I had done a project part of which was what you want to do. You can find it here... http://users.ntua.gr/ge04042/projects/dns/ Feel free to use the code. I hope this helps. Nikolas On Jan 15, 2008 5:48 AM, eliss wrote: > Hi everyone, > > I'm trying to write a python script to whois a few domains twice a day > so I get notified when they become available. I did it 2 ways, but > neither way is very reliable, so I'm asking here. > > 1) I tried just calling "whois %s" using popen, but I found that once > every few weeks, I get errors like: > connect: No route to host OR > fgets: Connection reset by peer > I don't think it's a connectivity issue because looking up the other > domains that day works, and just one domain will give an error. So > it's probably more like a networking issue? I don't know... > > 2) I tried using sockets to connect to the whois port of > whois.internic.net and then read the info, which works a little better > than 1). However, sometimes this is not reliable too and I get errors. > > Does anyone have any ideas how I can do this better? > > Thanks, > > eliss > -- > http://mail.python.org/mailman/listinfo/python-list > -- Nikolas Karalis Applied Mathematics and Physics Undergraduate National Technical University of Athens, Greece http://users.ntua.gr/ge04042 -------------- next part -------------- An HTML attachment was scrubbed... URL: From B.Ogryczak at addr.in.reply-to.invalid Sun Jan 20 12:07:17 2008 From: B.Ogryczak at addr.in.reply-to.invalid (Bart Ogryczak) Date: Sun, 20 Jan 2008 17:07:17 +0000 (UTC) Subject: Bug in __init__? References: <88580064-3590-471e-8036-a631dd5a38b4@i3g2000hsf.googlegroups.com> Message-ID: On 2008-01-20, citizen Arnaud Delobelle testified: > On Jan 20, 3:39?pm, Bart Ogryczak to.invalid> wrote: >> On 2008-01-18, citizen Zbigniew Braniecki testified: >> >> > It's really a nice pitfall, I can hardly imagine anyone expecting this, >> >> AFAIR, it's described in Diving Into Python. > > Still there seems to be about one message a week about this. Indeed I > reckon the greatest benefit of early binding of default function > arguments is that it attracts lots of new people to comp.lang.python. Generally there's lot of confusion about assigments of objects. I guess, there are lot of ppl, who started with languages like PHP, where $a = $b, translates to Python's a = copy(b). >> It's quiet elegant way of creating cache. > > IMHO, calling it 'elegant' is pushing it too far! Ok, maybe that's not a good choice of word. Not elegant, minimalist. bart -- "The first version of iBook looked a bit too much like toilet seat" (c)Newsweek http://candajon.azorragarse.info/ http://azorragarse.candajon.info/ From tjhnson at gmail.com Mon Jan 21 19:50:44 2008 From: tjhnson at gmail.com (tjhnson at gmail.com) Date: Mon, 21 Jan 2008 16:50:44 -0800 (PST) Subject: Max Long References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> <5vkog7F1m4dhvU1@mid.individual.net> Message-ID: On Jan 21, 3:34 pm, Bjoern Schliessmann wrote: > tjhn... at gmail.com wrote: > > How can I figure out the largest long available? > > Why would you? AFAIK, longs are only limited by available memory. Indeed, as the docs pointed out. I guess I was confused by "If pylong is greater than ULONG_MAX, an OverflowError is raised." at http://docs.python.org/api/longObjects.html. From http Mon Jan 28 05:04:33 2008 From: http (Paul Rubin) Date: 28 Jan 2008 02:04:33 -0800 Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> Message-ID: <7xk5lul0zy.fsf@ruckus.brouhaha.com> "Russ P." writes: > You might want to check into what the FAA allows in "flight-critical" > code, for example. I am certainly not an expert in that area, but I've > had a passing exposure to it. My understanding is that every possible > branch of the code must be fully and meticulously analyzed and > verified. Hence, the dynamic dispatching of ordinary object-oriented > code is either prohibited or severely frowned upon. This would also seem to impact higher-order functions, which are prominent in fancy verification systems based on extracting code from constructive theorem provers. I know those things are used in some sensitive security applications. I wonder what the aerospace community thinks of that area. From musiccomposition at gmail.com Tue Jan 29 09:44:27 2008 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 29 Jan 2008 06:44:27 -0800 (PST) Subject: refcount References: Message-ID: On Jan 29, 5:46 am, Christian Heimes wrote: > Simon Pickles wrote: > > Hi, > > > Is is possible to access the refcount for an object? > > > Ideally, I am looking to see if I have a refcount of 1 before calling del > > Help on built-in function getrefcount in module sys: > > getrefcount(...) > getrefcount(object) -> integer > > Return the reference count of object. The count returned is generally > one higher than you might expect, because it includes the (temporary) > reference as an argument to getrefcount(). Are there any cases when it wouldn't? > > Christian From grante at visi.com Wed Jan 30 20:59:17 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 31 Jan 2008 01:59:17 -0000 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! References: <832c7add-b222-46d7-a151-45f02444d520@s19g2000prg.googlegroups.com> Message-ID: <13q2arlaqtsjo13@corp.supernews.com> On 2008-01-31, ajaksu wrote: > On Jan 30, 10:40 pm, "Blubaugh, David A." > wrote: >> I do not understand why no one has answered the following question: >> >> Has anybody worked with Gene Expression Programming???? >> >> David Blubaugh > > I see. You don't understand. That's a fact. I'm sure there are free > online resources about the best way to understand why no one answered > your question in particular, or why people don't answer some questions > in a more comparative way. Like this: http://catb.org/~esr/faqs/smart-questions.html -- Grant Edwards grante Yow! Well, I'm on the at right planet---everyone visi.com looks like me!!! From over at thepond.com Wed Jan 23 13:38:57 2008 From: over at thepond.com (over at thepond.com) Date: Wed, 23 Jan 2008 18:38:57 GMT Subject: python24 symbol file...pyhon24.pdb References: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> Message-ID: On Wed, 23 Jan 2008 08:54:19 +0100, Christian Heimes wrote: >over at thepond.com wrote: >> I've seen a few references on the net to a python24.pdb file. I assume >> it's a symbol file along the lines of the pdb files issued by >> microsoft for their products. Maybe I'm wrong. > >.pdb files (program database) are created by MS' compiler, see >http://en.wikipedia.org/wiki/Program_database. Python doesn't ship the >files. You have to compile Python yourself to get the pdb files. > >Christian thanks From mal at egenix.com Fri Jan 4 11:10:27 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 04 Jan 2008 17:10:27 +0100 Subject: Memory Leaks and Heapy In-Reply-To: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> Message-ID: <477E5A73.9070400@egenix.com> On 2008-01-04 16:07, Yaakov Nemoy wrote: > Hi list, > > Firstly, this is my first post here, so I hope I'm not breaking some > unwritten etiquette rule about asking questions involving several > different libraries. > > I'm trying to plug some memory leaks in a TurboGears program. We (the > Fedora Project) have a few apps in Turbogears in infrastructure that > all seem to be running into the same issues in a variety of > configurations. Hopefully when I get to the cause of this in one app, > Smolt, we can fix the others too. > > The app in question is Smolt, which uses TurboGears, SQLAlchemy with a > MySQL backend, and simplejson for message passing between the server > and client. Smolt takes voluntary hardware reports from its clients, > and generally is configured to submit around the beginning of the > month. Normally, our main data is cached by some separate processes > that run short term, so we don't see any rapid memory growth, except > for the beginning of each month, which makes isolating the problem to > a few function calls fairly simple. To watch for memory growth, I > simply have a client hammer the server with 1-3 threads submitting > information simultaneously, 100 times, with a few deletion operations > in between. To monitor for memory leaks, I'm using Heapy. > > To insert Heapy into the process, instead of calling 'start_server', a > cherrypy method that does what you think it does and blocks, I'm using > the module 'threading' to push it into a new thread. Using the > process in heapy's documentation, I find that after running a single > thread, there is about 1200 bytes of leaked memory. Despite this, the > python process running the server has managed to grow from 16-18MB to > something between 23-28MB each time I try this. After a second > iteration, heapy shows 1168 bytes leaked. If heapy is correct, this > means there are not many leaked objects in the python space. Running > a larger example, say 100 threads, for a total of 10k submissions > takes about an hour, and in the process, python baloons up to about > 48MB. Still no signs of any missing objects. > > 48MB is not alot relatively speaking, but no amount of waiting seems > to show python giving back that memory afterwards. On our production > server, we have up to 200k machines all updating their information > over a 3 day period, in which the server process manages to reach > 600MB before we forcefully restart it. > > A couple of developers have mentioned that python might be fragmenting > its memory space, and is unable to free up those pages. How can I go > about testing for this, and are there any known problems like this? > If not, what else can I do to look for leaks? If you're using lots of small objects, you may be running into a problem with the Python memory allocation mechanism, pymalloc. It used to not return memory to the system. In Python 2.5 (IIRC, could be 2.6) this was changed to at least return completely empty blocks back to the OS. For details, see Objects/obmalloc.c This could be caused by interned strings which are kept in a special pool dictionary to speed up string comparisons. However, the first thing to check is whether any of the C extension modules you are using is leaking memory. Python itself is usually well tested for memory leaks, but this is less so for C extension modules and it's easy to mis a few Py_DECREFs (decrementing a Python object's reference count), causing objects to live forever. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jan 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From nytrokiss at gmail.com Mon Jan 7 16:54:05 2008 From: nytrokiss at gmail.com (James Matthews) Date: Mon, 7 Jan 2008 22:54:05 +0100 Subject: Python's great, in a word In-Reply-To: <87ve65mie1.fsf@benfinney.id.au> References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <87ve65mie1.fsf@benfinney.id.au> Message-ID: <8a6b8e350801071354m6666534ai2440705db722807d@mail.gmail.com> Just Another Vague Acronym = (Java) On Jan 7, 2008 10:32 PM, Ben Finney wrote: > MartinRinehart at gmail.com writes: > > > The best thing about Python is _______. > > The best thing about Python is its elegance. > > -- > \ "Like the creators of sitcoms or junk food or package tours, | > `\ Java's designers were consciously designing a product for | > _o__) people not as smart as them." -- Paul Graham | > Ben Finney > -- > 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 mark.e.tolonen at mailinator.com Fri Jan 25 23:40:23 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Fri, 25 Jan 2008 20:40:23 -0800 Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> Message-ID: "Summercool" wrote in message news:27249159-9ff3-4887-acb7-99cf0d2582a8 at n20g2000hsh.googlegroups.com... > > somebody who is a regular expression guru... how do you negate a word > and grep for all words that is > > tire > > but not > > snow tire > > or > > snowtire > > so for example, it will grep for > > winter tire > tire > retire > tired > > but will not grep for > > snow tire > snow tire > some snowtires > > need to do it in one regular expression > What you want is a negative lookbehind assertion: >>> re.search(r'(?>> re.search(r'(? Unfortunately you want variable whitespace: >>> re.search(r'(?", line 1, in File "C:\dev\python\lib\re.py", line 134, in search return _compile(pattern, flags).search(string) File "C:\dev\python\lib\re.py", line 233, in _compile raise error, v # invalid expression error: look-behind requires fixed-width pattern >>> Python doesn't support lookbehind assertions that can vary in size. This doesn't work either: >>> re.search(r'(? Here's some code (not heavily tested) that implements a variable lookbehind assertion, and a function to mark matches in a string to demonstrate it: ### BEGIN CODE ### import re def finditerexcept(pattern,notpattern,string): for matchobj in re.finditer('(?:%s)|(?:%s)'%(notpattern,pattern),string): if not re.match(notpattern,matchobj.group()): yield matchobj def markexcept(pattern,notpattern,string): substrings = [] current = 0 for matchobj in finditerexcept(pattern,notpattern,string): substrings.append(string[current:matchobj.start()]) substrings.append('[' + matchobj.group() + ']') current = matchobj.end() # substrings.append(string[current:]) return ''.join(substrings) ### END CODE ### >>> sample='''winter tire ... tire ... retire ... tired ... snow tire ... snow tire ... some snowtires ... ''' >>> print markexcept('tire','snow\s*tire',sample) winter [tire] [tire] re[tire] [tire]d snow tire snow tire some snowtires --Mark From ajsavige at yahoo.com.au Wed Jan 9 05:58:20 2008 From: ajsavige at yahoo.com.au (Andrew Savige) Date: Wed, 9 Jan 2008 02:58:20 -0800 (PST) Subject: Learning Python via a little word frequency program Message-ID: <493158.64888.qm@web56406.mail.re3.yahoo.com> I'm learning Python by reading David Beazley's "Python Essential Reference" book and writing a few toy programs. To get a feel for hashes and sorting, I set myself this little problem today (not homework, BTW): Given a string containing a space-separated list of names: names = "freddy fred bill jock kevin andrew kevin kevin jock" produce a frequency table of names, sorted descending by frequency. then ascending by name. For the above data, the output should be: kevin : 3 jock : 2 andrew : 1 bill : 1 fred : 1 freddy : 1 Here's my first attempt: names = "freddy fred bill jock kevin andrew kevin kevin jock" freq = {} for name in names.split(): freq[name] = 1 + freq.get(name, 0) deco = zip([-x for x in freq.values()], freq.keys()) deco.sort() for v, k in deco: print "%-10s: %d" % (k, -v) I'm interested to learn how more experienced Python folks would solve this little problem. Though I've read about the DSU Python sorting idiom, I'm not sure I've strictly applied it above ... and the -x hack above to achieve a descending sort feels a bit odd to me, though I couldn't think of a better way to do it. I also have a few specific questions. Instead of: for name in names.split(): freq[name] = 1 + freq.get(name, 0) I might try: for name in names.split(): try: freq[name] += 1 except KeyError: freq[name] = 1 Which is preferred? Ditto for: deco = zip([-x for x in freq.values()], freq.keys()) versus: deco = zip(map(operator.neg, freq.values()), freq.keys()) Finally, I might replace: for v, k in deco: print "%-10s: %d" % (k, -v) with: print "\n".join("%-10s: %d" % (k, -v) for v, k in deco) Any feedback on good Python style, performance tips, good books to read, etc. is appreciated. Thanks, /-\ Make the switch to the world's best email. Get the new Yahoo!7 Mail now. www.yahoo7.com.au/worldsbestemail From andre.john at s1999.tu-chemnitz.de Wed Jan 16 12:07:14 2008 From: andre.john at s1999.tu-chemnitz.de (Andre' John) Date: Wed, 16 Jan 2008 18:07:14 +0100 Subject: Generic string import like in strptime? In-Reply-To: References: Message-ID: Nice. Thanks a lot. Andre On Wed, 16 Jan 2008, Paul Hankin wrote: > On Jan 16, 8:34 am, Andre wrote: > > Hi there > > > > Is there a function like strptime, which takes a string and converts it > > into an array depending on a format string I provide. Like:>>> a = '3456\tblub-blib.0.9' > > >>> b = '%d\t%s-%s.%f' > > >>> c = mysticalfunction(a,b) > > >>> print c > > > > [3456,'blub','blib',0.9] > > Use regular expressions: see http://docs.python.org/lib/node49.html > > -- > Paul Hankin > From lotrpy at gmail.com Sun Jan 13 06:24:59 2008 From: lotrpy at gmail.com (lotrpy) Date: Sun, 13 Jan 2008 03:24:59 -0800 (PST) Subject: about sort a list with integer key Message-ID: <986e05f3-2fe9-4fe8-94e2-fef26713a78c@i72g2000hsd.googlegroups.com> hi, if I want sort each line ,by the last part,of a file, below is the source. from operator import itemgetter content = (line.split() for line in file('foo.txt', 'rb')) for cursor, line in enumerate(sorted(content, key = itemgetter(-1), reverse = True)): print cursor, ' '.join(line) the content of foo.txt is 21 job 3 joke the result is 0 3 joke 1 21 job if i want sort each line by the first part,(it's a integer, in fact). don't know how to do it with itemgetter. key = int(itemgetter(0)) is wrong, key = lambda x:int(x[0]) works. but s.b. told me itemgetter execute more quickly . From tarundevnani at gmail.com Mon Jan 28 02:52:43 2008 From: tarundevnani at gmail.com (tarun) Date: Mon, 28 Jan 2008 13:22:43 +0530 Subject: [wxPython-users] Issue with docking wx.listctrl window In-Reply-To: References: <4798D1B1.7020908@alldunn.com> <479A145C.40802@alldunn.com> Message-ID: Robin, I can use sizers and divide my frames into sections. But I also want to add menu options for display/hide window1 and window2 in my original example. Is this possible even if I use sizers. Regards, Tarun On Jan 28, 2008 1:09 PM, tarun wrote: > Thanks Robin. > Can you please elobrate more on this. > > Regards, > Tarun Devnani > On Jan 25, 2008 10:24 PM, Robin Dunn wrote: > > > tarun wrote: > > > Thanks a lot Robin. > > > > > > I tried using self.log and instead of self.log.list. *Code is > > attached.* > > > But this gives me a panel and listctrl in it. The extra blank space > > > around the listctrl in window1 is something that I don't need. > > > > Use a sizer to manage the layout of the listctrl. > > > > -- > > Robin Dunn > > Software Craftsman > > http://wxPython.org Java give you jitters? > > Relax with wxPython! > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Sat Jan 26 02:30:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 26 Jan 2008 08:30:53 +0100 Subject: python and multithreading problem In-Reply-To: <3a1379f5-f5f5-4af1-903c-8b1f52eb9ed7@k2g2000hse.googlegroups.com> References: <3a1379f5-f5f5-4af1-903c-8b1f52eb9ed7@k2g2000hse.googlegroups.com> Message-ID: <6005tiF1oad5lU1@mid.uni-berlin.de> whatazor schrieb: > Hi all, > I made an application that use multithreading (indifferently importing > thread or threading module) , but when I call some wrapped modules > (with swig) from my application they run like there is only a single > thread (and my application gui ,made with wxPython, freezes). If I use > other modules not wrapped, but created for test that multithread > works, and gui is not freezing are ok. > Modules that wrap DLL are not my product but are created by another > developer with VS.NET, and the only thing I can think is that they're > builded without multithreaded compiler option. Can it be another cause > for this behaviour, can this explanation be correct? maybe also swig > have a multithreading option. There is something called Global Interpreter Lock (GIL) that causes such behavior. It will ensure that python-code won't interfere with each other in multiple threads. However, for C-extensions it is common to release that GIL when a thread enters the extenison, and grab it again when finished. I don't know if SWIG does so, but to me it looks as if that is the problem. You might consider googling swig + gil or something to learn more about it. Diez From donn.ingle at gmail.com Mon Jan 14 11:02:56 2008 From: donn.ingle at gmail.com (Donn) Date: Mon, 14 Jan 2008 18:02:56 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A77F0.4000502@v.loewis.de> References: <200801132048.08966.donn.ingle@gmail.com> <478A77F0.4000502@v.loewis.de> Message-ID: <200801141802.56353.donn.ingle@gmail.com> Given that getlocale() is not to be used, what's the best way to get the locale later in the app? I need that two-letter code that's hidden in a typical locale like en_ZA.utf8 -- I want that 'en' part. BTW - things are hanging-together much better now, thanks to your info. I have it running in locale 'C' as well as my other test locales. What a relief! \d From sjmachin at lexicon.net Tue Jan 22 05:02:19 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 22 Jan 2008 02:02:19 -0800 (PST) Subject: stdin, stdout, redmon References: <4794a5e3$0$9014$426a74cc@news.free.fr> <4794ab22$0$19179$426a74cc@news.free.fr> <4795ba80$0$17176$426a74cc@news.free.fr> Message-ID: On Jan 22, 8:42 pm, Bernard Desnoues wrote: > Hello, > > I checked under linux and it works : > text.txt : > "first line of the text file > second line of the text file" > > test.py : > "import sys > a = sys.stdin.readlines() > x = ''.join(a) > x = x.upper() > sys.stdout.write(x)" > > >cat text.txt | python test.py > > But I reinstalled Python 2.5 under Windows XP and it doesn't work > anyway. Can you confirm that your script works with Win XP and Python 2.5 ? > > Regards > > Rolf van de Krol a ?crit : > > > I don't know what you did with your Python installation, but for me this > > works perfectly. > > > test3.py contains: > > > > import sys > > > print sys.stdin.readlines() > > > > > test.txt contains: > > > > Testline1 > > Testline2 > > > > > Output of 'python test3.py < test.txt' is: > > > > ['Testline1\n', 'Testline2'] > > > > > Just plain simple and just works. > > > Rolf > > > Bernard Desnoues wrote: > >> Rolf van de Krol a ?crit : > > >>> According to various tutorials this should work. > > >>> > >>> |import sys > >>> data = sys.stdin.readlines() > >>> print "Counted", len(data), "lines."| > >>> > > >>> Please use google before asking such questions. This was found with > >>> only one search for the terms 'python read stdin' > > >>> Rolf > > >>> Bernard Desnoues wrote: > > >>>> Hi, > > >>>> I've got a problem with the use of Redmon (redirection port > >>>> monitor). I intend to develop a virtual printer so that I can modify > >>>> data sent to the printer. > >>>> Redmon send the data flow to the standard input and lauchs the > >>>> Python program which send modified data to the standard output > >>>> (Windows XP and Python 2.5 context). > >>>> I can manipulate the standard output. > > >>>> "import sys > >>>> sys.stdout.write(data)" > > >>>> it works. > >>>> But how to manipulate standard input so that I can store data in a > >>>> string or in an object file ? There's no "read" method. > > >>>> "a = sys.stdin.read()" doesn't work. > >>>> "f = open(sys.stdin)" doesn't work. > > >>>> I don't find anything in the documentation. How to do that ? > >>>> Thanks in advance. > > >>>> Bernard Desnoues > >>>> Librarian > >>>> Biblioth?que de g?ographie - Sorbonne > > >> Hello Rolf, > > >> I know this code because I have search a solution ! > >> Your google code doesn't work ! No attribute "readlines". > > >> >>> import sys > >> >>> data = sys.stdin.readlines() > > >> Traceback (most recent call last): > >> File "", line 1, in > >> data = sys.stdin.readlines() > >> AttributeError: readlines Excuse me, gentlemen, may I be your referee *before* you resort to pistols at dawn? ===== IDLE ===== IDLE 1.2.1 >>> import sys >>> sys.stdin.readlines Traceback (most recent call last): File "", line 1, in sys.stdin.readlines AttributeError: readlines >>> ===== Command Prompt ===== C:\junk>python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdin.readlines >>> HTH, John From jr9445 at ATT.COM Fri Jan 18 13:25:55 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 18 Jan 2008 12:25:55 -0600 Subject: Filtering two files with uncommon column In-Reply-To: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.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 Madhur > Sent: Friday, January 18, 2008 4:23 AM > To: python-list at python.org > Subject: Filtering two files with uncommon column > > > Basically I want to compare the two files based on second column. If > the second > column matches on both the files do not print anything, else if there > is no matc > h in for the second column for first file in second file then print it > under Fil > e1 header, else if there is no match for the second column for second > file in fi > rst file print it under File2 header. > I often do this to compare property files between environments. The follow algorithm works for any number of files by creating a dictionary of lists (or hash of arrays in Perl-ese.) Create a dictionary Index = -1 For file in files Index++ For line in file col = match/split/regex the column If col not in dictionary Dictionary[col] = [] extend dictionary[col] to length of index dictionary[col][index] = col for col in sort(dictionary.keys()): extend dictionary[col] to length of index print dictionary[col] ***** 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. GA622 From hniksic at xemacs.org Mon Jan 14 18:00:45 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 15 Jan 2008 00:00:45 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> Message-ID: <87ir1wf1wi.fsf@mulj.homelinux.net> Ben Finney writes: > Hrvoje Niksic writes: > >> Wildemar Wildenburger writes: >> > __init__() /initializes/ an instance (automatically after >> > creation). It is called, /after/ the instance has been constructed >> >> I don't understand the purpose of this "correction". After all, >> __init__ *is* the closest equivalent to what other languages would >> call a constructor. > > No. That would be '__new__', which actually constructs the instance, That's not what other OO languages (C++, Java) actually call a constructor, so your correction is misplaced. My other posts in this thread have expanded on this. From ivan.illarionov at gmail.com Wed Jan 30 17:04:23 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 30 Jan 2008 14:04:23 -0800 (PST) Subject: Events in Python References: Message-ID: <2b005569-3dbc-41c1-aebf-8b6fd8d2175e@v46g2000hsv.googlegroups.com> You may need Louie (http://louie.berlios.de) Django (http://djangoproject.com) does the same in django.dispatch - and Django version works about 33% faster. Note that all those signals/events are very slow in Python. --Ivan From cwitts at gmail.com Fri Jan 4 09:07:08 2008 From: cwitts at gmail.com (Chris) Date: Fri, 4 Jan 2008 06:07:08 -0800 (PST) Subject: how to build a dict including a large number of data References: Message-ID: <6d89cea7-9c21-4c26-9659-aef204df1f09@c4g2000hsg.googlegroups.com> On Jan 4, 3:57 pm, wanzathe wrote: > hi everyone > i'm a newbie to python :) > i have a binary file named test.dat including 9600000 records. > the record format is int a + int b + int c + int d > i want to build a dict like this: key=int a,int b values=int c,int d > i choose using bsddb and it takes about 140 seconds to build the dict. > what can i do if i want to make my program run faster? > or is there another way i can choose? > Thanks in advance. > > My Code: > ----------------------------------------------------------------------------------- > my_file = file('test.dat','rb') > content = my_file.read() > record_number = len(content) / 16 > > db = bsddb.btopen('test.dat.db','n',cachesize=500000000) > for i in range(0,record_number): > a = struct.unpack("IIII",content[i*16:i*16+16]) > db['%d_%d' % (a[0],a[1])] = '%d_%d' % (a[2],a[3]) > > db.close() > my_file.close() my_file = file('test.dat','rb') db = bsddb.btopen('test.dat.db','n',cachesize=500000000) content = myfile.read(16) while content: a = struct.unpack('IIII',content) db['%d_%d' % (a[0],a[1])] = '%d_%d' % (a[2],a[3]) content = myfile.read(16) db.close() my_file.close() That would be more memory efficient, as for speed you would need to time it on your side. From mmanns at gmx.net Fri Jan 25 21:01:04 2008 From: mmanns at gmx.net (Martin Manns) Date: Sat, 26 Jan 2008 03:01:04 +0100 Subject: pyfov Package Index link broken Message-ID: Hi, I am looking for the code of pyfov, which is on the Package Index. However, the link is broken and the author does not seem to respond to e-mails. Any chance to get hands on the code? Martin From pete.forman at westerngeco.com Fri Jan 25 02:57:38 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Fri, 25 Jan 2008 07:57:38 +0000 Subject: When is min(a, b) != min(b, a)? References: <13pia6m7phe2n22@corp.supernews.com> <71a066ac-f7a4-4f3d-b154-353b88af24f2@x69g2000hsx.googlegroups.com> Message-ID: Mark Dickinson writes: > Any change to Python that made == and != checks involving NaNs raise > an exception would have to consider the consequences for set, dict, > list membership testing. > > > and if Python had separate operators for these two purposes it > wouldn't be Python any more. There are separate Python operators, "==" and "is". The C99 standard, which Python defers to for its implementation, says in 6.2.6.1.4: Two values (other than NaNs) with the same object representation compare equal, but values that compare equal may have different object representations. In 7.12.13, the fmax and fmin functions treat NaNs as missing arguments. Most other operations return NaN if an argument is NaN, or for a domain error. 7.12.14 specifies comparison macros that are quiet versions of the relational operators. BTW floating-point exceptions in C and IEEE are not the same as exceptions in higher level languages. The behavior of signalling NaNs are not defined in C. Only quiet NaNs are returned from operations. An invalid floating-point exception may well just set a status flag. That may be tested after a set of calculations. With pipelining the exact cause of the exception will be unknown. -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.port5.com -./\.- WesternGeco. From paul.sijben at xs4all.nl Mon Jan 14 05:58:43 2008 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Mon, 14 Jan 2008 11:58:43 +0100 Subject: encrypting python modules In-Reply-To: <5v0mquF1jhm3dU7@mid.dfncis.de> References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <5v0mquF1jhm3dU7@mid.dfncis.de> Message-ID: <478b4043$0$85785$e4fe514c@news.xs4all.nl> Robert Latest wrote: > Paul Sijben wrote: > >> The problem: I have a client-server app written in python. I want to >> make sure that the client is not: >> 1) destabilized by users accidentally or on purpose dropping python >> files in the path (after which calling the helpdesk will not be useful) >> 2) extended with "new features" without me knowing about it (again >> resulting in calls to my helpdesk...) > > You could check the MD5 hashes of your files. > > robert indeed but I still need to hook into import to do that reliably, right? From fredrik at pythonware.com Wed Jan 9 09:33:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 15:33:38 +0100 Subject: How does unicode() work? In-Reply-To: <1199888091.3474.9.camel@dot.uniqsys.com> References: <5ujt96F1i6h37U1@mid.dfncis.de> <1199888091.3474.9.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > If that really is the line that barfs, wouldn't it make more sense to > repr() the unicode object in the second position? > > import sys > for k in sys.stdin: > print '%s -> %s' % (k, repr(k.decode('iso-8859-1'))) > > Also, I'm not sure if the OP has told us the truth about his code and/or > his error message. The implicit str() call done by formatting a unicode > object with %s would raise a UnicodeEncodeError, not the > UnicodeDecodeError that the OP is reporting. So either I need more > coffee or there is something else going on here that hasn't come to > light yet. When mixing Unicode with byte strings, Python attempts to decode the byte string, not encode the Unicode string. In this case, Python first inserts the non-ASCII byte string in "%s -> %s" and gets a byte string. It then attempts to insert the non-ASCII Unicode string, and realizes that it has to convert the (partially built) target string to Unicode for that to work. Which results in a *UnicodeDecodeError*. >>> "%s -> %s" % ("???", "???") '\x86\x84\x94 -> \x86\x84\x94' >>> "%s -> %s" % (u"???", u"???") u'\xe5\xe4\xf6 -> \xe5\xe4\xf6' >>> "%s -> %s" % ("???", u"???") Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'ascii' codec can't decode byte 0x86 ... (the actual implementation differs a bit from the description above, but the behaviour is identical). From steve at REMOVE-THIS-cybersource.com.au Tue Jan 1 16:54:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 01 Jan 2008 21:54:27 -0000 Subject: Newbie: Why doesn't this work References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> Message-ID: <13nldkj6ecl4j31@corp.supernews.com> On Tue, 01 Jan 2008 13:01:24 -0800, petr.jakes.tpc wrote: >> > My question is: is it possible to set the "property" for any >> > attribute when I do not know what will be the name of the attribute >> > in the future? >> >> Uhm... I don't understand the question. Perhaps if you think of a >> concrete case...? > > Thanks for reply, > > few minutes after i posted my question, I have realized my posting is > probably a "nonsense". > > If I understand it properly, it is necessary, in the respect of > encapsulation, to define attributes inside the class (even it is > possible to add a new attribute to the existing object outside class > definition). > > The meaning of my question was: > Is it possible to define some general sort of set/get/del/doc rules for > the attributes which are defined in the code AFTER the instantiation of > an object. > > I am sending this question even I feel such a "on the fly" creation of > the attribute is probably not a good trick. Like all dynamic modification of classes, it is liable to abuse, but Python allows such things and trusts the programmer not to be foolish. class Parrot(object): pass def set_property(cls, propertyname, defaultvalue=None, docstring=''): """Make a readable, writable but not deletable property.""" privatename = '_' + propertyname setattr(cls, privatename, defaultvalue) def getter(self): return getattr(self, privatename) def setter(self, value): setattr(self, privatename, value) setattr(cls, propertyname, property(getter, setter, None, docstring)) set_property(Parrot, 'colour', 'red', """Parrots have beautiful coloured plumage.""") Now that you know how to do it, please don't. Except for the lack of docstring, the above is much better written as: class Parrot(object): colour = 'red' -- Steven From lasses_weil at klapptsowieso.net Wed Jan 30 09:29:45 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Wed, 30 Jan 2008 15:29:45 +0100 Subject: Removing Pubic Hair Methods In-Reply-To: References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> Message-ID: <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> Gerardo Herzig wrote: > I will use genital().extend(), thats for shure ^^ Well, you never go wrong with apply(genital(), females), do you? /W From projecteclipsor at gmail.com Sat Jan 12 02:03:42 2008 From: projecteclipsor at gmail.com (Landon) Date: Sat, 12 Jan 2008 01:03:42 -0600 Subject: Great Python books for the beginner Message-ID: Hi, I'm a freshman in college and I'm going to be taking an intro to programming course next semester which mainly uses Python, so I thought it might be a good time to pick up Python beyond the scope of the class as well. The text book for this class is Python for the Absolute Beginner or something similar to that name. I was wondering if anyone had any opinions on what other titles I could look into since this one seems from a glance at reviews to be teaching mainly through game programming (a topic I'm not too interested in) or if this one is a quality book by itself. From bj_666 at gmx.net Tue Jan 8 04:38:50 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 8 Jan 2008 09:38:50 GMT Subject: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> Message-ID: <5ugulaF1hqn2cU1@mid.uni-berlin.de> On Tue, 08 Jan 2008 09:20:16 +0000, Robert Latest wrote: > The program "slow" just writes the numbers 0 through 9 on stdout, one line a > second, and then quits. > > I would have expected the python program to spit out a numbers one by one, > instead I see nothing for 10 seconds and then the whole output all at once. > > How can I get and process the pipe's output at the pace it is generated? Both processes have to make their communication ends unbuffered or line buffered. See the documentation of `os.popen()` for the `bufsize` argument. And do whatever is needed to output the numbers from ``slow`` unbuffered or line buffered. Ciao, Marc 'BlackJack' Rintsch From python.list at tim.thechases.com Wed Jan 16 15:40:07 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 16 Jan 2008 14:40:07 -0600 Subject: Creating unique combinations from lists In-Reply-To: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> Message-ID: <478E6BA7.5030509@tim.thechases.com> > a = ['big', 'small', 'medium']; > b = ['old', 'new']; > c = ['blue', 'green']; > > I want to take those and end up with all of the combinations they > create like the following lists > ['big', 'old', 'blue'] > ['small', 'old', 'blue'] > ['medium', 'old', 'blue'] > ['big', 'old', 'green'] > ['small', 'old', 'green'] > ['medium', 'small', 'green'] > ['big', 'new', 'blue'] > ['small', 'new', 'blue'] > ['medium', 'new', 'blue'] > ['big', 'new', 'green'] > ['small', 'new', 'green'] > ['medium', 'new', 'green' ] > > I could do nested for ... in loops, but was looking for a Pythonic way > to do this. Ideas? You can use a recursive generator: def iterall(*iterables): if iterables: for head in iterables[0]: for remainder in iterall(*iterables[1:]): yield [head] + remainder else: yield [] for thing in iterall( ['big', 'medium', 'small'], ['old', 'new'], ['blue', 'green'], ): print thing The two for-loops plus recursion should handle any number of parameters, so if you were so inclined, you could do for thing in iterall( ['big', 'medium', 'small'], ['old', 'new'], ['blue', 'green'], ['smelly', 'fragrant'], ['spatula', 'avocado'], ): print thing and get all 3*2*2*2*2 items. Or count in binary: for i, bitstream in enumerate(iterall( [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], )): print ''.join(map(str, bitstream)), '=', i When you're iterating over combinations of items in groups of lists, I prefer the clarity of this over something like [(a,b,c,d,e) for a in [0,1] for b in [0,1] for c in [0,1] for d in [0,1] for e in [0,1]] -tkc From nagle at animats.com Sat Jan 26 12:28:04 2008 From: nagle at animats.com (John Nagle) Date: Sat, 26 Jan 2008 09:28:04 -0800 Subject: Portably killing/signalling another process not supported? Message-ID: <479b6c58$0$36354$742ec2ed@news.sonic.net> There doesn't seem to be any way to portably kill another process in Python. "os.kill" is Mac/Unix only. The "signal" module only lets you send signals to the current process. And the "subprocess" module doesn't have a "kill" function. Subprocess objects really should have a portable "interrupt" or "kill" function. They already have "poll" and "wait", which have to be implemented differently for different systems; that's the logical place for "kill". Yes, there are nonportable workarounds (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462) but no portable solution. John Nagle From lefevrol at yahoo.com Mon Jan 28 14:35:07 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Mon, 28 Jan 2008 20:35:07 +0100 Subject: read and readline hanging In-Reply-To: <9caacced-0f60-4552-b750-c6684acde062@d21g2000prg.googlegroups.com> References: <9caacced-0f60-4552-b750-c6684acde062@d21g2000prg.googlegroups.com> Message-ID: pexpect looks promising, thanks. -- O.L. From steve at REMOVE-THIS-cybersource.com.au Tue Jan 1 09:45:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 01 Jan 2008 14:45:58 -0000 Subject: ElementTree should parse string and file in the same way References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> <5tuqfaF1f8u9tU1@mid.uni-berlin.de> Message-ID: <13nkkh6almg8o6b@corp.supernews.com> On Tue, 01 Jan 2008 13:36:57 +0100, Diez B. Roggisch wrote: > And codemonkeys know that in python > > doc = et.parse(StringIO(string)) > > is just one import away Yes, but to play devil's advocate for a moment, doc = et.parse(string_or_file) would be even simpler. Is there any reason why it should not behave that way? It could be as simple as adding a couple of lines to the parse method: if isinstance(arg, str): import StringIO arg = StringIO(arg) I'm not saying it *should*, I'm asking if there's a reason it *shouldn't*. "I find it aesthetically distasteful" would be a perfectly acceptable answer -- not one I would agree with, but I could accept it. -- Steven From jarausch at skynet.be Mon Jan 21 12:25:06 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 21 Jan 2008 18:25:06 +0100 Subject: ctypes CDLL - which paths are searched? Message-ID: <4794d573$0$2980$ba620e4c@news.skynet.be> Hi, how can I specify the paths to be searched for a dynamic library to be loaded by ctypes' CDLL class on a Linux system. Do I have to set os.environment['LD_LIBRARY_PATH'] ? Many thanks for a hint, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From lists at cheimes.de Sat Jan 19 11:48:40 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 19 Jan 2008 17:48:40 +0100 Subject: What is a shortcut to the Default home directory in Windows In-Reply-To: <4791A092.7090704@timgolden.me.uk> References: <1f85750e-a85a-4bb5-8f20-cbb5939f89a3@p69g2000hsa.googlegroups.com> <1fddf38d-e6a2-416f-a8f8-020560970ab5@z17g2000hsg.googlegroups.com> <4791A092.7090704@timgolden.me.uk> Message-ID: Tim Golden wrote: > Umm... Is it not? The only thing I'm aware of doing is > retaining backwards compat. by using SHGetPathFromIDList > on the SHGetSpecialFolderLocation because I was writing against > Win9x at the time. Or are you saying something else? > > (Admit I haven't checked all the docs since I wrote it > to see what's been "deprecated" this week). A lot has been deprecated :( MS has deprecated all functions which are using CSIDL and introduced a new stack for Vista. Christian From software at ginstrom.com Thu Jan 10 04:55:17 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Thu, 10 Jan 2008 18:55:17 +0900 Subject: Win32com and Excel In-Reply-To: <096bc326-3c91-4287-817f-79994a8c507d@k39g2000hsf.googlegroups.com> References: <096bc326-3c91-4287-817f-79994a8c507d@k39g2000hsf.googlegroups.com> Message-ID: <013c01c8536e$e8181720$030ba8c0@MOUSE> > On Behalf Of Mike P > Does anyone have any code that does something similar? My > guess is i have to do something like thefollowing to enable > python to read xl? I think that what you want is UsedRange for row in sheet.UsedRange.Value: ... Regards, Ryan Ginstrom From gandalf at shopzeus.com Sun Jan 13 05:29:23 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Sun, 13 Jan 2008 11:29:23 +0100 Subject: ftplib question (cannot open data connection) In-Reply-To: <13ofegohhiu4uc9@corp.supernews.com> References: <13ofegohhiu4uc9@corp.supernews.com> Message-ID: <4789E803.8050604@shopzeus.com> > BUT: active FTP does not just send the data to the port that was in > the random port that was sent to the server... it addresses to the port > you sent, but it sends its data response FROM port 20. This means the > response looks like a totally unsolicited connection attempt from the > outside -- the firewall doesn't even have enough information to > determine which machine (if multiple) inside the firewall should be > receiving the data; since the server is sending the data stream on its > port 20 and there is no active connection for server:20 to ANY > client:???? Yes, I know. But it DOES work from inside my NAT network. I have no clue how. I'm sure that it is using active connections because this server cannot use passive mode. It might be a very clever firewall that does packet sniffing for "ftp PORT" commands. (?) Anyway, the problem is not with this computer, it was a counter-example. > Even if you could tell the firewall to let in connections on > the specified port, the NAT tables won't know what inside IP to > translate the inbound server port 20... > It does not need to. I can reconfigure the firewall to directly forward all incoming TCP connections from a specified port range to a given IP inside the internal network. But I do not even need to do that. The problem is with a computer that is NOT behind NAT. It is a single computer connected directly to the internet, but it has a firewall installed. So everything would be fine except one thing: I should tell ftplib which port(s) to open, and open those ports on my firewall. For example, I can open TCP ports between 50000 and 60000, and then tell ftplib to use ports between 50000 and 60000 in PORT and EPRT commands. How can I do that? If that is not possible, then what is the workaround? (Definitely I do not want to turn off the firewall completely on a production server.) > Passive mode turns this around. Yep, but this ftp server cannot use passive mode and I cannot change this. And finally, if this cannot be done in ftplib, then I would like to suggest to add this method to Ftp objects. :-) Best, Laszlo From ian at neustyle.com Sun Jan 6 02:21:54 2008 From: ian at neustyle.com (ian at neustyle.com) Date: Sat, 5 Jan 2008 23:21:54 -0800 (PST) Subject: list property fires get on append Message-ID: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com> I've created a class that has a property which points at a private list. When I try to use the append() function on this list property, the fget method is fired rather than the fset method. If I directly set my property to a literal list, the set method fires. Here's a stripped down version of my code: class Hierarchy(object): _children = [] def __init__(self): return def get_children(self): print("GETTING") return self._children def set_children(self, value): print("SETTING") self._children = value children = property(get_children, set_children) -----USAGE------ import Hierarchy hierarchy = Hierarchy.Hierarchy() # this fires a get for some reason hierarchy.children.append( Hierarchy.Hierarchy()) # this fires a set as expected hierarchy.children = [Hierarchy.Hierarchy()] ------RESULT------ it prints: GETTING SETTING From http Thu Jan 31 18:09:03 2008 From: http (Paul Rubin) Date: 31 Jan 2008 15:09:03 -0800 Subject: How to identify which numbers in a list are within each others' range References: <6b4ac79b-6267-438d-8b28-aa4bba78a586@i3g2000hsf.googlegroups.com> Message-ID: <7xzlula8z4.fsf@ruckus.brouhaha.com> "attn.steven.kuo at gmail.com" writes: > mysets = [set(range(x[2],x[1])) for x in mylist] This is pretty horrible, each set can be arbitrarily large, i.e. if x[2] and x[1] are 0 and 1000000, you get a set with a million elements. From http Fri Jan 11 18:26:42 2008 From: http (Paul Rubin) Date: 11 Jan 2008 15:26:42 -0800 Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> Message-ID: <7xsl147xl9.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > This function just wants X out of the list. It doesn't matter if this > happens before, during, or after something else; so long as it happens. If you're asking in a general way how to do something like that, there are several basic methods: 1. Put a single thread in charge of the list, and communicate with it by message passing through Queues. To get X out of the list, you'd send the mutator thread a message asking for removal. The mutator thread would loop reading and processing messages from the queue, blocking when no requests are pending. This is sort of the preferred Python style and is pretty simple to get correct, but if there are many such objects you can end up with more threads than you really want. 2. Associate a lock with the list. Anything wanting to access the list should acquire the lock, do its stuff, then release the lock. This gets confusing after a while. 3. Various other schemes involving finer grained locks etc. that get horrendously error prone (race conditions etc). There is probably a good tutorial somewhere about programming with threads. It's sometimes a tricky subject, so it's worth taking the time to study various approaches rather than re-inventing the wheeel. From vedrandekovic at gmail.com Wed Jan 2 06:43:23 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Wed, 2 Jan 2008 03:43:23 -0800 (PST) Subject: wxpython application ( problem ? ) References: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> <5u1asvF1fgr5bU2@mid.uni-berlin.de> Message-ID: <7cb975f6-e9a6-4527-bd84-2041aede197f@j20g2000hsi.googlegroups.com> On 2 sij, 12:29, Marc 'BlackJack' Rintsch wrote: > On Wed, 02 Jan 2008 03:24:56 -0800, vedrandekovic wrote: > > Here is sample of my simple script with wxpython and modules: > > subprocess,threading, directpython....... > > Are you accessing the GUI from threads? > > Ciao, > Marc 'BlackJack' Rintsch Hi again, yes, so what's the problem? Regards, Vedran From chiendarret at yahoo.com Mon Jan 7 01:49:47 2008 From: chiendarret at yahoo.com (Francesco Pietra) Date: Sun, 6 Jan 2008 22:49:47 -0800 (PST) Subject: Delete lines containing a specific word In-Reply-To: Message-ID: <281534.89912.qm@web57616.mail.re1.yahoo.com> --- Steven D'Aprano wrote: > On Sun, 06 Jan 2008 13:33:52 -0800, Francesco Pietra wrote: > > > Steven: > > Thanks. See below please (of very marginal interest) > > > > --- Steven D'Aprano wrote: > > > >> On Sun, 06 Jan 2008 09:21:33 -0800, Francesco Pietra wrote: > >> > >> > Please, how to adapt the following script (to delete blank lines) to > >> > delete lines containing a specific word, or words? > >> > >> That's tricky, because deleting lines from a file isn't a simple > >> operation. No operating system I know of (Windows, Linux, OS X) has a > >> "delete line" function. > > > > As I am at Debian Linux, I do that with grep -v > > grep doesn't delete lines. grep matches lines. If you want to delete > them, you still have to do the rest of the job yourself. Well, I use Debian Linux for scientific purposes, so that I have no much time toget expertise even in the OS. Though, from the command (as user) grep -v theword thefile.pdb I get thefile.pdb without the lines containing "theword". > > > >> Secondly, you might want the script to write its output to a file, > >> instead of printing. So, instead of the line "print line", you want it > >> to write to a file. > > > > may be cumbersome, though I use 2>&1 | tee output file.pdb so that I > > can see what happens on the screen and have the modified file. > > Yes, matching lines and sending them to stdout is a better solution than > trying to delete them from a file. > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From mr.cerutti at gmail.com Wed Jan 16 07:21:07 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 16 Jan 2008 07:21:07 -0500 Subject: no pass-values calling? In-Reply-To: <18c1e5f20801151909u4cdd227ah685741ea21734491@mail.gmail.com> References: <18c1e5f20801151909u4cdd227ah685741ea21734491@mail.gmail.com> Message-ID: <51302a8c0801160421i1a9db1aala222b847d4e01f3a@mail.gmail.com> On Jan 15, 2008 10:09 PM, J. Peng wrote: > Hello, > > I saw this statement in Core Python Programming book, > > All arguments of function calls are made by reference, meaning that > any changes to these parameters within the function > affect the original objects in the calling function. Yes, that's generally correct. But you must be careful about what is meant by "changes to parameters". Assigning a new value to a parameter name (inside the function, a parameter is just a local variable) does not change the original object--it only rebinds the local variable to a new object. In the following function, a is rebound with an assignment statement, while b is mutated, i.e., changed, with an assignment statement. def f(a, b): a = 12 b.value = 14 Argument a will never be changed, while argument b will be. Python's argument passing semantics are extremely simple. It's the assignment statement that's tricky: some assignments mutate/change objects, and some only rebind names. > Does this mean there is not pass-values calling to a function in > python? only pass-reference calling? Thanks! Neither is quite true. Values are passed by binding parameter names to their corresponding arguments. This is similar to pass-by-reference in some cases (when the argument is mutated) but not in others (when the argument is not mutated). Thinking of it as pass-by-reference may help you to understand it, but bear in mind that Python's "references" may be rebound to new objects, which is quite different from the usual behavior of references. -- Neil Cerutti From kyosohma at gmail.com Mon Jan 28 13:42:02 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 28 Jan 2008 10:42:02 -0800 (PST) Subject: Question on importing wxPython References: Message-ID: <3d81547e-7d9e-47a1-9b82-b571c20646fa@i72g2000hsd.googlegroups.com> On Jan 28, 12:06 pm, "Steven W. Orr" wrote: > python-2.3.5 > wx-2.6 > > I just bought the wxPython In Action book and I see that all the examples > say to > import wx > All of our pre-existing code was horribly doing a > from wxPython import * > > I changed all the code so that it was doing an import wx and found that > everything was broken. In particular, references to wxNewId would fail. > > 634 > python > Python 2.3.5 (#2, May 4 2005, 08:51:39) > [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> import wx > >>> wx.wxNewId > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'wxNewId' > > > > In fact, the *only* way to get it was to go back to > import wxPython > and then refer to it as wxPython.wx.wxNewId > > Is my system broken or am I missing something? i.e., should I be able to > say import wx? > > TIA > > -- > Time flies like the wind. Fruit flies like a banana. Stranger things have .0. > happened but none stranger than this. Does your driver's license say Organ ..0 > Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 > individuals! What if this weren't a hypothetical question? > steveo at syslang.net I think the issue is that you are using the old style of wxPython. The new style is wx.Something, so in this case, you want wx.NewId(). See sample code below: import wx new_id = wx.NewId() This helps the developer know what library that function comes from. I see you are using 2.6. Just so you know, 2.8 is out now...you may want to upgrade. Also, there's a really nice wxPython community mailing list you can join, which you'll find here: http://wxpython.org/maillist.php Mike From fredrik at pythonware.com Fri Jan 4 13:30:43 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 19:30:43 +0100 Subject: Simple calculation error In-Reply-To: <3CDC4613E97B134A9A7E61A5E43DCA55010FDE36@fr-mail1.fr.kyriba.com> References: <3CDC4613E97B134A9A7E61A5E43DCA55010FDE36@fr-mail1.fr.kyriba.com> Message-ID: Francois Liot wrote: > > I observed a strange calculation answer, on both python 2.3.4 and 2.4.4 > >> >> print 753343.44 - 753361.89 > > -18.4500000001 > >> >> print ( (753361.89*100) - (753343.44*100) ) / 100 > > 18.45 > > Can somebody help me to play correctly with decimal values? A 64-bit binary floating point number can hold values between -1e308 and +1e308, in only 64 bits of memory. Since 1e308 is a *lot* larger than float(2**64) = ~1.8e19, it does this by splitting the number in a binary fraction, and a multiplier (stored as an exponent). Unfortunately, very few decimal fractions can be *exactly* represented as binary fractions, so you often get representation errors: http://docs.python.org/tut/node16.html This is usually not much of a problem, since you usually end up rounding things to a suitable number of decimals or significant digits when you print them anyway (see below), but repr() doesn't do that -- it always outputs enough digits to get back the *exact* binary representation if you convert the string back to a floating point value again. In practice, you can usually ignore this; just use the appropriate output methods, and things will just work: While pathological cases do exist, for most casual use of floating-point arithmetic you'll see the result you expect in the end if you simply round the display of your final results to the number of decimal digits you expect. str() usually suffices, and for finer control see the discussion of Python's % format operator: the %g, %f and %e format codes supply flexible and easy ways to round float results for display. (from the above link) If you really need full control over this, no matter what, use the Decimal type, as provided by the decimal module in the standard library. See the library reference for the full story. From fabiofz at gmail.com Tue Jan 29 05:54:21 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 29 Jan 2008 08:54:21 -0200 Subject: Pydev 1.3.12 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.12 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: ----------------------------------------------------------------- * Mark occurrences: only requested on mouse-clicks and cursor changes. * Code-Analysis: No longer running in UI-Thread (bug which slowed things down in 1.3.10 and 1.3.11). * Code-Analysis: Cache optimizations. * Code-Analysis: Fixed 'statement without effect' when raising exception with arguments without using the exception constructor. * Code-Analysis: Fixed 'statement without effect' on tuple creation. * Code-Analysis: __path__ found for packages (__init__.py files). * Context-insensitive info: Correctly updated when code-analysis is off (or if file is not analyzed). Release Highlights in Pydev: ---------------------------------------------- * Code Coverage: coverage.py updated to version 2.78 (http://nedbatchelder.com/code/modules/coverage.html). * Optimization: Caches (with no memory overhead) added for a number of situations, which can speed completion requests a lot (up to 40x on tests). 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 lists at cheimes.de Sun Jan 6 11:13:58 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 06 Jan 2008 17:13:58 +0100 Subject: Cost of "unicode(s)" where s is Unicode In-Reply-To: <4780fb68$0$36341$742ec2ed@news.sonic.net> References: <4780fb68$0$36341$742ec2ed@news.sonic.net> Message-ID: <4780FE46.1070101@cheimes.de> John Nagle wrote: > Does > > text = unicode(text) > > make a copy of a Unicode string, or is that essentially a > free operation if the input is already Unicode? >>> u = u"some long unicode object" >>> unicode(u) is u True From kw at codebykevin.com Mon Jan 7 18:30:32 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 07 Jan 2008 18:30:32 -0500 Subject: Does PIL work with Tk 8.5? In-Reply-To: <4782B244.7010706@codebykevin.com> References: <2870$4782a5c4$4275d90a$673@FUSE.NET> <4782B074.8080709@v.loewis.de> <4782B244.7010706@codebykevin.com> Message-ID: <6b9d3$4782b618$4275d90a$4415@FUSE.NET> Kevin Walzer wrote: > > Tk itself has a stubs mechanism that allows libraries compiled against > earlier versions to be used with later versions. It's different than > Python in this respect. A pure-Tk library (such as Img or TkPNG) built > against Tk 8.4 would not require re-compilation to be used with 8.5. > Since PIL is a Python library, however, you may be right. > Indeed, this appears to be the problem. I tested my script against the Python bundled with Mac OS X, which links against 8.4, and it worked fine. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From jarausch at skynet.be Tue Jan 15 09:55:23 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 15 Jan 2008 15:55:23 +0100 Subject: common problem - elegant solution sought In-Reply-To: References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <478cc95b$0$29247$ba620e4c@news.skynet.be> Neil Cerutti wrote: > On Jan 15, 2008 5:33 AM, Helmut Jarausch wrote: >> Hi, >> >> I'm looking for an elegant solution of the following tiny but common problem. >> >> I have a list of tuples (Unique_ID,Date) both of which are strings. >> I want to delete the tuple (element) with a given Unique_ID, but >> I don't known the corresponding Date. >> >> My straight forward solution is a bit lengthy, e.g. >> >> L=[("a","070501"),("b","080115"),("c","071231")] > > If the data is truly sorted by Unique_ID, then binary search may be > feasible (though not actually recommended for such small list). > > import bisect > > i = bisect.bisect_left(L, ('b', '000000')) > if i[0] == 'b': > del L[i] > Thanks, unfortunately, they are sorted on 'Date' Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From bignose+hates-spam at benfinney.id.au Wed Jan 2 08:47:58 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 03 Jan 2008 00:47:58 +1100 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au> <87bq85rp2d.fsf@physik.rwth-aachen.de> <87abnoc13h.fsf@benfinney.id.au> Message-ID: <8763ycbapd.fsf@benfinney.id.au> Steven D'Aprano writes: > On Wed, 02 Jan 2008 15:17:54 +1100, Ben Finney wrote: > > > Torsten Bronger writes: > > > >> [...] the width of a tab is nowhere defined. It really is a matter of > >> the editor's settings. > > > > RFC 678 "Standard File Formats" > > : > > Dated 19 December 1974. So? The point is made: it's not true to say "the width of a tab is nowhere defined". Everything I can find that is in any way close to a "standard" defines the canonical width of an ASCII TAB as being eight columns. At least that one also acknowledges what we all know: that (even in those times) actually enforcing that canonical width is difficult. > I think it tells a lot about the spaces-only argument that it is > based on the state of the art thirty years ago I think it says a lot about this thread that you've devolved to taking a side point I raise merely to disprove a distracting fallacy, and claim that my core argument "is based on" it. It says, at least, that it's time for me to stop contributing to this thread, as it won't improve from here. My argument is made, earlier in this thread, utterly unrelated to this "width of a TAB" point, and it remains whether it convinces anyone who contributed or not. -- \ "Don't worry about people stealing your ideas. If your ideas | `\ are any good, you'll have to ram them down people's throats." | _o__) -- Howard Aiken | Ben Finney From bignose+hates-spam at benfinney.id.au Mon Jan 7 04:05:24 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 07 Jan 2008 20:05:24 +1100 Subject: do - loop References: Message-ID: <87zlvim2ej.fsf@benfinney.id.au> Hita Vora writes: > I have a dataset which has about 3000 subjects in it. I take each > subject and perform 3 to 4 geoprocessing tasks on it. Currently I > have a model where I manually feed in each subject's ID and then the > rest of the process is automated. I would like to automate the > process such that it would automatically select another subject > after the process has been completed on a specfic subject. ie to > repeat the same process on each of the IDs. def do_the_stuff(subject): """ Do the stuff to a single subject """ pass for this_subject in all_subjects: do_the_stuff(this_subject) -- \ "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 fredrik at pythonware.com Sun Jan 13 07:44:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 13 Jan 2008 13:44:58 +0100 Subject: __init__ explanation please In-Reply-To: <47895d25$0$30708$4c368faf@roadrunner.com> References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: Erik Lind wrote: > I'm new to Python, and OOP. I've read most of Mark Lutz's book and more > online and can write simple modules, but I still don't get when __init__ > needs to be used as opposed to creating a class instance by assignment. nothing is ever created by plain assignment in Python; to create a class instance in Python, you *call* the class object. an example: class MyClass: pass # create three separate instances obj1 = MyClass() obj2 = MyClass() obj3 = MyClass() (it's the () that creates the object, not the =) if you want to initialize the method's state (that is, set some attributes), you can do that from the outside: obj1.attrib = "some value" or in an "initialization" method in the class: class MyClass: def init(self): self.attrib = "some value" obj1 = MyClass() obj1.init() but in both cases, you'll end up with an inconsistent object state (in this case, no attribute named "attrib") if you forget to do this. obj1 = MyClass() print obj1.attrib # this will fail to avoid such mistakes, you can use __init__ instead. this is just a initialization method that's automatically called by Python *after* the object is created, but *before* the call to the class object returns. class MyClass: def __init__(self): self.attrib = "some value" obj1 = MyClass() print obj1.attrib # this will succeed also, any arguments that you pass to the class object call are passed on to the initialization method. class MyClass: def __init__(self, value): self.attrib = value obj1 = MyClass("hello") print obj1.attrib # prints "hello" as Jeroen points out, this is pretty much the same thing as a constructor in other languages -- that is, a piece of code that's responsible for setting up an object's state. Python's a bit different; the object is in fact created before the call to __init__, but this doesn't matter much in practice; if construction fails, the assignment will fail, so the object will be lost, and is reclaimed by the GC later on. (unless you explicitly store a reference to the object somewhere else, of course: >>> class MyClass: ... def __init__(self): ... global secret ... secret = self ... raise ValueError("oops! failed!") ... def method(self): ... print "here I am!" ... >>> obj = MyClass() Traceback (most recent call last): File "", line 1, in File "", line 5, in __init__ ValueError: oops! failed! >>> obj Traceback (most recent call last): File "", line 1, in NameError: name 'obj' is not defined >>> secret.method() here I am! ) finally, if you want full control also over the actual creation of the object, more recent Python versions support a __new__ method that can be used instead of __init__, or as a complement. but that's an advanced topic, and is nothing you need to worry about while trying to the hang of class basics. hope this helps! From stargaming at gmail.com Mon Jan 7 18:40:28 2008 From: stargaming at gmail.com (Stargaming) Date: 07 Jan 2008 23:40:28 GMT Subject: How to refer to the current module? References: Message-ID: <4782b86c$0$12421$9b622d9e@news.freenet.de> On Mon, 07 Jan 2008 05:21:42 -0800, Mike wrote: > I want to do something like the following (let's pretend that this is in > file 'driver.py'): > > #!/bin/env python > > import sys > > def foo(): > print 'foo' > > def bar(arg): > print 'bar with %r' % arg > > def main(): > getattr(driver, sys.argv[1])(*sys.argv[2:]) > > if __name__=='__main__': > main() > > > Essentially what I'm trying to get at here is dynamic function > redirection, like a generic dispatch script. I could call this as > > python driver.py foo > > or > > python driver.py bar 15 > > and at any time later I can add new functions to driver.py without > having to update a dispatch dict or what-have-you. > > The problem is, 'driver' doesn't exist in main() line 1. If I 'import > driver' from the command line, then getattr(driver, ...) works, but it's > not bound here. > > Is there any way around this? Can I somehow scope the 'current module' > and give getattr(...) an object that will (at run time) have the > appropriate bindings? > > Thanks in advance for all advice! > > Mike `__main__` (after you did ``import __main__``) could be an option as well. But I'd prefer a custom dictionary for your dispatch, rather than some magic with the module's names. See http://docs.python.org/ref/programs.html for details on __main__. From aisaac at american.edu Fri Jan 25 17:30:30 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 25 Jan 2008 22:30:30 GMT Subject: find minimum associated values In-Reply-To: References: <7xd4rpznl0.fsf@ruckus.brouhaha.com> Message-ID: Alan Isaac wrote: > #sort by id and then value > kv_sorted = sorted(kv, key=lambda x: (id(x[0]),x[1])) > #groupby: first element in each group is object and its min value > d =dict( g.next() for k,g in groupby( kv_sorted, key=lambda x: x[0] ) ) > > Yes, that appears to be fastest and is > pretty easy to read. On average. For the specified problem. ;-) From sjmachin at lexicon.net Thu Jan 3 18:02:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 3 Jan 2008 15:02:46 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> <76ba16c8-6ba0-4609-80bd-cd54aa08d74b@5g2000hsg.googlegroups.com> Message-ID: <590e6f12-16ad-4919-a87d-a2f2cc0b3516@t1g2000pra.googlegroups.com> On Jan 4, 8:03 am, mario wrote: > On Jan 2, 2:25 pm, Piet van Oostrum wrote: > > > Apparently for the empty string the encoding is irrelevant as it will not > > be used. I guess there is an early check for this special case in the code. > > In the module I an working on [*] I am remembering a failed encoding > to allow me, if necessary, to later re-process fewer encodings. If you were in fact doing that, you would not have had a problem. What you appear to have been doing is (a) remembering a NON-failing encoding, and assuming that it would continue not to fail (b) not differentiating between failure reasons (codec doesn't exist, input not consistent with specified encoding). A good strategy when dealing with encodings that are unknown (in the sense that they come from user input, or a list of encodings you got out of the manual, or are constructed on the fly (e.g. encoding = 'cp' + str(code_page_number) # old MS Excel files)) is to try to decode some vanilla ASCII alphabetic text, so that you can give an immemdiate in-context error message. > In the > case of an empty string AND an unknown encoding this strategy > failed... > > Anyhow, the question is, should the behaviour be the same for these > operations, and if so what should it be: > > u"".encode("non-existent") > unicode("", "non-existent") Perhaps you should make TWO comparisons: (1) unistrg = strg.decode(encoding) with unistrg = unicode(strg, encoding) [the latter "optimises" the case where strg is ''; the former can't because its output may be '', not u'', depending on the encoding, so ut must do the lookup] (2) unistrg = strg.decode(encoding) with strg = unistrg.encode(encoding) [both always do the lookup] In any case, a pointless question (IMHO); the behaviour is extremely unlikely to change, as the chance of breaking existing code outvotes any desire to clean up a minor inconsistency that is easily worked around. From http Mon Jan 21 15:56:14 2008 From: http (Paul Rubin) Date: 21 Jan 2008 12:56:14 -0800 Subject: index of min element of sequence References: <7xfxwrt1dx.fsf@ruckus.brouhaha.com> <6243b2e3-e2eb-41fb-bb7c-88b40ffcef60@e25g2000prg.googlegroups.com> Message-ID: <7xabmyyk29.fsf@ruckus.brouhaha.com> John Machin writes: > s/[1]/[0]/ or more generally: Oops, got two spellings confused. Originally was going to use from itertools import count, izip min(izip(seq, count()))[1] but did it with enumerate instead. I don't know which is actually faster. > minindex, minvalue = min(enumerate(seq), key=itemgetter(1)) Cool, I like this best of all. Or alternatively, minindex, minvalue = min(izip(seq, count())) From jazle at localhost.com Wed Jan 16 19:53:25 2008 From: jazle at localhost.com (Jaimy Azle) Date: Thu, 17 Jan 2008 07:53:25 +0700 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> <60b75f24-d33a-476e-932d-11dfb9880562@v4g2000hsf.googlegroups.com> Message-ID: "Paul Boddie" wrote: > I think the benefits of running Java on CPython are significantly less > than those had by running Python on the Java VM (or another VM). > Firstly, who wants to write statically typed code which then runs on a > virtual machine that can't take advantage of the type declarations? > Secondly, isn't it just better to use a virtual machine with just-in- > time compilation and all sorts of security mechanisms if you're > wanting to write the Java code that, when compiled, can take advantage > of all that stuff? In other words: what makes CPython a compelling VM > for the Java programmer? I agree, that's why i expecting nobody willing to. But despite of that, at least what you've done is a proof-of-concept that java byte-code could also be executed by python. Salam, -Jaimy. From bearophileHUGS at lycos.com Thu Jan 24 12:55:46 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 24 Jan 2008 09:55:46 -0800 (PST) Subject: Duplicating a variable References: Message-ID: <1f5684fd-d8e6-4429-953f-b57362eeb4d1@s19g2000prg.googlegroups.com> Hans: > I have run into a bit of a subtle problem. How do I go about > duplicating a variable (particularly a list of lists) in python. I > was surprised when simple assignment didn't work. Python is quite high-level language, but now and then it too accepts some compromises to increase its speed/size performance. Probably after Python someone will invent a language that may be slower than Python because it's higher level than Python, and avoids that problem you talk about (and other things). (And with a strategy of smart data sharing and copy-on-write the interpreter can avoid part of that overhead). > how do I go about duplicating a variable > which I can then manipulate independently? If your variable contains a list, then you can copy it like this: >>> l1 = [1, 2, 3] >>> l2 = l1[:] >>> l2[1] = 4 As you can see now they are two distinct lists: >>> l1 [1, 2, 3] >>> l2 [1, 4, 3] If you want to copy any kind of object you can use the copy function (instead of a simpler copy method that's absent): >>> d1 = {1:2, 3:4} >>> from copy import copy >>> d2 = copy(d1) >>> d1[1] = 5 >>> d1 {1: 5, 3: 4} >>> d2 {1: 2, 3: 4} But as you can see copy works only one level deep: >>> d3 = {1:[1], 3:4} >>> d3 {1: [1], 3: 4} >>> d4 = copy(d3) >>> d3[1][0] = 2 >>> d3 {1: [2], 3: 4} >>> d4 {1: [2], 3: 4} To copy all levels you need deepcopy: >>> from copy import deepcopy >>> d5 = deepcopy(d3) >>> d3[1][0] = 5 >>> d3 {1: [5], 3: 4} >>> d4 {1: [5], 3: 4} >>> d5 {1: [2], 3: 4} Bye, bearophile From lasses_weil at klapptsowieso.net Mon Jan 14 14:41:27 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 14 Jan 2008 20:41:27 +0100 Subject: bags? 2.5.x? In-Reply-To: References: Message-ID: <478bbae6$0$25383$9b4e6d93@newsspool4.arcor-online.net> Dan Stromberg wrote: > Is there a particular reason why bags didn't go into 2.5.x or 3000? > > I keep wanting something like them - especially bags with something akin > to set union, intersection and difference. > How about this recepie ? /W From colinlandrum at gmail.com Tue Jan 1 18:32:17 2008 From: colinlandrum at gmail.com (hubritic) Date: Tue, 1 Jan 2008 15:32:17 -0800 (PST) Subject: pyparsing question Message-ID: <8df809a0-1950-4250-a968-2d366f64cdb4@d21g2000prf.googlegroups.com> I am trying to parse data that looks like this: IDENTIFIER TIMESTAMP T C RESOURCE_NAME DESCRIPTION 2BFA76F6 1208230607 T S SYSPROC SYSTEM SHUTDOWN BY USER A6D1BD62 1215230807 I H Firmware Event My problem is that sometimes there is a RESOURCE_NAME and sometimes not, so I wind up with "Firmware" as my RESOURCE_NAME and "Event" as my DESCRIPTION. The formating seems to use a set number of spaces. I have tried making RESOURCE_NAME an Optional(Word(alphanums))) and Description OneOrMore(Word(alphas) + LineEnd(). So the question is, how can I avoid having the first word of Description sucked into RESOURCE_NAME when that field should be blank? The data I have has a fixed number of characters per field, so I could split it up that way, but wouldn't that defeat the purpose of using a parser? I am determined to become proficient with pyparsing so I am using it even when it could be considered overkill; thus, it has gone past mere utility now, this is a matter of principle! thanks From arne.k.h at gmail.com Mon Jan 21 15:38:48 2008 From: arne.k.h at gmail.com (Arne) Date: Mon, 21 Jan 2008 12:38:48 -0800 (PST) Subject: Trouble writing to database: RSS-reader References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> <4794e0f9$0$4429$426a74cc@news.free.fr> Message-ID: <739742b0-7d3d-4039-b793-ccefae4be721@1g2000hsl.googlegroups.com> On 21 Jan, 19:15, Bruno Desthuilliers wrote: > This should not prevent you from learning how to properly parse XML > (hint: with an XML parser). XML is *not* a line-oriented format, so you > just can't get nowhere trying to parse it this way. > > HTH Do you think i should use xml.dom.minidom for this? I've never used it, and I don't know how to use it, but I've heard it's useful. So, I shouldn't use this techinicke (probably wrong spelled) trying to parse XML? Should i rather use minidom? Thank you for for answering, I've learnt a lot from both of you, Desthuilliers and Genellina! :) From ptmcg at austin.rr.com Tue Jan 22 09:59:35 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 22 Jan 2008 06:59:35 -0800 (PST) Subject: Problem with processing XML References: <13pbudgks88rcf3@corp.supernews.com> Message-ID: <1839ec4e-045e-4ce2-a3ea-78ed83a8c288@u10g2000prn.googlegroups.com> On Jan 22, 8:11?am, John Carlyle-Clarke wrote: > Hi. > > I'm new to Python and trying to use it to solve a specific problem. ?I > have an XML file in which I need to locate a specific text node and > replace the contents with some other text. ?The text in question is > actually about 70k of base64 encoded data. > Here is a pyparsing hack for your problem. I normally advise against using literal strings like "" to match XML or HTML tags in a parser, since this doesn't cover variations in case, embedded whitespace, or unforeseen attributes, but your example was too simple to haul in the extra machinery of an expression created by pyparsing's makeXMLTags. Also, I don't generally recommend pyparsing for working on XML, since there are so many better and faster XML-specific modules available. But if this does the trick for you for your specific base64-removal task, great. -- Paul # requires pyparsing 1.4.8 or later from pyparsing import makeXMLTags, withAttribute, keepOriginalText, SkipTo xml = """ ... long XML string goes here ... """ # define a filter that will key off of the tag with the # attribute 'name="PctShow.Image"', and then use suppress to filter the # body of the following tag dataTag = makeXMLTags("data")[0] dataTag.setParseAction(withAttribute(name="PctShow.Image"), keepOriginalText) filter = dataTag + "" + SkipTo("").suppress() + "" xmlWithoutBase64Block = filter.transformString(xml) print xmlWithoutBase64Block From george.sakkis at gmail.com Thu Jan 17 19:41:03 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 17 Jan 2008 16:41:03 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> <7xy7aong73.fsf@ruckus.brouhaha.com> Message-ID: <4eba552a-3f9f-4bc7-81e7-150f109013ad@c23g2000hsa.googlegroups.com> On Jan 17, 7:13 pm, Paul Rubin wrote: > George Sakkis writes: > > And if the iterables don't necessarily support len(), here's a more > > general solution: > > Not trying to pick on you personally but there's this disease > when a newbie comes with a basically simple question (in this case, > how to solve the problem with ordinary lists) and gets back a lot > of complex, overly general "graduate level" solutions. Fair enough, although I don't think it's bad to show more general/ efficient/flexible solutions after the simple quick & dirty ones have been shown, as in this thread. My solution is just a step further from Paul Hankin's, not a direct response to the OP. > There's a humorous set of Haskell examples that takes this to extremes: > > http://www.willamette.edu/~fruehr/haskell/evolution.html Hehe.. I remember seeing a similar one for Java and "Hello world" using more and more elaborate abstractions and design patterns but I can't find the link. George From karlheinz.klingbeil at gmx.net Fri Jan 25 08:04:18 2008 From: karlheinz.klingbeil at gmx.net (Karlheinz Klingbeil) Date: Fri, 25 Jan 2008 14:04:18 +0100 Subject: Email module, how to add header to the top of an email? References: <97c04812-3b66-4d84-9e92-21de72a3ca56@c23g2000hsa.googlegroups.com> <088eeaff-8251-49a4-9202-a9481f5e8aaa@x69g2000hsx.googlegroups.com> Message-ID: Am 25.01.2008, 06:21 Uhr, schrieb David Erickson : > Bottom of the headers... but I am looking to insert at the top, and re- > ordering/inserting does matter depending on what type of header you > are, received headers for example must be inserted at the top of the > header list so you can watch the progression of the email. I was > unable to find a clean way to do this via the API which seems very > strange to me.. but perhaps I am just missing something? I think your are really missing something. First, Email-headers are unordered and every relay can, and probably will, rearrange them, add or delete headers. You therefore most definitely should not add any headers which are position-dependent. If you want to track mails somehow, add headers with timestamps. This way you can watch the progression of an email without being dependend on "sorted" headerlines. -- Greetz, lunqual - http://www.lunqual.de http://www.42pixels.de - Bilder http://www.rezeptbuch-pro.de - Software f?r den Destillateur From williampaul28 at yahoo.com Sat Jan 19 10:09:06 2008 From: williampaul28 at yahoo.com (william paul) Date: Sat, 19 Jan 2008 07:09:06 -0800 (PST) Subject: python scripts with IIS Message-ID: <120794.61529.qm@web38414.mail.mud.yahoo.com> Hello: I am trying to configure IIS to work with Python scripts: I've added in the Home Directory/Configuration the .py extention and the path to the python.exe as: c:\Python24\python.exe %S %S The python script has 1 line: print "This is a test for python scripts with IIS" When I launch the file using IE I get the message: CGI Error The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: This is a test for python scripts with IIS How can I remove the CGI error? Thank you William ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -------------- next part -------------- An HTML attachment was scrubbed... URL: From ggpolo at gmail.com Thu Jan 17 14:51:56 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 17 Jan 2008 17:51:56 -0200 Subject: how django discovers changed sources In-Reply-To: <18udndFmKMfgMRLanZ2dnUVZ_rzinZ2d@comcast.com> References: <18udndZmKMfMNhLanZ2dnUVZ_rzinZ2d@comcast.com> <18udndFmKMfgMRLanZ2dnUVZ_rzinZ2d@comcast.com> Message-ID: 2008/1/17, alf : > Jeff wrote: > > That is the behavior of the development server. When you are writing > > your application, you don't want to have to manually restart the > > server every time you change a file. On apache it obviously doesn't > > do that. > > thx for clarification, but still I am curious how it is done under the > hood. it really impressed me ... > -- > http://mail.python.org/mailman/listinfo/python-list > It checks if modification time on registered files have changed since last check -- -- Guilherme H. Polo Goncalves From grante at visi.com Fri Jan 18 11:48:38 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 18 Jan 2008 16:48:38 -0000 Subject: how to resolve Windows pathnames into cygwin ones References: <2ba97fb6-6bef-44aa-937b-2aa9582e4341@e4g2000hsg.googlegroups.com> Message-ID: <13p1m36m9htom5f@corp.supernews.com> On 2008-01-18, apatheticagnostic wrote: > On Jan 18, 11:10 am, "mgier... at gmail.com" wrote: >> I am looking for a function to resolve 'F:/foo/bar' into '/cygdrive/f/ >> foo/bar'. I get the original dirpath from tkFileDialog.askdirectory in >> a Windows form and none of os.path.* functions seem to resolve it to a >> cygwin form. Rather they _append_ it to the current directory, >> resulting at best in a monster '/cygdrive/c/whatever/f/foo/bar'. >> It's all being developed under cygwin currently (so it is a kind of >> mixed environment), but I would like the fix to work correctly in any >> environment. >> >> Thanks, >> Marcin > > Well, you could write it yourself.... > > (assuming path is a string, here's a first go at it...) > def path_into_cygpath(path): > drive, destination = path.split(':') > newpath = '/cygdrive/' + drive.lower() + destination > return newpath Don't forget to convert backslashes into forward slashes. -- Grant Edwards grante Yow! TONY RANDALL! Is YOUR at life a PATIO of FUN?? visi.com From sjmachin at lexicon.net Tue Jan 29 14:00:21 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 29 Jan 2008 11:00:21 -0800 (PST) Subject: Error in parsing XML for following test data References: Message-ID: <082482fe-65b8-4854-b567-30cc4fbc8a24@s13g2000prd.googlegroups.com> On Jan 29, 9:29 pm, abhishek wrote: > Hello group, > > I am having problem parsing following data set from XML. Please > provide hints on how to rectify this problem. You have provided no hints on what your problem is. What output do you want? What have you tried? What output and/or error message(s) did you get? What does "from XML" mean? > > I am using python2.4 version > > this is te test data that i am using -- > > """"""" > 1!!!!!!!!!!!!!!!11 > 2@@@@@@@@@@@@@@@22 [snip] > 33................. > Special Characters > #!/bin/bash > #start TG app > cd $1 > exec ./start-infopsyM.py > > """"""" > > This is really a nasty data set. It looks like (a) easily parseable but totally uninteresting guff followed by (b) the start of a bash script Is this some kind of joke? You are not trying to disassemble it, are you? From ivan.illarionov at gmail.com Wed Jan 30 17:24:48 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 30 Jan 2008 14:24:48 -0800 (PST) Subject: Events in Python References: <2b005569-3dbc-41c1-aebf-8b6fd8d2175e@v46g2000hsv.googlegroups.com> <60carvF1q0a0rU1@mid.individual.net> Message-ID: > Compared to what, did you measure something? As example, instantiation of Model classes in Django (Model.__init__) sends two signals (pre_init and post_init) - they are rarely used in practice - but they make instantiation about two times slower. Yes, I measured that. The creator of Louie (Patrick K. O'Brien) himself seems to use them only as an option that can be enabled/disabled in his projects (e.g. Schevo) - because they are slow. From fredrik at pythonware.com Mon Jan 7 11:17:12 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 17:17:12 +0100 Subject: I'm searching for Python style guidelines In-Reply-To: References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > Here's just one of my questions: > > foo = [ > 'some item, quite long', > 'more items, all demanding there own line as they are not short', > ... > > Where would you put the closing ']'? on a line by itself, indented as your favourite Python editor indents it. From steven at REMOVE.THIS.cybersource.com.au Wed Jan 16 01:30:27 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Jan 2008 06:30:27 -0000 Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> Message-ID: On Wed, 16 Jan 2008 13:59:03 +0800, J. Peng wrote: > Hi, > > How to modify the array passed to the function? I tried something like > this: > >>>> a > [1, 2, 3] >>>> def mytest(x): > ... x=[4,5,6] This line does NOT modify the list [1, 2, 3]. What it does is create a new list, and assign it to the name "x". It doesn't change the existing list. If you have not already done this, you should read this: http://effbot.org/zone/python-objects.htm Consider this function: def test(alist): alist.append(0) # this modifies the existing list alist = [1, 2, 3] # this changes the name "alist" return alist Now try it: oldlist = [10, 9, 8, 7] newlist = test(oldlist) Can you predict what oldlist and newlist will be equal to? oldlist will be [10, 9, 8, 7, 0] and newlist will be [1, 2, 3]. Do you see why? -- Steven From antroy at gmail.com Thu Jan 10 08:00:55 2008 From: antroy at gmail.com (Ant) Date: Thu, 10 Jan 2008 05:00:55 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <8f99cb7e-5664-4ebb-b3fc-dd32124ea5f4@m77g2000hsc.googlegroups.com> On Jan 10, 12:04 pm, "dongie.ag... at gmail.com" wrote: > For the most part, I agree with you, which is why I chose Python in > the first place. I like quick development. Unfortunately, this is > one of those cases where execution time is a factor. Who knows, maybe > someone who's done camera vision with Python will come in and say it's > just the algorithm in the example that needs work (I'm crossing my > fingers that that's the case). It would probably be worth reposting your question with a different subject line. Something along the lines of "Image/Video processing performance in Python", and explaining what you actually want to achieve. "Python too slow?" doesn't give enough information - clearly Python is fast enough for many many tasks, since it is so widely used. It also sounds like a troll - so many people who would actually be able to assist you (such as the PIL, pygame and numpy/scipy communities) may have ignored this thread. Cheers, -- Ant. From yantao at telus.com Tue Jan 1 21:17:17 2008 From: yantao at telus.com (Peter Pei) Date: Wed, 02 Jan 2008 02:17:17 GMT Subject: ElementTree should parse string and file in the same way In-Reply-To: <4778A47B.9020201@web.de> References: <4778A47B.9020201@web.de> Message-ID: To answer something posted deep down... It is fine with me if there are two functions - one to parse a file or file handler and one to parse a string, yet the returned objects should be consistent. From rw at smsnet.pl Fri Jan 11 13:27:33 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 11 Jan 2008 19:27:33 +0100 Subject: Using a proxy with urllib2 References: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> <87ir21o8sj.fsf@merkury.smsnet.pl> <26Ohj.3530$jJ5.1972@newssvr11.news.prodigy.net> Message-ID: <87odbs6wve.fsf@merkury.smsnet.pl> "Jack" writes: > Rob, > > I tried your code snippet and it worked great. I'm just wondering if > getopener( ) call > is lightweight so I can just call it in every call to fetchurl( )? Or I > should try to share > the opener object among fetchurl( ) calls? Creating an opener for every url is rather not reasonable way to go. Sharing is the better approach. In your case you might create e.g. two instances: simple_opener and proxy_opener. Regards, Rob From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 04:00:34 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 10:00:34 +0100 Subject: improving performance of python webserver running python scripts in cgi-bin In-Reply-To: <0842faf5-879b-4f50-bfd8-ce17ea7f9673@d4g2000prg.googlegroups.com> References: <0842faf5-879b-4f50-bfd8-ce17ea7f9673@d4g2000prg.googlegroups.com> Message-ID: <47873026$0$21435$426a74cc@news.free.fr> Dale a ?crit : > I am using a simple python webserver (see code below) to serve up > python scripts located in my cgi-bin directory. > > import BaseHTTPServer > import CGIHTTPServer > class Handler(CGIHTTPServer.CGIHTTPRequestHandler): > cgi_directories = ['/cgi-bin'] > httpd = BaseHTTPServer.HTTPServer(('',8000), Handler) > httpd.serve_forever() > > > This works fine, but now I would like to combine the python scripts > into the server program to eliminate starting the python interpreter > on each script call. I am new to python, and was wondering if there > is a better techique that will be faster. > > Also, can someone reccommend an alternative approach to > httpd.serve_forever(). I would like to perform other python functions > (read a serial port, write to an Ethernet port, write to a file, etc.) > inside the web server program above. Is there an example of how to > modify the code for an event loop style of operation where the program > mostly performs my python I/O functions until an HTTP request comes > in, and then it breaks out of the I/O operations to handle the HTTP > request. > May I suggest that you take a look at more sophisticated solutions, like either wsgi, CherryPy or Twisted ? From fredrik at pythonware.com Wed Jan 2 09:39:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 02 Jan 2008 15:39:11 +0100 Subject: PyCairo, PIL and StringIO In-Reply-To: <366566.9612.qm@web52211.mail.re2.yahoo.com> References: <366566.9612.qm@web52211.mail.re2.yahoo.com> Message-ID: Jair Trejo wrote: > I'm doing some image processing in PIL, and I want to > display the results in a GTK window using PyCairo, so > I create a Cairo image surface from the PIL Image like > this: > data > mfile = StringIO.StringIO() > final.save(mfile, format="PNG") > ima = > cairo.ImageSurface.create_from_png(mfile) > mfile.close() > return ima > > Where final is a PIL image. The problem is, I get a > IOError: error while reading from Input Stream. > > ?Any idea of why is this happening? "save" leaves the file pointer at an undefined position (usually at the end), so my guess is that you have to rewind the file before you pass it to the next function: final.save(mfile, format="PNG") mfile.seek(0) # rewind also note that compressing and decompressing will introduce unnecessary overhead; chances are that you might get a lot better performance if you just shuffle the raw pixels. I haven't used PyCairo myself, but from a quick look at the ImageSurface documentation, something like this should work (untested): if final.mode != "RGB": final = final.convert("RGB") w, h = final.size data = final.tostring() # get packed RGB buffer ima = cairo.ImageSurface.create(data, FORMAT_RGB24, w, h, w*3) (tweak as necessary) From sigpoggy at hotmail.com Sat Jan 26 14:30:02 2008 From: sigpoggy at hotmail.com (sigpoggy at hotmail.com) Date: Sat, 26 Jan 2008 11:30:02 -0800 (PST) Subject: wx.EVT_RIGHT_UP strangeness? Message-ID: I am playing with wxPython 2.8.7.1 on OS X 10.4.11 with MacPython 2.5 When running the demo program, the ShapeWindow demo does not close the window on right click. It turns out that the wx.EVT_RIGHT_UP does not fire. I discovered that one way to get it to fire is to bind the wx.EVT_RIGHT_DOWN event also. Thus adding the following two lines solves the problem: in __init__ add: self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) secondly add: def OnRightDown(self, evt): pass Everything then works ok. My question is: Is this how it is supposed to work, and if not, am I the only one with this problem? From JO3chiang at gmail.com Mon Jan 7 22:26:47 2008 From: JO3chiang at gmail.com (jo3c) Date: Mon, 7 Jan 2008 19:26:47 -0800 (PST) Subject: linecache and glob References: <0e16ca26-9e34-4f97-83de-9ddc3693d085@i12g2000prf.googlegroups.com> <0a62d553-7fe9-41c0-84dc-a1f3749b46f8@e23g2000prf.googlegroups.com> <3682a1dd-a3a6-436f-87a0-37feaef65ccc@h11g2000prf.googlegroups.com> Message-ID: <7dc7aac7-c3e7-4a88-8528-3ac350e0e1a3@j78g2000hsd.googlegroups.com> On Jan 4, 5:25 pm, Fredrik Lundh wrote: > jo3c wrote: > > i have a 2000 files with header and data > > i need to get the date information from the header > > then insert it into my database > > i am doing it in batch so i use glob.glob('/mydata/*/*/*.txt') > > to get the date on line 4 in the txt file i use > > linecache.getline('/mydata/myfile.txt/, 4) > > > but if i use > > linecache.getline('glob.glob('/mydata/*/*/*.txt', 4) won't work > > glob.glob returns a list of filenames, so you need to call getline once > for each file in the list. > > but using linecache is absolutely the wrong tool for this; it's designed > for *repeated* access to arbitrary lines in a file, so it keeps all the > data in memory. that is, all the lines, for all 2000 files. > > if the files are small, and you want to keep the code short, it's easier > to just grab the file's content and using indexing on the resulting list: > > for filename in glob.glob('/mydata/*/*/*.txt'): > line = list(open(filename))[4-1] > ... do something with line ... > > (note that line numbers usually start with 1, but Python's list indexing > starts at 0). > > if the files might be large, use something like this instead: > > for filename in glob.glob('/mydata/*/*/*.txt'): > f = open(filename) > # skip first three lines > f.readline(); f.readline(); f.readline() > # grab the line we want > line = f.readline() > ... do something with line ... > > thank you guys, i did hit a wall using linecache, due to large file loading into memory.. i think this last solution works well for me thanks From shriphanip at gmail.com Tue Jan 1 01:27:10 2008 From: shriphanip at gmail.com (Shriphani) Date: Mon, 31 Dec 2007 22:27:10 -0800 (PST) Subject: pdf library. References: <133097f4-de83-4e13-93f1-1404213333a4@l6g2000prm.googlegroups.com> Message-ID: On Dec 30 2007, 5:08 am, Waldemar Osuch wrote: > On Dec 29, 11:54 am,Shriphani wrote: > > > Hi, > > I am looking for a pdf library that will give me a list of pages where > > new chapters start. Can someone point me to such a module ? > > Regards, > >ShriphaniP. > > pyPdf may help you with that:http://pybrary.net/pyPdf/ I tried pyPdf for this and decided to get the pagelinks. The trouble is that I don't know how to determine whether a particular page is the first page of a chapter. Can someone tell me how to do this ? From bs866806 at 163.com Sat Jan 19 06:05:47 2008 From: bs866806 at 163.com (bs866806 at 163.com) Date: Sat, 19 Jan 2008 03:05:47 -0800 (PST) Subject: Movie Stars As Sources Of Wisdom Message-ID: Why do many people look to movie stars for answers to some of life's most challenging questions? While we have great respect for the art of acting, as explicated from Stanislavsky to Strasberg, the latter of whom we knew well and were fond of, we have never understood how the usual snippets who decide to become actors ascend in the minds of the public from being initially generally regarded as likely ne'er-do-wells to being considered the most readily available font of insightful advice on just about every topic that troubles the frontal lobe of contemporary humanity. Are we so doubtful of our own confidence to make up our minds that the resplendent light in which a current movie star is illuminated by his own publicity agents blinds us to the very probable vapidity of his or her own mind? After all, there is a certain disjunction between what movie stars do to win our attentions and what we expect of them once they succeed. They bring themselves to our attention by committing to memory, or by reading off one kind of prompter or another, words devised by others. We won't go so far as to say they achieve renown by presenting the thoughts of others, since realistic drama, in most of its contemporary manifestations, is apparently unable to present characters who might actually have an occasional considerable thought. But, once they ascend to the starry vault that hovers over us, do we expect of them anything consonant with the ability to recite the usual inanities? No, suddenly we want these storied performers to transform themselves into the wise harbingers of original insight and exemplary advice. We even search the most mundane aspects of their personal lives for a hint or two as to how we might enhance the happiness of our own comparatively desultory lives. Or, just as often, we suppose, in the hope of finding that, despite their great reservoir of astonishing expertise, their own lives are inexplicably entangled in antics so confoundedly absurd that their shortcomings make us feel far superior in the relatively rickety guidance of our own lives. Since we can only be sure that the lights of stage and screen will continue to be presented to us with all the wiles that can be managed through the deft employment of colorful media, as the engaging exemplars of how we should only hope to live, it appears that the only way to alter the mutual mockery is to become more realistic about what we really ought to expect from our dazzling stars-brights. http://www.cncarrental.cn/html/Humor/20060929/25390.html From deets at nospam.web.de Mon Jan 28 07:02:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jan 2008 13:02:59 +0100 Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> <479da620$0$25625$426a74cc@news.free.fr> <13067a3e-bce7-45ea-beba-4dc83c749a72@i12g2000prf.googlegroups.com> Message-ID: <605ujjF1o66nmU1@mid.uni-berlin.de> > If Python could be automatically converted to Ada or Java, that could > potentially be used as a baseline for actual operational software. > That would capture the algorithmic details more reliably than recoding > from scratch by hand. But such an automatic conversion is not feasible > without explicit typing. If python could be automatically converted to ADA or Java, it wouldn't be python. The fundamental difference IS the lack of static type annotations. The problem is that people often confuse type inference with dynamic typing, because it looks similar - but it isn't the same. All typeinference does is to take an expression like this: a = 10 * 100 and place type-variables on it, like this: a:t_0 = 10:int * 100:int Actually, the multiplication also gets annotated, like this: a:t_0 = *(10:int, 100:int):t_1 Then the unknown type variables are inferred - it is known (and that is an important property: ALL FUNCTIONS ARE KNOWN AT THIS POINT) that there exists a multiplication function that has this signature: _ * _ : [int, int] -> int so t_1 can be inferred to be int, thus t_0 can be inferred to be int as well. But the key-point is: each and every function declaration is and has to be fully statically typed. And all of them have to be known at compile-time!! And of course this extends to classes or interfaces and such. There are some nice tricks like generic types that themselves containt type-variables in their declaration, so that you can declcare e.g. map, reduce, filter and so forth in generic ways. But they are _fully_ type annotated. And the "normal" (Henly/Millner) type inference fails to produce correct results in cases like this: def foo(arg): if arg > 10: return 100 else: return "n/a" Which is perfectly legal and sometimes useful in python. Yes, there is dependent typing, but this also goes only so far. Additionally, it can be shown that type-inferencing becomes non-deterministic or even unsolvable in the very moment you start introducing recursive types - so, away with lists, arrays, trees and so forth. Which of course also means that the statically typed languages will produce errors, unless you restrict them heavily with respect to dynamic memory allocation and so forth (that restricted ADA variant sometimes popping up in discussions about this is one such case) bottom-line: type-inference doesn't do magic, fully staticly annotated languages still fail, and efforts like shedskin are interesting but will never grow to a full-fledged python. And adding static type-declarations to python will make it NotPython, a totally different language. Diez From gagsl-py2 at yahoo.com.ar Fri Jan 18 11:49:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 18 Jan 2008 14:49:23 -0200 Subject: How to use only a sub shell to execute many commands in python References: Message-ID: En Fri, 18 Jan 2008 09:31:25 -0200, raocheng escribi?: > Please see the following code. > Suppose I have many shell commands to be executed. And I don't want to > fork a sub shell for each command(eg: status,output = > commands.getstatusoutput(cmd)) because it is too expensive. I want to > use only one sub shell to execute all these commands and want to get > each command's output. How can I accomplish this task ? Thanks in > advance. The hard part is to determine WHEN the command has completed its execution, because there is no indication of that. One way would be to set a relatively uncommon prompt, and look for that string in stdout. You can't read beyond that, else the code would block. Another way is to use a separate thread to read from stdout/stderr, and set a timeout; when no more output comes whithin the timeout, you assume the command has finished. The code below uses the first approach, changing the prompt to <$$$>\r\n. I've tested it on Windows only, but should work on Linux too with some minor modifications. import subprocess from os import getenv # Windows only, this is to determine the shell in use # Linux users may try with getenv("SHELL", "sh") shell = getenv("COMSPEC", "cmd") p = subprocess.Popen(shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) expected = '<$$$>\r\n' cmds = ['prompt $L$$$$$$$G$_','date /t','cd','dir','ipconfig /all'] # The first command above sets an uncommon prompt, ending with a newline. # On Linux use PS1=whatever, but make sure it ends in \n and set the # expected variable accordingly. for cmd in cmds: print ">>>",cmd p.stdin.write('%s\n' % cmd) while True: line = p.stdout.readline() if line.endswith(expected): break print line, print "Waiting for subshell to terminate" p.stdin.write("exit\n") p.wait() print "Done" -- Gabriel Genellina From imageguy1206 at gmail.com Tue Jan 29 12:06:26 2008 From: imageguy1206 at gmail.com (imageguy) Date: Tue, 29 Jan 2008 09:06:26 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: Message-ID: <2f010feb-d745-4516-9b4f-b225e25670a9@f47g2000hsd.googlegroups.com> On Jan 29, 12:34?pm, William McBrine wrote: > Look at this -- from Python 2.5.1: > > >>> a = [1, 2, 3, 4, 5] > >>> for x in a: > > ... ? ? if x == 3: > ... ? ? ? ? a.remove(x) > ... ? ? print x > ... > 1 > 2 > 3 > 5 > > >>> a > [1, 2, 4, 5] > > Sure, the resulting list is correct. But 4 is never printed during the > loop! > > What I was really trying to do was this: > > apps = [name for name in os.listdir(ROOT) if > ? ? ? ? os.path.isdir(os.path.join(ROOT, name))] > > apptitles = {} > > for name in apps: > ? ? try: > ? ? ? ? app = __import__(name) > ? ? except: > ? ? ? ? apps.remove(name) > ? ? else: > ? ? ? ? apptitles[name] = getattr(app, 'TITLE', name.title()) > > which worked fine, until I actually had a directory with no module in it. > Then that directory was correctly removed from the list, but the _next_ > one was skipped, so its title was never assigned, which caused problems > later in the program. > > -- > 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on You should not change/modify the original sequence iterating over. In the list comprehension, try changing os.listdir(ROOT) to os.listdir(ROOT)[:] so you are get a copy of the original list. geoff. From bj_666 at gmx.net Fri Jan 25 15:31:47 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Jan 2008 20:31:47 GMT Subject: read and readline hanging References: Message-ID: <5vuv9iF1o6ambU2@mid.uni-berlin.de> On Fri, 25 Jan 2008 17:31:16 +0100, Olivier Lefevre wrote: > Thanks for the answer. Yes this is tricky. I have done it in Java > before, where you can, e.g., set up a thread to pump stuff out of > both stderr and stdout continuously but my python is too rudimentary > for that. The `trheading` module is modeled after Java's threading API. > There is a key difference anyway: in Java you can write > > while (br.readLine() != null) { } > > where br is the buffered reader in which you've wrapped the stdout > of the child process and it will not hang. But in python eventually > stdout.readline() hangs. This is a real nuisance: why can't it just > return None? Because that would be quite annoying because most of the time people want blocking behavior. >> 1. The subprocess has stopped producing output. > > Indeed, if I do this interactively, I can tell after 3 lines that I've > gotten all there is to get right now and the fourth readline() call > hangs. But how can I find out *programmatically* that there is no more > input? You can't. >> If you are only reading its standard output, are you sure that the > > subprocess is flushing its buffers so you can recognize it's time to > > provide more input? > > The subprocess in a purely passive position: it is an interpreter: I > send it commands and I read the answers. The python side is in charge. This doesn't answer if the interpreter doesn't flush its output buffer after every line. Ciao, Marc 'BlackJack' Rintsch From jura.grozni at gmail.com Mon Jan 28 10:05:55 2008 From: jura.grozni at gmail.com (azrael) Date: Mon, 28 Jan 2008 07:05:55 -0800 (PST) Subject: PYS file Message-ID: A I Understood correctly, pyc files are compiled py scripts. Is it possible to decomplite them. I guess it's possible, but how hard is it. From justin.mailinglists at gmail.com Thu Jan 3 00:45:07 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Wed, 2 Jan 2008 21:45:07 -0800 (PST) Subject: Python CGI - Presenting a zip file to user References: <475074c1-ef0d-4551-834c-5a16781de3f8@m34g2000hsf.googlegroups.com> Message-ID: On Jan 3, 1:35 pm, jwwest wrote: > Thanks! That worked like an absolute charm. > > Just a question though. I'm curious as to why you have to use the > msvcrt bit on Windows. If I were to port my app to *NIX, would I need > to do anything similar? > > - James not needed for *NIX as *NIX does not have a notion of binary- vs text- mode I seem to recall not needing the msvcrt stuff a while ago on Windows but recently needed it again for Python CGI on IIS From yantao at telus.com Sun Jan 27 10:56:14 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 15:56:14 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: References: <13po55nc0q0s06@corp.supernews.com> Message-ID: "I V" wrote in message news:PdVmj.1467$uE.1363 at newssvr22.news.prodigy.net... > On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: >> Yes, it is true that %s already support unicode, and I did not >> contradict that. But it counts the number of bytes instead of >> characters, and makes things like %-20s out of alignment. If you don't >> understand my assertion, please don't argue back and I am only >> interested in answers from those who are qualified. > > What version of python are you using? On python 2.4 and 2.5 on linux, 2.5.2 on windows, if you have tested linux, maybe... windows is the issue? > %-20s counts the characters, not the bytes, or, I think it does. when I > run: > >>>> print u'%-20s|\n%-20s|' % (u'foo bar', u'foo b?r') > > the output is: > > foo bar | > foo b?r | > From bignose+hates-spam at benfinney.id.au Wed Jan 9 22:55:04 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 10 Jan 2008 14:55:04 +1100 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> Message-ID: <87abneibc7.fsf@benfinney.id.au> erik gartz writes: > The loop performs some actions with web services. The particular > iteration I'm on isn't important to me. It is only important that I > attempt the web services that number of times. If I succeed I > obviously break out of the loop and the containing function (the > function which has the loop in it) returns True. If all attempts > fail the containing loop returns False. When you have iteration requirements that don't seem to fit the built-in types (lists, dicts, generators etc.), turn to 'itertools' in the standard library. >>> from itertools import repeat >>> def foo(): ... import random ... print "Trying ..." ... success = random.choice([True, False]) ... return success ... >>> max_attempts = 10 >>> for foo_attempt in repeat(foo, max_attempts): ... if foo_attempt(): ... break ... Trying ... Trying ... Trying ... Trying ... Trying ... Trying ... >>> Note that this is possibly more readable than 'for foo_attempt in [foo] * max_attempts", and is more efficient for large values of 'max_attempts' because 'repeat' returns an iterator instead of actually allocating the whole sequence. > I guess based on the replies of everyone my best bet is to leave the > code the way it is and suck up the warning from pylint. I think your intent -- "repeat this operation N times" -- is better expressed by the above code, than by keeping count of something you don't actually care about. > I don't want to turn the warning off because catching unused > variables in the general is useful to me. Agreed. -- \ "Dyslexia means never having to say that you're ysror." | `\ ?anonymous | _o__) | Ben Finney From a at b.c Thu Jan 10 09:20:23 2008 From: a at b.c (Caleb) Date: Thu, 10 Jan 2008 16:20:23 +0200 Subject: I'm searching for Python style guidelines In-Reply-To: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > Anything written somewhere that's thorough? Any code body that should > serve as a reference? 1. Don't use tabs (use spaces). 2. Study "import this" 3. Use lists and dictionaries as much as you possibly can 4. Use comprehensions and generators as much as you possibly can 5. Use the standard library for everything you possibly can 6. As much as you possibly can, when starting a new project, postpone setting up classes for everything (start with functions). In some projects, you might never need the overhead at all. It will be difficult to go far wrong regarding style if you do a lot of what's in this list. This list is not mine. I jotted these points down, but this information is continually repeated by the actual wise people (not me) in this newsgroup. Caleb From bkasterm at gmail.com Thu Jan 24 21:57:58 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Thu, 24 Jan 2008 18:57:58 -0800 (PST) Subject: Convert list to file object without creating an actual file. Message-ID: <32ae7d79-248a-4ac3-b51c-756699f11837@t1g2000pra.googlegroups.com> I have written a little program that takes as input a text file, converts it to a list with appropriate html coding (making it into a nice table). Finally I want to upload this list as a textfile using ftp. If homeworkhtml contains the list of lines; e.g. homeworkhtml = ["
", "", "" ..... I want to call: ftp.storlines("STOR " + filename, homeworkhtml) which gives me the error Traceback (most recent call last): File "./testhw.py", line 67, in ? ftp.storlines("STOR " + filename, homeworkhtml) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/ftplib.py", line 428, in storlines AttributeError: 'list' object has no attribute 'readline' Expected since homeworkhtml is in fact not a file. Is there a way to convert this list to a file object without first writing it to disc and then opening the resulting file? Best, Bart From http Sat Jan 12 03:51:50 2008 From: http (Paul Rubin) Date: 12 Jan 2008 00:51:50 -0800 Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> <437bac5f-7213-48d1-9c72-203cadffa664@k39g2000hsf.googlegroups.com> Message-ID: <7x8x2vifyx.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > > I'm writing an NxN observer pattern, mostly for my own personal > > exploration. Two threads -might- be calling 'Disconnect' at the same > > time, and I can't even guarantee that the function runs properly. I think the Pythonic way to do this is have the targets communicate with the observers through queues rather than with callbacks. From tgrav at mac.com Fri Jan 11 16:35:55 2008 From: tgrav at mac.com (Tommy Grav) Date: Fri, 11 Jan 2008 16:35:55 -0500 Subject: number of element in array/matrix In-Reply-To: <1200067795.478794d335c84@webmailimpb.dur.ac.uk> References: <1200067795.478794d335c84@webmailimpb.dur.ac.uk> Message-ID: <233643D4-3AA2-406A-A259-4EF89C3792B9@mac.com> On Jan 11, 2008, at 11:09 AM, m.s.mould at durham.ac.uk wrote: > > Hi, > I have what I suspect to be a fairly simple problem while using > python Numeric. > I am attempting to count the number of times that an element 'b' > occurs in > numeric array 'a'. I tried unsuccessfully to find a more efficient > function to > do this for me such as that offered when using a list, but couldn't > seem to find > anything for Numeric arrays. However, I suspect that my loop is not > the most > efficient way to achieve this. > > def countel(a, b): #counts the number of times value 'b' is found > in array 'a' > i=0 > count=0 > while (i j=0 > while (j if (a[i][j]==b): > count=count+1 > else: > pass > j=j+1 > i=i+1 > return count > > Any help or advice would be greatly appreciated, > Matt something like this? >>> import numpy as n >>> a = n.matrix([[1,2,3,4,1],[2,3,4,1,2],[3,4,1,2,3]],"float") >>> a matrix([[ 1., 2., 3., 4., 1.], [ 2., 3., 4., 1., 2.], [ 3., 4., 1., 2., 3.]]) >>> k = n.where(a==1,1,0) >>> k matrix([[1, 0, 0, 0, 1], [0, 0, 0, 1, 0], [0, 0, 1, 0, 0]]) >>> k.sum() 4 >>> Cheers Tommy From exarkun at divmod.com Tue Jan 22 08:42:33 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 22 Jan 2008 08:42:33 -0500 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <5vm8t3F1m1797U1@mid.uni-berlin.de> Message-ID: <20080122134233.15391.1170589248.divmod.quotient.1460@ohm> On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" wrote: >For a simple greenlet/tasklet/microthreading experiment I found myself in >the need to ask the question > >isgenerator(v) > >but didn't find any implementation in the usual suspects - builtins or >inspect. > >I was able to help myself out with a simple (out of my head, hope its > >def isgenerator(v): > def _g(): yield > return type(v) == type(_g()) > >But I wonder why there is no such method already available? > Why do you need a special case for generators? If you just pass the object in question to iter(), instead, then you'll either get back something that you can iterate over, or you'll get an exception for things that aren't iterable. Jean-Paul From mrmakent at cox.net Wed Jan 23 22:00:53 2008 From: mrmakent at cox.net (Mike Kent) Date: Wed, 23 Jan 2008 19:00:53 -0800 (PST) Subject: Can someone explain this unexpected raw_input behavior? References: Message-ID: Gabriel, thank you for clarifying the source of this behavior. Still, I'm surprised it would be hard-coded into Python. Consider an interactive program, that asks the user several questions, and displays paragraphs of information based on those questions. The paragraphs are output using print, and the questions are asked via raw_input. You want to do some simple debugging of the program by printing some debugging statements via 'print >>sys.stderr', and you don't want the debug output mixed in with the normal output on the screen, so you try to route the debugging output to a file by adding '2>filename' to the end of the command line. Unfortunately, you will no longer see any of the questions being printed via raw_input. The rest of the output will be fine, but the questions disappear. Your program just stops, without asking anything... you have to guess what should be there. I'm surprised that Python hard-codes this behavior without giving the programmer any way to change it. It leaves me with two options: to either always use the logging module for debugging messages (which is not odious at all, it's just that the code in question predates the logging module, which is why debugging was done as it is), or change the program so that raw_input is never used with a prompt parameter; the prompt must always be printed separately. At least I now know I'm not crazy... regarding this, anyway. From ptmcg at austin.rr.com Fri Jan 11 15:20:25 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 11 Jan 2008 12:20:25 -0800 (PST) Subject: split parameter line with quotes References: Message-ID: <7125d8e2-4881-46e8-9ffd-ab4feaf7430e@j20g2000hsi.googlegroups.com> On Jan 11, 12:50?pm, teddyber wrote: > Hello, > > first i'm a newbie to python (but i searched the Internet i swear). > i'm looking for some way to split up a string into a list of pairs > 'key=value'. This code should be able to handle this particular > example string : > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > i know i can do that with some regexp (i'm currently trying to learn > that) but if there's some other way... > > thanks Those quoted strings sure are pesky when you try to split along commas. Here is a solution using pyparsing - note the argument field access methods at the bottom. Also, the parse action attached to integer will do conversion of the string to an int at parse time. More info on pyparsing at http://pyparsing.wikispaces.com. -- Paul from pyparsing import Word, nums, alphas, quotedString, \ delimitedList, Literal, CharsNotIn, Dict, Group, \ removeQuotes arg = '''qop="auth,auth-int,auth-conf", cipher="rc4-40,rc4-56,rc4,des,3des", maxbuf=1024,charset=utf-8,algorithm=md5-sess''' # format is: delimited list of key=value groups, where value is # a quoted string, an integer, or a non-quoted string up to the next # ',' character key = Word(alphas) EQ = Literal("=").suppress() integer = Word(nums).setParseAction(lambda t:int(t[0])) quotedString.setParseAction(removeQuotes) other = CharsNotIn(",") val = quotedString | integer | other # parse each key=val arg into its own group argList = delimitedList( Group(key + EQ + val) ) args = argList.parseString(arg) # print the parsed results print args.asList() print # add dict-like retrieval capabilities, by wrapping in a Dict expression argList = Dict(delimitedList( Group(key + EQ + val) )) args = argList.parseString(arg) # print the modified results, using dump() (shows dict entries too) print args.dump() # access the values by key name print "Keys =", args.keys() print "cipher =", args["cipher"] # or can access them like attributes of an object print "maxbuf =", args.maxbuf Prints: [['qop', 'auth,auth-int,auth-conf'], ['cipher', 'rc4-40,rc4-56,rc4,des, 3des'], ['maxbuf', 1024], ['charset', 'utf-8'], ['algorithm', 'md5- sess']] [['qop', 'auth,auth-int,auth-conf'], ['cipher', 'rc4-40,rc4-56,rc4,des, 3des'], ['maxbuf', 1024], ['charset', 'utf-8'], ['algorithm', 'md5- sess']] - algorithm: md5-sess - charset: utf-8 - cipher: rc4-40,rc4-56,rc4,des,3des - maxbuf: 1024 - qop: auth,auth-int,auth-conf Keys = ['maxbuf', 'cipher', 'charset', 'algorithm', 'qop'] maxbuf = 1024 cipher = rc4-40,rc4-56,rc4,des,3des From python at rolfvandekrol.nl Mon Jan 21 09:52:59 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Mon, 21 Jan 2008 15:52:59 +0100 Subject: stdin, stdout, redmon In-Reply-To: <4794ab22$0$19179$426a74cc@news.free.fr> References: <4794a5e3$0$9014$426a74cc@news.free.fr> <4794ab22$0$19179$426a74cc@news.free.fr> Message-ID: <4794B1CB.2050908@rolfvandekrol.nl> I don't know what you did with your Python installation, but for me this works perfectly. test3.py contains: import sys print sys.stdin.readlines() test.txt contains: Testline1 Testline2 Output of 'python test3.py < test.txt' is: ['Testline1\n', 'Testline2'] Just plain simple and just works. Rolf Bernard Desnoues wrote: > Rolf van de Krol a ?crit : > >> According to various tutorials this should work. >> >> >> |import sys >> data = sys.stdin.readlines() >> print "Counted", len(data), "lines."| >> >> >> Please use google before asking such questions. This was found with only >> one search for the terms 'python read stdin' >> >> Rolf >> >> Bernard Desnoues wrote: >> >>> Hi, >>> >>> I've got a problem with the use of Redmon (redirection port monitor). >>> I intend to develop a virtual printer so that I can modify data sent >>> to the printer. >>> Redmon send the data flow to the standard input and lauchs the Python >>> program which send modified data to the standard output (Windows XP >>> and Python 2.5 context). >>> I can manipulate the standard output. >>> >>> "import sys >>> sys.stdout.write(data)" >>> >>> it works. >>> But how to manipulate standard input so that I can store data in a >>> string or in an object file ? There's no "read" method. >>> >>> "a = sys.stdin.read()" doesn't work. >>> "f = open(sys.stdin)" doesn't work. >>> >>> I don't find anything in the documentation. How to do that ? >>> Thanks in advance. >>> >>> Bernard Desnoues >>> Librarian >>> Biblioth?que de g?ographie - Sorbonne >>> > > Hello Rolf, > > I know this code because I have search a solution ! > Your google code doesn't work ! No attribute "readlines". > > >>> import sys > >>> data = sys.stdin.readlines() > > Traceback (most recent call last): > File "", line 1, in > data = sys.stdin.readlines() > AttributeError: readlines > From bearophileHUGS at lycos.com Sat Jan 5 18:07:10 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 5 Jan 2008 15:07:10 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> Message-ID: <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> Paddy: > Not really, it seems to me to be going the exact opposite way with > languages with automatic type conversions being seen as not suited for > larger programs. In Java you can add the number 1 to a string, and have it automatically converted to string before the string join... What do you think of that feature? Bye, bearophile From israelu at elbit.co.il Mon Jan 14 16:22:47 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 14 Jan 2008 13:22:47 -0800 (PST) Subject: import from question Message-ID: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> Hi all I've got three files: file a1.py: ======== the_number = None file a2.py: ======== import a1 def init(): a1.the_number = 100 file a3.py: ======== from a1 import the_number import a2 a2.init() print the_number, type(the_number) Runninr a3.py I get: None Changing a3.py to: import a1 import a2 a2.init() print a1.the_number, type(a1.the_number) gives: 100 Why doesn't it work in the first version of a3.py? Thanks, iu2 From ggpolo at gmail.com Wed Jan 23 17:42:02 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jan 2008 20:42:02 -0200 Subject: Creating new types and invoking super In-Reply-To: References: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> Message-ID: 2008/1/23, Guilherme Polo : > 2008/1/23, Arnaud Delobelle : > > On Jan 23, 8:55 pm, "Guilherme Polo" wrote: > > > Hello, > > > > Hi > > [...] > > > First I tried this: > > > > > > def init(func): > > > def _init(inst): > > > super(inst.__class__, inst).__init__() > > > func(inst) > > > > > > return _init > > > > > > class A(object): > > > @init > > > def __init__(self): pass > > > > This kind of approach can't work, you need to call super(A, obj). > > super(type(obj), obj) is pointless, it defeats the whole purpose of > > the mro! > > > > Yeh, as shown in the next examples in the previous email. Using a > decorator for that doesn't sound useful at all, was just trying > something different ;) I will stick to the no-decorator option. > > > The only way I can think of would be to create a metaclass, but I > > don't think it's worth it. super(A, obj).__init__() isn't that bad! > > > > Metaclass doesn't apply here because metaclass is related to > class-construction. This is related to instance initialization, and > I'm creating the types as the user asks. Oops, actually it can be done. But I am not going to stick to it, just did a sample here that "solves" for a not so deep structure: def init(func): def _init(cls): if hasattr(cls, "myclass"): super(cls.myclass, cls).__init__() else: super(cls.__class__, cls).__init__() func(cls) return _init class M(type): def __new__(cls, classname, bases, classdict): if not len(classdict): if 'myclass' in bases[0].__dict__: classdict['myclass'] = bases[0].__dict__['myclass'] else: classdict['myclass'] = bases[0] return type.__new__(cls, classname, bases, classdict) class Y(object): __metaclass__ = M class X(Y): @init def __init__(self): print "X" X() y = type("Z", (X, ), {}) w = type("W", (y, ), {}) y() w() > > > -- > > Arnaud > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > -- Guilherme H. Polo Goncalves > -- -- Guilherme H. Polo Goncalves From Scott.Daniels at Acm.Org Tue Jan 1 00:11:48 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 31 Dec 2007 21:11:48 -0800 Subject: using super In-Reply-To: <13nj9oc1vo7j10@corp.supernews.com> References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> <13niugpmvdls482@corp.supernews.com> <13nj1fp5m8u1i6f@corp.supernews.com> <13nj9oc1vo7j10@corp.supernews.com> Message-ID: <13njikdi21168e7@corp.supernews.com> Steven D'Aprano wrote: > On Mon, 31 Dec 2007 16:19:11 -0800, Scott David Daniels wrote: > >> Steven D'Aprano wrote: >>> On Mon, 31 Dec 2007 08:03:22 -0800, Scott David Daniels wrote: >>>> Steven D'Aprano wrote: ... >>>>> def chain(meth): # A decorator for calling super. >>>>> def f(self, *args, **kwargs): >>>>> result = meth(self, *args, **kwargs) >>>>> S = super(self.__class__, self) >>>> This line is the problem. The class parameter needs to be the class >>>> (B in this case) in which the chaining method is defined, not that of >>>> the object itself. >>> One minor correction: the class parameter needs to be the class >>> *itself*, not the class *name* (which would be the string "B"). >> Point taken. >> >>> I don't quite understand your description though. What do you mean "the >>> chaining method is defined"? chain() is defined outside of a class. >> The class where f (the chaining method) is defined; equivalently, the >> class in which the @chain is used. > > So why doesn't self.__class__ work? That's the class in which @chain is > used. OK, here's a simple 3-class example: class A(object): def meth(self): print 'A.meth:', self.__class__, '---' def pn(self): return '' class B(A): def meth(self): super(B, self).meth() print 'B.meth:', self.__class__, super(B, self).pn() def pn(self): return '' class C(B): def meth(self): super(C, self).meth() print 'C.meth:', self.__class__, super(C, self).pn() def pn(self): return '' c = C() c.meth() # Figure out why it printed what it did. # If not clear yet, how about this: for class_ in C, B: print class_.__name__, super(class_, c).pn() # And a bigger example (re-using A) to show why we class B0(A): def meth(self): super(B0, self).meth() print 'B0.meth:', self.__class__, super(B0, self).pn() def pn(self): return '' class B1(B0): def meth(self): super(B1, self).meth() print 'B1.meth:', self.__class__, super(B1, self).pn() def pn(self): return '' class B2(B0): def meth(self): super(B2, self).meth() print 'B2.meth:', self.__class__, super(B2, self).pn() def pn(self): return '' class C1(B1, B2): def meth(self): super(C1, self).meth() print 'C1.meth:', self.__class__, super(C1, self).pn() def pn(self): return '' class D1(C1): def meth(self): super(D1, self).meth() print 'D1.meth:', self.__class__, super(D1, self).pn() def pn(self): return '' d = D1() d.meth() # Figure out why it printed what it did. for class_ in D1, C1, B1, B2, B0: print class_.__name__, super(class_, d).pn() # Now (after much cogitation) might that do it? # finally, just a fillip, predict this before you run it: class E(D1, C): def meth(self): super(E, self).meth() print 'E.meth:', self.__class__, super(E, self).pn() def pn(self): return '' e = E() e.meth() for class_ in E, D1, C1, B1, B2, B0, C, B: print class_.__name__, super(class_, e).pn() > I can clearly see that it doesn't work, I just don't understand why. I'd > be inclined to chalk it up to super() being a mysterious black box that > makes no sense *wink* .... super (and mro) work to get to all the superclasses in an order that produces subtypes before their supertypes. The diamond inheritance examples "show" why its needed. -Scott From ec21i at hotmail.com Tue Jan 1 06:23:27 2008 From: ec21i at hotmail.com (ec21i at hotmail.com) Date: Tue, 1 Jan 2008 03:23:27 -0800 (PST) Subject: Fashion Footwear Industrial Co.,Ltd(Fujian,CHINA) Message-ID: <3a1b5ef1-ad23-4609-98cf-8b590bcc11f2@u10g2000prn.googlegroups.com> Dear my friend It is our pleasure to meet you here. we are wholesaler sport shoes,clothing,electrons in Fujian of China. our website: http://www.ec21i.com We are professional and honest wholesaler of all kinds of brand sneaks and apparel.the products our company supply are as follows: 1).Nike Jordans Jordan 1 jordan 1.5 jordan 2 jordan 3 jordan 3.5 jordan 4 jordan 5 jordan 5.5 jordan 6 jordan 6.5 jordan 7 jordan 8 jordan 9 jordan 9.5 jordan 10 jordan 11 jordan 12 jordan 13 jordan 13.5 jordan 14 jordan 15 jordan 16 jordan 17 jordan 18 jordan 18.5 jordan 19 jordan 20 jordan 21 jordan 21.5 jordan 22 jordan King jordan Dub Zero Jordan 23 Jordan 7.5 2).Air Force One Air Force one (low) Air Force one (High) Air Force one (Mid) Air Force one (clear) Air Force One 25 year 3).SHOX Shox R3 Shox R4 Shox R5 Shox TL1 Shox TL2 Shox TL3 Shox NZ Shox OZ Shox Turbo Show GO Shox CL Shox Coqnescenti Shox Energia Shox Explodine Shox Monster Shox Rhythmic Shox Warrior 4).Bape Shoes Bape Bape (transparent) 5).Air max AirMax 90 AirMax 95 AirMax 97 AirMax 2003 AirMax 2004 AirMax 2005 Air Max 2006 AirMax 180 AirMax LTD AirMax TN AirMax solas AirMax 87 AirMax Rift 6).Puma Puma Rpt2 Puma SK6 Puma Jayfi Puma Cir Puma Speed Puma Repli Puma Future Cat Puma Mostro Puma Lifestyle 7).Dunk SB Dunk High Dunk Low 8).Timberland Timberland High Timberland Low 9).Adidas Adidas 35 Adicolor Country city sense Adidas NBA 11).Prada & Gucci Prada Gucci 12).Footballer Shoes Footballer 13).Locaste 14).converse & Reebok converse Reebok 15).D&G shoes 16).Dsquared2 shoes 17).James shoes 18).Nike King 9).Children shoes Jordan Shox 20).Women shoes Women Jordans Women Shox R3 Women Shox R4 Women AirMax 95&97 Women AirMax 03&06 Women Dunk Women Shox NZ Women AF1 21).sandal & baboosh Nike Puma Gucci Prada CLOTHES 1).Bape 2).ED Hardy 3).BBC 4).CLH 5).LRG 6).Artful Dodger Hoodies 7).GINO GREEN GLOBAL 8).10 Deep 9).A&F Coat 11).Jersey NBA Jersey Football Jersey 12).Juicy Bikini 13).Adidas Coat 14).F1 Coat 15).D&G Coat 16).Superman Coat 17).NBA Coat JEAN 1).E&D Jeans 2).BBC Jeans 3).BAPE Jeans 4).D&G Jeans 5).EVSIU Jeans 6).Red monkey 7).COOGI Jeans T-shirt 1).POLO 2007 polo(women) 2007 POLO IIII(Men) POLO (stripe) polo (small ) 2).Lacoste Lacoste (LONG) Lacoste (SHORT) 3).Name Brand shirt D&G Shirt Giorgio Armani TN Shirt 4).BBC T-shirt 5).LRG & gina green glalal 6).Triumvir 7).ED handy 8).Evsiu 9).R.M.B 10).CLOT Burse & Handbag 1).LV Bag 2).Gucci Bag 3).Dior Bag 4).Chanel Bag 5).Fendi Bag 6).Coach Bag 7).Burberrys Bag 8).Prada Bag 9).Man Leisure Bag 11).D&G bag 12).nike bag 13).Wallet 14).Suitcase Electronics 1).Vertu Mobile 2).New iphone Mobile 3).Nokia Mobile 4).moto Mobile 5).PSP Game & memory card 6).Sony Mobile 7).Samsung Mobile 8).Ipod nano 9).Sony PS3 10).Laptops IBM laptops DELL laptops Sony laptops ASUS laptops CAP 1).ED Hardy Cap 2).New Bape & NY Cap 3).RMC Cap 4).New era NBA 5).F1 6).Chanel 7).D&G 8).gucci 9).LV 10).Prada 11).PUMA 12).wool WATCH 1).Rolex 2).Omega 3).Cartier 4).Chanel 5).Piaget 6).Breitling 7).Bvlgari 8).Corum Sunglasses 1).Gucci Sunglasses 2).D&G Sunglasses 3).Dior Sunglasses 4).LV Sunglasses 5).Chanel Sunglasses 6).Prada Sunglasses 7).Versace Sunglasses 8).Giorgio Armani Strap 1).Bape Strap 2).D&G Strap 3).Gucci Strap 4).LV Strap 5).Scarf Other 1).Lighter size chart Men Size: US: 7 8 8.5 9 9.5 10 10.5 11 11.5 12 13 14 15 UK: 6 7 7.5 8 8.5 9 9.5 10 10.5 11 12 13 14 EUR: 40 41 42 42.5 43 44 44.5 45 45.5 46 47.5 48 49 Women Size: US: 5 5.5 6 6.5 7 7.5 8 8.5 UK: 2.5 3 3.5 4 4.5 5 5.5 6 EUR: 35.5 36 36.5 37.5 38 38.5 39 40 Kid's US: 1 2 3 4 5 6 7 7.5 8 8.5 9 9.5 10 10.5 11 11.5 12 12.5 13 13.5 UK: 13 1 2 3 4 5 6 6.5 7 7.5 8 8.5 9 9.5 10 10.5 11 11.5 12 12.5 EUR:17 18 19 20 21 22 23 24 24.5 25 25.5 26 26.5 27 27.5 28 29 30 30.5 31 Clothing Size: S M L XL XXL XXXL XXXXL XXXXXL 7.because the space of the website is limited,we can also supply many other products which be not showed out in our site. if you have the photos of the products you need , we are pleasure to supply for your orders. And our company can supply for our customers ,as follow: 1. top quality.all our products have top quality. 2. most rational price. we offer the most competitive price to you to open your market. So today most of our products have sold well in the America, Europe, Middle East, Southeast Asia etc.. 3. safe and fast shipment. As different country you are in, we will deliver the products to you by different ways and pledge to arrive to your address 100%.and we will send the products to you within 24h after we get your payment. 4.many products in stock. We have many products in stock and kinds of size you need , also include kid's. 5.our credit. If the products can be not delivered to your address as our reason, we will refund the money you paid. Hope sincerely to have glad and long term business relationship with you. If you are interested in our products and have any problem, welcome to contact us. Please trust us , we will be your best choice !!! Website : http://www.ec21i.com MSN and E-mail: ec21i at hotmail.com Michael Fashion Footwear Industrial Co.,Ltd.(Fujian,CHINA) From asmodai at in-nomine.org Thu Jan 17 12:14:13 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 17 Jan 2008 18:14:13 +0100 Subject: working with a subversion repo In-Reply-To: <7f156399-d9ae-4f13-a80f-0ffe41d89427@s12g2000prg.googlegroups.com> References: <7f156399-d9ae-4f13-a80f-0ffe41d89427@s12g2000prg.googlegroups.com> Message-ID: <20080117171412.GN61556@nexus.in-nomine.org> -On [20080117 17:21], Luke (Luke.Visinoni at gmail.com) wrote: >I am able to import a module named "svn" on my ubuntu machine, but this >module is not available on windows. The entries libsvn and svn are installed in site-packages when you install the Python (SWIG) bindings for Subversion. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Nothing is constant but change... From martin at librador.com Mon Jan 21 02:01:20 2008 From: martin at librador.com (Martin Vilcans) Date: Mon, 21 Jan 2008 08:01:20 +0100 Subject: Looping through the gmail dot trick In-Reply-To: References: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> Message-ID: On Jan 20, 2008 8:58 PM, Martin Marcher wrote: > are you saying that when i have 2 gmail addresses > > "foo.bar at gmail.com" and > "foobar at gmail.com" > > they are actually treated the same? That is plain wrong and would break a > lot of mail addresses as I have 2 that follow just this pattern and they > are delivered correctly! > > Do you have any reference on that where one could read up why gmail would > have such a behaviour? Try the SMTP spec. IIRC there's a passage there that says that the server should try to make sense of addresses that don't map directly to a user name. Specifically, it says that firstname.lastname should be mapped to the user with those first and last names. -- martin at librador.com http://www.librador.com From gagsl-py2 at yahoo.com.ar Tue Jan 1 12:50:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Jan 2008 15:50:33 -0200 Subject: Using mouse References: <13nkl1ubh76bo8e@corp.supernews.com> Message-ID: En Tue, 01 Jan 2008 12:54:54 -0200, Grant Edwards escribi?: > On 2007-12-31, Lucas Prado Melo wrote: > >> I would like to control mouse events (i.e. I would like to >> "click" and move mouse around by code). How do I do this in >> python? > > http://python-xlib.sourceforge.net/doc/html/python-xlib_14.html On Windows, use the mouse_event function http://msdn2.microsoft.com/en-us/library/ms646260.aspx Available on pywin32 https://sourceforge.net/projects/pywin32/ or using ctypes directly. -- Gabriel Genellina From rong.xian at gmail.com Sun Jan 27 22:53:02 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 19:53:02 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> Message-ID: <72a03212-7cf3-486d-ac70-c97a002d90c7@n20g2000hsh.googlegroups.com> On 1?28?, ??5?50?, John Machin wrote: > On Jan 28, 7:47 am, "Mark Tolonen" > wrote: > > > > > > > >"John Machin" wrote in message > > >news:eeb3a05f-c122-4b8c-95d8-d13741263374 at h11g2000prf.googlegroups.com... > > >On Jan 27, 9:17 pm, glacier wrote: > > >> On 1?24?, ??3?29?, "Gabriel Genellina" > > >> wrote: > > > >*IF* the file is well-formed GBK, then the codec will not mess up when > > >decoding it to Unicode. The usual cause of mess is a combination of a > > >human and a text editor :-) > > > SAX uses the expat parser. From the pyexpat module docs: > > > Expat doesn't support as many encodings as Python does, and its repertoire > > of encodings can't be extended; it supports UTF-8, UTF-16, ISO-8859-1 > > (Latin1), and ASCII. If encoding is given it will override the implicit or > > explicit encoding of the document. > > > --Mark > > Thank you for pointing out where that list of encodings had been > cunningly concealed. However the relevance of dropping it in as an > apparent response to my answer to the OP's question about decoding > possibly butchered GBK strings is .... what? > > In any case, it seems to support other 8-bit encodings e.g. iso-8859-2 > and koi8-r ... > > C:\junk>type gbksax.py > import xml.sax, xml.sax.saxutils > import cStringIO > > unistr = u''.join(unichr(0x4E00+i) + unichr(ord('W')+i) for i in > range(4)) > print 'unistr=%r' % unistr > gbkstr = unistr.encode('gbk') > print 'gbkstr=%r' % gbkstr > unistr2 = gbkstr.decode('gbk') > assert unistr2 == unistr > > print "latin1 FF -> utf8 = %r" % > '\xff'.decode('iso-8859-1').encode('utf8') > print "latin2 FF -> utf8 = %r" % > '\xff'.decode('iso-8859-2').encode('utf8') > print "koi8r FF -> utf8 = %r" % '\xff'.decode('koi8-r').encode('utf8') > > xml_template = """%s data>""" > > asciidoc = xml_template % ('ascii', 'The quick brown fox etc') > utf8doc = xml_template % ('utf-8', unistr.encode('utf8')) > latin1doc = xml_template % ('iso-8859-1', 'nil illegitimati > carborundum' + '\xff') > latin2doc = xml_template % ('iso-8859-2', 'duo secundus' + '\xff') > koi8rdoc = xml_template % ('koi8-r', 'Moskva' + '\xff') > gbkdoc = xml_template % ('gbk', gbkstr) > > for doc in (asciidoc, utf8doc, latin1doc, latin2doc, koi8rdoc, > gbkdoc): > f = cStringIO.StringIO() > handler = xml.sax.saxutils.XMLGenerator(f, encoding='utf8') > xml.sax.parseString(doc, handler) > result = f.getvalue() > f.close > print repr(result[result.find(''):]) > > C:\junk>gbksax.py > unistr=u'\u4e00W\u4e01X\u4e02Y\u4e03Z' > gbkstr='\xd2\xbbW\xb6\xa1X\x81 at Y\xc6\xdfZ' > latin1 FF -> utf8 = '\xc3\xbf' > latin2 FF -> utf8 = '\xcb\x99' > koi8r FF -> utf8 = '\xd0\xaa' > 'The quick brown fox etc' > '\xe4\xb8\x80W\xe4\xb8\x81X\xe4\xb8\x82Y\xe4\xb8\x83Z' > 'nil illegitimati carborundum\xc3\xbf' > 'duo secundus\xcb\x99' > 'Moskva\xd0\xaa' > Traceback (most recent call last): > File "C:\junk\gbksax.py", line 27, in > xml.sax.parseString(doc, handler) > File "C:\Python25\lib\xml\sax\__init__.py", line 49, in parseString > parser.parse(inpsrc) > 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 > xml.sax._exceptions.SAXParseException: :1:30: unknown > encoding > > C:\junk>- ??????? - > > - ??????? - Thanks,John. It's no doubt that you proved SAX didn't support GBK encoding. But can you give some suggestion on how to make SAX parse some GBK string? From grante at visi.com Mon Jan 21 11:15:02 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 21 Jan 2008 16:15:02 -0000 Subject: When is min(a, b) != min(b, a)? References: Message-ID: <13p9h86e9aoa43e@corp.supernews.com> On 2008-01-21, Albert Hopkins wrote: > This issue may have been referred to in > news: but I didn't > entirely understand the explanation. Basically I have this: > > >>> a = float(6) > >>> b = float('nan') > >>> min(a, b) > 6.0 > >>> min(b, a) > nan > >>> max(a, b) > 6.0 > >>> max(b, a) > nan > > Before I did not know what to expect, but I certainly didn't expect > this. So my question is what is the min/max of a number and NaN or is it > not defined (for which I would have expected either an exception to be > raised or NaN returned in each case). For applications I work on, it should be NaN. But I think the result of comparing a Normal to a NaN is undefined, so the above behavior is allowed by the IEEE spec. > As a corrollary would I be able to rely on the above behavior or is it > subject to change (to fix a bug in min/max perhaps :-)? According to Wikipedia: In the proposed IEEE 754r revision of that standard the same rule applies, except that a few anomalous functions (such as the maxnum function, which returns the maximum of two operands which are expected to be numbers) favour numbers -- if just one of the operands is a NaN then the value of the other operand is returned. A different approach has been implemented in the NaN 'toolbox' for GNU Octave and MATLAB. In that toolbox, NaNs are assumed to represent missing values and so the statistical functions ignore NaNs in the data instead of propagating them. Every computation in the NaN toolbox is based on the data values only, which can be useful if it is known that NaNs cannot be produced by errors. -- Grant Edwards grante Yow! Remember, in 2039, at MOUSSE & PASTA will visi.com be available ONLY by prescription!! From sallport at altirium.com Wed Jan 2 04:12:32 2008 From: sallport at altirium.com (Steven Allport) Date: Wed, 2 Jan 2008 09:12:32 -0000 Subject: Problem with parsing email message with extraneous MIMEinformation References: <3PCdnchSqYywI_banZ2dnUVZ8qydnZ2d@bt.com> Message-ID: <79KdnVCfW_cfyObanZ2dnUVZ8u-dnZ2d@bt.com> Thanks for the response. The section of the email is an actual message fragment. The first blank line that appears in the message is immediately after the 1st ' boundary="------------m.182DA3C.BE6A21A3"' There are no blank line prior to this in the message. In the example that was snipped from an actual exported message there is a set of 5 _NextPart_ lines followed by the message header for the 1st attached message then a set of 7 _NextPart_ lines followed by the messge header for the 2nd attached message. Comprising in total 6 set of _NextPart_ lines. As some of the attached messages also contained messages as attachments. Unfortunately it is not possible for me to post or leave the message anywhere for you and so far I have been unable to recreate a test message of similar format. I will endeavour to do so and will if I can will let you know where it is. "Gabriel Genellina" wrote in message news:mailman.2780.1198749836.13605.python-list at python.org... > En Fri, 21 Dec 2007 10:22:53 -0300, Steven Allport > escribi?: > >> I am working on processing eml email message using the email module >> (python >> 2.5), on files exported from an Outlook PST file, to extract the >> composite >> parts of the email. In most instances this works fine, the message is >> read >> in using message_from_file, is_multipart returns True and I can process >> each >> component and extract message attachments. >> >> I am however running into problem with email messages that contain emails >> forwarded as attachments. The email has some additional encapulated >> header >> information from each of the forwared emails.When I processes the files >> is_multipart returns False the content-type is reported as text/plain >> and the payload includes all the message body from 'This message is in >> MIME >> format' though to the end. >> >> for example. >> >> >> MIME-Version: 1.0 >> X-Mailer: Internet Mail Service (5.5.2448.0) >> This message is in MIME format. Since your mail reader does not >> understand >> this format, some or all of this message may not be legible. >> ------_=_NextPart_000_01C43634.1A06A235 >> ------_=_NextPart_001_01C43634.1A06A235 >> ------_=_NextPart_001_01C43634.1A06A235 >> ------_=_NextPart_001_01C43634.1A06A235-- >> ------_=_NextPart_000_01C43634.1A06A235 >> >> ------_=_NextPart_002_01C43634.1A06A235 >> ------_=_NextPart_003_01C43634.1A06A235 >> ------_=_NextPart_003_01C43634.1A06A235 >> ------_=_NextPart_003_01C43634.1A06A235-- >> ------_=_NextPart_002_01C43634.1A06A235 >> ------_=_NextPart_002_01C43634.1A06A235-- >> ------_=_NextPart_000_01C43634.1A06A235 >> Mime-Version: 1.0 >> Content-Type: multipart/mixed; >> boundary="------------m.182DA3C.BE6A21A3" >> >> >> If I remove the section of the email from the 'This is in MIME format' >> through to Mime-Version: 1.0 the message is processed correctly. (ie. >> is_multipart = True , Content-Type = multipart/mixed etc.) > > Is this an actual message fragment? Can't be, or else it's broken. Headers > are separated from message body by one blank line. At least there should > be a blank line before "This message is in MIME...". > And are actually all those xxx_NextPart_xxx lines one after the other? > >> Could anybody tell me if the above message header breaks the conventions >> for >> email messages or is it just some that is not handled correctly by the >> email >> module. > > Could you post, or better leave available somewhere, a complete message > (as originally exported by Outlook, before any processing)? > > -- > Gabriel Genellina > > From hat at se-162.se.wtb.tue.nl Wed Jan 23 06:39:27 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 23 Jan 2008 12:39:27 +0100 Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? References: Message-ID: On 2008-01-23, ioscas at gmail.com wrote: > Hi, I am looking for a HTML parser who can parse a given page into > a DOM tree, and can reconstruct the exact original html sources. Why not keep a copy of the original data instead? That would be VERY MUCH SIMPLER than trying to reconstruct a parsed tree back to original source text. sincerely, Albert From deets at nospam.web.de Tue Jan 1 07:36:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 Jan 2008 13:36:57 +0100 Subject: ElementTree should parse string and file in the same way In-Reply-To: <13njba091eipl6f@corp.supernews.com> References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> Message-ID: <5tuqfaF1f8u9tU1@mid.uni-berlin.de> Steven D'Aprano schrieb: > On Tue, 01 Jan 2008 01:53:47 +0000, Peter Pei wrote: > >> You are talking shit. It is never about whether it is hard to write a >> wrapper. It is about bad design. I should be able to parse a string and >> a file in exactly same way, and that should be provided as part of the >> package. > > Oh my, somebody decided to start the new year with all guns blazing. > > Before abusing anyone else, have you considered asking *why* ElementTree > does not treat files and strings the same way? I believe the writer of > ElementTree, Fredrik Lundh, frequents this newsgroup. > > It may be that Fredrik doesn't agree with you that you should be able to > parse a string and a file the same way, in which case there's nothing you > can do but work around it. On the other hand, perhaps he just hasn't had > a chance to implement that functionality, and would welcome a patch. > > Fredrik, if you're reading this, I'm curious what your reason is. I don't > have an opinion on whether you should or shouldn't treat files and > strings the same way. Over to you... I think the decision is pretty clear to everybody who is a code-monkey and not a Peter-Pei-School-of-Excellent-And-Decent-Designers-attendant: when building a XML-document, you start from a Element or Elementtree and often do things like root_element = for child in some_objects: root_element.append(XML("""""" % child.attribute)) Which is such a common usage-pattern that it would be extremely annoying to get a document from XML/fromstring and then needing to extract the root-element from it. And codemonkeys know that in python doc = et.parse(StringIO(string)) is just one import away, which people who attend to Peter-Pei-School-of-Excellent-And-Decent-Designers may have not learned yet - because they are busy praising themselves and coating each other in edible substances before stepping out into the world and having all code-monkeys lick off their greatness in awe. http://www.youtube.com/watch?v=FM7Rpf1x7RU Diez From kyosohma at gmail.com Fri Jan 11 12:11:08 2008 From: kyosohma at gmail.com (Mike) Date: Fri, 11 Jan 2008 09:11:08 -0800 (PST) Subject: Using eggs References: <9a2575c7-5b62-4f00-a813-635a82e96b79@k39g2000hsf.googlegroups.com> Message-ID: <50913183-4424-47db-9bfa-5606a1be81d2@21g2000hsj.googlegroups.com> On Jan 11, 10:33 am, oj wrote: > Hi all! > > As is about to become apparent, I really don't know what I'm doing > when it comes to using eggs. > > I'm writing some software that is going to be deployed on a machine as > a number of eggs. Which is all well and good. > > These eggs all end up depending on each other; modules in egg A want > to import modules in egg B etc. > > It's not really practical to add the path to each individual egg to > the PYTHONPATH (although there's all in a directory that is in > PYTHONPATH). > > Do I have to add boiler-plate code to the beginning of all the modules > with these dependencies to check if modules are available and require > the eggs if they aren't? Or is there a way I can have stuff 'just > work' as it does in the development environment when the modules > haven't been bundled up into eggs? > > On a similar note, I can't seem to get the automatic script creation > stuff in setuptools to create scripts that have additional > requirements. I tried defining extra requires giving the names of > other eggs that will be required, and then specifying these as extras > to the console_scripts, but the generated scripts were no different. > Am I doing something wrong? Or am I just not understanding something? > > I'm muddling through getting this all working at the moment, but I get > the distinct impression that there's a better (correct?) way that I'm > not aware of. > > Sorry for such a vague posting. > > -Oli I know when I've asked questions about eggs and setup-tools, I was referred to the Distutils user group. I would cross-post there for double the fun! http://mail.python.org/mailman/listinfo/distutils-sig Mike From info at wingware.com Wed Jan 16 14:50:20 2008 From: info at wingware.com (Wingware) Date: Wed, 16 Jan 2008 14:50:20 -0500 Subject: ANN: Wing IDE 3.0.3 released Message-ID: <478E5FFC.2070008@wingware.com> Hi, We're happy to announce version 3.0.3 of Wing IDE, an advanced development environment for the Python programming language. It is available from: http://wingware.com/downloads This release focuses on fixing some usability issues found in Wing 3.0.2, including fixes for input handling in Debug I/O, Zope debugging on 64-bit Linux, several emacs and vi mode improvements, and about 34 other bugs. See the change log for details: http://wingware.com/pub/wingide/3.0.3/CHANGELOG.txt It is a free upgrade for all Wing 3.0 users. *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. New features added in Wing 3.0 include: * Multi-threaded debugger * Debug value tooltips in editor, debug probe, and interactive shell * Autocompletion and call tips in debug probe and interactive shell * Automatically updating project directories * Testing tool, currently supporting unittest derived tests (*) * OS Commands tool for executing and interacting with external commands (*) * Rewritten indentation analysis and conversion (*) * Introduction of Wing IDE 101, a free edition for beginning programmers * Available as a .deb package for Debian and Ubuntu * Support for Stackless Python * Support for 64 bit Python on Windows and Linux (*)'d items are available in Wing IDE Professional only. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). *Purchasing & Upgrading* Wing IDE Professional & Wing IDE Personal are commercial software and require a license to run. To upgrade a 2.x license or purchase a new 3.x license: Upgrade: https://wingware.com/store/upgrade Purchase: https://wingware.com/store/purchase Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From jr9445 at ATT.COM Fri Jan 11 16:21:06 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 11 Jan 2008 15:21:06 -0600 Subject: split parameter line with quotes 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 teddyber > Sent: Friday, January 11, 2008 1:51 PM > To: python-list at python.org > Subject: split parameter line with quotes > > Hello, > > first i'm a newbie to python (but i searched the Internet i swear). > i'm looking for some way to split up a string into a list of pairs > 'key=value'. This code should be able to handle this particular > example string : > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > i know i can do that with some regexp (i'm currently trying to learn > that) but if there's some other way... > import re s='''qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,3des",m axbuf=1024,charset=utf-8,algorithm=md5-sess''' print s all = re.findall(r'(.*?)=(".*?"|[^"]*?)(,|$)', s) print all for i in all: print i[0], "=", i[1].strip('"') Output: qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,3des",maxbuf =1024,charset=utf-8,algorithm=md5-sess [ ('qop', '"auth,auth-int,auth-conf"', ','), ('cipher', '"rc4-40,rc4-56,rc4,des,3des"', ','), ('maxbuf', '1024', ','), ('charset', 'utf-8', ','), ('algorithm', 'md5-sess', '') ] qop = auth,auth-int,auth-conf cipher = rc4-40,rc4-56,rc4,des,3des maxbuf = 1024 charset = utf-8 algorithm = md5-sess ***** 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 grante at visi.com Tue Jan 1 09:54:54 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Jan 2008 14:54:54 -0000 Subject: Using mouse References: Message-ID: <13nkl1ubh76bo8e@corp.supernews.com> On 2007-12-31, Lucas Prado Melo wrote: > I would like to control mouse events (i.e. I would like to > "click" and move mouse around by code). How do I do this in > python? http://python-xlib.sourceforge.net/doc/html/python-xlib_14.html -- Grant Edwards grante Yow! Pardon me, but do you at know what it means to be visi.com TRULY ONE with your BOOTH! From george.maggessy at gmail.com Tue Jan 8 13:32:06 2008 From: george.maggessy at gmail.com (George Maggessy) Date: Tue, 8 Jan 2008 10:32:06 -0800 (PST) Subject: Pet Store References: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com> <5ugv69F1hqn2cU3@mid.uni-berlin.de> Message-ID: <44713824-c8c9-4a4c-af7e-042260068c0c@x69g2000hsx.googlegroups.com> Yeap. It is. I'm looking for something like that app. Smth that I could base my future developments on. On Jan 8, 1:47 am, Marc 'BlackJack' Rintsch wrote: > On Mon, 07 Jan 2008 22:21:53 -0800, George Maggessy wrote: > > I'm an experience Java developer trying to learn Python. I just > > finished the Python tutorial on python.org and I'm currently reading > > the "Learning Python" book. However, if I could find something like a > > simple web app with some best practices, such as those famous "Java > > Pet Store" apps, I think that would help me to fill up some gaps in my > > learning process. Does anybody know any app like that? > > Isn't that a web application using Java web frameworks? So you are > looking for a Python web framework with a "Pet Store" tutorial? > > Ciao, > Marc 'BlackJack' Rintsch From steven at REMOVE.THIS.cybersource.com.au Sun Jan 6 16:09:41 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 06 Jan 2008 21:09:41 -0000 Subject: Delete lines containing a specific word References: Message-ID: On Sun, 06 Jan 2008 09:21:33 -0800, Francesco Pietra wrote: > Please, how to adapt the following script (to delete blank lines) to > delete lines containing a specific word, or words? That's tricky, because deleting lines from a file isn't a simple operation. No operating system I know of (Windows, Linux, OS X) has a "delete line" function. Do you really need to delete the lines in place? It would be much simpler to leave the original data as-is, and create a new file with just the lines that aren't deleted. > f=open("output.pdb", "r") > for line in f: > line=line.rstrip() > if line: > print line > f.close() How to adapt this script: First, think about what this script does. That is, it goes through each line, and if the line is not blank, it prints it. What do you want it to do instead? You want it to print the line if the line doesn't contain a specific word. So that's the first thing you need to change. Secondly, you might want the script to write its output to a file, instead of printing. So, instead of the line "print line", you want it to write to a file. Before you can write to a file, you need to open it. So you will need to open another file: you will have two files open, one for input and one for output. And you will need to close them both when you are finished. Does that help you to adapt the script? > If python in Linux accepts lines beginning with # as comment lines, > please also a script to comment lines containing a specific word, or > words, and back, to remove #. The same process applies. Instead of "delete line", you want to "comment line". -- Steven From python at rolfvandekrol.nl Mon Jan 28 20:47:58 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Tue, 29 Jan 2008 02:47:58 +0100 Subject: Executing other python code In-Reply-To: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: <479E85CE.6000507@rolfvandekrol.nl> AFAIK this can't be done with just python. You can use the C API of Python to achieve this. I don't know the details of that, but I guess you will need this (http://docs.python.org/api/api.html). Rolf Tim Rau wrote: > I'm working on a game, and I'd like players to be able to define thier > ships with scripts. Naturally, I don't want to give them the entire > program as thier romping ground. I would like to invoke a seperate > interpreter for these files, and give it a limited subset of the > functions in my game. What is the best way to achieve this effect? > From carsten at uniqsys.com Thu Jan 17 09:48:23 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 17 Jan 2008 09:48:23 -0500 Subject: Stop tab-completing empty lines! In-Reply-To: References: Message-ID: <1200581303.3475.9.camel@dot.uniqsys.com> On Thu, 2008-01-17 at 00:58 -0800, Casey Rodarmor wrote: > Hi everybody, > > I have the following in my python startup file: > > import readline, rlcompleter > readline.parse_and_bind("tab: complete") > > This lets me tab complete identifiers in the interpreter beautifully, > but there's a tiny problem... If I'm sitting at the beginning of a > blank line and just want a tab, it tries to tab complete, which kind > of a pain. > > -=SIMULATED PYTHON PROMPT=- > >>> def mega_awesome_function(cool_stuff, **some_sweet_kwargs): > ... X > > (The X is where I press tab and get super annoyed) Patching rlcompleter.py in the python library thusly seems to do the trick: """ --- rlcompleter.py.bak 2008-01-17 09:35:06.000000000 -0500 +++ rlcompleter.py 2008-01-17 09:35:08.000000000 -0500 @@ -99,6 +99,7 @@ defined in self.namespace that match. """ + if text=="": return ['\t'] import keyword matches = [] n = len(text) """ Note that this prevents tab-completion not only at the beginning of the line but also at the beginning of a token, i.e. after a parenthesis or a comma etc. I don't know if it's possible to have the completer distinguish between the beginning of a token in the middle of the line and the beginning of the line, though. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 04:44:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 27 Jan 2008 09:44:49 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> Message-ID: <13pokkh4ilf5227@corp.supernews.com> On Sun, 27 Jan 2008 08:58:01 +0000, over wrote: > On Fri, 25 Jan 2008 17:44:07 -0800 (PST), ajaksu > wrote: > >>On Jan 25, 11:36 pm, ajaksu wrote: >>> On Jan 25, 11:10 pm, o... at thepond.com wrote: >>[...] >> >>Gaah, is this what's going on? >> >>ajaksu at Belkar:~$ cat error.txt >>This is not assembler... >> >>ajaksu at Belkar:~$ ndisasm error.txt >>00000000 54 push sp >>00000001 686973 push word 0x7369 00000004 206973 >>and [bx+di+0x73],ch 00000007 206E6F and [bp+0x6f],ch >>0000000A 7420 jz 0x2c >>0000000C 61 popa >>0000000D 7373 jnc 0x82 >>0000000F 656D gs insw >>00000011 626C65 bound bp,[si+0x65] 00000014 722E >> jc 0x44 >>00000016 2E db 0x2E >>00000017 2E db 0x2E >>00000018 0A db 0x0A >> >>:/ > > not sure what you're saying. Sure looks like assembler to me. Take the > '54 push sp'. The 54 is an assembler opcode for push and the sp is the > stack pointer, on which it is operating. Deary deary me... Have a close look again at the actual contents of the file: $ cat error.txt This is not assembler... If you run the text "This is not assembler..." through a disassembler, it will obediently disassemble the bytes "This is not assembler..." into a bunch of assembler opcodes. Unfortunately, although the individual opcodes are "assembly", the whole set of them together is nonsense. You'll see that it is nonsense the moment you try to execute the supposed assembly code. It would be a fascinating exercise to try to generate a set of bytes which could be interpreted as both valid assembly code *and* valid English text simultaneously. For interest, here you will find one quine (program which prints its own source code) which is simultaneously valid in C and TCL, and another which is valid in C and Lisp: http://www.uwm.edu/~chruska/recursive/selfish.html -- Steven From xkenneth at gmail.com Wed Jan 2 12:18:38 2008 From: xkenneth at gmail.com (xkenneth) Date: Wed, 2 Jan 2008 09:18:38 -0800 (PST) Subject: XML-XSD Processing/Creation. Message-ID: Hi All, So i'm working with the WITSML standard, which is a pretty massive standard defined in XML for the transfer of oilfield data. There are a ton of XSD files for defining and checking all data in the WITSML format. I'd like to be able to easily create XML based on the types defined by the WITSML XSD files. Is there any way to create a basic XML object based on an XSD file and then populate it with data. Can i create python classes based off the XSD files? What else can I do with the XSD files? I'm looking for a really simplistic way to work with WITSML in python. Regards, Kenneth Miller Thanks a ton! From martin at marcher.name Tue Jan 8 09:18:33 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 08 Jan 2008 15:18:33 +0100 Subject: use fileinput to read a specific line References: Message-ID: Fredrik Lundh wrote: > Martin Marcher wrote: > >>> i need to read line 4 from a header file >> >> http://docs.python.org/lib/module-linecache.html > > I guess you missed the "using linecache will crash my computer due to > memory loading, because i am working on 2000 files each is 8mb" part. oops sorry indeed still the enumerate version seems fine: >>> for no, line in enumerate(file("data.txt", "r")): ... print no, line ... someone posted this already i think (or was it another thread?) -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From max at alcyone.com Fri Jan 4 04:24:48 2008 From: max at alcyone.com (Erik Max Francis) Date: Fri, 04 Jan 2008 01:24:48 -0800 Subject: dictionary/hash and '1' versus 1 In-Reply-To: References: Message-ID: Reedick, Andrew wrote: > As a Perl monkey in the process of learning Python, I just stepped on > the "'1' (string) is not the same as 1 (integer) in regards to keys for > dictionaries/hashes" landmine. This isn't a landmine; this is a _good_ thing. Python is strongly typed. > Is there a good way to ensure that > numbers represented as strings or ints do not get mixed up as keys? Convert them all to either strings or integers (whichever is more useful) before you add them to the dictionary, really. > It's fugly to wrap every key reference in str(), ex: > foo[str(some_func(i))]. Then wrap it in a function or a method of one of your classes. You only need to write it once. > It's tedious to add a has_key before every key > lookup. There's no need to do this, though you don't say why you're bothering to. Either use .setdefault, or just query and get the exception, or just insert the new key, value pair to override the contents. > Any good solutions or accepted practices to prevent the intermixing of > number strings and integers as hash keys? A hash wrapper class seems to > be the best bet so far. If you want to make sure something is always done in a particular situation, then solution is to have a function or method that does that, and then just call that function or method. That's true in any language -- any one that has functions, anyway. -- 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 Laws are silent in time of war. -- Cicero From jpeng at block.duxieweb.com Mon Jan 21 00:16:37 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Mon, 21 Jan 2008 13:16:37 +0800 Subject: object scope In-Reply-To: <13p8803q11tm32d@corp.supernews.com> References: <13p8803q11tm32d@corp.supernews.com> Message-ID: <47942AB5.4040301@block.duxieweb.com> Dennis Lee Bieber ??: > The scope of "name" is the entire function; lacking a "global name" > statement, AND being on the left side of an assignment, it is a function > local name. Thank you. Does python have so-called 'block scope' object? or if you can,please show me the doc for python's object scope. From arnodel at googlemail.com Tue Jan 29 16:33:12 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 29 Jan 2008 13:33:12 -0800 (PST) Subject: breaking out of outer loops References: <20080129215513.3352a90d@hyperspace> Message-ID: On Jan 29, 8:55?pm, pataphor wrote: > On Tue, 29 Jan 2008 11:51:04 -0800 (PST) > > noemailplease0... at gmail.com wrote: > > Any elegant way of breaking out of the outer for loop than below, I > > seem to have come across something, but it escapes me > > > for i in outerLoop: > > ? ?for j in innerLoop: > > ? ? ? ?if condition: > > ? ? ? ? ? break > > ? ?else: > > ? ? ? ?continue > > ? ? break > > Ha! Think outside the box to begin with ... > > P. > > def cross(args): > ? ? ans = [[]] > ? ? for arg in args: > ? ? ? ? ans = [x+[y] for x in ans for y in arg] > ? ? return ans ? ? While we're at it, a generator version: def iproduct(head=None, *tail): if head is None: return ((),) else: return ((x,)+y for x in head for y in iproduct(*tail)) for a, b, c in iproduct('124', 'ab', 'AB'): print a, b, c ;-) -- Arnaud From pavlovevidence at gmail.com Fri Jan 18 20:08:53 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 18 Jan 2008 17:08:53 -0800 (PST) Subject: TopSort in Python? References: <0000161d@bossar.com.pl> <358cc5a3-300f-49ba-9857-2f0cd629a4df@i12g2000prf.googlegroups.com> Message-ID: <12f0f54e-5d30-40bc-9135-2c59b8a5acc2@i3g2000hsf.googlegroups.com> On Jan 18, 7:01 pm, Paddy wrote: > On Jan 18, 9:47 pm, startec... at gmail.com wrote:> Tim, > > > Thanks for the topsort code. It would be useful in a project I'm > > working on. Can I use the code for free under public domain? Thanks! > > When I needed one I didn't know the name. I'm curious, how did you > know to look for the topological sort algorithm by name? I spent quite a bit of time looking for this one myself. It was quite a stumper. Sometimes Google gets us in the habit of just firing random search terms when we ought to be thinking it out. After quite of bit of dead end searching--like a week--I stepped back, thought about what I was looking for. I wanted a sort of dependency system: A must happen before B. What other programs do that? make, of course. I looked at the documents for make and found the term "directed acyclic graph", and pretty much instantly knew I had it. (It seems silly in retrospect that I didn't think of graphs before that, but then it also seems silly no one invented movable type before 1436.) Once I had that term, a quick Google search led me to the Wikipedia article, which led me to the topsort algorithm. I did a dance of joy. Ten minutes later I saw it mentioned it on comp.lang.python. Carl Banks From samuel.progin at gmail.com Thu Jan 10 02:43:19 2008 From: samuel.progin at gmail.com (Sam) Date: Wed, 9 Jan 2008 23:43:19 -0800 (PST) Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> Message-ID: <68516e24-9393-46ec-9772-2e6ecd7dcee5@n20g2000hsh.googlegroups.com> > Unfortunately, I don't *think* I can shut the > warning for that line or function off, only for the entire file. > Pylint gives you a rating of your quality of code which I think is wrong :) # pylint: disable-msg=XXXXX will only impact the current line! $ cat -n dummy.py 1 for i in range(2): # pylint: disable-msg=W0612 2 print "foo" 3 for i in range(2): 4 print "foo" pylint will not generate a warning on line 1, but will on line 3! Cheers. Sam From PrinceOfDataMining at gmail.com Sat Jan 19 11:30:39 2008 From: PrinceOfDataMining at gmail.com (Samuel) Date: Sat, 19 Jan 2008 08:30:39 -0800 (PST) Subject: ANN:proxysocket(socks4,socks5)v0.1 References: <7228288b-cb34-40ba-8483-a2dc57115511@d21g2000prf.googlegroups.com> Message-ID: <14b208ca-f2ea-44bd-823a-6c0070b8162e@d21g2000prg.googlegroups.com> v0.2 http://proxysocket.googlecode.com/files/ProxySocket.py On 1?18?, ??3?04?, Tim Roberts wrote: > Samuel wrote: > > >http://code.google.com/p/proxysocket/downloads/list > > Allow me to introduce you to the concept of comments. Python allows you to > include descriptive sentences in your program that explain what the > functions do, what your intentions were, what the variables do, what the > states mean, etc. It's easy to do; you just start the text with # signs. > > # This function allows you to ... > > # These variables define the connection state as the connection is > # made. > > They're great. You should try them. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From steve at holdenweb.com Thu Jan 31 06:09:21 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 06:09:21 -0500 Subject: Design question - Sharing of single object by multiple processes In-Reply-To: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> References: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> Message-ID: <47A1AC61.7080007@holdenweb.com> Mike D wrote: > Hello, I've just picked up the Python language and am really enjoying it. > > I've just signed up to this mailing list and I'm looking forward to > taking part in some discussions. > > My first post is a question I've been pondering for the last couple of days: > > For relatively static data (such as a list), is it possible to load a > single instance and have many python processes access it? > First there's the problem of having multiple processes access any kind of shared resource. So your question makes me wonder whether you mean processes, or threads. Are you *sure* you mean processes? > I want to have an object in memory. This object will be loaded on > application start up and will contain a list of objects. These will be > obtained from (most likely) the file system. > So "application startup" is different from "process startup"? Your application is a group of co-operating processes? Really? > My reasoning is: I want to prevent a file system or database fetch each > time as it seems unnecessary. > It might also seem unnecessary to start the Python interpreter for each process, but you are going to have to ... > Is this possible? In Java I'm pretty sure this could implemented with an > object factory and static methods. My understanding is that python > invokes a separate process for each request however. > Your understanding is clearly informed by some information you have omitted to share with us. > If possible, what would be a good way of providing a new structure as it > is updated. > > If anyone could give me some advice or point me in the correct direction > I'd really appreciate it. > > Thanks in advance, > More answers, please. There are mechanisms such as Pyro (Python remote objects) that allow inter-process method calls, but I am far from convinced that's what you really want (or need, anyway). Perhaps yo could let us know a little more about what it really is you are trying to do, and convince me, at least, that this isn't just a case of premature optimization. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From siona at chiark.greenend.org.uk Wed Jan 9 08:00:51 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Jan 2008 13:00:51 +0000 (GMT) Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <5ujp0tF1ehvg2U1@mid.dfncis.de> Message-ID: Robert Latest wrote: > BTW, where can I find all methods of the built-in types? >Section 3.6 only talks about strings and mentions the list append() method >only in an example. Am I too stupid to read the manual, or is this an >omission? 3.6 talks about features common to all "sequence" types. Strings are discussed specifically in 3.6.1 ("String Methods"). Lists are similarly discussed in 3.6.4 ("Mutable Sequence Types"). They are certainly not omitted, although maybe the title of 3.6.4 could be take a leaf from the Zen and be more explicit. -- \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 ms at cerenity.org Sat Jan 12 18:11:23 2008 From: ms at cerenity.org (Michael Sparks) Date: Sat, 12 Jan 2008 23:11:23 +0000 Subject: [Kamaelia] TCPClient: How to sense connection failure? References: <5uq49vF1jkgcoU1@mid.individual.net> Message-ID: <13oiho63bri4c76@corp.supernews.com> Bjoern Schliessmann wrote: > Hello, > > I'm currently trying to implement a simulation program with Kamaelia > and need a reliable TCP connection to a data server. The behaviour you're seeing sounds odd (which is hopefully encouraging :-), but it's not clear from the description whether its a bug in your code or Kamaelia. One question I really have as a result is what version are you using? Current release version 0.5.0, the version on /trunk, or the bleeding edge version on /branches/private_MPS_Scratch. (I'm using the latter to run my greylisting server - as are a few others). All that said though, looking at the differences between versions, I'm not convinced they're large enough to show the problem you're seeing. I'm not about to rule out a bug I don't know about though :-) > From Twisted, I know that a method is called if the connection fails > by whatever reason. I tried to get the same results with Kamaelia's > TCPClient component. If I start up the component and try to connect > to a closed TCP port it fails and sends a message out of the signal > box, that's okay. If you'd prefer more information in that message, please let me know. (all components send out a message when they shutdown. For things that send data out as one of their primary actions send out a producerFinished message) > But if the connection attempt succeeds and, after some time, the > server drops the connection with full TCP handshake (FIN, FIN+ACK, > ACK), the component just hangs and does nothing. Is this by design, > or could there be an error in my setup? It sounds like an error in your setup... but I hate saying that. (Doesn't tell me or you what it is, and doesn't help change things to discourage or detect mistakes in usage) When the server drops the connection in my setups, the client disconnects cleanly when the server dies, with the client code looking like this: self.send(producerFinished(self,self.howDied), "signal") Meaning you get a message telling you how the component shutdown as well as the fact it shutdown. (If "howDied" is None, it's just a normal shutdown - ie as a result of being told to shut down) The function where this is managed is runClient in the class Kamaelia.Internet.TCPClient.TCPClient (fully qualified name) The actual socket connections are handled by a class called ConnectedSocketAdapter which manages all logic of checking for errors, remote shutdown etc. That works the same for both servers and clients so breakage in clients would show up as breakage in servers as well, which would be particularly bad. > Also, how long does a TCPClient component live -- or how can/should > I terminate it explicitly? I'm afraid that if I create > a "ReconnectingTCPClient" component, it could eat up memory over > long runtime with hanging TCPClients. That shouldn't be an issue (I hate the word "should"), but you can do this using a carousel component. (I ought to write that as an example of how to use the Carousel component) In the meantime - whilst I check to see if there's a bug I didn't know about, the following 2 cookbook entries may be of use: * http://kamaelia.sourceforge.net/Cookbook/TCPSystems * http://kamaelia.sourceforge.net/Cookbook/Carousels - allows you to make something that exits reusable. It's a little awkward to get your head around, but is quite useful when you do. (I've heard of others using Carousel & TCPClient to make a reconnecting TCPClient in the past) All that said, I'm not going to rule out a bug and look into it. (if you have a simple example you find fails, please forward it to me :) *thinks* The following code may also be useful when debugging: from Kamaelia.Chassis.Pipeline import Pipeline class PeriodicWakeup(Axon.ThreadedComponent.threadedcomponent): interval = 300 def main(self): while 1: time.sleep(self.interval) self.send("tick", "outbox") class WakeableIntrospector(Axon.Component.component): def main(self): while 1: Q = [ q.name for q in self.scheduler.listAllThreads() ] Q.sort() print "*debug* THREADS"+ str(Q) self.scheduler.debuggingon = False yield 1 while not self.dataReady("inbox"): self.pause() yield 1 while self.dataReady("inbox"): self.recv("inbox") Pipeline( PeriodicWakeup(), WakeableIntrospector(), ).activate() If you put this code somewhere before your "run" call, you'll get periodic output to tell you what's running. When debugging manually I'd drop the interval to 3-10 seconds or so. I use 300 for a server. Now, off to see if I can reproduce your problem... :) Regards, Michael. -- http://kamaelia.sourceforge.net/Home http://yeoldclue.com/blog From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jan 24 10:14:28 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 24 Jan 2008 16:14:28 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <5vroakF1o4jkvU1@mid.individual.net> Tim Roberts wrote: > Bjoern Schliessmann >> So, how do processors execute Python scripts? :) > > Is that a rhetorical question? A little bit. > Grant is quite correct; Python scripts (in the canonical CPython) > are NOT compiled into assembly language. Scripts are compiled to > an intermediate language. Processors execute Python scripts when > the interpreter, written in a high-level language and compiled to > assembly, interprets the intermediate language created by the > Python "compiler". So in the end, the program defined in the Python script _is_ compiled to the CPU's language. But never mind, it depends on how you define "compile" in the end. Regards, Bj?rn -- BOFH excuse #225: It's those computer people in X {city of world}. They keep stuffing things up. From ajaksu at gmail.com Sun Jan 6 08:15:31 2008 From: ajaksu at gmail.com (ajaksu) Date: Sun, 6 Jan 2008 05:15:31 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> <617182dc-3ca1-4cf5-b1ca-1779dd8d6550@i3g2000hsf.googlegroups.com> Message-ID: <1926019f-bf46-4fbb-990d-ed0b9cf18353@n20g2000hsh.googlegroups.com> On Jan 5, 11:36 pm, c... at mailinator.com wrote: > > This one is good. Someone commented that you destroy the list, but > that can be fixed: > > def pick_random(seq, prop): > L = len(seq) > for i in xrange(L): > r = random.randrange(L - i) > if prop(seq[r]): > return seq[r] > seq[r], seq[L - i - 1]= seq[L - i - 1],seq[r] > > just pushing elements without the property to the end of the list > (list is mutated, true, but shuffle will do that too). In each > iteration of the for loop, there is only one random element, one check > of the property, and rebinding of elements without altering the lenght > of the list. This is optimal and has all the functionality. > > Two more comments: > for buzcor: deleting an element in the middle of a list is costly > for martin: that is certainly enough for me > > Thanks everybody! How about some benchmarks as a token of gratitude? ;) Or at least a nice hint on your expected number of lists (and their sizes) :) From pakmarshal at gmail.com Wed Jan 23 04:37:17 2008 From: pakmarshal at gmail.com (pakmarshal at gmail.com) Date: Wed, 23 Jan 2008 01:37:17 -0800 (PST) Subject: InstallShield file properties issues Message-ID: Hi, I am using Install Shield 11 express to create an upgrade package (msi) and came across an issue i.e. when installer installs the package it changes the created date of the files to modified date (changes created date with modified date), in my situation the files have modified date newer than the created date on source system and which I want to retain on the target system. That date difference helps me not to over write these files in next upgrade package. My questions are why Install Shield is showing that behavior or is there another reason for this? Is there any way to retain the created date, originally the file has? For this purpose I tested Install Shield's file properties options i.e. "Use System Attributes" which is used as, file installed with the same properties that it has on the development system, but it don't seems to be working in my case. Regards, Hassan From winjer at gmail.com Thu Jan 3 11:39:36 2008 From: winjer at gmail.com (winjer at gmail.com) Date: Thu, 3 Jan 2008 08:39:36 -0800 (PST) Subject: Fate of itertools.dropwhile() and itertools.takewhile() References: <7a86a421-089f-4634-8902-e9edfe139f03@e23g2000prf.googlegroups.com> Message-ID: <33c108cb-4378-4f34-bc52-b179772a73cb@n20g2000hsh.googlegroups.com> On Dec 29 2007, 11:10 pm, Raymond Hettinger wrote: > I'm considering deprecating these two functions and would like some > feedback from the community or from people who have a background in > functional programming. Well I have just this minute used dropwhile in anger, to find the next suitable filename when writing database dumps using date.count names: filename = "%02d-%02d-%d" % (now.day, now.month, now.year) if os.path.exists(filename): candidates = ("%s.%d" % (filename, x) for x in count(1)) filename = dropwhile(os.path.exists, candidates).next() Much clearer than the alternatives I think, please keep dropwhile and takewhile in itertools ;) Cheers, Doug. From emin.shopper at gmail.com Thu Jan 3 11:24:13 2008 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Thu, 3 Jan 2008 11:24:13 -0500 Subject: How do you pass compiler option to setup.py install? Message-ID: <32e43bb70801030824p7099da66s6ffb4ee0ea58b311@mail.gmail.com> Dear Experts, How do you pass the -c option to setup.py install? Specifically, when I try to install zope.interfaces version 3.3 from source on a windows machine, I get a message about using "-c mingw32". That works fine for setup.py build, but it does not work for "setup.py install". Note: I would have just used the binary installer for windows but couldn't find one for version 3.3. Thanks, -Emin -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at marcher.name Wed Jan 9 11:56:39 2008 From: martin at marcher.name (Martin Marcher) Date: Wed, 09 Jan 2008 17:56:39 +0100 Subject: printing dots in simple program while waiting References: Message-ID: John wrote: > import time > s = '.' > print 'working', # Note the "," at the end of the line > while True: > print s > time.sleep(1) see my comment in the code above... if that's what you mean /martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From DustanGroups at gmail.com Sat Jan 12 18:08:18 2008 From: DustanGroups at gmail.com (Dustan) Date: Sat, 12 Jan 2008 15:08:18 -0800 (PST) Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> <7xprw6g59t.fsf@ruckus.brouhaha.com> Message-ID: <6bcd73cf-8d36-4592-80e4-fefeb189090c@f10g2000hsf.googlegroups.com> On Jan 12, 2:25 pm, Paul Rubin wrote: > marcstuart writes: > > what I would like to get is 3 sublists > > > print z[0] = [1,2,3] > > print z[2] = [4,5,6] > > print z[3] = [7,8,9,10] > > Are you SURE you want that? In almost every situation I've seen, > > print z[0] = [1,2,3] > print z[2] = [4,5,6] > print z[3] = [7,8,9] > print z[4] = [10] > > is preferable. Even more preferable is: print z[0] = [1,2,3] print z[1] = [4,5,6] print z[2] = [7,8,9] print z[3] = [10] From asmodai at in-nomine.org Sat Jan 26 08:56:02 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 26 Jan 2008 14:56:02 +0100 Subject: Doesn't know what it wants In-Reply-To: <13plo358k5rf059@corp.supernews.com> References: <13plo358k5rf059@corp.supernews.com> Message-ID: <20080126135602.GI1050@nexus.in-nomine.org> -On [20080126 08:31], Steven D'Aprano (steve at REMOVE-THIS-cybersource.com.au) wrote: >The OP's code calls vec2d with a single tuple argument (0,0). Jeroen's >version calls vec2d with two int arguments, 0 and 0. Yes, but it was not what I intended at all. I guess I am just a bit too used to tacking on a , to denote a tuple since in almost every other language seeing (()) is just an additional layer of braces. I had totally forgotten Python would make it a tuple. And I guess my head was still stuck with some other languages as well when I made my other suggestion. Mea culpa. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ We have met the enemy and they are ours... From jimis at gmx.net Wed Jan 2 16:03:52 2008 From: jimis at gmx.net (Dimitrios Apostolou) Date: Wed, 2 Jan 2008 23:03:52 +0200 Subject: urllib2 disable proxy Message-ID: <200801022303.53722.jimis@gmx.net> Hello list, I've been looking for a way to explicitly disable the use of proxies with urllib2, no matter what the environment dictates. Unfortunately I can't find a way in the documentation, and reading the source leads me to believe that something like the following does the job: req.set_proxy(None,None) Where req is a urllib2.Request instance. So is there an official way of doing this? Perhaps it should be added in the documentation? Thanks in advance, Dimitris From patrick.waldo at gmail.com Wed Jan 2 09:33:00 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Wed, 2 Jan 2008 06:33:00 -0800 (PST) Subject: Pivot Table/Groupby/Sum question References: <148c3214-77b9-47b0-a680-ffb85dd3efcd@e6g2000prf.googlegroups.com> <2ada2837-7625-43c1-8264-5edc9046fbc8@i29g2000prf.googlegroups.com> <7f396128-2ce2-4dd6-bdc0-855bab8750c7@w38g2000hsf.googlegroups.com> <9f7b6dcc-216d-46a9-a9d5-022c00ee9d7d@d21g2000prf.googlegroups.com> <1caf93fd-3a50-4c77-87b0-5312cdebd35f@d21g2000prf.googlegroups.com> <63a5a87e-3385-4ef0-80a3-cd1a01eeeac3@w38g2000hsf.googlegroups.com> <276d150b-6b2a-4973-8569-bd8cad6df948@s19g2000prg.googlegroups.com> <018c37d5-67c0-4995-88e3-86f701580c26@e23g2000prf.googlegroups.com> Message-ID: <5d6721cc-1912-4adc-9e47-0afa21c51c89@21g2000hsj.googlegroups.com> Sorry for the delay in my response. New Year's Eve and moving apartment > - Where the data come from (I mean: are your data in Excel already > when you get them)? > - If your primary source of data is the Excel file, how do you read > data from the Excel file to Python (I mean did you solve this part of the task already)? Yes, the data comes from Excel and I use xlrd and PyExcelerator to read and write, respectively. #open for reading path_file = "c:\\1\\data.xls" book = xlrd.open_workbook(path_file) Counts = book.sheet_by_index(1) #get data n=1 data = [] while n References: Message-ID: <4784FEF9.9080807@tim.thechases.com> Martin Marcher wrote: > John wrote: > >> import time >> s = '.' >> print 'working', # Note the "," at the end of the line >> while True: >> print s, #Note the "," at the end of this line too... >> time.sleep(1) > > see my comment in the code above... see my added comment in the code above... Though this will produce spaces between the dots: waiting . . . . . . To eliminate the spaces, you need to write to a file-stream such as sys.stdout: from sys import stdout stdout.write('working') while True: stdout.write('.') # might need something like stdout.flush() here time.sleep(1) stdout.write('\n') -tkc From steve at holdenweb.com Thu Jan 31 10:31:43 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 10:31:43 -0500 Subject: Fwd: Re: Problems installing Python on server In-Reply-To: <200801310946.50733.inq1ltd@inqvista.com> References: <3bf78e92-1c95-4255-95fd-ca17c81d215b@i29g2000prf.googlegroups.com> <200801310946.50733.inq1ltd@inqvista.com> Message-ID: jim-on-linux wrote: > > >>> Also be careful and setup all the paths >>> that is required for compiling various >>> Python modules etc. >>> >>> On Jan 29, 8:28 am, Yansky >> wrote: >>>> I asked my hosting company if they >>>> would upgrade Python on my server to >>>> the latest version. They responded >>>> with: >>>> >>>> "Sorry no. We tend to stick with what >>>> comes packaged with the unix >>>> distribution to ease maintenance >>>> issues. >>>> >>>> There is nothing stopping you from >>>> running your own version of python >>>> from within your own account. Download >>>> the source and compile it and install >>>> it into your own space. Adjust the >>>> fist line of your python scripts to >>>> reflect the location of YOUR python >>>> binary: >>>> >>>> #! /home/youraccount/yourlibs/python >>>> >>>> and you should be all set." >> Go to the ReadME file after you unpack >> python. >> Open and look for "Installing". >> Read the section, it explains how to >> install on the entire system and how to >> install locally. >> "Make altinstall" is what you are looking >> for. >> >> jim-on-linux >> http:\\www.inqvista.com >> >>>> The build instructions for Python are: >>>> To start building right away (on >>>> UNIX): type "./configure" in the >>>> current directory and when it >>>> finishes, type "make". This creates an >>>> executable "./python"; to install in >>>> usr/local, first do "su root" and then >>>> "make install". >>>> >>>> The problem is, I don't have root >>>> access to the server so I can't do the >>>> "make install". I have ubuntu on my >>>> computer, but from what I understand I >>>> can't compile it on that and upload it >>>> because the server runs Red Had and >>>> the ./configure would have made it >>>> incompatible right? >>>> >>>> So how can I build Python without root >>>> access? > > Will the "make install" make my Python the > default one? If I want to install some > Python modules, will I need to alter their > installation as well or will it see my > Python version as the right one to install > too? > The "default one"? That's just the one that runs when a user enters the python command, right? "make install" will install Python wherever you told the configure utility to build it for. "make altinstall" is a convenience method that (IIRC) builds for /usr/local/bin. Generally speaking when you install an extension or other module, nowadays you use the command python setup.py install The installation takes place in whichever copy of Python runs setup.py, so with a "default" /usr/bin/python and an "alternate" /usr/local/bin/python, to install a module in the alternate you would run /usr/local/bin/python setup.py install The same is true of a Python you have installed somewhere under your home directory. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From savinovboris at gmail.com Tue Jan 22 12:35:16 2008 From: savinovboris at gmail.com (Boris) Date: Tue, 22 Jan 2008 09:35:16 -0800 (PST) Subject: Using utidylib, empty string returned in some cases Message-ID: <69c38011-4af7-4305-95fb-c824019c1550@v4g2000hsf.googlegroups.com> Hello I'm using debian linux, Python 2.4.4, and utidylib (http:// utidylib.berlios.de/). I wrote simple functions to get a web page, convert it from windows-1251 to utf8 and then I'd like to clean html with it. Here is two pages I use to check my program: http://www.ya.ru/ (in this case everything works ok) http://www.yellow-pages.ru/rus/nd2/qu5/ru15632 (in this case tidy did not return me anything just empty string) code: -------------- # coding: utf-8 import urllib, urllib2, tidy def get_page(url): user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)' headers = { 'User-Agent' : user_agent } data= {} req = urllib2.Request(url, data, headers) responce = urllib2.urlopen(req) page = responce.read() return page def convert_1251(page): p = page.decode('windows-1251') u = p.encode('utf-8') return u def clean_html(page): tidy_options = { 'output_xhtml' : 1, 'add_xml_decl' : 1, 'indent' : 1, 'input-encoding' : 'utf8', 'output-encoding' : 'utf8', 'tidy_mark' : 1, } cleaned_page = tidy.parseString(page, **tidy_options) return cleaned_page test_url = 'http://www.yellow-pages.ru/rus/nd2/qu5/ru15632' #test_url = 'http://www.ya.ru/' #f = open('yp.html', 'r') #p = f.read() print clean_html(convert_1251(get_page(test_url))) -------------- What am I doing wrong? Can anyone help, please? From arnodel at googlemail.com Tue Jan 29 05:34:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 29 Jan 2008 02:34:10 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <92b67efe-c437-40bc-89fc-bbdd85d6e718@s19g2000prg.googlegroups.com> <816442e1-be46-4543-88dc-1b328ced7231@j20g2000hsi.googlegroups.com> Message-ID: <8a7722da-7dd4-4135-862d-baec92b79abb@e25g2000prg.googlegroups.com> On Jan 29, 9:02?am, david.hot... at blueyonder.co.uk wrote: Oops I sent too quickly... > If you've found an efficient way to walk through the possible > solutions only once, then > - ?I expect that yours will be faster > - ?and well done! > > I guess I should try to understand your code... My code is quite naive and I suspect that combining your caching and the tree pruning discussed in this thread would yield faster results. Not sure if I'll have time to try this though... -- Arnaud From steven at REMOVE.THIS.cybersource.com.au Sun Jan 6 22:42:11 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 Jan 2008 03:42:11 -0000 Subject: Delete lines containing a specific word References: <5ud6qgF1hlfdaU1@mid.individual.net> Message-ID: On Mon, 07 Jan 2008 00:33:36 +0100, Bjoern Schliessmann wrote: > Steven D'Aprano wrote: > >> grep doesn't delete lines. grep matches lines. If you want to delete >> them, you still have to do the rest of the job yourself. > > In which way does "grep -v mypattern myfile > myfile" not delete the > lines matching mypattern? Okay, that will delete the lines matching mypattern. Unfortunately it will also delete all the lines NOT matching mypattern as well. Try it for yourself -- just not on anything you care about. This is what happens when abstractions leak. You *think* you're deleting lines, but you're not. That's just an abstraction, and when it leaks, you break things. -- Steven From jr9445 at ATT.COM Mon Jan 14 12:08:02 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Mon, 14 Jan 2008 11:08:02 -0600 Subject: __init__ explanation please In-Reply-To: <873at0mkv7.fsf@mulj.homelinux.net> References: <47895d25$0$30708$4c368faf@roadrunner.com><20080113104641.GN75977@nexus.in-nomine.org><478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net><87myr8v3p4.fsf@mulj.homelinux.net> <873at0mkv7.fsf@mulj.homelinux.net> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Hrvoje Niksic > Sent: Monday, January 14, 2008 11:29 AM > To: python-list at python.org > Subject: Re: __init__ explanation please > > Mel writes: > > >> I don't understand the purpose of this "correction". After all, > >> __init__ *is* the closest equivalent to what other languages would > >> call a constructor. > > > > Nevertheless, __init__ doesn't construct anything. > > Only if by "construct" you mean "allocate". __init__ starts out with > an empty object and brings it to a valid state, therefore > "constructing" the object you end up with. That operation is exactly > what other languages call a constructor. Nah. Most other languages combine the constructor and an init function. Normally with c++ I'll have the constructor call an Init() function so I can re-initialize the object as needed. Python has explicitly split the two. Besides, the Python docs say that __new__ is the constructor and __init__ may or may not be called after the instance is created: __new__( cls[, ...]) Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls). ... If __new__() returns an instance of cls, then the new instance's __init__() method will be invoked ... If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked. __init__( self[, ...]) Called when the instance is created. ... As a special constraint on constructors, no value may be returned; Also, how can a constructor require 'self' as an argument...? __init__(self, ...) If the __init__ function is called by the constructor it cannot return a value. However if called as a normal function, it can return a value. __init__ is just a function that gets called by the constructor, which is __new__. count = 0 class AClass (object): def __init__ (self): self.a = 4 global count if count > 0: return 'hello world' count += 1 a = AClass() print a.a print a.__init__() c:\foo\a.py> 4 hello world ***** 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. GA622 From fredrik at pythonware.com Sun Jan 20 07:43:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jan 2008 13:43:56 +0100 Subject: Okay I got a question regarding Tkinter and Labels In-Reply-To: References: Message-ID: Lamonte Harris wrote: > Okay I've created a script and basically when I loop through a folder it > is supposed to change the Label everytime it updates a file then again > it doesn't do nothing but shows the last file edited, whats the best way > to loop through files and display that file name in a Label's text > without skipping to the last one when the loop is finished? Tkinter is event-driven, and you need to keep the event loop running to make sure that changes to the widgets makes it to the screen. Usually, this is handled by the "mainloop" function, but if you're spending considerable time at the Python level, you need to call the "update" or "update_idletasks" methods from time to time to give Tkinter a chance to process incoming events. In your case, you can simply call the method after you've modified the label: label.config(text="something") label.update() Hope this helps! From BjornSteinarFjeldPettersen at gmail.com Sun Jan 13 07:55:04 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 13 Jan 2008 04:55:04 -0800 (PST) Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> <00cb6e9d-e8b6-4e65-be58-5a4472413c53@j78g2000hsd.googlegroups.com> Message-ID: <64a76486-2dd2-4a09-bc4f-0a1ddf49ba89@f3g2000hsg.googlegroups.com> On Jan 13, 1:05 pm, thebjorn wrote: > On Jan 12, 8:33 pm, Fredrik Lundh wrote: > > > > > marcstuart wrote: > > > How do I divide a list into a set group of sublist's- if the list is > > > not evenly dividable ? consider this example: > > > > x = [1,2,3,4,5,6,7,8,9,10] > > > y = 3 # number of lists I want to break x into > > > z = y/x > > > > what I would like to get is 3 sublists > > > > print z[0] = [1,2,3] > > > print z[2] = [4,5,6] > > > print z[3] = [7,8,9,10] > > > > obviously not even, one list will have 4 elements, the other 2 will > > > have 3., > > > here's one way to do it: > > > # chop it up > > n = len(x) / y > > z = [x[i:i+n] for i in xrange(0, len(x), n)] > > > # if the last piece is too short, add it to one before it > > if len(z[-1]) < n and len(z) > 1: > > z[-2].extend(z.pop(-1)) > > > > > Eh... > > def chop(lst, length): > n = len(lst) / length > z = [lst[i:i+n] for i in xrange(0, len(lst), n)] > if len(z[-1]) < n and len(z) > 1: > z[-2].extend(z.pop(-1)) > return z > > gives > > >>> chop(range(1,9), 3) > > [[1, 2], [3, 4], [5, 6], [7, 8]]>>> chop(range(1,8), 3) > > [[1, 2], [3, 4], [5, 6, 7]]>>> chop(range(1,6), 3) > > [[1], [2], [3], [4], [5]]>>> chop([1], 3) > > Traceback (most recent call last): > File "", line 1, in > File "beforemeth.py", line 9, in chop > if len(z[-1]) < n and len(z) > 1: > ValueError: xrange() arg 3 must not be zero > > Perhaps something like this? > > def chop(lst, length): > from itertools import islice > it = iter(lst) > z = [list(islice(it, length)) for i in xrange(1 + len(lst) // > length)] > if len(z) > 1: > z[-2].extend(z.pop()) # the last item will be empty or contain > "overflow" elements. > return z > > -- bjorn Bad for to reply to myself, I know, but I just realized that the OP wanted to control the _number_ of chunks, not the size of the chunks... Building on the above would give something like from itertools import islice from operator import add def chop(lst, nchunks): chunksize, extra = divmod(len(lst), nchunks) if not chunksize: raise ValueError('More chunks than elements in list.') it = iter(lst) z = [list(islice(it, chunksize)) for i in xrange(nchunks + extra)] z, extra = z[:nchunks], z[nchunks:] z[-1].extend(reduce(add, extra, [])) # because sum ain't add :-( return z -- bjorn From Brett.Friermood at gmail.com Tue Jan 22 11:23:11 2008 From: Brett.Friermood at gmail.com (Brett.Friermood at gmail.com) Date: Tue, 22 Jan 2008 08:23:11 -0800 (PST) Subject: Curses and Threading References: <3924ad84-a513-4b25-b9af-cbd358f5d40a@i3g2000hsf.googlegroups.com> Message-ID: > In fact you have *two* threads: the main thread, and the one you create > explicitly. > After you start the clock thread, the main thread continues executing, > immediately entering the finally clause. > If you want to wait for the other thread to finish, use the join() method. > But I'm unsure if this is the right way to mix threads and curses. This is what the python documentation says: join([timeout]) Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates. So according to this since I need to block the main thread until the clock thread ends I would need the main thread to call "cadtime().join()", correct? I'm not sure how to do this because I don't have a class or anything for the main thread that I know of. I tried putting that after cadtime().start() but that doesn't work. I guess what I'm trying to say is how can I tell the main thread what to do when it doesn't exist in my code? Thanks for the help -Brett From tjreedy at udel.edu Mon Jan 28 22:58:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jan 2008 22:58:52 -0500 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com><479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net><60411eF1ors2pU1@mid.uni-berlin.de><479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net><7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13pqd16n4o3rufe at corp.supernews.com... | I don't like the name convention. _name already has a perfectly good | convention: it's a private name, don't mess with it. That includes in | function/method signatures. With your convention, _foo is public. Since local names, including params are inaccesible outside a function, I don't see how the convention applies. However, the underscore could just as well go at the end of the name. There no current convention I know of with that. tjr From fredrik at pythonware.com Fri Jan 18 13:11:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 18 Jan 2008 19:11:14 +0100 Subject: Bug in __init__? In-Reply-To: References: Message-ID: Zbigniew Braniecki wrote: > It's really a nice pitfall, I can hardly imagine anyone expecting this, > or how easily could I find this info (e.g. what query should I give to > google to get it without bothering people on this group) looking things up in the documentation *before* deciding that you might have done something that nobody's done before is often a good idea: http://docs.python.org/tut/node6.html#SECTION006710000000000000000 "Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. /.../" http://docs.python.org/ref/function.html "Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same ``pre-computed'' value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary /.../ (to be precise, the default values are evaluated when the "def" state- ment is executed, in the same scope as the "def" statement itself. if you execute the same "def" statement multiple times, the values are recalculated.) From myth at spam.no Thu Jan 3 02:51:08 2008 From: myth at spam.no (Thin Myrna) Date: Thu, 03 Jan 2008 08:51:08 +0100 Subject: PyInstaller: Need some hints (perhaps a good example?) Message-ID: <477c93e9$0$29612$5402220f@news.sunrise.ch> I gave PyInstaller a shot and was pleased by the results so far. The usual problems occurred with missing data and icon files (the latter for splash screens only). However, it's a bit hard for me to overcome them. I tried COLLECT but the files don't seem to be added to the install. The reason is most likely, that I dont know, where to put the result of COLLECT: Is it pyz, is it exe, or...? Is anyone willing to post an example or two here, how this is done? Kind regards Thin From sjmachin at lexicon.net Tue Jan 15 16:58:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 15 Jan 2008 13:58:44 -0800 (PST) Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: <8a1bd1ac-037f-49ee-91e8-9875ed0a1b43@k39g2000hsf.googlegroups.com> On Jan 16, 3:25 am, "Colin J. Williams" wrote: Colin W. > > I'm sorry, there appears to be a bug: There is, but but not where you think it is :-) > # tSet.py > import sets [not the bug] Earlier evidence is that you are using 2.5.1; why import sets?? > s1= sets.Set([1, 2, 3]) > s1.union_update([3, 4,5]) > print(s1) > s2= sets.Set([6, 7, 8]) > s1 |+ s2 # This fails: > exceptions.TypeError: bad operand type > for unary +: 'Set' Try reading and understanding the exception message ... "unary +" as in the syntactically equivalent expression s1 | +s2 HTH, John From fredrik at pythonware.com Thu Jan 10 13:07:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 19:07:58 +0100 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: A.T.Hofkamp wrote: > Now the question you need to answer for yourself, is how much more worth is > your own time compared to the gain in CPU time. If you think they are equal (ie > the problem as a whole should be solved as fast as possible, thus the sum of > development time + execution time should be as short as possible), you can > spend an additional 1.5 seconds development in the alternative solution. so you only run your programs once? From hyugaricdeau at gmail.com Fri Jan 11 09:49:09 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Fri, 11 Jan 2008 06:49:09 -0800 (PST) Subject: Help needed References: Message-ID: On Jan 10, 9:15 pm, tijo wrote: > Hi mate > > i need o do a python program to connect 2 systems using TCP/IP and > UDP. Also i need to check the performance of these two protocols (how > many bytes received and how much time took). I havent worked in python > earlier and have no idea of this. Could someone pls help me. I created > a program which can connect between 2 systems using these UDP and TCP/ > IP protocols. I dont know how to check the rest like how many bytes > send or how much time taken > since this is part of my course work could someone please help me > thanks in advance. > > tijo The standard library documentation, while lacking in some areas, is very much your friend here: >From http://docs.python.org/lib/socket-objects.html (emphasis mine) send(string[, flags]) Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. *Returns the number of bytes sent.* recv(bufsize[, flags]) Receive data from the socket. The return value is a string representing the data received. For timing you can probably use the timeit module (http:// docs.python.org/lib/module-timeit.html) but I'm not really sure how you're defining "performance". I mean, I can already tell you that overall UDP will be "faster", as it has much less overhead. Surely your course has covered this... Hyuga From fredrik at pythonware.com Mon Jan 7 17:55:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 23:55:31 +0100 Subject: Tkinter variable trace problem In-Reply-To: <17687-68562@sneakemail.com> References: <17687-68562@sneakemail.com> Message-ID: C Martin wrote: > What am I doing wrong in this code? The callback doesn't work from the Entry widget. > > ##start code > import Tkinter > > tk = Tkinter.Tk() > var = Tkinter.StringVar() > print var._name > > def cb(name, index, mode): > print "callback called with name=%r, index=%r, mode=%r" % (name, index, mode) > varValue = tk.getvar(name) > print " and variable value = %r" % varValue iirc, getvar only looks at local Tcl variables when used inside a callback. variables created with StringVar are global Tcl variables. but instead of monkeying around at the Tcl level, why not just solve this on the Python level instead? def cb(variable, name, index, mode): ... var.trace('w', lambda *args: cb(var, *args)) # or some variation thereof (and for this specific case, Entry content tracking, binding to KeyRelease and possibly also ButtonRelease is usually good enough). From ptmcg at austin.rr.com Fri Jan 18 17:35:46 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 18 Jan 2008 14:35:46 -0800 (PST) Subject: strange syntax rules on list comprehension conditions References: Message-ID: On Jan 18, 1:04?pm, "Chris Mellon" wrote: > On Jan 18, 2008 12:53 PM, Nicholas wrote: > > > I was quite delighted today, after extensive searches yielded nothing, to > > discover how to place an else condition in a list comprehension. > > Trivial mask example: > > >>> [True if i <5 else False for i in range(10)] ? ? ? # A > > [True, True, True, True, True, False, False, False, False, False] > I think this would be preferred over your ternary-ish expression: >>> [ i<5 for i in range(10) ] [True, True, True, True, True, False, False, False, False, False] Do you also write code like: if i<5 == True: blah... If so, please just write: if i<5: better blah... -- Paul From Russ.Paielli at gmail.com Sun Jan 27 17:52:59 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 14:52:59 -0800 (PST) Subject: optional static typing for Python References: Message-ID: On Jan 27, 2:36 pm, Jarek Zgoda wrote: > Russ P. pisze: > > > I noticed that Guido has expressed further interest in static typing > > three or four years ago on his blog. Does anyone know the current > > status of this project? Thanks. > > I thought it was april fools joke? On January 21, 2000? Which calendar do you use? From Russ.Paielli at gmail.com Mon Jan 28 05:21:23 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jan 2008 02:21:23 -0800 (PST) Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> <479da620$0$25625$426a74cc@news.free.fr> Message-ID: <13067a3e-bce7-45ea-beba-4dc83c749a72@i12g2000prf.googlegroups.com> On Jan 28, 1:53 am, Bruno Desthuilliers wrote: > Russ P. a ?crit : > > > > > On Jan 27, 5:03 pm, Paddy > > >> If static typing is optional then a program written in a dynamic > >> language that passes such an automated static analysis of source code > >> would have to be a simple program written in a simplistic way, and > >> also in a static style. > > > Yes, but for safety-critical software you usually want the simplest > > possible solution. The last think you want is an unnecessarily "fancy" > > design. Unless there is a darn good reason to write a "non-static" > > program, you just don't do it. > > > You might want to check into what the FAA allows in "flight-critical" > > code, for example. I am certainly not an expert in that area, but I've > > had a passing exposure to it. My understanding is that every possible > > branch of the code must be fully and meticulously analyzed and > > verified. Hence, the dynamic dispatching of ordinary object-oriented > > code is either prohibited or severely frowned upon. > > Then Python is definitively out, so this whole thread is pointless. Yes, Python as it stands now is "definitely out" as the ultimate implementation language for flight-critical software. That's essentially a no-brainer. But it can certainly be useful as a prototyping language for R&D. The question then arises as to how to best make use of the prototype. Do you throw away the code and start from scratch? That doesn't seem wise to me. But maybe that's because I have some idea of how much effort can go into developing a good prototype. If Python could be automatically converted to Ada or Java, that could potentially be used as a baseline for actual operational software. That would capture the algorithmic details more reliably than recoding from scratch by hand. But such an automatic conversion is not feasible without explicit typing. And speaking of "pointless," ... I just wasted a significant amount of time replying to a pointless post. Oh, well. From google at mrabarnett.plus.com Wed Jan 30 21:24:37 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 30 Jan 2008 18:24:37 -0800 (PST) Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <9275bfdb-8f07-4c63-abbf-40c136388bf3@i7g2000prf.googlegroups.com> On Jan 31, 12:57 am, Asun Friere wrote: > On Jan 31, 3:13 am, Steve Holden wrote: > > > Wildemar Wildenburger wrote: > > > Well, you never go wrong with apply(genital(), females), do you? > > Never?! > > class PowerSocket () : > def __init__ (self, plug=female, active=False) : > self.plug = plug > self.active = active > > females = [p for p in powersockets if p.active and p.plug == 'female'] > > Ouch!! If on the other hand 'females' is populated by instances of > (or merely includes instances of) class 'Human', I suggest you test > for female.consent somewhere in your code! > The Pythonic approach would be to try the action and catch a NoConsentException. From pablo at decode.com.ar Mon Jan 7 15:55:33 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Mon, 07 Jan 2008 18:55:33 -0200 Subject: Python's great, in a word In-Reply-To: References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <478291C5.1000609@decode.com.ar> Dustan wrote: > On Jan 7, 11:40 am, Martin Marcher wrote: > >> it's pythonicness. >> > > "it is pythonicness"??? > Obviously a typo, for "It is pythonic, Ness". A reference to the well-known Loch Ness Monster, definitely pythonic if you see some pictures: http://images.google.com/images?q=loch+ness My 2 cents, Pablo From __peter__ at web.de Mon Jan 21 13:48:18 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Jan 2008 19:48:18 +0100 Subject: index of min element of sequence References: Message-ID: Neal Becker wrote: > What's a good/fast way to find the index of the minimum element of a > sequence? (I'm fairly sure sorting the sequence is not the fastest > approach) >>> items = "defbhkamnz" >>> min(xrange(len(items)), key=items.__getitem__) 6 >>> items[6] 'a' Peter From paul at subsignal.org Wed Jan 2 16:03:10 2008 From: paul at subsignal.org (paul) Date: Wed, 02 Jan 2008 22:03:10 +0100 Subject: XML-XSD Processing/Creation. In-Reply-To: References: Message-ID: xkenneth schrieb: > Hi All, > > So i'm working with the WITSML standard, which is a pretty > massive standard defined in XML for the transfer of oilfield data. > There are a ton of XSD files for defining and checking all data in the > WITSML format. I'd like to be able to easily create XML based on the > types defined by the WITSML XSD files. Is there any way to create a > basic XML object based on an XSD file and then populate it with data. > Can i create python classes based off the XSD files? What else can I > do with the XSD files? This might be worth looking at: http://www.rexx.com/~dkuhlman/#generateDS cheers Paul From ivan at 0x4849.net Thu Jan 10 23:45:31 2008 From: ivan at 0x4849.net (Ivan Novick) Date: Thu, 10 Jan 2008 20:45:31 -0800 (PST) Subject: Persistent HTTP Connections with Python? References: Message-ID: On Jan 10, 10:46 am, Scott Sharkey wrote: > Hello All, > > I am trying to write a python script to talk to an xml-based stock feed > service. They are telling me that I must connect and login, and then > "issue refresh requests" to fetch the data. This sounds a lot (to me) > like HTTP 1.1 persistent connections. Can I do that with the urllib > functions, or do I need to use the httplib functions for this kind of > work. Pointers and/or sample code would be much appreciated. Your questions leaves out all important details like the exact nature of the API being provided. I highly doubt HTTP persistent connections has anything to do with what you will need to connect to there service. Services like this normally come with example code, i recommend you get access to that. Regards, Ivan Novick http://www.0x4849.net From suyashjape at gmail.com Fri Jan 11 04:14:19 2008 From: suyashjape at gmail.com (suyash jape) Date: Fri, 11 Jan 2008 14:44:19 +0530 Subject: How to POST call and retrieve result page Message-ID: <16314edc0801110114t346bca6ek71660132de60b91e@mail.gmail.com> Hi all i want to access a web page through python script, fillup the necessary fields, and press submit button (which does POST call) and retrieve the result page and retrieve some values from it. Here is the script i have written till now. >import urllib2 > # create array of name/value pairs > self.params = urllib.urlencode({'seqname': 'BioSequence', 'sequence': 'ATACATTATCCAAACATAAAAAGCATGGCTT'}) > > # send http-post > request = urllib.urlopen("http://www.hydrazome.metazome.net/search.php", params) > > # read back each line of reply > line = request.read() >print line This script fills up the correct values in the search.php page.But i am not sure if it is doing the POST (submit call). Beacause in 'line' varialble, i am getting the search.php page.Not the result page which is blast_results.php. How to retrieve the result page? Thanks Suyash -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Fri Jan 11 04:16:42 2008 From: cwitts at gmail.com (Chris) Date: Fri, 11 Jan 2008 01:16:42 -0800 (PST) Subject: python recursive function References: Message-ID: On Jan 11, 10:30 am, Tom_chicollegeboy wrote: > here is what I have to do: > > This question involves a game with teddy bears. The game starts when I > give you some bears. You then start giving me back some bears, but you > must follow these rules (where n is the number of bears that you > have): > > If n is even, then you may give back exactly n/2 bears. (Hint: To test > whether n is even, use the expression ((n % 2) == 0).) > If n is divisible by 3 or 4, then you may multiply the last two digits > of n and give back this many bears. (By the way, the last digit of n > is n%10, and the next-to-last digit is (n%100)/10; this rule may not > be used if either of the last two digits is 0.) > > If n is divisible by 5, then you may give back exactly 42 bears. > The goal of the game for you is to end up with EXACTLY 42 bears. > > For example, suppose that you start with 250 bears. Then you could > make these moves: > > Start with 250 bears. > Since 250 is divisible by 5, you may return 42 of the bears, leaving > you with 208 bears. > Since 208 is even, you may return half of the bears, leaving you with > 104 bears. > Since 104 is even, you may return half of the bears, leaving you with > 52 bears. > Since 52 is divisible by 4, you may multiply the last two digits > (resulting in 10) and return these 10 bears. This leaves you with 42 > bears. > You have reached the goal! > Now, you are to write a program that, if I give you n bears, returns > true if it is at all possible for you to win the game. Your program > must use recursion to check all possible ways in which you can apply > the rules. > > Usage: > > >>> bears(42) > True > >>> bears(250) > True > >>> bears(50) > False > >>> bears(84) > True > >>> bears(41) > > False > > As you see my program must use recursion. > > I came up with this idea but I am not sure if its right or are there > any minor errors that I can easily fix: > > def bears (n): > if n==42: > return True > if n%5==0: > bears(n-42) > if n%2==0: > bears(n/2) > if n%3==0 or n%4==0: > one = (n%10) > two = ((n%100)/10) > if one!=0 and two!=0: > bears(n-(one*two)) > return False > > If a game hits 42 it should return True, otherwise False. If program > never hits 42 and return True, then it returns False. I figured out > base case, but I still get False when I enter bears(250). Any help > would be very appreciated! Stylistically I prefer 'if not n % 5', looks neater. As for your assignment, the hardest task will be creating an effective method of ensuring you recurse through all possibilities. ie. do you brute force on every step, or when getting to step do you fork your possibilities. That is more a design question rather than a python one though. From http Tue Jan 29 04:35:53 2008 From: http (Paul Rubin) Date: 29 Jan 2008 01:35:53 -0800 Subject: Encryption Recommendation References: <6b40b773-8554-4e9c-838f-e6934212d16e@n20g2000hsh.googlegroups.com> <606aj3F1pa0tfU1@mid.uni-berlin.de> Message-ID: <7xzlupug7a.fsf@ruckus.brouhaha.com> Michael Str?der writes: > But if the password checking is done with a challenge-response > mechanism (e.g. HTTP-Digest Auth or SASL with DIGEST-MD5) it's > required that the instance checking the password has the clear-text > password available. So reversible encryption for storing passwords > might be required. If you're trying to authenticate network logins using passwords, and if you have control over both ends of the protocol but for some reason don't want to use a full-blown encryption scheme, it's far better to authenticate with something like SRP (http://srp.stanford.edu) than a more primitive method like HTTP digest auth. SRP doesn't require storing plaintext passwords, and more importantly, it protects the password from offline dictionary searches by someone sniffing the network connection. There is a Python SRP implementation embedded in TLSLite (www.trevp.com/tlslite) but it might be nice to extract or reimplement the SRP code so that it can be used separately from TLS. From MartinRinehart at gmail.com Fri Jan 25 13:59:05 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Fri, 25 Jan 2008 10:59:05 -0800 (PST) Subject: Operator overloading References: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com> <5vuob3F1nd2bhU1@mid.uni-berlin.de> Message-ID: <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> Diez B. Roggisch wrote: > No, there is no way. You would change general interpreter behavior if > you could set arbitrary operators for predefined types. > > Start grumping... Thank you, Diez. If I ever design a language, please remind me that complete, easy, well-documented access to the working of the internals (and the ability to change same) would be very, uh, what's the right word? Pythonic? From Graham.Dumpleton at gmail.com Tue Jan 29 20:55:27 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 29 Jan 2008 17:55:27 -0800 (PST) Subject: Web Interface Recommendations References: <45040839-8b1f-40af-9ef5-1be274c6e95f@z17g2000hsg.googlegroups.com> Message-ID: <80d6ce9f-6c8b-412d-a261-cfe480bd0c3b@e10g2000prf.googlegroups.com> On Jan 30, 12:00 pm, PurpleServerMonkey wrote: > Looking for suggestions on the best framework to use for an > applications web interface. > > The user interface doesn't need immediate feedback and will be cross > platform so a web interface is a good solution especially since it > operates as a client\server system and not standalone. > > However there's just so many frameworks to choose from it's very > confusing. After a lot of reading it sounds like OSE or Cherrypy might > be good options but I don't have any real world experience with these > frameworks to go by. > > Basically the interface won't be the application, it's used to input > data and have the application act on it. It's going to have a > Postgresql database and a number of service\daemon processes that do > the actual work. It will also contain some form based information for > keeping track of requests etc. and grow to a fair number of screens > over time. > > Given the above what framework would you recommend? Surprised you even looked at OSE. Although OSE has some features for building HTML based web interfaces, they are very basic and not really intended for building major stuff. OSE can still be useful for writing backend applications, but would very much suggest you use just the XML- RPC interfaces it provides to talk into its distributed messaging system and service agent framework. If you use the XML-RPC interfaces then you can use a proper web application framework for doing the actual HTML based user interface front end. At that point you can choose any of the major frameworks, such as Django, Pylons, TurboGears, CherryPy or web.py. Splitting the front end from the backend like this also means that backend itself could be swapped out. Thus, instead of using OSE in the backend, you could use simpler XML-RPC enabled Python applications, or even use Pyro. In other words, you avoid intertwining code for front end and backend too much, thus perhaps making it easier to change and adapt as it grows. Graham From asmodai at in-nomine.org Fri Jan 4 05:32:21 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jan 2008 11:32:21 +0100 Subject: NetSpeed In-Reply-To: <52da23100801030810u72e0a06asa69438e9ebe6abfc@mail.gmail.com> References: <52da23100801030810u72e0a06asa69438e9ebe6abfc@mail.gmail.com> Message-ID: <20080104103221.GH82115@nexus.in-nomine.org> -On [20080104 10:34], Sunil Ghai (sunilkrghai at gmail.com) wrote: >Hey can i check the average Downloading speed of available internet connection >without downloading any dummy file? :o For all I know you cannot check anything until you have established some data over a given period of time. So at the start it will be: N/A Only after data has been passing through the connection and it having been measured can you calculate an average. But perhaps I missed something. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Death is that state where one exists only in the memories of others... From arnodel at googlemail.com Tue Jan 29 02:06:34 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 28 Jan 2008 23:06:34 -0800 (PST) Subject: Python self-evaluating strings References: <1BEEBF03-1A38-4745-B08B-DCA3106D1CC5@gmail.com> Message-ID: On Jan 29, 3:48 am, "Terry Reedy" wrote: > "Arnaud Delobelle" wrote in message > > news:a04ca850-fe63-4b7e-abff-cdacab3bcc0f at i29g2000prf.googlegroups.com... > | I found this:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > Exactly the one I meant. > > | It contains a lambda-solution similar to mine, only more concise: > > | (lambda x:x%`x`)('(lambda x:x%%`x`)(%s)') > > Being a Lisp novice, I was rather proud of that translation > > | I have been using python for 7 years, and it the first time ever that > | I see the `...` construct being used! > > It is going away in 3.0, so the above would need revision to work with > repr(), if indeed it will. Here's the py3k-compliant version: >>> k=(lambda x:x%repr(x))('(lambda x:x%%repr(x))(%s)') >>> k == eval(k) True -- Arnaud From grante at visi.com Sat Jan 12 11:26:15 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 12 Jan 2008 16:26:15 -0000 Subject: where do my python files go in linux? References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> <20080112113759.GJ75977@nexus.in-nomine.org> Message-ID: <13ohqh7fggu7i7c@corp.supernews.com> On 2008-01-12, Jorgen Bodde wrote: >> Normally you'd split up the bulk of the code into a module which gets >> installed into site-packages and a piece of stand-alone front-end code which >> imports the module and executes whatever you need to do and gets installed >> into a typical PATH directory. > > I would agree but it is not a site package I am trying to distribute, > but a wxPython application. I would not think my app belongs in the > python site packages dir. That's my opinion also, but I've seen several apps that are distributed that way. The bulk of the application code goes into the site-packages directory and then there's a 5-line script in /usr/bin that calls the application's main module that's in site-packages. That seems wrong to me... -- Grant Edwards grante Yow! Civilization is at fun! Anyway, it keeps visi.com me busy!! From toby at tobiah.org Mon Jan 7 17:59:13 2008 From: toby at tobiah.org (Tobiah) Date: Mon, 07 Jan 2008 14:59:13 -0800 Subject: Open source English dictionary to use programmatically w/ python In-Reply-To: References: Message-ID: <4782a2d2$0$26002$88260bb3@free.teranews.com> dgoldsmith_89 wrote: > Can anyone point me to a downloadable open source English dictionary > suitable for programmatic use with python: I'm programming a puzzle > generator, and I need to be able to generate more or less complete > lists of English words, alphabetized. Thanks! DG If all you want are the words themselves, then any linux box has a fairly complete list. I put mine here: http://tobiah.org/words.zip -- Posted via a free Usenet account from http://www.teranews.com From grahn+nntp at snipabacken.dyndns.org Sun Jan 20 08:53:54 2008 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 20 Jan 2008 13:53:54 GMT Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: On Fri, 18 Jan 2008 09:15:58 -0800 (PST), David Sanders wrote: > Hi, > > I am processing large files of numerical data. Each line is either a > single (positive) integer, or a pair of positive integers, where the > second represents the number of times that the first number is > repeated in the data -- this is to avoid generating huge raw files, > since one particular number is often repeated in the data generation > step. > > My question is how to process such files efficiently to obtain a > frequency histogram of the data (how many times each number occurs in > the data, taking into account the repetitions). My current code is as > follows: ... > The data files are large (~100 million lines), and this code takes a > long time to run (compared to just doing wc -l, for example). I don't know if you are in control of the *generation* of data, but I think it's often better and more convenient to pipe the raw data through 'gzip -c' (i.e. gzip-compress it before it hits the disk) than to figure out a smart application-specific compression scheme. Maybe if you didn't have a homegrown file format, there would have been readymade histogram utilities? Or at least a good reason to spend the time writing an optimized C version. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From hnessenospam at yahoo.com Thu Jan 24 12:36:37 2008 From: hnessenospam at yahoo.com (hnessenospam at yahoo.com) Date: Thu, 24 Jan 2008 09:36:37 -0800 (PST) Subject: Duplicating a variable Message-ID: I have run into a bit of a subtle problem. How do I go about duplicating a variable (particularly a list of lists) in python. I was surprised when simple assignment didn't work. For example, let y = [1,2,3] >>> x = y >>> x[2] = 5 >>> y [1,2,5] It seems that simply assigning x to y allows further modification of y via x. (I'm new to python and I'm sure this is obvious to experienced users). So my question, how do I go about duplicating a variable which I can then manipulate independently? Thanks, -Hans From deets at nospam.web.de Wed Jan 16 14:35:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jan 2008 20:35:34 +0100 Subject: Help with python shell In-Reply-To: References: <2706aa71-b072-4cbb-a7d9-abbfadd7d35a@c4g2000hsg.googlegroups.com> <5v7100F1kmtinU2@mid.uni-berlin.de> Message-ID: <5v74kaF1kt3a3U1@mid.uni-berlin.de> cbmeeks schrieb: > On Jan 16, 1:33 pm, "Diez B. Roggisch" wrote: >> cbmeeks schrieb: >> >>> I just upgraded my Python install up to version 2.5.1 (from 2.4.x) >>> using source code and compiling. >>> Everything went fine until I enter the command line mode and press any >>> arrow keys. >>> When I press UP arrow, I was getting my previous command as always but >>> now I get: ^[[A >>> What can I do to fix this?? >> Compiling with readline support? I guess that's missing. >> >> Diez > > I tried ./configure --enable-readline but that didn't do the trick. > ARG!! This is annoying. You don't just need to enable it - the readline lib needs to be installed, including the possible devel-package (If you are under linux) for the headers. Diez From martin at v.loewis.de Sun Jan 13 06:26:17 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jan 2008 12:26:17 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801131224.10263.donn.ingle@gmail.com> References: <200801130930.07852.donn.ingle@gmail.com> <4789D98A.80609@v.loewis.de> <200801131224.10263.donn.ingle@gmail.com> Message-ID: <4789F559.1090703@v.loewis.de> > I have found that os.listdir() does not always return unicode objects when > passed a unicode path. Sometimes "byte strings" are returned in the list, > mixed-in with unicodes. Yes. It does so when it fails to decode the byte string according to the file system encoding (which, in turn, bases on the locale). > I will try the technique given > on:http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html#guessing-the-encoding > Perhaps that will help. I would advise against such a strategy. Instead, you should first understand what the encodings of the file names actually *are*, on a real system, and draw conclusions from that. > I gather you mean that I should get a unicode path, encode it to a byte string > and then pass that to os.listdir > Then, I suppose, I will have to decode each resulting byte string (via the > detect routines mentioned in the link above) back into unicode - passing > those I simply cannot interpret. That's what I meant, yes. Again, you have a number of options - passing those that you cannot interpret is but one option. Another option is to accept moji-bake. >> Then, if the locale's encoding cannot decode the file names, you have >> several options >> a) don't try to interpret the file names as character strings, i.e. >> don't decode them. Not sure why you need the file names - if it's >> only to open the files, and never to present the file name to the >> user, not decoding them might be feasible > So, you reckon I should stick to byte-strings for the low-level file open > stuff? It's a little complicated by my using Python Imaging to access the > font files. It hands it all over to Freetype and really leaves my sphere of > savvy. > I'll do some testing with PIL and byte-string filenames. I wish my memory was > better, I'm pretty sure I've been down that road and all my results kept > pushing me to stick to unicode objects as far as possible. I would be surprised if PIL/freetype would not support byte string file names if you read those directly from the disk. OTOH, if the user has selected/typed a string at a GUI, and you encode that - I can easily see how that might have failed. >> That's correct, and there is no solution (not in Python, not in any >> other programming language). You have to made trade-offs. For that, >> you need to analyze precisely what your requirements are. > I would say the requirements are: > 1. To open font files from any source (locale.) > 2. To display their filename on the gui and the console. > 3. To fetch some text meta-info (family etc.) via PIL/Freetype and display > same. > 4. To write the path and filename to text files. > 5. To make soft links (path + filename) to another path. > > So, there's a lot of unicode + unicode and os.path.join and so forth going on. I notice that this doesn't include "to allow the user to enter file names", so it seems there is no input of file names, only output. Then I suggest this technique of keeping bytestring/unicode string pairs. Use the Unicode string for display, and the byte string for accessing the disc. >>> I went through this exercise recently and had no joy. It seems the string >>> I chose to use simply would not render - even under 'ignore' and >>> 'replace'. >> I don't understand what "would not render" means. > I meant it would not print the name, but constantly throws ascii related > errors. That cannot be. Both the ignore and the replace error handlers will silence all decoding errors. > I don't know if the character will survive this email, but the text I was > trying to display (under LANG=C) in a python script (not the immediate-mode > interpreter) was: "M?gul". The second character is a capital O with an umlaut > (double-dots I think) above it. For some reason I could not get that to > display as "M?gul" or "Mgul". I see no problem with that: >>> u"M\xd6gul".encode("ascii","ignore") 'Mgul' >>> u"M\xd6gul".encode("ascii","replace") 'M?gul' Regards, Martin From ptmcg at austin.rr.com Tue Jan 22 18:31:19 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 22 Jan 2008 15:31:19 -0800 (PST) Subject: Processing XML that's embedded in HTML References: Message-ID: <1d163d82-db6b-4f43-8462-4359fb1f4b01@f47g2000hsd.googlegroups.com> On Jan 22, 10:57?am, Mike Driscoll wrote: > Hi, > > I need to parse a fairly complex HTML page that has XML embedded in > it. I've done parsing before with the xml.dom.minidom module on just > plain XML, but I cannot get it to work with this HTML page. > > The XML looks like this: > ... Once again (this IS HTML Day!), instead of parsing the HTML, pyparsing can help lift the interesting bits and leave the rest alone. Try this program out: from pyparsing import makeXMLTags,Word,nums,Combine,oneOf,SkipTo,withAttribute htmlWithEmbeddedXml = """

Hey! this is really bold! Owner 1 07/16/2007 No Doe, John

1905 S 3rd Ave , Hicksville IA 99999
Owner 2 07/16/2007 No Doe, Jane
1905 S 3rd Ave , Hicksville IA 99999
", "test", "
more HTML blah blah blah... """ # define pyparsing expressions for XML tags rowStart,rowEnd = makeXMLTags("Row") relationshipStart,relationshipEnd = makeXMLTags("Relationship") priorityStart,priorityEnd = makeXMLTags("Priority") startDateStart,startDateEnd = makeXMLTags("StartDate") stopsExistStart,stopsExistEnd = makeXMLTags("StopsExist") nameStart,nameEnd = makeXMLTags("Name") addressStart,addressEnd = makeXMLTags("Address") # define some useful expressions for data of specific types integer = Word(nums) date = Combine(Word(nums,exact=2)+"/"+ Word(nums,exact=2)+"/"+Word(nums,exact=4)) yesOrNo = oneOf("Yes No") # conversion parse actions integer.setParseAction(lambda t: int(t[0])) yesOrNo.setParseAction(lambda t: t[0]=='Yes') # could also define a conversion for date if you really wanted to # define format of a , plus assign results names for each data field rowRec = rowStart + \ relationshipStart + SkipTo(relationshipEnd)("relationship") + relationshipEnd + \ priorityStart + integer("priority") + priorityEnd + \ startDateStart + date("startdate") + startDateEnd + \ stopsExistStart + yesOrNo("stopsexist") + stopsExistEnd + \ nameStart + SkipTo(nameEnd)("name") + nameEnd + \ addressStart + SkipTo(addressEnd)("address") + addressEnd + \ rowEnd # set filtering parse action rowRec.setParseAction(withAttribute(relationship="Owner",priority=1)) # find all matching rows, matching grammar and filtering parse action rows = rowRec.searchString(htmlWithEmbeddedXml) # print the results (uncomment r.dump() statement to see full # result for each row) for r in rows: # print r.dump() print r.relationship print r.priority print r.startdate print r.stopsexist print r.name print r.address This prints: Owner 1 07/16/2007 False Doe, John 1905 S 3rd Ave , Hicksville IA 99999 In addition to parsing this data, some conversions were done at parse time, too - "1" was converted to the value 1, and "No" was converted to False. These were done by the conversion parse actions. The filtering just for Row's containing Relationship="Owner" and Priority=1 was done in a more global parse action, called withAttribute. If you comment this line out, you will see that both rows get retrieved. -- Paul (Find out more about pyparsing at http://pyparsing.wikispaces.com.) From mr.cerutti at gmail.com Wed Jan 16 07:33:11 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 16 Jan 2008 07:33:11 -0500 Subject: Generic string import like in strptime? In-Reply-To: References: Message-ID: <51302a8c0801160433s8789ba9i9bb666a38e085983@mail.gmail.com> On Jan 16, 2008 3:34 AM, Andre wrote: > Hi there > > Is there a function like strptime, which takes a string and converts it > into an array depending on a format string I provide. Like: > >>> a = '3456\tblub-blib.0.9' > >>> b = '%d\t%s-%s.%f' > >>> c = mysticalfunction(a,b) > >>> print c > [3456,'blub','blib',0.9] No, not in the standard distribution of Python. In Python, you're expected to use appropriate string methods, or hold your nose and drag out the re module. There are some scanf-like libraries for Python available on the net, e.g., http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/. None of them have become popular enough with Python users to make it into the standard distribution. An excellent tool that can be used in these cases is pyparsing, which is also not in the standard distribution. http://pyparsing.wikispaces.com/ -- Neil Cerutti From gnewsg at gmail.com Sat Jan 12 11:31:59 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 12 Jan 2008 08:31:59 -0800 (PST) Subject: How to get user home directory on Windows Message-ID: Hi all, I'm trying to use the pywin32 extension to find out the user's home directory but currently I didn't find a solution yet. What I'd need to do is not getting the home directory of the currently logged in user but something like: >>> get_homedir("frank") "C:\home\users\frank" >>> get_homedir("josh") "C:\home\users\josh" Is there a way to do that? I tried to search through the Pywin32 documentation with no luck. In addition I'm not practiced with the Windows API at all. From nurple11 at gmail.com Sun Jan 27 16:36:56 2008 From: nurple11 at gmail.com (nurple11 at gmail.com) Date: Sun, 27 Jan 2008 13:36:56 -0800 (PST) Subject: python valentine Message-ID: <8b3988e8-aabf-456c-b748-10cc273ff050@i7g2000prf.googlegroups.com> Slightly off-topic, but this is the best Valentine's Day card I've seen in a while: http://unholidaycards.com/code.html I think I just might get some for my lab. #!/usr/bin/env python from relationships import * from alcohol import shot, beer def valentines_day(self): if self.dating: if self.money == 0: self.dating = False elif self.num_prev_dates == 0: self.money -= dinner() self.money -= pointless_gift() else: self.money -= dinner()/sqrt(self.num_prev_dates) if randInt(self.num_prev_dates): self.money -= pointless_gift()/self.num_prev_dates elif self.married: if self.years_married < 5: self.money -= dinner()/(self.years_married ** 2) else: pass else: while self.blood_alcohol < .08: self.blood_alcohol += beer() while self.blood_alcohol < .22: self.blood_alcohol += shot() sleep(86400) From eduardo.padoan at gmail.com Fri Jan 18 12:20:55 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Fri, 18 Jan 2008 15:20:55 -0200 Subject: Bug in __init__? In-Reply-To: References: Message-ID: On Jan 18, 2008 3:09 PM, Zbigniew Braniecki wrote: > I found a bug in my code today, and spent an hour trying to locate it > and then minimize the testcase. > > Once I did it, I'm still confused about the behavior and I could not > find any reference to this behavior in docs. > > testcase: > > class A(): > > def add (self, el): > self.lst.extend(el) > > def __init__ (self, val=[]): > print val > self.lst = val > > > def test (): > x = A() > x.add(["foo1","foo2"]) > b = A() > > > So, what I would expect here is that I will create two instances of > class A with empty self.lst property. Right? > > In fact (at least with my Python 2.5) > > gandalf at gandalf-desktop:~/projects/pyl10n$ ./scripts/test.py > [] > ['foo1', 'foo2'] > > This bug does not happen when I switch to __init__ (self, *args) and > assign self.lst= args[0]. > > Any clue on what's going on here, and/if where I should report it? It is a FAQ, not a bug: http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From jimis at gmx.net Thu Jan 10 15:15:37 2008 From: jimis at gmx.net (Dimitrios Apostolou) Date: Thu, 10 Jan 2008 22:15:37 +0200 (EET) Subject: urllib2 rate limiting In-Reply-To: <87ejcpo7r8.fsf@merkury.smsnet.pl> References: <87ejcpo7r8.fsf@merkury.smsnet.pl> Message-ID: On Thu, 10 Jan 2008, Rob Wolfe wrote: > Dimitrios Apostolou writes: > >> P.S. And something simpler: How can I disallow urllib2 to follow >> redirections to foreign hosts? > > You need to subclass `urllib2.HTTPRedirectHandler`, override > `http_error_301` and `http_error_302` methods and throw > `urllib2.HTTPError` exception. Thanks! I think for my case it's better to override redirect_request method, and return a Request only in case the redirection goes to the same site. Just another question, because I can't find in the docs the meaning of (req, fp, code, msg, hdrs) parameters. To read the URL I get redirected to (the 'Location:' HTTP header?), should I check the hdrs parameter or there is a better way? Thanks, Dimitris > > http://diveintopython.org/http_web_services/redirects.html > > HTH, > Rob > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Sun Jan 6 08:57:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 06 Jan 2008 14:57:34 +0100 Subject: Killing worker threads In-Reply-To: <8a6b8e350801060548m6f39594che1207cc5bc4b6487@mail.gmail.com> References: <8a6b8e350801060548m6f39594che1207cc5bc4b6487@mail.gmail.com> Message-ID: James Matthews wrote: > You can use the stop method! You can? >>> import threading >>> t = threading.Thread() >>> t.stop() Traceback (most recent call last): File "", line 1, in AttributeError: 'Thread' object has no attribute 'stop' >>> What Python version are you using? From jarausch at igpm.rwth-aachen.de Tue Jan 22 07:58:55 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 22 Jan 2008 13:58:55 +0100 Subject: ctypes CDLL - which paths are searched? In-Reply-To: References: <4794d573$0$2980$ba620e4c@news.skynet.be> Message-ID: <4795E88F.7050406@igpm.rwth-aachen.de> Thomas Heller wrote: > Helmut Jarausch schrieb: >> Hi, >> >> how can I specify the paths to be searched for a dynamic library >> to be loaded by ctypes' CDLL class on a Linux system. >> >> Do I have to set os.environment['LD_LIBRARY_PATH'] ? >> > > ctypes passes the argument given to CDLL(path) straight to > the dlopen(3) call, so your system documentation should tell you. > Thanks, but then it's difficult to use CDLL. Setting os.environ['LD_LIBRARY_PATH'] within the script which calls CDLL is too late. What other methods are possible rather than put an explicit export LD_LIBRARY_PATH=... before running the script, if I don't want to put the dynamic library into a standard system library. Many thanks, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From miki.tebeka at gmail.com Thu Jan 17 19:42:01 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 17 Jan 2008 16:42:01 -0800 (PST) Subject: "Code Friendly" Blog? References: <0fd979c6-5a11-4989-9438-51a7b20ecd23@n20g2000hsh.googlegroups.com> Message-ID: <12e6dfa8-a550-4485-8a4c-721baadd79a5@e6g2000prf.googlegroups.com> Hello Mel, [Hai] >> how about bracketing your code in the
 tags?
[Mel]
> That won't help the escape problem, though it will preserve vital
> Python whitespace.  HTML has to be interpreting '<' characters to
> recognize the ''.
They also manage to mess up the first indentation in the 
section :)

Thanks,
--
Miki 
http://pythonwise.blogspot.com


From petr.jakes.tpc at gmail.com  Tue Jan  1 16:01:24 2008
From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com)
Date: Tue, 1 Jan 2008 13:01:24 -0800 (PST)
Subject: Newbie: Why doesn't this work
References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com>
	
	
	
	
	
Message-ID: 

> > My question is: is it possible to set the "property" for any attribute
> > when I do not know what will be the name of the attribute in the
> > future?
>
> Uhm... I don't understand the question. Perhaps if you think of a concrete
> case...?

Thanks for reply,

few minutes after i posted my question, I have realized my posting is
probably a "nonsense".

If I understand it properly, it is necessary, in the respect of
encapsulation, to define attributes inside the class (even it is
possible to add a new attribute to the existing object outside class
definition).

The meaning of my question was:
Is it possible to define some general sort of set/get/del/doc rules
for the attributes which are defined in the code AFTER the
instantiation of an object.

I am sending this question even I feel such a "on the fly" creation of
the attribute is probably not a good trick.

Petr Jakes


From chiendarret at yahoo.com  Sun Jan  6 16:33:52 2008
From: chiendarret at yahoo.com (Francesco Pietra)
Date: Sun, 6 Jan 2008 13:33:52 -0800 (PST)
Subject: Delete lines containing a specific word
In-Reply-To: 
Message-ID: <210501.70143.qm@web57616.mail.re1.yahoo.com>

Steven:
Thanks. See below please (of very marginal interest)

--- Steven D'Aprano  wrote:

> On Sun, 06 Jan 2008 09:21:33 -0800, Francesco Pietra wrote:
> 
> > Please, how to adapt the following script (to delete blank lines) to
> > delete lines containing a specific word, or words?
> 
> That's tricky, because deleting lines from a file isn't a simple 
> operation. No operating system I know of (Windows, Linux, OS X) has a 
> "delete line" function.

As I am at Debian Linux, I do that with grep -v


> 
> Do you really need to delete the lines in place? It would be much simpler 
> to leave the original data as-is, and create a new file with just the 
> lines that aren't deleted.
> 
> 
> > f=open("output.pdb", "r")
> > for line in f:
> > 	line=line.rstrip()
> > 	if line:
> > 		print line
> > f.close()
> 
> How to adapt this script:
> 
> First, think about what this script does. That is, it goes through each 
> line, and if the line is not blank, it prints it.
> 
> What do you want it to do instead? You want it to print the line if the 
> line doesn't contain a specific word. So that's the first thing you need 
> to change.
> 
> Secondly, you might want the script to write its output to a file, 
> instead of printing. So, instead of the line "print line", you want it to 
> write to a file.

may be cumbersome, though I use  2>&1 | tee output file.pdb so that I can see
what happens on the screen and have the modified file.

> 
> Before you can write to a file, you need to open it. So you will need to 
> open another file: you will have two files open, one for input and one 
> for output. And you will need to close them both when you are finished.
> 
> Does that help you to adapt the script?
> 
> 
> > If python in Linux accepts lines beginning with # as comment lines,
> > please also a script to comment lines containing a specific word, or
> > words, and back, to remove #.
> 
> The same process applies. Instead of "delete line", you want to "comment 
> line". 
> 
> 
> 
> -- 
> Steven
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 



      ____________________________________________________________________________________
Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ 



From br.rizwan at googlemail.com  Thu Jan 17 17:30:50 2008
From: br.rizwan at googlemail.com (Rizwan)
Date: Thu, 17 Jan 2008 14:30:50 -0800 (PST)
Subject: Python Tutorial.
Message-ID: <2537f4eb-c047-4eae-9d26-93c7498b5840@f47g2000hsd.googlegroups.com>


Hiya,

I found one good website for python tutorial. just thought to share
with community.

Hope you all also like it..

 http://python.objectis.net


-MR



From kw at codebykevin.com  Mon Jan  7 18:14:12 2008
From: kw at codebykevin.com (Kevin Walzer)
Date: Mon, 07 Jan 2008 18:14:12 -0500
Subject: Does PIL work with Tk 8.5?
In-Reply-To: <4782B074.8080709@v.loewis.de>
References: <2870$4782a5c4$4275d90a$673@FUSE.NET>
	<4782B074.8080709@v.loewis.de>
Message-ID: <4782B244.7010706@codebykevin.com>

Martin v. L?wis wrote:

> OTOH, it's more likely that the PIL binaries you are using conflict with
> your Tk installation - if the binaries were for Tk 8.4 (which isn't
> quite clear to me whether that's indeed the case), then they can't work
> with Tk 8.5, as Tk doesn't provide that kind of binary compatibility.

Tk itself has a stubs mechanism that allows libraries compiled against 
earlier versions to be used with later versions. It's different than 
Python in this respect. A pure-Tk library (such as Img or TkPNG) built 
against Tk 8.4 would not require re-compilation to be used with 8.5. 
Since PIL is a Python library, however, you may be right.

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com


From alnilam at gmail.com  Tue Jan 22 22:41:20 2008
From: alnilam at gmail.com (Alnilam)
Date: Tue, 22 Jan 2008 19:41:20 -0800 (PST)
Subject: HTML parsing confusion
References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com>
	<1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> 
	<6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> 
	<50269e4a-af44-4d73-b6cb-c42af6b5164d@e10g2000prf.googlegroups.com> 
	<5vmkiiF1nadr7U1@mid.uni-berlin.de>
	
	
Message-ID: <6cc92ad4-4448-4254-8c01-a04b0c035117@d21g2000prf.googlegroups.com>

On Jan 22, 7:29?pm, "Gabriel Genellina" 
wrote:
>
> > I was asking this community if there was a simple way to use only the
> > tools included with Python to parse a bit of html.
>
> If you *know* that your document is valid HTML, you can use the HTMLParser ?
> module in the standard Python library. Or even the parser in the htmllib ?
> module. But a lot of HTML pages out there are invalid, some are grossly ?
> invalid, and those parsers are just unable to handle them. This is why ?
> modules like BeautifulSoup exist: they contain a lot of heuristics and ?
> trial-and-error and personal experience from the developers, in order to ?
> guess more or less what the page author intended to write and make some ?
> sense of that "tag soup".
> A guesswork like that is not suitable for the std lib ("Errors should ?
> never pass silently" and "In the face of ambiguity, refuse the temptation ?
> to guess.") but makes a perfect 3rd party module.
>
> If you want to use regular expressions, and that works OK for the ?
> documents you are handling now, fine. But don't complain when your RE's ?
> match too much or too little or don't match at all because of unclosed ?
> tags, improperly nested tags, nonsense markup, or just a valid combination ?
> that you didn't take into account.
>
> --
> Gabriel Genellina

Thanks, Gabriel. That does make sense, both what the benefits of
BeautifulSoup are and why it probably won't become std lib anytime
soon.

The pages I'm trying to write this code to run against aren't in the
wild, though. They are static html files on my company's lan, are very
consistent in format, and are (I believe) valid html. They just have
specific paragraphs of useful information, located in the same place
in each file, that I want to 'harvest' and put to better use. I used
diveintopython.org as an example only (and in part because it had good
clean html formatting). I am pretty sure that I could craft some
regular expressions to do the work -- which of course would not be the
case if I was screen scraping web pages in the 'wild' -- but I was
trying to find a way to do that using one of those std libs you
mentioned.

I'm not sure if HTMLParser or htmllib would work better to achieve the
same effect as the regex example I gave above, or how to get them to
do that. I thought I'd come close, but as someone pointed out early
on, I'd accidently tapped into PyXML which is installed where I was
testing code, but not necessarily where I need it. It may turn out
that the regex way works faster, but falling back on methods I'm
comfortable with doesn't help expand my Python knowledge.

So if anyone can tell me how to get HTMLParser or htmllib to grab a
specific paragraph, and then provide the text in that paragraph in a
clean, markup-free format, I'd appreciate it.


From cain171562 at gmail.com  Wed Jan  9 17:41:10 2008
From: cain171562 at gmail.com (mike)
Date: Wed, 9 Jan 2008 14:41:10 -0800 (PST)
Subject: mysqldb SELECT COUNT reurns 1
References: 
	
Message-ID: <4338fe75-e67d-41ec-a2ad-30c5303c941e@y5g2000hsf.googlegroups.com>

On Dec 27 2007, 5:25 pm, Ian Clark  wrote:
> On 2007-12-27, SMALLp  wrote:
>
> > connectionString = {"host":"localhost", "user":"root",
> > "passwd":"pofuck", "db":"fileshare"}
> > dataTable = "files"
> > conn = mysql.connect(host=connectionString["host"],
> > user=connectionString["user"], passwd=connectionString["passwd"],
> > db=connectionString["db"])
>
> Just to let you know, that last line can be rewritten as:
>
> conn = mysql.connect(**connectionString)
>
> Ian

Try using cursor.fetchall() instead of cursor.fetchone()


From nick at craig-wood.com  Fri Jan 11 07:30:04 2008
From: nick at craig-wood.com (Nick Craig-Wood)
Date: Fri, 11 Jan 2008 06:30:04 -0600
Subject: python recursive function
References: 
	<01c6fa55-3836-4d92-aaf4-02fec7fa529c@l6g2000prm.googlegroups.com>
Message-ID: 

HYRY  wrote:
>  def bears (n):
>      if n==42:
>          return True
>      if n%5==0:
>          if bears(n-42):
>              return True
>      if n%2==0:
>          if bears(n/2):
>              return True
>      if n%3==0 or n%4==0:
>          one = (n%10)
>          two = ((n%100)/10)
>          if one!=0 and two!=0:
>              if bears(n-(one*two)):
>                  return True
>      return False

Almost but you missed a case...

>>> for i in range(100):
...     try:
...         print i, bears(i)
...     except RuntimeError, e:
...         print i, e
...
0 0 maximum recursion depth exceeded
1 False
2 False
3 False
4 False
5 False
6 False
7 False
8 False
9 False
10 10 maximum recursion depth exceeded
11 False
12 12 maximum recursion depth exceeded
113 False
14 False
15 15 maximum recursion depth exceeded
16 16 maximum recursion depth exceeded
17 False
[snip]
89 False
90 90 maximum recursion depth exceeded
91 False
92 False
93 93 maximum recursion depth exceeded
94 False
95 False
96 96 maximum recursion depth exceeded
97 False
98 False
99 99 maximum recursion depth exceeded

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick


From phillip.sitbon at gmail.com  Tue Jan 15 13:58:57 2008
From: phillip.sitbon at gmail.com (Phillip Sitbon)
Date: Tue, 15 Jan 2008 10:58:57 -0800 (PST)
Subject: Python in IIS + WSGI
References: <86d01390-fb1c-4806-a10b-92446c008b10@k2g2000hse.googlegroups.com>
	<728a3b8a-074f-4435-89e3-4cdb095f193a@q39g2000hsf.googlegroups.com>
Message-ID: 

Looks like Sourceforge had a problem with the file upload, causing it
to be empty - I just fixed it.

http://pyisapie.sourceforge.net/

> On Jan 11, 4:37 pm, Phillip Sitbon  wrote:
>
> > Recently (finally) updated the PyISAPIe project. Version 1.0.4
> > includes WSGI support (tested with current Django SVN and Trac 0.10)
> > and a Django-native handler, as well as other examples of using it as
> > a standalone web app.
>
> > Also added some installation/usage docs on the project page.
>
> > Comments/feedback welcome!
>




From henry.baxter at gmail.com  Fri Jan 25 18:19:42 2008
From: henry.baxter at gmail.com (Henry Baxter)
Date: Fri, 25 Jan 2008 15:19:42 -0800
Subject: Index of maximum element in list
In-Reply-To: <479A58F9.4090805@gmx.net>
References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com>
	<8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com>
	<479A58F9.4090805@gmx.net>
Message-ID: <8d04436f0801251519g482a697dn625223b6d46e8f2c@mail.gmail.com>

Thanks Hexamorph and Neal. Somehow I didn't make the connection with using
'index', but I'm all sorted out now :)

On Jan 25, 2008 1:47 PM, Hexamorph  wrote:

> Henry Baxter wrote:
> > Oops, gmail has keyboard shortcuts apparently, to continue:
> >
> > def maxi(l):
> >     m = max(l)
> >     for i, v in enumerate(l):
> >         if m == v:
> >             return i
> >
>
> What's about l.index(max(l)) ?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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

From castironpi at gmail.com  Fri Jan 11 15:22:53 2008
From: castironpi at gmail.com (castironpi at gmail.com)
Date: Fri, 11 Jan 2008 12:22:53 -0800 (PST)
Subject: removeall() in list
Message-ID: 

Any ideas for a thread-safe list.removeall( X ): removing all
occurrences of X within list L, when L might be modified concurrently?

Sincerely,
Aaron


From socyl at 987jk.com.invalid  Tue Jan 29 11:39:02 2008
From: socyl at 987jk.com.invalid (kj)
Date: Tue, 29 Jan 2008 16:39:02 +0000 (UTC)
Subject: Python noob SOS (any [former?] Perlheads out there?)
Message-ID: 



For many months now I've been trying to learn Python, but I guess
I'm too old a dog trying to learn new tricks...  For better or
worse, I'm so used to Perl when it comes to scripting, that I'm
just having a very hard time getting a hang of "The Python Way."

It's not the Python syntax that I'm having problems with, but rather
with larger scale issues such as the structuring of packages,
techniques for code reuse, test suites, the structure of
distributions,...  Python and Perl seem to come from different
galaxies altogether...

Be that as it may, the activation barrier to using Python for my
scripting remains too high.

I'd written a Perl module to facilitate the writing of scripts.
It contained all my boilerplate code for parsing and validating
command-line options, generating of accessor functions for these
options, printing of the help message and of the full documentation,
testing, etc.

Of course, for Python now I don't have any of this, so I must write
it all from scratch, and the thing is *I don't even know where to
begin*!  And meanwhile works needs to get done, projects finished,
etc.  So naturally I revert to Perl, yadda-yadda-yadda, and the
Python project gets pushed back another week...

In a way it's the usual story with learning a new language, but
I've taught myself new languages before.  (After all, there was a
time when I didn't know Perl.)  It's harder this time, somehow...

Anyway, pardon the ramble.

Is there any good reading (to ease the transition) for Perl
programmers trying to learn Python?

Thanks!

kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.


From robleachza at gmail.com  Thu Jan 17 11:35:24 2008
From: robleachza at gmail.com (robleachza at gmail.com)
Date: Thu, 17 Jan 2008 08:35:24 -0800 (PST)
Subject: next line (data parsing)
References: 
	<13otnvakq8kc6a3@corp.supernews.com>
	
	
Message-ID: <6df36bbb-61a2-47b0-8df6-a7e37d782923@k2g2000hse.googlegroups.com>

I'm very appreciative for the comments posted. Thanks to each of you.
All good stuff.
Cheers,
-Rob


On Jan 16, 9:50 pm, George Sakkis  wrote:
> On Jan 17, 12:42 am, George Sakkis  wrote:
>
>
>
> > On Jan 17, 12:01 am, Scott David Daniels 
> > wrote:
>
> > > robleac... at gmail.com wrote:
> > > > Hi there,
> > > > I'm struggling to find a sensible way to process a large chuck of
> > > > data--line by line, but also having the ability to move to subsequent
> > > > 'next' lines within a for loop. I was hoping someone would be willing
> > > > to share some insights to help point me in the right direction. This
> > > > is not a file, so any file modules or methods available for files
> > > > parsing wouldn't apply.
>
> > > > I can iterate over each line by setting a for loop on the data object;
> > > > no problem. But basically my intension is to locate the line "Schedule
> > > > HOST" and progressively move on to the 'next' line, parsing out the
> > > > pieces I care about, until I then hit "Total", then I resume to the
> > > > start of the for loop which locates the next "Schedule HOST".
>
> > > if you can do:
>
> > >      for line in whatever:
> > >          ...
>
> > > then you can do:
>
> > >      source = iter(whatever)
> > >      for intro in source:
> > >          if intro.startswith('Schedule '):
> > >              for line in source:
> > >                  if line.startswith('Total'):
> > >                      break
> > >                  process(intro, line)
>
> > > --Scott David Daniels
> > > Scott.Dani... at Acm.Org
>
> > Or if you use this pattern often, you may extract it to a general
> > grouping function such ashttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877:
>
> Sorry, google groups fscked up with the auto linewrapping (is there a
> way to increase the line length?); here it is again:
>
> import re
>
> for line in iterblocks(source,
>         start = lambda line: line.startswith('Schedule HOST'),
>         end = lambda line: re.search(r'^\s*Total',line),
>         skip_delim = False):
>     process(line)
>
> George


From tezlo at gmx.net  Thu Jan 10 09:27:17 2008
From: tezlo at gmx.net (tezlo)
Date: Thu, 10 Jan 2008 15:27:17 +0100
Subject: Embedding python code into text document question.
References: 
Message-ID: <20080110152717.9fdd6d0f.tezlo@gmx.net>

Thomas Troeger  wrote:
> I've written a program that parses a string or file for embedded
> python commands, executes them and fills in the returned value.
> ...
> I've tried several solutions using eval, execfile or compile, but
> none of those would solve my problem. Does anyone have a solution
> that works? Any suggestions? Any help will be appreciated :)

Hi,
first, to quote the manual [1]
> Be aware that the return and yield statements may not be used
> outside of function definitions even within the context of code
> passed to the exec statement.

Once you get rid of those return statements, the first two
substitutions could simpy be eval'ed. Conditions and loops can be
exec'ed, but you need to capture the output somehow. You could
replace sys.stdout with your own StringIO before you exec, and
use 'print' instead of 'return' in your templates.

Two basic approaches: you eval every substitution by itself [2], or you
parse the whole template into one big python chunk, and exec that [3].

[1] http://docs.python.org/ref/exec.html
[2] http://blog.ianbicking.org/templating-via-dict-wrappers.html
[3] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/464766


From paddy3118 at googlemail.com  Sun Jan 27 20:17:56 2008
From: paddy3118 at googlemail.com (Paddy)
Date: Sun, 27 Jan 2008 17:17:56 -0800 (PST)
Subject: Python Standardization: Wikipedia entry
References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com>
	
Message-ID: <0c9a1a2d-68a9-4f9c-b140-8823950a5ba1@k2g2000hse.googlegroups.com>

On Jan 28, 1:05 am, ajaksu  wrote:
> On Jan 27, 10:32 pm, Paddy  wrote:
>
> > I would value the opinion of fellow Pythoneers who have also
> > contributed to Wikipedia, on the issue of "Is Python Standardized".
> > Specifically in the context of this table:
> >  http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Gene...
> >   (Comparison of programming languages)
> > And this entry in the talk page
> >  http://en.wikipedia.org/wiki/Talk:Comparison_of_programming_languages...
> >   (Talk:Comparison of programming languages#Standardized Python?)
>
> > - Thanks.
>
> Hmmm. Seems to me that "Is X Standardized" in the given context means
> having a formal, published standard issued by some Standards
> organization. While you can discuss the meaning of some so-called
> standards (like W3C's 'recommendations', RFCs, etc.), Python, IMHO,
> doesn't fit the label. There is no "Standard" to reference that is
> implementation, documentation and core-dev's opinion independent to a
> reasonable degree.
>
> I guess MilesAgain gives the best arguments regarding this issue.
>
> Not-that-my-opinion-should-have-any-weight-ly y'rs
> Daniel

Thanks Daniel. I am very close to the issue and would like to step
back and c.l.p'ers opinion.


From bronger at physik.rwth-aachen.de  Wed Jan  2 02:01:13 2008
From: bronger at physik.rwth-aachen.de (Torsten Bronger)
Date: Wed, 02 Jan 2008 08:01:13 +0100
Subject: Tab indentions on different platforms?
References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com>
	
	<13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au>
	
	<13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au>
	<13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au>
	<87bq85rp2d.fsf@physik.rwth-aachen.de>
	<87abnoc13h.fsf@benfinney.id.au>
Message-ID: <87odc4hft2.fsf@physik.rwth-aachen.de>

Hall?chen!

Ben Finney writes:

> Torsten Bronger  writes:
>
>> [...] the width of a tab is nowhere defined. It really is a
>> matter of the editor's settings.
>
> RFC 678 "Standard File Formats"
> :
>
>          Horizontal Tab  
>
> [...]

As far as I can see, this excerpt of a net standard has been neither
normative nor influential on the behaviour of text editors.

>> I, for example, dislike too wide indenting. I use four columns in
>> Python and two in Delphi. However, there are Python projects
>> using eight spaces for each indentation level.
>
> How many columns to indent source code is an orthogonal question
> to how wide an ASCII TAB (U+0009) should be rendered. [...]

I don't know what you want to say with this.  Obviousy, is is
impossible to indent four columns with 8-columns tabs.  Anyway, my
sentence was supposed just to lead to the following:

>> If all Python code used tabs, everybody could use their own
>> preferences, for both reading and writing code, and
>> interoperability would be maintained nevertheless.
>
> Interoperability isn't the only criterion though. On the contrary,
> source code is primarily for reading by programmers, and only
> incidentally for reading by the compiler.

Well, I, the programmer, want code snippets from different versions
fit together as seemlessly as possible, and I want to use my editor
settings for every piece of Python code that I load into it.

Tsch?,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
                                      Jabber ID: bronger at jabber.org
               (See http://ime.webhop.org for further contact info.)


From justin.mailinglists at gmail.com  Wed Jan  2 21:56:25 2008
From: justin.mailinglists at gmail.com (Justin Ezequiel)
Date: Wed, 2 Jan 2008 18:56:25 -0800 (PST)
Subject: Python CGI - Presenting a zip file to user
References: 
Message-ID: 

On Jan 3, 7:50 am, jwwest  wrote:
> Hi all,
>
> I'm working on a cgi script that zips up files and presents the zip
> file to the user for download. It works fine except for the fact that
> I have to overwrite the file using the same filename because I'm
> unable to delete it after it's downloaded. The reason for this is
> because after sending "Location: urlofzipfile" the script stops
> processing and I can't call a file operation to delete the file. Thus
> I constantly have a tmp.zip file which contains the previously
> requested files.
>
> Can anyone think of a way around this? Is there a better way to create
> the zip file and present it for download "on-the-fly" than editing the
> Location header? I thought about using Content-Type, but was unable to
> think of a way to stream the file out.
>
> Any help is appreciated, much thanks!
>
> - James

import sys, cgi, zipfile, os
from StringIO import StringIO

try: # Windows only
    import msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
except ImportError: pass

HEADERS = '\r\n'.join(
    [
        "Content-type: %s;",
        "Content-Disposition: attachment; filename=%s",
        "Content-Title: %s",
        "Content-Length: %i",
        "\r\n", # empty line to end headers
        ]
    )

if __name__ == '__main__':
    os.chdir(r'C:\Documents and Settings\Justin Ezequiel\Desktop')
    files = [
        '4412_ADS_or_SQL_Server.pdf',
        'Script1.py',
        'html_files.zip',
        'New2.html',
        ]
    b = StringIO()
    z = zipfile.ZipFile(b, 'w', zipfile.ZIP_DEFLATED)
    for n in files:
        z.write(n, n)

    z.close()

    length = b.tell()
    b.seek(0)
    sys.stdout.write(
        HEADERS % ('application/zip', 'test.zip', 'test.zip', length)
        )
    sys.stdout.write(b.read())
    b.close()



From steve at REMOVE-THIS-cybersource.com.au  Fri Jan 25 07:43:20 2008
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: Fri, 25 Jan 2008 12:43:20 -0000
Subject: inode number in windows XP
References: <3331a284-b786-42d5-bbe8-a764d59af920@c4g2000hsg.googlegroups.com>
Message-ID: <13pjmb84dt1m4fc@corp.supernews.com>

On Fri, 25 Jan 2008 04:28:43 -0800, asit wrote:

> why this program shows ambiguous behavior ??


You should read this page, it will help you solve your problem:

http://catb.org/~esr/faqs/smart-questions.html



-- 
Steven


From lasses_weil at klapptsowieso.net  Tue Jan 29 13:46:37 2008
From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger)
Date: Tue, 29 Jan 2008 19:46:37 +0100
Subject: Python noob SOS (any [former?] Perlheads out there?)
In-Reply-To: 
References: 
Message-ID: <479f7492$0$27193$9b4e6d93@newsspool1.arcor-online.net>

kj wrote:
> Is there any good reading (to ease the transition) for Perl
> programmers trying to learn Python?
> 

www.diveintopython.org

While it is a bit dated by now (Python 2.2), that thing worked wonders 
for me. Shows you Python in action and presents a fair amount of its 
philosophy along the way.

Maybe(!) that helps a bit.

/W


From arnodel at googlemail.com  Wed Jan 23 13:12:22 2008
From: arnodel at googlemail.com (Arnaud Delobelle)
Date: Wed, 23 Jan 2008 10:12:22 -0800 (PST)
Subject: Just for fun: Countdown numbers game solver
References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com>
	<5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> 
	
	<127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com>
	
Message-ID: <457550e3-f5e1-4fad-b553-c3e5e400dbb1@u10g2000prn.googlegroups.com>

On Jan 23, 3:45?pm, Terry Jones  wrote:
> Hi Arnaud and Dan

Hi Terry

> >>>>> "Arnaud" == Arnaud Delobelle  writes:
> >> What was wrong with the very fast(?) code you sent earlier?
>
> Arnaud> I thought it was a bit convoluted, wanted to try something I
> Arnaud> thought had more potential. ?I think the problem with the second
> Arnaud> one is that I repeat the same 'fold' too many times.
>
> and later:
>
> Arnaud> Yes, I've been doing this by writing an 'action' (see my code) that
> Arnaud> takes note of all reached results.
>
> These are both comments about pruning, if I understand you. In the first
> you weren't pruning enough and in the second you're planning to prune more.

Yes I think the first one is about pruning, I couldn't think of the
english word.

> I'm giving up thinking about this problem because I've realized that the
> pruning solution is fundamentally subjective. I.e., whether or not you
> consider two solutions to be the "same" depends on how hard you're willing
> to think about them (and argue that they're the same), or how smart you
> are.

FWIW, I have a clear idea of what the space of solutions is, and which
solutions I consider to be equivalent.  I'll explain it below.  I'm
not saying it's the right model, but it's the one within which I'm
thinking.

> I have a new version that does some things nicely, but in trying to do
> efficient pruning, I've realized that you can't satisfy everyone.
>
> Some examples for the problem with target 253, numbers = 100, 9, 7, 6, 3, 1
>
> Firstly, there are nice solutions that go way negative, like:
>
> ? 1 7 6 3 9 sub mul mul sub ? or ? 1 - 7 * 6 * (3 - 9)

I think it's best to forbid negatives.  Solutions always be written
without any negative intermediate answer.  E.g. 1-7*6*(3-9) can be
done as 1+7*6*(9-3).

>
> Here's a pruning example. Are these the "same"?
>
> ? 1 3 7 100 9 sub sub mul sub ?or ?1 - 3 * (7 - 100 - 9)

rather 1 - 3*(7 - (100 - 9))

> ? 1 3 7 9 100 sub add mul sub ?or ?1 - 3 * (7 - 9 - 100)

rather 1 - 3*(7 + (9 - 100))

Not allowing negatives means these are
   3*(100 - 9 - 7) + 1
or 3*(100 - (9 + 7)) + 1
or 3*(100 - 7 - 9) + 1

I don't consider these to be equivalent, because their equivalence
depends on understanding the meaning of subtraction and addition.
(I've also applied the 'big then small' rule explained below)

>
> I think many people would argue that that's really the "same" and that one
> of the two should not appear in the output. The same goes for your earlier
> example for 406. It's 4 * 100 + 2 x 3, and 2 x 3 + 100 * 4, and so on.

There is a simple rule that goes a long way: "big then small", i.e.
only allow a  b when a > b.
So the above is canonically written as 100*4 + 2*3.

>
> My latest program does all these prunings.
>
> But you can argue that you should push even further into eliminating things
> that are the same. You could probably make a pretty fast program that
> stores globally all the states it has passed through (what's on the stack,
> what numbers are yet to be used, what's the proposed op) and never does
> them again. But if you push that, you'll wind up saying that any two
> solutions that look like this:
>
> ? ....... 1 add
>
> e.g.
>
> ? 6 9 3 sub mul 7 mul 1 add ? or ?6 * (9 - 3) * 7 + 1
> ? 7 6 mul 9 3 sub mul 1 add ? or ?7 * 6 * (9 - 3) + 1
>
> are the same.

I honestly think this is outside the scope of this problem, which must
remain simple.  I'm not trying to convince you of anything, but I'll
just explain briefly what solutions I don't want to repeat.

I see a solution as a full ordered binary tree.  Each node has a
weight (which is the result of the calculation it represents) and the
left child of a node has to be at least as heavy as the right child.
Each parent node can be labeled + - * or /.
If a node x has two children y and z and is labeled , let me write
    x = (y  z)

so     6 9 3 sub mul 7 mul 1 add -> (((6 * (9 - 3)) * 7) + 1)
and    7 6 mul 9 3 sub mul 1 add -> (((7 * 6) * (9 - 3)) + 1)

are two distinct solutions according to my criterion.

But
       9 3 sub 6 mul 7 mul 1 add -> ((((9 - 3) * 6) * 7) + 1)

is not a solution because 9-3 < 6

To be perfectly honest (and expose my approach a little to your
argument) I added a three additional rules:

* Don't allow x - x
* Don't allow x * 1
* Don't allow x / 1

My aim was find and efficient way to generate all solutions exactly
once if there is no repeat in the list of starting numbers.  This is a
clearly defined problem and I wanted to find a nice way of solving
it.  I realised that the folding method was redundant in that respect
and this is what I wanted to fix (I have a fix, I think, but the
'proof' of it is only in my head and might be flawed).

If there are repeats in the list of starting numbers, I don't worry
about repeating solutions.

> If anyone wants the stack simulation code, send me an email.

I'd like to see it :)

--
Arnaud




From ickyelf at gmail.com  Sat Jan 19 14:15:21 2008
From: ickyelf at gmail.com (David Delony)
Date: Sat, 19 Jan 2008 19:15:21 GMT
Subject: Gui front-end to version control program
Message-ID: 

I spoke with Eric S. Raymond at a Linux user's group meeting a few days ago 
about the need for version control for end users.
I thought that Python might be a good candidate for this. 

Luckily, Guido was there as well. I talked this over with him and he
suggested using Google Documents sinceI usually collborate on text documents.

I want something that can work with any file, as Subversion does. I can't 
think of any 
GUI wrappers written in Python off the top of my head. I would like to use one
as a model and get my feet wet by contributing to it. I don't feel proficient
enough to lead a project yet. 


-- 
There's no place like ~!


From info at telenet.be  Tue Jan 29 21:00:39 2008
From: info at telenet.be (info at telenet.be)
Date: Wed, 30 Jan 2008 02:00:39 GMT
Subject: Telenet nieuwsgroepen mededeling: nieuwsserver adres
	aanpassen/Attention: modification de l'adresse du serveur de newsgroup
Message-ID: 

Beste klant,

Telenet heeft een migratie gedaan van haar nieuwsservers. 

Wat betekent dit concreet voor jou als gebruiker?

Er verandert niets aan de service, maar om verder gebruik te maken van de
Telenet nieuwsgroepen service moet je bij de instellingen van je nieuwslezer
het adres van de nieuwsserver veranderen van news.telenet.be of
newsbin.telenet.be in newsgroups.telenet.be. Verder dien je de authenticatie
op deze nieuwsserver uit te schakelen.

Met vriendelijke groeten,

Het Telenet team

----------------------------------------------------------------------------------------------------------
 
Cher client,
 
Telenet a effectue une migration de ses serveurs de newsgroup.

Pour continuer a utiliser les newsgroups de Telenet, modifiez dans la
configuration de lecteur de nouvelles l'adresse du serveur de newsgroup:
newsgroups.telenet.be a la place de news.telenet.be ou newsbin.telenet.be.
Ceci ne necessite pas que vous vous identifiez pour acceder a ce serveur de
newsgroup.
 
Cordialement,

L'equipe Telenet



From eliss.carmine at gmail.com  Mon Jan 14 22:48:34 2008
From: eliss.carmine at gmail.com (eliss)
Date: Mon, 14 Jan 2008 19:48:34 -0800 (PST)
Subject: reliable whois in python
Message-ID: 

Hi everyone,

I'm trying to write a python script to whois a few domains twice a day
so I get notified when they become available. I did it 2 ways, but
neither way is very reliable, so I'm asking here.

1) I tried just calling "whois %s" using popen, but I found that once
every few weeks, I get errors like:
connect: No route to host OR
fgets: Connection reset by peer
I don't think it's a connectivity issue because looking up the other
domains that day works, and just one domain will give an error. So
it's probably more like a networking issue? I don't know...

2) I tried using sockets to connect to the whois port of
whois.internic.net and then read the info, which works a little better
than 1). However, sometimes this is not reliable too and I get errors.

Does anyone have any ideas how I can do this better?

Thanks,

eliss


From bblais at bryant.edu  Tue Jan 29 17:55:18 2008
From: bblais at bryant.edu (Brian Blais)
Date: Tue, 29 Jan 2008 17:55:18 -0500
Subject: load movie frames in python?
Message-ID: <4697A1F5-6273-477D-8A6C-3BD34786CD64@bryant.edu>

Hello,

Is there a way to read frames of a movie in python?  Ideally,  
something as simple as:

for frame in movie('mymovie.mov'):
     pass


where frame is either a 2-D list, or a numpy array?  The movie format  
can be anything, because I can probably convert things, but most  
convenient would be avi, mov, and flv (for youtube videos).


		thanks,


			Brian Blais

-- 
Brian Blais
bblais at bryant.edu
http://web.bryant.edu/~bblais



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

From Russ.Paielli at gmail.com  Fri Jan  4 02:37:42 2008
From: Russ.Paielli at gmail.com (Russ P.)
Date: Thu, 3 Jan 2008 23:37:42 -0800 (PST)
Subject: C++ equivalent of comp.lang.python?
References: <60597295-1493-493c-969c-a14dd7da98a3@s19g2000prg.googlegroups.com>
Message-ID: <005550c8-00f6-42b2-b804-2d2baea0b60e@s8g2000prg.googlegroups.com>

On Jan 3, 9:39 am, brzr... at gmail.com wrote:
> Hopefully this isn't too OT.
>
> One thing I like about comp.lang.python is the breadth of topics
> discussed here.  People can ask about Python installation and
> configuration issues on specific platforms, compare third party
> libraries, ask for book recommendations, and discuss current Python
> projects.  Lurking here has greatly increased my understanding of
> Python over the last year or so.
>
> I also do a lot of C++ development, but I've never found a similar
> discussion group for that language.  comp.lang.c++ isn't what I'm
> looking for.  I find it hard to get practical advice on that group
> because its focus is so narrow.  I frequently see posters there
> redirect people to one of the OS-specific C++ groups, but most of my
> projects are cross-platform, so hanging out on one of those doesn't
> make sense either.  As an example, I was recently trying to get
> information about writing cross-platform code for dynamic linking, but
> I couldn't find anywhere appropriate to ask about it.
>
> For those of you who work in C++, where do you go to discuss it
> online?  I'm interested in any newsgroups, mailing lists, or web
> boards you can recommend.
>
> Thanks,
> Casey

Well, if the good folks at comp.lang.c++ can't even direct you to an
appropriate forum on C++, then I doubt the folks at comp.lang.python
can. I suggest you abandon C++ and try Python, Java, or Ada.


From MartinRinehart at gmail.com  Wed Jan  9 07:13:15 2008
From: MartinRinehart at gmail.com (MartinRinehart at gmail.com)
Date: Wed, 9 Jan 2008 04:13:15 -0800 (PST)
Subject: I'm searching for Python style guidelines
References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com>
	<1d895d6d-a649-439e-8223-0ae7d3a4eb40@l6g2000prm.googlegroups.com> 
	 
	<4fb7129f-3887-4e3b-a827-3255344047f3@c23g2000hsa.googlegroups.com> 
	
Message-ID: 



Matthew Woodcraft wrote:
> I think [the olpc guidlines are] mostly PEP 8, with some notes added.

Took a good look. You are absolutely correct.

PEP 8 is basically word processing text stuck between 
 and 
tags. OLPC is Wiki HTML. Good example of how the latter is a lot bigger than the former, with little extra content. From john.m.roach at gmail.com Wed Jan 9 11:48:46 2008 From: john.m.roach at gmail.com (John) Date: Wed, 9 Jan 2008 08:48:46 -0800 (PST) Subject: printing dots in simple program while waiting Message-ID: Ok, so this should be a really simple thing to do, but I haven't been able to get it on the first few tries and couldn't find anything after searching a bit. what i want to do is print a 'waiting' statement while a script is working-- the multithreading aspect isn't an issue, the printing on the same line is. i want to print something like: (1sec) working... (2sec) working.... (3sec) working..... where the 'working' line isn't being printed each second, but the dots are being added with time. something like: import time s = '.' print 'working' while True: print s time.sleep(1) however, this doesn't work since it prints: working . . . any suggestions? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 06:45:59 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 12:45:59 +0100 Subject: anti-spam policy for c.l.py? In-Reply-To: <08ed32c4-6230-4b14-9c31-4b94e0231cf2@c4g2000hsg.googlegroups.com> References: <08ed32c4-6230-4b14-9c31-4b94e0231cf2@c4g2000hsg.googlegroups.com> Message-ID: <478dee4e$0$28424$426a34cc@news.free.fr> _wolf a ?crit : > this list has been receiving increasing amounts of nasty OT spam > messages for some time. are there any plans to prevent such messages > from appearing on the list or to purge them retrospectively? Apart from checking posts headers and complaining about the relevant ISPs, there's not much you can do AFAIK. This is usenet, not a mailing-list. From gagsl-py2 at yahoo.com.ar Fri Jan 25 12:50:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 Jan 2008 09:50:22 -0800 (PST) Subject: inode number in windows XP References: <3331a284-b786-42d5-bbe8-a764d59af920@c4g2000hsg.googlegroups.com> Message-ID: On 25 ene, 10:28, asit wrote: > why this program shows ambiguous behavior ?? > > st=os.stat(file_name) > print "file size", "=>",st[stat.ST_SIZE] > print "inode number", "=>",st[stat.ST_INO] > print "device inode resides on", "=>",st[stat.ST_DEV] > print "number of links to this inode", "=>",st[stat.ST_NLINK] > > i ran this program in Winows XP SP2 in python 2.5. Using my recently repaired crystal ball, I see that you don't get what you expect for some of those fields. All files sharing the same inode, by example. The usual file systems used by Windows aren't built around the inode concept, they're different, so there is no "inode number" to report, among other things. From http://docs.python.org/lib/os-file-dir.html "On Windows, some items are filled with dummy values". Don't rely on anything but st_mode, st_size, and st_[cma]time, and perhaps a few more for fstat. -- Gabriel Genellina From asmodai at in-nomine.org Tue Jan 8 03:58:34 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 09:58:34 +0100 Subject: Strip lines from files In-Reply-To: <455957.93301.qm@web57611.mail.re1.yahoo.com> References: <455957.93301.qm@web57611.mail.re1.yahoo.com> Message-ID: <20080108085834.GG75977@nexus.in-nomine.org> -On [20080108 09:40], Francesco Pietra (chiendarret at yahoo.com) wrote: >A variant need has now emerged, to perform the same task from a very long >series of shorter files trp.pdb.1, trp.pdb.2 ,..... Could you see how to adapt >the above script to the new need? Look at sys.argv and pass the list of files to your script as a wildcard: ./myscript.py trp.pdb.* And iterate over every argv you have to strip the WAT. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ The wisdom of the wise, and the experience of ages, may be preserved by quotations... From fredrik at pythonware.com Fri Jan 11 07:14:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jan 2008 13:14:24 +0100 Subject: import gzip error (please help) In-Reply-To: References: Message-ID: syahreza.octadian wrote: > Please help, i have error message when i import gzip module. The error > like this below: > > bash-3.00$ python > Python 2.5 (r25:51908, Sep 20 2006, 03:46:40) > [GCC 3.4.6] on sunos5 > Type "help", "copyright", "credits" or "license" for more information. >>>> import gzip > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python2.5/gzip.py", line 9, in > import zlib > ImportError: ld.so.1: python: fatal: relocation error: file /usr/local/ > lib/python2.5/lib-dynload/zlib.so: symbol inflateCopy: referenced > symbol not found the core zlib library (libz.so) isn't installed on your machine. From lists at cheimes.de Thu Jan 24 09:28:44 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 24 Jan 2008 15:28:44 +0100 Subject: When is min(a, b) != min(b, a)? In-Reply-To: References: Message-ID: Antoon Pardon wrote: > That doesn't follow. The problem is not that x < nan returns False > because that is correct since x isn't smaller than nan. The problem > is cmp(x, nan) returning 1, because that indicates that x is greater > than nan and that isn't true. Please report the problem. cmp(), min() and max() don't treat NaNs right. I don't think that x < nan == False is the correct answer, too. But I've to check the IEEE 754 specs. IMHO < nan and > nan should raise an exception. Christian From lepto.python at gmail.com Sun Jan 6 21:50:01 2008 From: lepto.python at gmail.com (Oyster) Date: Sun, 6 Jan 2008 18:50:01 -0800 (PST) Subject: Why python says "unexpected parameter 'mini.py'" for my code? References: Message-ID: <6bbf668a-2713-4f65-8e89-2d51a5accc16@e25g2000prg.googlegroups.com> you need wx-c.so from wxnet.sourceforge.net on linux My source uses wx-c.dll, because I am in ms win2k On Jan 4, 10:30 pm, Nick Craig-Wood wrote: > oyster wrote: > > The following is my pure-python wxwidgets test. > > It is hardly pure python since it depends on wxWindows and ctypes... > > > It runs and give a frame, but soon python comes up to say > > "unexpected parameter > > 'mini.py'" and I have to close it. > > I cannot find the reason. Can somebody give me a hint to let it work > > well? Thanks > > I tried it but it doesn't work at all on linux. > > I suggest you use wxPython and stop re-inventing the wheel! > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick From python at rolfvandekrol.nl Tue Jan 22 08:02:01 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Tue, 22 Jan 2008 14:02:01 +0100 Subject: stdin, stdout, redmon In-Reply-To: References: <4794a5e3$0$9014$426a74cc@news.free.fr> <4794ab22$0$19179$426a74cc@news.free.fr> <4795ba80$0$17176$426a74cc@news.free.fr> Message-ID: <4795E949.6090508@rolfvandekrol.nl> Well, that's at least weird. I did test my code with Python 2.5 on Win XP, using the command prompt. But testing it with IDLE gives exactly the same error Bernard has. So apparently STDIN can't be accessed with IDLE. Rolf John Machin wrote: > > Excuse me, gentlemen, may I be your referee *before* you resort to > pistols at dawn? > > ===== IDLE ===== > IDLE 1.2.1 > >>>> import sys >>>> sys.stdin.readlines >>>> > > Traceback (most recent call last): > File "", line 1, in > sys.stdin.readlines > AttributeError: readlines > > > ===== Command Prompt ===== > C:\junk>python > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>> import sys >>>> sys.stdin.readlines >>>> > > > > HTH, > John > From arnodel at googlemail.com Tue Jan 1 04:32:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 1 Jan 2008 01:32:18 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <6aba9463-f0ea-43a2-b8de-9c7026c4d14e@e4g2000hsg.googlegroups.com> <75ea72e9-f69f-4b3a-98fe-ffc364fa7543@l6g2000prm.googlegroups.com> Message-ID: <8552dc15-0b82-4f5c-a44c-8f5c4b72f239@e4g2000hsg.googlegroups.com> On Jan 1, 5:26?am, NickC wrote: > On Jan 1, 3:22 am, Arnaud Delobelle wrote: > > > On Dec 31, 10:58 am, Odalrick wrote: > > > > I'm surprised noone has said anything about the why of default > > > mutables. I think it is becasue it isn't easy to do it an other way. > > > [...] > > > There is an easy enough way: evaluate default values when the function > > is called rather than when it is defined. ?This behaviour comes with > > its own caveats as well I imagine, and it's not 'as easy' to implement > > as the current one. > > As Odalrick notes, there is no way to give different calls to a > function their own copies of mutable default arguments without re- > evaluating the defaults every time the function is called. The > horrendous performance implications mean that that simply isn't going > to happen. So the status quo, where the defaults are calculated once > when the function is defined and the result cached in the function > object is unlikely to change. I'm in no way advocating a change, in fact I wouldn't like things to change. I was just saying that it was not difficult (technically) to alter the behaviour, but that this change wouldn't be desirable because it would make code more difficult to reason on. OTOH a very common idiom in python is def foo(x, y, z=None): if z is None: z = ['a', 'mutable', 'object'] # stuff that foo does This the current way to say "I want the default value of z to be reevaluated each time it is used". I use this much more often than def bar(x, y, z=ExpensiveImmutableCreation()) So I'm not so convinced with the performance argument at face value (though it's probably pertinent:) > > What's good about the current behaviour is that it is easy to reason > > with (once you know what happens), even though you almost have to get > > bitten once. ?But using this to have static variable is extremely ugly > > IMHO. > > The only thing it doesn't give you is a static variable that isn't > visible to the caller. Py3k's keyword-only arguments (PEP 3102) will > make those cases a little tidier, since it won't be possible to > accidentally replace the static variables by providing too many > positional arguments. I was always a bit puzzled by this PEP. If this is one of the underlying reasons for it, then I am even more puzzled. > I believe the suggestion of permitting static variables after the ** > entry in a function's parameter list was raised during the PEP 3102 > discussions, but never gained much traction over a '_cache={}' keyword- > only argument approach (and the latter has the distinct advantage of > being *much* easier to test, since you can override the cache from the > test code to ensure it is being handled correctly). Well I'm glad that didn't go through, argument lists in function definitions are complicated enough already! -- Arnaud From kirby.urner at gmail.com Wed Jan 9 18:05:25 2008 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: Wed, 9 Jan 2008 15:05:25 -0800 (PST) Subject: Collecting Rich Data Structures for students References: <8b4e7954-b666-4515-9ae2-821d979ebd7f@m34g2000hsf.googlegroups.com> Message-ID: On Jan 9, 8:15 am, Paddy wrote: > On Jan 9, 6:52 am, Paddy wrote: > > > > > On Jan 9, 2:19 am, "kirby.ur... at gmail.com" > > wrote: > > > > Greetings Pythoneers -- > > > > Some of us over on edu-sig, one of the community actives, > > > have been brainstorming around this Rich Data Structures > > > idea, by which we mean Python data structures already > > > populated with non-trivial data about various topics such > > > as: periodic table (proton, neutron counts); Monty Python > > > skit titles; some set of cities (lat, long coordinates); types > > > of sushi. > > > > Obviously some of these require levels of nesting, say > > > lists within dictionaries, more depth of required. > > > > Our motivation in collecting these repositories is to give > > > students of Python more immediate access to meaningful > > > data, not just meaningful programs. Sometimes all it takes > > > to win converts, to computers in general, is to demonstrate > > > their capacity to handle gobs of data adroitly. Too often, > > > a textbook will only provide trivial examples, which in the > > > print medium is all that makes sense. > > > > Some have offered XML repositories, which I can well > > > understand, but in this case we're looking specifically for > > > legal Python modules (py files), although they don't have > > > to be Latin-1 (e.g. the sushi types file might not have a > > > lot of romanji). > > > > If you have any examples you'd like to email me about, > > > kirby.ur... at gmail.com is a good address. > > > > Here's my little contribution to the mix:http://www.4dsolutions.net/ocn/python/gis.py > > > > Kirby Urner > > > 4D Solutions > > > Silicon Forest > > > Oregon > > > I would think there was more data out there formatted as Lisp S- > > expressions than Python data-structures. > > Wouldn't it be better to concentrate on 'wrapping' XML and CSV data- > > sources? > > > - Paddy. > > The more I think on it the more I am against this- data should be > stored in programming language agnostic forms but which are easily > made available to a large range of programming languages. > If the format is easily parsed by AWK then it is usually easy to parse > in a range of programming languages. > > - Paddy. It's OK to be against it, but as many have pointed out, it's often just one value adding step to go from plaintext or XML to something specifically Python. Sometimes we spare the students (whomever they may be) this added step and just hand them a dictionary of lists or whatever. We may not be teaching parsing in this class, but chemistry, and having the info in the Periodic Table in a Python data structure maybe simply be the most relevant place to start. Many lesson plans I've seen or am working on will use these .py data modules. Kirby From fredrik at pythonware.com Sun Jan 20 07:51:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jan 2008 13:51:08 +0100 Subject: Memory errors with imaplib In-Reply-To: <6012daff-0fd3-4835-a9ca-c18d2a2ac53c@v29g2000hsf.googlegroups.com> References: <6012daff-0fd3-4835-a9ca-c18d2a2ac53c@v29g2000hsf.googlegroups.com> Message-ID: Martey wrote: > I am trying to use imaplib to download messages, but I keep getting > memory errors when I try to download a large message (i.e. one with > attachments). Here is my test code (similar to the example in the > imaplib documentation): > /.../ > I am using Mac OS X 10.5 and Python 2.5.1 (downloaded from > python.org). I think it is possible that it is issue1092502>, but the workarounds suggested there do not seem to work > for me. Is this an actual Python bug, or am I doing something wrong? looks like a known bug in imaplib: http://bugs.python.org/issue1389051 "In a worst case scenario, you'll need some 13 gigabytes of virtual memory to read a 15 megabyte message..." From benjamin.zimmerman at gmail.com Fri Jan 25 00:14:22 2008 From: benjamin.zimmerman at gmail.com (benjamin.zimmerman at gmail.com) Date: Thu, 24 Jan 2008 21:14:22 -0800 (PST) Subject: Which is more pythonic? Message-ID: <56518bb9-1d56-47c3-8112-6e0778832c12@v29g2000hsf.googlegroups.com> I have a goal function that returns the fitness of a given solution. I need to wrap that function with a class or a function to keep track of the best solution I encounter. Which of the following would best serve my purpose and be the most pythonic? class Goal: def __init__(self, goal): self.goal = goal self.best = None self.best_score = None def __call__(self, solution): score = self.goal(solution) if self.best is None or score > self.best_score: self.best_score = score self.best = solution return score def save_best_goal(goal): def new_goal(solution): score = goal(solution) if new_goal.best is None or score > new_goal.best_score: new_goal.best = solution new_goal.best_score = score return score new_goal.best = new_goal.best_score = None return new_goal -Ben From gnewsg at gmail.com Sun Jan 13 22:38:47 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 13 Jan 2008 19:38:47 -0800 (PST) Subject: Threaded server Message-ID: Hi, I'm trying to run an asynchronous FTP server I wrote into a thread for being able to run a test suite against it. The code below is the threaded FTP server code I'm using: --- snippet --- class FTPd(threading.Thread): def __init__(self): self.active = False threading.Thread.__init__(self) def start(self, flag=None): assert not self.active self.flag = flag threading.Thread.start(self) def run(self): assert not self.active ftpd = ftpserver.FTPServer(address, ftp_handler) if self.flag: self.flag.set() self.active = True while self.active: ftpd.server_forever(timeout=1, count=1) ftpd.close() def stop(self): assert self.active self.active = False flag = threading.Event() ftpd = FTPd() ftpd.start(flag) flag.wait() # wait for it to start unittest.main() # run the test suite ftpd.stop() --- /snippet --- Sometimes I get a strange error when all the tests have finished, the server is stopped and Python is exiting: ---------------------------------------------------------------------- Ran 50 tests in 1.515s OK Exception exceptions.TypeError: "'NoneType' object is not callable" in > ignored Exception exceptions.TypeError: "'NoneType' object is not callable" in > ignored I sincerely don't know why that happens but it's likely because I'm not using threads properly. My concern is that this could be caused by a sort of race condition (e.g. Python tries to exit when ftpd.close call is not yet completed). I tried to put a lock in the close() method for waiting the run() method to be completed before returning but I didn't solve the problem. Another information, in case it could be useful, is that this seems to happen with Python 2.3 only. By using 2.4 and Python 2.5 I have no problems. In such cases which is the right way for doing things? Using setDaemon(True)? Could someone point me in the right direction? I've always used the asynchronous approach and dealing with threads is a real pain for me. Thanks in advance. -- Giampaolo From DustanGroups at gmail.com Sun Jan 27 18:26:19 2008 From: DustanGroups at gmail.com (Dustan) Date: Sun, 27 Jan 2008 15:26:19 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> Message-ID: <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> On Jan 27, 12:41 pm, Torsten Bronger wrote: > Hall?chen! > > > > Wildemar Wildenburger writes: > > Andr? wrote: > > >> Personally, I like the idea you suggest, with the modification > >> that I would use "." instead of "@", as in > > >> class Server(object): > >> def __init__(self, .host, .port, .protocol, .bufsize, .timeout): > >> pass > > > I like :) > > > However, you can probably cook up a decorator for this (not > > certain, I'm not a decorator Guru), which is not that much worse. > > > Still, I'd support that syntax (and the general idea.). > > Well, you save one or two lines per class. Not enough in my > opinion. Are you referring to the alternate syntax or to the decorator? Either way, you could be saving 4 or 5 or more lines, if you have enough arguments. From arnodel at googlemail.com Thu Jan 31 17:53:54 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 31 Jan 2008 14:53:54 -0800 (PST) Subject: helper function in a class' namespace References: <47a226bb$0$2982$ba620e4c@news.skynet.be> <47a22a17$0$8306$9b622d9e@news.freenet.de> Message-ID: <386f1e82-aaf0-4585-b4fb-ee705aa1681b@v17g2000hsa.googlegroups.com> On Jan 31, 8:05?pm, Stargaming wrote: [...] > > class A(object): > > ? ?def Helper(M) : > > ? ? ?return 'H>'+M > > ? ?def __init__(self,Msg) : > > ? ? ?print Helper(Msg) > > > doesn't work since Python is looking for a global function Helper (why?) > > Because in the scope of the ``__init__`` function, the name ``Helper`` is > not bound. It then jumps out to the global scope. But it is 'Helper' bound in the scope of the *definition* of __init__, hence you *could* write: >>> class A(object): ... def _helper(x): return '<<%s>>' % x ... def __init__(self, msg, _helper=_helper): ... print _helper(msg) ... del _helper ... >>> A('spam') <> <__main__.A object at 0x70170> Confusingly yours, -- Arnaud From CHanemann at cch.com.au Tue Jan 29 18:43:54 2008 From: CHanemann at cch.com.au (Christian Hanemann) Date: Wed, 30 Jan 2008 10:43:54 +1100 Subject: ImageFilter failing for mode = 1 Message-ID: Hello, I'm trying to sharpen some JPEGs after resizing and am being given a valueError as per the below: File "getGraphicDetails.py", line 32, in main enhancer = ImageEnhance.Sharpness(img) File "/usr/local/lib/python2.3/site-packages/PIL/ImageEnhance.py", line 89, in __init__ self.degenerate = image.filter(ImageFilter.SMOOTH) File "/usr/local/lib/python2.3/site-packages/PIL/Image.py", line 786, in filter return self._new(filter.filter(self.im)) File "/usr/local/lib/python2.3/site-packages/PIL/ImageFilter.py", line 55, in filter return apply(image.filter, self.filterargs) ValueError: image has wrong mode Does anyone know if I'm just using an old version of PIL and this has subsequently been addressed or if I'm using it incorrectly. It appears to die on the line: enhancer = ImageEnhance.Sharpness(img) If I put in an: If img.mode = "1": enhancer = ImageEnhance.Sharpness(img.convert("L")) it works fine, but I was wondering if the library should or does work without having to convert. Thankyou -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcroy.olsen at gmail.com Wed Jan 23 10:35:44 2008 From: marcroy.olsen at gmail.com (marcroy.olsen at gmail.com) Date: Wed, 23 Jan 2008 07:35:44 -0800 (PST) Subject: Lxml on mac References: <47975B09.8090705@web.de> Message-ID: On Jan 23, 4:19?pm, Stefan Behnel wrote: > marcroy.ol... at gmail.com wrote: > > What to one do if one what to use lxml(http://codespeak.net/lxml/ > > index.html) on a mac? > > Have you tried installing up-to-date versions of libxml2/libxslt and running > > ? ?easy_install lxml > > ? > > Stefan No not yet. That was my nest step. But do anybody know if there is an easy way to use schema validation in python(on a mac) ? From rupert.thurner at gmail.com Sat Jan 19 09:49:43 2008 From: rupert.thurner at gmail.com (rupert.thurner) Date: Sat, 19 Jan 2008 06:49:43 -0800 (PST) Subject: finding memory leak in edgewall trac 0.11 Message-ID: what would be a good means of finding where the 0.11 version of edgewall trac uses excessive memory. see http://groups.google.com/group/trac-dev/browse_thread/thread/116e519da54f16b for some details, where jonas suggested http://wingolog.org/archives/2007/11/27/reducing-the-footprint-of-python-applications as reading. tiran already gave some hints on http://bugs.python.org/issue1871, but also suggested to ask the general mailing list: Do you have classes with a __del__ method which may create reference cycles? The GC can't break cycles when a __del__ method is involved. Are you keeping references to tracebacks, exception objects (except Exception, err) or frames (sys._getframe()) many thanks, rupert. From deets at nospam.web.de Tue Jan 15 08:31:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 Jan 2008 14:31:39 +0100 Subject: "env" parameter to "popen" won't accept Unicode on Windows -minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net><5v2cudF1k5a1oU1@mid.individual.net><478c551a$0$36354$742ec2ed@news.sonic.net> <5v3dq9F1k2577U1@mid.uni-berlin.de> Message-ID: <5v3qtsF1khn11U1@mid.uni-berlin.de> Brian Smith wrote: > Diez B. Roggisch wrote: >> Sure thing, python will just magically convert unicode to the >> encoding the program YOU invoke will expect. Right after we >> introduced the >> >> solve_my_problem() >> >> built-in-function. Any other wishes? > > There's no reason to be rude. If you'd know John, you'd know there is. > Anyway, at least on Windows it makes perfect sense for people to expect > Unicode to be handled automatically. popen() knows that it is running on > Windows, and it knows what encoding Windows needs for its environment > (it's either UCS2 or UTF-16 for most Windows APIs). At least when it > receives a unicode string, it has enough information to apply the > conversion automatically, and doing so saves the caller from having to > figure out what exact encoding is to be used. For once, the distinction between windows and other platforms is debatable. I admit that subprocess contains already quite a few platform specific aspects, but it's purpose is to abstract these away as much as possible. However, I'm not sure that just because there are wide-char windows apis available automatically means that using UCS2/UTF-16 would succeed. A look into the python sources (PC/_subprocess.c) reveals that someone already thought about this, but it seems that just setting a CREATE_UNICODE_ENVIRONMENT in the CreateProcess-function should have been easy enough to do it if there weren't any troubles to expect. Additionally, passing unicode to env would also imply that os.environ should yield unicode as well. Not sure how much code _that_ breaks. Diez From gagsl-py2 at yahoo.com.ar Sun Jan 27 13:55:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 16:55:18 -0200 Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> <87dd811e-3095-41d0-80fd-7312338e5254@i3g2000hsf.googlegroups.com> <489b6fc5-e871-425e-b242-45be618fc9f4@n20g2000hsh.googlegroups.com> <87r6g4q7hq.fsf@mulj.homelinux.net> Message-ID: En Sun, 27 Jan 2008 12:51:51 -0200, Dox33 escribi?: > Yes, I know. > There are several ways to work around the problem. > (Look at the innitial code I provided in this discussion start) > Fact is, every time I'm getting a script from somewhere or someone, I > have to search and replace all the affected code. > Not very conveniant. > That's why I rather would have a correct working version. Add this on your sitecustomize.py module (or create one) import sys def raw_input(prompt=None): if prompt: sys.stdout.write(prompt) return original_raw_input() import __builtin__ original_raw_input = __builtin__.raw_input __builtin__.raw_input = raw_input It just replaces the builtin raw_input with a custom function. -- Gabriel Genellina From peter.schuller at infidyne.com Thu Jan 24 08:57:49 2008 From: peter.schuller at infidyne.com (Peter Schuller) Date: Thu, 24 Jan 2008 07:57:49 -0600 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> Message-ID: >> Not necessarily. In part it is the name, in that __name__ will be >> different. But to the extent that calling code can potentially import >> them under differents names, it's identity. Because importing the same >> module under two names results in two distinct modules (two distinct >> module objects) that have no realation with each other. So for >> example, if a module has a single global protected by a mutex, there >> are suddenly two copies of that. In short: identity matters. > > That's not true. It doesn't matter if you Import a module several times > at different places and with different names, it's always the same module > object. Sorry, this is all my stupidity. I was being daft. When I said importing under different names, I meant exactly that. As in, applying hacks to import a module under a different name by doing it relative to a different root directory. This is however not what anyone is suggesting in this discussion. I got my wires crossed. I fully understand that "import x.y.z" or "import x.y.z as B", and so one do not affect the identity of the module. > Ok, there is one exception: the main script is loaded as __main__, but if > you import it using its own file name, you get a duplicate module. > You could confuse Python adding a package root to sys.path and doing > imports from inside that package and from the outside with different > names, but... just don't do that! Right :) > I don't really understand what your problem is exactly, but I think you > don't require any __import__ magic or arcane hacks. Perhaps the __path__ > package attribute may be useful to you. You can add arbitrary directories > to this list, which are searched for submodules of the package. This way > you can (partially) decouple the file structure from the logical package > structure. But I don't think it's a good thing... That sounds useful if I want to essentially put the contents of a directory somewhere else, without using a symlink. In this case my problem is more related to the "file == module" and "directory == module" semantics, since I want to break contents in a single module out into several files. > Isn't org.lib.animal a package, reflected as a directory on disk? That's > the same both for Java and Python. Monkey.py and Tiger.py would be modules > inside that directory, just like Monkey.java and Tiger.java. Aren't the > same thing? No, because in Java Monkey.java is a class. So we have class Monkey in package org.lib.animal. In Python we would have class Monkey in module org.lib.animal.monkey, which is redundant and does not reflect the intended hierarchy. I have to either live with this, or put Monkey in .../animal/__init__.py. Neither option is what I would want, ideally. Java does still suffer from the same problem since it forces "class == file" (well, "public class == file"). However it is less of a problem since you tend to want to keep a single class in a single file, while I have a lot more incentive to split up a module into different files (because you may have a lot of code hiding behind the public interface of a module). So essentially, Java and Python have the same problem, but certain aspects of Java happens to mitigate the effects of it. Languages like Ruby do not have the problem at all, because the relationship between files and modules is non-existent. -- / Peter Schuller PGP userID: 0xE9758B7D or 'Peter Schuller ' Key retrieval: Send an E-Mail to getpgpkey at scode.org E-Mail: peter.schuller at infidyne.com Web: http://www.scode.org From boblatest at yahoo.com Tue Jan 8 04:47:25 2008 From: boblatest at yahoo.com (Robert Latest) Date: 8 Jan 2008 09:47:25 GMT Subject: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> <5ugulaF1hqn2cU1@mid.uni-berlin.de> Message-ID: <5ugv5dF1i0edtU1@mid.dfncis.de> Marc 'BlackJack' Rintsch wrote: > Both processes have to make their communication ends unbuffered or line > buffered. Yeah, I figured something like that. > And do whatever is needed to output the numbers from ``slow`` > unbuffered or line buffered. Hm, "slow" of course is just a little test program I wrote for this purpose. In reality I want to call another program whose behavior I can't influence (well, technically I could because it's open-source, but let's assume it to be a black box for now). If 'slow' or some other program does buffered output, how come I can see its output line-by-line in the shell? robert From PurpleServerMonkey at gmail.com Sun Jan 27 20:23:33 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Sun, 27 Jan 2008 17:23:33 -0800 (PST) Subject: Struct.Pack and Binary files Message-ID: Having trouble working out an appropriate format string for packing a binary file. The below is something I use for ASCII files but now I need something equivalent for working with binary files i.e jpg, zips etc. fileHandle = open("test.txt") while loop: fileBuffer = fileHandle.read(512) format = "!hh%dc" % len(fileBuffer) outdata = struct.pack(format, *fileBuffer) clientSocket.sendto(outdata, DestAddress) I've reused the basic structure below for a binary file, the issue I'm having is working out the correct format string. At first I thought a float or double would have been the one to use but the interpreter complains about invalid types being passed. fileHandle = open("test.zip", "rb") while loop: fileBuffer = fileHandle.read(512) format = "!hh%dd" % len(fileBuffer) outdata = struct.pack(format, *fileBuffer) clientSocket.sendto(outdata, DestAddress) If someone could shed some light on the problem it would be appreciated, I'm clearly missing something fairly obvious. Thanks in advance. From bignose+hates-spam at benfinney.id.au Fri Jan 11 20:44:22 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Jan 2008 12:44:22 +1100 Subject: encrypting python modules References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <87sl14getd.fsf@benfinney.id.au> <5uqi86F6710oU1@mid.uni-berlin.de> Message-ID: <87k5mfhl6x.fsf@benfinney.id.au> Marc 'BlackJack' Rintsch writes: > On Sat, 12 Jan 2008 09:47:26 +1100, Ben Finney wrote: > > > Trying to make bits uncopyable and unmodifiable is like trying to > > make water not wet. > > Certainly not. I can put water into the freezer Turning it into ice, and making it not useable as water. So, to the extent you've made it not-wet, you've also made it not-water. To torture the analogy further, this would be equivalent to engraving the bits in stone and sealing the whole in a concrete slab. While still technically the bits can be extracted, the extent to which they are uncopyable and unmodifiable is exactly the extent to which they are useless as bits. As soon as they become available for use as digital bits in some way, they become available for copying and modifying again. -- \ "People demand freedom of speech to make up for the freedom of | `\ thought which they avoid." -- Soren Aabye Kierkegaard | _o__) (1813-1855) | Ben Finney From steven.p.clark at gmail.com Thu Jan 10 17:32:12 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Thu, 10 Jan 2008 17:32:12 -0500 Subject: Newbie question on Classes In-Reply-To: <8cf64cf7-d38c-4239-b188-b0b861407512@j78g2000hsd.googlegroups.com> References: <8cf64cf7-d38c-4239-b188-b0b861407512@j78g2000hsd.googlegroups.com> Message-ID: <663744510801101432s154dad96ib3b280da65a60d30@mail.gmail.com> > l = [] > l.append(man) > l.append(woman) > > # Print the state. > for item in l: > print item.state() > > Small, off-topic nitpick: please don't use "l" (lower-case el) as a variable name. >From http://www.python.org/dev/peps/pep-0008/: "Naming Conventions Names to Avoid Never use the characters `l' (lowercase letter el), `O' (uppercase letter oh), or `I' (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use `l', use `L' instead." From paddy3118 at googlemail.com Sat Jan 26 03:12:20 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 26 Jan 2008 00:12:20 -0800 (PST) Subject: Testing whether something is of type Exception References: <47991a8a$0$36353$742ec2ed@news.sonic.net> Message-ID: <09a2f59e-b6a8-40f7-ac80-c17792c47578@e25g2000prg.googlegroups.com> On Jan 24, 11:14 pm, John Nagle wrote: > How can I tell whether an object is of type Exception? Use it as if it is one and catch any exceptions :-) - Paddy. (Grabs coat, heads for the exit) From ggpolo at gmail.com Wed Jan 23 15:55:04 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jan 2008 18:55:04 -0200 Subject: Creating new types and invoking super Message-ID: Hello, Before starting, let me show some sample codes so I can explain: class A(object): def __init__(self): super(A, self).__init__() x = type("X", (A, ), {})() This works fine, but suppose I have several classes like A and I would like to create a decorator to call super. First I tried this: def init(func): def _init(inst): super(inst.__class__, inst).__init__() func(inst) return _init class A(object): @init def __init__(self): pass This works when I create a instance by doing A(), but I get "RuntimeError: maximum recursion depth exceeded" when I create a new type doing type("X", (A, ), {}) and then create an instance of it. To "solve" this problem, I changed the init function to this then: def init(func): def _init(inst): super(inst.__class__.__mro__[-2], inst).__init__() func(inst) return _init It works if A is a direct subclass of object, if it is not I have to adapt the index [-2]. So, is there a better way to do this ? -- -- Guilherme H. Polo Goncalves From JAMoore84 at gmail.com Sat Jan 26 12:02:17 2008 From: JAMoore84 at gmail.com (JAMoore84 at gmail.com) Date: Sat, 26 Jan 2008 09:02:17 -0800 (PST) Subject: Beginner String formatting question Message-ID: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> Hi all, I am trying to write a simple program that will accept an integral "time" input in the HHMMSS format and output a "HH:MM:SS" form. My code is as follows: ======================== import string def FormatTime(time): '''Converts an HHMMSS string to HH:MM:SS format.''' timeString = str(time) #converts the num to string hours = [timeString[0], timeString[1]] minutes = [timeString[2], timeString[3]] seconds = [timeString[4], timeString[5]] Ftime = "%s:%s:%s",(hours,minutes,seconds) clock = Ftime.join() return clock =========================== when I run it from IDLE, I get this: >>> Format.FormatTime(time) ['1', '1', ':', '2', '2', ':', '3', '3'] ['1', '1', ':', '2', '2', ':', '3', '3'] My questions- 1) Why is this function printing out twice? 2)It may be a formatting issue, but I want to have the output as "HH:MM:SS", rather than having it broken out into each cell. I thought the 'join' command would do this, but I must not be using it properly/understanding something. 3)as a side note, I've noticed that the parameter "time" passed in must be passed in as a string, otherwise I receive an error that "time" is unsubscriptable. Am I unable to pass in an int and then convert it to a string within the function with str()? I've been at this for a while, so I may not be able to see the forest through the trees at this point. I'd greatly appreciate any suggestions or instruction on these mistakes. Best, Jimmy From siona at chiark.greenend.org.uk Fri Jan 4 12:08:23 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 04 Jan 2008 17:08:23 +0000 (GMT) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: >BTW if you're using C++, why not simply use std::set? Because ... how to be polite about this? No, I can't. std::set is crap. The implementation is a sorted sequence -- if you're lucky, this is a heap or a C array, and you've got O(log n) performance. But the real killer is that requirement for a std::set is that T::operator< exists. Which means, for instance, that you can't have a set of complex numbers.... -- \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 __peter__ at web.de Fri Jan 11 07:32:36 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jan 2008 13:32:36 +0100 Subject: reading a specific column from file References: Message-ID: A.T.Hofkamp wrote: > On 2008-01-11, cesco wrote: >> Hi, >> >> I have a file containing four columns of data separated by tabs (\t) >> and I'd like to read a specific column from it (say the third). Is >> there any simple way to do this in Python? >> >> I've found quite interesting the linecache module but unfortunately >> that is (to my knowledge) only working on lines, not columns. >> >> Any suggestion? > > the csv module may do what you want. Here's an example: >>> print open("tmp.csv").read() alpha beta gamma delta one two three for >>> records = csv.reader(open("tmp.csv"), delimiter="\t") >>> [record[2] for record in records] ['gamma', 'three'] Peter From richardjones at optushome.com.au Mon Jan 7 15:51:45 2008 From: richardjones at optushome.com.au (Richard Jones) Date: Tue, 08 Jan 2008 07:51:45 +1100 Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Message-ID: <478290e1$0$32673$afc38c87@news.optusnet.com.au> Berco Beute wrote: > What I would like to know is what it was that boosted Python's > popularity in 2004 (see http://www.tiobe.com/tiobe_index/Python.html). > Equally interesting is the question why it dropped shortly after. They explain the discontinuity on the index page in the FAQ. Richard From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Jan 26 08:47:50 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 26 Jan 2008 14:47:50 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <600s07F1m9jgbU1@mid.individual.net> over at thepond.com wrote: > Intel processors can only process machine language[...] There's no > way for a processor to understand any higher level language, even > assembler, since it is written with hexadecimal codes and basic > instructions like MOV, JMP, etc. The assembler compiler can > convert an assembler file to a binary executable, which the > processor can understand. This may be true, but I think it's not bad to assume that machine language and assembler are "almost the same" in this context, since the translation between them is non-ambiguous (It's just "recoding"; this is not the case with HLLs). > Both Linux and Windows compile down to binary files, which are > essentially 1's and 0's arranged in codes that are meaningful to > the processor. (Not really -- object code files are composed of header data and different segments, data and code, and only the code segments are really meaningful to the processor.) > Once a python py file is compiled into a pyc file, I can > disassemble it into assembler. But you _do_ know that pyc files are Python byte code, and you could only directly disassemble them to Python byte code directly? > Assembler is nothing but codes, which are combinations of 1's and > 0's. No, assembly language source is readable text like this (gcc): .LCFI4: movl $0, %eax popl %ecx popl %ebp leal -4(%ecx), %esp ret Machine language is binary codes, yes. > You can't read a pyc file in a hex editor, By definition, you can read every file in a hex editor ... > but you can read it in a disassembler. It doesn't make a lot of > sense to me right now, but if I was trying to trace through it > with a debugger, the debugger would disassemble it into > assembler, not python. Not at all. Again: It's Python byte code. Try experimenting with pdb. Regards, Bj?rn -- BOFH excuse #340: Well fix that in the next (upgrade, update, patch release, service pack). From snoylr at gmail.com Sat Jan 19 17:14:30 2008 From: snoylr at gmail.com (snoylr) Date: Sat, 19 Jan 2008 14:14:30 -0800 (PST) Subject: Naming a file Message-ID: <89bb0095-429f-404c-b7f6-ff0a554b07cc@i72g2000hsd.googlegroups.com> I have a variable called filename How do I create a file using the filename variable as the name of the file? For example if the variable is 105Markum What statement do I need to create a file name 105Markum.txt? From kw at codebykevin.com Thu Jan 10 10:42:21 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 10 Jan 2008 10:42:21 -0500 Subject: Problem with Tkinter.PhotoImage In-Reply-To: References: Message-ID: <47863CDD.9060200@codebykevin.com> C?dric Lucantis wrote: > Hi, > > I can only load gif images with Tkinter.PhotoImage and none with BitmapImage. > I tried png, jpg, bmp and xpm and always got this errors : > That's because Tk only supports the gif format natively. You need to install an additional photo library to support additional images (Tk has an Img extension, and Python Image Library is also very good). -- Kevin Walzer Code by Kevin http://www.codebykevin.com From mathewbrown at fastmail.fm Wed Jan 9 11:10:47 2008 From: mathewbrown at fastmail.fm (Mrown) Date: Wed, 9 Jan 2008 08:10:47 -0800 (PST) Subject: subprocess.Popen spawning cmd shells References: Message-ID: <2aa3bb72-7094-44cc-a8af-d7777916755c@e25g2000prg.googlegroups.com> On Jan 9, 5:17?pm, Mrown wrote: > Hi, > ? I'm currently writing a python program that relies on a CLI > program. ?What I'm currently doing is using subprocess.Popen on Python > 2.5.1. ?Here's the line that I'm currently running: > > ? ? ? ? ? ? child = subprocess.Popen(["c:\app.exe", node, "-w", > str(tmpTime * 1000), '-n', str(1), '-l'], stdin=subprocess.PIPE, > stdout=subprocess.PIPE, stderr=subprocess.PIPE) > > The problem is that although the above works, a CMD shell is spawned > and becomes visible for each time I run the above. ?I thought that by > redircting stdin, stdout and stderr, no CMD shell should pop-up. ?Is > something wrong in the way I'm using subprocess? ?Thanks for your help. To anyone interested, I found the solution by using the CREATE_NO_WINDOW creation flag. So this is what the code now looks like (and it doesn't spawn any shells): CREATE_NO_WINDOW = 0x8000000 child = subprocess.Popen(["c:\app.exe", node, "-w", str(tmpTime * 1000), '-n', str(1), '-l'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags = CREATE_NO_WINDOW) From steven at REMOVE.THIS.cybersource.com.au Wed Jan 23 01:38:30 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 06:38:30 -0000 Subject: subprocess and & (ampersand) References: Message-ID: On Tue, 22 Jan 2008 22:53:20 -0700, Steven Bethard wrote: > I'm having trouble using the subprocess module on Windows when my > command line includes special characters like "&" (ampersand):: > > >>> command = 'lynx.bat', '-dump', 'http://www.example.com/?x=1&y=2' > >>> kwargs = dict(stdin=subprocess.PIPE, > ... stdout=subprocess.PIPE, ... > stderr=subprocess.PIPE) > >>> proc = subprocess.Popen(command, **kwargs) proc.stderr.read() > "'y' is not recognized as an internal or external command,\r\noperable > program or batch file.\r\n" > > As you can see, Windows is interpreting that "&" as separating two > commands, instead of being part of the single argument as I intend it to > be above. Is there any workaround for this? How do I get "&" treated > like a regular character using the subprocess module? That's nothing to do with the subprocess module. As you say, it is Windows interpreting the ampersand as a special character, so you need to escape the character to the Windows shell. Under Windows, the escape character is ^, or you can put the string in double quotes: # untested command = 'lynx.bat -dump http://www.example.com/?x=1^&y=2' command = 'lynx.bat -dump "http://www.example.com/?x=1&y=2"' In Linux land, you would use a backslash or quotes. To find the answer to this question, I googled for "windows how to escape special characters shell" and found these two pages: http://www.microsoft.com/technet/archive/winntas/deploy/prodspecs/shellscr.mspx http://technet2.microsoft.com/WindowsServer/en/library/44500063-fdaf-4e4f-8dac-476c497a166f1033.mspx Hope this helps, -- Steven From 7146031596 at tmomail.net Wed Jan 30 14:56:24 2008 From: 7146031596 at tmomail.net (7146031596 at tmomail.net) Date: Wed, 30 Jan 2008 14:56:24 -0500 Subject: No subject Message-ID: <32288466.29282731201722984918.JavaMail.imb@mgwatl04.cns.mms.com> 17146031598 From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 11:05:41 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 17:05:41 +0100 Subject: Python help for a C++ programmer In-Reply-To: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> References: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> Message-ID: <478e2b2b$0$1716$426a74cc@news.free.fr> mlimber a ?crit : > I'm writing a text processing program to process some survey results. > I'm familiar with C++ and could write it in that, but I thought I'd > try out Python. I've got a handle on the file I/O and regular > expression processing, FWIW, and depending on your text format, there may be better solutions than regexps. > but I'm wondering about building my array of > classes (I'd probably use a struct in C++ since there are no methods, > just data). If you have no methods and you're sure you won't have no methods, then just use a dict (name-indexed record) or a tuple (position-indexed record). > I want something like (C++ code): > > struct Response > { > std::string name; > int age; > int iData[ 10 ]; > std::string sData; > }; > > // Prototype > void Process( const std::vector& ); > > int main() > { > std::vector responses; > > while( /* not end of file */ ) > { > Response r; > > // Fill struct from file > r.name = /* get the data from the file */; > r.age = /* ... */; > r.iData[0] = /* ... */; > // ... > r.sData = /* ... */; > responses.push_back( r ); > } > > // Do some processing on the responses > Process( responses ); > } > > What is the preferred way to do this sort of thing in Python? # assuming you're using a line-oriented format, and not # worrying about exception handling etc... def extract(line): data = dict() data['name'] = # get the name data['age'] = # get the age data['data'] = # etc... return data def process(responses): # code here if name == '__main__': import sys path = sys.argv[1] responses = [extract(line) for line in open(path)] process(response) If you have a very huge dataset, you may want to either use tuples instead of dicts (less overhead) and/or use a more stream-oriented approach using generators - if applyable of course (that is, if you don't need to extract all results before processing) HTH From fredrik at pythonware.com Mon Jan 7 14:30:23 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 20:30:23 +0100 Subject: Does Python cache the startup module? In-Reply-To: References: Message-ID: Baz Walter wrote: > It's hard to supply an example for this, since it is local to the machine I am > using. The startup module would look something like this: would look, or does look? if it doesn't look like this, what else does it contain? > #!/usr/local/bin/python > > if __name__ == '__main__': > > import sys > from qt import QApplication, QWidget > > application = QApplication(sys.argv) > mainwindow = QWidget() > application.setMainWidget(mainwindow) > mainwindow.show() > sys.exit(application.exec_loop()) > > If I change the name 'mainwindow' to 'mainwidget', the widget it refers to does > not get destroyed; when I change it back again, it does get destroyed. > Otherwise, the program runs completely normally. I don't see any code in there that destroys the widget, and I also don't see any code in there that creates more than one instance of the main widget. what do you do to run the code, and how to you measure leakage? is the name "mainwidget" used for some other purpose in your application? From mikael at isy.liu.se Thu Jan 31 03:46:49 2008 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 31 Jan 2008 09:46:49 +0100 Subject: Sine Wave Curve Fit Question In-Reply-To: <47a0c8b5$0$2994$ba620e4c@news.skynet.be> References: <7eOdnXVrB-fQFD3anZ2dnUVZ8hednZ2d@giganews.com> <47a0c8b5$0$2994$ba620e4c@news.skynet.be> Message-ID: Helmut Jarausch wrote: > Your model is A*sin(omega*t+alpha) where A and alpha are sought. > Let T=(t_1,...,t_N)' and Y=(y_1,..,y_N)' your measurements (t_i,y_i) > ( ' denotes transposition ) > > First, A*sin(omega*t+alpha) = > A*cos(alpha)*sin(omega*t) + A*sin(alpha)*cos(omega*t) = > B*sin(omega*t) + D*cos(omega*t) > > by setting B=A*cos(alpha) and D=A*sin(alpha) > > Once, you have B and D, tan(alpha)= D/B A=sqrt(B^2+D^2) This is all very true, but the equation tan(alpha)=D/B may fool you. This may lead you to believe that alpha=arctan(D/B) is a solution, which is not always the case. The point (B,D) may be in any of the four quadrants of the plane. Assuming B!=0, the solutions to this equation fall into the two classes alpha = arctan(D/B) + 2*k*pi and alpha = arctan(D/B) + (2*k+1)*pi, where k is an integer. The sign of B tells you which class gives you the solution. If B is positive, the solutions are those in the first class. If B is negative, the solutions are instead those in the second class. Whithin the correct class, you may of course choose any alternative. Then we have the case B=0. Then the sign of D determines alpha. If D is positive, we have alpha=pi/2, and if D is negative, we have alpha=-pi/2. Last if both B and D are zero, any alpha will do. /MiO From ckimyt at gmail.com Mon Jan 7 08:46:26 2008 From: ckimyt at gmail.com (Mike) Date: Mon, 7 Jan 2008 05:46:26 -0800 (PST) Subject: How to refer to the current module? References: Message-ID: Sweet! Thanks! Mike On Jan 7, 8:30 am, "Guilherme Polo" wrote: > > globals() =) > From bellman at lysator.liu.se Fri Jan 25 17:33:07 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Fri, 25 Jan 2008 22:33:07 +0000 (UTC) Subject: read and readline hanging References: Message-ID: Olivier Lefevre wrote: >> 1. The subprocess has stopped producing output. > Indeed, if I do this interactively, I can tell after 3 lines that I've > gotten all there is to get right now and the fourth readline() call > hangs. Can you really? How do you know if the program has finished or if it is just taking a very long time to produce the next line in its response? Unless there is some way to differentiate between the last line all the other lines of a response, you can't really be sure. > But how can I find out *programmatically* that there is no more > input? It is possible to check if there is something more to read at the moment, but you can't check if the subprocess will produce more to read in the future. To check if there is something to read at this very moment, you can use any of the following methods: - select.select() - the FIONREAD ioctl (the ioctl() function lives in the fcntl module, and the FIONREAD constant is in the termios module) - set the underlying file descriptor in non-blocking mode: flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NDELAY) After that, reads on the pipe will raise an IOError exception with the errorcode EWOULDBLOCK. - start a thread that does blocking reads from the pipe, and puts the chunks it reads on a queue for your main thread to grab. For the last approach, you might be interrested in my asyncproc module, which does exactly that. You can download it from . However, none of these approaches absolves you from the necessity of knowing when one response ends. You still need to solve that problem. The proper way is to define a protocol between your program and the subprocess, in which you can clearly tell when you have reached the end of a response. Then you need to get the program you are calling to adher to that protocol, of course... The SMTP protocol is a good example of how this can look. In SMTP, each response to a command consists of a number of lines. Each line has a three-digit response code, an "end of response" flag, and a text message. The "end of response" flag is a space (" ") for the last line in the response, and a dash ("-") for all the other lines. The response to an EHLO command can look like this: 250-sellafield Hello localhost [127.0.0.1], pleased to meet you 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-EXPN 250-VERB 250-8BITMIME 250-SIZE 250-DSN 250-ETRN 250-DELIVERBY 250 HELP Since there is a space instead of a dash after the "250" code in the last line above, the SMTP client knows that there won't be any more lines in response to its command. If you can't get the program you are calling to follow some protocol like this, then you can only make guesses. Sometimes you can make fairly good guesses, and sometimes it will be more or less impossible... -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "Life IS pain, highness. Anyone who tells ! bellman @ lysator.liu.se differently is selling something." ! Make Love -- Nicht Wahr! From michael.pearmain at tangozebra.com Thu Jan 10 04:21:01 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Thu, 10 Jan 2008 01:21:01 -0800 (PST) Subject: Win32com and Excel Message-ID: <096bc326-3c91-4287-817f-79994a8c507d@k39g2000hsf.googlegroups.com> Hi, I currently have an excel table (1 table each time) that has differing number of rows and differing number of columns each time, for another program i use (SPSS) to import the data i need to know the cell range of this data table. I.e what the last row of data is and the last column that has data in it. Does anyone have any code that does something similar? My guess is i have to do something like thefollowing to enable python to read xl? import win32com.client working_dir = '//c:/temp/' xl = win32com.client.Dispatch("Excel.Application") xl.Visible = 1 #open MS Excel xl.Workbooks.Open('%s/working_output.xls' % (working_dir)) then code to find the cell ranges Any help here is much appreciated Mike From rndblnch at gmail.com Fri Jan 25 14:47:33 2008 From: rndblnch at gmail.com (rndblnch) Date: Fri, 25 Jan 2008 11:47:33 -0800 (PST) Subject: is possible to get order of keyword parameters ? References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> Message-ID: <5b6e2bc6-8136-4e3a-8bf2-bb6d689d6110@s8g2000prg.googlegroups.com> On Jan 25, 5:27 pm, Larry Bates wrote: > Keyword arguments are normally treaded as "order independent". > Why do you think you need to find the order? What problem do > you wish to solve? > > -Larry On Jan 25, 7:39 pm, Duncan Booth wrote: > The question remains, what use is there for this? my goal is to implement a kind of named tuple. idealy, it should behave like this: p = Point(x=12, y=13) print p.x, p.y but what requires to keep track of the order is the unpacking: x, y = p i can't figure out how to produce an iterable that returns the values in the right order. relying on a "natural" order of the key names is not possible: x, and y are alphabetically sorted but the following example should also work: size = Point(width=23, height=45) w, h = size if you have any suggestion to implement such a thing... thank you renaud From http Sun Jan 13 08:28:00 2008 From: http (Paul Rubin) Date: 13 Jan 2008 05:28:00 -0800 Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> <00cb6e9d-e8b6-4e65-be58-5a4472413c53@j78g2000hsd.googlegroups.com> Message-ID: <7xabn94zz3.fsf@ruckus.brouhaha.com> thebjorn writes: > Perhaps something like this? > > def chop(lst, length): > from itertools import islice > it = iter(lst) > z = [list(islice(it, length)) for i in xrange(1 + len(lst) // length)] > if len(z) > 1: > z[-2].extend(z.pop()) # the last item will be empty or contain "overflow" elements. > return z def chop(lst, length): def chop1(): t = len(lst) // length - 1 for i in xrange(t): yield lst[i*length: (i+1)*length] yield lst[t*length:] return list(chop1()) From stefan.behnel-n05pAM at web.de Wed Jan 30 14:04:04 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 30 Jan 2008 20:04:04 +0100 Subject: "Code Friendly" Blog? In-Reply-To: <876318a9-5806-4613-a7d5-9437860af3f7@v29g2000hsf.googlegroups.com> References: <876318a9-5806-4613-a7d5-9437860af3f7@v29g2000hsf.googlegroups.com> Message-ID: <47A0CA24.10101@web.de> Hai Vu wrote: > Why don't you try to use Code Colorizer: > http://www.chamisplace.com/colorizer/cc.asp Looks like it lacks support for one important language, though... Stefan From bignose+hates-spam at benfinney.id.au Wed Jan 9 17:57:17 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 10 Jan 2008 09:57:17 +1100 Subject: Natural-language datetime parsing and display References: <873at7lq0d.fsf@benfinney.id.au> Message-ID: <87bq7uk3oy.fsf@benfinney.id.au> "Daniel Fetchinson" writes: > > The OP was looking for presentation though. I know roundup has > > code for this if an independent library can't be found. > > Thanks for all the responses! > Indeed I was looking for presentation and not parsing, I'll take a > look at roundup. Yes, that's why I indicated that Chandler Desktop would be a good place to look. Roundup sounds like an equally good place to look. Hopefully, with a couple of options like that, you'll find something decent. It would be good to see a generic "natural-language datetime presentation" library in the Cheeseshop, since the functionality seems quite well-suited to a separate generic library. -- \ "The best mind-altering drug is truth." -- Jane Wagner, via | `\ Lily Tomlin | _o__) | Ben Finney From paul at boddie.org.uk Sat Jan 12 11:47:57 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 12 Jan 2008 08:47:57 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <13od12b23hfv772@corp.supernews.com> <5b035c91-72eb-4d88-b19b-e89470865c5b@i7g2000prf.googlegroups.com> <13ogbfasbcici1c@corp.supernews.com> Message-ID: <389f20bb-ccbf-43bd-b38b-e359a3f62c3a@f47g2000hsd.googlegroups.com> On 12 Jan, 04:03, Steven D'Aprano wrote: > > Given the way that people seem to use "interpreted" as a pejorative and a > synonym for "slow", I don't doubt it one bit. Especially in management, > where they might be making technical judgments on the basis of half- > remembered Comp Sci 101 lessons from fifteen years earlier and vague > buzzword-laden articles in trade magazines. Indeed. Still, there's reason to be upbeat about Python's potential here. The big question is this: what is everyone with any degree of concern about Python's performance doing to improve the situation? Sure, C (or actually C++) seems to win the shootout [1], but there are plenty of language implementations between g++ and CPython to suggest that the old choice of extension modules written in C vs. other code written in Python doesn't provide a complete map of the opportunities. Paul [1] http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=all From sjmachin at lexicon.net Sun Jan 13 16:50:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 13 Jan 2008 13:50:25 -0800 (PST) Subject: time.time or time.clock References: Message-ID: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> On Jan 14, 7:05 am, Ron Adam wrote: > I'm having some cross platform issues with timing loops. It seems > time.time is better for some computers/platforms and time.clock others, but Care to explain why it seems so? > it's not always clear which, so I came up with the following to try to > determine which. > > import time > > # Determine if time.time is better than time.clock > # The one with better resolution should be lower. > if time.clock() - time.clock() < time.time() - time.time(): > clock = time.clock > else: > clock = time.time > > Will this work most of the time, or is there something better? > Manual: """ clock( ) On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of ``processor time'', depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond. [snip] time( ) Return the time as a floating point number expressed in seconds since the epoch, in UTC. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non- decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls. """ AFAICT that was enough indication for most people to use time.clock on all platforms ... before the introduction of the timeit module; have you considered it? It looks like your method is right sometimes by accident. func() - func() will give a negative answer with a high resolution timer and a meaningless answer with a low resolution timer, where "high" and "low" are relative to the time taken for the function call, so you will pick the high resolution one most of the time because the meaningless answer is ZERO (no tick, no change). Some small fraction of the time the low resolution timer will have a tick between the two calls and you will get the wrong answer (-big < -small). In the case of two "low" resolution timers, both will give a meaningless answer and you will choose arbitrarily. HTH, John From martin at v.loewis.de Thu Jan 24 00:17:44 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 24 Jan 2008 06:17:44 +0100 Subject: os.system behavior when calling SQLPlus with spooling In-Reply-To: References: Message-ID: <47981f79$0$18719$9b622d9e@news.freenet.de> > I would prefer not to use os.system() since I want to analyze the > results. Can anyone suggest how I should go about executing sqlplus > in this case? You need to find out why it hangs. Perhaps sqlplus tries to read from its stdin, asking the user for input, yet your script doesn't provide any? You can use "strace -p " to find out what it's doing when it hangs. Regards, Martin From edloper at seas.upenn.edu Tue Jan 29 23:22:51 2008 From: edloper at seas.upenn.edu (Edward Loper) Date: Tue, 29 Jan 2008 23:22:51 -0500 Subject: epydoc 3.0 released Message-ID: <3131dfac0801292022y3fdb3129p20758d91b94a2853@mail.gmail.com> Announcing epydoc 3.0 ~~~~~~~~~~~~~~~~~~~~~ Webpage: http://epydoc.sourceforge.net/ Download: http://tinyurl.com/yoo6d7 Epydoc is a tool for generating API documentation for Python modules, based on their docstrings. A lightweight markup language called epytext can be used to format docstrings, and to add information about specific fields, such as parameters and instance variables. Epydoc also understands docstrings written in reStructuredText, Javadoc, and plaintext. For some examples of the documentation generated by epydoc, see: - The API documentation for epydoc. - The API documentation for the Python 2.5 standard library. - The API documentation for NLTK, the natural language toolkit. Improvements in Version 3.0 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Version 3.0 of epydoc adds support for extracting documentation information using both introspection (i.e., importing & inspecting the modules programmatically) and parsing (i.e., reading the source code of the modules); and for combining both sources of information. This is important because each source has its own advantages and disadvantages with respect to the other. See the epydoc FAQ for more information about the relative benefits of introspection and parsing, and why it's good to merge information from both sources: http://epydoc.sourceforge.net/faq.html#introspect_vs_parse Version 3.0 also adds the following features: * Support for variable docstrings. * Automatic generating of source code graphs, including class trees, package trees, uml class graphs, and import graphs. * Syntax highlighted source code, including links from identifiers back into the documentation. For more details about what's new in Epydoc 3.0, see: http://epydoc.sourceforge.net/whatsnew.html ---------------------------------------------------------------------- Edward Loper edloper at gradient.cis.upenn.edu http://www.cis.upenn.edu/~edloper/ ---------------------------------------------------------------------- From hexamorph at gmx.net Fri Jan 25 14:25:06 2008 From: hexamorph at gmx.net (Hexamorph) Date: Fri, 25 Jan 2008 20:25:06 +0100 Subject: Operator overloading In-Reply-To: <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> References: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com> <5vuob3F1nd2bhU1@mid.uni-berlin.de> <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> Message-ID: <479A3792.3040504@gmx.net> MartinRinehart at gmail.com wrote: > > Diez B. Roggisch wrote: >> No, there is no way. You would change general interpreter behavior if >> you could set arbitrary operators for predefined types. >> >> Start grumping... > > Thank you, Diez. > > If I ever design a language, please remind me that complete, easy, > well-documented access to the working of the internals (and the > ability to change same) would be very, uh, what's the right word? > Pythonic? You mean you want the ability to change for example the + operator for ints to something like calculating the cosine instead of doing addition? That will break the whole system in general as other parts of the language (or modules, libraries and programs) rely on a certain inner behaviour. There are some languages in which you can do this (Lisp/Scheme for example) but messing with the internals is almost never done for good reasons. From mrmakent at cox.net Wed Jan 23 10:13:35 2008 From: mrmakent at cox.net (Mike Kent) Date: Wed, 23 Jan 2008 07:13:35 -0800 (PST) Subject: How avoid both a newline and a space between 2 print commands? References: Message-ID: On Jan 23, 9:03 am, "seber... at spawar.navy.mil" wrote: > print "foo" > print "bar" > > has a newline in between "foo" and "bar" > > print "foo", > print "bar" > > has a space in between "foo" and "bar" > > How prevent ANYTHING from going in between "foo" and "bar" ?? > > (Without defining a string variable.) > > Chris print "%s%s" % ("foo", "bar") ## If "%s%s" doesn't violate your condition of not defining a string variable, I'm not sure. From lotrpy at gmail.com Sun Jan 13 08:45:02 2008 From: lotrpy at gmail.com (lotrpy) Date: Sun, 13 Jan 2008 05:45:02 -0800 (PST) Subject: about sort a list with integer key References: <986e05f3-2fe9-4fe8-94e2-fef26713a78c@i72g2000hsd.googlegroups.com> <87fxx1nbwv.fsf@mulj.homelinux.net> Message-ID: On 1?13?, ??8?32?, Hrvoje Niksic wrote: > Use lambda when it works better for you, the speed difference is > marginal in practice anyway. itemgetter is not (and was never > intended to be) a general substitute for functions, as you've > discovered. > > The marginal speed difference between itemgetter and an explicit > lambda that does the subscripts is a consequence of itemgetter being > written in C, meaning it avoids the creation of a Python stack frame, > etc. Combining int(...) with this operation requires coding the key > function in Python, which removes itemgetter's advantage. In other > words, you cannot retain itemgetter's speed advantage with more > complex keys. If the sorting performance is a problem for you, please > give more details about what you're doing -- there might be better > ways to speed up the code. Fredrik and Hrvoje, thanks for the reply, here the sorting performance is not a big problem for me. the text file is just several hundred line, each line include several item separated by space. I'll run the script each week or month, just 1 second to get the result,so maybe stick to lambda here is just fine. From ask at me Sun Jan 20 22:08:18 2008 From: ask at me (alf) Date: Sun, 20 Jan 2008 21:08:18 -0600 Subject: auto import Message-ID: Hi, is there any way to tweak __import__ so it imports module with another arbitrary selected module included? For instance I have my mylibs.py module. Then when I import a oneofhundredssmallmodules.py module from other place the mylibs.py is automatically imported without a explicit import. The effect is the same like below: module oneofhundredssmallmodules.py: import * from mylibs In my software I hundreds of small modules constituting certain custom scripts. I need an ability to dynamically control what is imported into them before custom code kicks in. Andy From __peter__ at web.de Thu Jan 17 11:10:41 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jan 2008 17:10:41 +0100 Subject: class closure question References: Message-ID: Steven W. Orr wrote: > I want to indirectly change the value of a variable. > > #! /usr/bin/python > foo = [44] > bar = foo > bar[0] = 55 > print 'bar = ', bar > print 'foo = ', foo > > This works fine. > > bar = [55] > foo = [55] > > But I want to do the same with a class value. > > #! /usr/bin/python > S = None > dd = { 'class': [S] } > class C1(object): > def __init__(self): > print 'Hello from C1' > > def mkclass(base): > class zzz(base): > pass > return zzz > > dd['class'][0] = mkclass( C1 ) > print "dd['class'][0].__bases__ = ", dd['class'][0].__bases__ > print 'S = ', S > > The answer is not what I want: > > dd['class'][0].__bases__ = (,) > S = None > > The goal is for S to be set to the returned class from mkclass. > > Can someone help? What you want is not possible in Python. You can modify some objects (called "mutable") but rebinding a name has to be explicit. Peter From lefevrol at yahoo.com Mon Jan 28 14:52:54 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Mon, 28 Jan 2008 20:52:54 +0100 Subject: read and readline hanging In-Reply-To: <5vuv9iF1o6ambU2@mid.uni-berlin.de> References: <5vuv9iF1o6ambU2@mid.uni-berlin.de> Message-ID: >> But in python eventually stdout.readline() hangs. This is a real >> nuisance: why can't it just return None? > > Because that would be quite annoying because most of the time people want > blocking behavior. Just an afterthought: do people prefer the blocking behaviour because blocking until there's something to read is more economical of computer resources than polling for a non-null read (what I was trying to do, in effect)? The problem with polling is you need a minimum of 2 threads to do anything useful: it is quite inconvenient to block in the main thread. -- O.L. From socyl at 987jk.com.invalid Thu Jan 10 11:13:10 2008 From: socyl at 987jk.com.invalid (kj) Date: Thu, 10 Jan 2008 16:13:10 +0000 (UTC) Subject: ISO Python example projects (like in Perl Cookbook) Message-ID: I'm looking for "example implementations" of small projects in Python, similar to the ones given at the end of most chapters of The Perl Cookbook (2nd edition, isbn: 0596003137). (Unfortunately, the otherwise excellent Python Cookbook (2nd edition, isbn: 0596007973), by the same publisher (O'Reilly), does not have this great feature.) The subchapters devoted to these small projects (which are called "Program"s in the book), each consists of a description of the task, a discussion of the relevant design considerations, and one or more illustrative implementations. As such, these programs are larger and more complex than the typical "recipe" in the book, but are still short enough to be read and understood in a few minutes. I find the study of such small programs invaluable when learning a new language. Does anyone know of a source of similar material for Python? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From propanbutan at gmx.net Tue Jan 22 09:33:28 2008 From: propanbutan at gmx.net (propanbutan) Date: Tue, 22 Jan 2008 15:33:28 +0100 Subject: make exe from application with py2exe References: <6d553403-1275-459e-b2e0-9463cab39250@e10g2000prf.googlegroups.com> Message-ID: <20080122153328.37b4364c.propanbutan@gmx.net> vedrandekovic at gmail.com wrote: > Is there any idea how can i create (.exe) from application (.exe ) > with py2exe? yes. here [1], here [2] and maybe here [3]. bye. http://catb.org/~esr/faqs/smart-questions.html [1] http://www.google.com [2] http://www.py2exe.org [3] From dg.google.groups at thesamovar.net Mon Jan 21 04:01:07 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Mon, 21 Jan 2008 01:01:07 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> Message-ID: <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Hi all, It's great how many different sorts of solutions (or almost solutions) this puzzle has generated. Speedwise, for reference my solution posted above takes about 40 seconds on my 1.8GHz laptop, and the less elegant version (on my webpage linked to in the original post) takes about 15 seconds. It seems to me like surely this problem can be more efficiently solved than that? My version isn't very Pythonic (it could almost be written in C++ the way I've done it) so I liked the idea of the first solution, but I don't think it can be fixed. I adapted it so that it doesn't use the same number more than once, but it still has some problems. Firstly, it only finds solution ((a op b) op c) op d etc. and won't find (for example (1+2)*(3+4). Secondly, it stores a dictionary value->how to get to value which is fine if you can re-use numbers because one way to get to a given value is as good as another, but sometimes you can get to the same number in two different ways using different numbers, so it misses solutions. Paul: 758 = 8+(5*((2+4)*25)) Arnaud: I haven't had time to play with your solution yet - how quick does it run? My fantasy is that there is a solution that isn't TOO slow where you can just look at the code and go 'Oh yes, of course that works!' and understand it immediately. Maybe that's too much to ask even of Python! ;-) From arnodel at googlemail.com Sun Jan 20 17:07:14 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 20 Jan 2008 14:07:14 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Message-ID: <891374fb-cf1d-4445-829d-0e10a8a1ed69@d21g2000prf.googlegroups.com> On Jan 20, 5:41?pm, dg.google.gro... at thesamovar.net wrote: > Ever since I learnt to program I've always loved writing solvers for > the Countdown numbers game problem in different languages, and so now > I'm wondering what the most elegant solution in Python is. > > If you don't know the game, it's simple: you're given six randomly > chosen positive integers, and a target (another randomly chosen > positive integer), and you have to make the target using only the > numbers you're given, and +,-,* and / (and any number of brackets you > like). You're not allowed fractions as intermediate values. So, given > 2, 3 and 5 say, and a target of 21, you could do (2+5)*3 = 21. > Neat problem! I couldn't help but have a go. I have no idea how efficient it is, I didn't think too much before I started typing :) def partitions(l): """"split(l) -> an iterator over all partitions of l into two lists There is no repetition provided that all elements of l are distinct.""" # Works only for lists of length < 8*size(int) due to xrange limitations for i in xrange(1, 2**len(l)-1, 2): partition = [], [] for x in l: i, r = divmod(i, 2) partition[r].append(x) yield partition def calc(l, filter=lambda *x:x): """calc(l, filter) -> an iterator over all expressions involving all numbers in l filter is a function that returns its two arguments with possible side-effects. """ if len(l) == 1: yield l[0], str(l[0]) else: for l1, l2 in partitions(l): for v1, s1 in calc(l1, filter): for v2, s2 in calc(l2, filter): yield filter(v1 + v2, '(%s+%s)' % (s1, s2)) yield filter(v1 * v2, '(%s*%s)' % (s1, s2)) if v1 > v2: yield filter(v1 - v2, '(%s-%s)' % (s1, s2)) elif v2 > v1: yield filter(v2 - v1, '(%s-%s)' % (s2, s1)) if not v1 % v2: yield filter(v1 / v2, '(%s/%s)' % (s1, s2)) elif not v2 % v1: yield filter(v2 / v1, '(%s/%s)' % (s2, s1)) def print_filter(target): """print_filter(target) -> filter that prints all expressions that equal target""" def filter(v, s): if v == target: print s return v, s return filter class ShortestFilter(object): def __init__(self, target): self.shortest = None self.target = target def __call__(self, v, s): if v == self.target: if not self.shortest or len(self.shortest) > len(s): self.shortest = s return v, s def countdown(numbers, target): """countown(numbers, target) -> None -- print all countdown solutions""" for dummy in calc(numbers, print_filter(target)): pass def best_countdown(numbers, target): """best_countdown(numbers, target) -> str -- return shortest solution""" filter = ShortestFilter(target) for dummy in calc(numbers, filter): pass return filter.shortest >>> countdown([7,8,50,8,1,3], 923) (((((50*8)-1)/3)*7)-8) (((((50*8)-1)*7)/3)-8) (((((8*50)-1)/3)*7)-8) (((((8*50)-1)*7)/3)-8) >>> print best_countdown([100,9,7,6,3,1], 234) (((1+(3*6))+7)*9) -- Arnaud From cwitts at gmail.com Fri Jan 11 07:28:26 2008 From: cwitts at gmail.com (Chris) Date: Fri, 11 Jan 2008 04:28:26 -0800 (PST) Subject: reading a specific column from file References: Message-ID: <336cbbb2-c7a8-42ad-9f3a-6696a616a700@v46g2000hsv.googlegroups.com> On Jan 11, 2:15 pm, cesco wrote: > Hi, > > I have a file containing four columns of data separated by tabs (\t) > and I'd like to read a specific column from it (say the third). Is > there any simple way to do this in Python? > > I've found quite interesting the linecache module but unfortunately > that is (to my knowledge) only working on lines, not columns. > > Any suggestion? > > Thanks and regards > Francesco for (i, each_line) in enumerate(open('input_file.txt','rb')): try: column_3 = each_line.split('\t')[2].strip() except IndexError: print 'Not enough columns on line %i of file.' % (i+1) continue do_something_with_column_3() From israelu at elbit.co.il Tue Jan 1 05:00:23 2008 From: israelu at elbit.co.il (iu2) Date: Tue, 1 Jan 2008 02:00:23 -0800 (PST) Subject: using super References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> <58c1aa27-98e4-4129-852c-f9a8477605db@i7g2000prf.googlegroups.com> Message-ID: <7220614d-311d-4dc6-b14f-39f0c091dbdb@q77g2000hsh.googlegroups.com> On Jan 1, 9:59?am, Michele Simionato wrote: > No PEP, this would never pass. There would be no way > to stop a method from calling its parent: you would > lose control of your classes, so I think this is a > bad idea. Not all classes, only classes the programmer chooses to have this behaviour. >Having said so, it is easy to implement > what you want with a metaclass: > > def callParent(*methodnames): > ? ? ?class Meta(type): > ? ? ? ? ?def __init__(cls, name, bases, dic): ... Thanks From sjmachin at lexicon.net Wed Jan 23 17:47:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 14:47:35 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com><5vphe6F1njt09U1@mid.uni-berlin.de><12d19814-b7b9-44b0-aee3-299befac7279@i12g2000prf.googlegroups.com> <66446d1e-189c-4c24-bd7a-83cbd66deb60@i12g2000prf.googlegroups.com> Message-ID: <7920ea6d-fdb0-4c83-826d-3e5829a6ec0f@t1g2000pra.googlegroups.com> On Jan 24, 7:57 am, "Reedick, Andrew" wrote: > > Why is it that so many Python people are regex adverse? Use the dashed > line as a regex. Convert the dashes to dots. Wrap the dots in > parentheses. Convert the whitespace chars to '\s'. Presto! Simpler, > cleaner code. Woo-hoo! Yesterday was HTML day, today is code review day. Yee-haa! > > import re > > state = 0 > header_line = '' > pattern = '' > f = open('a.txt', 'r') > for line in f: > if line[-1:] == '\n': > line = line[:-1] > > if state == 0: > header_line = line > state += 1 state = 1 > elif state == 1: > pattern = re.sub(r'-', r'.', line) > pattern = re.sub(r'\s', r'\\s', pattern) > pattern = re.sub(r'([.]+)', r'(\1)', pattern) Consider this: pattern = ' '.join('(.{%d})' % len(x) for x in line.split()) > print pattern > state += 1 state = 2 > > headers = re.match(pattern, header_line) > if headers: > print headers.groups() > else: > state = 2 assert state == 2 > m = re.match(pattern, line) > if m: > print m.groups() > > f.close() > From steven at REMOVE.THIS.cybersource.com.au Tue Jan 15 20:02:55 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Jan 2008 01:02:55 -0000 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> <87ir1wf1wi.fsf@mulj.homelinux.net> <87k5mbd8bv.fsf@benfinney.id.au> Message-ID: On Tue, 15 Jan 2008 14:02:43 -0800, Lie wrote: > I've been in this Python mailing list for a few days, and I've noticed > several things here: There are too many fundamentalist! > > Don't play stupid and all, don't be a fundamentalist. It might be true > that __init__ isn't a constructor and __new__ might be the constructor It is true. > (some people even claimed __new__ is also not a constructor). They did? I must have missed them. > From the base definition of a constructor: constructor is the creator of > an object. In this case, __new__ is technically the constructor while > __init__ is an initializer. Yes, that is correct, although I too have been known to use "constructor" to *informally* refer to __init__. It's a bad habit, and while technically wrong, not always unforgivably wrong. > However, it is also to be noted that __init__ is what makes an object > meaningful, and that makes it a constructor in a sense (while still > technically a constructor). Without initialization, an object is > meaningless, even if the definition of the initializer is to leave it as > it is. Nope, not at all. The following class does not call the initializer: class MyClass(object): class __metaclass__(type): def __call__(cls, *args, **kwargs): obj = cls.__new__(cls) print "There is no __init__." return obj def __new__(cls, *args, **kwargs): print "This is the constructor, see me construct an instance!" return object.__new__(cls) def __init__(self, *args, **kwargs): raise Exception("die die die!!!") Now use it: >>> c = MyClass() This is the constructor, see me construct an instance! There is no __init__. And call the initializer by hand: >>> c.__init__() Traceback (most recent call last): File "", line 1, in ? File "", line 7, in __init__ Exception: die die die!!! Here's a class with no constructor (or rather, a constructor that the user *can't get to*): class OldClass: def __new__(cls, *args, **kwargs): # this is not called raise Exception("die die die!!!") def __init__(self, *args, **kwargs): print "This is the initializer, see me initialize " \ "the already-constructed instance 'self'!" >>> c = OldClass() This is the initializer, see me initialize the already-constructed instance 'self'! For various reasons, Python splits the process of constructing and initializing instances into two stages. What other languages do is irrelevant. Perhaps Java and C++ don't need to distinguish between "constructor" and "initializer", but Python does. > Python creates object by doing something like this: a = anObject(arg1, > arg2, arg3) That's what the programmer does. Under the hood, Python does something different. > These arguments is then passed to __new__ and __init__ for their > arguments in its sake of creating and initializing the object. Then > anObject() returns an instance of anObject. Assuming the standard metaclass. > From an outsider's point of view, there is no difference between __new__ > and __init__ since they're "implementation details" No, they most certainly are not implementation details. ANY implementation of Python MUST use __new__ and __init__ or else it is not Python, it is a different language. The nature of how Python creates instances is part of the language specification, not the implementation. > (in other languages, > these are private functions[1] that is invisible to outsiders, Python > doesn't like privacy but the semantic of being implementation detail > still exist). For an outsider, there is absolutely no need to know that > __new__ and __init__ exists, they just need to know anObject()'s > arguments, which is the public view of the constructor and > initializer[2]. I don't understand your argument. If you are saying that people who don't care about the details of Python instance creation don't care about the details of Python instance creation, then you're right, but it's a rather pointless observation. Yes, people who don't care don't care. But people who want to: (1) Program successfully in Python; (2) Compare how Python works to other computer languages; (3) Do metaclass programming; or (4) Find out how Python creates instances will care about the details. Anybody asking for an explanation of __init__ (like this thread!) is asking about the details. Why on earth do you think it is a bad thing to answer the question accurately? [snip] > If you can't be convinced with this argument, then I'd give you another > that's a bit more Pythonic: > DUCK TYPING: If it looks like a duck, walks like a duck, and quacks like > a duck, it is a duck! > > From the class programmer's point of view, __init__ acts like an object > constructor in other languages, there is no significant difference > between __init__ and constructor in other languages. Fortunately, Python isn't those other languages. We're not discussing how Java creates instances, or C++, or VisualBasic. We're discussing Python, so any answer given that starts off "Well, in Java it works like this..." is almost certainly going to be useless to the Python programmer asking about Python. [snip] > In this sense, VB's New, C ++ > constructor, and C# constructor is equal to Python's __init__, thus the > Duck Typing spirit applies here. It isn't enough to quack like a duck. It also needs to walk like a duck and swim like a duck too. -- Steven From ganeshborse at gmail.com Thu Jan 31 05:41:42 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 31 Jan 2008 02:41:42 -0800 (PST) Subject: how to get string printed by PyErr_Print( )? References: <03c09680-cf9b-4e35-96d4-f28d11c40bbc@m77g2000hsc.googlegroups.com> Message-ID: <2a5a9cc1-683a-438d-9620-c67d5a72dc3c@s37g2000prg.googlegroups.com> On Jan 9, 8:01?pm, grbgooglefan wrote: > On Dec 19 2007, 5:55?pm, Christian Heimes wrote: > >grbgooglefanwrote: > > > PythonC API functionPyErr_Print( ) prints an error string onto stderr > > > if PyErr_Occurred() is true. > > > I don't want to print this to stderr because my Python+C code is > > > running daemon mode & won't have terminal / stderr. > > > So, I want to retrieve the string whichPyErr_Print( ) will print. > > > E.g.,PyErr_Print() printed following string when I tried to call > > > setTuple with one extra argument > > > Traceback (most recent call last): > > > ? File "", line 2, in isTacticSafe > > > IndexError: tuple assignment index out of range > > > I suggest a different approach. A daemon must have a stdin, stdout and > > stderr connected to a terminal. You can use freopen() to redirect stderr > > and stdout to a log file and fclose() to close stdin. > > >http://www.gnu.org/software/libc/manual/html_mono/libc.html#Opening-S... > > > Christian > > I do not want to redirect anything to file. Because I do not want to > avoid the disk access completely - for reading as well as writing. > I liked the 1st option suggested by Robert Kern. > > Can you please explain a little bit how can I replace sys.stderr with > StringIO or my char* buffer? > I have to show the error message of Python code compilation & > execution to the user on the GUI & therefore I want to capture the > error message directly instead of logging it to file. > > Thanks in advance for all your help.- Hide quoted text - > > - Show quoted text - Well, I managed to do it myself. Here is what I am doing now to do this. In Python-C/C++ world, if someone wants to do the same thing, may use this. Note: For this, am assigning the cStringIO object to sys.stderr once I do Py_Initialize & then use cStringIO.getvalue() everytime I get error. While importing cStringIO module with Python-2.3.3, I faced the problem of "undefined symbol:PyObject_SelfIter". I could resolve that also. I have put that note in the post which I had opened for that. /+++++++++++++++++++++++++++++++++++++++++++++++ PyObject *_pPyModule; PyObject *_pPyDictionary; PyObject *_pPyGetValFunc; PyObject *_pPyobStringIO; Init(){ // Py_Initialize should have been done by now..... PyObject *modStringIO = NULL; PyObject *obFuncStringIO = NULL; // Import cStringIO module modStringIO = PyImport_ImportModule("cStringIO"); if(PyErr_Occurred() || modStringIO == NULL){ printf("pyParserEvaluator::Init::PyImport cStringIO failed:"); PyErr_Print(); goto PY_INIT_ERR; } // get StringIO constructor obFuncStringIO = PyObject_GetAttrString(modStringIO, "StringIO"); if(PyErr_Occurred() || obFuncStringIO == NULL){ printf("pyParserEvaluator::Init: cant find cStringIO.StringIO:"); PyErr_Print(); goto PY_INIT_ERR; } // Construct cStringIO object _pPyobStringIO = PyObject_CallObject(obFuncStringIO, NULL); if(PyErr_Occurred() || _pPyobStringIO==NULL){ printf("pyParserEvaluator::Init: cStringIO.StringIO() failed:"); PyErr_Print(); goto PY_INIT_ERR; } // get getvalue() method in StringIO instance _pPyGetValFunc = PyObject_GetAttrString(_pPyobStringIO, "getvalue"); if(PyErr_Occurred() || _pPyGetValFunc==NULL){ printf("pyParserEvaluator::Init: cant find getvalue function:"); PyErr_Print(); goto PY_INIT_ERR; } // try assigning this object to sys.stderr ret = PySys_SetObject("stderr", _pPyobStringIO); if(ret != 0){ printf("failed to assign _pPyobStringIO to stderr\n"); goto PY_INIT_ERR; } return ret; PY_INIT_ERR: Py_XDECREF(modStringIO); Py_XDECREF(obFuncStringIO); Py_XDECREF(_pPyobStringIO); Py_XDECREF(_pPyGetValFunc); } int _getPythonErrorMessage() { // call getvalue() method in StringIO instance int ret = 0; PyObject *obResult=NULL; char *sresult = NULL; obResult = PyObject_CallObject(_pPyGetValFunc, NULL); if(PyErr_Occurred() || obResult==NULL){ printf("getvalue() failed\n"); ret = -1; goto CLEAN_AND_RETURN; } // did getvalue return a string? if(!PyString_Check(obResult)){ printf("getvalue() did not return error string\n"); ret = -1; goto CLEAN_AND_RETURN; } // retrieve error message string from this object if(NULL != (sresult = PyString_AsString(obResult))){ pErrorString = strdup(sresult); } else { ret = -1; goto CLEAN_AND_RETURN; } return(ret); CLEAN_AND_RETURN: Py_XDECREF(obResult); return(ret); } ================================================= From mutawafayez at yahoo.com Sat Jan 19 07:09:38 2008 From: mutawafayez at yahoo.com (small giant) Date: Sat, 19 Jan 2008 04:09:38 -0800 (PST) Subject: the God that never was Message-ID: <32cbed1b-1922-40b5-9e50-27a63676df35@d21g2000prf.googlegroups.com> Islam is the only religion which teaches the existence of a PERFECT God. A perfect God means that there is no sharer in His Nature and His Attributes: "Say: He is God, the One and Only; God, the Eternal, Absolute; He begetteth not, nor is He begotten; and there is none like unto Him." (Holy Qur'an, 112:1-4) There has appeared a man in Benoni. He is not qualified in theology, but is fondly cherishing the self-delusion that he is an apostle of Christ, appointed by God to convert Muslims to Christianity. Because he is a lawyer by profession, he is adept at juggling with words and quoting the Holy Qur'an totally out of context without knowing a word of Arabic. He wants Muslims to believe that Jesus was also a God, a belief that is abhorrent to us, because it is an antithesis of the Absolute perfection of Allah Subhaanahoo Wa Ta 'Aala! Thus intent upon reversing the process of Truth, which is: "And say: The Truth has come and falsehood vanished. Surely falsehood is ever bound to vanish." (Qur'an, 17:81). In this he will never succeed because the process of Truth is irreversible. TWO REASONS He has given two reasons to prove that Jesus is God, viz: (i) "When we say Jesus is deity (or even God for that matter), we do not make him the Father! He is one with the Father and therefore HE SHARES HIS NATURE", and (ii) "HE IS IN EVERY WAY LIKE THE FATHER but he is not the Father". In short, according to him, Jesus is God because He SHARES THE NATURE OF GOD, and HE IS IN EVERY WAY LIKE GOD. These two reasons given by him to prove the divinity of Jesus are so puerile that they speak volumes of his legal training. Numerous quotations from the Bible are given below to prove that Jesus neither SHARED THE NATURE OF GOD, nor is he IN EVERY WAY LIKE GOD. He can, therefore, NEVER be GOD. We have given the quotations from the Bible without comment, because the Bible speaks for itself! TO SAY THAT JESUS IS GOD OR SON OF GOD IS NOT ONLY A MOCKERY OF GODHOOD, BUT BLASPHEMY OF THE LOWEST ORDER AND AND INSULT TO THE INTELLIGENCE OF MEN! (Note: Unless otherwise stated, all quotations from the Bible are given from the Authorized Version. In our headings and subheadings we have referred to Jesus as "God" in inverted commas in order to show the ABSURDITY of the claim of this man that Jesus is God!) THE BIRTH OF "GOD" "God" was created from the seed of David: "Concerning his Son Jesus Christ our Lord, which was made of the SEED of David according to the flesh." (Romans, 1:3) "God" was the fruit of the loins of David: "Therefore being a prophet, and knowing that God had sworn with an oath to him, that of the fruit of his loins, according to the flesh, he would raise up Christ to sit on his throne." (Acts, 2:30) The Ancestors of "God": "The generations of Jesus Christ, the son of David, the son of Abraham." (Matthew, 1:1) The Sex of "God": "And when eight days were accomplished for the circumcising of the child, his name was called Jesus." (Luke, 2:21) How Mary Conceived and Delivered "God". Mary conceived Jesus like any other woman: "The days were accomplished that she should be delivered," (Luke, 2:6) which means that she went through all the normal stages of pregnancy. Nor was her delivery any different from other expectant mothers: "And she being with child cried, travelling in birth, and pained to be delivered." (Revelation, 12:2) "God" Sucked The Paps of a Woman: "And it came to pass, as he spake these things, a certain woman of the company lifted up her voice, and said unto him, Blessed is the womb that bare thee, and the paps which thou hast sucked." (Luke, 11:27) The Country of Origin of "God": "Jesus was born in Bethlehem of Judaea in the days of Herod the king. (Matthew, 2:1) The Occupation of "God": "Jesus was a carpenter by trade." (Mark, 6:3), "and the son of a carpenter." (Matthew, 13:55) The Transport of "God": "Behold, thy king cometh unto thee, meek, and sitting upon an ass." (Matthew, 21:5) "And Jesus, when he had found a young ass, sat thereon." (John, 12:14) The Wining and Dining of "God": "The Son of man came eating and drinking, and they say, behold a man gluttonous, and a winebibber, a friend of publicans and sinners." (Matthew, 11:9; Luke, 7:34) The Poverty of "God": "And Jesus saith unto him, the foxes have holes, and the birds of the air have nests; but the Son of man hath not where to lay his head." (Matthew, 8:20) The Meagre Possessions of "God": "Shoes of Jesus" (Luke, 3:16), "Garments and coat of Jesus" (John, 19:23) "God" Was a Devout Jew: "And in the morning, rising up a great while before day, he went out, and departed into a solitary place, and there prayed." (Mark, 1:35) "God" Was a Loyal Subject: Jesus was a good citizen, he was loyal to Caesar. He said: "Render therefore unto Caesar the things which are Caesar's; and unto God the things that are God's." (Matthew, 22:21) He paid his tax regularly. (Matthew, 17:24-27) THE FAMILY OF "GOD" "God" Was the Son of Joseph: "Philip findeth Nathanael, and saith unto him, we have found him, of whom Moses in the law, and the prophets, did write, Jesus of Nazareth, the son of Joseph" (John, 1:45) Brothers and Brothers-in-law of "God": "And when he was come into his own country, he taught them in their synagogue, insomuch that they were astonished, and said, whence hath this man this wisdom, and these mighty works? Is not this the carpenter's son? Is not his mother called Mary? and his brethren, James, and Joses, and Simon, and Judas? And his sisters, are they not all with us? Whence hath this man all these things? (Matthew, 13:54-56) THE DEVELOPMENT OF "GOD" Spiritual Development of "God": "And the child grew, and waxed strong in spirit, filled with wisdom." (Luke, 2:40) Mental, Physical and Moral Development of "God": "And Jesus increased in wisdom and stature, and in favor with God and man." (Luke, 2:52) "God" Was 12 Years Old When His Parents Took Him to Jerusalem: "Now his parents went to Jerusalem every year at the feast of the passover. And when he was twelve years old, they went up to Jerusalem after the custom of the feast." (Luke, 2:41-42) The Powerless "God" (Jesus) said: "I can of mine own self do nothing." (John, 5:30) "God" Was Ignorant of the Time. Jesus said: "But of that day and that hour knoweth no man, no, not the angels which are in heaven, neither the Son, but the Father." (Mark, 13:32) "God" Was Ignorant of the Season: "And on the morrow, when they were come from Bethany, he (Jesus) was hungry: and seeing a fig tree afar off having leaves, he came, if haply he might find anything thereon: and when he came to it, he found nothing but leaves; for the time of figs was not yet." (Mark, 11:12-13) "God" Was Unlettered: "Now about the midst of the feast Jesus went up into the temple, and taught. And the Jews marvelled, saying, How knoweth this man letters, having never learned?" (John, 7:14-15) "God" Learnt Through Experience: "Learned he obedience by the things which he sufered." (Hebrews, 5:8) THE TEMPTING OF "GOD" The Devil Tempted "God" For 40 Days: "And immediately the spirit driveth him into the wilderness. And he was there in the wilderness forty days, tempted of Satan." (Mark, 1:12-13) The Devil Tempted "God" Continuously: "And when the devil had ended all the temptation, he departed from him for a season." (Luke, 4:13) Like the Sinners, "God" Was Tempted In All Things: "But (he) was in all points tempted like as we are, yet without sin." (Hebrews, 4:15) True God Cannot be Tempted With Evil: "God cannot be tempted with evil, neither tempteth he any man." (James, 1:13) Only The Ungodly Are Tempted With Evil: "But every man is tempted, when he is drawn away of his own lust, and enticed." (James, 1:14) THE MISSION OF "GOD" The Confession and Repentance of "God": before the beginning of his public ministry: "Jesus was baptized by John the Baptist" (Matthew, 3:13), "which signified the confession of sins" (Matthew, 3:6), "and repentance from sins (Matthew, 3:11). "God" Did Not Come to Save the Sinners: "And when he was alone, they that were about him with the twelve asked of him the parable. And he said unto them, unto you it is given to know the mystery of the kingdom of God: but unto them that without, all these things are done in parables: That seeing they may see, and not perceive; and hearing they may hear, and not understand; lest at any time they should be converted, and their sins should be forgiven them." (Mark, 4:10-12) THE RACIAL "GOD" "God" Was a Tribal Jew: "The lion of the tribe of Juda." (Revelation, 5:5) "God" Came For The Jews Only: "But he answered and said, I am not sent but unto the lost sheep of the house of Israel." (Matthew, 15:24) Racial Discrimination of "God": "These twelve Jesus sent forth, and commanded them, saying, Go not into the way of the Gentiles, and into any city of the Samaritans enter ye not: But go rather to the lost sheep of the house of Israel." (Matthew, 10:5-6) According to "God", The Gentiles Are Dogs: "It is not meet to take the children's bread, and to cast it to dogs." (matthew, 15:26) The Kingdom of "God": And he (Jesus) shall reign over THE HOUSE OF JACOB for ever; and of his kingdom there shall be no end." (Luke, 1:33) The Titles of "God": "The king of the Jews" (Matthew, 2:2), "The king of Israel" (John, 1:49; 12:13) A "GOD" UNLIKE THE GOD A Hungry "God": "And when he had fasted forty days and forty nights, he was afterward an hungered." (Matthew 4:2), "Now in the morning as he returned into the city, he hungered." (Matthew, 21:18), "and on the morrow, when they were come from Bethany, he was hungry." (Mark, 11:12) A Thirsty "God": "(He) saith, I thirst." (John, 19:28) A Sleepy "God": "He was asleep." (Matthew, 8:24), "He fell asleep" (Luke, 8:23), "And he was in the hinder part of the ship, asleep on a pillow." (Mark, 4:38) A Weary "God": Jesus therefore, being wearied with his journey, sat thus on the well." (John, 4:6) A Groaning "God": "He groaned in the spirit, and was troubled." (John, 11:33), "Jesus therefore again groaning in himself cometh to the grave." (John, 11:38) A Weeping "God": "Jesus wept." (John, 11:35) A Sorrowing "God": "And (he) began to be sorrowful and very heavy." (Matthew 26:37). "Then saith he unto them, my soul is exceeding sorrowful, even unto death." (Matthew, 26:38) A Hysterical "God": "And (he) began to be soreamazed and to be very heavy." (Mark, 14:33) A Weak "God": "And there appeared an angel unto him from heaven, strengthening him." (Luke, 22:43) THE WARRING "GOD" The Strong-Arm Method of "God": "And he went into the temple, and began to cast out them that sold therein, and them that bought." (Luke, 19:45). "And the Jews' passover was at hand, and Jesus went up to Jerusalem, and found in the temple those that sold oxen and sheep and doves, and the changers of money sitting: and when he had made a scourge of small cords, he drove them all out of the temple, and the sheep, and the oxen; and poured out the changers' money, and overthrew the tables." (John, 2:13-15) The "God" of War: Jesus said: "Think not that I am come to send peace on earth: I came not to send peace, but a sword." (Matthew, 10:34) The Sabre-Rattling "God": Jesus said: "And he that hath no sword, let him sell his garment, and buy one." (Luke, 22:36) The "GOD" ON THE RUN "God" Was Panic-Stricken: "After these things Jesus walked in Galilee: for he would not walk in Jewry, because the Jews sought to kill him." (John, 7:1) "God" Walked in Fear of the Jews: "Then from that day forth they took counsel together for to put him to death. Jesus therefore walked no more openly among the Jews." (John, 11:53-54) "God" Has Shown a Clean Pair of Heels: "Therefore they sought again to take him: but he escaped out of their hand." (John, 10:39) "God" Fled in Disguise: "Then took they up stones to cast at him: but Jesus hid himself, and went out of the temple, going through the midst of them, and so passed by." (John, 8:59) THE CAPTURE OF "GOD" A Friend Betrayed the Secret Hiding Place of "God": "And Judas also, which betrayed him, knew the place: for Jesus off-times resorted thither with his disciples. Judas then, having received a band of man and officers from the chief priests and Pharisees, cometh thither with lanterns and torches and weapons." (John, 18:2-3) "God" Was Arrested, Bound and Led Away: "Then the band and the captain and officers of the Jews took Jesus, and bound him, and led him away." (John, 18:12-13) "God" Was Humiliated: "And the men that held Jesus mocked him, and smote him. And when they had blindfolded him, they struck him on the face." (Luke, 22:63-64). "Then did they spit in his face, and buffeted him; and others smote him with the palms of their hands." (Matthew, 26:67) "God" Was Defenseless: "One of the officers which stood by struck Jesus with the palm of his hand", he said: "Why smitest thou me?" (John, 18:22-23) "God" Was Condemned to Death: "And they all condemned him to be guilty of death." (Mark, 14:64). "They answered and said, he is guilty of death." (Matthew, 26:66) The Dumb and Docile "God": "He was led as a sheep to the slaughter; and like a lamb dumb before his shearer, so opened he not his mouth." (Acts, 8:32) THE SUPPOSED END OF "GOD" The Dying "God": "And Jesus cried with a loud voice, and gave up the ghost." (Mark, 15:37) The "God" That Was Supposed Dead and Defunct: "Christ died." (Romans, 5:6). "He was dead". (John, 19:33) The Supposed Corpse of "God": "he (Joseph of Arimathaea) went to Pilate, and begged the body of Jesus. Then Pilate commanded the body to be delivered." (Matthew, 27:58) The Shroud of "God": "And when Joseph had taken the body, he wrapped it in a clean linen cloth." (Matthew, 27:59) The Orbituary of The Late And Lamented "God": "Now when the centurion saw what was done, he glorified God, saying, certainly this was a righteous man." (Luke, 23:47) EPILOGUE According to this self-appointed apostle of Christ, Jesus is God because: (i) "HE SHARED THE NATURE OF GOD", and (ii) because "IN EVERY WAY HE IS LIKE GOD". But according to the quotations of the Bible given above, we find that Jesus did neither SHARE THE NATURE OF GOD nor is he IN EVERY WAY LIKE GOD. He is, therefore, definitely NOT God! The onus to prove that Jesus is God now rests with this Christian. Either he must prove that Jesus is God, or he must admit that he is a polytheist, i.e., a believer in more than one God. WITH ALL THE TRICKS AND VERBAL LEGERDEMAIN OF HIS PROFESSION, HE WILL NEVER BE ABLE TO PROVE THAT JESUS IS GOD!! He and his fellow-preachers in Christ, will never succeed in convincing the Muslims that Jesus was anything other than a natural man and a prophet of God, sent unto the house of Israel to bear the good news of the coming of the KINGDOM OF GOD, which prophecy was fulfilled with the advent of the Holy Prophet Muhammed (Sallal Laahu Alaihi Wa Sallam)! see this site for more information www.sultan.org From sipickles at hotmail.com Sat Jan 26 06:10:03 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Sat, 26 Jan 2008 11:10:03 +0000 Subject: Hashable Message-ID: Hi, The term 'hashable'. Am I right in thinking it means it can be indexed? like a string or a dict? Thanks Si -- Linux user #458601 - http://counter.li.org. From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 21:42:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 02:42:00 -0000 Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <13oga7o2i4fls5a@corp.supernews.com> On Fri, 11 Jan 2008 14:55:18 -0600, Reedick, Andrew wrote: > For those of us who still think in Perl, here's an easy to read ... > s = re.sub(r'_(.*?(_|$))', r':\1', s) "Easy to read"? Oh that's priceless. Andrew, you should consider writing comedy professionally! -- Steven From kyosohma at gmail.com Tue Jan 15 11:48:33 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 15 Jan 2008 08:48:33 -0800 (PST) Subject: A question about event handlers with wxPython References: <478c3bb2$0$5150$4c368faf@roadrunner.com> <2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com> <478ccbc3$0$11000$4c368faf@roadrunner.com> Message-ID: On Jan 15, 9:04 am, "Erik Lind" wrote: > > def HandleSomething(self, event): > > generating_control = event.GetEventObject() > > print generating_control > > > HTH, > > Thank you.That is what I was looking for, but as often seems the case, one > thing exposes another. Is there any way to listen for events without > specifically binding to a handler (it seems one cannot bind an event to two > handlers?)? One could do so with globals, but I'm trying to avoid that. > > For example, "press any button to stop" > > def HandleSomething(self, event): > ................. > while generating_control: == something: > run > else > stop I forgot to provide a link to a fairly straight-forward explanation of event propagation on the wxPython wiki: http://wiki.wxpython.org/EventPropagation Hope that helps! Mike From ajcppmod at gmail.com Thu Jan 10 12:10:00 2008 From: ajcppmod at gmail.com (ajcppmod at gmail.com) Date: Thu, 10 Jan 2008 09:10:00 -0800 (PST) Subject: ISO Python example projects (like in Perl Cookbook) References: <67f0df0e-ac6a-491c-b141-11fe8dadf4de@i29g2000prf.googlegroups.com> Message-ID: Have a look at Dive into Python by Mark Pilgrim. It is available for free here http://www.diveintopython.org/. Andy From steve at REMOVE-THIS-cybersource.com.au Wed Jan 30 21:25:52 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 31 Jan 2008 02:25:52 -0000 Subject: booleans, hash() and objects having the same value References: <9cdb261f-b81b-4eca-955a-a9b516eba9d2@s13g2000prd.googlegroups.com> Message-ID: <13q2cdg11ai9c88@corp.supernews.com> On Wed, 30 Jan 2008 17:14:32 -0800, Ryszard Szopa wrote: > Hi all, > > I've just read PEP 285 so I understand why bool inherits from int and > why, for example, ((False - True)*True)**False==1. And don't think that the choice was uncontroversial. > This was necessary for backwards compatibility "Necessary" is perhaps a little strong, but otherwise yes. > and to give the beast some ability to do moral reasoning. > For example, Python knows to value the whole truth more > than just a half-truth: > > In [95]: True > 0.5*True > Out[95]: True You're trying to be funny, yes? > Anyway, the thing that bothers me is the behavior of booleans when > passed as argument to the hash() function... That is, hash(True) == > hash(1) and hash(False) == hash(0). How do you feel about this? >>> hash(1.0) == hash(1) True >>> hash(0.0) == hash(0) True >>> hash(9907.0) == hash(9907) True It's the same thing: True is actually 1, just as 1.0 is, and so hash(True) is the same as hash(1), hash(1.0) and hash(1L). > This leads to a rather > counterintuitive interaction with dicts: [...] > Out[128]: {True: '1'} Yes, that's one of the disadvantages of having bools actually be ints, in the rare cases that you want bools to hash differently from ints, they don't. But that's no different from longs and ints hashing the same, or strings and unicode strings. > You may argue that this is a rather strange use case... However, you may > imagine that somebody would want a dict mapping from objects to their > representations, with 0, 1 and booleans among the objects, like in: > > In [123]: dict((el, repr(el)) for el in [0, 1, True, False]) Out[123]: > {0: 'False', 1: 'True'} Why bother with such a mapping? It already exists, and it is called repr(). Best of all, repr() shouldn't give a KeyError, and it can take mutable arguments. > In both cases, the result is rather unexpected, though after some > thinking, understandable (`==' tests the equality of values of objects, > True==1, and (from the documentation of hash) "Two objects with the same > value have the same hash value"). However, is this approach really > sound? Absolutely. As a general data type, the most sensible behaviour for hash tables is for dict[X] and dict[Y] to give the same result if X and Y are equal. > Wouldn't it be more sensible to have bool its own __hash__? Who cares what bools hash to? The real question is, should True be equal to 1 (and 1.0 and 1L) or not? The decision that it should was made a long time ago. It may or may not have been the best decision, but it's a decision and I doubt that it will be changed before Python 4000. Or possibly Python 5000. > PEP 285 doesn't mention anything about hashing (in fact, it doesn't > contain the string `hash' at all). Is it that nobody has noticed the > problem, it is a well known fact usually classified as a non-problem, or > maybe there are some serious reasons to keep 1 and True having the same > hash value? It's a non-problem in general. There might be highly specialized situations where you want 1.0 and 1 to map to different items, or 'xyz' and u'xyz', but being specialist they belong in your application code and not the language. Here's a start in implementing such a thing: class MyDict(dict): def __getitem__(self, key): key = (type(key), key) return super(MyDict, self).__getitem__(key) def __setitem__(self, key, value): key = (type(key), key) super(MyDict, self).__setitem__(key, value) >>> D = MyDict(); D[1] = "one"; D[1.0] = "one point oh" >>> D[1L] = "long one"; D[True] = "True" >>> D[1] 'one' >>> D[True] 'True' (I leave implementing the other necessary methods as an exercise.) > (Also, it is not completely clear what it means for two Python objects > to "have the same value". My first intuition would be that variables may > have a value, which usually is some Python object. I think that value should be interpreted rather fuzzily. I don't believe it is strongly defined: the concept of the value of an object depends on whatever the object wants it to be. For example, given an instance x with an attribute "foo", is x.foo part of the value of x, or is it something extra? Only the object x can make that decision. However, for standard objects like strings, ints, floats, etc. the value of the object corresponds to the intuitive ideas about strings, ints, floats etc. The value of the int 5 is 5, the value of the string "xyz" is "xyz", and so forth. For "well-behaved" objects, x and y have the same value when x == y returns True. Leave it to the objects to decide what their value is. It's easy to create ill-behaved objects: class Weird: def __eq__(self, other): if other is self: return False elif other is True: return True elif other == 1: return False else: import time return int(time.time()) % 2 == 0 but in general, you don't need to worry about such nonsense objects. > The second intuition > would be that objects with compatible (i.e. one inherits from the other) > types and ==-equal dicts have the same value. However, this is > _sometimes_ true. Python rarely cares about the type of objects, only the behaviour. Inheritance doesn't come into it, except as one possible way to get that behaviour: class MyInt: # DON'T inherit from int def __init__(self, value): if value == 'one': a, b = 0, 1 elif value == 'two': a, b = 1, 1 elif value == 'three': a, b = 1, 2 else: raise ValueError("can't count that high") self.data = (a, b) def __eq__(self, other): return other == sum(self.data) Instances of MyInt have the same value as the ints 1, 2, or 3 as appropriate. In all other ways though, MyInt and int behave very differently: for example, you can't add MyInts. -- Steven From ggpolo at gmail.com Tue Jan 22 18:55:32 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 22 Jan 2008 21:55:32 -0200 Subject: UDP Client/Server In-Reply-To: References: Message-ID: 2008/1/22, Martin Marcher : > Hello, > > I created a really simple udp server and protocol but I only get every 2nd > request (and thus answer just every second request). > > Maybe someone could shed some light, I'm lost in the dark(tm), sorry if this > is a bit oververbose but to me everything that happens here is black magic, > and I have no clue where the packages go. I can't think of a simpler > protocol than to just receive a fixed max UDP packet size and answer > immediately (read an "echo" server). > > thanks > martin > > > ### server > >>> from socket import * > >>> import SocketServer > >>> from SocketServer import BaseRequestHandler, UDPServer > >>> class FooReceiveServer(SocketServer.UDPServer): > ... def __init__(self): > ... SocketServer.UDPServer.__init__(self, ("localhost", 4321), > FooRequestHandler) > ... > >>> class FooRequestHandler(BaseRequestHandler): > ... def handle(self): > ... data, addr_info = self.request[1].recvfrom(65534) Your FooReceiveServer subclasses UDPServer, it already handled the recvfrom for you, so, this is wrong. > ... print data > ... print addr_info > ... self.request[1].sendto("response", addr_info) > ... > >>> f = FooReceiveServer() > >>> f.serve_forever() > request 0 > ('127.0.0.1', 32884) > request 1 > ('127.0.0.1', 32884) > request 2 > ('127.0.0.1', 32884) > request 2 > ('127.0.0.1', 32884) > request 2 > ('127.0.0.1', 32884) > > > > ### client > >>> target = ('127.0.0.1', 4321) > >>> from socket import * > >>> s = socket(AF_INET, SOCK_DGRAM) > >>> for i in range(10): > ... s.sendto("request " + str(i), target) > ... s.recv(65534) > ... > 9 > Traceback (most recent call last): > File "", line 3, in > KeyboardInterrupt > >>> s.sendto("request " + str(i), target) > 9 > >>> str(i) > '0' > >>> for i in range(10): > ... s.sendto("request " + str(i), target) > ... s.recv(65534) > ... > 9 > 'response' > 9 > 'response' > 9 > Traceback (most recent call last): > File "", line 3, in > KeyboardInterrupt > >>> #this was hanging, why? > ... > >>> s.sendto("request " + str(i), target) > 9 > >>> s.recv(65534) > 'response' > >>> s.sendto("request " + str(i), target) > 9 > >>> s.recv(65534) > Traceback (most recent call last): > File "", line 1, in > KeyboardInterrupt > >>> s.sendto("request " + str(i), target) > 9 > >>> s.sendto("request " + str(i), target) > 9 > >>> s.recv(65534) > 'response' > >>> s.recv(65534) > Traceback (most recent call last): > File "", line 1, in > KeyboardInterrupt > >>> s.sendto("request " + str(i), target) > 9 > >>> > > -- > http://noneisyours.marcher.name > http://feeds.feedburner.com/NoneIsYours > > You are not free to read this message, > by doing so, you have violated my licence > and are required to urinate publicly. Thank you. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From sjmachin at lexicon.net Fri Jan 11 05:00:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 11 Jan 2008 02:00:40 -0800 (PST) Subject: adding methods at runtime References: <940fcb28-764e-46ab-a627-aff513e009e1@j78g2000hsd.googlegroups.com> <5unou0F1ifu47U1@mid.uni-berlin.de> Message-ID: <46e3064b-bd95-4f8b-aa63-c5142031be85@d21g2000prg.googlegroups.com> On Jan 11, 10:44 am, Marc 'BlackJack' Rintsch wrote: > On Thu, 10 Jan 2008 14:55:18 -0800, zsl... at gmail.com wrote: > > Can I access the class attributes from a method added at runtime? (My > > experience says no.) > > I experimented with the following code: > > > [Code snipped] > > > So it seems to me, if you add a method to an instance, the method will > > not get "self" as parameter. > > You are not adding a method but a function. Take a look at > `types.MethodType()` to create a method from a function, instance, and > class. > Just in case gentle readers are wondering where to find the docs for types.MethodType, here's a hint: >>> import types, new; types.MethodType is new.instancemethod True >>> From peng.kyo at gmail.com Fri Jan 18 03:04:31 2008 From: peng.kyo at gmail.com (J. Peng) Date: Fri, 18 Jan 2008 16:04:31 +0800 Subject: too long float In-Reply-To: <13p0mfhjgriek01@corp.supernews.com> References: <13p0mfhjgriek01@corp.supernews.com> Message-ID: <18c1e5f20801180004g2e194480l2ea294f41bd5809e@mail.gmail.com> thanks all! On Jan 18, 2008 3:49 PM, Dennis Lee Bieber wrote: > On Fri, 18 Jan 2008 13:55:17 +0800, "J. Peng" > declaimed the following in comp.lang.python: > > > > > why this happened on my python? > > > > >>> a=3.9 > > >>> a > > 3.8999999999999999 > > > > I wanted 3.9 but got 3.89................ > > How to avoid it? thanks. > > > Avoid it? You don't... You alleviate the concern by understanding > that floating point is only precise if the value is a fraction of 2: 1, > 0.5, 0.25, 0.125... > > Computer Science recommends that one does NOT compare two floats for > equality -- instead one should compare the absolute value of the > difference of the two floats against some required epsilon (ie, how far > apart two floats can be and still be considered equal... > abs(f1 - f2) < 0.000001 > for example) > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > From hat at se-162.se.wtb.tue.nl Thu Jan 17 11:07:26 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 17 Jan 2008 17:07:26 +0100 Subject: How to create graphs an embed them in GUI? References: Message-ID: On 2008-01-17, Heiko Niedermeyer wrote: > As I'm learning Python from scratch, I don't care wether to use (=learn) > TKinter or PyQt or whatever, I just need some advice, which suits my > needs best. > It would be nice to have the programm working under win and linux > (shouldn't be a big Problem) and my requirements concerning the standard PyGTK is a 3rd option, and wxWindows + Python is a 4th option. TKinter is supplied with Python, which means everybody with Python also has TKinter. Main draw-backs are that it is quite old. Also, it has a peculiar way of getting stuff drawn at a canvas. PyQt is available free with some additional restriction (plz read the license) for the Linux system, I don't know whether you can also get a Win version under the same conditions (you couldn't when I looked the last time). PyGTK is said to be usable for both platforms. I know it works with Linux, and there exists a PyGTK installer for Win, but I hacve never used it. No recent experience with wxWindows. > My problem is, that I want to add graph (simple, line connected X,Y- > scatter plots) and if possible the 3D representation of atoms in a > molecule (-> coloured spheres in space). You should probably seperate both problems, in particular if you want to have the program do the layout for you. For 2D layout, Graphviz is one of the better known packages, run it as a child process. There are several graphviv/dot Python libraries available, search PyPI for them. For 3D, I don't know any programs. > I think it would take me years to program those by myself, so I would ne > ready to use packages, if available. > Long story short: Are there packages that could do this, and does it > matter which GUI I want to embed them in? If you want a GUI that understands how to layout chemical structures, you won't have many options (on the other hand, you never know, have you tried searching PyPI already?). On the other hand, once you have the coordinates, drawing them is kind of trivial in just about any GUI toolkit. (An alternative may be to have the user lay them out by dragging them with the mouse. Programming that is however probably a lot more work.) Sincerely, Albert From bearophileHUGS at lycos.com Mon Jan 28 18:48:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 28 Jan 2008 15:48:13 -0800 (PST) Subject: A question about osyco References: <606hucF1p0rptU1@mid.uni-berlin.de> Message-ID: <4e8bd7b3-29d2-4fcc-baad-7e6ecfe829c4@v4g2000hsf.googlegroups.com> Marc 'BlackJack' Rintsch: > Try calling the iterative one twice and measure the time of the second > call. IIRC psyco needs at least one call to analyze the function, so the > first call is not speed up. That's how Java HotSpot works, but Psyco is very different from HotSpot, and I think you are wrong. I don't exactly know the answer to the question of the OP, but I think the two functions are different: in the second function most time isn't spent in managing the xrange or in the assign, but in the sum between long ints, and Psyco can't speed up that operation (you need gmpy for that, and in certain tricky situations gmpy may even result slower, maybe when you use small numbers). Bye, bearophile From fredrik at pythonware.com Thu Jan 10 02:51:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 08:51:44 +0100 Subject: docstrings style question In-Reply-To: <13obcbumpitbe23@corp.supernews.com> References: <13obcbumpitbe23@corp.supernews.com> Message-ID: Steve Brown wrote: > I've got a series of modules which look like this: > > #************ > # > # Temperature Sense Test > # > #************ > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > > I don't like the duplicated information: But the comment is attractive, and > the docstring self.__doc__ is already in use in the test log. I've read that > all modules and classes should have docstrings, but I don't really have > anything else to say, and each module contains only one class. I don't think > that > > """Temperature Sense Test""" > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > would be a real improvement. > > What do you think? since you already seem to cater to your audience (clearly marked comments for people browsing the code, brief docstrings for the test log), I don't really see why you should change anything. > I've read that all modules and classes should have docstrings if nobody's going to read them, there's no reason to add them. don't treat generic style advice as dogma. From victorsubervi at gmail.com Mon Jan 28 10:21:55 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 28 Jan 2008 11:21:55 -0400 Subject: Unicode Problem Message-ID: <4dc0cfea0801280721h2e70c605p565b73bc6b6c4d87@mail.gmail.com> Hi; New to unicode. Got this error: Traceback (most recent call last): File "", line 1, in File "", line 29, in tagWords File "/usr/local/lib/python2.5/codecs.py", line 303, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 9: ordinal not in range(128) I think the problem comes from this code snippet: for line in sentences: print line tup = re.split(' ', line) for word in tup: for key, value in dictionary.items(): if key == word: word = word + '::' + value newLine.append(word) sentences.close() TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Jan 24 18:51:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jan 2008 00:51:47 +0100 Subject: creating .pyo with make In-Reply-To: <4798ddac$0$28813$426a74cc@news.free.fr> References: <4797c5d7$0$20781$426a34cc@news.free.fr> <4797c8d7$0$16956$426a74cc@news.free.fr> <5vq03cF1mod1jU1@mid.uni-berlin.de> <4798ddac$0$28813$426a74cc@news.free.fr> Message-ID: <5vsmknF1nnebqU2@mid.uni-berlin.de> Yann Leboulanger schrieb: > Diez B. Roggisch wrote: >> Yann Leboulanger schrieb: >>> Yann Leboulanger wrote: >>>> Hi, >>>> >>>> I use autoconf / automake to manage my python project, and I'l like >>>> make / make install to create / install .pyo files instead of .py >>>> files. >>>> >>>> Is there something I should add to my Makefile.am files to do that? >>>> Or should I do all that myself with py_compile module? >>>> >>>> Are there some examples somewhere with autotools? >>>> >>>> Thanks for your help >>> >>> Hehe replying to myself. It seems I just have to replace >>> project_DATA = $(srcdir)/*.py >>> by >>> project_PYTHON = $(srcdir)/*.py >>> >>> Then when I do make install, it installs .py, .pyc and .pyo. >>> Would it be possible to install only .pyo? Is it a good idea? >> >> There might be the occasional code that relies on doc-strings to work >> - seldomly, but possible. Which are obmitted by .pyo, but not of pyc. >> >> Apart from that, having only pyc-files (or pyo for that matter) sucks. >> Just today I had to delve into a ZOPE-application, setting breakpoints >> and getting things done. It would have been impossible or at least >> much more inconvenient to debug if I hadn't had the sources available >> (and put at a place where they actually get invoked from the >> interpreter, not lying around unrelated) >> >> Diez > > Source are available i ntarballs, but when I do make install I don't > care to install .py files. .pyo are enough to run the application. As I said - not installing them will make debugging for someone who knows how to deal with it just more inconvenient. And if you plan to release the code anyway - don't bother separating pyc/pyo from the py. Diez From musiccomposition at gmail.com Fri Jan 18 22:46:31 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 18 Jan 2008 19:46:31 -0800 (PST) Subject: Unique thread ID References: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> <97c1bc57-5caf-4fa5-96d7-f6847db9e18c@f10g2000hsf.googlegroups.com> Message-ID: <93fa9e1f-92c5-43de-af59-8db8c9b98174@u10g2000prn.googlegroups.com> On Jan 18, 8:31 pm, "Gabriel Genellina" wrote: > En Fri, 18 Jan 2008 22:41:47 -0300, Benjamin > escribi?: > > > On Jan 18, 2:31 am, Christian Heimes wrote: > >> Benjamin wrote: > >> > Is there a way to obtain a unique ID for the current thread? I have an > >> > object that I need to store local thread data in, and I don't want to > >> > use threading.local because each thread might have multiple instances > >> > of my object. > > >> threading.get_ident() but please use threading.local. Nobody is going to > >> stop you if you use a list or dict in threading.local. > > then, I have to figure out how to represent an instance of my object > > in threading.local. (The data also won't be garbage collect when my > > object is, will it?) I think the unique id is elegant in this case. > > I think you didn't get how threading.local works yet. It's a lot easier > than you imply. Just store your instances as attributes of a > threading.local object. You may use a list or dictionary if you want > multiple instances. > Read _threading_local.py, it contains a lot of examples. You're correct. I misread the documentation. I now understand how it works and am using it. Thanks for pointing me down the right path. > > -- > Gabriel Genellina From walterbyrd at iname.com Tue Jan 29 12:11:38 2008 From: walterbyrd at iname.com (walterbyrd) Date: Tue, 29 Jan 2008 09:11:38 -0800 (PST) Subject: Trying to understand Python web-development Message-ID: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com> I don't know much php either, but running a php app seems straight forward enough. Python seems to always use some sort of development environment vs production environment scheme. For development, you are supposed to run a local browser and load 127.0.0.1:5000 - or something like that. Then to run the same thing in a development environment, I have to configure some files, or touch all the files, restart the web-server, or something. Why is that? Python also seems to require some sort of "long running processes" I guess that the python interpretor has to running all of time. I am not really sure about what wsgi is supposed to accomplish. From solipsis at pitrou.net Tue Jan 8 04:46:34 2008 From: solipsis at pitrou.net (Antoine Pitrou) Date: Tue, 8 Jan 2008 09:46:34 +0000 (UTC) Subject: Passing contextual information when logging References: Message-ID: Hi Vinay, > I would welcome your views on whether the LoggerAdapter class is > suitable for adding to the logging package in Python 2.6/3.0. Does it > do what might reasonably be expected out of the box? I think it's quite suited to the problem, yes. One question : why does the exception() method call Logger.error() rather than Logger.exception() ? One suggestion : pass in a Logger object rather than a logger name to the LoggerAdapter constructor. (this also means that users could stack LoggerAdapter objects if they wanted to) Thanks Antoine. From andre.roberge at gmail.com Sun Jan 27 21:02:51 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 27 Jan 2008 18:02:51 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> Message-ID: On Jan 27, 9:47 pm, Steven D'Aprano wrote: > On Sun, 27 Jan 2008 19:13:27 -0500, Terry Reedy wrote: > > [snip] > > > class Test(object): > > @autoassign > > def __init__(self, _foo, _bar, baz): > > print 'baz =', baz > > [snip] > > > I think this version, with this name convention, is nice enough to > > possibly go in the stdlib if there were an appropriate place for it. > > Not sure where though. If there were a classtools module.... > > -1/2 > > I don't like the name convention. _name already has a perfectly good > convention: it's a private name, don't mess with it. That includes in > function/method signatures. With your convention, _foo is public. > > I suppose you could write __foo for a private name, and ___foo for a > *really* private name, relying on the decorator to strip one of the > underscores. But counting all those underscores is a PITA, and what > happens if you don't actually want that private name set as an instance > attribute? > > As nice as this feature would be, and I vote +2 on the functionality, I > wonder whether the amount of line noise in method definitions now will be > approaching Perlish levels? We've got default values, type annotations > (in Python3), *args and **kwargs, _ private names, and now we want to add > auto-assignment. > > If we do get syntax support, I vote +1 on &foo, +1/2 on @foo, -1 on .foo > and -1 on self.foo. (It's explicit, but it's long...). > > -- > Steven Here's a version that 1. does not require new syntax 2. does not *necessarily* override the "_" prefix convention 3. follows the "Explicit is better than implicit" convention when being called. (Note: I do not necessarily recommend the "self_" choice) ======== from functools import wraps from inspect import getargspec def autoassign(prefix): def _autoassign(_init_): @wraps(_init_) def __autoassign(self, *args, **kwargs): argnames, _, _, _ = getargspec(_init_) for name, value in zip(argnames[1:], args): if name.startswith(prefix): setattr(self, name[len(prefix):], value) _init_(self, *args, **kwargs) return __autoassign return _autoassign class Test(object): @autoassign('self_') def __init__(self, self_foo, self_bar, baz): print 'baz =', baz t = Test(1, 2, 3) print t.foo print t.bar print t.baz # raises an exception ============= Andr? From BjornSteinarFjeldPettersen at gmail.com Sun Jan 27 03:46:14 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 27 Jan 2008 00:46:14 -0800 (PST) Subject: Using a dict as if it were a module namespace References: <13podkpqqvef674@corp.supernews.com> Message-ID: <80e42440-e172-4c4d-8b83-9fcd43744be2@q77g2000hsh.googlegroups.com> On Jan 27, 8:45 am, Steven D'Aprano wrote: > I have a problem which I think could be solved by using a dict as a > namespace, in a similar way that exec and eval do. > > When using the timeit module, it is very inconvenient to have to define > functions as strings. A good alternative is to create the function as > normal, and import it: > > def myfunc(x, y): > return x+y > > timeit.Timer("myfunc(59, 60)", "from __main__ import myfunc").timeit() > > Not only is this an easy idiom to follow, but myfunc can live in another > module: just replace __main__ with the module name. > > Now, I'm trying to build a suite of tests to use with timeit. I have a > bunch of tests which I've created as dicts: > > test_suite= [dict(x=59, y=60), dict(x=-1, y=-2)] > > What I *think* I want to do is use the from ... import idiom to grab > arguments from the dicts as if they were modules, but this doesn't work: > > expr = "myfunc(x, y)" > for test in test_suite: > setup = "from __main__ import myfunc; from test import x, y" > t = timeit.Timer(expr, setup).timeit() > > Even if the Timer could see test, it is not a module and you can't import > from it. Naturally. > > Alternatives that I have found: > > (1) Import the test and grab the values needed from it: > > setup = """from __main__ import myfunc, test > x, y = test['x'], test['y']""" > > I don't like this one. It doesn't seem very elegant to me, and it gets > unwieldy as the complexity increases. Every item I need from test has to > be named twice, violating the principle Don't Repeat Yourself. If the > tests change, the setup string has to be explicitly changed also. > > (2) Mess with the global namespace: > > globals().update(t) > setup = "from __main__ import myfunc" > > I don't like this one. It looks hackish, and I worry about conflicts and > side-effects. If it works (and I haven't tested it) it relies on an > implementation detail of timeit.Timer.__init__, namely the line > "exec code in globals(), ns". Worst of all, it pollutes or even mangles > the global namespace of the calling code, not the code being tested. > > (3) Explicitly pass a namespace dict to the Timer class, possibly even > getting rid of setup altogether: > > test['myfunc'] = myfunc > t = timeit.Timer(expr, '', ns=test).timeit() > > This would be the most elegant solution, but at this time it is > completely hypothetical. Timer does not have that functionality. > > (4) Dump the test data straight into the setup string: > > setup = "from __main__ import myfunc; x = %(x)s; y = %(y)s" % t > > Again, unwieldy and against DRY. The additional disadvantage is that > there are many types of test data that can't be converted to and from > strings like that. > > What do others think? Have I missed something? What other alternatives > are there? > > -- > Steven You might have lost me, but wouldn't it be easier to do some variation on this test_suite = [ '(x=59, y=60)', # either have strings here... '(x=-1, y=-2)', ] for test in test_suite: # ... or convert the dicts to appropriate strings here... expr = 'myfunc' + test t = timeit.Timer(expr, 'from __main__ import myfunc').timeit() ... -- bjorn From sigpoggy at hotmail.com Sat Jan 26 02:08:34 2008 From: sigpoggy at hotmail.com (JimT) Date: Fri, 25 Jan 2008 23:08:34 -0800 Subject: wx.EVT_RIGHT_UP strangeness? Message-ID: <479adc74$0$5107$9a6e19ea@unlimited.newshosting.com> I'm playing with wxPython 2.8.7.1 on OS X 10.4.11 with MacPython 2.5 I ran the demo program found what may be a bug with the right mouse button up event. The demo is ShapedWindow.py. Everthing thing seems to work fine except that right clicking does not close the window. Tracing the program shows that the event never fires. Upon closer scrutiny I discovered if you bind the wx.EVT_RIGHT_DOWN event, the wx.EVT_RIGHT_UP now fires. I tried this in a couple programs and the behavior is consistent. Is this the way it is supposed to work? If not, am I the only one with this problem? From mr.cerutti at gmail.com Tue Jan 15 13:25:27 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Tue, 15 Jan 2008 13:25:27 -0500 Subject: Why this apparent assymetry in set operations? In-Reply-To: <5a3ace63-a8cf-4970-a95e-4243226fbac7@j20g2000hsi.googlegroups.com> References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> <5a3ace63-a8cf-4970-a95e-4243226fbac7@j20g2000hsi.googlegroups.com> Message-ID: <51302a8c0801151025g1ceca717i8f9995a9807d7074@mail.gmail.com> On Jan 15, 2008 12:06 PM, Chris M wrote: > On Jan 15, 11:51 am, "Neil Cerutti" wrote: > > > > So this is a bug in set_update or in set_ior. They can't both be > > right. > > > > It's not a bug. > > "Note, the non-operator versions of union(), intersection(), > difference(), and symmetric_difference(), issubset(), and issuperset() > methods will accept any iterable as an argument. In contrast, their > operator based counterparts require their arguments to be sets. This > precludes error-prone constructions like set('abc') & 'cbs' in favor > of the more readable set('abc').intersection('cbs')." Thanks. That neatly answers Skip's question, assuming he buys the putative error pronicity. The docs say the design is based on lessons learned from the sets module, so that also explains why it's different from the module version, as well. -- Neil Cerutti From dtgeadamo at yahoo.com Fri Jan 25 03:22:36 2008 From: dtgeadamo at yahoo.com (mistersexy) Date: Fri, 25 Jan 2008 00:22:36 -0800 (PST) Subject: Ideas for Python Programming Message-ID: <9daf42a0-90bf-4881-8c07-3851a2b3f564@c23g2000hsa.googlegroups.com> I have been programming in python for some time but I have become short of ideas. A software exhibition is coming up, and I plan to show python's worth 'cos it is quite underrated in this part of the world. Could anyone suggest any really good program ideas and information on how to implement them? I heartily welcome any good ideas. From Steven.Watanabe at autodesk.com Tue Jan 22 10:02:35 2008 From: Steven.Watanabe at autodesk.com (Steven Watanabe) Date: Tue, 22 Jan 2008 07:02:35 -0800 Subject: Don't want child process inheriting open sockets Message-ID: <800886C2A4A73E44BA0FE45152C023702503AD6561@ADSK-NAMSG-02.MGDADSK.autodesk.com> I'm using subprocess.Popen() to create a child process. The child process is inheriting the parent process' open sockets, but I don't want that. I believe that on Unix systems I could use the FD_CLOEXEC flag, but I'm running Windows. Any suggestions? -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Jan 11 17:29:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 11 Jan 2008 14:29:32 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> Message-ID: <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> On Jan 11, 2:57 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > Any ideas for a thread-safe list.removeall( X ): removing all > > occurrences of X within list L, when L might be modified concurrently? > > That way lies madness. Do something sensible instead. Put a lock > around the list, or put all mutators for the list into a single > thread, or whatever. Don't do what you're describing. This function just wants X out of the list. It doesn't matter if this happens before, during, or after something else; so long as it happens. From ajd at kring.com Tue Jan 22 23:37:15 2008 From: ajd at kring.com (Ajay Deshpande) Date: Wed, 23 Jan 2008 10:07:15 +0530 Subject: monitoring device status with python ... Message-ID: hi everyone: i am writing a program, which needs to keep monitoring whether a certain usb hard drive is connected/hot-plugged in or not. instead of repeatedly checking if its path exists or not, can i have the os let my program know that the device has been connected? i have read about the minihallib module but have not come across an elaborate example. can any of you point me to any examples (or alternatives)? id appreciate any help. regards, -ajay -------------- next part -------------- An HTML attachment was scrubbed... URL: From B.Ogryczak at addr.in.reply-to.invalid Sun Jan 20 10:39:35 2008 From: B.Ogryczak at addr.in.reply-to.invalid (Bart Ogryczak) Date: Sun, 20 Jan 2008 15:39:35 +0000 (UTC) Subject: Bug in __init__? References: Message-ID: On 2008-01-18, citizen Zbigniew Braniecki testified: > It's really a nice pitfall, I can hardly imagine anyone expecting this, AFAIR, it's described in Diving Into Python. It's quiet elegant way of creating cache. def calculate(x,_cache={}): try: return _cache[x] except KeyError: _cache[x] = result = _lotsa_slow_calculations(x) return result bart -- This signature is intentionally left blank. http://candajon.azorragarse.info/ http://azorragarse.candajon.info/ From fredrik at pythonware.com Thu Jan 3 17:21:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 23:21:27 +0100 Subject: choosing random dynamic port number In-Reply-To: <32e43bb70801031409o5d1dcd2at5a159339cd43ae52@mail.gmail.com> References: <32e43bb70801031409o5d1dcd2at5a159339cd43ae52@mail.gmail.com> Message-ID: Emin.shopper Martinian.shopper wrote: > Is there a good way to choose/assign random dynamic port numbers in python? > > I had in mind something like the following, but if multiple programs are > generating random port numbers, is there a way to check if a given port > number is already taken? > > def GenerateDynamicPortNumber(): > "Generate a random dynamic port number and return it." > # port numbers between 49152 to 65535 are dynamic port numbers > return 49152 + random.randrange(15000) def GenerateDynamicPortNumber(): return 0 (to get the actual number, use getsockname() on the socket after you've called "bind" on it) From fredrik at pythonware.com Tue Jan 8 05:57:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 Jan 2008 11:57:25 +0100 Subject: use fileinput to read a specific line In-Reply-To: References: Message-ID: Martin Marcher wrote: >> i need to read line 4 from a header file > > http://docs.python.org/lib/module-linecache.html I guess you missed the "using linecache will crash my computer due to memory loading, because i am working on 2000 files each is 8mb" part. From __peter__ at web.de Thu Jan 10 06:29:01 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jan 2008 12:29:01 +0100 Subject: Rebuild list of objects with redundancies on objects' attribute References: Message-ID: Nico Grubert wrote: > Hi there > > I have a list of dummy objects which have the attributes 'location', > 'name', 'gender'. > Now I want to rebuild this list in order to avoid redundancies on > objects with the same 'location'. > > Example: > > #------------------------------------------------------------------ > class Dummy: > pass > > a = Dummy() > a.location = 'tokio' > a.name = 'john' > a.gender = 'm' > > b = Dummy() > b.location = 'tokio' > b.name = 'peter' > b.gender = 'm' > > c = Dummy() > c.location = 'madrid' > c.name = 'susan' > c.gender = 'f' > > d = Dummy() > d.location = 'london' > d.name = 'alex' > d.gender = 'm' > > persons = [a, b, c, d] > > print "loc name gender" > print "---------------------" > for obj in persons: > print "%s - %s - %s" % (obj.location, obj.name, obj.gender) > > #------------------------------------------------------------------ > > The output reads like this: > > loc name gender > --------------------- > tokio john m > tokio peter m > madrid susan f > london alex m > > I want to create this list (where name and gender are lists): > loc name gender > ----------------------------- > tokio [john, peter] [m] > madrid [susan] [f] > london [alex] [m] > > How can I do this? Put the persons into a dictionary using the location as key from collections import defaultdict groups = defaultdict(list) for p in persons: groups[p.location].append(p) Below is a spoiler that uses itertools.groupby(), but you learn more if you try to work it out yourself ;) from itertools import groupby def location(p): return p.location persons.sort(key=location) print "loc name gender" print "---------------------" for loc, group in groupby(persons, key=location): group = list(group) genders = sorted(set(p.gender for p in group)) names = sorted(p.name for p in group) print "%s - %s - %s" % (loc, names, genders) Peter From dongie.agnir at gmail.com Wed Jan 9 14:11:39 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Wed, 9 Jan 2008 11:11:39 -0800 (PST) Subject: Python too slow? Message-ID: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> I'm pretty new to Python, and even newer to Image/Video processing, and trying to get started on a project similar to GRL Vienna's laser marker. I found some sample code here http://janto.blogspot.com/2006/01/motion-capture-in-python.html, but after running the code with the included sample input file, it seems quite slow (1-2 seconds from start to finish to do the 800 by 600 gif image). Is there a better way to do color tracking, or is Python just too slow as an interpreted language to do any effective color tracking? From casey at rodarmor.com Thu Jan 17 02:50:25 2008 From: casey at rodarmor.com (Casey Rodarmor) Date: Wed, 16 Jan 2008 23:50:25 -0800 Subject: Extending the readline module? Message-ID: Hi everyone, I'm writing a little curses-mode utility for renaming files using regexes, and I want to use GNU readline to get user input. However, it looks like the readline module doesn't support all of readline's functionality. I've looked around, and it looks like the best thing to do would be to try to extend the readline module myself to expose the functions I need. I'm exited to try to tackle the project, and it would be nice to get in touch with the maintainer of the module, so that I can get some advice and maybe try to get my additions included in the main branch. What is the best way to go about doing this? Best regards, Casey Rodarmor -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyrie at uh.cu Tue Jan 22 20:28:39 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 23 Jan 2008 01:28:39 +0000 Subject: translating Python to Assembler In-Reply-To: References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: <1201051719.479698475c99d@comuh.uh.cu> I second Wim's opinion. Learn python as a high level language, you won't regret it. About google, I'll give you a little gtip: > > For example a Google for "python.pdb" returns +python > > +pdb, so I get a ridiculous number of returns referring to the python > > debugger. I have mentioned this to Google several times, but I guess > > logic isn't one of their strong points. :-) Instead of searching 'python.pdb' try the query "filetype:pdb python", or even "python pdb" (quoted). The first one whould give you files with pdb extension and python in the name or contents, and the second one (quoted) should return pages with both words together, except for commas, spaces, dots, slashs, etc. However... one of the second query results is this thread in google groups... not a good sign. -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie Quoting Wim Vander Schelden : > Python modules and scripts are normally not even compiled, if they have > been, > its probably just the Python interpreter packaged with the scripts and > resources. > > My advice is that if you want to learn Python, is that you just read a book > about > it or read only resources. Learning Python from assembler is kind of... > strange. > > Not only are you skipping several generations of programming languages, > spanned > over a period of 40 years, but the approach to programming in Python is so > fundamentally different from assembler programming that there is simply no > reason > to start looking at if from this perspective. > > I truly hope you enjoy the world of high end programming languages, but > treat them > as such. Looking at them in a low-level representation or for a low-level > perspective > doesn't bear much fruits. > > Kind regards, > > Wim > > On 1/22/08, over at thepond.com wrote: > > > > My expertise, if any, is in assembler. I'm trying to understand Python > > scripts and modules by examining them after they have been > > disassembled in a Windows environment. > > > > I'm wondering if a Python symbols file is available. In the Windows > > environment, a symbol file normally has a PDB extension. It's a little > > unfortunate that Python also uses PDB for its debugger. Google, for > > whatever reason, wont accept queries with dots, hyphens, etc., in the > > query line. For example a Google for "python.pdb" returns +python > > +pdb, so I get a ridiculous number of returns referring to the python > > debugger. I have mentioned this to Google several times, but I guess > > logic isn't one of their strong points. :-) > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- "Al mundo nuevo corresponde la Universidad nueva" UNIVERSIDAD DE LA HABANA 280 aniversario From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 10:10:33 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 16:10:33 +0100 Subject: Basic inheritance question In-Reply-To: <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> Message-ID: <478e1e3e$0$18054$426a74cc@news.free.fr> Lie a ?crit : > On Jan 15, 9:00 pm, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Lie a ?crit : >> >> >> >>> On Jan 7, 2:46 am, Bruno Desthuilliers >>> wrote: >>>> Lie a ?crit : (snip) >>>>> No, seriously it isn't Java habits only, most other languages wouldn't >>>>> need explicit calling of class name. >>>> Where is the "explicit calling of class name" exactly ? >>> >>> Perhaps I was a bit tired when writing that (I wouldn't understand >>> what I wrote if I were you)... what I meant is most other languages >>> doesn't usually enforce us to explicitly state the containing class >>> name, which in python is generally called "self". >> >> 'self' (or whatever you name it) is not the "containing class name", > > Current instance is what I meant, thanks for pointing out the > incorrect term I used. > >> it's the first argument of the function - which usually happens to be >> the current instance when the function is used as a method. > > And that's the point, self (or anything you name it) is almost always > the current instance # this is a plain function. In this function, # 'obj' can be whatever that happens to have a (numeric) # 'stuff' attribute def func(obj, arg): return (obj.stuff + arg) / 2.0 # this is a class with an instance attribute 'stuff' class Foo(object): def __init__(self, bar): self.stuff = bar + 42 # this is another (mostly unrelated) class # with a class attribute 'stuff' class Bar(object): stuff = 42 # this is a dummy container class: class Dummy(object): pass # now let's play: import new d = Dummy() d.stuff = 84 print func(d, 1) d.baaz = new.instancemethod(func, d, type(d)) print d.baaz(2) f = Foo(33) print func(f, 3) Foo.baaz = func f.baaz(4) print func(Bar, 5) Bar.baaz = classmethod(func) Bar.baaz(6) > and that makes it functionally the same as Me and > this in VB and Java. Depends on the context, cf above !-) >>> Most other languages >>> 1) automatically assign the containing class' object >> s/containing class' object/current instance/ >> >>> in a keyword >>> (Java: this, VB: Me) behind the screen, > >> That's not very far from what a Python method object does - >> automatically assign the current instance to something. The difference >> is that Python uses functions to implement methods (instead of having >> two distinct contructs), so the only reliable way to "inject" the >> reference to the current instance is to pass it as an argument to the >> function (instead of making it pop from pure air). > > It isn't very far, but Python makes it obvious about the assignment > (not behind the screen). Exactly. And given both the simplicity of the solution and what it let you do, that's a *very* GoodThing(tm) IMHO. (snip) >>> and 2) automatically searches >>> variable name in both the local variable table and the containing >>> class variable table (so to refer to a class variable named var from a >>> method inside the class, we only need to write var, not self.var as in >>> python). >> This - as you know - cannot work well with Python's scoping rules and >> dynamicity. Anyway, implicit object reference is definitively a >> BadThing(tm) wrt/ readbility, specially with multiparadigm languages >> (like Python or C++). Why do you think soooo many C++ shops impose the >> m_something naming scheme ? > > Implicit object reference for the containing class has little harm, if > a class is so complex that there are more than 10 class-level > variable, then it is obvious that that class needs to be fragmented to > smaller classes. Not necessarily. There are general rules (like 'keep your classes small and focused', which I wholefully agree with), there are guidelines (like 'more than 10 member variables might smell like refactoring), and there's real life, where one very often faces classes that have much more than 10 member variables and still are as small and focused as possible. > Remembering less than 10 variable and avoiding naming > collision among just 10 variable is not hard (and 10 is really too > many, most classes should only use 2-4 variables), I really doubt you'll be able to write any working non-trivial software trying to strictly follow this rule. > especially if you > have a good IDE that employs Intellisense-like technology (IDLE has > it). IDLE is certainly not a "good IDE" in my book. > And it is always a Bad Thing(tm) to use the same name for two > variable in the class and in function (which is the main and only > source of possible ambiguity) in ANY language, even in Python. Ho, yes.... Like, this would be bad ? class Person(object): def __init__(self, firstname, lastname, birthdate, gender): self.firstname = firstname self.lastname = lastname self.birthdate = birthdate self.gender = gender C'mon, be serious. It's often hard enough to come with sensible names, why would one have to find synonyms too ? Try to come with something more readable than the above, and let us know. Seriously, this braindead rule about "not using the same name for an attribute and a local var" obviously comes from languages where the "this" ref is optional, and FWIW it's obviously the wrong solution to a real problem (the good solution being, of course, to use the fully qualified name for attributes so there's no possible ambiguity). >> Anyway, I actually know 3 languages (4 if C# works the same) that has >> this implicit 'this' (or whatever the name) 'feature', and at least 5 >> that don't. So I'm not sure that the "most other languages" qualifier >> really applies to point 2 !-) > > What's this 5 languages? Smalltalk, Python, PHP, javascript, Ruby. I don't remember how Scheme, CLOS and OCaml handle the case. > Are they a mainstream, high-level languages > or lesser known, low-level languages? C-family, Java, and Basic are > the Big Three of high-level programming language. None of C, C++, Java nor Basic qualify as "hi-level". C is the lowest possible level above assembly, C++ is often refered to as an "object oriented assembler", Java is way too static, crippled, verbose an unexpressive to qualify as "hi-level" (even if it suffers from some problems usually associated with higher level languages). I won't even comment on basic (is that really a language at all ?). >>> In VB, Me is extremely rarely used, >> I used to systematically use it - like I've always systematically used >> 'this' in C++ and Java. > > And that is what reduces readability. A proficient VB/C/Java > programmer There are quite a few proficient C/C++/Java programmers here. As far as I'm concerned, I would not pretend being one - I just have a good enough knowledge of C, Java and (alas) VB to be able to get up to speed in a reasonnable time frame. As a side note, the problem just doesn't exists in C, which has absolutely no support for OO. > would frown upon the extra, unneeded garbage as they > thought it was clear already that the variable refers to a class-level > variable. In C++, the canonical way to make this "clear" is to use the m_name convention. There must be some reason C++ programmers feel a need for this "extra, unneeded garbage" ?-) > It is a different story if, like Python, the use of self is > enforced by the language, the self wouldn't be viewed as extra > unnecessary garbage. >>> in Python, self is all >>> over the place. Well, there is positive and negative to both sides, >>> convenience in VB, and flexibility in Python. >> As far as I'm concerned, there's *no* positive point in implicit object >> reference, and there has never been (and before some paranoid nutcase >> around accuse me of overzealous biggotry : I already held this very same >> opinion years before I discovered Python). > > There is one major positive point: convenience and shorter code. > (isn't that two?) These are not rated as "positive" in my book. That's perhaps why Python is so far MFL ? > As I've pointed out, there is little harm in class-level variable's > implicit reference. Have some working experience on any non-trivial C++ project ? >>> Compare the following codes: >>> VB.NET: >>> Public Class A >>> Dim var >>> Public Function aFunction() >>> return var >> Add three levels of inheritence and a couple globals and you'll find out >> that readability count !-) > > It's the mental model that have to be adapted here, if the current > class is inheriting from another class, you've got to think it as > names from parent class as it is a native names, so you don't actually > need to know where the variable comes from In C++ (and VB IIRC), it might as well be a global So sorry but yes, I have to know where it comes from. > since knowing where it > comes from is breaking the encapsulation Nope, it's knowing what you're doing and how the piece of software at hand is working. And FWIW, while data hiding is one possible mean of encapsulation, it's by no way a synonym for encapsulation. > (which, in Python is very > weakly implemented, which favors flexibility in many cases[1]). > > [1] In Python, it is impossible to create a completely private > variable, which is the reason why the mental model of these other > languages doesn't fit Python. Never heard about the infamous '#define private public' hack in C++ ? And don't worry, there are also ways to get at so called 'private' vars in Java. >> In any non-trivial piece of C++ code, and unless the author either used >> the explicit 'this' reference or the 'm_xxx' naming convention, you'll >> have hard time figuring out where a given name comes from when browsing >> a function's code. > > If you're used to the implicit naming scheme it's easy to know where a > variable came from, if not the current scope, it's the class' scope You forgot the global scope. (snip) > As a final note: > I don't think implicit class reference is superior to explicit class > reference, neither do I think explicit class reference is superior to > implicit class reference. I think both have their own +s and -s. I > only pointed out that implicit do have its benefits, "benefit" here is a judgement call. It happens that neither I nor probably most of the people here share your judgement on this. Time for you to "import this" I'd say. > depending on the > language used (obviously Python wouldn't benefit from using implicit > behavior, due to it being extremely dynamic). Not only. This is also (and almost firstly as far as I'm concerned) a matter of readability. Anyway: this-dead-horse-been-beaten-to-hell-and-back... So if you *really* want to have the last word, I'll leave it to you !-) From nagle at animats.com Fri Jan 11 12:20:12 2008 From: nagle at animats.com (John Nagle) Date: Fri, 11 Jan 2008 09:20:12 -0800 Subject: Analyzing Python GC output - what is a "cell", and what information is available about it. In-Reply-To: References: <478707f2$0$36360$742ec2ed@news.sonic.net> Message-ID: <4787a42e$0$36403$742ec2ed@news.sonic.net> Duncan Booth wrote: > John Nagle wrote: > >> I'm printing out each entry in "gc.garbage" after a garbage collection in >> DEBUG_LEAK mode, and I'm seeing many entries like >> >> >> >> That's the output of "repr". Are "cell" objects created only from >> external C libraries, or can regular Python code generate them? Is there >> any way to find out what the 'function object' is from within Python? >> > Cell objects are created whenever you have a function that references a > variable in an outer scope. e.g. > > So in your case, cell.cell_contents.func_name might help. Tried that: print repr(item).encode('ascii','replace') print "Type:",type(item) try: print item.cell_contents except Exception, message: print "Unprintable:",message Type: Unprintable: 'cell' object has no attribute 'cell_contents' So it doesn't have a "cell_contents" attribute. Tried: print item.dir() got: 'cell' object has no attribute 'dir' Tried: print item.__dict__ got: 'cell' object has no attribute '__dict__' It looks like this is a low-level PyCellObject not generated from Python code. Any ideas? I'm using the M2Crypto and MySQLdb libraries, and suspect a reference count bug in one of those. John Nagle From erexsha at gmail.com Mon Jan 21 19:46:11 2008 From: erexsha at gmail.com (Arash Arfaee) Date: Mon, 21 Jan 2008 16:46:11 -0800 Subject: problem With Psyco on Wingide mac Message-ID: <266557d0801211646w1c9f7cd9r3a5bd19c360a57b0@mail.gmail.com> Hello All, I am trying to use psyco with wingide on mac. when I open Mac Python shell I can import psyco, but not inside the wingide. Even python shell on wingide cannot import psyco. Can anybody help me to solvethis problem? Thanks, Arash From ematus.tesis at gmail.com Fri Jan 4 08:11:13 2008 From: ematus.tesis at gmail.com (Eduardo Matus) Date: Fri, 4 Jan 2008 14:11:13 +0100 Subject: Scales question Message-ID: Hi all... I want to represent a point in 800 X 600 board in a 640 X 480 board..., for example (13, 50) in 640X480 to 800X600 so.. will be like this... Xscale = (13 * 800)/640 Xscale = 16.25 Yscale = (50 * 600)/480 Yscale = 62.5 what happend with the decimals??? I round up or down??? or there is another way to calculate this more accurate? Thks... -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigisbert.etra-id at grupoetra.com Thu Jan 3 02:27:43 2008 From: jigisbert.etra-id at grupoetra.com (Jose Ignacio Gisbert) Date: Thu, 3 Jan 2008 08:27:43 +0100 Subject: Manually installing PIL Message-ID: <001001c84dda$23d26760$2000a8c0@depid.local> Hello All, Does somebody install PIL manually??, I mean, copy directories manually without executing setup.py. I saw an identical message from Guirai, but I didn't see any response. Thanks in advance! Best Regards, Naxo -------------- next part -------------- An HTML attachment was scrubbed... URL: From Russ.Paielli at gmail.com Mon Jan 28 04:06:14 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jan 2008 01:06:14 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> <8763xe8vzd.fsf@benfinney.id.au> <87y7aa742r.fsf@benfinney.id.au> Message-ID: <4ba43e41-6218-4ccc-a738-9342758d6fb2@v46g2000hsv.googlegroups.com> On Jan 28, 12:21 am, Ben Finney wrote: > "Russ P." writes: > > OK, then how about a special function that could be called from > > inside the constructor (or anywhere else for that matter) to > > initialize a list of data members. For example, > > > self.__set__(host, port, protocol, bufsize, > > timeout) > > > This would be equivalent to > > > self.host = host > > self.port = port > > # etc. > > > I'm not sure if that is technically feasible, but it would cut down > > on repetition of names. > > It's much more attractive, because it doesn't change the function > signature. In fact, here's a variation that doesn't even need a > language change:: > > >>> class Foo(object): > ... def __init__(self, spam, eggs, beans): > ... self.__dict__.update(dict( > ... (name, value) for (name, value) in vars().items() > ... if name in ['spam', 'beans'])) > ... > >>> foo = Foo("some spam", "more eggs", "other beans") > >>> foo.spam > 'some spam' > >>> foo.eggs > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'Foo' object has no attribute 'eggs' > >>> foo.beans > 'other beans' > > -- > \ "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 If you can wrap that in a clean function that works for every class you might have something. From sgeiger at ncee.net Wed Jan 30 21:18:17 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 30 Jan 2008 20:18:17 -0600 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <47A11E78.7030003@tim.thechases.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> <47A11E78.7030003@tim.thechases.com> Message-ID: <47A12FE9.3020209@ncee.net> The answer is here: http://www.google.com/search?q=gene+expression+programming+python Tim Chase wrote: >> I do not understand why no one has answered the following question: >> >> Has anybody worked with Gene Expression Programming???? >> > > Well, my father's name is Gene, and he's expressed software wants > that I've implemented in Python...so yes, I guess I've done some > Gene Expression Programming... > > ;-P > > -tkc > > > -- 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 gneuner2/ at /comcast.net Sat Jan 12 21:16:22 2008 From: gneuner2/ at /comcast.net (George Neuner) Date: Sat, 12 Jan 2008 21:16:22 -0500 Subject: DEK's birthday References: <58762470-a68c-4fc5-af29-3d5fa06e8a4f@l1g2000hsa.googlegroups.com> Message-ID: On Sat, 12 Jan 2008 12:03:49 -0800 (PST), thermate2 at india.com wrote: >On Jan 10, 9:57?am, Jim wrote: >> DEK celebrates 70 today. >> >> I doubt he'll read this but I'll say it anyway: Happy Birthday! >> >> Jim Hefferon > >Donald Knuth is a son of a bitch who made a lot of money from tax >payer's grants. The computers he began with were built with tax >payer's money. > >His mother lived in the same newyork where the yank bastards staged >that fake drama > >letsroll911.org >stj911.org >scholarsfor911truth.org >nkusa.org >countercurrents.org >counterpunch.org > >and the bastard did not lift a finger, did not lift a pen in the >defense of the truth. > >may such bastard scholars burn in hell for ever and never know the >kingdom of heavan. > >Amen Why don't you play Hide And Go Fuck Yourself. From http Fri Jan 18 19:11:41 2008 From: http (Paul Rubin) Date: 18 Jan 2008 16:11:41 -0800 Subject: TopSort in Python? References: <0000161d@bossar.com.pl> <358cc5a3-300f-49ba-9857-2f0cd629a4df@i12g2000prf.googlegroups.com> Message-ID: <7x8x2meksi.fsf@ruckus.brouhaha.com> Paddy writes: > When I needed one I didn't know the name. I'm curious, how did you > know to look for the topological sort algorithm by name? It's a well known algorithm in computer science, described in any number of textbooks, for example probably http://projects.csail.mit.edu/clrs/ There is also a wikipedia article: http://en.wikipedia.org/wiki/topological_sorting From nodrogbrown at gmail.com Mon Jan 21 11:08:12 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Mon, 21 Jan 2008 08:08:12 -0800 (PST) Subject: eucledian dist calculations References: <87aff9a8-a9d8-4236-8a86-66aa58417792@i72g2000hsd.googlegroups.com> <13c59b0c-534a-4a4a-bad3-f6f51721ab78@n20g2000hsh.googlegroups.com> Message-ID: <8f7c5035-cb02-4ab2-83af-30c605194c17@l1g2000hsa.googlegroups.com> > > 1. 'temp' is not used > 2. Lose the superfluous parentheses in 'if' statements > 3. Put space around operators > 4. I've never used any of numpy & friends, but: > (a) Can't you replace the inner loop with something like this: > distance = abs(input_weight - weights[image, :]) > (b) I doubt that you need the .copy() > 5. Lose the hard-wired numbers like 30 and 100 > 6. Put it inside a function and *TEST* it > thanx John , will go thru those and do the cleanup gordon From nytrokiss at gmail.com Sun Jan 6 08:48:08 2008 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 6 Jan 2008 14:48:08 +0100 Subject: Killing worker threads In-Reply-To: References: Message-ID: <8a6b8e350801060548m6f39594che1207cc5bc4b6487@mail.gmail.com> You can use the stop method! On Jan 6, 2008 2:04 PM, tarun wrote: > Hello All, > > Can anyone help me with a simple code through which the main thread can > kill the worker thread it started. > > Thanks & Regards, > Tarun Devnani > > -- > 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 bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 03:57:05 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 09:57:05 +0100 Subject: python recursive function In-Reply-To: References: Message-ID: <47872f56$0$21435$426a74cc@news.free.fr> Gary Herron a ?crit : > Tom_chicollegeboy wrote: >> here is what I have to do: >> >> This question involves a game with teddy bears. The game starts when I >> give you some bears. You then start giving me back some bears, but you >> must follow these rules (where n is the number of bears that you >> have): >> > This sounds very much like a homework assignment, Indeed. > and so should probably > not be answered here. (Neither should it have been asked here.) If, > in your attempt to write this program, you have some questions about > Python, then I encourage to ask those questions here. Garry, you should have read the whole post before answering. The OP's attempt at solving the problem was below, along with the question. (snip) From ivan at 0x4849.net Fri Jan 11 12:46:29 2008 From: ivan at 0x4849.net (Ivan Novick) Date: Fri, 11 Jan 2008 09:46:29 -0800 (PST) Subject: reading a specific column from file References: Message-ID: <4fb9145b-6930-4d89-a4a3-ddd3504373aa@e23g2000prf.googlegroups.com> On Jan 11, 4:15 am, cesco wrote: > Hi, > > I have a file containing four columns of data separated by tabs (\t) > and I'd like to read a specific column from it (say the third). Is > there any simple way to do this in Python? You say you would like to "read" a specific column. I wonder if you meant read all the data and then just seperate out the 3rd column or if you really mean only do disk IO for the 3rd column of data and thereby making your read faster. The second seems more interesting but much harder and I wonder if any one has any ideas. As for the just filtering out the third column, you have been given many suggestions already. Regards, Ivan Novick http://www.0x4849.net From bret.wortman at gmail.com Wed Jan 23 08:58:05 2008 From: bret.wortman at gmail.com (Bret) Date: Wed, 23 Jan 2008 05:58:05 -0800 (PST) Subject: A global or module-level variable? References: <7637fd0b-961e-4730-abd8-96e85c907082@i72g2000hsd.googlegroups.com> <7xwsq1tyts.fsf@ruckus.brouhaha.com> Message-ID: <63002d69-7738-4cae-bfb5-b933f16591b8@t1g2000pra.googlegroups.com> On Jan 22, 1:00 pm, Paul Rubin wrote: > If you have to do it that way, use: Is there a better way? A more Pythonic way? From martin at v.loewis.de Sun Jan 13 12:51:06 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 13 Jan 2008 18:51:06 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801131928.54459.donn.ingle@gmail.com> References: <200801131550.50119.donn.ingle@gmail.com> <478A4408.2090805@v.loewis.de> <200801131928.54459.donn.ingle@gmail.com> Message-ID: <478A4F8A.5010108@v.loewis.de> > What happens if there is a filename that cannot be represented in it's > entirety? i.e. every character is 'replaced'. Does it simply vanish, or does > it appear as "?????????" ? :) The latter. I did open(u"\u20ac\u20ac","w") in an UTF-8 locale, then did "LANG=C ls", and it gave me ?????? (as the two characters use 6 bytes) > I spent an hour trying to find a single file on the web that did *not* have > (what seemed like) ascii characters in it and failed. Even urls on Japanese > websites use western characters ( a tcp/ip issue I suspect). Actually, an HTTP and URL issue. Non-ASCII URLs aren't really supported in the web. > I was hoping to > find a filename in Kanji (?) ending in .jpg or something so that I could > download it and see what my system (and Python) made of it. Use a text editor instead to create such a file. For example, create a new document, and save it as "????.txt" (which Google says means "casestudies.txt") Regards, Martin From gagsl-py2 at yahoo.com.ar Sun Jan 20 21:58:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 00:58:45 -0200 Subject: dynamic type variable References: <47940570.6080003@block.duxieweb.com> Message-ID: En Mon, 21 Jan 2008 00:37:36 -0200, J. Peng escribi?: > Python's variable is dynamic type,is it? No. Python has objects, and names that refer to those objects. Objects have a type, which can't change once the object is created. But a name may refer to different objects of different types at different times. See http://effbot.org/zone/python-objects.htm > But why this can't work? > >>>> 3 + 'a' > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > > So I see the number 3 can't be converted to string type automacially. Python never "converts" anything, except numeric types in expressions (2+3.0, sqrt(5L)) and sometimes string/unicode. -- Gabriel Genellina From lists at cheimes.de Thu Jan 17 01:59:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 17 Jan 2008 07:59:05 +0100 Subject: assigning values in python and perl In-Reply-To: <34e2dc93-9819-479f-a8d5-79d11350f0b3@s8g2000prg.googlegroups.com> References: <2d37f441-c01f-439b-9897-35b7e4dfa77b@h11g2000prf.googlegroups.com> <34e2dc93-9819-479f-a8d5-79d11350f0b3@s8g2000prg.googlegroups.com> Message-ID: George Sakkis wrote: > Posting a counter-example where the difference is clearly shown would > be more vastly useful than referring to a list of long obscure usenet > posts with practically no examples. C/C++ are not even mentioned in > that page. I am not claiming you are wrong, I just don't find > particularly this page particularly enlightening. I don't find a posting like "It's call-by-reference, but in fact it's doesn't behave like call-by-reference" helpful. The text explains Python's calling convention on a CS level. Please trust me that the explanation on the site is right. It was written by somebody who designed and wrote parts of Python. Christian From sylvain.thenault at logilab.fr Mon Jan 14 08:59:29 2008 From: sylvain.thenault at logilab.fr (Sylvain =?iso-8859-1?Q?Th=E9nault?=) Date: Mon, 14 Jan 2008 14:59:29 +0100 Subject: [ANN] pylint 0.14 / logilab-astng 0.17.2 Message-ID: <20080114135929.GD22982@logilab.fr> Hi there! I'm pleased to announce a new release of pylint [1] and logilab-astng [2]. I haven't personally found a lot of time to work on those projects since the latest releases but others contributors have and so I decided to publish releases including various contributions and other minor bug or crash fixes (some of which were pending for a while now). You're greatly encouraged to upgrade, see projects'changelog for more information about what changed. [1] http://www.logilab.org/projects/pylint [2] http://www.logilab.org/projects/logilab-astng Many thanks to every people who contributed! regards, -- Sylvain Th?nault LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science From khoard at gmail.com Sat Jan 19 08:48:23 2008 From: khoard at gmail.com (FireNWater) Date: Sat, 19 Jan 2008 05:48:23 -0800 (PST) Subject: Core Python Programming . . . References: <7xir1q29j5.fsf@ruckus.brouhaha.com> Message-ID: <0005f532-409b-4c4e-8483-b2e32bbc724a@q77g2000hsh.googlegroups.com> On Jan 18, 6:00 pm, Yu-Xi Lim wrote: > Mike Driscoll wrote: > > > 6-11 Conversion. > > (a) Create a program that will convert from an integer to an > > Internet Protocol (IP) address in the four-octet format of WWW.XXX.YYY.ZZZ > > (b) Update your program to be able to do the vice verse of the > > above. > > I think it's is asking to convert a 32-bit int to the dotted form. > > It's a little known fact, but IP addresses are valid in non-dotted > long-int form. Spammers commonly use this trick to disguise their IP > addresses in emails from scanners. I guess I'm not fully up to speed on what constitutes an IP address. Does the term 'octet' refer to an 8-bit (xFF) number? From paddy3118 at googlemail.com Fri Jan 18 04:21:57 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 18 Jan 2008 01:21:57 -0800 (PST) Subject: array and list References: <24f854eb-93a8-414d-a518-842bb2d185fb@s13g2000prd.googlegroups.com> Message-ID: On Jan 18, 8:18 am, "J. Peng" wrote: > > On Jan 18, 3:23 am, "J. Peng" wrote: > > >> what's the difference between an array and a list in python? > >> I see list has all features of array in C or perl. > >> so please tell me.thanks. > > > If you are new to Python, then where other languages may reach for an > > 'array', Python programs might organise data as lists. Lists are used > > much more than arrays in Python. you should find that is the case in > > tutorials/books too. > > >http://wiki.python.org/moin/PerlPhrasebook?highlight=%28perl%29 > > > - Paddy. > > Hi, > > From Core Python Programming book (btw I like this book) I know the > difference is that array can hold only one type (the C standard?), but > list can hold every type of object. But hmm, perl's array also can hold > every type of variables, why perl call it array and python call it list? Similar ideas, different names. It happens. I guess 'under the hood' Python (& Perl?), arrays might be more like an implementation of what the C programmer might call a linked list, but even then there are differences as most linked list examples given in C tutorials are lists of the same type of object,.... - Paddy. > Also, if I understand it correctly, python's tuple is called as 'list' > in perl, so I'm somewhat confused about them. > > > P.S. if you know Perl then try: > > Yes I know some Perl. I have registered module on CPAN. > > thanks! From nyamatongwe+thunder at gmail.com Thu Jan 31 18:39:16 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Thu, 31 Jan 2008 23:39:16 GMT Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> <13q2960err4db28@corp.supernews.com> Message-ID: Steve Holden wrote: > ... > Look guys, I thought we'd agreed that the PSU was no longer to be How did Steve manage to click send again after the para From jairtrejo at yahoo.com.mx Wed Jan 2 14:19:16 2008 From: jairtrejo at yahoo.com.mx (Jair Trejo) Date: Wed, 2 Jan 2008 13:19:16 -0600 (CST) Subject: Python-list Digest, Vol 52, Issue 19 In-Reply-To: Message-ID: <548872.65181.qm@web52202.mail.re2.yahoo.com> > > De: Fredrik Lundh > A: python-list at python.org > Fecha: Wed, 02 Jan 2008 15:39:11 +0100 > Asunto: Re: PyCairo, PIL and StringIO > > Jair Trejo wrote: > > > I'm doing some image processing in PIL, and I want > to > > display the results in a GTK window using PyCairo, > so > > I create a Cairo image surface from the PIL Image > like > > this: > > data > > mfile = StringIO.StringIO() > > final.save(mfile, format="PNG") > > ima = > > cairo.ImageSurface.create_from_png(mfile) > > mfile.close() > > return ima > > > > Where final is a PIL image. The problem is, I get > a > > IOError: error while reading from Input Stream. > > > > ?Any idea of why is this happening? > > "save" leaves the file pointer at an undefined > position (usually at the > end), so my guess is that you have to rewind the > file before you pass it > to the next function: > > final.save(mfile, format="PNG") > mfile.seek(0) # rewind > > also note that compressing and decompressing will > introduce unnecessary > overhead; chances are that you might get a lot > better performance if you > just shuffle the raw pixels. I haven't used PyCairo > myself, but from a > quick look at the ImageSurface documentation, > something like this should > work (untested): > > if final.mode != "RGB": > final = final.convert("RGB") > w, h = final.size > data = final.tostring() # get packed RGB buffer > ima = cairo.ImageSurface.create(data, > FORMAT_RGB24, w, h, w*3) > > (tweak as necessary) > > Thank, you, it worked! I tried rewinding the file, and it worked OK. But you were right about performance issues, so I tweaked your code and left it as: from array import array ... w,h = final.size data=array('c') data.fromstring(final.tostring()) ima=cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32,w,h,w*4) return ima Which is around 10 times faster. The problem is, it swaps the R and B bands. I could probably write my own Image.tostring(), but i found it more convenient to swap the channels before processing, and it worked just fine. ____________________________________________________________________________________ ?Capacidad ilimitada de almacenamiento en tu correo! No te preocupes m?s por el espacio de tu cuenta con Correo Yahoo!: http://correo.yahoo.com.mx/ From paddy3118 at googlemail.com Mon Jan 28 02:13:14 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 27 Jan 2008 23:13:14 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: Message-ID: On Jan 27, 5:06 pm, coldpizza wrote: > There is a pattern that occurs fairly often in constructors in Python > and other OOP languages. > > Let's take an example: > > class Server(object): > def __init__(self, host, port, protocol, bufsize, timeout): > self.host = host > self.port = port > self.protocol = protocol > self.bufsize = bufsize > self.maxthreads = maxthreads > self.timeout = timeout > > Imho, in the class above the assignment to instance fields does not > contain much programming logic and therefore can be safely 'abstracted > away' by the language itself with a syntax which would look something > like this: > > class Server(object): > def __init__(self, @host, @port, @protocol, @bufsize, @timeout): > pass > > This would be equivalent to the first example above, yet it does not > obfuscate the code in any way. Or does it? It does look much cleaner > to me. > > Of course, the ampersand is just an arbitrary choice and might have > bad connotations for those who read it as 'take address of' but @ has > some allusion to delegates which maybe is ok. > > I am not an experienced programmer and I am not sure if this is > necessarily a good idea, so I wanted to get some feedback from more > experienced Pythonistas before submitting it elsewhere. Is it not possible to write a function that queries its call stack when run to find the name of all arguments and locals() of the level above so you could write: class test(object): def __init__(self, x, y): arg2inst() and automatically assign self.x=x; self.y=y ? It could be extended so that... class test(object): def __init__(self, x, y): arg2inst("x") ... then only assigns x. Has anyone seen something like this in the cookbook? - Paddy. From http Mon Jan 14 18:15:28 2008 From: http (Paul Rubin) Date: 14 Jan 2008 15:15:28 -0800 Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> <7xsl105fvv.fsf@ruckus.brouhaha.com> <13onli9dk7mu926@corp.supernews.com> Message-ID: <7xhchgatin.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > map = {'a': Aclass, 'b': Bclass, 'c': Cclass} > class_ = map.get(astring, default=Zclass) > > The result I want is the class, not the result of calling the class > (which would be an instance). If I wanted the other semantics, I'd be > using defaultdict instead. I used default as a keyward arg name indicating the presence of a callable. I probably should have called it defaultfunc or something. x = d.get('a', f) # --> default value is f x = d.get('a', defaultfunc=f) # --> default value is result of f() . From mario at ruggier.org Thu Jan 3 09:33:42 2008 From: mario at ruggier.org (mario) Date: Thu, 3 Jan 2008 06:33:42 -0800 (PST) Subject: unicode(s, enc).encode(enc) == s ? References: <5e49e7e6-f2b3-4c9f-9dec-e5f01f12d59a@e4g2000hsg.googlegroups.com> <4773f0de$0$15825$9b622d9e@news.freenet.de> <7cb20641-ab33-4818-a911-80c684cb9792@q77g2000hsh.googlegroups.com> <4775AC6B.8070109@v.loewis.de> <1310677e-51ec-49f2-9709-196dcc4e1ac9@e4g2000hsg.googlegroups.com> <477BF54E.7090000@v.loewis.de> Message-ID: Thanks again. I will chunk my responses as your message has too much in it for me to process all at once... On Jan 2, 9:34 pm, "Martin v. L?wis" wrote: > > Thanks a lot Martin and Marc for the really great explanations! I was > > wondering if it would be reasonable to imagine a utility that will > > determine whether, for a given encoding, two byte strings would be > > equivalent. > > But that is much easier to answer: > > s1.decode(enc) == s2.decode(enc) > > Assuming Unicode's unification, for a single encoding, this should > produce correct results in all cases I'm aware of. > > If the you also have different encodings, you should add > > def normal_decode(s, enc): > return unicode.normalize("NFKD", s.decode(enc)) > > normal_decode(s1, enc) == normal_decode(s2, enc) > > This would flatten out compatibility characters, and ambiguities > left in Unicode itself. Hmmn, true, it would be that easy. I am now not sure why I needed that check, or how to use this version of it... I am always starting from one string, and decoding it... that may be lossy when that is re-encoded, and compared to original. However it is clear that the test above should always pass in this case, so doing it seems superfluos. Thanks for the unicodedata.normalize() tip. mario From teddyber at gmail.com Fri Jan 11 17:30:34 2008 From: teddyber at gmail.com (teddyber) Date: Fri, 11 Jan 2008 14:30:34 -0800 (PST) Subject: split parameter line with quotes References: Message-ID: <37fac828-20ec-4cb9-8ea7-a85cce7d3e91@k39g2000hsf.googlegroups.com> wow! that's perfect this shlex module! thanks for pointing this! On 11 jan, 20:36, Joshua Kugler wrote: > teddyber wrote: > > first i'm a newbie to python (but i searched the Internet i swear). > > i'm looking for some way to split up a string into a list of pairs > > 'key=value'. This code should be able to handle this particular > > example string : > > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > > i know i can do that with some regexp (i'm currently trying to learn > > that) but if there's some other way... > > Take a look at the shlex module. You might be able to fiddle with the shlex > object and convince it to split on the commas. But, to be honest, that > above would be a lot easier to parse if the dividing commas were spaces > instead. > > j From pavlovevidence at gmail.com Sat Jan 26 00:03:43 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 25 Jan 2008 21:03:43 -0800 (PST) Subject: Generational Interfaces Message-ID: <1b7b3b47-72f0-4a5d-9185-4903e75dba47@d70g2000hsb.googlegroups.com> While thinking about generational garbage collection, the thought of generational interfaces occurred to me. I'd thought I'd run it by you guys. I'm curious if there are any examples of this out there. I've opined on this chat room before that interfaces are more often cumbersome than helpful, especially in the early stages of a project where lots of refactoring is (or ought to be) happening. But as projects mature, interfaces do too, and that made me think interfaces could be generated automatically by monitoring the software over time. As an example, say I'm writing a flight simulator, and I have a abstract base class Airplane, that I want to have an interface someday, but I don't know what it is yet. So I define an AirplaneInterface = InterfaceTracker("Airplane") What this does is to open a sort of persistent database called Airplane (details aren't important now). The database tracks all objects that claim to implement the interface. So say the first airplane is a Piper Cherokee. I'd write a class like this: class PiperCherokeeX1(object): wingspan = 52.2 wingchord = 7.9 ... def __init__(self): self.x = 0.0 self.y = 0.0 self.z = 0.0 ... set_up_initial_state() ... AirplaneInterface.report(self) def move_stick(self,dx,dy): ... def move_thottle(self,ds): ... def move_rudder_pedals(self,ddr): ... def camera_matrix(self): return self._quat_to_matrix(self.q0,self.q1,self.q2,self.q3) def step(self,dt): ... The key here is the call to AirplaneInterface.report() at the end of __init__; this tells the interface tracker that, as of this call, this object is implementing the Aircraft interface. At this point, the interface tracker notes that PiperCherokeeX1 object has certain methods (move_stick, move_throttle, etc), certain class attributes, and certain instance attributes. And that's all it does-- at first. It just writes information into the database. As time passes, and development continues, methods and data are added, changed, reconfigured. For instance, I might split up move_stick() into move_stick_x() and move_stick_y() for some reason. Then I might get rid of these functions altogether in favor of a move_control(self,n,dx). And so on. I add more classes that implement the Aircraft interface, too. They look almost nothing like the original interface. However, through all that, the class attribute "wingspan" remains there. Until one day when the project is quite mature I add a new class, say Airbus380, that fails to define "wingspan". When this class calls AirplaneInterface.report(), it raises an InterfaceException. Basically, the InterfaceTracker decides, after some threshold of nearly universal usage of a certain method or attribute, that it has become a required part of the interface and starts raising exceptions when it's not there. Make sense? Details can vary, but that's the basic idea. In this way, you can combine some of the openness that helps in early development, but also have some of the benefits of stricter typing when things mature and turn out to be pretty strictly useful, without much effort. Thoughts? (Surely someone's thought to do this before.) Carl Banks From andymac at bullseye.apana.org.au Sat Jan 5 05:47:49 2008 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 05 Jan 2008 20:47:49 +1000 Subject: Memory Leaks and Heapy In-Reply-To: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> Message-ID: <477F6055.9050208@bullseye.andymac.org> Yaakov Nemoy wrote: > A couple of developers have mentioned that python might be fragmenting > its memory space, and is unable to free up those pages. How can I go > about testing for this, and are there any known problems like this? > If not, what else can I do to look for leaks? Marc-Andre brought up pymalloc, but it is worth clarifying a couple of issues related to its use: - pymalloc only manages allocations up to (and including) 256 bytes; allocations larger than this are passed to the platform malloc to allocate. - the work that was put in to allow return of empty arenas (in Python 2.5) was geared to handling the general case of applications that created huge volumes of objects (usually at start up) and then destroy most of them. There is no support that I'm aware of for any form of arena rationalisation in the case of sparsely occupied arenas. - it has been my experience that pymalloc is a significant benefit over the platform malloc for the Python interpreter, both in terms of performance and gross memory consumption. Prior to defaulting to using pymalloc (as of 2.3) CPython had run into issues with the platform malloc of just about every platform it had been ported to, heap fragmentation being particularly notable on Windows (though other platforms have also been subject to this). While pymalloc is highly tuned for the general case behaviour of the Python interpreter, just as platform malloc implementations have corner cases so does pymalloc. Be aware that ints and floats are managed via free lists with memory allocation directly by the platform malloc() - these objects are never seen by pymalloc, and neither type has support for relinquishing surplus memory. Be also aware that many C extensions don't use pymalloc even when they could. In addition to Marc-Andre's suggestions, I would suggest paying particular attention to the creation and retention of objects in your code - if something's no longer required, explicitly delete it. It is all too easy to lose sight of references to objects that hang around in ways that defeat the gc support. Watch out for things that might be sensitive to thread-ids for example. Careful algorithm planning can also be useful, leveraging object references to minimise duplicated data (and possibly get better performance). -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From rowen at cesmail.net Fri Jan 25 19:49:16 2008 From: rowen at cesmail.net (Russell E. Owen) Date: Fri, 25 Jan 2008 16:49:16 -0800 Subject: Problem with Tkinter scrollbar callback References: Message-ID: In article , "Ivan Van Laningham" wrote: > Hi All-- > That helps. Doing a get() on the scrollbar before a set(0.0,0.0) > returns a 4-tuple: (0.0, 0.0, 0.0, 0.0) ! I did the set(0.0,0.0) > and now the callback gets the correct number of arguments. > > However, I'm still getting the weird behaviour when clicking the > arrowheads--and the heads are all I want. They act like they've been > set to a keybounce timeout of about a millisecond. ... The arrow > click increments the number of cells in a table row (effectively), and > it shoots up from 5 to 26 columns almost instantly (that's the > internal max I set). Is the scroll bar's repeatinterval set to a reasonable value? -- Russell From grante at visi.com Sat Jan 5 12:28:34 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 05 Jan 2008 17:28:34 -0000 Subject: Question on os.tempnam() vulnerability References: <13nt81gftkfa32d@corp.supernews.com> <13nv5m68qeknk1f@corp.supernews.com> <477FA9B5.9050609@v.loewis.de> <13nvb525r3m6m39@corp.supernews.com> Message-ID: <13nvfi2nu3erpd5@corp.supernews.com> On 2008-01-05, Fredrik Lundh wrote: > Grant Edwards wrote: > >>> IOW, it's the same approach as on Unix. >> >> Not really. Under Unix you can safely create a temp file with >> a name that can be used to open the file. > > Unless I'm missing something, it's not possible to do this in a safe > way in the shared temp directory; you can do that only by creating a > file in a directory that's under full control of your user. Which is what I do. > And *that* approach works on Windows as well, of course. I was asking how to create a named temporary file under Windows without a race condition. I've re-read the tempfile module documentation a couple more times, and it finally dawned on me that I'd been misreading the following statement about tempfiles created by NamedTemporaryFile/mkstemp: "Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later)." I don't know how many times I've read that and missed the phrase "while the named temporary file is still open". I had always read that as saying that the tempfile couldn't be opened a second time under Windows. I know, that would make the availability of the path/name a moot point, but so many things under Windows don't make sense to me that I just let it slide. As Emily Litella used to say: "Oh. That's very different. Never mind." -- Grant Edwards grante Yow! It's hard being at an ARTIST!! visi.com From nanjundi at gmail.com Thu Jan 10 17:06:49 2008 From: nanjundi at gmail.com (Nanjundi) Date: Thu, 10 Jan 2008 14:06:49 -0800 (PST) Subject: Newbie question on Classes References: Message-ID: <8cf64cf7-d38c-4239-b188-b0b861407512@j78g2000hsd.googlegroups.com> On Jan 10, 4:46 pm, "Adrian Wood" wrote: > Hi al! I'm new to the list, and reasonably new to Python, so be gentle. > > Long story short, I'm having a hard time finding a way to call a > function on every object of a class at once. Example: > > I have a class Person, which has a function state(). This prints a > basic string about the Person (position, for example). In the program, > I have created two objects of class Person, called man and woman. > > I can call man.state() and then woman.state() or Person.state(man) and > Person.state(woman) to print the status of each. This takes time and > space however, and becomes unmanageable if we start talking about a > large number of objects, and unworkable if there is an unknown number. > What I'm after is a way to call the status of every instance of Man, > without knowing their exact names or number. > > I've gone through the relevant parts of the online docs, tried to find > information elsewhere online, and looked for code samples, but the > ionformation either isn't there, or just isn't clicking with me. I've > tried tracking the names of each object in a list, and even creating > each object within a list, but don't seem to be able to find the right > syntax to make it all work. > > I'd appreciate anyone who could help, especially if they could include > a short sample. My apologies if I'm not following the etiquette of the > group in some way my making this request. > > Thank you, > Adrian Hi Adrian, One easy way, is to append the objects to a list, as you have mentioned and call the state method in iteration. l = [] l.append(man) l.append(woman) # Print the state. for item in l: print item.state() (If I understood right, man and woman qualifies as "every instance of man") -N From guptaabhishek1983 at gmail.com Tue Jan 29 05:29:30 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Tue, 29 Jan 2008 02:29:30 -0800 (PST) Subject: Error in parsing XML for following test data Message-ID: Hello group, I am having problem parsing following data set from XML. Please provide hints on how to rectify this problem. I am using python2.4 version this is te test data that i am using -- """"""" 1!!!!!!!!!!!!!!!11 2@@@@@@@@@@@@@@@22 3###############33 4$$$$$$$$$$$$$$$44 5%%%%%%%%%%%%%%%55 6^^^^^^^^^^^^^^^66 7&&&&&&&&&&&&&&&77 8***************88 9(((((((((((((((99 10)))))))))))))))00 11----------------- 12================= 13+++++++++++++++++ 14||||||||||||||||| 15\\\\\\\\\\\\\\\\\ 16<<<<<<<<<<<<<<<<< 17>>>>>>>>>>>>>>>>> 18///////////////// 19????????????????? 20;;;;;;;;;;;;;;;;; 21::::::::::::::::: 22''''''''''''''''' 23""""""""""""""""" 24[[[[[[[[[[[[[[[[[ 25]]]]]]]]]]]]]]]]] 26{{{{{{{{{{{{{{{{{ 27}}}}}}}}}}}}}}}}} 28***************** 29+++++++++++++++++ 30----------------- 31````````````````` 32~~~~~~~~~~~~~~~~~ 33................. Special Characters #!/bin/bash #start TG app cd $1 exec ./start-infopsyM.py """"""" This is really a nasty data set. From bernard.chhun at gmail.com Thu Jan 31 16:00:03 2008 From: bernard.chhun at gmail.com (Bernard) Date: Thu, 31 Jan 2008 13:00:03 -0800 (PST) Subject: sending a handmade SOAP request References: <21d3ff54-d20f-45dd-951b-0508682fc472@e6g2000prf.googlegroups.com> Message-ID: <56762aa1-1160-4e4c-b0fa-6f38b455154f@i7g2000prf.googlegroups.com> On 31 jan, 15:23, Van Gale wrote: > Yes, it's quite easy to SOAP by hand. > > I use Oren Tirosh's ElementBuilder class (on top of lxml instead of > ElementTree) to build the SOAP request and the xpath capabilities in lxml > to pull out the data I need from the response. > > http://www.tothink.com/python/ElementBuilder/http://codespeak.net/lxml/ > > An incomplete example for contructing a request looks something like this: > > body = Element('soap:Envelope', > { 'xmlns:soap': nss['soap']}, > Element('soap:Header'), Element('soap:Body', > { 'xmlns:msgs': nss['msgs'] }, > Element('msgs:login', > Element('msgs:passport', > { 'xmlns:core': nss['core'] }, > Element('core:password', password), > Element('core:account', account))))) > > I use httplib2 for sending the HTTP requests: > > http://code.google.com/p/httplib2/ > > Incomplete example: > > headers['SOAPAction'] = action > headers['Content-length'] = str(len(etree.tostring(body))) > response, content = self._client.request( > self.ns_uri, "POST", > body=etree.tostring(body), headers=self._headers) > if response.status == 500 and not \ > (response["content-type"].startswith("text/xml") and \ > len(content) > 0): > raise HTTPError(response.status, content) > if response.status not in (200, 500): > raise HTTPError(response.status, content) > doc = etree.parse(StringIO(content)) > if response.status == 500: > faultstring = doc.findtext(".//faultstring") > raise HTTPError(response.status, faultstring) > > Now it's just a matter of using xpath expressions to dig into the "doc" > structure for the bits you need. oh my that is quite the handy answer Van Gal! I'll try it out right now. thanks a bunch man! From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 2 08:18:09 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 02 Jan 2008 14:18:09 +0100 Subject: wxpython application ( problem ? ) References: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> <5u1asvF1fgr5bU2@mid.uni-berlin.de> <7cb975f6-e9a6-4527-bd84-2041aede197f@j20g2000hsi.googlegroups.com> Message-ID: <5u1h8hF1fkosqU1@mid.individual.net> vedrandekovic at gmail.com wrote: > yes, so what's the problem? http://wxwidgets.org/manuals/stable/wx_wxthreadoverview.html | If you do decide to use threads in your application, it is | strongly recommended that no more than one thread calls GUI | functions. The thread sample shows that it is possible for many | different threads to call GUI functions at once (all the threads | created in the sample access GUI), but it is a very poor design | choice for anything except an example. The design which uses one | GUI thread and several worker threads which communicate with the | main one using events is much more robust and will undoubtedly | save you countless problems (example: under Win32 a thread can | only access GDI objects such as pens, brushes, &c created by | itself and not by the other threads). Regards, Bj?rn -- BOFH excuse #241: _Rosin_ core solder? But... From deets at nospam.web.de Sat Jan 12 16:23:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 12 Jan 2008 22:23:54 +0100 Subject: sqlite3 is it in the python default distro? In-Reply-To: References: Message-ID: <5uspfbF1hkm9bU1@mid.uni-berlin.de> Martin Marcher schrieb: > Hello, > > I can see that sqlite is in the standard lib documentation: > http://docs.python.org/lib/module-sqlite3.html > > however debian and ubuntu (and gentoo according to the packages info) seem > _not_ to include it. > > Now 2 question arise: > > a) Is sqlite included in the python default distribution Yes, since 2.5 > b) In real life can I consider (on linux) that an installation of python > includes the sqlite stuff? distutils is an example of a standard-module that gets ripped out of python by distros frequently, so that people need to install python-dev or such a package. So - yes, it happens that distros don't deliver the whole standard distribution. Now I'm not sure if that happens for sqlite, but if your own tests show so (reminder: python 2.5, accidentially using earlier versions that are installed won't work of course), then the answer is - no, you can't Diez From albert at spenarnc.xs4all.nl Mon Jan 28 04:50:48 2008 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 28 Jan 2008 09:50:48 GMT Subject: Transforming ascii file (pseduo database) into proper database References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> Message-ID: In article <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8 at e32g2000prn.googlegroups.com>, p. wrote: >I need to take a series of ascii files and transform the data >contained therein so that it can be inserted into an existing >database. The ascii files are just a series of lines, each line >containing fields separated by '|' character. Relations amongst the >data in the various files are denoted through an integer identifier, a >pseudo key if you will. Unfortunately, the relations in the ascii file >do not match up with those in the database in which i need to insert >the data, i.e., I need to transform the data from the files before >inserting into the database. Now, this would all be relatively simple >if not for the following fact: The ascii files are each around 800MB, >so pulling everything into memory and matching up the relations before >inserting the data into the database is impossible. In this case good old fashioned batch processing (line by line) may be appropriate. Read up on tools like sort and join. These tools are present on all Unix-like systems, and on windows in open-source toolkits. > >My questions are: >1. Has anyone done anything like this before, and if so, do you have >any advice? Puzzling question. Computers weren't invented for GUI's. They were invented for precisely this kind of thing. So, yes, it is a sure bet. >2. In the abstract, can anyone think of a way of amassing all the >related data for a specific identifier from all the individual files >without pulling all of the files into memory and without having to >repeatedly open, search, and close the files over and over again? As long as you don't use Excell, it is not up to it ;-) Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- like all pyramid schemes -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From pavlovevidence at gmail.com Fri Jan 25 19:48:38 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 25 Jan 2008 16:48:38 -0800 (PST) Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> <87k5lx5v19.fsf@benfinney.id.au> Message-ID: <22c3fd21-2fe3-4893-89f4-b23e1703d083@y5g2000hsf.googlegroups.com> On Jan 25, 6:45 pm, Ben Finney wrote: > "Gabriel Genellina" writes: > > You can also put, in animal/__init__.py: > > from monkey import Monkey > > and now you can refer to it as org.lib.animal.Monkey, but keep the > > implementation of Monkey class and all related stuff into > > .../animal/monkey.py > > This (as far as I can understand) is exactly the solution the original > poster desired to "shoot down", for reasons I still don't understand. Come on, the OP explained it quite clearly in his original post. Did you guys even read it? The module where org.lib.animal.Monkey is actually defined should be an implementation detail of the library, but simply importing Monkey into org.lib.animal doesn't quite make it one. If a user pickles a Monkey class, and then the OP decides to refactor the Monkey class into a new module (say org.lib.animal.primate.monkey), then the user would not be able to unpickle it. Because, you see, pickles record the module a class is defined in. So, now the user has to worry about where Monkey is actually defined. It is not an implementation detail. The solution is to modify the class's __module__ attribute as well as importing it, as I've already pointed out: from org.lib.animal.monkey import Monkey Monkey.__module__ = 'org.lib.animal' This should be enough to satisfy the OP's requirements, at least for classes, without softening the one-to-one module-to-file relationship, or using "hacks". In fact, I'd say this is good practice. Carl Banks From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 10 03:47:28 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 10 Jan 2008 09:47:28 +0100 Subject: Learning Python via a little word frequency program In-Reply-To: <2f65ede2-f491-435b-9a81-20ea7bd3cf5a@k2g2000hse.googlegroups.com> References: 4784bbea$0$17616$426a74cc@news.free.fr <2f65ede2-f491-435b-9a81-20ea7bd3cf5a@k2g2000hse.googlegroups.com> Message-ID: <4785db9a$0$23202$426a34cc@news.free.fr> Paul Hankin a ?crit : > On Jan 9, 12:19 pm, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Andrew Savige a ?crit : >>> and the -x hack above to >>> achieve a descending sort feels a bit odd to me, though I couldn't think >>> of a better way to do it. >> The "other" way would be to pass a custom comparison callback to sort, >> which would be both slower and more complicated. Your solution is IMHO >> the right thing to do here. > > Both list.sort and sorted have a parameter 'reverse' which does a > descending rather than ascending sort. Yes. But here the specs says that sort must be descending on first key (frequency) and ascending on the second (name), so you can't just use reverse sort. FWIW, a correct (and readable) solution - based on the 'key' param - has been given by Peter Otten, but it still requires a callback function, so while it avoids the '-x hack', it's still more expensive than a plain sort. From fredrik at pythonware.com Fri Jan 11 06:20:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jan 2008 12:20:50 +0100 Subject: Property with Arguments In-Reply-To: <3b8f3359-2889-42d5-9a5f-db2ee4268e8c@l1g2000hsa.googlegroups.com> References: <3b8f3359-2889-42d5-9a5f-db2ee4268e8c@l1g2000hsa.googlegroups.com> Message-ID: Lie wrote: > Is there a way to create a property with arguments? That's called method in Python, and has it's own syntax. You cannot assign to methods. > Or an index value like a list? Make the property that returns a list-like object (hooking __getitem__, __setitem__, etc). From Matthew_WARREN at bnpparibas.com Thu Jan 31 13:06:13 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Thu, 31 Jan 2008 18:06:13 +0000 Subject: Fw: Undeliverable Message In-Reply-To: Message-ID: > Heres the code > > def increment(digits,symbols): > ? ? ? ? overflow=True > ? ? ? ? digitpos=-1 > ? ? ? ? while overflow and -digitpos<=len(digits): > ? ? ? ? ? ? ? ? digitsymbolindex=symbols.index(digits[digitpos]) > ? ? ? ? ? ? ? ? if digitsymbolindex==len(symbols)-1: > ? ? ? ? ? ? ? ? ? ? ? ? overflow=True > ? ? ? ? ? ? ? ? ? ? ? ? digits[digitpos]=symbols[0] > ? ? ? ? ? ? ? ? ? ? ? ? digitpos=digitpos-1 > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? digits[digitpos]=symbols[digitsymbolindex+1] > ? ? ? ? ? ? ? ? ? ? ? ? overflow=False > ? ? ? ? return digits > > Now, this works. All good. It's nice and simple. ?I'm just wondering how > anyone else might approach it? >I (not an expert at all) have only minor comments and one question: >comments: >why keep setting overflow to True, if you do not touch it will not >change. good point. >digitpos -= 1 is easier to read in my mind it's just something ive done for years, so I read it perfectly fine. It's cause I was programming for ages before I first ever saw -= or += (bbc basic didnt have 'em ;P) >question: >Why first extract the indices and then compare (in your if statement), >and >why do you not just compare the symbols? I put the index into digitsymbolindex because it is used in more than one place in the code, and I'd rather have the result stored than recompute it possibly twice. have fun! Matt. -- 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 steve at REMOVE-THIS-cybersource.com.au Wed Jan 16 17:01:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Jan 2008 22:01:05 -0000 Subject: Creating unique combinations from lists References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> Message-ID: <13osvl1j4pvka15@corp.supernews.com> On Wed, 16 Jan 2008 11:15:16 -0800, breal wrote: > I could do nested for ... in loops, but was looking for a Pythonic way > to do this. Ideas? What makes you think nested loops aren't Pythonic? -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Jan 21 07:52:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 12:52:23 -0000 Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> <479451D9.3060207@block.duxieweb.com> Message-ID: <13p95c78aeitf55@corp.supernews.com> On Mon, 21 Jan 2008 17:32:42 +0800, J. Peng wrote: > Steven D'Aprano ??: >> On Mon, 21 Jan 2008 16:23:50 +0800, J. Peng wrote: >> >>> J. Peng ??: >>> >>>> k = (i.split())[3] >>>> y = (i.split())[1] >>> btw, why can't I write the above two into one statement? >>> >>> (k,y) = (i.split())[3,1] >> >> I don't know. What's "i"? >> >> I'm guessing "i" is a string (and what a horrible choice of a name for >> a string!) So i.split() will return a list. List indexing with multiple >> arguments isn't defined, which is why you can't write >> >> k, y = (i.split())[3,1] >> >> > Thanks. > Then one have to split the list twice.Given the list is large,it's maybe > not good for performance.Is it a more effective split way? Yes, split the string once and store it. words = "Nobody expects the Spanish Inquisition!" alist = words.split() k = alist[3] # "Spanish" y = alist[1] # "expects" -- Steven From haraldarminmassa at gmail.com Tue Jan 22 09:12:40 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Tue, 22 Jan 2008 06:12:40 -0800 (PST) Subject: building psycopg2 on windows using mingw, "cannot find -lpq" References: <5vk1sqF1mal8qU1@mid.uni-berlin.de> Message-ID: <42089805-0751-4ff9-a567-6b302c739077@h11g2000prf.googlegroups.com> > > The compile works, BUT linking fails: > > > 2.5\Release\psycopg\_psycopg.def -Lc:\python25\libs -Lc: > > \python25\PCBuild -Lc:/p > > ostgres/83RC2/lib -lpython25 -lpq -lws2_32 -ladvapi32 -o build > > > ?-Lc:/postgres/83RC2/lib > > Are you sure using forward slashes in the path works here? Not at all. But that commandline is generated by setup.py, not by me : ( and setup.py extracts the paths from pg_config so: I have no idea how to make it use backslash :( Thanks for the idea, Harald From martin at v.loewis.de Sun Jan 13 12:02:00 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 13 Jan 2008 18:02:00 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801131550.50119.donn.ingle@gmail.com> References: <200801131427.54672.donn.ingle@gmail.com> <478A0F5D.3030906@v.loewis.de> <200801131550.50119.donn.ingle@gmail.com> Message-ID: <478A4408.2090805@v.loewis.de> > Could it not be that the app doing the output (say konsole) could be > displaying a filename as best as it can (doing the ignore/replace) trick and > using whatever fonts it can reach) and this would disguise the situation? No. It may use replacement characters (i.e. a question mark, or an empty square box), but if you don't see such characters, then the terminal has successfully decoded the file names. Whether it also correctly decoded them is something for you to check (i.e. do they look right?) > I have been looking for somewhere online that I can download files obviously > in a non-ascii set (like japan someplace) but can't find anything easy. I > want to see exactly how my system (Kubuntu 7.10) handles things. So what does sys.getfilesystemencoding() say what encoding is used for filenames? Regards, Martin From srikrishnamohan at gmail.com Wed Jan 2 05:09:45 2008 From: srikrishnamohan at gmail.com (km) Date: Wed, 2 Jan 2008 15:39:45 +0530 Subject: Python Trajectory Module? In-Reply-To: <477AD5E8.3060007@gmail.com> References: <8ec8091e-8670-4d04-8198-c688c14576cf@p69g2000hsa.googlegroups.com> <477AD5E8.3060007@gmail.com> Message-ID: Hi have a look at these demos (includes trajectory etc) with VPython http://showmedo.com/videos/series?name=pythonThompsonVPythonSeries best wishes, KM ------------------------------------------------------------------------------------------------------------------------------ On Jan 2, 2008 5:38 AM, Stef Mientki wrote: > squishywaffle at gmail.com wrote: > > Greetings, > > > > I was wondering if there was a python Module/Library out there that > > handles some trajectory/physics stuff like moving an object along a > > straight path in an X,Y 2D (or 3D) plane or calculating parabolic > > arcs. I'd really settle for just the moving of an object along a > > straight line. > > > > I know it's not terribly difficult to implement this on your own, but > > I'd rather not re-invent the wheel if someone else already did a good > > job of it the first time. > > > > Thanks! > > > Depends on how detailed / graphical you've in mind. > You might be interested in this: > > > http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_animations_screenshots.html > > I've put a scanned version of my written notes about the trajectory > example. > No need for ODE in my very simple mind, because the functions describing > the solution are already known. > > If you want to view the demos / animations, > be sure to view the demo at the bottom first, > because it explains the philosophy behind the program. > Only 1 major feature is not described in this demo (because when I made > the demo I had no solution for it, now I think I have) > and that is : > an integrated help / instruction / assignment / fill-in forms / > judgement, specially for educational puposes. > > The program is not yet released, > because I'm now cleaning it up and debugging it (by making demos ;-) > cheers, > Stef > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nodrogbrown at gmail.com Mon Jan 21 01:07:31 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Sun, 20 Jan 2008 22:07:31 -0800 (PST) Subject: newbie doubt ..numpy array Message-ID: if this is too silly a qn pls forgive I was learning numpy.ndarrays thru the tutorial. myarr=numpy.array( [ [10, 20, 30, 40],[1,2,3,4],[5,6,7,8] ] ) if i want to access the element 3 i can do it by myarr[1, 2] but then myarr[1][2] will also give the same result..is there any reason why two types of indexing is allowed? gordon p.s(i tried to post to numpy grp but it is not appearing there!) From phd at phd.pp.ru Thu Jan 10 07:26:47 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 10 Jan 2008 15:26:47 +0300 Subject: SQLObject 0.7.10 Message-ID: <20080110122647.GB3070@phd.pp.ru> Hello! I'm pleased to announce the 0.7.10 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.10 News and changes: http://sqlobject.org/docs/News.html What's New ========== News since 0.7.9 ---------------- * With PySQLite2 do not use encode()/decode() from PySQLite1 - always use base64 for BLOBs. * MySQLConnection doesn't convert query strings to unicode (but allows to pass unicode query strings if the user build ones). DB URI parameter sqlobject_encoding is no longer used. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From paul.hankin at gmail.com Sat Jan 5 05:37:53 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 5 Jan 2008 02:37:53 -0800 (PST) Subject: Basic inheritance question References: Message-ID: On Jan 5, 10:31?am, MartinRineh... at gmail.com wrote: > ... > class code: > ? ? def __init__( self, start, stop ): > ? ? ? ? startLoc = start > ? ? ? ? stopLoc = stop > ... You've forgotten the explicit self. def __init__( self, start, stop ): self.startLoc = start self.stopLoc = stop -- Paul Hankin From rw at smsnet.pl Thu Jan 3 14:13:18 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 03 Jan 2008 20:13:18 +0100 Subject: urllib2 disable proxy References: <878x373o6c.fsf@merkury.smsnet.pl> Message-ID: <87odc2hgdt.fsf@merkury.smsnet.pl> Dimitrios Apostolou writes: > On Wed, 2 Jan 2008, Rob Wolfe wrote: > >> Dimitrios Apostolou writes: >> >>> Hello list, >>> >>> I've been looking for a way to explicitly disable the use of proxies with >>> urllib2, no matter what the environment dictates. Unfortunately I can't find >>> a way in the documentation, and reading the source leads me to believe that >>> something like the following does the job: >>> >>> req.set_proxy(None,None) >>> >>> Where req is a urllib2.Request instance. So is there an official way of doing >>> this? Perhaps it should be added in the documentation? >> >> I believe that the recommended way is to use `urllib2.ProxyHandler`. >> Take a look at: >> http://www.voidspace.org.uk/python/articles/urllib2.shtml > > Thanks for the pointer, I will use that way. However it seems rather > non-elegant way to do something so simple and I was hoping not to mess > with ProxyHandler, especially since I want *no* proxy... IMHO > something like the following would be more elegant: > > req.set_proxy('','http') > > or > > req.set_proxy(None,'http') > > > However these ways *don't* work. You think I should file a feature > request somewhere or send this to the python-dev list? Actually, I like this idea of handlers and openers and find it simple and _elegant_, so I can't second that request. Besides disabling proxies despite environmental settings is a special case, so imho using `instal_opener` is justified. Regards, Rob From paddy3118 at netscape.net Wed Jan 9 15:28:33 2008 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Wed, 09 Jan 2008 20:28:33 GMT Subject: alternating string replace: Extended input (Long). In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: cesco wrote: I created some more test strings and ran posters solutions against them. results attached. - Paddy. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: alternating_replacements.py URL: From martin at v.loewis.de Wed Jan 2 15:48:30 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Jan 2008 21:48:30 +0100 Subject: different encodings for unicode() and u''.encode(), bug? In-Reply-To: <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> Message-ID: <477BF89E.1010906@v.loewis.de> > Do not know what the implications of encoding according to "ANSI > codepage (CP_ACP)" are. Windows only seems clear, but why does it only > complain when decoding a non-empty string (or when encoding the empty > unicode string) ? It has no implications for this issue here. CP_ACP is a Microsoft invention of a specific encoding alias - the "ANSI code page" (as Microsoft calls it) is not a specific encoding where I could specify a mapping from bytes to characters, but instead a system-global indirection based on a langage default. For example, in the Western-European/U.S. version of Windows, the default for CP_ACP is cp1252 (local installation may change that default, system-wide). The issue likely has the cause that Piet also guessed: If the input is an empty string, no attempt to actually perform an encoding is done, but the output is assumed to be an empty string again. This is correct behavior for all codecs that Python supports in its default installation, at least for the direction bytes->unicode. For the reverse direction, such an optimization would be incorrect; consider u"".encode("utf-16"). HTH, Martin From hniksic at xemacs.org Thu Jan 17 10:45:01 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 17 Jan 2008 16:45:01 +0100 Subject: Is this a bug, or is it me? References: Message-ID: <87ir1so3r6.fsf@mulj.homelinux.net> cptnwillard at gmail.com writes: > Hello all, > For some reason, the following does not work : > > > class C: > TYPES = [None] > DICT = {} > for Type in TYPES: > DICT.update((E,Type) for E in [1]) > >>>> NameError: global name 'Type' is not defined > > > What do you think? Is this a bug? It works if you change the generator expression to a list comprehension, by adding [] around it. Feels like a bug to me, but there might be subtleties involved. From vriolk at gmail.com Tue Jan 15 14:43:54 2008 From: vriolk at gmail.com (coldpizza) Date: Tue, 15 Jan 2008 11:43:54 -0800 (PST) Subject: UTF-8 in basic CGI mode Message-ID: <241b96e8-8ea3-41c5-954f-4d47619baa18@d21g2000prf.googlegroups.com> Hi, I have a basic Python CGI web form that shows data from a SQLite3 database. It runs under the built-in CGIWebserver which looks like this: [code] import SimpleHTTPServer import SocketServer SocketServer.TCPServer(("", 80),SimpleHTTPServer.SimpleHTTPRequestHandler).serve_forever() [/code] The script runs Ok with ANSI characters, but when I try to process non- ASCII data I get an UnicodeDecodeError exception ('ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)). I have added the the 'u' prefix to all my literal strings, and I _have_ wrapped all my output statements into myString.encode('utf8', "replace"), but, apparently the UnicodeDecodeError exception occurs because of a string that I get back to the script through cgi.FieldStorage( ). I.e. I have the lines: form = cgi.FieldStorage( ) word= form['word'] which retrieve the 'word' value from a GET request. I am using this 'word' variable like this: print u'''''' % (word) and apparently this causes exceptions with non-ASCII strings. I've also tried this: print u'''''' % (word.encode('utf8')) but I still get the same UnicodeDecodeError.. What is the general good practice for working with UTF8? The standard Python CGI documentation has nothing on character sets. It looks insane to have to explicitly wrap every string with .encode('utf8'), but even this does not work. Could the problem be related to the encoding of the string returned by the cgi.fieldstorage()? My page is using UTF-8 encoding. What would be encoding for the data that comes from the browser after the form is submitted? Why does Python always try to use 'ascii'? I have checked all my strings and they are prefixed with 'u'. I have also tried replacing print statements with sys.stdout.write (DATA.encode('utf8')) but this did not help. Any clues? Thanks in advance. From joemystery123 at gmail.com Tue Jan 1 14:24:04 2008 From: joemystery123 at gmail.com (crybaby) Date: Tue, 1 Jan 2008 11:24:04 -0800 (PST) Subject: pexpect ssh login and ls | grep References: <3eb81375-3e4a-4e0f-a4e7-bbb1d6cd0f8c@s19g2000prg.googlegroups.com> <477a6eec$0$17448$bf4948fe@news.tele2.nl> <1c62b205-e2dd-4bb9-ac99-e14ce652afab@21g2000hsj.googlegroups.com> Message-ID: I did try to excute the ssh and shell ls grep command in all in one like so: ssh my at mycomp2 "ls mytest.log > /dev/null 2>&1; echo $?" This seem to work, but also throwing exceptions. Also, including ssh and shell command together would be a problem when I later add a pass phrase to ssh key. Can someone provide little insight on this? >>> import pexpect >>> child=pexpect.spawn('ssh my at mycomp2 "ls mytest.log > /dev/null 2>&1; echo $?"') >>> >>> child.expect([pexpect.TIMEOUT, '\$']) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/pexpect.py", line 1064, in expect return self.expect_list(compiled_pattern_list, timeout, searchwindowsize) File "/usr/lib/python2.4/site-packages/pexpect.py", line 1132, in expect_list raise EOF (str(e) + '\n' + str(self)) pexpect.EOF: End Of File (EOF) in read_nonblocking(). Exception style platform. version: 2.1 ($Revision: 395 $) command: /usr/bin/ssh args: ['/usr/bin/ssh', 'my at mycomp2', 'ls mytest.log > /dev/null 2>&1; echo $?'] patterns: pexpect.TIMEOUT \$ buffer (last 100 chars): before (last 100 chars): 0 after: pexpect.EOF match: None match_index: None exitstatus: 0 flag_eof: True pid: 3524 child_fd: 3 closed: False timeout: 30 delimiter: pexpect.EOF logfile: None maxread: 2000 ignorecase: False searchwindowsize: None delaybeforesend: 0.1 delayafterclose: 0.1 delayafterterminate: 0.1 >>> >>> result=child.before >>> result2=child.after >>> print result 0 >>> print result2 pexpect.EOF From goon12 at gmail.com Tue Jan 29 14:21:01 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 29 Jan 2008 14:21:01 -0500 Subject: noob stuck on reading double In-Reply-To: <6a2ccd190801291102m457f1fb9odca04ef24fb47ac3@mail.gmail.com> References: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk> <6a2ccd190801291059q1a18c70co8e9db881c6994f63@mail.gmail.com> <6a2ccd190801291102m457f1fb9odca04ef24fb47ac3@mail.gmail.com> Message-ID: <6a2ccd190801291121p68ba4c7bode9cd5831eca60d2@mail.gmail.com> Since you're unpacking it with the 'd' format character I am assuming a "doubleword" field is a double. You said you had 113 of them in the binary file. You should be doing something like this: file = open('data.bin', 'rb') file.seek(0) raw = file.read() unpacked = unpack('113d', raw) for i in range(0,113): print unpacked[i] file.close() From kyosohma at gmail.com Wed Jan 9 16:57:00 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 9 Jan 2008 13:57:00 -0800 (PST) Subject: getting absolute path ? References: Message-ID: On Jan 9, 3:22 pm, Stef Mientki wrote: > hello, > > I'm trying to convert the links in html pages to absolute links, > these pages can either be webpages or files on local harddisk (winXP). > Now I've struggling for a while, and this code works a lilttle: > > i = line.find ( 'href=' ) > if i < 0 : > i = line.find ( ' src=' ) > if i >= 0 : > ii = line.find ( '"', i+6 ) > file = line [ i+6 : ii ] > #print urlparse.urljoin ( p, file ) > if file.find ( 'http:' ) < 0 : > abspath = os.path.normpath ( os.path.join ( p, file ) ) > line = line.replace ( file, abspath ) > print line > > but it only covers files on local disk and just 1 link per line, > so I guess it's a lot of trouble to catch all cases. > Isn't there a convenient function for (OS independent preferable) ? > Googled for it, but can't find it. > > thanks, > Stef Mientki I googled a bit too. The Perl forums talk about using a regular expression. You can probably take that and translate it into the Python equivalent: http://forums.devshed.com/perl-programming-6/how-to-parse-relatives-links-to-absolute-links-8173.html I also found this, which appears to be an old c.l.py thread: http://www.dbforums.com/archive/index.php/t-320359.html You might have more luck if you google for "relative to absolute links". I would also take a look at how django or cherrypy creates their URLs. Mike From booboo at gforcecable.com Wed Jan 9 06:43:38 2008 From: booboo at gforcecable.com (Tom La Bone) Date: Wed, 9 Jan 2008 03:43:38 -0800 (PST) Subject: Update of Gnuplot.py Message-ID: <14710180.post@talk.nabble.com> Can someone suggest where to get a version of Gnuplot.py (for Windows) that has been updated to use numpy? Or, is there another interface available to use GnuPlot from Python? Thanks. Tom -- View this message in context: http://www.nabble.com/Update-of-Gnuplot.py-tp14710180p14710180.html Sent from the Python - python-list mailing list archive at Nabble.com. From michele.simionato at gmail.com Fri Jan 4 10:23:26 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 4 Jan 2008 07:23:26 -0800 (PST) Subject: python interfaces References: Message-ID: On Jan 4, 3:59 pm, hyperboreean wrote: > Hi, > Probably it has been asked before, but I'll still ask. > Why doesn't python provide interfaces trough its standard library? Or it > was ever proposed to be included in the language? > Zope's implementation seems pretty flexible and straightforward. > > Thanks. Python 3.0 will introduce Abstract Base Classes: http://www.python.org/dev/peps/pep-3119/ From asmodai at in-nomine.org Wed Jan 2 12:48:21 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 2 Jan 2008 18:48:21 +0100 Subject: XML-XSD Processing/Creation. In-Reply-To: References: Message-ID: <20080102174821.GF67953@nexus.in-nomine.org> -On [20080102 18:21], xkenneth (xkenneth at gmail.com) wrote: > So i'm working with the WITSML standard, which is a pretty >massive standard defined in XML for the transfer of oilfield data. I cannot answer (yet) the question of generating XML data from an XSD. But for writing out XML files I like to use either ElementTree or lxml. Very easy and straightforward use of XML from Python in my opinion. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Once sent from the Golden Hall... From Russ.Paielli at gmail.com Thu Jan 10 03:04:25 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 10 Jan 2008 00:04:25 -0800 (PST) Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: On Jan 9, 11:51 pm, Fredrik Lundh wrote: > Steve Brown wrote: > > I've got a series of modules which look like this: > > > #************ > > # > > # Temperature Sense Test > > # > > #************ > > class Test3(ar_test.AR_TEST): > > """Temperature Sense Test""" > > > I don't like the duplicated information: But the comment is attractive, and > > the docstring self.__doc__ is already in use in the test log. I've read that > > all modules and classes should have docstrings, but I don't really have > > anything else to say, and each module contains only one class. I don't think > > that > > > """Temperature Sense Test""" > > class Test3(ar_test.AR_TEST): > > """Temperature Sense Test""" > > > would be a real improvement. > > > What do you think? > > since you already seem to cater to your audience (clearly marked > comments for people browsing the code, brief docstrings for the test > log), I don't really see why you should change anything. > > > I've read that all modules and classes should have docstrings > > if nobody's going to read them, there's no reason to add them. don't > treat generic style advice as dogma. > > Well, trivial modules certainly don't need much documentation, but he didn't say they were trivial. I assumed there was more to them then he showed. From zbigniew.braniecki at gmail.com Fri Jan 18 12:09:47 2008 From: zbigniew.braniecki at gmail.com (Zbigniew Braniecki) Date: Fri, 18 Jan 2008 18:09:47 +0100 Subject: Bug in __init__? Message-ID: I found a bug in my code today, and spent an hour trying to locate it and then minimize the testcase. Once I did it, I'm still confused about the behavior and I could not find any reference to this behavior in docs. testcase: class A(): def add (self, el): self.lst.extend(el) def __init__ (self, val=[]): print val self.lst = val def test (): x = A() x.add(["foo1","foo2"]) b = A() So, what I would expect here is that I will create two instances of class A with empty self.lst property. Right? In fact (at least with my Python 2.5) gandalf at gandalf-desktop:~/projects/pyl10n$ ./scripts/test.py [] ['foo1', 'foo2'] This bug does not happen when I switch to __init__ (self, *args) and assign self.lst= args[0]. Any clue on what's going on here, and/if where I should report it? Greetings Zbigniew Braniecki From ganesh.borse at credit-suisse.com Thu Jan 10 20:31:26 2008 From: ganesh.borse at credit-suisse.com (Borse, Ganesh) Date: Fri, 11 Jan 2008 09:31:26 +0800 Subject: PyImport_ImportModule("cStringIO") failure with undefined symbol Message-ID: Hi, Can you please guide me for the following problem? The call to "PyImport_ImportModule("cStringIO");" is failing with an error of "undefined symbol: PyObject_SelfIter". Before importing this module, I am importing only the sys module. Py_SetProgramName("/usr/bin/python"); Py_Initialize(); char* argv[] = { "python","-v",""}; PySys_SetArgv(2,argv); PyRun_SimpleString("import sys"); PyObject *modStringIO = NULL; // Import cStringIO module modStringIO = PyImport_ImportModule("cStringIO"); Should I be importing any other additional module(s) to make this import work? Please help. I am trying to use the function GetPythonErrorMessage provided in this post: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9212ebc42e8438a7/f0bd5f5b15902b14?lnk=gst&q=PyErr_Print#f0bd5f5b15902b14 Thanks in advance for your help. Regards. ============================================================================== Please access the attached hyperlink for an important electronic communications disclaimer: http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html ============================================================================== From donn.ingle at gmail.com Sun Jan 13 05:24:10 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 12:24:10 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <4789D98A.80609@v.loewis.de> References: <200801130930.07852.donn.ingle@gmail.com> <4789D98A.80609@v.loewis.de> Message-ID: <200801131224.10263.donn.ingle@gmail.com> Martin, Thanks, food for thought indeed. > On Unix, yes. On Windows, NTFS and VFAT represent file names as Unicode > strings always, independent of locale. POSIX file names are byte > strings, and there isn't any good support for recording what their > encoding is. I get my filenames from two sources: 1. A wxPython treeview control (unicode build) 2. os.listdir() with a unicode path passed to it I have found that os.listdir() does not always return unicode objects when passed a unicode path. Sometimes "byte strings" are returned in the list, mixed-in with unicodes. I will try the technique given on:http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html#guessing-the-encoding Perhaps that will help. Re os.listdir(): > If you think you may have file names with mixed locales, and > the current locale might not match the file name's locale, you should > be using the byte string variant on Unix (which it seems you are already > doing). I gather you mean that I should get a unicode path, encode it to a byte string and then pass that to os.listdir Then, I suppose, I will have to decode each resulting byte string (via the detect routines mentioned in the link above) back into unicode - passing those I simply cannot interpret. > Then, if the locale's encoding cannot decode the file names, you have > several options > a) don't try to interpret the file names as character strings, i.e. > don't decode them. Not sure why you need the file names - if it's > only to open the files, and never to present the file name to the > user, not decoding them might be feasible So, you reckon I should stick to byte-strings for the low-level file open stuff? It's a little complicated by my using Python Imaging to access the font files. It hands it all over to Freetype and really leaves my sphere of savvy. I'll do some testing with PIL and byte-string filenames. I wish my memory was better, I'm pretty sure I've been down that road and all my results kept pushing me to stick to unicode objects as far as possible. > b) guess an encoding. For file names on Linux, UTF-8 is fairly common, > so it might be a reasonable guess. > c) accept lossy decoding, i.e. decode with some encoding, and use > "replace" as the error handler. You'll have to preserve the original > file names along with the decoded versions if you later also want to > operate on the original file. Okay, I'm getting your drift. > That's not true. Try open("\xff","w"), then try interpreting the file > name as UTF-8. Some byte strings are not meaningful UTF-8, hence that > approach cannot work. Okay. > That's correct, and there is no solution (not in Python, not in any > other programming language). You have to made trade-offs. For that, > you need to analyze precisely what your requirements are. I would say the requirements are: 1. To open font files from any source (locale.) 2. To display their filename on the gui and the console. 3. To fetch some text meta-info (family etc.) via PIL/Freetype and display same. 4. To write the path and filename to text files. 5. To make soft links (path + filename) to another path. So, there's a lot of unicode + unicode and os.path.join and so forth going on. > > I went through this exercise recently and had no joy. It seems the string > > I chose to use simply would not render - even under 'ignore' and > > 'replace'. > I don't understand what "would not render" means. I meant it would not print the name, but constantly throws ascii related errors. I don't know if the character will survive this email, but the text I was trying to display (under LANG=C) in a python script (not the immediate-mode interpreter) was: "M?gul". The second character is a capital O with an umlaut (double-dots I think) above it. For some reason I could not get that to display as "M?gul" or "Mgul". BTW, I just made that up - it means nothing (to me). I hope it's not a swear word in some other language :) > As for font files - I don't know what encoding the family is in, but > I would sure hope that the format specification of the font file format > would also specify what the encoding for the family name is, or that > there are at least established conventions. You'd think. It turns out that font file are anything but simple. I am doing my best to avoid being sucked-into the black hole of complexity they represent. I must stick to what PIL/Freetype can do. The internals of font-files are waaaaaay over my head. > >> I would avoid locale.getlocale. It's a pointless function (IMO). > As a consequence, it will return None if it doesn't know better. > If all you want is the charset of the locale, use > locale.getpreferredencoding(). Brilliant summary - thanks a lot for that. > You could just leave out the languages parameter, and trust gettext > to find some message catalog. Right - I'll give that a go. > > This would mean cutting-out a percentage of the external font files that > > can be used by the app. > See above. There are other ways to trade-off. Alternatively, you could > require that the program finds a richer locale, and bail out if the > locale is just "C". That's kind of what the OP is all about. If I make this a 'design decision' then it means I have a problem with the Debian packaging (and RPM?) rules that require a "C" locale support. I think I shall have to break the links between my setup.py and the rest of my app - so that setup.py will allow LANG=C but the app (when run) will not. > That doesn't help. For Turkish in particular, the UTF-8 locale is worse > than the ISO-8859-9 locale, as the lowercase I takes two bytes in UTF-8, > so tolower can't really work in the UTF-8 locale (but can in the > ISO-8859-9 locale). Wow. I still get cold chills -- but I assume that once the right encoding is known this sort of thing will be okay. Thanks again. It's coming together slowly. \d From vriolk at gmail.com Tue Jan 15 15:42:21 2008 From: vriolk at gmail.com (coldpizza) Date: Tue, 15 Jan 2008 12:42:21 -0800 (PST) Subject: UTF-8 in basic CGI mode Message-ID: <1f8a4051-27cb-48aa-a0ab-793f59ab3845@s13g2000prd.googlegroups.com> Hi, I have a basic Python CGI web form that shows data from a SQLite3 database. It runs under the built-in CGIWebserver which looks something like this: [code] from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler HTTPServer("8000", CGIHTTPRequestHandler).serve_forever( ) [/code] The script runs Ok with ANSI characters, but when I try to process non- ASCII data I get an UnicodeDecodeError exception ('ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)). I have added the the 'u' prefix to all my literal strings, and I _have_ wrapped all my output statements into myString.encode('utf8', "replace"), but, apparently the UnicodeDecodeError exception occurs because of a string that I get back to the script through cgi.FieldStorage( ). I.e. I have the lines: form = cgi.FieldStorage( ) word= form['word'] which retrieve the 'word' value from a GET request. I am using this 'word' variable like this: print u'''''' % (word) and apparently this causes exceptions with non-ASCII strings. I've also tried this: print u'''''' % (word.encode('utf8')) but I still get the same UnicodeDecodeError.. What is the general good practice for working with UTF8? The standard Python CGI documentation has nothing on character sets. It looks insane to have to explicitly wrap every string with .encode('utf8'), but even this does not work. Could the problem be related to the encoding of the string returned by the cgi.fieldstorage()? My page is using UTF-8 encoding. What would be encoding for the data that comes from the browser after the form is submitted? Why does Python always try to use 'ascii'? I have checked all my strings and they are prefixed with 'u'. I have also tried replacing print statements with sys.stdout.write (DATA.encode('utf8')) but this did not help. Any clues? From ruoyu0088 at gmail.com Fri Jan 11 04:52:16 2008 From: ruoyu0088 at gmail.com (HYRY) Date: Fri, 11 Jan 2008 01:52:16 -0800 (PST) Subject: python recursive function References: Message-ID: <01c6fa55-3836-4d92-aaf4-02fec7fa529c@l6g2000prm.googlegroups.com> > def bears (n): > if n==42: > return True > if n%5==0: > bears(n-42) > if n%2==0: > bears(n/2) > if n%3==0 or n%4==0: > one = (n%10) > two = ((n%100)/10) > if one!=0 and two!=0: > bears(n-(one*two)) > return False > > If a game hits 42 it should return True, otherwise False. If program > never hits 42 and return True, then it returns False. I figured out > base case, but I still get False when I enter bears(250). Any help > would be very appreciated! try this: def bears (n): if n==42: return True if n%5==0: if bears(n-42): return True if n%2==0: if bears(n/2): return True if n%3==0 or n%4==0: one = (n%10) two = ((n%100)/10) if one!=0 and two!=0: if bears(n-(one*two)): return True return False print bears(42) print bears(250) print bears(50) print bears(84) print bears(41) From fredrik at pythonware.com Fri Jan 4 09:00:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 15:00:44 +0100 Subject: Strange varargs issue In-Reply-To: References: Message-ID: Mike wrote: > __f.func(a) > TypeError: func() takes exactly 1 argument (2 given) > > How can this possibly be? The "caller" print statement obviously > shows "a" is singular. __f.func(a) is a method call, and methods always get the object itself as an extra initial argument. to fix this, add "self" to the method signature: class foobar(object): def func(self, arg): print 'foobar.func: %r' % arg see the tutorial for more info. > I'm not sure if this is a bug or if I'm just not understanding > something correctly. you are aware that blaming your mistakes on bugs in widely used code is somewhat rude, right? http://www.catb.org/~esr/faqs/smart-questions.html#id306617 From rong.xian at gmail.com Sun Jan 27 08:49:58 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 05:49:58 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <5vr1ekF1njt09U2@mid.uni-berlin.de> <84f39f37-4d18-47c1-9349-bf3f471b2bf5@s19g2000prg.googlegroups.com> <19efc1d4-d77d-4855-9647-7a4782b064eb@d21g2000prg.googlegroups.com> Message-ID: <1d551606-336a-4956-b7d6-71a3009aea09@y5g2000hsf.googlegroups.com> On 1?27?, ??7?04?, John Machin wrote: > On Jan 27, 9:18 pm, glacier wrote: > > > > > > > On 1?24?, ??4?44?, Marc 'BlackJack' Rintsch wrote: > > > > On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote: > > > > My second question is: is there any one who has tested very long mbcs > > > > decode? I tried to decode a long(20+MB) xml yesterday, which turns out > > > > to be very strange and cause SAX fail to parse the decoded string. > > > > That's because SAX wants bytes, not a decoded string. Don't decode it > > > yourself. > > > > > However, I use another text editor to convert the file to utf-8 and > > > > SAX will parse the content successfully. > > > > Because now you feed SAX with bytes instead of a unicode string. > > > > Ciao, > > > Marc 'BlackJack' Rintsch > > > Yepp. I feed SAX with the unicode string since SAX didn't support my > > encoding system(GBK). > > Let's go back to the beginning. What is "SAX"? Show us exactly what > command or code you used. > SAX is the package 'xml.sax' distributed with Python 2.5:) 1,I read text from a GBK encoded XML file then I skip the first line declare the encoding. 2,I converted the string to uncode by call decode('mbcs') 3,I used xml.sax.parseString to parse the string. ######################################################################## f = file('e:/temp/456.xml','rb') s = f.read() f.close() n = 0 for i in xrange(len(s)): if s[i]=='\n': n += 1 if n == 1: s = s[i+1:] break s = ''+s+'' s = s.decode('mbcs') xml.sax.parseString(s,handler,handler) ######################################################################## > How did you let this SAX know that the file was encoded in GBK? An > argument to SAX? An encoding declaration in the first few lines of the > file? Some other method? ... precise answer please. Or did you expect > that this SAX would guess correctly what the encoding was without > being told? I didn't tell the SAX the file is encoded in GBK since I used the 'parseString' method. > > What does "didn't support my encoding system" mean? Have you actually > tried pushing raw undecoded GBK at SAX using a suitable documented > method of telling SAX that the file is in fact encoded in GBK? If so, > what was the error message that you got? I mean SAX only support a limited number of encoding such as utf-8 utf-16 etc.,which didn't include GBK. > > How do you know that it's GBK, anyway? Have you considered these > possible scenarios: > (1) It's GBK but you are telling SAX that it's GB2312 > (2) It's GB18030 but you are telling SAX it's GBK > Frankly speaking, I cannot tell if the file contains any GB18030 characters...^______^ > HTH, > John- ??????? - > > - ??????? - From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 10 03:37:57 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 10 Jan 2008 09:37:57 +0100 Subject: Python too slow? In-Reply-To: <13oattm5ijqvf58@corp.supernews.com> References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> Message-ID: <4785d960$0$22237$426a74cc@news.free.fr> Ed Jensen a ?crit : > Bruno Desthuilliers wrote: >> And the reference implementation of Python (CPython) is not >> interpreted, it's compiled to byte-code, which is then executed by a VM >> (just like Java). > > Wow, this is pretty misleading. Ho yes ??? Why so, please ? Care to point to anything *wrong* in the above statement ? > Java is, indeed, compiled to bytecode; however, modern JVMs typically > compile the bytecode to native code and then execute the native code. Which is known as JIT compilation - and there are a couple attempts at it in Python too. Anyway, the JIT compiler is not part of the Java spec (while the byte-code/VM is), and its not garanteed to be there on each an every Java VM. > CPython strictly interprets bytecode; And ? > it does not compile the > bytecode to native code. And ? I fail to see how the existence of JIT compilers in some Java VM changes anything to the fact that both Java (by language specification) and CPython use the byte-code/VM scheme. From vriolk at gmail.com Thu Jan 17 04:38:03 2008 From: vriolk at gmail.com (coldpizza) Date: Thu, 17 Jan 2008 01:38:03 -0800 (PST) Subject: UTF-8 in basic CGI mode References: <1f8a4051-27cb-48aa-a0ab-793f59ab3845@s13g2000prd.googlegroups.com> Message-ID: Thanks, Sion, that makes sense! Would it be correct to assume that the encoding of strings retrieved by FieldStorage() would be the same as the encoding of the submitted web form (in my case utf-8)? Funny but I have the same form implemented in PSP (Python Server Pages), running under Apache with mod_python and it works transparently with no explicit charset translation required. On Jan 16, 4:31?pm, Sion Arrowsmith wrote: > coldpizza ? wrote: > >I am using this 'word' variable like this: > > >print u'''''' % (word) > > >and apparently this causes exceptions with non-ASCII strings. > > >I've also tried this: > >print u'''''' % > >(word.encode('utf8')) > >but I still get the same UnicodeDecodeError.. > > Your 'word' is a byte string (presumably UTF8 encoded). When python > is asked to insert a byte string into a unicode string (as you are > doing with the % operator, but the same applies to concatenation > with the + operator) it attempts to convert the byte string into > unicode. And the default encoding is 'ascii', and the ascii codec > takes a very strict view about what an ASCII character is -- and > that is that only characters below 128 are ASCII. > > To get it to work, you need to *decode* word. It is already UTF8 > (or something) encoded. Under most circumstances, use encode() to > turn unicode strings to byte strings, and decode() to go in the > other direction. > > -- > \S -- si... 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 martin at v.loewis.de Sat Jan 12 18:08:42 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jan 2008 00:08:42 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: References: Message-ID: <4789487A.1020209@v.loewis.de> > 2. If this returns "C" or anything without 'utf8' in it, then things start > to go downhill: > 2a. The app assumes unicode objects internally. i.e. Whenever there is > a "string like this" in a var it's supposed to be unicode. Whenever > something comes into the app (from a filename, a file's contents, the > command-line) it's assumed to be a byte-string that I decode("utf8") on > before placing it into my objects etc. That's a bug in the app. It shouldn't assume that environment variables are UTF-8. Instead, it should assume that they are in the locale's encoding, and compute that encoding with locale.getpreferredencoding. > 2b. Because of 2a and if the locale is not 'utf8 aware' (i.e. "C") I start > getting all the old 'ascii' unicode decode errors. This happens at every > string operation, at every print command and is almost impossible to fix. If you print non-ASCII strings to the terminal, and you can't be certain that the terminal supports the encoding in the string, and you can't reasonably deal with the exceptions, you should accept moji-bake, by specifying the "replace" error handler when converting strings to the terminal's encoding. > 3. I made the decision to check the locale and stop the app if the return > from getlocale is (None,None). I would avoid locale.getlocale. It's a pointless function (IMO). Also, what's the purpose of this test? > Does anyone have some ideas? Is there a universal "proper" locale that we > could set a system to *before* the Debian build stuff starts? What would > that be - en_US.utf8? Your program definitely, absolutely must work in the C locale. Of course, you cannot have any non-ASCII characters in that locale, so deal with it. If you have solved that, chances are high that it will work in other locales as well (but be sure to try Turkish, as that gives a surprising meaning to "I".lower()). Regards, Martin From kyosohma at gmail.com Fri Jan 18 17:20:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jan 2008 14:20:13 -0800 (PST) Subject: What is a shortcut to the Default home directory in Windows References: <1f85750e-a85a-4bb5-8f20-cbb5939f89a3@p69g2000hsa.googlegroups.com> Message-ID: <1fddf38d-e6a2-416f-a8f8-020560970ab5@z17g2000hsg.googlegroups.com> On Jan 18, 2:19 pm, Daniel Folkes wrote: > I am trying to write a file to the users file system. > > I need it to be in there home directory in WINDOWS. I know there is a > "shortcut" to home in Linux("~"), but is there an equivalent to that > in windows. Or to get to their "Documents and Settings" directory? > > Thanks in advance for the help. > > -Daniel Folkes I personally use Tim Golden's excellent win32 API wrapper, the winshell script. You can find it here: http://timgolden.me.uk/python/winshell.html Mike From bearophileHUGS at lycos.com Tue Jan 22 10:25:56 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 22 Jan 2008 07:25:56 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> Message-ID: Alan Isaac>What is the fastest way? (Ignore the import time.)< Maybe someday someone will realize such stuff belongs to the python STD lib... If you need a lazy generator without padding, that splits starting from the start, then this is the faster to me if n is close to 2: def xpartition(seq, n=2): return izip( *(iter(seq),)*n ) If you need the faster greedy version without padding then there are two answers, one for Psyco and one for Python without... :-) If you need padding or to start from the end then there are more answers... Bye, bearophile From David.Reksten at sweco.no Wed Jan 30 04:54:29 2008 From: David.Reksten at sweco.no (David.Reksten at sweco.no) Date: Wed, 30 Jan 2008 10:54:29 +0100 Subject: SV: Unicode literals to latin-1 In-Reply-To: <60avf7F1ps52dU3@mid.uni-berlin.de> References: <60avf7F1ps52dU3@mid.uni-berlin.de> Message-ID: <7C90895B4B6EE44AAF5F16CB1F48427162C41CE470@srv-mail-02.nettverk.int> On 30. januar 2008 10:48, Marc 'BlackJack' Rintsch wrote: >On Wed, 30 Jan 2008 09:57:55 +0100, David.Reksten wrote: > >> How can I convert a string read from a database containing unicode >> literals, such as "Fr\u00f8ya" to the latin-1 equivalent, "Fr?ya"? >> >> I have tried variations around >> "Fr\u00f8ya".decode('latin-1') >> but to no avail. > >In [388]: 'Fr\u00f8ya'.decode('unicode-escape') >Out[388]: u'Fr\xf8ya' > >In [389]: print 'Fr\u00f8ya'.decode('unicode-escape') >Fr?ya 'unicode-escape' did the trick! Thank you! .david From ajaksu at gmail.com Mon Jan 7 21:08:38 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 7 Jan 2008 18:08:38 -0800 (PST) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: <1d895d6d-a649-439e-8223-0ae7d3a4eb40@l6g2000prm.googlegroups.com> On Jan 7, 11:25 am, MartinRineh... at gmail.com wrote: > There's a lot of dumb stuff out there. "Algorithms should be coded > efficiently ..." Thanks, I'll keep that in mind. > > van Rossum's guidelines tend toward "pick something and stick to it" > which is OK if you have enough experience to pick something Pythonic. > I'm a relative newbie, not qualified to pick. > > Anything written somewhere that's thorough? Any code body that should > serve as a reference? I've done this search before and it was very interesting, doing it again gave me new results that also seem valuable. Here's most of them (where PCG = Python Coding Guidelines). Cogent project PCG http://jaynes.colorado.edu/PythonGuidelines.html (also http://jaynes.colorado.edu/PythonIdioms.html) Freevo Coding Standard http://doc.freevo.org/CodingStandard Mercurial Basic Coding Style http://www.selenic.com/mercurial/wiki/index.cgi/Basic_Coding_Style PyBlosxom Coding Style Guide http://pyblosxom.sourceforge.net/blog/static/development#coding MoinMoin Coding Style http://moinmoin.wikiwikiweb.de/CodingStyle Webware Style Guidelines http://www.webwareforpython.org/Docs/StyleGuidelines.html NOAA Enhanced Forecaster Tools PCG http://www-md.fsl.noaa.gov/eft/developer/PythonCodingStandards.html BioPython Coding Conventions http://biopython.org/wiki/Contributing#Coding_conventions Mnet PCG http://mnet.sourceforge.net/coding_standards.html Michael Foord's (aka Voidspace) PCG http://www.voidspace.org.uk/python/weblog/arch_d7_2006_04_01.shtml#e296 SQLObject Coding Style http://www.sqlobject.org/DeveloperGuide.html#style-guide WxPython PCG http://www.wxpython.org/codeguidelines.php Python coding style guide for Mailman http://barry.warsaw.us/software/STYLEGUIDE.txt VoiceCode PCG http://voicecode.iit.nrc.ca/VoiceCode/uploads/codingGuidelines.html Bazaar Coding Stile Guidelines http://doc.bazaar-vcs.org/bzr.dev/en/developer-guide/HACKING.html#coding-style-guidelines IPython Developer Guidelines http://ipython.scipy.org/moin/Developer_Zone/Developer_Guidelines OSAF Chandler PCG http://chandlerproject.org/Projects/ChandlerCodingStyleGuidelines (along with http://chandlerproject.org/Projects/ChandlerEpydocStyleGuide) Twisted Coding Standard http://twistedmatrix.com/trac/browser/trunk/doc/development/policy/coding-standard.xhtml?format=raw PyPy RPython and CPython Coding Guidelines http://codespeak.net/pypy/dist/pypy/doc/coding-guide.html Django PCG (and general contribution recommendations) http://www.djangoproject.com/documentation/contributing/#coding-style Docutils PCG http://docutils.sourceforge.net/docs/dev/policies.html#python-coding-conventions Trac Coding Style http://trac.edgewall.org/wiki/TracDev/CodingStyle OLPC PCG http://wiki.laptop.org/go/Python_Style_Guide Skeletonz Coding and Naming Conventions http://orangoo.com/skeletonz/Developer_guide/Coding_convention/ http://orangoo.com/skeletonz/Developer_guide/Naming_convention/ CherryPy Code Conventions http://www.cherrypy.org/wiki/CodeConventions More generic but still good (or great) insights: Software Carpentry on style http://www.swc.scipy.org/lec/style.html Zope's Coding Style http://wiki.zope.org/zope3/CodingStyle The docstrings PEP http://www.python.org/dev/peps/pep-0257/ The NiceStyle Triad?: Pyflakes http://divmod.org/trac/wiki/DivmodPyflakes PyChecker http://pychecker.sourceforge.net/ Pylint http://www.logilab.org/857 Do you think this could be a valuable addition to the Python wiki? HTH, Daniel From kyosohma at gmail.com Fri Jan 11 12:20:05 2008 From: kyosohma at gmail.com (Mike) Date: Fri, 11 Jan 2008 09:20:05 -0800 (PST) Subject: ISO books of official Python docs References: Message-ID: On Jan 9, 2:59 pm, Fredrik Lundh wrote: > Doug Morse wrote: > > Several of the O'Reilly & Assoc. books -- such as Python in a Nutshell, The > > Python Standard Library, etc -- are in large part reproductions of the > > official docs and references. > > if you're using "reproduction" to mean "copy", I think you owe both me > and Alex a big apology. > > I am a fan of your effbot blog and I've thought about buying your book before. Can you tell me how much of it is still valid for Python 2.5 since the book was released in 2001 and written with 2.0 in mind? Are you planning to update it at some point? It would be nice to have a complete library reference with a good index at times. Thank you, Mike From madhurrajn at gmail.com Fri Jan 18 04:23:09 2008 From: madhurrajn at gmail.com (Madhur) Date: Fri, 18 Jan 2008 01:23:09 -0800 (PST) Subject: Filtering two files with uncommon column Message-ID: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> I would like to know the best way of generating filter of two files based upon the following condition I have two files. Contents of the first file is File 1 abc def hij asd sss lmn hig pqr mno File 2 jih def asd poi iuu wer wer pqr jjj I would like have the output as Output File1 asd sss lmn File2 poi iuu wer Basically I want to compare the two files based on second column. If the second column matches on both the files do not print anything, else if there is no matc h in for the second column for first file in second file then print it under Fil e1 header, else if there is no match for the second column for second file in fi rst file print it under File2 header. Thankyou Madhur From over at thepond.com Tue Jan 22 17:29:54 2008 From: over at thepond.com (over at thepond.com) Date: Tue, 22 Jan 2008 22:29:54 GMT Subject: translating Python to Assembler Message-ID: <6ircp35hju5cb2iu9ip6rc7qjt9d585cde@4ax.com> My expertise, if any, is in assembler. I'm trying to understand Python scripts and modules by examining them after they have been disassembled in a Windows environment. I'm wondering if a Python symbols file is available. In the Windows environment, a symbol file normally has a PDB extension. It's a little unfortunate that Python also uses PDB for its debugger. Google, for whatever reason, wont accept queries with dots, hyphens, etc., in the query line. For example a Google for "python.pdb" returns +python +pdb, so I get a ridiculous number of returns referring to the python debugger. I have mentioned this to Google several times, but I guess logic isn't one of their strong points. :-) From paddy3118 at googlemail.com Wed Jan 9 01:47:19 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 8 Jan 2008 22:47:19 -0800 (PST) Subject: Congratulations to the CPython Developers on an outstanding codebase Message-ID: <2c04cf4b-fa6f-4e13-9cd4-3349215abc52@f47g2000hsd.googlegroups.com> It looks a bit like an add for Coverity, but under all that, they seem to have picked Python as one of the OS projects to test with their improved testing software because our developers were so good at working on any "bugs" reported by their earlier tool. Good job guys. http://scan.coverity.com/ - Paddy. P.S. I wonder, do any closed source programming languages have such bug reports available? From python.list at tim.thechases.com Tue Jan 8 08:15:57 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 08 Jan 2008 07:15:57 -0600 Subject: Look for a string on a file and get its line number In-Reply-To: <03a301c851e1$4f211a00$0203a8c0@MOUSE> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <03a301c851e1$4f211a00$0203a8c0@MOUSE> Message-ID: <4783778D.2050406@tim.thechases.com> >> I have to search for a string on a big file. Once this string >> is found, I would need to get the number of the line in which >> the string is located on the file. Do you know how if this is >> possible to do in python ? > > This should be reasonable: > >>>> for num, line in enumerate(open("/python25/readme.txt")): > if "Guido" in line: > print "Found Guido on line", num > break > > > Found Guido on line 1296 Just a small caveat here: enumerate() is zero-based, so you may actually want add one to the resulting number: s = "Guido" for num, line in enumerate(open("file.txt")): if s in line: print "Found %s on line %i" % (s, num + 1) break # optionally stop looking Or one could use a tool made for the job: grep -n Guido file.txt or if you only want the first match: sed -n '/Guido/{=;p;q}' file.txt -tkc From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 06:51:22 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 12:51:22 +0100 Subject: no pass-values calling? In-Reply-To: References: <13or6esikdrqa33@corp.supernews.com> Message-ID: <478def8f$0$28424$426a34cc@news.free.fr> J. Peng a ?crit : > On Jan 16, 2008 2:30 PM, Steven D'Aprano > wrote: >> On Wed, 16 Jan 2008 13:59:03 +0800, J. Peng wrote: >> >>> Hi, >>> >>> How to modify the array passed to the function? I tried something like >>> this: >>> >>>>>> a >>> [1, 2, 3] >>>>>> def mytest(x): >>> ... x=[4,5,6] >> >> This line does NOT modify the list [1, 2, 3]. What it does is create a >> new list, and assign it to the name "x". It doesn't change the existing >> list. >> > > Sounds strange. > In perl This is Python, not Perl. Please follow the links provided by Steven and read carefully. From bblais at bryant.edu Wed Jan 9 09:43:07 2008 From: bblais at bryant.edu (Brian Blais) Date: Wed, 9 Jan 2008 09:43:07 -0500 Subject: packaging questions Message-ID: Hello, I am trying to package a number of python files, and I plan to use Mercurial to do the version control. In more established projects that I see, I notice that there are a number of files, like Changelog, MANIFEST, INSTALL, etc... that would seem to be generated automatically. Also, within the python code, and the setup.py, there are properties like __version__ which one would like to have generated automatically as well, so that you aren't hand-editing a number of files. Is there a standard way of doing this? thanks, Brian Blais -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Fri Jan 11 06:16:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jan 2008 12:16:53 +0100 Subject: Why Python.exe is breaking with memory dump?? In-Reply-To: References: Message-ID: abhishek wrote: > Hi group i have created a simple .pyd using which i m able call C > function from python code. There are around 6 such functions. 4 of > them work great. But when i try to run other two python's exe breaks > giving memory dump. > > Any pros or cons on what led to such a situation.. Is it a problem in > my c code?? yes. check for reference counting errors, plus the usual C stuff: memory allocation errors, memory overwrites, bogus pointers, etc. From mccredie at gmail.com Fri Jan 18 12:55:56 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 18 Jan 2008 09:55:56 -0800 (PST) Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <54efb87e-5a54-42a4-adcc-3d05e03a4859@s8g2000prg.googlegroups.com> On Jan 18, 9:15 am, David Sanders wrote: > Hi, > > I am processing large files of numerical data. Each line is either a > single (positive) integer, or a pair of positive integers, where the > second represents the number of times that the first number is > repeated in the data -- this is to avoid generating huge raw files, > since one particular number is often repeated in the data generation > step. > > My question is how to process such files efficiently to obtain a > frequency histogram of the data (how many times each number occurs in > the data, taking into account the repetitions). My current code is as > follows: > > ------------------- > #!/usr/bin/env python > # Counts the occurrences of integers in a file and makes a histogram > of them > # Allows for a second field which gives the number of counts of each > datum > > import sys > args = sys.argv > num_args = len(args) > > if num_args < 2: > print "Syntaxis: count.py archivo" > sys.exit(); > > name = args[1] > file = open(name, "r") > > hist = {} # dictionary for histogram > num = 0 > > for line in file: > data = line.split() > first = int(data[0]) > > if len(data) == 1: > count = 1 > else: > count = int(data[1]) # more than one repetition > > if first in hist: # add the information to the histogram > hist[first]+=count > else: > hist[first]=count > > num+=count > > keys = hist.keys() > keys.sort() > > print "# i fraction hist[i]" > for i in keys: > print i, float(hist[i])/num, hist[i] > --------------------- > > The data files are large (~100 million lines), and this code takes a > long time to run (compared to just doing wc -l, for example). > > Am I doing something very inefficient? (Any general comments on my > pythonic (or otherwise) style are also appreciated!) Is > "line.split()" efficient, for example? > > Is a dictionary the right way to do this? In any given file, there is > an upper bound on the data, so it seems to me that some kind of array > (numpy?) would be more efficient, but the upper bound changes in each > file. My first suggestion is to wrap your code in a function. Functions run much faster in python than module level code, so that will give you a speed up right away. My second suggestion is to look into using defaultdict for your histogram. A dictionary is a very appropriate way to store this data. There has been some mention of a bag type, which would do exactly what you need, but unfortunately there is not a built in bag type (yet). I would write it something like this: from collections import defaultdict def get_hist(file_name): hist = defaultdict(int) f = open(filename,"r") for line in f: vals = line.split() val = int(vals[0]) try: # don't look to see if you will cause an error, # just cause it and then deal with it cnt = int(vals[1]) except IndexError: cnt = 1 hist[val] += cnt return hist HTH Matt From fredrik at pythonware.com Sat Jan 12 04:51:02 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Jan 2008 10:51:02 +0100 Subject: removeall() in list In-Reply-To: <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > I'm writing an NxN observer pattern, mostly for my own personal > exploration. Two threads -might- be calling 'Disconnect' at the same > time, and I can't even guarantee that the function runs properly. > > for emelem in [ e for e in emlist if e.func is func ]: > try: > emlist.remove( emelem ) > except ValueError: > pass so use a lock. it's a whopping two lines of code: creation: lock = threading.Lock() usage: with lock: for emelem in ... ... more here: http://effbot.org/zone/thread-synchronization.htm and btw, looping over a list to figure out what you want to remove from that list is a bit pointless. better just create a new list: with lock: # get rid of all func instances emlist = [e for e in emlist if e.func is not func] an alternative approach would be to replace emlist with a dictionary, keyed on func objects. that'll let you remove all items associated with a given function with a single atomic operation: del emdict[func] From mgierdal at gmail.com Fri Jan 18 11:10:45 2008 From: mgierdal at gmail.com (mgierdal at gmail.com) Date: Fri, 18 Jan 2008 08:10:45 -0800 (PST) Subject: how to resolve Windows pathnames into cygwin ones Message-ID: I am looking for a function to resolve 'F:/foo/bar' into '/cygdrive/f/ foo/bar'. I get the original dirpath from tkFileDialog.askdirectory in a Windows form and none of os.path.* functions seem to resolve it to a cygwin form. Rather they _append_ it to the current directory, resulting at best in a monster '/cygdrive/c/whatever/f/foo/bar'. It's all being developed under cygwin currently (so it is a kind of mixed environment), but I would like the fix to work correctly in any environment. Thanks, Marcin From paddy3118 at googlemail.com Thu Jan 24 10:26:27 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 07:26:27 -0800 (PST) Subject: piping into a python script References: Message-ID: On Jan 24, 3:17 pm, Donn Ingle wrote: > Hi, > (Gnu/Linux - Python 2.4/5) > Given these two examples: > 1. > ./fui.py *.py > 2. > ls *.py | ./fui.py > > How can I capture a list of the arguments? > I need to get all the strings (file or dir names) passed via the normal > command line and any that may come from a pipe. > > There is a third case: > 3. > ls *.jpg | ./fui.py *.png > Where I would be gathering strings from two places. > > I am trying to write a command-line friendly tool that can be used in > traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. > > I have tried: > 1. pipedIn = sys.stdin.readlines() > Works fine for example 2, but example 1 goes into a 'wait for input' mode > and that's no good. Is there a way to tell when no input is coming from a > pipe at all? > > 2. import fileinput > for line in fileinput.input(): > print (line) > But this opens each file and I don't want that. > > I have seen a lot of search results that don't quite answer this angle of > the question, so I'm trying on the list. > > \d Try the fileinput module. What you describe above is pretty close to the unix 'standard' but not quite. if we substitute the lp command instead of ./fui, the command normally takes a list of files to act on as its arguments, and anything piped in goes to its stdin where it is processed if it has an argument of - fileinput works that way but you may have problems with your: ls *.jpg | ./fui.py *.png Which might better be expressed as: ./fui.py `ls *.jpg` *.png which would work for ls and a python program using the fileinput module. - Paddy. From fetchinson at googlemail.com Tue Jan 8 16:31:11 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 8 Jan 2008 13:31:11 -0800 Subject: Newbie question: Classes In-Reply-To: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com> References: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com> Message-ID: > Basically, I have created a program using tkinter without using any class > structure, simply creating widgets and functions (and finding ways around > passing variables from function to function, using global variables etc). > The program has become rather large ( lines?) I am trying to now put it into > a class structure, because I hear it is easier to handle. > > So basically, I put all the stuff into a class, making the widgets in the > "def __init__(self, root)" (root being my Tk() ) and then I have had to put > a "self." in front of any instance of any variable or widget. Is this right? > it seems like nothing is any easier (except having variables locally). Is > this right? Should I be creating more classes for different things or what? Use the method that works best for you. If you like the procedural approach more then don't worry about being object oriented. The good thing is that python is multi-paradigm so if custom objects don't make your life easier then just forget about them :) From stefan.behnel-n05pAM at web.de Thu Jan 3 08:50:05 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 03 Jan 2008 14:50:05 +0100 Subject: ElementTree should parse string and file in the same way In-Reply-To: References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> <477C9804.40003@web.de> Message-ID: <477CE80D.3050508@web.de> Fredrik Lundh wrote: > Stefan Behnel wrote: > >>> My take on the API decision in question was always that a file is >>> inherently an XML *document*, while a string is inherently an XML >>> *fragment*. >> >> Not inherently, no. I know some people who do web processing with an XML >> document coming in as a string (from an HTTP request) /.../ > > in which case you probably want to stream the raw XML through the parser > *as it arrives*, to reduce latency (to do that, either parse from a > file-like object, or feed data directly to a parser instance, via the > consumer protocol). It depends on the abstraction the web framework provides. If it allows you to do that, especially in an event driven way, that's obviously the most efficient implementation (and both ElementTree and lxml support this use pattern just fine). However, some frameworks just pass the request content (such as a POSTed document) in a dictionary or as callback parameters, in which case there's little room for optimisation. > also, putting large documents in a *single* Python string can be quite > inefficient. it's often more efficient to use lists of string fragments. That's a pretty general statement. Do you mean in terms of reading from that string (which at least in lxml is a straight forward extraction of a char*/len pair which is passed into libxml2), constructing that string (possibly from partial strings, which temporarily *is* expensive) or just keeping the string in memory? At least lxml doesn't benefit from iterating over a list of strings and passing it to libxml2 step-by-step, compared to reading from a straight in-memory string. Here are some numbers: $$ cat listtest.py from lxml import etree # a list of strings is more memory expensive than a straight string doc_list = [""] + ["
test"] * 2000 + [""] # document construction temporarily ~doubles memory size doc = "".join(doc_list) def readlist(): tree = etree.fromstringlist(doc_list) def readdoc(): tree = etree.fromstring(doc) $$ python -m timeit -s 'from listtest import readlist,readdoc' 'readdoc()' 1000 loops, best of 3: 1.74 msec per loop $$ python -m timeit -s 'from listtest import readlist,readdoc' 'readlist()' 100 loops, best of 3: 2.46 msec per loop The performance difference stays somewhere around 20-30% even for larger documents. So, as expected, there's a trade-off between temporary memory size, long-term memory size and parser performance here. Stefan From boblatest at yahoo.com Tue Jan 8 05:10:20 2008 From: boblatest at yahoo.com (Robert Latest) Date: 8 Jan 2008 10:10:20 GMT Subject: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> <5ugulaF1hqn2cU1@mid.uni-berlin.de> <5ugv5dF1i0edtU1@mid.dfncis.de> <87fxx8mycm.fsf@mulj.homelinux.net> Message-ID: <5uh0gcF1hoialU2@mid.dfncis.de> Hrvoje Niksic wrote: > stdio uses different buffering strategies depending on the output > type. When the output is a TTY, line buffering is used; when the > output goes to a pipe or file, it is fully buffered. Makes sense. > If you see lines one by one, you are in luck, and you can fix things > on the Python level simply by avoiding buffering in popen. If not, > you will need to resort to more advanced hackery (e.g. fixing stdio > using LD_PRELOAD). Do I really? After all, the shell itself doesn't hack stdio, does it? Anyway, I'm taking this over to comp.unix.programmer since it really isn't a python problem. Thanks, robert From ptmcg at austin.rr.com Mon Jan 7 13:33:14 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 7 Jan 2008 10:33:14 -0800 (PST) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> <0b11ce6b-3565-41b6-8e63-17cb941b8197@i7g2000prf.googlegroups.com> Message-ID: <105594e7-39bd-4e6a-9d21-71ba6b1fabfa@e10g2000prf.googlegroups.com> On Jan 7, 12:26?pm, MartinRineh... at gmail.com wrote: > Guilherme Polo wrote: > > foo = [ > > ? ? 'too long', > > ? ? 'too long too', > > ? ? ... > > ? ? ] > > OK, I'll put it there too, and it will be easy for us to read each > other's code (at least in this particular). While not required by any means, you will also find it handy to follow *every* entry in the list with a comma, even the last one in the list (this is legal Python). That is, in your example: foo = [ 'too long', 'too long too', 'too long too', 'last item', ] Later on when you want to reorder the items, then you can just copy/ paste whole lines, even if moving to or from the bottom of the list. This is also a good argument for putting the closing ']' on its own line, instead of on the same line as the last item. -- Paul From boblatest at yahoo.com Wed Jan 9 07:41:38 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 12:41:38 GMT Subject: How does unicode() work? References: <5ujt96F1i6h37U1@mid.dfncis.de> Message-ID: <5ujto2F1i6h37U2@mid.dfncis.de> Robert Latest wrote: > ...but it barfs when actually fed with iso8859-1 characters. Specifically, it says: UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 0: ordinal not in range(128) which doesn't make sense to me, because I specifically asked for the iso8859-1 decoder, not the 'ascii' one. robert From gagsl-py2 at yahoo.com.ar Sun Jan 27 14:15:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 17:15:45 -0200 Subject: Replacing a package with another References: Message-ID: En Sat, 26 Jan 2008 12:10:03 -0200, J. Pablo Fern?ndez escribi?: > Is it possible to replace one package with another at runtime, that is, I > have package a.blah which I want instead of b.blah, so I can "inject" > functionality in an existing package? It might be done, just assign the replacement functions/classes to the existing module. This has the same warnings as the reload() function: already created objects maintain their original behavior, already imported names from modules maintain their original value, already bound names to default arguments maintain their original value, etc. So it is best to do it as early as possible, but anyway some effects can't be avoided: === a.py === default_tax_pct = 21 print "in a, default_tax_pct=",default_tax_pct def foo(): print "original foo" def tax(amount, pct=default_tax_pct): print amount, pct, amount*pct/100 === path_a.py === import a def foo(): print "other foo" print "patching a.foo", a.foo = foo print a.foo print "patching a.default_tax_pct", a.default_tax_pct = 15 print a.default_tax_pct === main.py === import a from a import default_tax_pct import patch_a print "in main, a.default_tax_pct", a.default_tax_pct print "in main, default_tax_pct", default_tax_pct print "calling a.foo:" a.foo() print "calling a.tax(100.0):" a.tax(100.0) === output === in a, default_tax_pct= 21 patching a.foo patching a.default_tax_pct 15 in main, a.default_tax_pct 15 in main, default_tax_pct 21 calling a.foo: other foo calling a.tax(100.0): 100.0 21 21.0 -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Wed Jan 9 15:26:05 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 09 Jan 2008 21:26:05 +0100 Subject: Python too slow? In-Reply-To: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <47852dd8$0$27994$426a74cc@news.free.fr> dongie.agnir at gmail.com a ?crit : > I'm pretty new to Python, and even newer to Image/Video processing, > and trying to get started on a project similar to GRL Vienna's laser > marker. I found some sample code here http://janto.blogspot.com/2006/01/motion-capture-in-python.html, > but after running the code with the included sample input file, it > seems quite slow (1-2 seconds from start to finish to do the 800 by > 600 gif image). > > Is there a better way to do color tracking, Not having any experience with this domain, I can't comment on this. > or is Python just too slow > as an interpreted language Being "interpreted" is a quality of an implementation, not of a language. And the reference implementation of Python (CPython) is not interpreted, it's compiled to byte-code, which is then executed by a VM (just like Java). So while CPython may possibly be too slow for your application (it can indeed be somewhat slow for some tasks), the reasons are elsewhere (hint: how can a compiler safely optimize anything in a language so dynamic that even the class of an object can be changed at runtime ?) ... > to do any effective color tracking? From dstromberglists at gmail.com Mon Jan 14 12:41:35 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Mon, 14 Jan 2008 17:41:35 GMT Subject: bags? 2.5.x? Message-ID: Is there a particular reason why bags didn't go into 2.5.x or 3000? I keep wanting something like them - especially bags with something akin to set union, intersection and difference. From phillip.sitbon at gmail.com Fri Jan 11 19:37:29 2008 From: phillip.sitbon at gmail.com (Phillip Sitbon) Date: Fri, 11 Jan 2008 16:37:29 -0800 (PST) Subject: Python in IIS + WSGI Message-ID: <86d01390-fb1c-4806-a10b-92446c008b10@k2g2000hse.googlegroups.com> Recently (finally) updated the PyISAPIe project. Version 1.0.4 includes WSGI support (tested with current Django SVN and Trac 0.10) and a Django-native handler, as well as other examples of using it as a standalone web app. Also added some installation/usage docs on the project page. Comments/feedback welcome! http://pyisapie.sourceforege.net Cheers, Phillip From ajcppmod at gmail.com Wed Jan 9 08:16:58 2008 From: ajcppmod at gmail.com (ajcppmod at gmail.com) Date: Wed, 9 Jan 2008 05:16:58 -0800 (PST) Subject: flatten sequences in a dictionary Message-ID: Hi I wondering if someone could give me a pointer. I have a dictionary with the following structure: testDict = dict(foo=((1,2,3),(1,4,3)), bar=((3,2,1),(9,8,7,)), mumble=((1,2,3),)) I am trying to create a list of the the 3 element tuples using itertools (just for a bit of fun). I'm trying this: list(itertools.chain(testDict.itervalues()) but that's doesn't work. I think I need a way to convert the iterator returned by itervalues() into a sequence of iterables. Any clues? Thanks Andy From hkimball at eti-web.com Sun Jan 6 20:23:11 2008 From: hkimball at eti-web.com (hkimball at eti-web.com) Date: Sun, 6 Jan 2008 17:23:11 -0800 (PST) Subject: ctypes Message-ID: <5bc0722e-efe7-4067-9bf4-afee3f1c9a03@f3g2000hsg.googlegroups.com> I am having trouble with ctypes: i can load the third party dll, and gain access to the function but the function calls do not actually perform their intended purpose. I have tried this in both interactive mode and from a saved script. I know that is a somewhat vague description but any help would be greatly appreciated. thanks harold kimball From lists at cheimes.de Sat Jan 19 18:18:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 20 Jan 2008 00:18:09 +0100 Subject: Python 3000 and import __hello__ In-Reply-To: References: Message-ID: <47928531.7030806@cheimes.de> Brad wrote: > Just playing around with Python3000 a2 release on Windows XP 32-bit x86. > > import __hello__ > > doesn't print 'hello world...' as it does on 2.5 > > The import doesn't fail or generate errors... just no output. Perhaps > this is by design? I changed the __hello__ frozen module a while ago. The print was unreliable for some new unit tests. Christian From alan.nichols at staarinc.com Fri Jan 25 12:50:29 2008 From: alan.nichols at staarinc.com (Alan Nichols) Date: Fri, 25 Jan 2008 11:50:29 -0600 Subject: Windows issue -- method to control generation of bytecode files Message-ID: <000501c85f7a$c6b07100$54115300$@nichols@staarinc.com> Hello, I'm curious to know if there is a means available to control the location in which bytecode files are generated. It seems that for some types of user accounts (specifically regular users, not superusers or admins) MS Windows will not allow writes to the C:\Program Files directory. As a result, .py source files cannot be located in C:\Program Files because the .pyc files cannot be generated there. Up to now we have been installing the Python code in another directory; we'd like to move away from this if we can. Is anyone aware of a workaround that would address this issue? Skip Montonaro raised a suggestion in 2003 (PEP304) that looked promising but it never generated much interest. Thank you for your help, Alan Nichols -------------- next part -------------- An HTML attachment was scrubbed... URL: From ggpolo at gmail.com Mon Jan 7 06:31:52 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 09:31:52 -0200 Subject: python syntax In-Reply-To: <633886.19582.qm@web45510.mail.sp1.yahoo.com> References: <633886.19582.qm@web45510.mail.sp1.yahoo.com> Message-ID: 2008/1/7, mpho raborife : > Please help me get this syntax right: > > os.system("HCopy -T 1 -C" 'os.path.join(conf_dir, "/hcopy.conf")' "-S" > 'os.path.join(list_dir, "hcopy_list.txt")') > import os import subprocess subprocess.Popen(["HCopy", "-T", "1", "-C", os.path.join(conf_dir, "hcopy.conf"), "-S", os.path.join(list_dir, "hcopy_list.txt")]) > > > ________________________________ > Looking for last minute shopping deals? Find them fast with Yahoo! Search. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bruno.desthuilliers at gmail.com Sat Jan 12 11:52:16 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jan 2008 08:52:16 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> Message-ID: On 11 jan, 15:41, Hrvoje Niksic wrote: > Bruno Desthuilliers > writes: > > > fact 1: CPython compiles source code to byte-code. > > fact 2: CPython executes this byte-code. > > fact 3: Sun's JDK compiles source code to byte-code. > > fact 4: Sun's JDK executes this byte-code. > > > Care to prove me wrong on any of these points ? Don't bother: you > > can't. > > Fact 4 is misleading because it is only one option available to Sun's > JDK. Sun's JDK is also capable of transforming the byte-code to > native code and letting the processor execute that instead of the > original byte code, and that is where the most significant speed > increase comes from. Most importantly, it does so automatically, by > default, with no programmer intervention or configuration, and with > 100% compatibility, so it doesn't compare well to Python accelerators > like psyco. Then fact 1 is misleading too since Python handles the compilation automatically without programmer's intervention while Java requires someone to explicitely invoke the byte-code compiler. I just don't understand what's all that fuss with this simple and quite comparison of Java and Python. You can google this ng archives, you'll find hundreds of posts saying the same thing, and everyone so far seemed to be smart enough to understand that this had nothing to do with the byte-code specifications, VM implementation and presence or absence of a JIT compiler. Anyway, I do maintain that what I said is 100% correct, 100% accurate given the context, and 0% misleading unless you're clueless enough to not be able to parse a single english sentence (in which case I just can't help). As a matter of fact, this didn't seem to "mislead" the OP into thinking such a thing. Regards. From gagsl-py2 at yahoo.com.ar Thu Jan 24 01:51:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 Jan 2008 04:51:14 -0200 Subject: Function wrappers References: Message-ID: En Thu, 24 Jan 2008 00:16:01 -0200, escribi?: > def f( callback, *bar, **bkwar ): > def preg ( callfore, *far, **fkwar ): > return g( callback, callfore, bar, bkwar, far, fkwar ) > return preg > > Does anyone see a way to rewrite this, perhaps along the lines of > partial( partial, partial )? Ok to modify 'g' call. What's wrong with this? Why do you want to rewrite it? -- Gabriel Genellina From fredrik at pythonware.com Tue Jan 15 12:22:29 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jan 2008 18:22:29 +0100 Subject: ElementTree and namespaces in the header only In-Reply-To: <2c769fe0-8add-4aa1-9657-b8ee5f76cb91@k39g2000hsf.googlegroups.com> References: <2c769fe0-8add-4aa1-9657-b8ee5f76cb91@k39g2000hsf.googlegroups.com> Message-ID: Peter Bengtsson wrote: > root = Element('feed', xmlns='http://www.w3.org/2005/Atom') > root.set('xmlns:se', NS_URL) > entry = SubElement(root, 'entry') > SubElement(root, 'title').text = 'Title' > SubElement(entry, SEN('category')).text = 'Category' > But surely the xmlns:se attribute on the tag is > excessive since the namespace (by the URI) is already defined in the > tag. How do I set non-default namespace tags in elements > without the automatic xmlns:se attribute repeated each time? ET 1.2's standard serializer doesn't take explicitly set namespaces into account. If you want full control over namespace generation, you have to do it yourself: http://effbot.org/zone/element-namespaces.htm#explicitly-setting-namespace-attributes ET 1.3 provides a default_namespace option for this specific case (but you still have to use universal names for everything that should go into the default namespace). From pavlovevidence at gmail.com Sat Jan 12 01:32:53 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 12 Jan 2008 01:32:53 -0500 Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> Message-ID: On Fri, 11 Jan 2008 08:29:18 -0800, dg.google.groups wrote: > Hi all, > > I'm part of a small team writing a Python package for a scientific > computing project. The idea is to make it easy to use for relatively > inexperienced programmers. As part of that aim, we're using what we're > calling 'magic functions', and I'm a little bit concerned that they are > dangerous code. I'm looking for advice on what the risks are (e.g. > possibility of introducing subtle bugs, code won't be compatible with > future versions of Python, etc.). > > Quick background: Part of the way our package works is that you create a > lot of objects, and then you create a new object which collects together > these objects and operates on them. We originally were writing things > like: > > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > bigobj = Bigobj(objects=[obj1,obj2]) > bigobj.run() > > This is fine, but we decided that for clarity of these programs, and to > make it easier for inexperienced programmers, we would like to be able > to write something like: > > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > run() > > The idea is that the run() function inspects the stack, and looks for > object which are instances of class Obj, creates a Bigobj with those > objects and calls its run() method. > > So, any comments on that approach? 1. Even if you implement magic functions, don't get rid of the straightforward "hard way". Magic functions should be for convenience only. The user should be free to choose to do it the straightforward, explicit "hard way", and not rely on the magic. In your example, Bigobj should still be available to users, and should be documented at least as well as the magic run() function. The main reason for this (aside from the philosophical question) is that users often have different needs that you can anticipate, and your magic might not meet those unanticipated needs, forcing the user to resort to hacks and workarounds. 2. If your intention is to perform this operation on all Objs, then it might be a good idea to arrange your code so that Objs are already registered by the time the user gets them. One way to do this has already been mentioned: by having the Obj class track all its instances. Another way that might be preferable is to have Bigobj create Objs on behalf of the user. Here's a stripped down example: class Bigobj(object): def __init__(self): self.tracked_objs = set() def create_object(self,*args): obj = Obj(*args) self.tracked_objs.add(obj) return obj def run(self): for obj in self.tracked_objs: # do something with obj bigobj = Bigobj() obj1 = bigobj.create_object(params1) obj2 = bigobj.create_object(params2) # maybe do something with obj1 and obj2 here bigobj.run() Carl Banks From steven.bethard at gmail.com Wed Jan 23 02:03:31 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 23 Jan 2008 00:03:31 -0700 Subject: subprocess and & (ampersand) In-Reply-To: References: Message-ID: <-pidnVUyKPNZewvanZ2dnUVZ_tyknZ2d@comcast.com> Steven D'Aprano wrote: > On Tue, 22 Jan 2008 22:53:20 -0700, Steven Bethard wrote: > >> I'm having trouble using the subprocess module on Windows when my >> command line includes special characters like "&" (ampersand):: >> >> >>> command = 'lynx.bat', '-dump', 'http://www.example.com/?x=1&y=2' >> >>> kwargs = dict(stdin=subprocess.PIPE, >> ... stdout=subprocess.PIPE, ... >> stderr=subprocess.PIPE) >> >>> proc = subprocess.Popen(command, **kwargs) proc.stderr.read() >> "'y' is not recognized as an internal or external command,\r\noperable >> program or batch file.\r\n" >> >> As you can see, Windows is interpreting that "&" as separating two >> commands, instead of being part of the single argument as I intend it to >> be above. Is there any workaround for this? How do I get "&" treated >> like a regular character using the subprocess module? > > > That's nothing to do with the subprocess module. As you say, it is > Windows interpreting the ampersand as a special character, so you need to > escape the character to the Windows shell. > > Under Windows, the escape character is ^, or you can put the string in > double quotes: > > # untested > command = 'lynx.bat -dump http://www.example.com/?x=1^&y=2' > command = 'lynx.bat -dump "http://www.example.com/?x=1&y=2"' Sorry, I should have mentioned that I already tried that. You get the same result:: >>> command = 'lynx.bat', '-dump', 'http://www.example.com/?x=1^&y=2' >>> proc = subprocess.Popen(command, ... stdin=subprocess.PIPE, ... stdout=subprocess.PIPE, ... stderr=subprocess.PIPE) >>> proc.stderr.read() "'y' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n" In fact, the "^" doesn't seem to work at the command line either:: >lynx.bat -dump http://www.example.com/?x=1^&y=2 Can't Access `file://localhost/C:/PROGRA~1/lynx/1' Alert!: Unable to access document. lynx: Can't access startfile 'y' is not recognized as an internal or external command, operable program or batch file. Using quotes does work at the command line:: C:\PROGRA~1\lynx>lynx.bat -dump "http://www.example.com/?x=1&y=2" You have reached this web page by typing "example.com", "example.net", or "example.org" into your web browser. These domain names are reserved for use in documentation and are not available for registration. See [1]RFC 2606, Section 3. References 1. http://www.rfc-editor.org/rfc/rfc2606.txt But I get no output at all when using quotes with subprocess:: >>> command= 'lynx.bat', '-dump', '"http://www.example.com/?x=1^&y=2"' >>> proc = subprocess.Popen(command, ... stdin=subprocess.PIPE, ... stdout=subprocess.PIPE, ... stderr=subprocess.PIPE) >>> proc.stderr.read() '' Any other ideas? STeVe From jzgoda at o2.usun.pl Mon Jan 28 08:59:28 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 28 Jan 2008 14:59:28 +0100 Subject: Set ulimit when using subprocess.Popen? In-Reply-To: References: Message-ID: Rob Wolfe napisa?(a): > > Jarek Zgoda napisa?(a): >> Hi, all, >> >> anybody has an idea on how to set ulimit (-v in my case, linux) for >> process started using subprocess.Popen? > > What about: > > from subprocess import call > call('ulimit -v 1000 && ulimit -v && ls', shell=True) subprocess.Popen('ulimit -v 1024; ls', shell=True) works perfect. Unfortunately, the nature of ulimit impacts deadly my application when the limit is reached, so this knowledge is of no help in my 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 paddy3118 at googlemail.com Thu Jan 24 11:38:31 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 08:38:31 -0800 (PST) Subject: piping into a python script References: Message-ID: On Jan 24, 4:02 pm, Donn Ingle wrote: > > Try the fileinput module. > > I did give the fileinput module a go, but I can't find much info on it and > the help is ... well, it's python help ;) Try http://effbot.org/librarybook/fileinput.htm > > > in goes to its stdin where it is processed if it has an argument of - > > fileinput works that way > > Okay, I did think of the dash, but did not know how to handle it. Is it a > bash thing or will that dash get passed into the args? (I am using getopt > to parse the options and args) - gets passed in and fileinput handles it. > > > which would work for ls and a python program using the fileinput > > module. > > Any examples of fileinput (that do not open each file) would be great! > (I'll go searching now anyway) fileinput is set to process each file a line at a time unfortunately. > > Thanks, Your welcome :-) - Paddy. From dblubaugh at belcan.com Thu Jan 31 20:26:52 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Thu, 31 Jan 2008 20:26:52 -0500 Subject: PLEASE ACCEPT MY SINCERE APOLOGIES In-Reply-To: References: Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380239F7FB@AWMAIL04.belcan.com> 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.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 7:30 PM To: python-list at python.org Subject: Python-list Digest, Vol 53, Issue 2 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. From donn.ingle at gmail.com Fri Jan 25 09:40:56 2008 From: donn.ingle at gmail.com (Donn Ingle) Date: Fri, 25 Jan 2008 16:40:56 +0200 Subject: piping into a python script References: <4798D092.9000308@gmx.net> Message-ID: Hexamorph wrote: > It's a bit clumsy, but seems to do what I guess you want. Hey, thanks for that! I will have a go. \d From nytrokiss at gmail.com Wed Jan 30 04:59:12 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 30 Jan 2008 10:59:12 +0100 Subject: help using python on Vista In-Reply-To: References: Message-ID: <8a6b8e350801300159o4aedcacfme7fbb84c989fa4c3@mail.gmail.com> You need to go into folder options which is in the control panel and there under the view tab click Show hidden files and folders On Jan 30, 2008 9:36 AM, Safe Alattar wrote: > I have no issues using python on XP. However on Vista I cant get the > python gui (IDLE) to open! > > I did some research and found out that I need to unhide .idlerc but I > cannot find any hidden files by that name whatsoever. Please help me. Im > fairly new to python but I want to get this going. User friendly > instructions would be much appreciated. Thanks. > > -- > 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 terry at jon.es Wed Jan 2 20:06:56 2008 From: terry at jon.es (Terry Jones) Date: Thu, 3 Jan 2008 02:06:56 +0100 Subject: Two candies In-Reply-To: Your message at 16:33:11 on Wednesday, 2 January 2008 References: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com> <736e51b5-d7f6-4523-89f1-df62256ce7c0@s19g2000prg.googlegroups.com> Message-ID: <18300.13616.437878.199164@terry.local> >>>>> "Raymond" == Raymond Hettinger writes: Raymond> * in most apps (except for sparse arrays), the initialization time Raymond> for an array is dominated by the time spent actually doing Raymond> something useful with the array (iow, this is an odd place to be Raymond> optimizing) This brings to mind an old algorithms chestnut (exercise 2.12 in the 1st edition of Aho, Hopcroft & Ullman [1]): If the implementation of an algorithm uses (for simplicity's sake) a square array to represent its data, why are _all_ such algorithms not necessarily O(n^2) due simply to the initialization requirement (supposing a model of computation that counts assignments)? Terry [1] http://www.amazon.com/Analysis-Algorithms-Addison-Wesley-Information-Processing/dp/0201000296 From steven.bethard at gmail.com Wed Jan 23 14:06:19 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 23 Jan 2008 12:06:19 -0700 Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? In-Reply-To: References: Message-ID: Kristian Domke wrote: > I am trying to learn python at the moment studying an example program > (cftp.py from the twisted framework, if you want to know) > > There I found a line > > foo = (not f and 1) or 0 Equivalent to ``foo = int(not f)`` > In this case f may be None or a string. > > If I am not wrong here, one could simply write > > foo = not f No cast to int() here. STeVe From phil at riverbankcomputing.co.uk Thu Jan 3 07:02:00 2008 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 3 Jan 2008 12:02:00 +0000 Subject: PyObject_CallObject code dump after calling 4 times In-Reply-To: References: Message-ID: <200801031202.00450.phil@riverbankcomputing.co.uk> On Thursday 03 January 2008, grbgooglefan wrote: > I have a following C++ code which uses PyObject_CallObject to evaluate > expressions dynamically. This code sets the input parameters for the > function also dynamically. After calling this function 4 times (with > these shown values), PyObject_CallObject causes application to crash > in frame_dealloc. > 1) Can some one please help me understand why is this crash happening > in frame_dealloc & how to solve it? > 2) Is there anything wrong I am doing about incrementing or > decrementing the reference counts of the object passed to > PyObject_CallObject? Yes. > 3) Is it because of the big value (2299265.500000) I am trying to > convert from double to float using PyFloat_FromDouble? > > //========================= code reduced for readability > =============== > switch(ndtyp){ > case(INT_T): > { > printf("PyInt_FromLong val %d, var %s > \n",inputVar.nionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > val = PyInt_FromLong(inputVar.nionum); > break; > } > case(LONG_T): > { > printf("PyLong_FromLong val %ld, var %s > \n",inputVar.lionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > val = PyLong_FromLong(inputVar.lionum); > break; > } > case(FLOAT_T): > { > printf("PyFloat_FromDouble val %f, var %s > \n",inputVar.fionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > val = PyFloat_FromDouble(inputVar.fionum); > break; > } > case(DOUBLE_T): > { > printf("PyFloat_FromDouble val %f, var %s > \n",inputVar.dionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > val = PyFloat_FromDouble(inputVar.dionum); > break; > } > case(STRING_T): > { > printf("PyString_FromString val %s, var %s > \n",inputVar.ioString,pEvalFunc->pExprVarsArray[nCtr].szVarName); > val = PyString_FromString(inputVar.ioString); > break; > } > default: > printf("Unknown data type [%d] for %s\n",ndtyp,pEvalFunc- > > >pExprVarsArray[nCtr].szVarName); > > } > if(!val){ > ret = -1; > printf("Failed to convert %d %s to PyObject\n",ndtyp,pEvalFunc- > > >pExprVarsArray[nCtr].szVarName); fflush(stdout); > > Py_XDECREF(pTuple); > break; > } > PyTuple_SetItem(pTuple, nCtr, val); > Py_XDECREF(val); Don't do this - PyTuple_SetItem() steals a reference to val. > } > // all variables are set, call Python function > Py_XINCREF(pTuple); Why do this? > PyObject *pResult = PyObject_CallObject(pEvalFunc- > > >pPyEvalFunction,pTuple); > > Py_XDECREF(pTuple); Why do this? > if(PyErr_Occurred()){ > PyErr_Print(); > } else { > char* plevel = NULL; > if(NULL != (plevel = PyString_AsString(pResult))){ > ret = 0; > sprintf(szEvalResult,"%s",plevel); > } > } > Py_XDECREF(pResult); pTuple will now have the same number of references as when you started the above code, so you may want to Py_DECREF() it. Phil From littlesweetmelon at gmail.com Fri Jan 18 00:22:39 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Fri, 18 Jan 2008 13:22:39 +0800 Subject: [python] How to detect a remote webpage is accessible? (in HTTP) Message-ID: Howdy, all, I want to use python to detect the accessibility of website. Currently, I use urllib to obtain the remote webpage, and see whether it fails. But the problem is that the webpage may be very large; it takes too long time. Certainly, it is no need to download the entire page. Could you give me a good and fast solution? Thank you. -- ShenLei From bronger at physik.rwth-aachen.de Sun Jan 27 13:41:07 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 27 Jan 2008 19:41:07 +0100 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <873asjdscc.fsf@physik.rwth-aachen.de> Hall?chen! Wildemar Wildenburger writes: > Andr? wrote: > >> Personally, I like the idea you suggest, with the modification >> that I would use "." instead of "@", as in >> >> class Server(object): >> def __init__(self, .host, .port, .protocol, .bufsize, .timeout): >> pass > > I like :) > > However, you can probably cook up a decorator for this (not > certain, I'm not a decorator Guru), which is not that much worse. > > Still, I'd support that syntax (and the general idea.). Well, you save one or two lines per class. Not enough in my opinion. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From mail at timgolden.me.uk Tue Jan 15 04:05:58 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jan 2008 09:05:58 +0000 Subject: hide object property from dir() function? In-Reply-To: References: Message-ID: <478C7776.5090405@timgolden.me.uk> jerryji wrote: > Sorry for this newbie question, I was puzzled why the existing > property of an object is not shown in the dir() function output. The under-development version of Python (2.6) allows for a __dir__ magic method by which the class implementer can return whatever he wishes from a dir (). This is to help, for example, modules like my WMI one which makes heavy use of __getattr__ magic to proxy across Windows COM attributes. This, in turn, helps editors and IDEs which can provide popup lists of attributes etc. All that said, I don't believe it takes any automatic account of properties. TJG class X (object): def __init__ (self, a): self.a = a print dir (X (1)) def __dir__ (self): return ['x', 'y', 'z'] X.__dir__ = __dir__ print dir (X (2))
From duncan.booth at invalid.invalid Wed Jan 23 04:30:28 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jan 2008 09:30:28 GMT Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? References: Message-ID: Kristian Domke wrote: > foo = (not f and 1) or 0 > > In this case f may be None or a string. > > If I am not wrong here, one could simply write > > foo = not f > Yes, it sounds pretty silly, and not just on the level you spotted. The only difference between the two expressions is that the original sets foo to an integer whereas your version sets it to a bool. So the question of which is most appropriate actually comes down to what foo is being used for. Is there really some code which requires a numeric value of 1 when f is None or an empty string and a value of 0 for any other string? I can't think offhand of any obvious situations where you would want that. My guess is that foo is being used later as a condition in an 'if' statement. If you really do need an integer then in Python 2.5+ another way to write it would be: foo = 0 if f else 1 Also 'foo' is a silly name since it gives no indication at about the purpose of the expression, but I'm hoping that was just you paraphrasing the code you posted. Ok, I just looked at the code, it is indeed being used as a boolean, so self.useProgressBar = not f or self.useProgressBar = f is not None if you want to be more specific about checking for None. From bignose+hates-spam at benfinney.id.au Mon Jan 14 23:21:12 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 15:21:12 +1100 Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> <874pdgf2wo.fsf@benfinney.id.au> <44c962f1-184c-4f79-9ce8-84bd69f9ef64@f47g2000hsd.googlegroups.com> Message-ID: <87odbnd8hz.fsf@benfinney.id.au> George Sakkis writes: > On Jan 14, 5:39 pm, Ben Finney > wrote: > > > I think of NotImplemented as equivalent to None; it's useful as a > > sentinel value to set an attribute to in (e.g.) an abstract class. > > My guess would be that it is more of an implementation performance > decision than semantic. Checking 'if result is NotImplemented' is much > faster than guarding the call with a try/except NotImplementedError > block Even better is not to check at all, and just try to use the return value as normal. If it's the NotImplemented object, exceptions will soon be raised that explain the problem. EAFP, dotcha know. > Semantically though, 'return NotImplemented' looks odd compared to > 'raise NotImplementedError'. I use 'NotImplemented' as the default value for something that *shouldn't* be used as-is, because the *programmer* needs to do more work on the implementation. This either means an abstract base class, that must be inherited from to override the attribute; or a section of code that needs more work directly to complete it. I have never written 'return NotImplemented' except for the implementation of __cmp__ and friends. I can't think when that would be a good idea as compared to 'raise NotImplementedError("explanatory text")' (note: create an instance, don't just raise the class object). -- \ "To succeed in the world it is not enough to be stupid, you | `\ must also be well-mannered." -- Voltaire | _o__) | Ben Finney From sjmachin at lexicon.net Sat Jan 26 01:53:16 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 22:53:16 -0800 (PST) Subject: Doesn't know what it wants References: Message-ID: On Jan 26, 5:32 pm, Jeroen Ruigrok van der Werven wrote: > -On [20080126 06:26], Tim Rau (bladedpeng... at gmail.com) wrote: > > >Line 147 reads: > > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) > > I think it expects something like: > > # badly named variable, pick something better depending on context > temp = vec2d(0, 0) > cp.cpMomentForCircle(self.mass, .2, 0, temp) That *cannot* give a different result in Python. The called function will be presented with *exactly* the same object as the OP's code does. From fredrik at pythonware.com Sun Jan 27 13:35:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Jan 2008 19:35:53 +0100 Subject: ElementTree.fromstring(unicode_html) In-Reply-To: <58b4d6e5-da52-4247-9892-3fbcfd0f1979@m34g2000hsb.googlegroups.com> References: <58b4d6e5-da52-4247-9892-3fbcfd0f1979@m34g2000hsb.googlegroups.com> Message-ID: globophobe wrote: > In [1]: unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f > \u3044\r\n' > > I need to turn this into an elementtree, but some of the data is > japanese whereas the rest is html. This string contains a
. where?
is an element, not a character. "\r" and "\n" are characters, not elements. If you want to build a tree where "\r\n" is replaced with a
element, you can encode the string as UTF-8, use the replace method to insert the element, and then call fromstring. Alternatively, you can build the tree yourself: import xml.etree.ElementTree as ET unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f\u3044\r\n' parts = unicode_html.splitlines() elem = ET.Element("data") elem.text = parts[0] for part in parts[1:]: ET.SubElement(elem, "br").tail = part print ET.tostring(elem) From noel at webeok.org Tue Jan 15 16:09:14 2008 From: noel at webeok.org (noel at webeok.org) Date: Tue, 15 Jan 2008 13:09:14 -0800 (PST) Subject: Running Multiple Versions Message-ID: <795bedbb-e21e-49b8-856d-bce83a5fced3@f10g2000hsf.googlegroups.com> Hi, We are windows shop with some unix servers as well. We run 2.4.1 and want to begin migrating to 2.5.1. I am looking for information dealing with having more than one version of python on a server at one time. I believe this is called side-by-side and all that is needed to select a version on a windows box is to set the path to the desired version of python prior to launching the script. Does this sound correct? Is there doc online that describes this? For windows, has anyone come up with a way to have the script launch the correct version at load time - similar to the she-bang method used in unix? Thanks Noel From bearophileHUGS at lycos.com Wed Jan 9 14:54:02 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 9 Jan 2008 11:54:02 -0800 (PST) Subject: Converting a bidimensional list in a bidimensional array References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> Message-ID: <005679e9-c355-4e0a-872c-e0dae3181fd0@x69g2000hsx.googlegroups.com> Santiago Romero: > - Speed Performance: Do you think that changing from list to Array() > would improve speed? I'm going to do lots of tilemap[y][x] checks (I > mean, player jumping around the screen, checking if it's falling over > a non-zero tile, and so). First of all: if you have enough memory to use a python list, then I suggest you to use a list. That said, often the best way to know the speed is to write a little testing code. Often python lists are faster than array.array (maybe because python lists actually contain pyobjects). If you want an array.array to be faster than a list you can use Psyco. Bye, bearophile From over at thepond.com Sun Jan 27 03:58:01 2008 From: over at thepond.com (over at thepond.com) Date: Sun, 27 Jan 2008 08:58:01 GMT Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> Message-ID: On Fri, 25 Jan 2008 17:44:07 -0800 (PST), ajaksu wrote: >On Jan 25, 11:36 pm, ajaksu wrote: >> On Jan 25, 11:10 pm, o... at thepond.com wrote: >[...] > >Gaah, is this what's going on? > >ajaksu at Belkar:~$ cat error.txt >This is not assembler... > >ajaksu at Belkar:~$ ndisasm error.txt >00000000 54 push sp >00000001 686973 push word 0x7369 >00000004 206973 and [bx+di+0x73],ch >00000007 206E6F and [bp+0x6f],ch >0000000A 7420 jz 0x2c >0000000C 61 popa >0000000D 7373 jnc 0x82 >0000000F 656D gs insw >00000011 626C65 bound bp,[si+0x65] >00000014 722E jc 0x44 >00000016 2E db 0x2E >00000017 2E db 0x2E >00000018 0A db 0x0A > >:/ not sure what you're saying. Sure looks like assembler to me. Take the '54 push sp'. The 54 is an assembler opcode for push and the sp is the stack pointer, on which it is operating. From g.usar.t at hotmail.es Sat Jan 12 21:05:25 2008 From: g.usar.t at hotmail.es (gustarmas) Date: Sat, 12 Jan 2008 18:05:25 -0800 (PST) Subject: HONESTO AND VERY EASY MONEY!!!!!what to in a year and did so in less than a month Message-ID: <9e6c4fac-e250-4f92-86bd-5b44fa493ef6@l1g2000hsa.googlegroups.com> ! EUROS OR INVEST 30 $ 30 DOLLARS. EARN MONEY AND SO $ HONESTA AND QUICK! Fec A FRIEND (A) has: Monday, 26 OCTOBER 2007 HOLA Read this notice, surely you. This is a great opportunity, to the extent that participants are HONESTOS SOLIDARIOS And, since there is NO INTERMEDIATE only Direct contact between persons interested ... This is a way Honest attempt to improve our economic situation. It will take you About 5 minutes to read this article and you will see that you Interested. If you really want to know if this works, just look at eople how many p Is doing this ... If this does not convince you, nothing will not !!!!!... Let this opportunity pass. If you want to read it several times until Convince you ... I do not believe, but I am now convinced and Improving my ECONOMIC SITUATION !!!!!, which was quite Bad ... It has nothing to lose, but much to gain. You will notice that something is truly ingenious, it is you and Will earn a few euros or dollars and only need to invest! $ 30 euros or $ 30 dollars! ... And this is nothing compared to what Or report you could win if you take a little time and Sacrifice ... Remember that people only need SERIOUS, AND WITH GOOD HONESTAS INTENSIONES ...!! BUSINESS FOR MAKING THIS IS NOT MAKE THE ROMPA CHAIN !!... NOW YOU EXPLICO AS CONOCI ON THIS SYSTEM ... While sailing in a page news himself as what you You are doing now ... I found an article like this, Which read: "! YOU CAN WIN THOUSANDS OF DOLLARS IN FEW WEEKS WITH AN INVESTMENT OF $ 30 OR $ 30 EUROS DOLLARS !"... Then I thought: "How OH, NO, MORE ANOTHER SCAM?", But like most Us, "curiosity might more", then went on reading ... "You send $ 5 euros, or $ 5 dollars to each of the names And addresses mentioned in this article ... "After this, write your NAME AND ADDRESS at the end of the list, Replacing the # 6 and I sent this article or put in at least 200 NEWSGROUPS (there are thousands of these on the Internet )"... After thinking over and over again and consult with friends, I decided to try it, I thought that the only thing that could lose were 6 Mail stamps and $ 30 euros or dollars ... As many of us probably felt a little concerned about the Legality of this. Then I consulted the Local Mail and I Confirmed that, in fact it was legal !!!!... I was astonished and My immediate investing $ 30 euros ... INMAGINENSE THAT !!!!!... Several days Later, I began to receive mail MONEY !!... I was happy as a child with a new toy and very surprised !!!!!... And I thought that this would end in a few days and tried to forget the Matter, in any case had already recovered investment, but the money Still coming !!!!!... In my first week I made between $ 100 and $ 300 Euro. By the end of the second week, had a total of $ 5000 (thousand euros )!!!!!... NOT BELIEVE PODIA !!!!!... In the fourth Week, $ 25,000 (twenty five thousand euros) and were still coming !!!!!. In the fourth week, I had a total of $ 65000 euros and this continues Arriving each day, the faster (in my house is the opening pass Envelopes and I getting "NEWSGROUP"). THIS IS SERIOUSLY PUSO ... NOW PERMITEME EXPLICARTE THIS AND HOW IT WORKS THE MOST IMPORTANT, THE EXCELENTEMENTE WHY IT WORKS: Step # 1: Get 6 sheets of paper and write to each one of them "PLEASE INCLUIRME AT ITS LIST OF CORRESPONDENCE OR E-MAIL. "Then write Your NAME, ADDRESS AND EMAIL (E-MAIL). NOTE: This LEGAL is what makes the system since it is paying for the Service to be included on a mailing list. Now get 6 tickets for $ 5 euros, or $ 5 and enter the 5euros dollars or an envelope with the road, enveloping the ticket with the Sheet, so that the ticket is not through on !!... It is better that the role is of a dark color to prevent thefts Correlation. ????? SL SUMAMENTE IMPORTANT THAT !!!!! Otherwise Way, the people working in the mail, which could detect Deals with money and stay with the thousands of envelopes you go Coming ... What you are doing is creating a service and as such, it does FULLY LEGAL !!!!!... From now on, you are not mand?ndole five five EUROS OR DOLLARS someone without any reason, they pay five dollars or dollars for a SERVICE LEGITIMO !!!!! . You forward the 6 envelopes to the following addresses: 1) John Alexander Valverde del Carpio. Jr. Spring j-6, Campo Marte, Paucarpata, Arequipa, Peru. 2) Alexander Roldan Francisco Romero. Carrera 65 # 10 - 102, Barrio El Limonar Cali - Colombia. (3) Humberto Zapata Sotelo. Jr. Macar? No. 279 Urb. Zarumilla, St. Martin de Porres, Lima, Peru. Postcode Lima # 31. (4) Sergio Urquiaga Gallegos. Av. Alameda del Corregidor 1234 Dep. 102. Urb. Sirius - La Molina. Lima-Peru (5) Agramonte Osiris Ricardo Pena. John Paul Pina Street # 02, Villa Flores. San Juan de la Maguana, Dominican Republic. Postcode San Juan de la Maguana # 72000. (6) Gustavo Artigas Fernando Lafuente, neighborhood san martin street Paysand? esq. Island of Flores Maldonado Uruguay Step # 2: Now remove the # 1 on the list and move the other names Numbers up (# 6 becomes the # 5 and # 5 is Becomes the # 4 and so on) and add your NAME AND ADDRESS as # 6 on the list. Step # 3: Change anything he deems necessary in this article, but Tries to keep as close as possible to the original. Now enter or Publish your article in at least 200 NEWSGROUPS (200 Announcements). There are more than 24000000 of Newsgroups on the Internet. Just 200 as a minimum, but the more put this letter with your data Newgroups more, the better the chance of receiving money as aid. HOW TO MANAGE THE NEWSGROUPS (NEWSGROUPS) 1 .- You do not need to write this letter to all yours Own. Just put your cursor at the beginning of this letter, please Click with the left mouse button and let it pressed; download it Until the end of the letter and release the mouse button. The entire letter should be "shaded". Then make a "clicking" The Right mouse button anywhere in the shaded part and COPY COPY or selected. This will cause the entire letter is at the Temporary memory your computer. 2 .- Open a new file in NOTEPAD (Notebook) or WORD ... Make Click with the right mouse button (Right click) and select PASTE or PEGAR ... GRABE or SALVE file with the name you want and you It can be identified at any time ... Since then Will have this letter on your computer and you can add your name in the # 6 on the list following the instructions that appear more Above. 3 .- (saved) recorded Taking this letter on your computer, every time As you like, you can add or change anything without problems. FOR THOSE WHO USE INTERNET EXPLORER 4 .- Go to "NEWSGROUPS" (Newsgroups), and select "POST AND ARTICLE "or" WRITING NEW MESSAGE / DISCUSSION. " 5 .- Load, look, call or invoke the rule that kept Previously. 6 .- Select the entire contents of the file containing the Letter and copy it using the same procedure described Above ... Back to "NEWSGROUPS and choose NEWS TO 'O' NEW DISCUSSION, "in this way, you are creating the space for power PEGAR the contents of the letter. 7 .- Press the "POST" or "SEND MESSAGE". FOR WHICH MANEJAN NETSCAPE 4 .- Within the programme NETSCAPE, go to the window titled "WINDOW" and select "NetscapeNews" ... Then go to the menu "OPTIONS" and select "SHOW ALL NEWSGROUPS" ... Then you will see a List all of its Server Newsgroups ... Then Click on any Newsgroup ... This Newsgroup click Under "TO NEWS", which should be up in the extreme Left of the page ... Newsgroup This will take you to the box Messages. 5 .- Fill this space. This is the title everyone will see that when To travel through the list of a particular group. 6 .- Mark or select the entire contents of the file Contains the letter and copy it using the same procedure described Previously .... Back to Newsgroup, "TO NEWS" and you are creating And empastando this letter within your program or "POSTING. 7 .- Press "SEND", which is in the top left corner and You have completed your first Newsgroup. .....????? CONGRATULATIONS !!!!!..... .....????? THAT IS ALL !!!!!..... IF YOU ACHIEVE .....????? PUDE, YOU ALSO CAN !!!!!..... .....????? FORWARD !!!!!..... All you have to do is meterte in different Newsgroups (Newsgroups) or plaster and add your text. Once you have Practice, only takes about 30 seconds for each ANNOUNCEMENT. It is further recommended that when publishing the description of this Article, try to give a name to "catch" or call the lot Care, such as: "Go NEED MONEY FAST? ... READ THIS ARTICLE" "Go NEED MONEY TO PAY YOUR DEBT?", "BAJE ARCHIVE AND READ THIS HOW CAN RECEIVE MONEY BY MAIL, "and so on., And not:" WINS MILLION IN ONE WEEK, "that nobody takes seriously. REMEMBER: IF YOU GET MORE NEWSGROUPS, MORE MONEY AND ANSWERS RECEIVE !!!!!... BUT MUST ENTER IN AT LEAST 200 NEWSGROUPS ... AND NOW THIS !!!!!... Another way would be to use your CONDUCT OF E-MAIL and send All your contacts this message. It also can expand Chain. You will be receiving money from all over the world in places that neither Known in a few days !!!!!... Eventually you will want to rent a P. O. BOX. (Zip), the number of envelopes that will go Receiving !!!!!... (((ASEG?RATE THAT ALL ADDRESSES ARE CORRECT )))... Now the WHY of all this: Of 200 envoys, say that only Receive 5 replies (very low example). Then I made $ 25 euros, or $ 25 dollars with my name in the # 6 of this letter. Now, each One of the people who sent me $ 5 euros, or US $ 5, also Make a number of 200 Newsgroups or ads from the list and only 5 persons respond to each of the original 5, this makes $ 125 Euros or dollars more than I receive. Now, these 25 individuals put a Minimum of 200 listings with my name on the # 4 and only received 5 responses each. It would make another $ 625 euros or dollars Additional. Now, those 125 people put a minimum of 200 groups with my name In the # 3 and only get 5 replies each person, I Get an additional $ 3,125 euros or dollars !!!!!, OK. Here is the More fun part, each of those 625 people put their letters Other 200 groups or ad with my name on the # 2 and each 5 receives an answer, and this makes me get $ 30,625 euros or An additional $ !!!!!... These 3125 people send this message To a minimum of 200 listings, with my name on the # 1 and only 5 People respond to the 200 ads, this means that I get $ 78,125 euros or dollars !!!!!. From an investment of $ 30 euros or dollars, do not believe it is FABULOUS !!!!!?????. And as I said earlier, that only 5 people respond to 200 groups or advertisements (the actual average is 20 to 30 People !!!!!)... IF YOU WANT A calculation SACA !!!!!... IF ONLY 15 PEOPLE RESPONDIERAN ... DAR?A THIS AS A RESULT: Being in a position # 6 ...=$ 78.00 Being in a position # 5 ...=$ 768.00 Being in a position # 4 ...=$ 12.288.00 Being in a position # 2 ...=$ 184.552.00 ????? Now comes the good, do not be afraid !!!!!: In the # 1 ........ ((((( $ 2.764.800.00 ))))). !!!!! S?????, ALMOST THREE MILLION DOLLARS OR !!!!!... THE IMPOSSIBLE BELIEVE, TRUE !!!!!?????... BUT WITH SOME OF DEDICATION, AND TIME EFFORT WE CAN ACHIEVE !!!!!... Some people come to think ... "And if anyone answer me ?"... QUEEEEE !!!!!... What is the likelihood that this will happen? ... If Thousands and thousands of people HONESTAS (like us) looking for a How to have financial independence and pay their debts !!!!!... And Are willing to try. Because if I say "NO WORSE TO FIGHT WHICH ARE NOT !".... This is a fact that you may be interested: There are an estimated 20000 to 50000 new Internet users ALL DAILY (THROUGHOUT THE WORLD) ... REMEMBER TO DO SO HONESTA, CLEAN AND PROPER and operate safely !!!... *** In step: "! ONLY THE HONESTY AND INTEGRITY OF PARTICIPANTS CAN MAKE THAT THIS OPERATING SYSTEM. "As you may have Noticed, there is no middleman "MILAGROSO" multiply the Money ... That intermediary each of the individuals involved This "FLOW OF MONEY" ... So, the only way that this Not work, is that unscrupulous individuals publish article WITHOUT SEND MONEY those concerned. Now if they ALL OR MANY This evil act and it is logical that this wonderful idea will not work As it should be ... So APELO YOUR HONESTY AND INTEGRITY ... And remember, There is a divine law which says that: "THERE THAT GIVE TO RECEIVE" ... !!!!! BENDICIONES SUERTE !!!!!..... FOR ALL AND Reply to author Forward From http Fri Jan 11 00:11:08 2008 From: http (Paul Rubin) Date: 10 Jan 2008 21:11:08 -0800 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <7xejcplzf7.fsf@ruckus.brouhaha.com> Mike Meyer writes: > data_out = [[] for _ in data_in] > ... > But I'm curious - what's the difference between the "foreach" you have > in mind and the standard python "for"? The "for" loop, like the list comprehension, pollutes the namespace with an index variable that's not used for anything. I prefer genexps: data_out = list([] for x in data_in) From http Thu Jan 10 21:28:45 2008 From: http (Paul Rubin) Date: 10 Jan 2008 18:28:45 -0800 Subject: Minimalistic Software Transactional Memory References: <13lm7nd85v7jk70@corp.supernews.com> <13lmemmsnjuhm04@corp.supernews.com> <6b14fcf9-9549-422b-b837-afa5b32cf7f2@n20g2000hsh.googlegroups.com> Message-ID: <7xbq7tccyq.fsf@ruckus.brouhaha.com> Fuzzyman writes: > STM isn't lock free - it just abstracts the locks away from the > 'user'. You still need to lock around committing the transaction. The idea is that readers don't need locks. They just look at the version number before they start reading and after they finish. If the number didn't change, the read was successful. If it changed, they have to retry. On multiprocessor systems this relies on an instruction like CMPXCHG for writers to increment the version number. Otherwise it requires a lock separate from the version number, and multiple operations on the lock. From Lie.1296 at gmail.com Mon Jan 21 12:26:35 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 21 Jan 2008 09:26:35 -0800 (PST) Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> <478e1e3e$0$18054$426a74cc@news.free.fr> <34aa1a1f-2034-471d-91ee-2a758dab555b@f47g2000hsd.googlegroups.com> <47949466$0$18516$426a34cc@news.free.fr> Message-ID: <4e3c42c8-a198-4897-86fd-98ab254bcb94@q77g2000hsh.googlegroups.com> > > Please stop taking my words to its letters. > > So we're supposed to actually guess what you really mean ??? That's what human does, otherwise you'll "Fail the Turing Test". > >> Personally, I've seen many C++ programs with complex class designs > >> where it definitely helps to consistently use "this->". I cannot > >> remember all local (and global) variables in bigger methods. > > > In that case, you have the _option_ to do it. > > Make no sens when maintaining code wrote by someone that didn't use this > 'option'. > > (snip) > > > > >>>> it's the first argument of the function - which usually happens to be > >>>> the current instance when the function is used as a method. > >>> And that's the point, self (or anything you name it) is almost always > >>> the current instance > >> # this is a plain function. In this function, > >> # 'obj' can be whatever that happens to have a (numeric) > >> # 'stuff' attribute > >> def func(obj, arg): > >> ? ?return (obj.stuff + arg) / 2.0 > > >> # this is a class with an instance attribute 'stuff' > >> class Foo(object): > >> ? ? def __init__(self, bar): > >> ? ? ? self.stuff = bar + 42 > > >> # this is another (mostly unrelated) class > >> # with a class attribute 'stuff' > >> class Bar(object): > >> ? ?stuff = 42 > > >> # this is a dummy container class: > >> class Dummy(object): pass > > >> # now let's play: > >> import new > > >> d = Dummy() > >> d.stuff = 84 > >> print func(d, 1) > > >> d.baaz = new.instancemethod(func, d, type(d)) > >> print d.baaz(2) > > >> f = Foo(33) > >> print func(f, 3) > >> Foo.baaz = func > >> f.baaz(4) > > >> print func(Bar, 5) > >> Bar.baaz = classmethod(func) > >> Bar.baaz(6) > > >>> ?and that makes it functionally the same as Me and > >>> this in VB and Java. > >> Depends on the context, cf above !-) > > > Please again, stop taking letters to the words, I don't meant them to > > be exactly the same, rather the same would meant that they generally > > can be considered equal, > > If you still think that way after having read the above code, then I > can't help. We obviously don't share the same mental model here. I don't get what you're trying to meant, in that piece of code self is used in the regular way, in a regular context. > > exceptions exists of course. And btw, I don't > > understand what you meant by your example, they seemed to be a > > completely OK program for me, > > Indeed it's ok (even if totally useless by itself). The point is that > 'self' (or whatever you name it) is just and only the first argument of > a function, period. And it is... but I still don't get what you meant > > even though it's a bit confusing to > > follow[2]. > > Nothing in it should be confusing to anyone having a decent knowledge of > Python's object model IMHO. > > > [2] btw, the reason it's a bit confusing to follow is one of my > > points: It is a Bad Thing(tm) to use the same name for different > > variables > > Where do I "use the same name for different variables" here ? It's not confusing in the way of object model, but in the way that you used meaningless names in overloaded manner. > > even in a language like Python that enforce explicit naming > > of classes > > Python doesn't "enforce" explicit name of classes - IIRC, there are ways > to instanciate anonymous class objects. But I definitively don't see how > this relate to this discussion. We're not talking about anonymous class objects here, and I'm sure you actually understand what I meant by "naming the class" from previous discussions. > Yes, I know, "please guess what I mean" !-) but sorry, there's no sens > discussing a technical point without using accurate and appropriate > technical naming of technical concepts invlved. Well, it's not my fault for being born as a non-native speaker of English, sometimes what I meant might goes a bit off from what I write. Anyway, human languages aren't designed to be fully unambiguous, so it is natural for human to provide a margin of errors when speaking to each other, well unless you're not a human... > >>>>> Most other languages > >>>>> 1) automatically assign the containing class' object > >>>> s/containing class' object/current instance/ > >>>>> in a keyword > >>>>> (Java: this, VB: Me) behind the screen, > >>>> That's not very far from what a Python method object does - > >>>> automatically assign the current instance to something. The difference > >>>> is that Python uses functions to implement methods (instead of having > >>>> two distinct contructs), so the only reliable way to "inject" the > >>>> reference to the current instance is to pass it as an argument to the > >>>> function (instead of making it pop from pure air). > >>> It isn't very far, but Python makes it obvious about the assignment > >>> (not behind the screen). > >> Exactly. And given both the simplicity of the solution and what it let > >> you do, that's a *very* GoodThing(tm) IMHO. > > > I agree, it's a Good Thing but it doesn't make the point less pointy, > > the difference between Me/this and self is just the explicit > > assignment. Other things that is possible because of the explicit > > assignment is just a "coincidence" of design choice. > > Are you sure ? As far as I'm concerned, I think that the design choice > somehow results from what it makes possible. It's correct, IF you see it traversing from the past, when many design choice is being made for any possible features that is required. If you dumped the past for a while, it is just a "coincidence" of design choice. > >>> And it is always a Bad Thing(tm) to use the same name for two > >>> variable in the class and in function (which is the main and only > >>> source of possible ambiguity) in ANY language, even in Python. > >> Ho, yes.... Like, this would be bad ? > > >> class Person(object): > >> ? ?def __init__(self, firstname, lastname, birthdate, gender): > >> ? ? ?self.firstname = firstname > >> ? ? ?self.lastname = lastname > >> ? ? ?self.birthdate = birthdate > >> ? ? ?self.gender = gender > > >> C'mon, be serious. It's often hard enough to come with sensible names, > >> why would one have to find synonyms too ? Try to come with something > >> more readable than the above, and let us know. Seriously, this braindead > >> rule about ?"not using the same name for an attribute and a local var" > >> obviously comes from languages where the "this" ref is optional, and > >> FWIW it's obviously the wrong solution to a real problem (the good > >> solution being, of course, to use the fully qualified name for > >> attributes so there's no possible ambiguity). > > > The code fragment you've given way above (about the Foo, Bar, bazz, > > and func) also suffers from the bad habits of using the same name for > > different variables. > > Where ? And how does this answer the question above ? > > And it's not a "braindead" rule > > The way you express it, and as far as i'm concerned, it is, definitively. Perhaps I forgot to say that always might still have exceptions. > > The example you've given IS the most readable form since the function > > is _simple_, consider a function that have complex codes, possibly > > calculations instead of simply assigning initial values I'm sure you'd > > slip up between the self.* variables and the * variables once or > > twice, > > *you* would perhaps have this problem. And you would indeed have this > problem in Java or C++. In Python, this problem just don't exist. No it exists in any language, the way to avoid it is by good class design. > > possibly becoming the source of hard-to-find bugs. > > Consistant and intelligible naming is quite another problem. And it's > too much dependant on the context, language, domain and whatnot for any > rule like your one above to be universally applyable. It is universally applicable, with some exceptions of course, such as in a field where there is no agreed naming convention yet. > > > And in languages that doesn't enforce explicit naming of classes, > > I still don't understand how all this relates to the naming of class > objects ? > > Oops, sorry: you meant "in languages that has implicit instance > reference available in methods" ? Python doesn't have it, so any rule > deriving from this "feature" is out of scope here. > > > ?when > > there is the two or more same names, the one with the smallest scope > > is picked, so in _simple_ functions, the trick of using full qualified > > names and overloaded local names is still possible and feasible. In > > complex functions, the trick fails even in Python, because even if > > Python and our full-concentration-brain is aware of the difference > > between self.* and *, our spreaded-concentration-brain that is > > scanning the code for the source of bugs might get stumbled on the > > confusing use of self.* and *. > > Here again, *you* may have this problem. I don't, since I always used > explicit instance reference. I don't have that much of a problem, I only pointed out that it is possible to miss the names overloading in quick scanning. The reason why you never get stumbled is possibly because your brain memorizes the names and doesn't even understand what a name actually meant. This halved the reason of spending some time to find a meaningful name. With your brainset, it is just possible to create a program fully with names like foo and bar and never get stumbled. In this case, it excels, but it's a poor man's way of trying to be smart. > >>>> Anyway, I actually know 3 languages (4 if C# works the same) that has > >>>> this implicit 'this' (or whatever the name) 'feature', and at least 5 > >>>> that don't. So I'm not sure that the "most other languages" qualifier > >>>> really applies to point 2 !-) > >>> What's this 5 languages? > >> Smalltalk, Python, PHP, javascript, Ruby. I don't remember how Scheme, > >> CLOS and OCaml handle the case. > > > Among all them, only Javascript is considerably mainstream. > > Is that a joke ? PHP is probably the most used language for web apps > (server side of course). And Python is certainly not an obscure unknown > geek-only language no more. But anyway: you were talking about "most > other languages" - not "most mainstream languages". Yes, I'm aware that Python and PHP indeed have larger user base than perhaps smalltalk and Ruby, but nevertheless they're middle sized. What's I'm talking about mainstream is large as in large, not medium. PHP's domain has lots of competition, ASP, JSP, CGI, etc and this market is very fragmented, even though server-side scripting plays important role in the Internet, the role of each language is lessened because of the fragmentation making none of them mainstream enough. Python is shaded by Java in the market for ultra portable (VM) language. And I'm not talking about Smalltalk and Ruby here. > >>> Are they a mainstream, high-level languages > >>> or lesser known, low-level languages? C-family, Java, and Basic are > >>> the Big Three of high-level programming language. > >> None of C, C++, Java nor Basic qualify as "hi-level". C is the lowest > >> possible level above assembly, C++ is often refered to as an "object > >> oriented assembler", Java is way too static, crippled, verbose an > >> unexpressive to qualify as "hi-level" (even if it suffers from some > >> problems usually associated with higher level languages). I won't even > >> comment on basic (is that really a language at all ?). > > > Your criteria on being high-level is simply just odd. > > > My criteria on being hi-level seems quite common: automatic memory > management, portability, "rich" builtin data types, functions as first > class citizens, lexical closures, strong introspection features, strong > metaprogramming support, etc... We're talking language-wise here, not the implementation, and those criteria are for implementations. It is the case where we blindfold our eyes against "the things behind" and see only the language from the front. Yeah, perhaps "the things behind" would have some effect to the front side, like it is possible to create C with automatic memory management with little change in the language itself, it's possible to have more built-in datatypes than the standard set without major change in language itself. These are the criteria for language-wise comparison. > > The rest of the > > world recognizes C-family, Java, and Basic as high-level languages. > > C was "hi-level" wrt/ assembler, indeed. And Java is "hi-level" wrt/ > C++. Ho, and _please_ don't get me started on basic !-) And the world is content with that. C is probably the lowest shade a high level language could be, but it is still a high-level. > > If I have to say it, Python is actually lower level than Basic. Language-wise, indeed it is. Implementation-wise, Python might be higher than Basic. > > While > > Java is just below Python and C and C++ is just below Java. Why do I > > consider Basic the highest-level? Because it is the cleanest to scan > > (no confusing symbols, i.e. no curly braces, no confusing use of > > parens (Python uses (), [], and {}, VB only use ()[3]), > > Basic != VB. There are quite a few other basics here. I'm aware of that, but VB is the one with the largest user base, and I think it could be used to represent the language as a whole. And VB.NET is one with possibly the highest shade of level among other Basics. > Now if you choose this criteria, you may want to learn some Lisp dialect. > > In what way C++ resembles an assembler? > C++ is some OO stuff bolted on a very close-to-the-metal language itself > designed to write operating systems, drivers and other low-level stuff. In what way is C++ close to the metal? It's very far actually, C- family don't have a one-to-one relationship with assembly or plain executable binary. > > Have you ever programmed in > > assembly? > > I did. And surely you'd realize that the level of C and assembly is very far, perhaps the furthest leap in programming language level. > > How hard is it to create a simple program in assembly? And > > how hard is it to create a complex program in C++ > Roughly the same, thanks to scoping rules, dependencies hell, lack of > automatic memory management and overcomplex features. By saying that you've revealed that you missed my point too far. There is no point to continue talking about A when you're talking about B. > > (which AFAIK is used > > by hundreds of mega projects including CPython)? > CPython - as the name implies - is written in C. And by saying that I'm sure you agree that even C, which is lower level than C++ is high-level enough to be used in large projects like CPython. I'm interested in seeing Python implemented in pure assembly, perhaps asmPython? > > And have you ever used Basic at all? > I did. And not only VB. > > Some programmers would instantly frown upon Basic, simply because they > > don't know that Basic is "just another language". > I've used at least four different variants of Basic. Then with such experience in Basic you should realize that Basic isn't much off from other languages. > >>>>> In VB, Me is extremely rarely used, > >>>> I used to systematically use it - like I've always systematically used > >>>> 'this' in C++ and Java. > >>> And that is what reduces readability. A proficient VB/C/Java > >>> programmer > >> There are quite a few proficient C/C++/Java programmers here. As far as > >> I'm concerned, I would not pretend being one - I just have a good enough > >> knowledge of C, Java and (alas) VB to be able to get up to speed in a > >> reasonnable time frame. > >> As a side note, the problem just doesn't exists in C, which has > >> absolutely no support for OO. > > When I said C, it might mean C and C-family, > When you say "C", it means "C" to everyone reading you. Depending on the context, it's easy to rule out which means what. > > so please stop > > misunderstanding me. > Please learn to express yourself clearly. If you say "X" when you mean > "Y", *you* are the one responsible for misunderstandings. This is human > communication 101 skill. Even computers are designed to tolerate errors in data transfer, then human is less intelligent than computers you say? > >>> would frown upon the extra, unneeded garbage as they > >>> thought it was clear already that the variable refers to a class-level > > >>> variable. > >> In C++, the canonical way to make this "clear" is to use the m_name > >> convention. There must be some reason C++ programmers feel a need for > >> this "extra, unneeded garbage" ?-) > > > In some cases, an extremely complex class that can't be fragmented any > > further, the m_ convention is surely useful, but in most cases you > > could skip them out. > > You "could" skip this convention, but it's really considered bad > practice by quite a lot of C++ programmers. Bad, because a lot of them are already accustomed to it and it have become a de facto "rules". > > And the canonical way to make this "clear" is not > > the m_ convention, it's the name itself. A well-designed class would > > choose names that is recognizable instantly from the name itself, even > > without the pseudo-name appended to it (or prepended). > > I await for your exemples. > > > btw you must have been memorizing names braindeadly, because the only > > way you could stumble on that is by memorizing names braindeadly. > > Names shouldn't be memorized, it should be inferred and memorized. For > > example, when you met a variable name firstname and lastname inside a > > class called Person, you'd immediately realize that it is Class Level > > variable because you know that the function you're currently working > > on use the name initialfirstname and initiallastname. > > Fine, I now have four names to handle, each of them being possibly an > argument, a local variable, a member variable or a global variable. Great. > > Sorry but I won't buy this. THAT'S the point. You are unable to infer that the name initialfirstname and initiallastname is a local variable, since it is quite impossible for something initial to be a member variable or global. If it is a global, it shouldn't be named initial, perhaps default, if it is member variable, it should be plain vanilla firstname and lastname. This is called inferring scope from name. > >>> As I've pointed out, there is little harm in class-level variable's > >>> implicit reference. > >> Have some working experience on any non-trivial C++ project ? > > > No > > I would have been surprised if you had answer otherwise. > > > (you could say I'm a student so I've never "worked"[1]). But I've > > done some medium-sized projects in other languages. > > > [1] If you understand the irony, you'd realized I was deliberately > > misunderstanding you > > Not sure. Don't cut my words apart, it's meant to be together or it lose its sense of humor. > > >>>>> Compare the following codes: > >>>>> VB.NET: > >>>>> Public Class A > >>>>> Dim var > >>>>> Public Function aFunction() > >>>>> return var > >>>> Add three levels of inheritence and a couple globals and you'll find out > >>>> that readability count !-) > >>> It's the mental model that have to be adapted here, if the current > >>> class is inheriting from another class, you've got to think it as > >>> names from parent class as it is a native names, so you don't actually > >>> need to know where the variable comes from > >> In C++ (and VB IIRC), it might as well be a global So sorry but yes, I > >> have to know where it comes from. > > > How many times would you use globals, it is a Bad Thing(tm) to use > > globals in the first case. > > It is, most of the time, indeed. > > The problem is that you rarely start a project from scratch - most of > the time, you have to work on legacy code. And you really seldom have > the possibility to do a major rewrite to fix all warts. But it is always possible to reduce the most critical of all of them. > > In some exceptional cases globals might be > > unavoidable, but it is trivial to work out that you have to reduce the > > amount of globals to a minimum, in almost any cases to a number you > > can use a hand to count with. > > That very nice, from a theoretical POV. That's alas just not how it > works in real life. A bit utopic, I agree, but it's always possible. > > And applying the hacks mentioned, why > > don't you use the m_ convention for globals, and retains the > > convenience of m_-free variables in your class variable. You use class > > variable much more often than globals, and in most projects class- > > level variable is used just as often as local-variable. > > The problem is not what *I* (would) do, but how is the existing code. > > >>> since knowing where it > >>> comes from is breaking the encapsulation > >> Nope, it's knowing what you're doing and how the piece of software at > >> hand is working. And FWIW, while data hiding is one possible mean of > >> encapsulation, it's by no way a synonym for encapsulation. > > > I agree that knowing an underlying class's implementation is useful > > (in fact, very useful) but what I'm talking is about should-ness, > > we > > shouldn't _need_ to know the underlying implementation, > > How can you hope to extend a class without _any_ knowledge of it's > implementation ? By knowing its interface is usually enough to extend a class. (USUALLY!) > >>> (which, in Python is very > >>> weakly implemented, which favors flexibility in many cases[1]). > >>> [1] In Python, it is impossible to create a completely private > >>> variable, which is the reason why the mental model of these other > >>> languages doesn't fit Python. > >> Never heard about the infamous '#define private public' hack in C++ ? > >> And don't worry, there are also ways to get at so called 'private' vars > >> in Java. > > > No, but it's violating the language's rule. > > Nope. It's just making use of some part of the language's rules. No, its a hack that should be illegal, a kind of abuse of rules. > > Python OTOH, provides > > formal ways to got to private vars. > > Python doesn't have "private vars" at all. THAT'S the point. Even __vars and _vars that are supposed to be (semantic-wise) the private variable of Python is accessible from outside while still using a formal ways of accessing it (instead of a hack) > > It's easy to keep track of globals, as you shouldn't have a > > lot of them even in a huge project. > > Can't you understand that starting a new project afresh is *not* the > common case ? But I'm sure even an old, dirty codes wouldn't usually have as much global as a twenty pages listing of globals. If they do, then just quit that job. > >>> As a final note: > >>> I don't think implicit class reference is superior to explicit class > >>> reference, neither > >> ... > > > I'm sure you don't believe it since I'm talking on implicit's side, > > but that's the fact, I just pointed you out that implicits do have its > > positive side (even if you don't consider them positive in _your_ > > book) but that doesn't meant I believe it is better than the other. > > > To clear things up: > > As a final note: > > I don't think implicit class reference is superior to explicit class > > reference, but I don't think the vice versa is true either. > > Once again : what classes have to do with this ? > > Seriously, how can you hope to be taken seriously when you're obviously > confusing such important concepts as instance and class ? I'm struggling with English as of now, so please make me more confused by having to choose the most proper terms, when it is easy to rule out what I meant. This is going to be my last two cents on this topic. I'm tired of this pointless discussion. We could like a language even though we have principal differences on how to see the language and how to think about it. From paddy3118 at googlemail.com Thu Jan 24 10:12:14 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 07:12:14 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: <32dfff9c-ec49-424d-8d56-0775f22740b2@i3g2000hsf.googlegroups.com> On Jan 24, 2:28 pm, Christian Heimes wrote: > Antoon Pardon wrote: > > That doesn't follow. The problem is not that x < nan returns False > > because that is correct since x isn't smaller than nan. The problem > > is cmp(x, nan) returning 1, because that indicates that x is greater > > than nan and that isn't true. > > Please report the problem. cmp(), min() and max() don't treat NaNs > right. I don't think that x < nan == False is the correct answer, too. > But I've to check the IEEE 754 specs. IMHO < nan and > nan should raise > an exception. > > Christian To a floating point interested layman such as I, treating not-a-number comparisons with floats should give the same result as comparing a fileobject (also not-a-number), with a float. Or does nan have /need a more domain specific interpretation? - Paddy. From jzgoda at o2.usun.pl Tue Jan 8 04:53:21 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 08 Jan 2008 10:53:21 +0100 Subject: Pet Store In-Reply-To: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com> References: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com> Message-ID: George Maggessy napisa?(a): > I'm an experience Java developer trying to learn Python. I just > finished the Python tutorial on python.org and I'm currently reading > the "Learning Python" book. However, if I could find something like a > simple web app with some best practices, such as those famous "Java > Pet Store" apps, I think that would help me to fill up some gaps in my > learning process. Does anybody know any app like that? TurboGears and Pylons both have "wiki" tutorials. Django has "poll" tutorial. There are plenty others on the web. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From bignose+hates-spam at benfinney.id.au Wed Jan 16 16:50:18 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 17 Jan 2008 08:50:18 +1100 Subject: import from question References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> <478d04d4$0$26042$88260bb3@free.teranews.com> <87tzleb2st.fsf@benfinney.id.au> <478E658A.9070003@tobiah.org> Message-ID: <87prw1bftx.fsf@benfinney.id.au> Tobiah writes: > Ben Finney wrote: > > Tobiah writes: > > > >> This is a little surprising. So "from mod import *" really copies > >> all of the scalars into new variables in the local namespace. > > > > No. Nothing is copied. All the objects (remembering that in Python, > > *everything* is an object) created by the code in module 'mod' are > > given names in the current namespace. > > Yeah, copied. Just as in: > > >>> a = 3 > >>> b = a > >>> a = 5 > >>> b > 3 > >>> Again, those aren't copies. There is only one instance of each value, referenced by multiple names. This is made clearer by using a mutable value: >>> a = [1, 2, 3] >>> b = a >>> c = b >>> a = [4, 5, 6] >>> a, b, c ([4, 5, 6], [1, 2, 3], [1, 2, 3]) >>> a.append("spam") >>> b.append("eggs") >>> a, b, c ([4, 5, 6, 'spam'], [1, 2, 3, 'eggs'], [1, 2, 3, 'eggs']) The value referenced by 'b' and 'c' is one instance; they don't have copies of the value. Assignment binds a reference to a value, it doesn't make a copy. A "copy" is what's implemented by the standard library 'copy' module, hence the name. -- \ "Whenever you read a good book, it's like the author is right | `\ there, in the room talking to you, which is why I don't like to | _o__) read good books." -- Jack Handey | Ben Finney From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 23 08:04:15 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 23 Jan 2008 14:04:15 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> Message-ID: <5vosafF1nn9odU2@mid.individual.net> Grant Edwards wrote: > Trying to find assembly language stuff to look at is futile. > Python doesn't get compiled into assembly language. So, how do processors execute Python scripts? :) > If you want to learn Python, then read a book on Python. ACK. Regards, Bj?rn -- BOFH excuse #198: Post-it Note Sludge leaked into the monitor. From python.leojay at gmail.com Sun Jan 6 10:00:02 2008 From: python.leojay at gmail.com (Leo Jay) Date: Sun, 6 Jan 2008 23:00:02 +0800 Subject: C++ equivalent of comp.lang.python? In-Reply-To: <60597295-1493-493c-969c-a14dd7da98a3@s19g2000prg.googlegroups.com> References: <60597295-1493-493c-969c-a14dd7da98a3@s19g2000prg.googlegroups.com> Message-ID: <4e307e0f0801060700v9beb978hc3dae8f063e79b3c@mail.gmail.com> On Jan 4, 2008 1:39 AM, wrote: > Hopefully this isn't too OT. > > One thing I like about comp.lang.python is the breadth of topics > discussed here. People can ask about Python installation and > configuration issues on specific platforms, compare third party > libraries, ask for book recommendations, and discuss current Python > projects. Lurking here has greatly increased my understanding of > Python over the last year or so. > > I also do a lot of C++ development, but I've never found a similar > discussion group for that language. comp.lang.c++ isn't what I'm > looking for. I find it hard to get practical advice on that group > because its focus is so narrow. I frequently see posters there > redirect people to one of the OS-specific C++ groups, but most of my > projects are cross-platform, so hanging out on one of those doesn't if you can't use the standard library or any existing third-party library to solve your problem, that's platform specific. so, find the right group and ask there. > make sense either. As an example, I was recently trying to get > information about writing cross-platform code for dynamic linking, but > I couldn't find anywhere appropriate to ask about it. as to dynamic linking, afaik, i don't think you can deal with it in a consistent way. you'd better find a third-party library or handle all platforms one by one manually. > > For those of you who work in C++, where do you go to discuss it > online? I'm interested in any newsgroups, mailing lists, or web > boards you can recommend. > -- Best Regards, Leo Jay From python at rcn.com Tue Jan 8 17:40:08 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 8 Jan 2008 14:40:08 -0800 (PST) Subject: stupid/style/list question References: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> Message-ID: <69b7aea8-a291-47da-906d-252ae6f33f09@q39g2000hsf.googlegroups.com> On Jan 8, 7:34 am, "Giampaolo Rodola'" wrote: > I was wondering... > To flush a list it is better doing "del mylist[:]" or "mylist = []"? > Is there a preferred way? If yes, why? To empty an existing list without replacing it, the choices are "del mylist[:]" and "mylist[:] = []". Of the two, I prefer the former because it reads more explicity (delete all of the items from the list"). In terms of performance, they are basically the same. To replace a list, "mylist = []" is the way to go. This is an affirmative statement that you are creating a new list. Raymond From python.list at tim.thechases.com Tue Jan 22 15:31:32 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 22 Jan 2008 14:31:32 -0600 Subject: question In-Reply-To: <6760762.631391201031899339.JavaMail.root@hrndva-web18-z01> References: <6760762.631391201031899339.JavaMail.root@hrndva-web18-z01> Message-ID: <479652A4.1090309@tim.thechases.com> > def albumInfo(theBand): > def Rush(): > return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > > def Enchant(): > return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > > The only problem with the code above though is that I > don't know how to call it, especially since if the user is > entering a string, how would I convert that string into a > function name? For example, if the user entered 'Rush', > how would I call the appropriate function --> > albumInfo(Rush()) > It looks like you're reaching for a dictionary idiom: album_info = { 'Rush': [ 'Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres', ], 'Enchant': [ 'A Blueprint of the World', 'Wounded', 'Time Lost', ], } You can then reference the bits: who = "Rush" #get this from the user? print "Albums by %s" % who for album_name in album_info[who]: print ' *', album_name This is much more flexible when it comes to adding groups and albums because you can load the contents of album_info dynamically from your favorite source (a file, DB, or teh intarweb) rather than editing & restarting your app every time. -tkc PS: to answer your original question, you can use the getattr() function, such as results = getattr(albumInfo, who)() but that's an ugly solution for the example you gave. From vedrandekovic at gmail.com Wed Jan 2 06:24:56 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Wed, 2 Jan 2008 03:24:56 -0800 (PST) Subject: wxpython application ( problem ? ) Message-ID: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> Hello, Here is sample of my simple script with wxpython and modules: subprocess,threading, directpython....... Code sample: import wx import wx.aui app=wx.App() frame=wx.Frame(None,title="New project") #There is also part with wx.aui frame.Show() app.MainLoop() After a few minutes wx application does destroy. Any ides why? From steven.bethard at gmail.com Tue Jan 22 13:27:48 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 22 Jan 2008 11:27:48 -0700 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <5vme8iF1mqjl6U1@mid.uni-berlin.de> References: <5vme8iF1mqjl6U1@mid.uni-berlin.de> Message-ID: <479635A4.8@gmail.com> Diez B. Roggisch wrote: > Jean-Paul Calderone wrote: > >> On Tue, 22 Jan 2008 15:15:43 +0100, "Diez B. Roggisch" >> wrote: >>> Jean-Paul Calderone wrote: >>> >>>> On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" >>>> wrote: >>>>> For a simple greenlet/tasklet/microthreading experiment I found myself >>>>> in the need to ask the question >>>>> >>>>> [snip] >>>> Why do you need a special case for generators? If you just pass the >>>> object in question to iter(), instead, then you'll either get back >>>> something that you can iterate over, or you'll get an exception for >>>> things that aren't iterable. >>> Because - as I said - I'm working on a micro-thread thingy, where the >>> scheduler needs to push returned generators to a stack and execute them. >>> Using send(), which rules out iter() anyway. >> Sorry, I still don't understand. Why is a generator different from any >> other iterator? > > Because you can use send(value) on it for example. Which you can't with > every other iterator. And that you can utizilize to create a little > framework of co-routines or however you like to call it that will yield > values when they want, or generators if they have nested co-routines the > scheduler needs to keep track of and invoke after another. So if you need the send() method, why not just check for that:: try: obj.send except AttributeError: # not a generator-like object else: # is a generator-like object Then anyone who wants to make an extended iterator and return it can expect it to work just like a real generator would. STeVe From vinay_sajip at yahoo.co.uk Tue Jan 8 09:23:58 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 8 Jan 2008 06:23:58 -0800 (PST) Subject: Passing contextual information when logging References: Message-ID: <5d681c92-7ac0-4627-baf6-60ee00b359e7@1g2000hsl.googlegroups.com> On 8 Jan, 09:46, Antoine Pitrou wrote: > One question : why does the exception() method call Logger.error() rather than > Logger.exception() ? exception() is a convenience method which adds the keyword argument exc_info=1 to append traceback information to the log. Both exception() and error() log at the ERROR level. > One suggestion : pass in a Logger object rather than a logger name to the > LoggerAdapter constructor. (this also means that users could stack LoggerAdapter > objects if they wanted to) Done, see http://dpaste.com/30253/ Regards, Vinay From george.sakkis at gmail.com Mon Jan 21 17:34:09 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 21 Jan 2008 14:34:09 -0800 (PST) Subject: Transforming ascii file (pseduo database) into proper database References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> <7x8x2iyhrc.fsf@ruckus.brouhaha.com> Message-ID: On Jan 21, 4:45 pm, Paul Rubin wrote: > "p." writes: > > 1. Has anyone done anything like this before, and if so, do you have > > any advice? > > Sort all the files with an external sort utility (e.g. unix sort), so > that records with the same key are all brought together. Then you can > process the files sequentially. Seconded. Unix sort can do external sorting [1] so your program will work even if the files don't fit in memory. Once they are sorted, itertools (especially groupby) is your friend. George [1] http://en.wikipedia.org/wiki/External_sort From basilisk96 at gmail.com Mon Jan 14 21:01:38 2008 From: basilisk96 at gmail.com (Basilisk96) Date: Mon, 14 Jan 2008 18:01:38 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> Message-ID: On Jan 14, 7:53 am, Michele Simionato wrote: > I really need to publish this one day or another, since these > questions > about super keeps coming out: > > http://www.phyast.pitt.edu/~micheles/python/super.html Please do. It is a very enlightening discussion, and I'm sure a bunch of folks will benefit from it. And please update it (if necessary) to the current Python version. At the time of that writing, 2.3 must have been King, but oh my, how time flies :-) Cheers, -Basilisk96 From henry.baxter at gmail.com Fri Jan 25 16:37:38 2008 From: henry.baxter at gmail.com (Henry Baxter) Date: Fri, 25 Jan 2008 13:37:38 -0800 Subject: Index of maximum element in list Message-ID: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> I apologize if this has already been discussed - funnily enough my googling did bring up a previous thread about it on this mailing list, but despite the promising subject line, seemed to mainly be concerned with whether python-list should its own FAQ...so I assume this has been asked many times before, but my apologies I cannot find the answer. Here is what I have: def maxi(l): it -- Henry -------------- next part -------------- An HTML attachment was scrubbed... URL: From dongie.agnir at gmail.com Wed Jan 9 18:45:41 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Wed, 9 Jan 2008 15:45:41 -0800 (PST) Subject: Python too slow? References: 76bc64cc-541c-434f-aac5-96d1a2d231ee@c23g2000hsa.googlegroups.com <7115e305-429c-47d3-a942-8a0e2a0e846f@m34g2000hsf.googlegroups.com> Message-ID: Okay I profiled the code and here is the output: http://heightened.files.wordpress.com/2008/01/output.txt It seems that the function it spends the longest on is the red_points function that he uses to find the points. From steve at REMOVE-THIS-cybersource.com.au Fri Jan 25 22:09:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 26 Jan 2008 03:09:05 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: <13pl92h3um45rc1@corp.supernews.com> On Wed, 23 Jan 2008 08:49:20 +0100, Christian Heimes wrote: > It's even > possible to write code with Python assembly and compile the Python > assembly into byte code. Really? How do you do that? I thought it might be compile(), but apparently not. -- Steven From jatinpatni at gmail.com Wed Jan 9 07:44:37 2008 From: jatinpatni at gmail.com (jatin patni) Date: Wed, 9 Jan 2008 12:44:37 +0000 Subject: Problem in the program flow...please help? Message-ID: I am making a python application with a GUI using WXGlade which connects to a website and extracts some information, this takes around 5-20 seconds of time per website. I have a button(GUI) which when clicked, calls a function connect( ) which takes around 5-20 seconds to complete(As I mentioned Earlier) The problem is, during this time the other part of the code is rendered useless, I cannot access other parts of the code, for example a cancel( ) function to be called when cancel button is pressed, cannot be pressed until the previous function is completed and moreover the GUI hangs(stops responding). I am planning to explore Threading and Asynchronous data transfer, next. Please help me out if anyone has had a similar experience in the past. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sat Jan 26 05:25:22 2008 From: http (Paul Rubin) Date: 26 Jan 2008 02:25:22 -0800 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> Message-ID: <7xy7acsx2l.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > def posmax(seq, key=None): > """Return the position of the first maximum item of a sequence. > It accepts the usual key parameter too.""" > if key: > return max(enumerate(seq), key=lambda k: key(k[1]))[0] > else: > return max(enumerate(seq), key=itemgetter(1))[0] def posmax(seq, key=lambda x:x): return max(enumerate(seq), key=lambda k: key(k[1]))[0] From bigblueswope at gmail.com Mon Jan 7 21:04:27 2008 From: bigblueswope at gmail.com (BJ Swope) Date: Mon, 7 Jan 2008 21:04:27 -0500 Subject: Open a List of Files Message-ID: given a list such as ['messages', 'recipients', 'viruses'] how would I iterate over the list and use the values as variables and open the variable names a files? I tried for outfile in ['messages', 'recipients', 'viruses']: filename = os.path.join(Host_Path, outfile) outfile = open(filename, 'w') But it's not working. -- We are all slave to our own paradigm. -- Joshua Williams If the letters PhD appear after a person's name, that person will remain outdoors even after it's started raining. -- Jeff Kay -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sat Jan 12 10:38:11 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 07:38:11 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> Message-ID: <05133da5-a1fb-4c24-acd0-23dbccea5813@j78g2000hsd.googlegroups.com> On Jan 12, 8:04 am, castiro... at gmail.com wrote: > On Jan 11, 5:26 pm, Paul Rubin wrote: > > > castiro... at gmail.com writes: > > > 1. Put a single thread in charge of the list, and communicate with it > > by message passing through Queues. To get X out of the list, you'd > > send the mutator thread a message asking for removal. The mutator > > thread would loop reading and processing messages from the queue, > > blocking when no requests are pending. This is sort of the preferred > > Python style and is pretty simple to get correct, but if there are > > many such objects you can end up with more threads than you really > > want. > > I've heard this called 'fire and forget'. You can insure that > mutations are honored one-at-a-time and in the order received. How > do you make a -read- operation; wait for queued mutations, that is > lock for a turn on the queue? Can you optionally read whatever the > state is, regardless of what's happened in the meantime? Thing is, > one thread needs its -own- preceding operations completed before a > reading operation. Brainstorm. First, isolation of problem: Terminates at 2000 or so, on my computer. import thread import time import random counter= 0 def simplecounter(): global counter ret= counter counter+= 1 time.sleep( random.uniform( 0, .001 ) ) return counter glist= [] def th3(): while 1: ret= simplecounter() glist.append( ret ) print ret, assert glist== range( 1, len( glist )+1 ) thread.start_new_thread( th3, () ) time.sleep(1) thread.start_new_thread( th3, () ) time.sleep( 1000 ) Second, the thoughts: 'with a.callbacklock():' looks best currently. '''multithreading ideas: 1. Put a single thread in charge a.k.a. fire and forget. - Lots of extra threads + But most are blocking most of the time + honored one-at-a-time, and in order received + ...optionally including read-access, blocking on to get return values a. synchronous callbacks, for read-access + multi-step, user-definitionized operations - one consumer can hang an entire object i. with a.callbacklock():? + only call acquire() from curr. thread, enqueue lock obj., released from producer thread "soon" using message-queue semantics b. mini-transaction, guarantees all and only consumer's ops occur in succession - can't do anything amidst an indivdual locking - no multi-step ops 2. Lock mutation and/or all operations a. Locker.op b. with Locker.withop - In Python, other programmers always have access to your data; nothing guarantees they'll use "with locker" + User-definitioning quite easy 3. @mutation decorator def mutation( func ): def newfunc( self, *a, **k ): self.lock.acquire() func( *a, **k ) self.lock.release() 4. List-only solution: Use a dictionary, map item to its index. To retrieve, sort on value, not key ''' From grflanagan at yahoo.co.uk Wed Jan 16 05:21:28 2008 From: grflanagan at yahoo.co.uk (grflanagan) Date: Wed, 16 Jan 2008 02:21:28 -0800 (PST) Subject: searching an XML doc References: <327368a7-694f-4f30-8f76-db0569ed4a5c@k2g2000hse.googlegroups.com> Message-ID: <2d290754-4a44-427f-9287-134210b217d5@q77g2000hsh.googlegroups.com> On Jan 15, 9:33 pm, Gowri wrote: > Hello, > > I've been reading about ElementTreee and ElementPath so I could use > them to find the right elements in the DOM. Unfortunately neither of > these seem to offer XPath like capabilities where I can find elements > based on tag, attribute values etc. Are there any libraries which can > give me XPath like functionality? > > Thanks in advance Create your query like: ns0 = '{http://a.b.com/phedex}' query = '%srequest/%sstatus' % (ns0, ns0) Also, although imperfect, some people have found this useful: http://gflanagan.net/site/python/utils/elementfilter/elementfilter.py.txt [CODE] test = ''' T1_RAL_MSS T2_London_ICHEP T2_Southgrid_Bristol /PrimaryDS1/ProcessedDS1/ Tier /PrimaryDS2/ ProcessedDS2/Tier/block ''' from xml.etree import ElementTree as ET root = ET.fromstring(test) ns0 = '{http://a.b.com/phedex}' from rattlebag.elementfilter import findall, data #http://gflanagan.net/site/python/utils/elementfilter/ elementfilter.py.txt query0 = '%(ns)srequest/%(ns)sstatus' % {'ns': ns0} query1 = '%(ns)srequest/%(ns)ssubscription[@type=="replicate"]/% (ns)sitems' % {'ns': ns0} query2 = '%(ns)srequest[@id==1234]/%(ns)sstatus/%(ns)sapproved' % {'ns': ns0} print 'With ElementPath: ' print root.findall(query0) print print 'With ElementFilter:' for query in [query0, query1, query2]: print print '+'*50 print 'query: ', query print for item in findall(root, query): print 'item: ', item print 'xml:' ET.dump(item) print '-'*50 print print 'approved: ', data(root, query2) [/CODE] [OUTPUT] With ElementPath: [] With ElementFilter: ++++++++++++++++++++++++++++++++++++++++++++++++++ query: {http://a.b.com/phedex}request/{http://a.b.com/phedex}status item: xml: T1_RAL_MSS T2_London_ICHEP T2_Southgrid_Bristol ++++++++++++++++++++++++++++++++++++++++++++++++++ query: {http://a.b.com/phedex}request/{http://a.b.com/ phedex}subscription[@type =="replicate"]/{http://a.b.com/phedex}items item: xml: /PrimaryDS1/ProcessedDS1/ Tier /PrimaryDS2/ ProcessedDS2/Tier /block ++++++++++++++++++++++++++++++++++++++++++++++++++ query: {http://a.b.com/phedex}request[@id==1234]/{http://a.b.com/ phedex}status/ {http://a.b.com/phedex}approved item: xml: T1_RAL_MSS item: xml: T2_London_ICHEP -------------------------------------------------- approved: ['T1_RAL_MSS', 'T2_London_ICHEP'] INFO End logging. [/OUTPUT] From jimis at gmx.net Thu Jan 3 12:23:21 2008 From: jimis at gmx.net (Dimitrios Apostolou) Date: Thu, 3 Jan 2008 19:23:21 +0200 (EET) Subject: urllib2 disable proxy In-Reply-To: <878x373o6c.fsf@merkury.smsnet.pl> References: <878x373o6c.fsf@merkury.smsnet.pl> Message-ID: On Wed, 2 Jan 2008, Rob Wolfe wrote: > Dimitrios Apostolou writes: > >> Hello list, >> >> I've been looking for a way to explicitly disable the use of proxies with >> urllib2, no matter what the environment dictates. Unfortunately I can't find >> a way in the documentation, and reading the source leads me to believe that >> something like the following does the job: >> >> req.set_proxy(None,None) >> >> Where req is a urllib2.Request instance. So is there an official way of doing >> this? Perhaps it should be added in the documentation? > > I believe that the recommended way is to use `urllib2.ProxyHandler`. > Take a look at: > http://www.voidspace.org.uk/python/articles/urllib2.shtml Thanks for the pointer, I will use that way. However it seems rather non-elegant way to do something so simple and I was hoping not to mess with ProxyHandler, especially since I want *no* proxy... IMHO something like the following would be more elegant: req.set_proxy('','http') or req.set_proxy(None,'http') However these ways *don't* work. You think I should file a feature request somewhere or send this to the python-dev list? Thank you for the help, Dimitris > > HTH, > Rob > -- > http://mail.python.org/mailman/listinfo/python-list > From mwilson at the-wire.com Mon Jan 21 08:44:54 2008 From: mwilson at the-wire.com (Mel) Date: Mon, 21 Jan 2008 08:44:54 -0500 Subject: problem with 'global' References: Message-ID: Duncan Booth wrote: > Mel wrote: > >> oyster wrote: >>> why the following 2 prg give different results? a.py is ok, but b.py >>> is 'undefiend a' >>> I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC >>> v.1310 32 bit (Intel)] on win32 >>> #a.py >>> def run(): >>> if 1==2: # note, it always False >>> global a >>> a=1 >>> >>> run() >>> a >>> >>> #b.py >>> def run(): >>> a=1 >>> >>> run() >>> a >> The docs seem to be in >> but don't look all that helpful. > > Why are you reading Python 2.4 docs? Try > http://docs.python.org/ref/global.html > > The first sentence (which hasn't changed since 2.4) describing the global > statement seems clear enough to me: "The global statement is a declaration > which holds for the entire current code block." I don't think that would stop the OP from thinking the global statement had to be executed. In the code example, it seems to have been stuck in a if 1==2: global a and it still worked. Mel. From harald.karner at a1.net Fri Jan 25 05:58:06 2008 From: harald.karner at a1.net (Harald Karner) Date: Fri, 25 Jan 2008 11:58:06 +0100 Subject: time.gmtime In-Reply-To: <293bb767-603b-4aef-b9c8-23af565b090f@s8g2000prg.googlegroups.com> References: <293bb767-603b-4aef-b9c8-23af565b090f@s8g2000prg.googlegroups.com> Message-ID: <1201258685.993333@nntpcache01.si.eunet.at> asit wrote: > we know that time.gmtime(secs) takes a parameter secs. what does this > secs suggest ??What is it's significance ?? >>> import time >>> help (time.gmtime) Help on built-in function gmtime in module time: gmtime(...) gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst) Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a. GMT). When 'seconds' is not passed in, convert the current time instead. >>> time.gmtime (0) (1970, 1, 1, 0, 0, 0, 3, 1, 0) >>> From aspineux at gmail.com Mon Jan 14 14:07:22 2008 From: aspineux at gmail.com (aspineux) Date: Mon, 14 Jan 2008 11:07:22 -0800 (PST) Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> Message-ID: <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> On Jan 14, 7:49 pm, "Chris Mellon" wrote: > On Jan 14, 2008 12:39 PM, aspineux wrote: > > > > > This append in both case > > > dict(a=1).get('a', f()) > > dict(a=1).setdefault('a', f()) > > > This should be nice if f() was called only if required. > > Think about the change to Python semantics that would be required for > this to be true, and then use collections.defaultdict instead. Yes, I missed 'get' and 'setdefault' are functions :-) Then why not some new semantic d.get('a', f()) --> d['a', f()] d.setdefault('a', f()) --> d['a'=f()] Is is a good idea enough to change the python semantic ? Or simply is it a good idea ? From mail at microcorp.co.za Fri Jan 18 02:23:55 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 18 Jan 2008 09:23:55 +0200 Subject: Interesting Thread Gotcha References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> Message-ID: <000001c859f0$05b796c0$03000080@hendrik> "Dan" wrote: > Would it be possible to have pychecker (or some such) warn that there > is an insufficient parameter count to start_new_thread? I guess that > would require knowing the type of thread. . . I think this is the hub of the thing - its not only start_new_thread, but the way that parameters are evaluated before being counted, generally. See my reply to Diez's post - Hendrik From benedict.verheyen at gmail.com Mon Jan 28 04:32:06 2008 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Mon, 28 Jan 2008 10:32:06 +0100 Subject: starting programs from python script on windows Message-ID: Hi, i want to automate starting programs on my windows machine and i want to do it with windows. This is a sample script: from subprocess import Popen, PIPE import time print " Starting app 1" time.sleep(1) try: p1 = Popen(["C:\Program Files\Microsoft Office\OFFICE11\OUTLOOK.EXE"], stdout=PIPE) except Exception, e: print "Error on startup app 1 %s " % str(e) print " Starting app 2" time.sleep(1) try: p2 = Popen(["C:\Windows\system32\cmd.exe"], stdout=PIPE) except Exception, e: print "Error on startup app 2 %s " % str(e) It start it from a batch file: SET PYTHONPATH=C:\Python25 rem - path to script to execute %PYTHONPATH%\python.exe C:\login.py This is the result: C:\>C:\Python25\python.exe C:\login.py Starting app 1 Starting app 2 Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. 1. I get an error message saying the process has tried to write to a non existing pipe. 2. Order of execution isn't respected: it prints the 2 messages and then it tries to start the programs. Outlook is started but the command prompt not. Anyway, if it works, i would like to start using python to drive the startup scripts of the users on the system. How can i use python to start several programs as i would otherwise do manually and keep the order i want? Thanks, Benedict From hniksic at xemacs.org Sun Jan 13 07:32:48 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 13 Jan 2008 13:32:48 +0100 Subject: about sort a list with integer key References: <986e05f3-2fe9-4fe8-94e2-fef26713a78c@i72g2000hsd.googlegroups.com> Message-ID: <87fxx1nbwv.fsf@mulj.homelinux.net> lotrpy writes: > if i want sort each line by the first part,(it's a integer, in fact). > don't know how to do it with itemgetter. > key = int(itemgetter(0)) is wrong, key = lambda x:int(x[0]) works. > but s.b. told me itemgetter execute more quickly . Use lambda when it works better for you, the speed difference is marginal in practice anyway. itemgetter is not (and was never intended to be) a general substitute for functions, as you've discovered. The marginal speed difference between itemgetter and an explicit lambda that does the subscripts is a consequence of itemgetter being written in C, meaning it avoids the creation of a Python stack frame, etc. Combining int(...) with this operation requires coding the key function in Python, which removes itemgetter's advantage. In other words, you cannot retain itemgetter's speed advantage with more complex keys. If the sorting performance is a problem for you, please give more details about what you're doing -- there might be better ways to speed up the code. From antroy at gmail.com Wed Jan 9 06:40:05 2008 From: antroy at gmail.com (Ant) Date: Wed, 9 Jan 2008 03:40:05 -0800 (PST) Subject: Learning Python via a little word frequency program References: Message-ID: <43a9a28c-0713-4789-b4f0-4e6ba0e8bbfd@u10g2000prn.googlegroups.com> > I'm interested to learn how more experienced Python folks would solve > this little problem. I think I'd do the following: from collections import defaultdict names = "freddy fred bill jock kevin andrew kevin kevin jock" freq = defaultdict(lambda: 0) for name in names.split(): freq[name] += 1 pairs = [(v, k) for k, v in freq.iteritems()] for v, k in reversed(sorted(pairs)): print "%-10s: %d" % (k, v) defaultdict makes the frequency accumulation neater. reversed(sorted(pairs)) avoids the little -v hack and makes it more obvious what you are doing. Of course this could also be achieved by doing pairs.sort() and pairs.reverse() before iterating over the pairs list. Cheers, -- Ant. From alitosis at gmail.com Wed Jan 30 22:28:37 2008 From: alitosis at gmail.com (alitosis at gmail.com) Date: Wed, 30 Jan 2008 19:28:37 -0800 (PST) Subject: writing Python in Emacs References: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> <87r6gc5wr5.fsf@merkury.smsnet.pl> Message-ID: <48499955-2c23-4acc-9252-ee2963bc233c@i12g2000prf.googlegroups.com> Rob Wolfe wrote: > The good news is that I managed to configure completion for Python > in Emacs using pymacs, python-mode.el, pycomplete.el and pycomplete.py. > For contents of my pycomplete.el, pycomplete.py and necessary > settings in .emacs see below. Thanks for that! I've been hoping something like this landed on my lap for years. From python at rolfvandekrol.nl Sat Jan 19 10:33:59 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Sat, 19 Jan 2008 16:33:59 +0100 Subject: python scripts with IIS In-Reply-To: <120794.61529.qm@web38414.mail.mud.yahoo.com> References: <120794.61529.qm@web38414.mail.mud.yahoo.com> Message-ID: <47921867.5040309@rolfvandekrol.nl> Adding the following lines before your print statement should do the trick. IIS complains about the headers, so adding headers should help. print "Content-Type: text/html" # HTML is following print # blank line, end of headers william paul wrote: > > Hello: > > I am trying to configure IIS to work with Python scripts: > > I've added in the Home Directory/Configuration the .py extention and > the path to the python.exe as: c:\Python24\python.exe %S %S > The python script has 1 line: > print "This is a test for python scripts with IIS" > > When I launch the file using IE I get the message: > > *CGI Error* > The specified CGI application misbehaved by not returning a complete > set of HTTP headers. The headers it did return are: > > This is a test for python scripts with IIS > > How can I remove the CGI error? > > Thank you > > William > > ------------------------------------------------------------------------ > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try > it now. > From lists at cheimes.de Sat Jan 19 16:31:38 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 19 Jan 2008 22:31:38 +0100 Subject: finding memory leak in edgewall trac 0.11 In-Reply-To: <20080119202909.GY61556@nexus.in-nomine.org> References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> Message-ID: <47926C3A.5060000@cheimes.de> Jeroen Ruigrok van der Werven wrote: > Hi Christian, > > -On [20080119 16:16], Christian Heimes (lists at cheimes.de) wrote: >> I forgot one important point in my reply. The GC module contains some >> useful methods for debugging. Check gc.garbage. It should be empty. > > Yeah, we're messing around with that stuff as well as many other ways of > trying to track issues, but it can really be looking for a needle in a > haystack to be honest. > There's so much output that, I guess, make sense only when you're semi-deep > into the Python internals to even make heads or tails out of it. =\ > And even third-party code is not helping much to reduce the clutter and > provide insight. Under normal circumstances gc.garbage should be an empty list. In general it's a bad sign if gc.garbage contains lots of objects. I found several potential leaks in trac: $ find -name \*.py | xargs grep __del__ ./trac/versioncontrol/svn_fs.py: def __del__(self): ./trac/versioncontrol/svn_fs.py: def __del__(self): ./trac/db/pool.py: def __del__(self): $ find -name \*.py | xargs grep frame ./trac/web/main.py: [...] ./trac/core.py: frame = sys._getframe(1) ./trac/core.py: locals_ = frame.f_locals I recommend that you either replace __del__ with a weak reference callback or to remove it. Referencing a frame, traceback or f_locals is going to leak, too. You *must* explicitly del every frame and locals variable. Christian From jitrowia at yahoo.com Fri Jan 25 22:48:44 2008 From: jitrowia at yahoo.com (jitrowia) Date: Sat, 26 Jan 2008 03:48:44 -0000 Subject: How can I use the up and down, left and right arrow keys to control a Python Pgm Message-ID: I was wondering what kind of python code I would need to enable me to use the up and down, left and right arrow keys to control software programming decisions within a Python Program. Any direction and advice would be greatly appreciated, Thank You, Rodney From john.rominsky at gmail.com Fri Jan 4 12:30:12 2008 From: john.rominsky at gmail.com (Rominsky) Date: Fri, 4 Jan 2008 09:30:12 -0800 (PST) Subject: matplotlib fill command on axes plot problem Message-ID: I am trying to use the fill command to draw a box around an object in an image. I can get the box drawn, but there seems to be a side effect. The fill command is adding white lines to the top and sometimes right side of my axes plots. I am using small images, 124x200, and after the fill command the axes plot is changed to 140x200, with the top 16 lines being all white. I am running it in interactive mode from the python command line. Here is code that reproduces the problem. from pylab import * im_array = zeros((124,200)) ion() figure() imshow(im_array) hold(True) x=40 y=40 fill([x-5,x+5,x+5,x-5],[y+5,y+5,y-5,y-5],ec='r', fill = False) hold(False) Any thoughts on what I might be doing wrong? From bignose+hates-spam at benfinney.id.au Thu Jan 17 23:05:23 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 18 Jan 2008 15:05:23 +1100 Subject: array and list References: Message-ID: <87bq7jbwxo.fsf@benfinney.id.au> "J. Peng" writes: > what's the difference between an array and a list in python? In Python, 'list' is a basic built-in type. Python has no 'array' type, though that term is often used to refer to the 'array' type defined in Numeric Python (which is not part of the standard library, so not really part of Python). > I see list has all features of array in C or perl. You may also want to compare and constrast Python 'list' and 'dict'. -- \ "When cryptography is outlawed, bayl bhgynjf jvyy unir | `\ cevinpl." -- Anonymous | _o__) | Ben Finney From Brett.Friermood at gmail.com Mon Jan 21 20:06:10 2008 From: Brett.Friermood at gmail.com (Brett.Friermood at gmail.com) Date: Mon, 21 Jan 2008 17:06:10 -0800 (PST) Subject: Curses and Threading Message-ID: <3924ad84-a513-4b25-b9af-cbd358f5d40a@i3g2000hsf.googlegroups.com> I am writing a program that uses curses and threading. I am working on displaying a clock in the upper right hand corner of the screen. I have only one thread at the moment, that gets the time and displays it in curses. To make it easier to debug right now, the program starts curses in a try: clause then starts the thread which runs for 10 iterations displaying the time every second. Then the thread exits, and the program is supposed to run the finally: clause to clean up the terminal. I also have set curs_set(0) so the cursor is invisible. What happens is that everything starts fine but the cursor is visible. It runs for the 10 seconds then quits without restoring the terminal to working order. I am trying this on a Fedora 4 computer have also tried it on a Fedora 8 one with same results. I have tried searching but Google doesn't find anything using both curses and threading. The only thing I can find regarding both is that curses seems to block when waiting for input, but I do not have any input yet. Below is what I have right now: #! /usr/bin/env python import curses import threading import time class cadtime(threading.Thread): def run(self): x=0 while x<10: cadtimevl=time.strftime("%d %b %H:%M: %S",time.localtime()) leng=len(cadtimevl) stdscr.addstr(0,width-leng-1,cadtimevl) stdscr.refresh() x=x+1 time.sleep(1) return try: stdscr=curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) curses.start_color() curses.curs_set(0) width=curses.COLS-1 cadtime().start() finally: curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin() I can't figure out why the cursor still shows and why they terminal is screwed up afterward because the finally: should catch any failures and reset the terminal. -Brett From mal at egenix.com Mon Jan 7 07:55:05 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 07 Jan 2008 13:55:05 +0100 Subject: Memory Leaks and Heapy In-Reply-To: <7f692fec0801041819r675e2137i293084baeae4954f@mail.gmail.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> <477E5A73.9070400@egenix.com> <7f692fec0801040823q14d16429y370ffceaf046a6f3@mail.gmail.com> <477E6525.3010805@egenix.com> <7f692fec0801041819r675e2137i293084baeae4954f@mail.gmail.com> Message-ID: <47822129.4050500@egenix.com> On 2008-01-05 03:19, Yaakov Nemoy wrote: > On Jan 4, 2008 11:56 AM, M.-A. Lemburg wrote: >>> The most common answer I heard was possible fragmentation, meaning >>> there are no or few completely empty blocks to be found. If there are >>> no 'leaks' in the VM, then it's probably related to how memory is >>> freed. >> You can check for this by using a special build of Python >> with disabled PyMalloc - Python will then use the standard >> OS malloc for all object allocations. It still uses free lists >> for a couple of object types, but those won't cause major >> leak problems. > > How do I go about setting this up? There's a configure option for this: --with(out)-pymalloc disable/enable specialized mallocs >> Alternatively, try to tune the PyMalloc implementation (see >> objmalloc.c), e.g. enable WITH_MEMORY_LIMITS. >> >>>> This could be caused by interned strings which are kept in a special >>>> pool dictionary to speed up string comparisons. >>> That's quite possible, a majority of the code is a huge number of SQL >>> connections and code. All string based. >> Note that strings are normally *not* interned. However, you can >> write code in a way that causes Python to intern more strings >> than needed, e.g. if you dynamically compile code in your app, >> which then causes all identifiers in the compiled code to be >> interned. >> >> The interned dictionary is not exposed in Python, but you can >> access it using a debugger via Objects/stringobject.c:interned. > > That's going a bit more low level detail than I think I can handle. > I'm not much for C programming, and i'll have a hard time sifting > through the noise to find the signal. Fair enough. Just wanted to give some more details as to where to look for things that look like leaks, but are in fact just results of internal feature of the Python interpreter. >>>> However, the first thing to check is whether any of the C extension >>>> modules you are using is leaking memory. Python itself is usually >>>> well tested for memory leaks, but this is less so for C extension >>>> modules and it's easy to mis a few Py_DECREFs (decrementing a >>>> Python object's reference count), causing objects to live forever. >>> I'll try to track it down, but AFAIK, most of the code is python, and >>> the only C code there would be is the MySQL container. How can I >>> debug the VM though, to determine where the leak lies? Heapy wasn't >>> able to tell me this, and this is the important aspect. I'm wondering >>> how most people go about determining the causes of leaks like these, >>> so I can provide some accurate bug information. >> Building Python in debug mode provides some help with this. >> You can then detect whether objects get properly freed. > > Again, what's the best way to go about doing this? Again, configure with: --with-pydebug build with Py_DEBUG defined >> Doing explicit garbage collection via the gc module also >> helps in narrowing down the leak. > > Adding an explicit gc.collect() statement at the end of the offending > function didn't do much to solve matters much. It slowed the rate > that garbage piled up, but it's not a solution. > > Thanks for all the help. You're welcome. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jan 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 t_spens at yahoo.com Wed Jan 23 18:46:40 2008 From: t_spens at yahoo.com (Tim Spens) Date: Wed, 23 Jan 2008 15:46:40 -0800 (PST) Subject: handling asynchronous callbacks from c++ in a python script Message-ID: <155356.55301.qm@web45109.mail.sp1.yahoo.com> I have a c++ program running that has boost python hooks for the c++ api. I'm running a python client that makes calls into the c++ api. The problem is there are c++ asynchronous callbacks that need to pass information to the python client. What I was hoping to do is call a python function from c++ that resides in the running "main()" python client while in the c++ callback handlers. Is this possible and if you can point me to an example or documentation on how to do this it would be much appreciated? NOTE: I've been asking on the c++-sig mailing list about this and David Abrahams (very well versed in boost python) said: "I'm not an expert on asynchronous python and this is really not a Boost.Python question. I suggest you ask on the regular Python mailing list. Sorry." ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From sergio.correia at gmail.com Tue Jan 15 11:15:33 2008 From: sergio.correia at gmail.com (Sergio Correia) Date: Tue, 15 Jan 2008 11:15:33 -0500 Subject: Why this apparent assymetry in set operations? In-Reply-To: References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: Both of you are correct. >>> x = set([1,2,3]) >>> y = set([4,5]) >>> x |= y >>> x set([1, 2, 3, 4, 5]) On Jan 15, 2008 11:07 AM, Skip Montanaro wrote: > > > Why is that? Doesn't the |= operator essentially map to an update() call? > > > > No, according to 3.7 Set Types, s | t maps to s.union(t). > > I was asking about the |= assignment operator which according to the > docs *does* map to the update method. > > Skip > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From musiccomposition at gmail.com Thu Jan 17 22:53:38 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 17 Jan 2008 19:53:38 -0800 (PST) Subject: How to create graphs an embed them in GUI? References: Message-ID: On Jan 17, 10:07 am, "A.T.Hofkamp" wrote: > On 2008-01-17, Heiko Niedermeyer wrote: > > > As I'm learning Python from scratch, I don't care wether to use (=learn) > > TKinter or PyQt or whatever, I just need some advice, which suits my > > needs best. > > It would be nice to have the programm working under win and linux > > (shouldn't be a big Problem) and my requirements concerning the standard > > PyGTK is a 3rd option, and wxWindows + Python is a 4th option. > > TKinter is supplied with Python, which means everybody with Python also has > TKinter. Main draw-backs are that it is quite old. Also, it has a peculiar way > of getting stuff drawn at a canvas. > > PyQt is available free with some additional restriction (plz read the > license) for the Linux system, I don't know whether you can also get a Win > version under the same conditions (you couldn't when I looked the last time). > PyGTK is said to be usable for both platforms. I know it works with Linux, and > there exists a PyGTK installer for Win, but I hacve never used it. PyQt 4+ is now available for MacOS, Windows, and X under GPL. I tried Tkinter and wxPython before settling on PyQt. It's more powerful than Tkinter and has a cleaner API than wxPython. > > No recent experience with wxWindows. > > > My problem is, that I want to add graph (simple, line connected X,Y- > > scatter plots) and if possible the 3D representation of atoms in a > > molecule (-> coloured spheres in space). Qwt (Q Widgets for Technical Applications) provides graphs widgets that plug into Qt. There are, of course, Python bindings (pyqwt). > > You should probably seperate both problems, in particular if you want to have > the program do the layout for you. For 2D layout, Graphviz is one of the better > known packages, run it as a child process. There are several graphviv/dot > Python libraries available, search PyPI for them. > > For 3D, I don't know any programs. > > > I think it would take me years to program those by myself, so I would ne > > ready to use packages, if available. > > Long story short: Are there packages that could do this, and does it > > matter which GUI I want to embed them in? > > If you want a GUI that understands how to layout chemical structures, you won't > have many options (on the other hand, you never know, have you tried searching > PyPI already?). > > On the other hand, once you have the coordinates, drawing them is kind of > trivial in just about any GUI toolkit. > > (An alternative may be to have the user lay them out by dragging them with the > mouse. Programming that is however probably a lot more work.) > > Sincerely, > Albert From fredrik at pythonware.com Wed Jan 9 11:21:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 17:21:07 +0100 Subject: sqlite fetchall breacking because decoding. In-Reply-To: <514759dc-faf7-4e34-bf6d-624a0cc540ae@e4g2000hsg.googlegroups.com> References: <514759dc-faf7-4e34-bf6d-624a0cc540ae@e4g2000hsg.googlegroups.com> Message-ID: tyoc wrote: > The database is not corrupt, I mean Im sure if I do a C program for > read and print the row, it will get it and just printit and not fail > like this well, the database *is* corrupt, since sqlite3 (both the engine and the Python binding) expects you to use a supported encoding for the data stored in the database: http://www.sqlite.org/datatype3.html http://docs.python.org/lib/node346.html the fact that you're able to use an API that doesn't care about encodings at all to violate the database requirements doesn't necessarily mean that an API that does the right thing is broken... if you're not able to fix your database, you have to plug in a custom text_factory handler. this should work: conn = sqlite3.Connect(...) conn.text_factory = str also see: http://docs.python.org/lib/sqlite3-Connection-Objects.html From george.sakkis at gmail.com Wed Jan 23 02:33:00 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 22 Jan 2008 23:33:00 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> On Jan 23, 1:39 am, Steven D'Aprano wrote: > Given the human psychology displayed involved, in the absence of > definitive evidence one way or another it is a far safer bet to assume > that people are unnecessarily asking for "the fastest" out of a misguided > and often ignorant belief that they need it, rather than the opposite. > People who actually need a faster solution usually know enough to preface > their comments with an explanation of why their existing solution is too > slow rather than just a context-free demand for "the fastest" solution. As I mentioned already, I consider the seeking of the most efficient solution a legitimate question, regardless of whether a "dumb" solution is fast enough for an application. Call it a "don't be sloppy" principle if you wish. It's the same reason I always use xrange() instead of range() for a loop, although in practice the difference is rarely measurable. > Fast code is like fast cars. There *are* people who really genuinely need > to have the fastest car available, but that number is dwarfed by the vast > legions of tossers trying to make up for their lack of self-esteem by > buying a car with a spoiler. Yeah, you're going to be traveling SO FAST > on the way to the mall that the car is at risk of getting airborne, sure, > we believe you. > > (The above sarcasm naturally doesn't apply to those who actually do need > to travel at 200mph in a school zone, like police, taxi drivers and stock > brokers.) Good example; it shows that there's more than the utilitarian point of view. People don't buy these cars because of an actual need but rather because of the brand, the (perceived) social value and other reasons. And since you like metaphors, here's another one: caring about efficient code only when you need it is like keeping notes for a course only for the material to be included in the final exams, skipping the more encyclopedic, general knowledge lectures. Sure, you may pass the class, even with a good grade, but for some people a class is more than a final grade. George From thynnus at gNOTmail.com Tue Jan 22 11:45:40 2008 From: thynnus at gNOTmail.com (Thynnus) Date: Tue, 22 Jan 2008 16:45:40 GMT Subject: stdin, stdout, redmon In-Reply-To: <4794a5e3$0$9014$426a74cc@news.free.fr> References: <4794a5e3$0$9014$426a74cc@news.free.fr> Message-ID: On 1/21/2008 9:02 AM, Bernard Desnoues wrote: > Hi, > > I've got a problem with the use of Redmon (redirection port monitor). I > intend to develop a virtual printer so that I can modify data sent to > the printer. FWIW: there is a nice update the RedMon (v1.7) called RedMon EE (v1.81) available at http://www.is-foehr.com/ that I have used and like a lot. From the developers website: Fixed issues and features [with respect to the orininal RedMon] * On Windows Terminal Server or Windows XP with fast user switching, the "Prompt for filename" dialog will appear on the current session. * "SaveAs" now shows XP style dialogs if running under XP * Support for PDF Security added - experimental -. * Support for setting the task priority - experimental - * Use of file-shares as output * Environment variables are passed to the AfterWorks Process now. * Environment variables are replaced in the program arguments. No workaround is needed. * RedMon EE comes with an RPC communication feature which could transfer output-files back to the client starting the print job on a print server. Error messages will be send to the client. * Redmon EE may start a process after the print job has finished (After works process). e.g. starting a presentation program to show the pdf generated by GhostScript. * additional debug messages may be written for error analysis. No special debug version is needed. * user interface has been rewritten. May be it's more friendly. Added some basic system information which may help if running in failures. * new feature: running on a print server. * cleanup of documentnames "Microsoft -" * define templates for output-file names with full environment variable substitution e.g. %homedrive%\%homedir%\%redmon-user%-%date%-%time%-%n.pdf * RedMon EE does not support for NT 3.5 and Windows 95/98 ! -Thynnus From israelu at elbit.co.il Tue Jan 15 06:07:47 2008 From: israelu at elbit.co.il (iu2) Date: Tue, 15 Jan 2008 03:07:47 -0800 (PST) Subject: print >> to a derived file References: Message-ID: <30e4d68b-8d0f-42b5-afe1-ac78dd35be97@k39g2000hsf.googlegroups.com> On Jan 15, 12:44?pm, "Ben Fisher" wrote: > This might have something to do with the class being derived from file. > > I've written it so that it doesn't derive from file, and it works. > > class File_and_console(): > ? ? ? ? def __init__(self, *args): > ? ? ? ? ? ? ? ? self.fileobj = open(*args) > ? ? ? ? def write(self, s): > ? ? ? ? ? ? ? ? self.fileobj.write(s) > ? ? ? ? ? ? ? ? print s, > > f = File_and_console('testout.tmp','w') > f.write('hello') > print >>f,'hello', > Thanks, but that's what I tried first. Then I though it would be nice if I could just inherit from 'file' and implement this with less code. From ian at neustyle.com Sun Jan 6 03:31:13 2008 From: ian at neustyle.com (Soviut) Date: Sun, 6 Jan 2008 00:31:13 -0800 (PST) Subject: list property fires get on append References: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com> Message-ID: On Jan 6, 3:03 am, Fredrik Lundh wrote: > i... at neustyle.com wrote: > > I've created a class that has a property which points at a private > > list. When I try to use the append() function on this list property, > > the fget method is fired rather than the fset method. If I directly > > set my property to a literal list, the set method fires. > > # this fires a get for some reason > > hierarchy.children.append( Hierarchy.Hierarchy()) > > that's the expected behaviour: you're *fetching* the "children" > attribute in order to modify it, you're not replacing it. > > reading up on Python's object model might be helpful. > > I figured that an append would be treated as a set since I'm adding to the list. But what you say makes sense, although I can't say I'm happy with the behaviour. Is there any way I can get the append to fire a set? I'm thinking of properties from my C# background where i believe that manipulation such this would be considered a set. From chaosgy at gmail.com Sat Jan 26 12:36:32 2008 From: chaosgy at gmail.com (chaosgy at gmail.com) Date: Sat, 26 Jan 2008 09:36:32 -0800 (PST) Subject: Beginner String formatting question References: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> Message-ID: <7d795bb4-665c-4a03-8d54-aef06e97f686@i29g2000prf.googlegroups.com> On 1?27?, ??1?02?, JAMoor... at gmail.com wrote: > Hi all, > > I am trying to write a simple program that will accept an integral > "time" input in the HHMMSS format and output a "HH:MM:SS" form. My > code is as follows: > ======================== > import string > > def FormatTime(time): > '''Converts an HHMMSS string to HH:MM:SS format.''' > > timeString = str(time) #converts the num to string > > hours = [timeString[0], timeString[1]] > minutes = [timeString[2], timeString[3]] > seconds = [timeString[4], timeString[5]] > > Ftime = "%s:%s:%s",(hours,minutes,seconds) > clock = Ftime.join() > > return clock > =========================== > > when I run it from IDLE, I get this: > > >>> Format.FormatTime(time) > > ['1', '1', ':', '2', '2', ':', '3', '3'] > ['1', '1', ':', '2', '2', ':', '3', '3'] > > My questions- > 1) Why is this function printing out twice? > 2)It may be a formatting issue, but I want to have the output as > "HH:MM:SS", rather than having it broken out into each cell. I > thought the 'join' command would do this, but I must not be using it > properly/understanding something. > 3)as a side note, I've noticed that the parameter "time" passed in > must be passed in as a string, otherwise I receive an error that > "time" is unsubscriptable. Am I unable to pass in an int and then > convert it to a string within the function with str()? > > I've been at this for a while, so I may not be able to see the forest > through the trees at this point. I'd greatly appreciate any > suggestions or instruction on these mistakes. > > Best, > > Jimmy import string def FormatTime(time): '''Converts an HHMMSS string to HH:MM:SS format.''' timeString = "%06d" % (time, ) #converts the num to string return timeString[:2] + ":" + timeString[2:4] + ":" + timeString[4:]; this works From thegooddale at gmail.com Thu Jan 31 00:15:05 2008 From: thegooddale at gmail.com (Yansky) Date: Wed, 30 Jan 2008 21:15:05 -0800 (PST) Subject: Online Debugging Message-ID: I'm trying to debug a script on my server and it's taking forever using print to find the error. I've tried to use the debugging examples on this page http://webpython.codepoint.net/debugging but they don't seem to be working for me. Is there an easier/better way to debug online scripts? I was hoping there might be something similar to php where it gives some error info and the line code. Cheers. From Christopher.Osthaus at ngc.com Thu Jan 17 11:06:05 2008 From: Christopher.Osthaus at ngc.com (Osthaus, Christopher (Mission Systems)) Date: Thu, 17 Jan 2008 10:06:05 -0600 Subject: Importing java within python Message-ID: Hi All, This is an easy one - I'm new to Python and working on a script where I need to use some java swing classes. I'm running Python on Windows. I've got an import statement that looks something like: from java.lang import System from javax.swing import JPasswordField from javax.swing import JOptionPane How do I get Python to recognize the java module? I assume I need to set one of my environment variables? I realize this is probably very obvious but I can't seem to figure it out :) Thanks everyone... -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun Jan 27 21:20:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jan 2008 21:20:22 -0500 Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> Message-ID: "Russ P." wrote in message news:9aec1b73-79f5-467b-a544-889107caa3b2 at q77g2000hsh.googlegroups.com... |> Perhaps this:http://www.python.org/dev/peps/pep-3107/might be relevant? | Thanks. If I read this correctly, this PEP is on track for Python 3.0. Wonderful! If you experiment with static analysis using annotations, I am sure many would be interested in the results. tjr From kay.schluehr at gmx.net Sun Jan 27 22:40:40 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 27 Jan 2008 19:40:40 -0800 (PST) Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> Message-ID: <7401a20c-d583-4690-92da-503e6651b223@b2g2000hsg.googlegroups.com> On Jan 28, 12:22 am, Arnaud Delobelle wrote: > On Jan 27, 11:00 pm, "Russ P." wrote: > > > On Jan 27, 2:49 pm, "Andr?" wrote: > > > Perhaps this:http://www.python.org/dev/peps/pep-3107/mightbe > > > relevant? > > > Andr? > > > Thanks. If I read this correctly, this PEP is on track for Python 3.0. > > Wonderful! > > Note that annotations do not provide explicit typing, AFAIK: > > def f(x:int) -> int: return x*2 > > is stricly equivalent to > > def f(x): return x*2 > f.__annotations__ = {'x':int, 'return':int} > > You still need to write a type-checking wrapper. Has anyone figured out how to match arguments passed into a "wrapper" function defined within a decorator onto the signature of f or onto f.__annotations__ respectively? > PEP 3107 mentions two > such tools: > *http://oakwinter.com/code/typecheck/ > *http://maxrepo.info/taxonomy/term/3,6/all > Neither require annotations. I like the design of the typecheck package. Everying is implemented in __init__.py ;) From jarausch at igpm.rwth-aachen.de Fri Jan 11 03:28:09 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Fri, 11 Jan 2008 09:28:09 +0100 Subject: module finalizer - is there such a beast? Message-ID: <5uonkrF1ios6tU1@mid.dfncis.de> Hi, when a module gets imported the statements not contained in function definitions or classes are executed. This can be thought of an initializer for the module. But how can I get control when the module gets unloaded either by Python's gc, Python's exit or by a module reload. Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From __peter__ at web.de Tue Jan 22 04:30:22 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 Jan 2008 10:30:22 +0100 Subject: Question on sort() key function References: <5vlopgF1mv4ekU1@mid.dfncis.de> <7xve5mfdmr.fsf@ruckus.brouhaha.com> <5vlqbjF1kl9cjU1@mid.dfncis.de> Message-ID: Robert Latest wrote: > Paul Rubin wrote: >> The attribute is on instances of File, not on the class itself. See >> if this works: >> >> flist.sort(key=lambda f: f.mod_date.toordinal) > > It doesn't throw an error any more, but neither does it sort the list. This, > however, works: > > ---------------------- > def by_date(f1, f2): > return f1.mod_date.toordinal() - f2.mod_date.toordinal() > > flist.sort(by_date) > ---------------------- > > So I'm sticking with it, although I sort of liked the key approach. > > robert This should work then: def date_key(f): return f.mod_date.toordinal() flist.sort(key=date_key) This can also be written as flist.sort(key=lambda f: f.mod_date.toordinal()) Peter From jpeng at block.duxieweb.com Mon Jan 21 03:03:37 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Mon, 21 Jan 2008 16:03:37 +0800 Subject: Sorting a list depending of the indexes of another sorted list In-Reply-To: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> Message-ID: <479451D9.3060207@block.duxieweb.com> I tried to write it below,it can work,:) v= """preference 10 host mx1.domain.com preference 30 host anotherhost.domain.com preference 20 host mx2.domain.com""" x=v.split("\n") li =[] for i in x: k = (i.split())[3] y = (i.split())[1] li.append((y,k)) li.sort() print li the output is: [('10', 'mx1.domain.com'), ('20', 'mx2.domain.com'), ('30', 'anotherhost.domain.com')] Santiago Romero ??: > Hi ... > > I have the following DNS MX records info: > > domain.com > preference 10 host mx1.domain.com > preference 30 host anotherhost.domain.com > preference 20 host mx2.domain.com > > I'm storing this info in 2 lists: > > preferences = [10, 30, 20] > hosts = [ "mx1.domain.com", "anotherhost.domain.com", > "mx2.domain.com"] > From paul at boddie.org.uk Wed Jan 23 07:57:48 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 23 Jan 2008 04:57:48 -0800 (PST) Subject: Problem with processing XML References: <13pbudgks88rcf3@corp.supernews.com> <47971EFF.8070701@web.de> Message-ID: <6c291c78-7a11-4d6f-be15-c916017ccf60@s13g2000prd.googlegroups.com> On 23 Jan, 12:03, Stefan Behnel wrote: > > I had a discussion with Java people lately and they were all for Ruby, Groovy > and similar languages, "because they have curly braces and are easy to learn > when you know Java". > > My take on that is: Python is easy to learn, full-stop. Well, that may be so, but it's somewhat beside the point in question. > It's the same for DOM: when you know DOM from (usually) the Java world, having > a DOM-API in Python keeps you from having to learn too many new things. But > when you get your nose kicked into ElementTree, having to learn new things > will actually help you in understanding that what you knew before did not > support your way of thinking. I'm not disputing the benefits of the ElementTree approach, but one has to recall that the DOM is probably the most widely used XML API out there (being the one most client-side developers are using) and together with the other standards (XPath and so on) isn't as bad as most people like to make out. Furthermore, I don't think it does Python much good to have people "acting all Ruby on Rails" and telling people to throw out everything they ever did in order to suck up the benefits, regardless of the magnitude of those benefits; it comes across as saying that "your experience counts for nothing compared to our superior skills". Not exactly the best way to keep people around. As I noted in my chronology, the kind of attitude projected by various people in the Python community at various times (and probably still perpetuated in the Ruby community) is that stuff originating from the W3C is bad like, for example, XSLT because "it's like Lisp but all in XML (yuck!)", and yet for many tasks the most elegant solution is actually XSLT because it's specifically designed for those very tasks. Fortunately or unfortunately, XSLT didn't make it into the standard library and thus isn't provided in a way which may or may not seem broken but, like the DOM stuff, if the support for standardised/ recognised technologies is perceived as deficient, and given the point above about glossing over what people themselves bring with them to solve a particular problem, then people are quite likely to gloss over Python than hear anyone's sermon about how great Python's other XML technologies are. > http://www.python.org/about/success/esr/ > > So, there is a learning curve, but it's much shorter than what you already > invested to learn 'the wrong thing'. It's what people on this list tend to > call their "unlearning curve". Well, maybe if someone helped the inquirer with his namespace problem he'd be getting along quite nicely with his "unlearning curve". Paul From aisaac at american.edu Tue Jan 22 11:10:53 2008 From: aisaac at american.edu (Alan Isaac) Date: Tue, 22 Jan 2008 16:10:53 GMT Subject: pairs from a list In-Reply-To: References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: Arnaud Delobelle wrote: > According to the docs [1], izip is defined to be equivalent to: > > def izip(*iterables): > iterables = map(iter, iterables) > while iterables: > result = [it.next() for it in iterables] > yield tuple(result) > > This guarantees that it.next() will be performed from left to right, > so there is no risk that e.g. pairs4([1, 2, 3, 4]) returns [(2, 1), > (4, 3)]. > > Is there anything else that I am overlooking? > > [1] http://docs.python.org/lib/itertools-functions.html fwiw, Alan Isaac From bruno.desthuilliers at gmail.com Wed Jan 9 18:10:55 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 9 Jan 2008 15:10:55 -0800 (PST) Subject: Python too slow? References: 76bc64cc-541c-434f-aac5-96d1a2d231ee@c23g2000hsa.googlegroups.com Message-ID: <7115e305-429c-47d3-a942-8a0e2a0e846f@m34g2000hsf.googlegroups.com> On 10 jan, 00:02, "bruno.desthuilli... at gmail.com" > (sorry, hit the wrong key - time to bed I guess...) > If none of the two above answers fits your needs, and no Python Guru > comes with a better answer, then I'm afraid you'll have to go for a > language with a faster implementation. Python is quite faster nowadays > than it used to be, and is usually fast enough for most day-to-day > programming tasks (a ... at least for my own day-to-day tasks) > but it's still not as highly optimized as some > Lisp implementations (to compare to another highly ... dynamic language). From tjreedy at udel.edu Thu Jan 31 19:18:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Jan 2008 19:18:57 -0500 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: "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. From timr at probo.com Sun Jan 13 18:36:57 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 13 Jan 2008 23:36:57 GMT Subject: paging in python shell References: Message-ID: "Alex K" wrote: > >Does anyone know if the python shell supports paging or if I should >look into iPython? Thank you so much. "Paging" is an overloaded term. What do you mean, exactly? Do you mean something like piping the output into "more"? The Python shell does that for the "help" command, but maybe you could post a more precise example of what you want. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From nick at craig-wood.com Wed Jan 9 09:30:06 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 09 Jan 2008 08:30:06 -0600 Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <87ejcri96v.fsf@mulj.homelinux.net> <87abnfi84i.fsf@mulj.homelinux.net> <5ujp20F1ehvg2U2@mid.dfncis.de> Message-ID: Fredrik Lundh wrote: > Nick Craig-Wood wrote: > > > Using keywords[:] stops the creation of another temporary list. > > in CPython, "list[:] = iter" actually creates a temporary list object on > the inside, in case "iter" isn't already a list or a tuple. > > (see the implementation of PySequence_Fast() for details). Ah, OK, thanks for the correction! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bladedpenguin at gmail.com Sat Jan 26 01:52:58 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 22:52:58 -0800 (PST) Subject: Doesn't know what it wants References: Message-ID: <0104616d-87be-4250-b3ef-7a77ac39664a@u10g2000prn.googlegroups.com> On Jan 26, 1:41 am, John Machin wrote: > On Jan 26, 4:20 pm, Tim Rau wrote: > > > > > Traceback (most recent call last): > > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > > \sandbox.py", line 242, in > > player = ship() > > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > > \sandbox.py", line 121, in __init__ > > self.phyInit() > > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > > \sandbox.py", line 147, in phyInit > > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) > > ArgumentError: argument 4: : expected > > vec2d instance instead of vec2d > > > As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't > > seems like it doesn't know what it wants, but I thought only teenagers > > did that, no programming languages. > > It possibly means that it is expecting an instance of a class whose > name is "vec2d" but you have given it an instance of some *other* > class whose name just happens to be "vec2d". > > > clearly, Im missing something. > > Yes, some information: > 1. what is vec2d, class or function? > 2. what do you believe vec2d((0, 0)) should return? > 3. what is this belief based on? > 4. what has it actually returned this time? > 5. what do you believe that cp.cpMomentForCircle expects as argument > 4? > 6. what is this belief based on? > > The ArgumentError exception is raised by ctypes "when a foreign > function call cannot convert one of the passed arguments". Based on > guessin'n'googlin' the cp thing is a set of Python bindings to a > library written in C++ ... have you considered asking the author of > the bindings? 1. vec2d is a class, designed to hold and manipulte 2d vectors 2. it should return a vector with x=0 and y=0 3. That's what it's done before. 4. trying it in the interpreter seems to show that it returns a vec2d with zero length. as it should. 5.cp.cpMomentForCircle seems to expect a vec2d. I'm baseing that on a functioning demo that uses the exact same line. I guess that the vec2d I've got is not the one it wants. How do I tell the difference? I'll go look at all the imports. From steve at holdenweb.com Wed Jan 23 22:54:48 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 23 Jan 2008 22:54:48 -0500 Subject: newbie question: On installation of additional packages to Python In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Tue, 22 Jan 2008 00:36:34 -0200, Nasser Abbasi escribi?: > >> I am running on windowz. I have downloaded and installed 2.5.1 Python. >> >> my question is on installing additional packages. >> >> What is the easiest way to do that? I read about python 'eggs' (like jar >> files for Java), and easyInstall script, and such. > > Once you have setuptools installed, it's as easy as executing: > easy_install packagename > The alternative is to find and download the package yourself, unzip in a > temporary directory, and execute: setup.py install > For most packages that's all that is required. > >> Is there some automated way to install Python packages? a >> manual/document I >> could read that describes step by step how to do that? Browsing the >> documentation, there does not seem to be something specific there (other >> than saying download this tar file and install it). >> >> I like how one can install additional packages in 'R' . In 'R' one can do >> all that from the user interface for R by a pull-down menu, then one >> selects >> a mirror site, then one can see all the packages available, then select >> the >> package to download, and the rest is done automatically. (The package is >> downloaded, installed, etc...) > > That's mainly what easy_install does, plus dependency checking. > So, the only step you are missing is how to install setuptools. This is simplicity itself: 1. In your web browser visit http://peak.telecommunity.com/dist/ez_setup.py 2. Save the Python. In Internet Explorer use "File | Save As", in Firefox use "File | Save Page As" 3. Run it from the command line (or possibly by double-clicking it in an explorer window, never tried that) You should now be able to run easy_install from the command line and install packages from the usual suspects. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gherron at islandtraining.com Fri Jan 11 03:30:46 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 11 Jan 2008 00:30:46 -0800 Subject: HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? In-Reply-To: <7243c2ac-fa22-4b5b-bd8c-34235123ab69@t1g2000pra.googlegroups.com> References: <7243c2ac-fa22-4b5b-bd8c-34235123ab69@t1g2000pra.googlegroups.com> Message-ID: <47872936.9070603@islandtraining.com> abhishek wrote: > Hi group any idea on HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? > > > Thank you > POINTERS? Heaps? Huh? Ummm, let me think -- those terms *do* sound vaguely familiar -- from sometime in the deep dark primitive past. Perhaps from back in my (shudder) C/C++ days -- ya, that's it. Thankfully, this is Python and the modern era -- we don't use no stinking POINTERS here. Seriously, this group deals with Python. There are no pointers in Python. Now please, what did you *really* mean to ask? Gary Herron From steven.bethard at gmail.com Tue Jan 15 13:58:41 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 15 Jan 2008 11:58:41 -0700 Subject: SyntaxError: 'import *' not allowed with 'from .' In-Reply-To: <9ac37212-7521-454d-a35f-afd6f7ec24f6@m34g2000hsf.googlegroups.com> References: <9ac37212-7521-454d-a35f-afd6f7ec24f6@m34g2000hsf.googlegroups.com> Message-ID: George Sakkis wrote: > Unless I missed it, PEP 328 doesn't mention anything about this. > What's the reason for not allowing "from .relative.module import *' ? Generally, there's a move away from all "import *" versions these days. For example, Python 3.0 removes the ability to use "import *" within a function: http://www.python.org/dev/peps/pep-3100/ I suspect the "import *" version is not enabled for relative imports because most of python-dev is against "import *" forms anywhere. STeVe From tommy.nordgren at comhem.se Fri Jan 11 19:48:40 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Sat, 12 Jan 2008 01:48:40 +0100 Subject: IDLE won't start in Python 2.5 for Windows In-Reply-To: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> References: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> Message-ID: <5C0D44EF-6B44-4024-85FA-82CF56DB738F@comhem.se> On 12 jan 2008, at 01.18, mikez302 wrote: > I have Python 2.5 and Windows XP SP2. For a while, IDLE worked, but > now it doesn't. The last time I was using it, I was changing some > keyboard shortcuts, then the window suddenly disappeared. Since then, > I haven't been able to start it. > > When I try to start it, I see pythonw.exe come up on my Task Manager > for about a second, then disappear. Other than that, I don't see any > hint as to what is happening. The Python command line works fine. > > I tried rebooting, repairing Python, uninstalling and reinstalling > Python, and upgrading to version 2.5.1, but I still haven't fixed the > problem. Is there anything else I can do to fix it? > > Elias > -- > http://mail.python.org/mailman/listinfo/python-list I suggest you try: 1) Cleaning the registry 2) Searching for IDLE preference files and delete them. Corrupt preference settings are a common cause for application misfunction on all Operating Systems. ------------------------------------------------------ "Home is not where you are born, but where your heart finds peace" - Tommy Nordgren, "The dying old crone" tommy.nordgren at comhem.se From ggpolo at gmail.com Wed Jan 23 19:11:15 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jan 2008 22:11:15 -0200 Subject: Creating new types and invoking super In-Reply-To: <9eeb9667-f362-4ce2-971a-42ef639c8f86@c4g2000hsg.googlegroups.com> References: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> <9eeb9667-f362-4ce2-971a-42ef639c8f86@c4g2000hsg.googlegroups.com> Message-ID: 2008/1/23, Arnaud Delobelle : > On Jan 23, 10:18 pm, "Guilherme Polo" wrote: > > 2008/1/23, Arnaud Delobelle : > > > > > The only way I can think of would be to create a metaclass, but I > > > don't think it's worth it. super(A, obj).__init__() isn't that bad! > > > > Metaclass doesn't apply here because metaclass is related to > > class-construction. This is related to instance initialization, and > > I'm creating the types as the user asks. > > Not completely clear to me what you want but here is a 'proof of > concept': > > ========== > > class callsuper(object): > def __init__(self, f): > self.f = f > def __get__(self, obj, cls=None): > def newfunc(*args, **kwargs): > super(self.cls, obj).__init__() > return self.f(obj, *args, **kwargs) > return newfunc > > class Type(type): > def __init__(self, name, bases, attrs): > for attrname, attr in attrs.iteritems(): > if isinstance(attr, callsuper): > attr.cls = self > > class A: > __metaclass__ = Type > def __init__(self): > print "init A" > > class B(A): > @callsuper > def __init__(self): > print "init B" > > ========== > > >>> b=B() > init A > init B > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for this concept, works better than mine :) -- -- Guilherme H. Polo Goncalves From robert.rawlins at thinkbluemedia.co.uk Mon Jan 28 12:46:14 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 28 Jan 2008 17:46:14 -0000 Subject: Get Available Functions In-Reply-To: <479E0A7A.9080305@tim.thechases.com> References: <020501c861ca$d604dc70$820e9550$@rawlins@thinkbluemedia.co.uk> <479E0A7A.9080305@tim.thechases.com> Message-ID: <022f01c861d5$ad6b7c50$084274f0$@rawlins@thinkbluemedia.co.uk> Thanks for that Tim, I'll have a play around with these functions later today and see what happens, hopefully it'll shed some light on this API for me. Thanks mate, I appreciate it. Rob -----Original Message----- From: Tim Chase [mailto:python.list at tim.thechases.com] Sent: 28 January 2008 17:02 To: Robert Rawlins - Think Blue Cc: python-list at python.org Subject: Re: Get Available Functions > I'm working with a python module which isn't part of the core > Python API and it also isn't very documented or supported, is > there any way that I can easily dump/view the available > classes and methods within the package from within python? Most of the time, the dir(), type() and help() functions can be your friend: >>> import somelib >>> dir(somelib) ['Foo', 'thing', 'whatever'] >>> type(somelib.Foo) >>> dir(somelib.Foo) ['method1', 'method2'] >>> type(somelib.thing) >>> print somelib.thing 'I didn't expect the Spanish Inquisition!' >>> type(somelib.whatever) >>> help(somelib.whatever) Help on function whatever in module somelib: whatever(param1, param2, *args, **kwargs) >>> I've had a couple cases where the underlying module was written in C (mod_python in particular...don't know if it still has this problem) where dir() wouldn't actually tell you about the object, but for most cases, dir() will get you pointed in the right dir-ection. :) -tkc From fredrik at pythonware.com Sun Jan 13 08:02:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 13 Jan 2008 14:02:13 +0100 Subject: Simple List division problem In-Reply-To: <00cb6e9d-e8b6-4e65-be58-5a4472413c53@j78g2000hsd.googlegroups.com> References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> <00cb6e9d-e8b6-4e65-be58-5a4472413c53@j78g2000hsd.googlegroups.com> Message-ID: thebjorn wrote: > Eh... oh, forgot that it was "pulling requirements out of thin air" week on c.l.python. > def chop(lst, length): > n = len(lst) / length > z = [lst[i:i+n] for i in xrange(0, len(lst), n)] > if len(z[-1]) < n and len(z) > 1: > z[-2].extend(z.pop(-1)) > return z > > gives >>>> chop([1], 3) > Traceback (most recent call last): > File "", line 1, in > File "beforemeth.py", line 9, in chop > if len(z[-1]) < n and len(z) > 1: > ValueError: xrange() arg 3 must not be zero well, it doesn't. there's no xrange on that line. > Perhaps something like this? > from itertools import islice or just use an if-statement, or the max function. but I guess those tools are too old and boring for c.l.python these days... From peter.maas at somewhere.com Sat Jan 5 15:29:49 2008 From: peter.maas at somewhere.com (Peter Maas) Date: Sat, 05 Jan 2008 21:29:49 +0100 Subject: python interfaces In-Reply-To: References: Message-ID: Sion Arrowsmith wrote: > hyperboreean wrote: >> Why doesn't python provide interfaces trough its standard library? > > Because they're pointless. Wrong. I'm using Eclipse with the Java Development Tools (JDT) who do a wonderful job using interfaces to perform lots of checking, warning and code generation *nearly in real time while I am editing my code*. Because JDT knows interfaces it knows what to do and to suggest. An interface is a software specification allowing you to use a software package without extensive code studies. This is a good thing. > Java interfaces are a hack around the complexities of multiple > inheritence. A hack is something applied subsequently to solve a software problem while avoiding large changes. Java interfaces originate from careful language design. You are free to dislike Java interfaces but calling them a hack is just plain wrong. Once software becomes really big interfaces are very useful to handle complexity. Ever wondered why the Zope people introduced interfaces in their Python code? > Interfaces used purely with the idea of type safety provide > precious little gain for the added clutter and inconvenience. An interface is a software specification allowing you to use a software package without extensive code studies. This is a good thing. Interfaces have nothing to do with multiple inheritance. They just tell you how to connect, how to plug in. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From grante at visi.com Mon Jan 21 11:04:25 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 21 Jan 2008 16:04:25 -0000 Subject: Memory errors with imaplib References: <6012daff-0fd3-4835-a9ca-c18d2a2ac53c@v29g2000hsf.googlegroups.com> <13p6pf5he8am89e@corp.supernews.com> <13p7jubq0hiqr55@corp.supernews.com> Message-ID: <13p9gk93fi8gh75@corp.supernews.com> On 2008-01-21, Christian Heimes wrote: > Grant Edwards wrote: > >> If the solution shown in the bug report is correct, I'd be >> more than happy to generate a patch. > > The solution seems fine but IMO it should be fixed in the ssl > socket and not in imaplib. I like to get it *fixed* and not > *worked around*. :) I've always been taught that you can't assume that a read on a socket (ssl or otherwise) will return the number of bytes you request. You've always got to code for the case where read() returns smaller chunks. Maybe I've been taught wrongly, but under Unix at least I've found that it's always a good practice to assume that network reads will often return smaller chunks than requested. -- Grant Edwards grante Yow! Are we on STRIKE yet? at visi.com From andre.roberge at gmail.com Sun Jan 27 22:18:29 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 27 Jan 2008 19:18:29 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> <7xhcgyodvy.fsf@ruckus.brouhaha.com> Message-ID: <9a9f7b3f-50ff-46f9-9c7e-5d635ff7bec3@n20g2000hsh.googlegroups.com> On Jan 27, 10:57 pm, Paul Rubin wrote: > Wildemar Wildenburger writes: > > class Server(object): > > def __init__(self, self.host, self.port, > > self.protocol, self.bufsize, self.timeout): > > pass > > ? > > That could temporarily bind those attributes but it shouldn't > persistently mutate the object. > > How about: > > class Server(object): > def __init__(self, host, port, protocol, bufsize, timeout): > self.(host, port, protocol, bufsize, timeout) = \ > host, port, protocol, bufsize, timeout > > That's fairly explicit yet cuts down the total amount of boilerplate. Not much; you're still repeating each variable name 3 times. I prefer the standard way of one definition per line over this notation myself. Andr? From cokofreedom at gmail.com Thu Jan 24 03:24:58 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 24 Jan 2008 00:24:58 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <7x8x2g8isi.fsf@ruckus.brouhaha.com> <13pfgdct573772d@corp.supernews.com> <04d0ed52-4b45-4c07-8ea6-ab3bb3f85225@e25g2000prg.googlegroups.com> <18aa66c3-78ba-45f6-aeb4-9dec0a37e074@t1g2000pra.googlegroups.com> Message-ID: <26a4c312-4969-412e-b368-1ffbead47fff@l32g2000hse.googlegroups.com> On Jan 24, 8:21 am, ryan k wrote: > On Jan 23, 6:30 pm, John Machin wrote: > > > On Jan 24, 9:50 am, ryan k wrote: > > > > Steven D'Aprano, you are a prick. > > > And your reasons for coming to that stridently expressed conclusion > > after reading a posting that was *not* addressed to you are .....? > > Because his tone is extremely condescending and quite frankly > annoying. From this post to others, his terse remarks scar this > community and fade its atmosphere of friendliness. And your response was any better because...? From andre.roberge at gmail.com Mon Jan 28 11:08:18 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 28 Jan 2008 08:08:18 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> Message-ID: On Jan 28, 11:45 am, Steven Bethard wrote: > Arnaud Delobelle wrote: > > Sligthly improved (not for performance! but signature-preserving and > > looks for default values) > > > from functools import wraps > > from inspect import getargspec > > from itertools import izip, chain > > > def autoassign(*names): > > def decorator(f): > > fargnames, _, _, fdefaults = getargspec(f) > > defaults = [(n,v) for (n,v) > > in izip(reversed(fargnames), reversed(fdefaults)) > > if n in names] > > @wraps(f) > > def decorated(self, *args, **kwargs): > > self.__dict__.update(defaults) > > for name, arg in chain(izip(fargnames, args), > > kwargs.iteritems()): > > if name in names: > > setattr(self, name, arg) > > return f(self, *args, **kwargs) > > return decorated > > return decorator > > > class Test(object): > > @autoassign('foo', 'bar') > > def __init__(self, foo, bar=3, baz=6): > > print 'baz =', baz > > > t = Test(1, 2, 6) > > u = Test(foo=8) > > > print t.foo # 1 > > print t.bar # 2 > > > print u.foo # 8 > > print u.bar # 3 (default) > > You should definitely post this to the cookbook: > > http://aspn.activestate.com/ASPN/Cookbook/Python > > STeVe If I may suggest, I would extend this so that autoassign's signature would be as follows: autoassign(all=True, include_only=None, exclude=None) Either one of include_only or exclude could be a list of function to which the automatic assignment would apply (or not). I was planning to write this up and submit it to the cookbook later this evening, but since the suggestion has been made, someone else can jump on it. ;-) Andr? From cwitts at gmail.com Fri Jan 4 08:58:35 2008 From: cwitts at gmail.com (Chris) Date: Fri, 4 Jan 2008 05:58:35 -0800 (PST) Subject: Strange varargs issue References: Message-ID: On Jan 4, 3:45 pm, Mike wrote: > I'm not sure if this is a bug or if I'm just not understanding > something correctly. I'm running the following (broken.py) on > ActivePython 2.5.1.1, based on Python 2.5.1 (r251:54863 5/1/2007) as > "python broken.py foo" (on Windows, of course): > > #!/bin/env python > > import sys > > class foobar(object): > def func(arg): > print 'foobar.func: %r' % arg > > __f = foobar() > > def caller(a): > print 'caller: %r' % a > __f.func(a) > > def main(): > rest = sys.argv[1:] > print 'main: %r' % rest > caller(*rest) > > if __name__ == '__main__': > main() > > ...and the result of running this ("python broken.py foo") is: > > main: ['foo'] > caller: 'foo' > Traceback (most recent call last): > File "broken.py", line 21, in > main() > File "broken.py", line 18, in main > caller(*rest) > File "broken.py", line 13, in caller > __f.func(a) > TypeError: func() takes exactly 1 argument (2 given) > > How can this possibly be? The "caller" print statement obviously > shows "a" is singular. > > Thanks in advance for any and all insight... > > Mike class foobar(object): def func(arg): print 'foobar.func: %r' % arg def caller(a): __f.func() >>> main: ['foo'] >>> caller: 'foo' >>> foobar.func: <__main__.foobar object at 0x00A45550> class foobar(object): def func(self, arg): print 'foobar.func: %r' % arg def caller(a): __f.func(a) >>> main: ['foo'] >>> caller: 'foo' >>> foobar.func: 'foo' You're already passing the object as an argument in the first case. From list-ener at strank.info Tue Jan 22 10:29:32 2008 From: list-ener at strank.info (Stefan Rank) Date: Tue, 22 Jan 2008 16:29:32 +0100 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <707d792b-e802-4c0e-854e-aac264d83c48@c4g2000hsg.googlegroups.com> References: <5vm8t3F1m1797U1@mid.uni-berlin.de> <707d792b-e802-4c0e-854e-aac264d83c48@c4g2000hsg.googlegroups.com> Message-ID: <47960BDC.3030809@strank.info> on 22.01.2008 16:09 Paul McGuire said the following: > On Jan 22, 7:46 am, Stefan Rank wrote: >> I also need to test for generator functions from time to time for which >> I use:: >> >> def _isaGeneratorFunction(func): >> '''Check the bitmask of `func` for the magic generator flag.''' >> return bool(func.func_code.co_flags & CO_GENERATOR) >> >> cheers, >> stefan > > Might want to catch AttributeError in this routine - not all func > arguments will have a func_code attribute. See below: > > class Z(object): > def __call__(*args): > for i in range(3): > yield 1 > > for i in Z()(): > print i > # prints 1 three times > > import types > print type(Z()()) == types.GeneratorType > # prints 'True' > > print Z()().func_code > # raises AttributeError, doesn't have a func_code attribute You are right about that for generator *objects*. But _isaGeneratorFunction tests for generator *functions* (the ones you call in order to get a generator object) and those must have a func_code. So in your example:: >>> from compiler.consts import CO_GENERATOR >>> Z().__call__.func_code.co_flags & CO_GENERATOR 32 >>> Z.__call__.func_code.co_flags & CO_GENERATOR 32 You have to use __call__ directly, you can't use the code-object-flag test on the callable class instance Z(), but I think that's just as well since this kind of test should not be necessary at all, except in rare code parts (such as Diez' microthreading experiments). cheers, stefan From ivanlan9 at gmail.com Tue Jan 29 13:03:20 2008 From: ivanlan9 at gmail.com (Ivan Van Laningham) Date: Tue, 29 Jan 2008 11:03:20 -0700 Subject: Problem with Tkinter scrollbar callback In-Reply-To: References: Message-ID: No Joy. Waits the 1 second, then clicks the button once per second until the limit's reached. Sigh. Metta, Ivan On Jan 29, 2008 10:20 AM, Russell E Owen wrote: > >Nope: > > > >'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '300'), > > > >And even after I set it, it looks funny: > > > >'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '1000'), > > > >And when I try it with the new repeatdelay (1000), the only thing that > >has changed is that it waits 1000 milliseconds before exhibiting the > >same uncontrolled growth as before. > > You need to change repeatinterval, not repeatdelay. > > As to "looking funny": that is the standard output format for > configure(). I think can get a more reasonable value using > "cget(repeatdelay)". > > -- Russell > > > > > >Metta, > >Ivan > > > >On Jan 25, 2008 5:49 PM, Russell E. Owen wrote: > >> In article , > >> "Ivan Van Laningham" wrote: > >> > >> > Hi All-- > >> > That helps. Doing a get() on the scrollbar before a set(0.0,0.0) > >> > returns a 4-tuple: (0.0, 0.0, 0.0, 0.0) ! I did the set(0.0,0.0) > >> > and now the callback gets the correct number of arguments. > >> > > >> > However, I'm still getting the weird behaviour when clicking the > >> > arrowheads--and the heads are all I want. They act like they've been > >> > set to a keybounce timeout of about a millisecond. ... The arrow > >> > click increments the number of cells in a table row (effectively), and > >> > it shoots up from 5 to 26 columns almost instantly (that's the > >> > internal max I set). > >> > >> Is the scroll bar's repeatinterval set to a reasonable value? > >> > >> -- Russell > >> > >> -- > >> 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 > > -- 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 deets at nospam.web.de Mon Jan 28 10:30:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jan 2008 16:30:29 +0100 Subject: sharing objects between classes References: Message-ID: <606aolF1pa0tfU2@mid.uni-berlin.de> Gerardo Herzig wrote: > Hi all. Im wondering the way to share a database connection between some > classes: > > So far, i came up with a simple class schema, where each class means > each different relation, i mean i have the follow classes > > class Database(object): > ## make the connection > self.conn = make_conn(....) > > class Table(object): > def get_fields: > .... > > And at this point i dont know how to use the Database.conn attribute, > since the get_fields method will perform a query over the given database. > At first, i just define the Table class as a inner class of Database, > but if i try a > class Database(object): > ## make the connection > def __init__(self): > self.conn = sql_connect(....) > self.table = Table('foo') > > class Table(object): ## inner class > def get_fields(self, name): > .... > > I get a "NameError: global name 'Table' is not defined". > > So, which would the right pattern to use here? Using a global module? I > dont know why, but i dont like that idea too much. > > Any comments will be appreciated! > Thanks! Take a look at the sources of e.g. SQLObject and how they do it (in SO, the concept is called "HUB") Essentially, you set a reference to a global connection object that itself isn't a simple global but useses threading.local to have one connection per thread. Then you can access that connection transparently. Diez From mmanns at gmx.net Sun Jan 13 16:31:15 2008 From: mmanns at gmx.net (Martin Manns) Date: Sun, 13 Jan 2008 22:31:15 +0100 Subject: Slicing wrapped numpy arrays Message-ID: Hi, I have created a class that wraps a numpy array of custom objects. I would like to be able to slice respective objects (without copying the array if possible). I have browsed the doc and found some hints at __getitem__. However, I still do not grasp how to do it. How do I implement __getitem__ correctly? from numpy import * class Cell(object): pass class Map(object): def __init__(self, dimensions): self.generate_map(dimensions) def generate_map(self, dimensions): map_range = xrange(reduce(lambda x,y: x*y, dimensions)) self.map = array([Cell() for i in map_range]) self.map = self.map.reshape(dimensions) mymap = Map((100, 100, 100)) mymap[10:20,15:20,:] # This line should work afterwards Thanks in advance Martin From paul.hankin at gmail.com Tue Jan 29 17:49:09 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 29 Jan 2008 14:49:09 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: Message-ID: On Jan 29, 4:34?pm, William McBrine wrote: > Look at this -- from Python 2.5.1: > > >>> a = [1, 2, 3, 4, 5] > >>> for x in a: > > ... ? ? if x == 3: > ... ? ? ? ? a.remove(x) > ... ? ? print x > ... > 1 > 2 > 3 > 5 > > >>> a > [1, 2, 4, 5] > > Sure, the resulting list is correct. But 4 is never printed during the > loop! > > What I was really trying to do was this: > > apps = [name for name in os.listdir(ROOT) if > ? ? ? ? os.path.isdir(os.path.join(ROOT, name))] > > apptitles = {} > > for name in apps: > ? ? try: > ? ? ? ? app = __import__(name) > ? ? except: > ? ? ? ? apps.remove(name) > ? ? else: > ? ? ? ? apptitles[name] = getattr(app, 'TITLE', name.title()) > > which worked fine, until I actually had a directory with no module in it. > Then that directory was correctly removed from the list, but the _next_ > one was skipped, so its title was never assigned, which caused problems > later in the program. How about... for name in apps: try: app == __import__(name) apptitles[name] = getattr(app, 'TITLE', name.title()) except ImportError: pass # Remove apps with no title, ie those that didn't import. apps = [name for name in apps if apptitles.get(name)] Alternatives for the last line would be 'apps = filter(apptitles.get, apps)' or 'apps = apptitles.keys()'. -- Paul Hankin From jo at durchholz.org Tue Jan 1 11:14:45 2008 From: jo at durchholz.org (Joachim Durchholz) Date: Tue, 01 Jan 2008 17:14:45 +0100 Subject: Choosing a new language In-Reply-To: References: <20071228162351.f29a3ce4.coolzone@it.dk> Message-ID: > Xah Lee wrote: >> [...] PHP and Perl are practically identical in their >> high-levelness or expressiveness or field of application (and >> syntax), That must have been a very, very distant point of view with narrowly squinted eyes. Regards, Jo From donn.ingle at gmail.com Thu Jan 24 10:17:25 2008 From: donn.ingle at gmail.com (Donn Ingle) Date: Thu, 24 Jan 2008 17:17:25 +0200 Subject: piping into a python script Message-ID: Hi, (Gnu/Linux - Python 2.4/5) Given these two examples: 1. ./fui.py *.py 2. ls *.py | ./fui.py How can I capture a list of the arguments? I need to get all the strings (file or dir names) passed via the normal command line and any that may come from a pipe. There is a third case: 3. ls *.jpg | ./fui.py *.png Where I would be gathering strings from two places. I am trying to write a command-line friendly tool that can be used in traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. I have tried: 1. pipedIn = sys.stdin.readlines() Works fine for example 2, but example 1 goes into a 'wait for input' mode and that's no good. Is there a way to tell when no input is coming from a pipe at all? 2. import fileinput for line in fileinput.input(): print (line) But this opens each file and I don't want that. I have seen a lot of search results that don't quite answer this angle of the question, so I'm trying on the list. \d From gagsl-py2 at yahoo.com.ar Thu Jan 24 02:43:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 Jan 2008 05:43:22 -0200 Subject: Smart factory class References: Message-ID: En Thu, 24 Jan 2008 05:11:19 -0200, kramer31 escribi?: > Can anyone tell me if there is a way in python that I can implement a > factory function which takes as input a string ClassName and returns > an object of type ClassName? def InstanceFactory(classname): cls = globals()[classname] return cls() If the class resides in a different module: def InstanceFactory(modulename, classname): if '.' in modulename: raise ValueError, "can't handle dotted modules yet" mod = __import__(modulename) cls = getattr(mod, classname] return cls() I suppose you get the names from a configuration file or something - usually it's better to just pass the class instead of the class name. -- Gabriel Genellina From detlev at die-offenbachs.de Sat Jan 12 03:50:32 2008 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 12 Jan 2008 09:50:32 +0100 Subject: eric4 request for contribution Message-ID: Hi, I am in the progress of writing a refactoring plugin for eric4 using the rope refactoring library. Unfortunately, this library does not contain a nice icon to be shown in an About Rope dialog. Is there anybody around, who could contribute such an icon. Maybe it could look like the Python snake but instead of the snake a rope is shown. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From remco at gerlich.nl Wed Jan 23 09:18:22 2008 From: remco at gerlich.nl (Remco Gerlich) Date: Wed, 23 Jan 2008 15:18:22 +0100 Subject: How avoid both a newline and a space between 2 print commands? In-Reply-To: References: Message-ID: <7ae3ca10801230618m58823d19ied08079091e1a0f1@mail.gmail.com> Hi, Use import sys sys.stdout.write("foo") sys.stdout.write("bar") (and, possibly, sys.stdout.flush() to get the text to show up, it might wait for the end of a complete line otherwise). The alternative import sys print "foo", sys.stdout.softspace=0 print "bar" is just too hackish. In Python 3, this will be improved! Remco On Jan 23, 2008 3:03 PM, seberino at spawar.navy.mil wrote: > print "foo" > print "bar" > > has a newline in between "foo" and "bar" > > print "foo", > print "bar" > > has a space in between "foo" and "bar" > > How prevent ANYTHING from going in between "foo" and "bar" ?? > > (Without defining a string variable.) > > Chris > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From theller at ctypes.org Fri Jan 25 07:59:56 2008 From: theller at ctypes.org (Thomas Heller) Date: Fri, 25 Jan 2008 13:59:56 +0100 Subject: Windows AVIFile problems In-Reply-To: References: Message-ID: c d saunter schrieb: > Hi All, > > I'm trying to access individual video frames of an AVI file from within > Python 2.4 or 2.5 under Windows XP. > > I have found this example code here for that does exactly what I want, > using the windows avifile.dll but I am unable to find the AVIFile.h > header... > > http://mail.python.org/pipermail/image-sig/2002-February/001748.html > > An alternative is to call into avifile.dll dynamically using ctypes, > however under both Python 2.4 and 2.5 the following error happens: > >>>> from ctypes import * >>>> windll.AVIFile > > Traceback (most recent call last): > File "", line 1, in > windll.AVIFile > File "C:\Python25\lib\ctypes\__init__.py", line 415, in __getattr__ > dll = self._dlltype(name) > File "C:\Python25\lib\ctypes\__init__.py", line 340, in __init__ > self._handle = _dlopen(self._name, mode) > WindowsError: [Error 193] %1 is not a valid Win32 application > The dll is not corrupt. It is the 16-bit dll, possibly present for legacy 16-bit support. You must use the 32-bit dll, it seems it called avifil32.dll. Also I guess to get the AVIFILE.H header file, you need to install some MS SDK or the platform sdk. Thomas From rw at smsnet.pl Wed Jan 2 16:36:27 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 02 Jan 2008 22:36:27 +0100 Subject: urllib2 disable proxy References: Message-ID: <878x373o6c.fsf@merkury.smsnet.pl> Dimitrios Apostolou writes: > Hello list, > > I've been looking for a way to explicitly disable the use of proxies with > urllib2, no matter what the environment dictates. Unfortunately I can't find > a way in the documentation, and reading the source leads me to believe that > something like the following does the job: > > req.set_proxy(None,None) > > Where req is a urllib2.Request instance. So is there an official way of doing > this? Perhaps it should be added in the documentation? I believe that the recommended way is to use `urllib2.ProxyHandler`. Take a look at: http://www.voidspace.org.uk/python/articles/urllib2.shtml HTH, Rob From vinay_sajip at yahoo.co.uk Tue Jan 8 04:08:08 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 8 Jan 2008 01:08:08 -0800 (PST) Subject: Passing contextual information when logging Message-ID: Some users of the logging package have raised an issue regarding the difficulty of passing additional contextual information when logging. For example, the developer of a networked application may want to log, in addition to specifics related to to the network service being provided, information about the IP address of the remote machine and the username of the person logged into and using the service. Python 2.4 introduced an 'extra' keyword argument which was intended to hold a dict-like object containing additional information to be added to a LogRecord. The additional information would then be printed via placeholders in a format string. While this works, it is a little unwieldy to use in practice, because users need to provide the 'extra' parameter in every logging call. This has led people in some instances to create context-specific Logger instances (e.g. one logger for every connection). This has a drawback in that a logger name can only provide limited contextual information, and moreover, if the number of connections is effectively unbounded over time, the number of Logger instances will also grow in an unbounded way. (Logger instances are never garbage collected, because references to them are always held in the logging package. This alleviates a burden on users in that they never have to pass loggers around, but means that creating a lot of Logger instances will lead to a long-lived memory burden.) One solution is to create a generic wrapper around loggers to which a logger name and contextual information can be passed. The wrapper would delegate logging calls to the logger with the specified name, but would manipulate the arguments passed to the logging call to insert the contextual information. I have created such a wrapper class, called LoggerAdapter, which is in the example script located at http://dpaste.com/30230/ I would welcome your views on whether the LoggerAdapter class is suitable for adding to the logging package in Python 2.6/3.0. Does it do what might reasonably be expected out of the box? LoggerAdapters are, of course, garbage collected in the normal way and so impose no particular memory burden. Best regards, Vinay Sajip From phd at phd.pp.ru Thu Jan 10 07:38:10 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 10 Jan 2008 15:38:10 +0300 Subject: SQLObject 0.9.3 Message-ID: <20080110123810.GJ3070@phd.pp.ru> Hello! I'm pleased to announce the 0.9.3 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.3 News and changes: http://sqlobject.org/News.html What's New ========== Bug Fixes ~~~~~~~~~ * With PySQLite2 do not use encode()/decode() from PySQLite1 - always use base64 for BLOBs. * MySQLConnection doesn't convert query strings to unicode (but allows to pass unicode query strings if the user build ones). DB URI parameter sqlobject_encoding is no longer used. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From jr9445 at ATT.COM Mon Jan 7 12:09:50 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Mon, 7 Jan 2008 11:09:50 -0600 Subject: dictionary/hash and '1' versus 1 In-Reply-To: <13o06hleh4dkj45@corp.supernews.com> References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com><7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com><8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> <13o06hleh4dkj45@corp.supernews.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 Steven D'Aprano > Sent: Saturday, January 05, 2008 7:01 PM > To: python-list at python.org > Subject: Re: dictionary/hash and '1' versus 1 > > The problem with automatic conversions between strings and integers is > that it isn't clear what the user wants when they do something like > this: > > >>> x = '1' + 1 > > Should x be the string '11' or the int 2? Please justify your answer. > > > On the other hand, if the language includes separate operators for > addition and concatenation (say, + and &) then that sort of auto- > conversion is no longer ambiguous: > > >>> '2' + 3 > 5 > >>> '2' & 3 > '23' Bingo. Perl has specific operators to establish intent: > Perl -e "'1' + 1" > 2 > Perl -e "'1' . 1" > 11 '+' is the operator for addition '.' is the operator for string concatenation int and string comparisons also have specific operators: $a == $b # compare as integers: ==, >, <, <=, >= $a eq $b # compare as strings: eq, gt, lt, le, ge Which now morphs the conversation into the issue of how too much operator overloading creates confusion and/or ambiguity. ***** 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 pavlovevidence at gmail.com Thu Jan 24 03:01:02 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 24 Jan 2008 00:01:02 -0800 (PST) Subject: Module/package hierarchy and its separation from file structure References: Message-ID: <04ab182a-5ecd-4d1b-89c5-ac321048f6f1@x69g2000hsx.googlegroups.com> On Jan 23, 4:49 am, Peter Schuller wrote: > I do *not* want to simply break out X into org.lib.animal.x, and have > org.lib.animal import org.lib.animal.x.X as X. While this naively > solves the problem of being able to refer to X as org.lib.animal.X, > the solution is anything but consistent because the *identity* of X is > still org.lib.animal.x.X. Examples of way this breaks things: > > * X().__class__.__name__ gives unexpected results. > * Automatically generated documentation will document using the "real" > package name. > * Moving the *actual* classes around by way of this aliasing would > break things like pickled data structure as a result of the change > of actual identity, unless one *always* pre-emptively maintains > this shadow hierarchy (which is a problem in and of itself). You can reassign the class's module: from org.lib.animal.monkey import Monkey Monkey.__module__ = 'org.lib.animal' (Which, I must admit, is not a bad idea in some cases.) Carl Banks From jr9445 at ATT.COM Wed Jan 9 14:52:53 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 9 Jan 2008 13:52:53 -0600 Subject: problem of converting a list to dict In-Reply-To: References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> <962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.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 Fredrik Lundh > Sent: Wednesday, January 09, 2008 2:39 PM > To: python-list at python.org > Subject: Re: problem of converting a list to dict > > Louis.Soninhu at gmail.com wrote: > > >> to see what's going on on your machine, try printing "a" after the > >> split, but before you use it to populate the dictionary. > > > > 'print a' works > > so what does it tell you? > A bigger hint: a=i.split('=') print "'%s' splits into " % (i), a assert len(a) == 2 mydict[a[0]]=a[1] From israelu at elbit.co.il Wed Jan 16 17:47:44 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 16 Jan 2008 14:47:44 -0800 (PST) Subject: Hebrew in idle ans eclipse (Windows) Message-ID: Hi all, I'll realy appreciate your help in this: I read data from a database containg Hebrew words. When the application is run from IDLE a word looks like this, for example: \xe8\xe9\xe5 But when I run the same application from eclipse or the Windows shell I get the 'e's replaced with '8's: \x88\x89\x85 The IDLE way is the way I need, since using Hebrew words in the program text itself, as keys in a dict, for example, yield similar strings (with 'e's). When running from eclipse I get KeyError for this dict.. What do I need to do run my app like IDLE does? Thanks iu2 From tjreedy at udel.edu Mon Jan 28 23:01:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jan 2008 23:01:20 -0500 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net><60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net><7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com><13pqd16n4o3rufe@corp.supernews.com> Message-ID: "Andr?" wrote in message news:e82b9c41-935d-45c9-8d7b-6bd3fa7eaae5 at i3g2000hsf.googlegroups.com... |Here's a version that |1. does not require new syntax |2. does not *necessarily* override the "_" prefix convention 'self_' is way too bulky and intrusive. Putting '_' at the end of the word is nearly as easy to detect and conflicts with no convention I know of. tjr From lefevrol at yahoo.com Fri Jan 25 11:31:16 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Fri, 25 Jan 2008 17:31:16 +0100 Subject: read and readline hanging In-Reply-To: References: Message-ID: Hi Steve, Thanks for the answer. Yes this is tricky. I have done it in Java before, where you can, e.g., set up a thread to pump stuff out of both stderr and stdout continuously but my python is too rudimentary for that. There is a key difference anyway: in Java you can write while (br.readLine() != null) { } where br is the buffered reader in which you've wrapped the stdout of the child process and it will not hang. But in python eventually stdout.readline() hangs. This is a real nuisance: why can't it just return None? > 1. The subprocess has stopped producing output. Indeed, if I do this interactively, I can tell after 3 lines that I've gotten all there is to get right now and the fourth readline() call hangs. But how can I find out *programmatically* that there is no more input? > If you are only reading its standard output, are you sure that the > subprocess is flushing its buffers so you can recognize it's time to > provide more input? The subprocess in a purely passive position: it is an interpreter: I send it commands and I read the answers. The python side is in charge. > 2. The subprocess has blocked because it has filled its stderr buffer > and is waiting for something (i.e. your program) to read it. No, that's not it or it would hang immediately. I can get a few lines out of stdout and then I hang because I can't tell when it's time to stop pumping. But you are right that if there was something on stderr I would be in trouble. Regards, -- O.L. From mwm at mired.org Wed Jan 9 15:24:03 2008 From: mwm at mired.org (Mike Meyer) Date: Wed, 9 Jan 2008 15:24:03 -0500 Subject: Another dumb scope question for a closure. In-Reply-To: References: Message-ID: <20080109152403.433b113a@bhuda.mired.org> On Wed, 9 Jan 2008 13:47:30 -0500 (EST) "Steven W. Orr" wrote: > So sorry because I know I'm doing something wrong. > > 574 > cat c2.py > #! /usr/local/bin/python2.4 > > def inc(jj): > def dummy(): > jj = jj + 1 > return jj > return dummy > > h = inc(33) > print 'h() = ', h() > 575 > c2.py > h() = > Traceback (most recent call last): > File "./c2.py", line 10, in ? > print 'h() = ', h() > File "./c2.py", line 5, in dummy > jj = jj + 1 > UnboundLocalError: local variable 'jj' referenced before assignment > > I could have sworn I was allowed to do this. How do I fix it? Nope. This is one of the things that makes lisper's complain that Python doesn't have "real closures": you can't rebind names outside your own scope (except via global, which won't work here). Using a class is the canonical way to hold state. However, any of the standard hacks for working around binding issues work. For instance: >>> def inc(jj): ... def dummy(): ... box[0] = box[0] + 1 ... return box[0] ... box = [jj] ... return dummy ... >>> h = inc(33) >>> h() 34 http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From JAMoore84 at gmail.com Thu Jan 24 12:13:39 2008 From: JAMoore84 at gmail.com (JAMoore84 at gmail.com) Date: Thu, 24 Jan 2008 09:13:39 -0800 (PST) Subject: Beginner Pyserial Question References: <93223c7c-c891-424c-bc4f-00d61592663a@l32g2000hse.googlegroups.com> <13phgpma9fb3cb8@corp.supernews.com> Message-ID: <50bf1637-0954-4d35-9c16-76c3b9aabe05@y5g2000hsf.googlegroups.com> > My guess is that for whatever reason the 'first' serial port > (which is what you're asking for by specifying a 0 when > instantiating the Serial class) doesn't actually exist. Serial > device names under Windows are broken. I realize this. I tried connecting to different port "numbers", but I have not tried the serial.Serial(COM1). I wasn't sure if that worked, but I know a quick way to find out. > Try using the actual name of the com port (e.g. 'COM3' or > 'COM5') instead of 0. The com port used in Hyper Terminal is COM40. I have tried connecting to 39/40/41 to no avail. > Oh, if you end up having to use a com port higher than COM9, > that's broken in Windows as well, and you've got to sprinkle a > bunch of backslashes into the device name (I don't remember the > exact syntax). That might become an issue when I try to read COM40 for the GPS bluetooth transmission. This issue does not relate to why I cannot open smaller com ports, though. From radiosrfun at radiosrfun.com Sat Jan 12 02:01:09 2008 From: radiosrfun at radiosrfun.com (radiosrfun) Date: Sat, 12 Jan 2008 02:01:09 -0500 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> Message-ID: <478865b1$0$26840$ecde5a14@news.coretel.net> "ChairmanOfTheBored" wrote in message news:58ogo3pmecob8al6hvnb67rts0jo7j4qf1 at 4ax.com... > On Fri, 11 Jan 2008 18:25:53 -0800 (PST), thermate at india.com wrote: > >>The yank... > > > You're a goddamned retard. Go back to yanking your pathetic excuse for > a dick. American Bastards deserve to be raped? WTF? Boy - if that wasn't an admission to queerdom - I don't know what was! However - it would have to be oral - as I've heard those punks there - much by their own admission - have a milimeter peter - so in that case - they couldn't "rape" - let alone tickle - any of us "American Bastards". We "might" die - laughing our ass off though! American Bastards? Hahahahahaha............ thats funny! Come kiss this American Bastard's - ASS. You can call me an American Bastard, Prick - whatever - fact is - we're still better than you pukes will ever be. I WISH - that the President and Congress of this country would shut off ALL foreign aid. Maybe these sons of bitches would sing a different tune. We get hit by a massive hurricane - wiping out almost an entire state - we don't get a damned penny or offer of help from any one. Them dog eaters have a Tsunami, Tropical Storm - whatever fart Mother Nature gives them, we send them millions. FUCK THAT. And we have helped India - a lot. We're currently sending hundreds if not thousands of jobs there - thanks to the low life top level business people. Bring all those jobs back here - let them mother fuckers starve in poverty. From http Sun Jan 20 16:35:58 2008 From: http (Paul Rubin) Date: 20 Jan 2008 13:35:58 -0800 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> Message-ID: <7xprvwfadd.fsf@ruckus.brouhaha.com> dg.google.groups at thesamovar.net writes: > Unfortunately I realise I stated the problem imprecisely. You're only > allowed to use each number once (otherwise there's a trivial solution > for every problem, i.e. x/x + x/x + x/x + ... + x/x repeated y times > for target y given any source number x). Trying your program on 234 > from [100,9,7,6,3,1] gives you 9*9*3-9 using the 9 three times. Here is a pretty inefficient solution. It doesn't find 234 but it does find 253 twice: from operator import * def countdown(nums, ops, trace): n0 = nums[0] if len(nums) == 1: yield n0, str(n0) return for i,n in enumerate(nums[1:]): for f in ops: for r,t in countdown(nums[1:i] + nums[i+1:], [add, mul, sub], trace): if f != div or r != 0 and n0 % r == 0: yield f(n0, r), '%s(%s,%s)'% (f.__name__, n0, t) def search(nums, target): for x,t in countdown(nums, [add, mul, sub, div], []): if x == target: print x,t search([100,9,7,6,3,1], 253) From steve at holdenweb.com Thu Jan 31 13:10:26 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 13:10:26 -0500 Subject: Python for mobiles In-Reply-To: <03e0ad28-e72c-4582-8518-b5cb07d408df@e10g2000prf.googlegroups.com> References: <03e0ad28-e72c-4582-8518-b5cb07d408df@e10g2000prf.googlegroups.com> Message-ID: pavloutefkros at gmail.com wrote: > Hello, > > Is there any chance that i could compile python programs to java (.jar > [java bytecode]) so that i could run them with full support (no > interpreter) in a wireless device (talking about mobiles eg. nokia, > ericsson). > I am aware of jython, however i am not elegible of finding a proper > article claiming wheather this ability is provided or not. > > Thanks in advance! A better solution would surely be to get a Nokia S60 'phone, for which there is a native Python implementation. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From martin at v.loewis.de Wed Jan 23 04:19:28 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Jan 2008 10:19:28 +0100 Subject: python24 symbol file...pyhon24.pdb In-Reply-To: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> References: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> Message-ID: <479706a0$0$13412$9b622d9e@news.freenet.de> > Also, is there source code available for python24 for Windoze? I have > seen reference to source code but not in a package for Windows. It's available from http://www.python.org/ftp/python/2.4/Python-2.4.tgz Regards, Martin From Lie.1296 at gmail.com Thu Jan 17 12:55:44 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 17 Jan 2008 09:55:44 -0800 (PST) Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com><20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net><87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> <87ir1wf1wi.fsf@mulj.homelinux.net> <87k5mbd8bv.fsf@benfinney.id.au> Message-ID: <95691ba1-f734-4f17-b329-29128b4c38a7@s13g2000prd.googlegroups.com> On Jan 16, 5:34?am, "Reedick, Andrew" wrote: > > >From the base definition of a constructor: constructor is the creator > > of an object. In this case, __new__ is technically the constructor > > while __init__ is an initializer. > > > However, it is also to be noted that __init__ is what makes an object > > meaningful, and that makes it a constructor in a sense (while still > > technically a constructor). Without initialization, an object is > > meaningless, even if the definition of the initializer is to leave it > > as it is. > > You don't need to have an __init__ defined. ?A subclass has to > explicitly call the parent's __init__ or the parent's __init__ is never > run. ? In other languages, constructor might be optional. In the case of non- existent constructor, compilers would add an empty constructor, but what's the difference (from programmer's POV) between Python ignoring __init__ and other languages adding empty constructor? That's just an implementation detail. > If the __init__ makes the object meaningful, then how meaningful > is an object without an __init__? ? It actually depends on the object, some objects might be pretty meaningless without being initialized (or its members altered from outside very carefully). Examples include a simple vector class. If the vector is not initialized, the x and y equals None, which is not a valid value for vector, which means the object is meaningless. > I'm pretty sure that an object > without an __init__ is still a viable, working object. I'm sure it is, although it's initial value might not be a valid value. > > If you can't be convinced with this argument, then I'd give you > > another that's a bit more Pythonic: > > DUCK TYPING: If it looks like a duck, walks like a duck, and quacks > > like a duck, it is a duck! > > But you don't need __init__ to be a duck! lol... > > >From the class programmer's point of view, __init__ acts like an > > object constructor in other languages, there is no significant > > difference between __init__ and constructor in other languages. > > How many times can you call an object's constructor in other languages? > __init__ can be called repeatedly. That's a very good argument to separate __init__ from a real constructor, but how many projects you do would require object recycling (which is the only reason I can think of for calling initializers more than once)? Object recycling should only be done on systems which lacks resources because it have big potential to introduce bugs caused by incomplete cleaning. > __init__ is the last straw that breaks the camel's back. ?Or rather, the > last method we see in the object creation process, and thus must be > 'guilty' of being a constructor. ?Only a fundamentalist would blame the > victim instead of the real criminal, __new__. It's not about blaming, rather they shared parts in the act. > We're splitting hairs. ?And I'm pretty sure that, aside from being a > spiffy thought experiment, no one cares as long as it works and makes > sense. ? =) I agree with that. From grante at visi.com Sun Jan 27 11:19:06 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 27 Jan 2008 16:19:06 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> <13pp2h2eugn8594@corp.supernews.com> <603npdF1oh17aU6@mid.uni-berlin.de> Message-ID: <13ppbnqcegh0993@corp.supernews.com> On 2008-01-27, Marc 'BlackJack' Rintsch wrote: >> I'm starting to wonder if it is possible for somebody to be >> simultaneously so self-assured and so ignorant, or if we're >> being trolled. > > I recently learned that this is called the Dunning-Kruger effect: > > The Dunning-Kruger effect is the phenomenon wherein people who have > little knowledge think that they know more than others who have much > more knowledge. > > [?] > > The phenomenon was demonstrated in a series of experiments performed by > Justin Kruger and David Dunning, then both of Cornell University. Their > results were published in the Journal of Personality and Social > Psychology in December 1999. I remember reading that paper about a year ago and it sure seemd to explain the behavior of a number of people I've known. Not only is it possible to be simultaneously self-assured and ignorant, that appears to be the normal way that the human mind works. ... must restist ... urge... to mention... Bush... Damn. -- Grant Edwards grante Yow! You can't hurt at me!! I have an ASSUMABLE visi.com MORTGAGE!! From jens at aggergren.dk Fri Jan 25 08:48:27 2008 From: jens at aggergren.dk (Jens) Date: Fri, 25 Jan 2008 05:48:27 -0800 (PST) Subject: Terse Syntax through External Methods Message-ID: Hello Everyone I'm newbie to Zope and i have a few questions regarding external methods. What i wan't to do is provide a terse syntax for converting urls to special tracking urls: turns the provided url into something like http://host/tracking?url=http%3A%2F%2Fmyurl%2F in the output. i've been trying to use a external procedure like this. ## Script (Python) "track_link" ##bind container=container ##bind context=context ##bind namespace=_ ##bind script=script ##bind subpath=traverse_subpath ##parameters=self,url ##title=track link ## return "%s%s" % (self.tracking_prefix, url_quote(url)) This doesn't work because because the method doesn't have access to the environment. Obviously I don't wan't to pass everything explicitly into the function as this would defeat the purpose of the exercise, namely to provide a terse syntax. I have a background in other languages so I might be missing something conceptually with regard Zope and DTML.. Is there a better was of doing this, perhaps without using external methods? Currently im doing the following which isn't very elegant: in content document ">link ... tracking: Appreciate any input you might have on this- From http Fri Jan 11 18:51:16 2008 From: http (Paul Rubin) Date: 11 Jan 2008 15:51:16 -0800 Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> Message-ID: <7xd4s7c45n.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > > 2. Associate a lock with the list. Anything wanting to access the > > list should acquire the lock, do its stuff, then release the lock. > > This gets confusing after a while. > > To keep it generic, how about: > > listA.op( insert, x ) > listA.op( remove, x ) Sure, there are various ways you can make the code look uniform. What gets messy is if you want to (say) operate on several lists at the same time, which means you need to hold multiple locks simultaneously, and some other thread is also trying to do the same thing. If you acquire the locks in the wrong order, you can get a situation where both threads deadlock forever. From nagle at animats.com Sat Jan 19 11:06:15 2008 From: nagle at animats.com (John Nagle) Date: Sat, 19 Jan 2008 08:06:15 -0800 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. In-Reply-To: <3b14e57b-9461-4e1c-9bde-fdde99f87617@z17g2000hsg.googlegroups.com> References: <478FAC5A.50206@animats.com> <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> <479046a5$0$36403$742ec2ed@news.sonic.net> <3b14e57b-9461-4e1c-9bde-fdde99f87617@z17g2000hsg.googlegroups.com> Message-ID: <47921ea4$0$36366$742ec2ed@news.sonic.net> Paul Boddie wrote: > Unlike your approach, pprocess employs the fork system call. Unfortunately, that's not portable. Python's "fork()" is "Availability: Macintosh, Unix." I would have preferred to use "fork()". John Nagle From nagle at animats.com Fri Jan 18 13:03:23 2008 From: nagle at animats.com (John Nagle) Date: Fri, 18 Jan 2008 10:03:23 -0800 Subject: [python] How to detect a remote webpage is accessible? (in HTTP) In-Reply-To: References: Message-ID: <4790e898$0$36384$742ec2ed@news.sonic.net> ?? wrote: > Howdy, all, > I want to use python to detect the accessibility of website. > Currently, I use urllib > to obtain the remote webpage, and see whether it fails. But the problem is that > the webpage may be very large; it takes too long time. Certainly, it > is no need to download > the entire page. Could you give me a good and fast solution? > Thank you. > -- > ShenLei If you can get through "urlopen", you've already received the HTTP headers. Just open, then use "info()" on the file descriptor to get the header info. Don't read the content at all. Setting the socket timeout will shorten the timeout when the requested domain won't respond at all. But if the remote host opens an HTTP connection, then sends nothing, the socket timeout is ineffective and you wait for a while. This is rare, but it happens. John Nagle From mail at timgolden.me.uk Wed Jan 23 06:49:58 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Jan 2008 11:49:58 +0000 Subject: wxpython In-Reply-To: <77cc3d61-5dd0-4878-b436-b6d07e40de4d@i7g2000prf.googlegroups.com> References: <77cc3d61-5dd0-4878-b436-b6d07e40de4d@i7g2000prf.googlegroups.com> Message-ID: <479729E6.4010409@timgolden.me.uk> joe jacob wrote: > I am trying to open a file containing non displayable characters like > contents an exe file. The is is with the below mentioned code: > > self.text_ctrl_1.SetValue(file_content) > > If the file_content contains non displayable characters I am getting > an error like this: > > Traceback (most recent call last): > File "C:\Documents and Settings\joe_jacob\Desktop\notepad.py", line > 102, in open_file > self.text_ctrl_1.SetValue(file_content) > File "D:\softwares\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx > \_controls.py", line 1708, in SetValue > return _controls_.TextCtrl_SetValue(*args, **kwargs) > File "D:\softwares\Python25\lib\encodings\cp1252.py", line 15, in > decode > return codecs.charmap_decode(input,errors,decoding_table) > UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position > 2: character maps to > > I am trying to create an encryption program so if I open any file even > if it is an exe file it should display in text ctrl. > > What is this problem with this ? How can I rectify this? If I may be permitted a bit of levity at your expense: you're asking how to display "non displayable" characters! The most serious answer I can give is: how do you *want* to display those characters? What do you *expect* to appear in the text control. wxPython is trying to interpret your byte stream as a Unicode text stream encoded as cp1252. But it's not, so it gives up in a heap. One solution is to pass the repr of file_content. Another solution is for you to prefilter the text, replacing non-printables by their hex value or by some marker. Not much in it, really. import random file_content = "".join ( chr (random.randint (0, 255)) for i in range (1000) ) munged_text = "".join ( c if 32 <= ord (c) <= 126 else hex (ord (c)) for c in file_content ) print repr (file_content) print munged_text TJG From arnodel at googlemail.com Thu Jan 31 17:16:39 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 31 Jan 2008 14:16:39 -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> Message-ID: <1ffed8a2-f00b-4913-802f-b2cc9fa0ab19@i12g2000prf.googlegroups.com> On Jan 31, 4:12?pm, erikcw wrote: > Hi, > > I have a list of numbers each with a +/- margin of error. ?I need to > identify which ones overlab each other. > > For example: > 55 +/- 3 > 20 +/- 2 > 17 +/- 4 > 60 +/- 3 > > #base, max, min > list = [ > (55, 58, 52), > (20, 22, 18), > (17, 21, 13), > (60, 63, 57), > ] > > In this example the range of list[0] overlaps the range of list[3] AND > list[1] overlaps list[2] > > 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. This is definitely the best way: ======================= lst = [ (55, 58, 52), (20, 22, 18), (17, 21, 13), (60, 63, 57), ] from itertools import chain def overlaps(lst): bounds = chain(*(((x[1],i), (x[2], i)) for i,x in enumerate(lst))) inside = {} for x, i in sorted(bounds): if inside.pop(i, None) is None: for j, y in inside.iteritems(): if y != x: yield i, j inside[i] = x ============================== >>> list(overlaps(lst)) [(1, 2), (3, 0)] -- Arnaud From sjmachin at lexicon.net Wed Jan 2 05:47:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 2 Jan 2008 02:47:01 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> Message-ID: On Jan 2, 8:44 pm, John Machin wrote: > (1) Try these at the Python interactive prompt: > > unicode('', 'latin1') Also use those 6 cases to check out the difference in behaviour between unicode(x, y) and x.decode(y) From patrickkidd.lists at gmail.com Fri Jan 11 00:26:07 2008 From: patrickkidd.lists at gmail.com (Patrick Stinson) Date: Thu, 10 Jan 2008 22:26:07 -0700 Subject: loading a script from text data Message-ID: <664bf2b80801102126r1cf800dan90bfe313a9e30d2c@mail.gmail.com> Is it possible to load a script from it's text data, and not from a file? I'm writing a scripting engine and need to run the scripts right from the editor. cheers! -- Patrick Kidd Stinson http://www.patrickkidd.com/ http://pkaudio.sourceforge.net/ http://pksampler.sourceforge.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From software at ginstrom.com Thu Jan 10 22:52:56 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Fri, 11 Jan 2008 12:52:56 +0900 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com><87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <030401c85405$75f50260$030ba8c0@MOUSE> > On Behalf Of Marty > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) > > This caused me to wonder why Python does not have a "foreach" > statement (and also why has it not come up in this thread)? > I realize the topic has probably been beaten to death in > earlier thread(s), but does anyone have the short answer? data_out = [[] for item in data_in] Regards, Ryan Ginstrom From george.maggessy at gmail.com Tue Jan 8 01:14:36 2008 From: george.maggessy at gmail.com (George Maggessy) Date: Mon, 7 Jan 2008 22:14:36 -0800 (PST) Subject: User Group Message-ID: <41ef8ab8-6b1d-4fa0-84d3-ee29e2352222@l1g2000hsa.googlegroups.com> Hi Guys, Is there a python user group in the bay area? Cheers, George From ggpolo at gmail.com Mon Jan 7 08:45:23 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 11:45:23 -0200 Subject: Launching a wx GUI from within our python framework In-Reply-To: <0f4a1b94-9fc0-457f-81c3-b8986f5086cd@d70g2000hsb.googlegroups.com> References: <0f4a1b94-9fc0-457f-81c3-b8986f5086cd@d70g2000hsb.googlegroups.com> Message-ID: 2008/1/7, bg_ie at yahoo.com : > Hi, > > At my work we have a framework writen in python which allows us to > test our equipment. This framework is quite large and uses a Singelton > called frameworkExec which we pass around between objects in order to > share functionailty. For example, frameWorkExec stores an instance of > the BatteryManagement module which I use to set the voltage during > certain tests. > > I've just writen a gui using wx which I wish to use to calibrate our > voltage supply. I launch this app at the moment within python win as > follows - > > app = VoltageCalibrationApp(0) > app.MainLoop() > > class VoltageCalibrationApp(wx.App): > def OnInit(self): > > voltageCalibration = {} > voltageCalibration[0.0] = 1.2 > voltageCalibration[9.0] = 10.1 > voltageCalibration[22.0] = 22.7 > voltageCalibration[24.0] = 24.8 > voltageCalibration[30.0] = 31.1 > voltageCalibration[35.0] = 36.9 > > frame = VoltageCalibrationFrame(None, -1, 'Voltage Calibration', > voltageCalibration) > frame.Show(True) > frame.Centre() > return True > > I hope that by adding the code above into the framework, I will be > able to call this app as part of the framework before the execution of > certain tests, as follows - > > app = VoltageCalibrationApp(0) > app.MainLoop() > test1.run() > test2.run() > > As you can see in the VoltageCalibrationApp class, I am currently > hardcoding voltageCalibration. Rather than doing this, I wish to store > them in our singleton which is available at the scope at which I > create my VoltageCalibrationApp instance. But I can't figure our a way > of referencing my singleton with the OnInit function. Normally, you > would pass the reference via __init__ > > How can I do this? You can define the __init__ method in your wx.App subclass, something like this: class MyApp(wx.App): def __init__(self, thingYouWant, redirect=True, filename=None): self.thingyouwant = thingYouWant wx.App.__init__(self, redirect, filename) def OnInit(self): ... something that uses self.thingyouwant ... ... > > Thanks, > > Barry. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From sjmachin at lexicon.net Mon Jan 7 15:22:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 7 Jan 2008 12:22:31 -0800 (PST) Subject: Does Python cache the startup module? References: Message-ID: <3c346bb2-c84a-4268-9e7b-b0c601fe9710@s12g2000prg.googlegroups.com> On Jan 8, 6:21 am, Baz Walter wrote: > Guilherme Polo gmail.com> writes: > > > Uhm.. this didn't make much sense. If you say the module is cached, > > then supposing you did a minor edit, and then supposing because it is > > cached your application wouldn't detect the change, then I don't see > > the connection with memory leak. > > > Bring some concrete proof. > > Thanks for your reply. > > It's hard to supply an example for this, since it is local to the machine I am > using. The startup module would look something like this: > > #!/usr/local/bin/python > > if __name__ == '__main__': > > import sys > from qt import QApplication, QWidget > > application = QApplication(sys.argv) > mainwindow = QWidget() > application.setMainWidget(mainwindow) > mainwindow.show() > sys.exit(application.exec_loop()) > > If I change the name 'mainwindow' to 'mainwidget', the widget it refers to does > not get destroyed; when I change it back again, it does get destroyed. > Otherwise, the program runs completely normally. If you execute that stuff inside a function (see below) instead of in global scope, do you get the same effect? if __name__ == '__main__': import sys def main(): from qt import QApplication, QWidget application = QApplication(sys.argv) mainwindow = QWidget() application.setMainWidget(mainwindow) mainwindow.show() result = application.exec_loop()) return result sys.exit(main()) From steve at REMOVE-THIS-cybersource.com.au Sat Jan 5 03:01:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 05 Jan 2008 08:01:41 -0000 Subject: mail References: Message-ID: <13nueb5l2j44fa5@corp.supernews.com> On Fri, 04 Jan 2008 23:03:15 -0800, sanjeet wrote: > hi all, > I am facing problem to fetch mail from internet mail server. Plz help > me, how can do this? Yes. Everything you need to know to fix your problem can be found here: www.catb.org/~esr/faqs/smart-questions.html -- Steven From paddy3118 at googlemail.com Thu Jan 24 00:57:05 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 23 Jan 2008 21:57:05 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> <13pfdh31k2bp8eb@corp.supernews.com> <8f2a164c-5516-487f-802b-5651cb15b404@h11g2000prf.googlegroups.com> Message-ID: On 23 Jan, 22:39, George Sakkis wrote: > On Jan 23, 4:48 pm, Steven D'Aprano > cybersource.com.au> wrote: > > As for your other points, I think we're actually very much in agreement, > > except for your tolerance of random posters asking what I believe is an > > incoherent question: "what's the fastest way to do ...?". It seems to me > > you're willing to give them the benefit of the doubt that they've done > > their profiling and considered their trade-offs, or at the very worst are > > asking from purely intellectual curiosity. > > It depends on the specific problem and the context. For small well- > defined algorithmic type problems, I just assume it's intellectual > curiosity or that performance really matters. If the same question was > asked in the context of, say, a typical web application fetching data > from a database and rendering dynamic pages, I might have dismissed it > as YAGNI. > > George George, I tend to think that the more context an OP gives, the more thought they have given their problem. Often, to get a better answer you need to help the OP divulge context. I too like the intellectual challenge of exploring small problem, and from lurking on c.l.p I thought there would be lots of answers of that ilk, but this time I thought why not contribute in a different way? Reading c.l.p I am often reminded of good software practice memes in answers and think its part of what makes c.l.p. a rewarding experience. It may be hubris to think that a random reader might read my post and then follow my points before making a routine faster; but there you go :-) - Paddy. From robleachza at gmail.com Wed Jan 16 19:54:53 2008 From: robleachza at gmail.com (robleachza at gmail.com) Date: Wed, 16 Jan 2008 16:54:53 -0800 (PST) Subject: next line (data parsing) Message-ID: Hi there, I'm struggling to find a sensible way to process a large chuck of data--line by line, but also having the ability to move to subsequent 'next' lines within a for loop. I was hoping someone would be willing to share some insights to help point me in the right direction. This is not a file, so any file modules or methods available for files parsing wouldn't apply. I run a command on a remote host by using the pexpect (pxssh) module. I get the result back which are pages and pages of pre-formatted text. This is a pared down example (some will notice it's tivoli schedule output). ... Job Name Run Time Pri Start Time Dependencies Schedule HOST #ALL_LETTERS ( ) 00:01 10 22:00(01/16/08) LTR_CLEANUP (SITE1 LTR_DB_LETTER 00:01 10 Total 00:01 Schedule HOST #DAILY ( ) 00:44 10 18:00(01/16/08) DAILY_LTR (SITE3 RUN_LTR14_PROC 00:20 10 (SITE1 LTR14A_WRAPPER 00:06 10 SITE3#RUN_LTR14_PROC (SITE1 LTR14B_WRAPPER 00:04 10 SITE1#LTR14A_WRAPPER (SITE1 LTR14C_WRAPPER 00:03 10 SITE1#LTR14B_WRAPPER (SITE1 LTR14D_WRAPPER 00:02 10 SITE1#LTR14C_WRAPPER (SITE1 LTR14E_WRAPPER 00:01 10 SITE1#LTR14D_WRAPPER (SITE1 LTR14F_WRAPPER 00:03 10 SITE1#LTR14E_WRAPPER (SITE1 LTR14G_WRAPPER 00:03 10 SITE1#LTR14F_WRAPPER (SITE1 LTR14H_WRAPPER 00:02 10 SITE1#LTR14G_WRAPPER Total 00:44 Schedule HOST #CARDS ( ) 00:02 10 20:30(01/16/08) STR2_D (SITE7 DAILY_MEETING_FILE 00:01 10 (SITE3 BEHAVE_HALT_FILE 00:01 10 SITE7#DAILY_HOME_FILE Total 00:02 ... I can iterate over each line by setting a for loop on the data object; no problem. But basically my intension is to locate the line "Schedule HOST" and progressively move on to the 'next' line, parsing out the pieces I care about, until I then hit "Total", then I resume to the start of the for loop which locates the next "Schedule HOST". I realize this is a really basic problem, but I can't seem to articulate my intension well enough to find documentation or examples that have been helpful to me. I bought the Python cookbook yesterday which has gotten me a lot further in some areas, but still hasn't given me what I'm looking for. This is just a pet project to help me reduce some of the tedious aspects of my daily tasks, so I've been using this as means to discover Python. I appreciate any insights that would help set me in the right direction. Cheers, -Rob From fredrik at pythonware.com Sun Jan 6 08:48:36 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 06 Jan 2008 14:48:36 +0100 Subject: Killing worker threads In-Reply-To: References: Message-ID: tarun wrote: > Can anyone help me with a simple code through which the main thread can > kill the worker thread it started. it cannot. threads cannot be killed from the "outside". From deets at nospam.web.de Mon Jan 14 17:58:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 14 Jan 2008 23:58:24 +0100 Subject: Append zip files together, just get the binary data (in memory) In-Reply-To: <53f66038-ccc3-4c3d-97b2-fa5deb148809@d4g2000prg.googlegroups.com> References: <53f66038-ccc3-4c3d-97b2-fa5deb148809@d4g2000prg.googlegroups.com> Message-ID: <5v27oiF1kavhlU1@mid.uni-berlin.de> BerlinBrown schrieb: > Is it possible to just build the binary content of a zip file. I want > to create the content in memory (e.g. return binary data) and then get > those byte strings representing the zip file? Is that possible? > > Or could I possibly override functions in the zip class. > > 1. Create a zip file object (e.g. dont actually create the file). > 2. Append stuff to the zip file (e.g. a file) > 3. Zip that content into memory (but still not touching the > filesystem) > 4. Extract those byte strings for (an array?) later use. > > My goal is to concatenate multiple zip files into another binary file. Module StringIO is your friend. Diez From python.list at tim.thechases.com Fri Jan 25 08:04:01 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 25 Jan 2008 07:04:01 -0600 Subject: Minimum Requirements for Python In-Reply-To: References: Message-ID: <4799DE41.8000608@tim.thechases.com> > Can someone tell me the minimum requitements for Python as I can't > find it anwhere on the site. I have 3 PC's which are only 256mb RAM, > wanted to know if this was sufficenent. It runs just fine here on an old P133 laptop running OpenBSD with a mere 32 megs of memory. I wouldn't do numerical processing on it, or memory intensive tasks, but for most scripts, it's just fine. -tkc From musiccomposition at gmail.com Mon Jan 14 22:26:20 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 14 Jan 2008 19:26:20 -0800 (PST) Subject: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net> <5v2cudF1k5a1oU1@mid.individual.net> Message-ID: On Jan 14, 6:26 pm, Bjoern Schliessmann wrote: > John Nagle wrote: > > It turns out that the strings in the "env" parameter have to be > > ASCII, not Unicode, even though Windows fully supports Unicode in > > CreateProcess. > > Are you sure it supports Unicode, not UTF8 or UTF16? Probably using > something like u"thestring".encode("utf16") will help. Otherwise: bugs.python.org > > Regards, > > Bj?rn > > -- > BOFH excuse #31: > > cellular telephone interference From python at rcn.com Fri Jan 25 23:16:50 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 25 Jan 2008 20:16:50 -0800 (PST) Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> Message-ID: <1d73c5f5-2c9d-4c46-9205-289a5462fabb@v46g2000hsv.googlegroups.com> On Jan 25, 1:47?pm, Hexamorph wrote: > Henry Baxter wrote: > > Oops, gmail has keyboard shortcuts apparently, to continue: > > > def maxi(l): > > ? ? m = max(l) > > ? ? for i, v in enumerate(l): > > ? ? ? ? if m == v: > > ? ? ? ? ? ? return i > > What's about l.index(max(l)) ? from itertools import izip, count answer = max(izip(l, count()))[1] Raymond From bearophileHUGS at lycos.com Sun Jan 6 13:03:34 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 6 Jan 2008 10:03:34 -0800 (PST) Subject: Point Object References: <4673edc3-b76c-4c6e-98f0-4f2becee930e@j20g2000hsi.googlegroups.com> Message-ID: Pete: > Translate the hexadecimal form > into decimal and confirm that they match. No need to convert the IDs... Soviut: > You shouldn't have to compare the hex IDs. Just a simple comparison > operator will work: > > firstPoint = Point() > secondPoint = Point() > print(firstPoint == secondPoint) > > result: True Remember about __eq__ and "is": class Foo: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x f1 = Foo(1) f2 = Foo(2) f3 = Foo(2) f4 = f3 print f1 == f2, f1 is f2 # False False print f2 == f3, f2 is f3 # True False print f3 == f4, f3 is f4 # True True Bye, bearophile From sour.craig at gmail.com Fri Jan 11 11:21:18 2008 From: sour.craig at gmail.com (Craig Ward) Date: Fri, 11 Jan 2008 11:21:18 -0500 Subject: newbie question regarding int(input(:)) Message-ID: <275866c0801110821r46ac1174wea4c1ddad22b9d1d@mail.gmail.com> Hi experts! I am trying to write a menu script that will execute bash scripts. Everything is fine until the script executes and I want to see if there are any more options to run before quitting. Example: def menu(opt1 = "something", opt2 = "something else"): -- Computers are like air conditioners. They stop working when you open Windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From toby at tobiah.org Tue Jan 29 14:48:38 2008 From: toby at tobiah.org (Tobiah) Date: Tue, 29 Jan 2008 11:48:38 -0800 Subject: Removing Pubic Hair Methods In-Reply-To: References: Message-ID: <479f7759$0$25985$88260bb3@free.teranews.com> class genital: def pubic_hair(self): pass def remove(self): del(self.pubic_hair) "Removing pubic hair methods" xikom01 at yahoo.com.tw wrote: > Shaving is the most common removing pubic hair method. However, it is > not the only one. > > After you have decided you want to remove your pubic hair, you will > have to examine the different methods for removing pubic hair and > decide which one is the best for you. > > The following lines include a brief glance of the existing pubic hair > removal methods: > > 1. Shaving - razor shaving is the most popular removing pubic hair > method. One should shave his pubic hair area carefully and gently > using a proper razor and shaving cream. Make sure you wash and clean > your pubic hair area before and after the shave. > > 2. Hair removal creams - those can cause lots of pain and allergic > reactions. However, they are very effective in removing pubic hair. We > suggest you test in on a harmless spot like your back or the inside of > your elbow to check for possible allergic reactions. If your skin gets > red or itchy for a long period of time (more than 3 hours) do use it. > Again, wash you pubic hair area carefully after using this removing > pubic hair method. > > 3. Waxing - We strongly suggest avoiding using wax for removing pubic > hair. Most of the women can not stand the pain and the outcome is as > good as the other removing pubic hair methods. > > 4. Electrolysis - A permanent pubic hair removing methods using > electric shocks. It can be done in a hair salon or at home after > purchasing a personal device. This method is very expensive (It may > cost more than a thousand dollars). It also painful in most cases but > this method provides a permanent pubic hair removal. > > 5. Pulling - We got to know in our research quite a few women who > prefer pull their pubic hair out. It takes time, Its painful but it > involves a satisfaction. > > Now you can make the proper decision on the best removing pubic hair > method for you. Good luck. > > > http://www.dontplayplay.com/html/Bothsexes/20061002/47329.html > -- Posted via a free Usenet account from http://www.teranews.com From steve at holdenweb.com Wed Jan 30 21:51:53 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Jan 2008 21:51:53 -0500 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <13q2960err4db28@corp.supernews.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> <13q2960err4db28@corp.supernews.com> Message-ID: <47A137C9.507@holdenweb.com> Grant Edwards wrote: > On 2008-01-31, Daniel Fetchinson wrote: >>> I do not understand why no one has answered the following question: >>> >>> Has anybody worked with Gene Expression Programming???? >> Hmmmmm, maybe because nobody did? Just a thought. It can also be that >> everyone worked with it but everyone is part of a big conspiracy not >> to answer any of your emails just to make you act weird. > > That's it then, now we're going to have to kill you... > Look guys, I thought we'd agreed that the PSU was no longer to be From robert.kern at gmail.com Tue Jan 29 14:44:33 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 29 Jan 2008 13:44:33 -0600 Subject: Module/package hierarchy and its separation from file structure In-Reply-To: <0a285e6e-a3a9-4be9-ae59-4cb7547ffa3a@q21g2000hsa.googlegroups.com> References: <874pd49qjl.fsf@benfinney.id.au> <0a285e6e-a3a9-4be9-ae59-4cb7547ffa3a@q21g2000hsa.googlegroups.com> Message-ID: Carl Banks wrote: > On Jan 29, 7:48 am, Peter Schuller > wrote: >>> You can also put, in animal/__init__.py: >>> from monkey import Monkey >>> and now you can refer to it as org.lib.animal.Monkey, but keep the >>> implementation of Monkey class and all related stuff into >>> .../animal/monkey.py >> The problem is that we are now back to the identity problem. The class >> won't actually *BE* org.lib.animal.Monkey. > > The usage is the same; it works in all cases once you redefine > __module__. Who cares what it really is? The inspect module. [animals]$ ls animals [animals]$ rm animals/*.pyc [animals]$ ls animals [animals]$ ls animals __init__.py monkey.py [animals]$ cat animals/monkey.py class Monkey(object): pass [animals]$ cat animals/__init__.py from animals.monkey import Monkey Monkey.__module__ = 'animals' [animals]$ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from animals import Monkey >>> import inspect >>> inspect.getsource(Monkey) Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/inspect.py", line 629, in getsource lines, lnum = getsourcelines(object) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/inspect.py", line 618, in getsourcelines lines, lnum = findsource(object) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/inspect.py", line 494, in findsource raise IOError('could not find class definition') IOError: could not find class definition >>> -- 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 lists at cheimes.de Wed Jan 23 14:32:54 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 23 Jan 2008 20:32:54 +0100 Subject: math and numerical fixes (was: When is min(a, b) != min(b, a)?) In-Reply-To: References: Message-ID: <47979666.2020900@cheimes.de> Jason wrote: > Please note that NaN's are very funky and platform dependent. They > depend on their underlying platform's C library for creation and > display. On windows, "float('nan')" will cause an exception, as there > are no valid string representations of NAN that can be converted to > the special floating point value. Also, if you manage to create a nan > under Windows, it displays as "1.#QNAN". > > Infinite values are also problematic. In almost all cases, it is far > better to avoid infinite and NaN values. CC to Python Dev I've fixed that and enhanced the support for NaN and inf for 2.6 and 3.0. I'm working together with Mark on more NaN and inf related fixes and he has fixed some numerical issues in the cmath module. We both hope to get Python's math more sound and stable across platforms. So far I got float('nan'), float('inf') and float('-inf') working on all platforms. The math module got three new methods: isinf, isnan, copysign. Additionally the trunk-math branch contains code for inverse hyberbolic functions (acosh), log1p, Mark's fixes for complex math and more stuff. For example operations on NaNs now return a NaN on all platforms (except 1**NAN which is defined as 1 and 0**NAN which is defined as 0). In 2.5 it depends on the platform whether a function raises an exception or returns NaN. Mark had the nice idea to introduce a thread local or global flag for NaN support. Depending on a flag Python turns a NaN into an exception. The feature needs a proper PEP. Maybe Mark has time to write a PEP in time. Christian From bearophileHUGS at lycos.com Sat Jan 5 17:59:33 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 5 Jan 2008 14:59:33 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: Sion Arrowsmith: > Because ... how to be polite about this? No, I can't. std::set is > crap. The implementation is a sorted sequence What about using hash_map instead? You can use it with GCC too (but you have to use a trick if you want to use string keys). Bye, bearophile From rtw at freenet.co.uk Wed Jan 2 14:07:00 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Wed, 02 Jan 2008 13:07:00 -0600 Subject: Extracting files from an ISO image? References: <34a84caa-5387-40a2-a808-5e7bd325023e@w47g2000hsa.googlegroups.com> Message-ID: Ant wrote in news:34a84caa-5387-40a2-a808- 5e7bd325023e at w47g2000hsa.googlegroups.com in comp.lang.python: [snip] > > So I have two questions really: > > 1) Is there a module out there for extracting files from an ISO? There are command line programs that can do this: http://cdrecord.berlios.de/old/private/cdrecord.html This (with isoinfo.exe from the above) will list all files in an iso image file: CD = import subprocess subprocess.call( [ "isoinfo.exe", '-f', '-i', CD ] ) isoinfo.exe also has a switch to extract a file to stdout One problem you may have is daemon tools will mount cd images that aren't iso images, where as isoinfo appears to handle only genuine iso file systems. Rob. -- http://www.victim-prime.dsl.pipex.com/ From dannox at gmail.com Thu Jan 10 16:14:40 2008 From: dannox at gmail.com (whatazor) Date: Thu, 10 Jan 2008 13:14:40 -0800 (PST) Subject: outgoing traffic monitor Message-ID: <409e811c-ca36-4273-b407-32ec364af5ed@k39g2000hsf.googlegroups.com> Hi all, I have thread that call a module which upload a file in a remote repository. A possible approach to calculate the time is tomonitor outgoing traffic of that thread. How can I do in python. There are modules usefull for this kind of requests? thank you all, bye w From tjreedy at udel.edu Thu Jan 24 17:34:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jan 2008 17:34:05 -0500 Subject: Increment Variable Name References: <9e9714f6-24d8-46fe-908f-205d223574cd@p69g2000hsa.googlegroups.com> Message-ID: "Paul Hankin" wrote in message news:fdff5a3c-376c-41da-bc7c-| > Do you want to do this?: | > locals()['var'+str(1)] = "spam" | | As I recently learnt in this newsgroup, that's not guaranteed to work. | >From http://docs.python.org/lib/built-in-funcs.html | | Warning: The contents of this dictionary should not be modified; | changes may not affect the values of local variables used by the | interpreter. It currently works at module level, where locals() is globals(). But then, one might as well write globals()['var'+str(1)] = "spam". But in Python, one is almost certainly better to use a collection object than this idiom (indefinite multiple numbered variables) imported from languages which do not have them. From lists at cheimes.de Fri Jan 25 09:28:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 25 Jan 2008 15:28:10 +0100 Subject: del self? In-Reply-To: References: Message-ID: Simon Pickles wrote: > Hi, > > Just curious... What are the implications of a class member calling: > > del self A method like def spam(self): del self just removes self from the local namespace of the spam function and thus results in decreasing the reference count of self by one. A class ordinary doesn't implement a __del__ function. The C implementation of classes use different methods to remove a class from memory (tp_dealloc, tp_clear and more). Christian From tjreedy at udel.edu Sat Jan 26 22:34:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jan 2008 22:34:47 -0500 Subject: Operator overloading References: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com><5vuob3F1nd2bhU1@mid.uni-berlin.de><2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> Message-ID: | > > Sure. Cosines are a monadic operation and the monadic '+' is a NOP, so | > > why shouldn't I define +45 to return cosine of 45, (presuming I needed | > > lots of cosines). I'd even let you define your own operators. Lots of | > > programmers really liked '++' and '--', for examples. One cannot change builtin types. One can subclass most of them and override most if not all the special methods. import math as m class trigint(int): def __pos__(self): return m.cos(m.pi*self/180.0) print +trigint(45) >>> 0.707106781187 Of course, for this case, def cosi(degrees): return m.pi*degrees/180.0 would probably be more sensible. There is and is no prospect of being able to add operators. Terry Jan Reedy From mr.cerutti at gmail.com Thu Jan 24 08:58:00 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 24 Jan 2008 08:58:00 -0500 Subject: Test driven development In-Reply-To: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> Message-ID: <51302a8c0801240558n7eb8d09at9df65163e6592393@mail.gmail.com> On 1/24/08, ajcppmod at gmail.com wrote: > Hi > > Sorry if this is a bit off topic but as unit testing is such a > cornerstone of python development I thought a few of you may be able > to share your knowledge/experiences. Test driven development, simplistically, means to write the tests before you write the code. > I like the concept of TDD but find it difficult to put into practice > most of the time. I think this primarily because I tend to like top- > down development and functional/object decomposition and TDD feels > more like a bottom-up approach. It should work with any unit of development, although it can be hard to usefully test high-level functionality that depends on currently unimplemented underware. > So my question is when approaching a project that you want to employ > test driven development on how and where do you start? And also if > anyone uses top-down design with TDD I would be interested in how you > do it (does it involve lots of mock objects/ is the first test you > write the last one to pass)? The system I've adopted is to use inline doctests for the simplest, tutorial-like examples, with "outline" unit tests composd to verify implementation details and to probe bounderies. Typically, I write a doctest, then the routine, and finally the unit tests. Top-down should work fine with test-driven, although your highest level tests will fail until your low-level tests pass. All the failing tests might be kind of depressing, though. Personally, I haven't really given top-down a fair shake, so I don't know which approach reveals my stupid design mistakes faster. -- Neil Cerutti From nodrogbrown at gmail.com Sat Jan 26 02:21:52 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Fri, 25 Jan 2008 23:21:52 -0800 (PST) Subject: getting values from cache Message-ID: <480b367b-e5c4-4018-a968-8c146555dbdd@v29g2000hsf.googlegroups.com> hi i am writing code to check a folder containing images and then process thir vals using PIL and do some calc to create a matrix of values .if the folder has any new imgs added the program will do all calc again and dump the values into a cachefile.If the folder contents remain unaltered the program should not do calc but load the vals from cachefile..it is assumed that malicious alterations are not made on the folder and so i wont be doing any thorogh check but just checking if contents of folder have changed..i do something like this def checkCache(self): filenameslist=getfilenameslist() # made by parsing folder before this try: f=open(cachefile) except IOError: #no cache found ,do all calc mynumpymatrix1,imgwdth,imght=docalculations() f2=open(cachefile,"w") #dump values as tuple pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f2) f2.close() else: #cache exists, need to check if folder contents changed oldfilenameslist,wd,ht, mynumpymatrix1=pickle.load(f) f.close() if(filenamelist==oldfilelist): #if oldfilenamelst same,it means folder hasn't changed #use the vals from cache..... else: #folder changed mynumpymatrix1,imgwdth,imght=docalculations() f3=open(cachefile,"w") pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f3) f3.close() this works and does what i need in my code..but i want to know if a more elegant solution is possible i am not worried about someone deliberately renaming files like aaaa.jpeg to aaa.jped and a.jpeg to deceive the checking since it is assumed that noone has permission to modify the folder except a trusted admin/code will be grateful for your suggestions tia From bborcic at gmail.com Fri Jan 25 06:25:03 2008 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 25 Jan 2008 12:25:03 +0100 Subject: sudoku solver in Python ... In-Reply-To: References: <43b2a56b-c8eb-4851-a9f6-10aa7e32e3ce@i29g2000prf.googlegroups.com> <222A1E46-A1C1-4793-A91E-9E0785463278@gmail.com> Message-ID: <4799c740$1_4@news.bluewin.ch> >> http://norvig.com/sudoku.html (...) > Below is the "winner" of my hacking for an as fast as > possible 110% pure python (no imports at all!) comprehensive sudoku > solver under 50 LOCs, back in 2006. Performance is comparable to the > solver you advertize - numbers are slightly better, but platform > differences could easily absorb that - More precise comparisons, after noting that on Norvig's pages there were contradictory performance numbers (obviously some 0 inserted or deleted). Running on my machine on the "top95" list of hard problems given on Norvig's page, my code takes about 7.5 ms/problem while Norvig's takes 42 ms/problem. So that's a 82% reduction of running time. Psyco.full() reduces the running time of my code to just about 4 ms/problem while it grows Norvig's to 47 ms/problem. BB > eg (not counting module > initialization and not using psyco) it takes 9.3 ms average on the "AI > escargot" problem linked to in Norvig's page, 5.6 ms/problem on some > standard "top1465" list of hard problems, and 3.4 ms/problem on the > first 1000 on some other "top50000" list of relatively hard problems. > This on my 2GHz Intel Centrino '05 laptop. Psyco reduces times by about > 50%. Dropping performance requirements by half allows reducing LOC count > in proportion. > > OTOH, the code although short is nearly unreadable, sorry; should > probably feature/comment it on some web page, like the two already > proposed in the thread. Will do if/for reviewer. Interface is calling > sudoku99(problem) with 'problem' a standard 81 character string with '0' > or '.' placeholder for unknowns. Returns same with values filled in. > > Beware that although in practice it solved all well-formed > human-solvable problems I could find, it is not guaranteed to deal > properly (or even terminate?) for underdetermined problems or determined > problems that would require exploring choicepoints with more than 2 > possibilities (if such exist). > > Cheers, Boris > > > > w2q = [[n/9,n/81*9+n%9+243,n%81+162,n%9*9+n/243*3+n/27%3+81] > for n in range(729)] > q2w = (z[1] for z in sorted((x,y) for y,s in enumerate(w2q) for x in s)) > q2w = map(set,zip(*9*[q2w])) > w2q2w = [set(w for q in qL for w in q2w[q] if w!=w0) for w0,qL in > enumerate(w2q)] > empty = set(range(729)).copy > > def sudoku99(problem) : > givens = set(9*j+int(k)-1 for j,k in enumerate(problem) if '0' ws=search(givens,[9]*len(q2w),empty()) > return ''.join(str(w%9+1) for w in sorted(ws)) > > def search(w0s,q2nw,free) : > while 1 : > while w0s: > w0 = w0s.pop() > for q in w2q[w0] : q2nw[q]=100 > wz = w2q2w[w0]&free > free-=wz > for w in wz : > for q in w2q[w] : > n = q2nw[q] = q2nw[q]-1 > if n<2 : > ww,=q2w[q]&free > w0s.add(ww) > if len(free)==81 : return free > thres = int((len(free)+52.85)/27.5) > ix,vmax = -1,0 > try : > while 1 : > ix=q2nw.index(2,ix+1) > for w0 in (q2w[ix]&free)-w0s : > v = len(w2q2w[w0]&free) > if v > vmax : > ixmax = ix > if v >=thres : break > vmax = v > w0s.add(w0) > else : continue > break > except : pass > w0,w1 = q2w[ixmax]&free > try : > w0s.clear() > w0s.add(w0) > return search(w0s,q2nw[:],free.copy()) > except ValueError : > w0s.clear() > w0s.add(w1) > From bj_666 at gmx.net Sun Jan 13 02:59:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Jan 2008 07:59:45 GMT Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> Message-ID: <5utunhF1jl8liU1@mid.uni-berlin.de> On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: > However, I am very surprised to learn that > > super_object.__getattr__(name)(*args, **kwargs) > > getattr(super_object, name)(*args, **kwargs) > > are not equivalent. This is quite odd, at least when with len() > and .__len__, str() and .__str__. Do you maybe know what's the > rationale behind not following that convention by getattr? I think you are confusing `__getattr__` and `__getattribute__` here! `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's different. Ciao, Marc 'BlackJack' Rintsch From info at thegrantinstitute.com Tue Jan 22 18:45:21 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 22 Jan 2008 15:45:21 -0800 Subject: Professional Grant Proposal Writing Workshop (April 2008: Vancouver, British Columbia) Message-ID: <20080122154521.4978BC0DD8845659@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From cokofreedom at gmail.com Thu Jan 17 09:42:42 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 17 Jan 2008 06:42:42 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> Message-ID: <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> On Jan 17, 2:52 pm, Chris wrote: > On Jan 17, 2:35 pm, cokofree... at gmail.com wrote: > > > > > On Jan 17, 1:21 pm, Sacred Heart wrote: > > > > Hi, > > > I'm new to Python and have come across a problem I don't know how to > > > solve, enter com.lang.python :) > > > > I'm writing some small apps to learn the language, and I like it a lot > > > so far. > > > > My problem I've stumbled upon is that I don't know how to do what I > > > want. I want to do a loop in a loop. I think. > > > > I've got two arrays with some random stuff in, like this. > > > > array1 = ['one','two','three','four'] > > > array2 = ['a','b','c','d'] > > > > I want to loop through array1 and add elements from array2 at the end, > > > so it looks like this: > > > > one a > > > two b > > > three c > > > four c > > > > I'm stuck. I know how to loop through the arrays separatly and print > > > them, but both at the same time? Hmmm. > > > > A push in the right direction, anyone? > > > > R, > > > SH > > > for i in zip(array1, array2): > > print i > > > Although I take it you meant four d, the issue with this method is > > that once you hit the end of one array the rest of the other one is > > ignored. > > You could always pre-pad the lists you are using before using the zip > function, kinda like > > def pad(*iterables): > max_length = 0 > for each_iterable in iterables: > if len(each_iterable) > max_length: max_length = > len(each_iterable) > for each_iterable in iterables: > each_iterable.extend([None for i in xrange(0,max_length- > len(each_iterable))]) > > pad(array1, array2, array3) > for i in zip(array1, array2, array3): > print i > > What you could also do is create an index to use for it. > > for i in xrange(0, length_of_longest_list): > try: print array1[i] > except IndexError: pass > try: print array2[i] > except IndexError: pass couldn't you just do something like if len(array1) is not len(array2): if len(array1) < len(array2): max_length = len(array2) - len(array1) array1.extend([None for i in xrange(0, max_length)]) elif len(array1) > len(array2): max_length = len(array1) - len(array2) array2.extend([None for i in xrange(0, max_length)]) for i in zip(array1, array2): print i Though my case only really works for these two, whereas yours can be used on more than two lists. :) From lists at cheimes.de Fri Jan 25 09:29:06 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 25 Jan 2008 15:29:06 +0100 Subject: psyco on mac In-Reply-To: <266557d0801181710p5eb54420h79def10af5135985@mail.gmail.com> References: <266557d0801181710p5eb54420h79def10af5135985@mail.gmail.com> Message-ID: Arash Arfaee wrote: > Hello, > > I have problem installing psyco on my mac. Can anybody help me? Psyco doesn't work on a PowerPC Mac. It requires a i4986 compatible CPU (aka x86 or IA32). Christian From stefan.behnel-n05pAM at web.de Wed Jan 23 10:19:37 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 16:19:37 +0100 Subject: Lxml on mac In-Reply-To: References: Message-ID: <47975B09.8090705@web.de> marcroy.olsen at gmail.com wrote: > What to one do if one what to use lxml(http://codespeak.net/lxml/ > index.html) on a mac? Have you tried installing up-to-date versions of libxml2/libxslt and running easy_install lxml ? Stefan From fredrik at pythonware.com Wed Jan 9 05:02:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 11:02:52 +0100 Subject: Open a List of Files In-Reply-To: <4f67337a-14ea-4552-8a5a-6de9703e58ff@d70g2000hsb.googlegroups.com> References: <874pdomrrd.fsf@mulj.homelinux.net> <4f67337a-14ea-4552-8a5a-6de9703e58ff@d70g2000hsb.googlegroups.com> Message-ID: Paul Hankin wrote: > This can be more cleanly written using locals() > > for fn in filenames: > locals()[fn] = open(os.path.join(host_path, fname + '.txt', 'wb') from the reference manual: locals() Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. examples: >>> def foo(): ... locals()["foo"] = 1 ... print foo ... >>> foo() >>> def foo(): ... foo = 1 ... locals()["foo"] = 2 ... print foo ... >>> foo() 1 From cptnwillard at gmail.com Fri Jan 18 14:01:29 2008 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Fri, 18 Jan 2008 11:01:29 -0800 (PST) Subject: Is this a bug, or is it me? References: <87myr4o3sg.fsf@mulj.homelinux.net> Message-ID: <8afa3779-6803-43ed-ae4d-d0a102eda00d@x69g2000hsx.googlegroups.com> I filed a bug report, and here is the short answer to my question: genexps are code blocks, and code blocks cannot see variables in class scopes. Congrats to Neil Cerutti who figured it out. Now here is another one for your enjoyment: class C: @staticmethod def f1(): pass F = { '1' : f1 } C().F['1']() >>> TypeError: 'staticmethod' object is not callable What do you think of this one? From iclark at mail.ewu.edu Wed Jan 16 11:12:42 2008 From: iclark at mail.ewu.edu (Ian Clark) Date: Wed, 16 Jan 2008 16:12:42 +0000 (UTC) Subject: error/warning color customization in interactive console? References: Message-ID: On 2008-01-16, yhvh wrote: > Is it possible to output error messages in a different color? > I'm using Terminal on Gnome. >>> print "\033[1;31mHello\033[0m There!" Some reading: http://en.wikipedia.org/wiki/ANSI_escape_code http://www.ioncannon.net/ruby/101/fun-with-ansi-escape-codes/ Also, you might look at sys.excepthook to colorize an uncaught exception, and PYTHONSTARTUP to load code automagically before an interactive session. Ian From jr9445 at ATT.COM Fri Jan 11 10:51:01 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 11 Jan 2008 09:51:01 -0600 Subject: python recursive function 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 Tom_chicollegeboy > Sent: Friday, January 11, 2008 3:30 AM > To: python-list at python.org > Subject: python recursive function > > Now, you are to write a program that, if I give you n bears, returns > true if it is at all possible for you to win the game. Your program > must use recursion to check all possible ways in which you can apply > the rules. > > if n==42: > return True > return False You have to check for all possible paths. Returning True/False is futile since the recursive chains will be returning a mix of true and false. Use a global variable to indicate if a solution is found. (Or pass the flag in using a list, since lists are passed by reference (if n == 42: found_it[0] = True; return.) There's also another teaching exercise in here. Do you follow the literal directions ('check all possible ways') and generate all possible paths? Or do you 'interpret' that to mean try all possible paths until you find a solution? (i.e. do you short circuit the recursion once you have a solution?) One of the most difficult things about programming is conveying the requirements from Human A to Human Programmer B. This is especially difficult since business people and techies speak different languages and, more importantly, think differently (different assumptions, different paradigms, different levels of hand-waving away of details, etc..) And don't get me started about the people in marketing... ***** 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 gnewsg at gmail.com Sat Jan 12 11:49:37 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 12 Jan 2008 08:49:37 -0800 (PST) Subject: How to get user home directory on Windows References: Message-ID: <0bb27916-5416-47b2-b58c-1eb82ccb6d3e@k2g2000hse.googlegroups.com> On 12 Gen, 17:44, Christian Heimes wrote: > Giampaolo Rodola' wrote: > > Is there a way to do that? > > home = os.path.expanduser("~") > > Christian That gives the home of the *current logged in user*. I need another thing. From stefan.behnel-n05pAM at web.de Wed Jan 23 11:49:44 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 17:49:44 +0100 Subject: Processing XML that's embedded in HTML In-Reply-To: References: <6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> <47972624.2050002@web.de> Message-ID: <47977028.3070106@web.de> Mike Driscoll wrote: > Both the normal parser example and the objectify example you gave me > give a traceback as follows: > > Traceback (most recent call last): > File "\\clippy\xml_parser2.py", line 70, in -toplevel- > for row in tree.iterfind("//Row"): > AttributeError: 'etree._ElementTree' object has no attribute > 'iterfind' > > > Is there some kind of newer version of lxml? Yep, lxml 2.0. It's currently in beta, but that doesn't say much. http://codespeak.net/lxml/dev/ Stefan From cokofreedom at gmail.com Wed Jan 9 08:08:03 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jan 2008 05:08:03 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <2a90b41a-2e82-465a-8b97-50ead52dca5b@x69g2000hsx.googlegroups.com> Message-ID: <84bd2cda-30d7-44a8-bff2-3efaccf6fa08@e10g2000prf.googlegroups.com> Designed a pretty basic way that is "acceptable" on small strings. evenOrOdd = True s1 = "hi_cat_bye_dog_foo_bar_red" s2 = "" for i in s1: if i == '_': if evenOrOdd: s2 += ':' evenOrOdd = not evenOrOdd else: s2 += ',' evenOrOdd = not evenOrOdd else: s2 += i print s2 From martin at v.loewis.de Thu Jan 17 00:21:03 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 Jan 2008 06:21:03 +0100 Subject: Creating unique combinations from lists In-Reply-To: References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> <13osvl1j4pvka15@corp.supernews.com> <001640bd-7759-423b-ad74-275b27e5d5d6@v4g2000hsf.googlegroups.com> Message-ID: <478EE5BF.7020008@v.loewis.de> > The main emphasis was to show that there was a pattern unfolding that > should have been translated into more pythonic code than just > hard-coding nested loops. Practicality beats purity. That you would solve a more general problem in a more general way doesn't mean that you shouldn't solve the more specific problem (combinations from three sets) in a specific, easy-to-read way. Readability counts. I find your solution (with nested generators) *very* unpythonic. It is much more complicated than necessary to solve the problem at hand, and it doesn't get Pythonic just by using the latest language features. It may be a smart solution, but not a Pythonic one. Regards, Martin P.S. To solve the general problem, I like http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496807 From deets at nospam.web.de Tue Jan 15 06:03:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 Jan 2008 12:03:25 +0100 Subject: common problem - elegant solution sought References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <5v3i7tF1jvujbU1@mid.uni-berlin.de> Helmut Jarausch wrote: > Hi, > > I'm looking for an elegant solution of the following tiny but common > problem. > > I have a list of tuples (Unique_ID,Date) both of which are strings. > I want to delete the tuple (element) with a given Unique_ID, but > I don't known the corresponding Date. > > My straight forward solution is a bit lengthy, e.g. > > L=[("a","070501"),("b","080115"),("c","071231")] > pos=-1 > found=-1 > for (Key,Date) in L : > pos+= 1 > if Key == "b" : > found= pos > break > > if found >= 0 : > del L[found] > > print L > > Most probably there are much more elegant solutions. > Unfortunately, the index-list-method doesn't take an > additional function argument for the comparisons. > > Many thanks for your hints, Several solutions: - use a different datastructure, as others suggested - use a database. SQLite for example. - replace the list in-place like this: L[:] = [(k, d) for k, d in L if k != "b"] Diez From israelu at elbit.co.il Wed Jan 23 14:44:39 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 23 Jan 2008 11:44:39 -0800 (PST) Subject: Hebrew in idle ans eclipse (Windows) References: <478ee0c0$0$4589$9b622d9e@news.freenet.de> <86ea4c94-f4b3-4bc3-9b2a-bc9b5c182264@i12g2000prf.googlegroups.com> <478FBC1A.4080201@v.loewis.de> <47970642$0$13412$9b622d9e@news.freenet.de> Message-ID: <5831f555-f445-4cb5-9796-56b6df12c7f8@e10g2000prf.googlegroups.com> On Jan 23, 11:17 am, "Martin v. L?wis" wrote: > If you are claimaing that the program > > Apparently, they do the OEMtoANSI conversion when you run a console > application (i.e. python.exe), whereas they don't convert when running > a GUI application (pythonw.exe). > > I'm not quite sure how they find out whether the program is a console > application or not; the easiest thing to do might be to turn the > autoconversion off on the server. > > Regards, > Martin True! It's amazing, I've just written a little code that reads from the database and writes the data to a file. Then I ran the code with both python.exe and pythonw.exe and got the two kinds of results - the IDLE one and the eclipse one! From lepto.python at gmail.com Sun Jan 20 22:21:40 2008 From: lepto.python at gmail.com (oyster) Date: Mon, 21 Jan 2008 11:21:40 +0800 Subject: problem with 'global' Message-ID: <6a4f17690801201921v38a83770qcdceb9ec051a3c73@mail.gmail.com> why the following 2 prg give different results? a.py is ok, but b.py is 'undefiend a' I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 #a.py def run(): if 1==2: # note, it always False global a a=1 run() a #b.py def run(): a=1 run() a From kirby.urner at gmail.com Thu Jan 10 13:29:30 2008 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: Thu, 10 Jan 2008 10:29:30 -0800 (PST) Subject: Collecting Rich Data Structures for students References: <8b4e7954-b666-4515-9ae2-821d979ebd7f@m34g2000hsf.googlegroups.com> <13obk7gpdug6f5d@corp.supernews.com> Message-ID: On Jan 10, 1:01 am, Dennis Lee Bieber wrote: > On Wed, 9 Jan 2008 15:05:25 -0800 (PST), "kirby.ur... at gmail.com" > declaimed the following in comp.lang.python: > > > Sometimes we spare the students (whomever they may be) this added > > step and just hand them a dictionary of lists or whatever. We > > may not be teaching parsing in this class, but chemistry, and > > having the info in the Periodic Table in a Pythondatastructure > > maybe simply be the most relevant place to start. > > In this particular example, I'd probably suggest stuffing thedata > into an SQLite3 database file... Searching on name, symbol, weight, etc. > would be much easier then trying to dig through a nested dictionary. > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ That's not a bad idea. We might see people passing ZODBs around more too, as 'import zodb' in IDLE or whatever is increasingly the style, vs. some megabundle you have to install. Think of Zope as another site-package. The advantage of just passing .py files around, among XO users for example, is the periodicTable.py's contents are directly eyeballable as ascii/unicode text, vs. stuffed into a wrapper. I think what I'm getting from this fruitful discussion is the different role of amalgamator-distributors, and Sayid or Kate as classroom teachers, just trying to get on with the lesson and having no time for computer science topics. XML or YAML also make plenty of sense, for the more generic distributor type operations. Speaking only for myself, I appreciated some of the pointers to APIs. Over on edu-sig, we've been talking a lot about the 3rd party module for accessing imdb information -- not a screen scraper. Given xml-rpc, there's really no limit on the number of lightweight APIs we might see. How about CIA World Factbook? Too boring maybe, but it's already going out on the XOs, or some of them, just because it's relatively up to date. Could be imported as Python module too -- maybe that work has already been done? Kirby From gnewsg at gmail.com Mon Jan 14 07:56:52 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Mon, 14 Jan 2008 04:56:52 -0800 (PST) Subject: Threaded server References: Message-ID: <7decdf29-aab4-4fc6-93d8-7b2565e23f78@m34g2000hsf.googlegroups.com> On 14 Gen, 12:30, Nick Craig-Wood wrote: > Giampaolo Rodola' wrote: > > ?I'm trying to run an asynchronous FTP server I wrote into a thread for > > ?being able to run a test suite against it. > > ?The code below is the threaded FTP server code I'm using: > > > ?class FTPd(threading.Thread): > > > ? ? ?def __init__(self): > > ? ? ? ? ?self.active = False > > ? ? ? ? ?threading.Thread.__init__(self) > > > ? ? ?def start(self, flag=None): > > ? ? ? ? ?assert not self.active > > ? ? ? ? ?self.flag = flag > > ? ? ? ? ?threading.Thread.start(self) > > > ? ? ?def run(self): > > ? ? ? ? ?assert not self.active > > ? ? ? ? ?ftpd = ftpserver.FTPServer(address, ftp_handler) > > ? ? ? ? ?if self.flag: > > ? ? ? ? ? ? ?self.flag.set() > > ? ? ? ? ?self.active = True > > ? ? ? ? ?while self.active: > > ? ? ? ? ? ? ?ftpd.server_forever(timeout=1, count=1) > > ? ? ? ? ?ftpd.close() > > > ? ? ?def stop(self): > > ? ? ? ? ?assert self.active > > ? ? ? ? ?self.active = False > > > ?flag = threading.Event() > > ?ftpd = FTPd() > > ?ftpd.start(flag) > > ?flag.wait() ?# wait for it to start > > ?unittest.main() # run the test suite > > ?ftpd.stop() > > > ?Sometimes I get a strange error when all the tests have finished, the > > ?server is stopped and Python is exiting: > > > ?Ran 50 tests in 1.515s > > > ?OK > > ?Exception exceptions.TypeError: "'NoneType' object is not callable" in > > > ?thod FTPHandler.__del__ of > ?127.0.0.1:2 > > ?249 at 0xa4b080>> ignored > > ?Exception exceptions.TypeError: "'NoneType' object is not callable" in > > > ?thod FTPServer.__del__ of > ?127.0.0.1:543 > > ?21 at 0x9e1a30>> ignored > > > ?I sincerely don't know why that happens but it's likely because I'm > > ?not using threads properly. > > ?My concern is that this could be caused by a sort of race condition > > ?(e.g. Python tries to exit when ftpd.close call is not yet > > ?completed). > > It looks like when python is shutting down, it has removed an object > the ftphandler code relies on. > > I see you attempt to kill the ftp server with ftpd.stop(). ?That is > good, but you don't wait for the thread to finish (it might take up to > a second in ftpd.server_forever if I understand correctly). > > I expect if you put a self.join() at the end of the stop() method the > problem will go away. > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Tried it but the problem remains. The strange thing is that it sometimes happens, sometimes doesn't. From israelu at elbit.co.il Thu Jan 17 03:00:37 2008 From: israelu at elbit.co.il (iu2) Date: Thu, 17 Jan 2008 00:00:37 -0800 (PST) Subject: Hebrew in idle ans eclipse (Windows) References: <478ee0c0$0$4589$9b622d9e@news.freenet.de> Message-ID: <86ea4c94-f4b3-4bc3-9b2a-bc9b5c182264@i12g2000prf.googlegroups.com> On Jan 17, 6:59?am, "Martin v. L?wis" wrote: > > What do I need to do run my app like IDLE does? > > Can you please show the fragment of your program that prints > these strings? > > Regards, > Martin Hi, I use pymssql to get the data from a database, just like this (this is from the pymssql doc): import pymssql con = pymssql.connect(host='192.168.13.122',user='sa',password='',database='tempdb') cur = con.cursor() cur.execute('select firstname, lastname from [users]') lines = cur.fetchall() print lines or print lines[0] 'lines' is a list containing tuples of 2 values, for firstname and lastname. The names are Hebrew and their code looks different when I'm runnig it from IDLE than when running it from Windows shell or eclipse, as I described in my first post. Important: This doesn't happer when I read text from a file containing Hebrew text. In that case both IDLE and eclipse give the same reulst (the hebrew word itself is printed to the console) From sween119 at hotmail.com Sat Jan 12 09:29:24 2008 From: sween119 at hotmail.com (sween119 at hotmail.com) Date: Sat, 12 Jan 2008 06:29:24 -0800 (PST) Subject: Great Python books for the beginner References: Message-ID: On Jan 12, 2:03?am, Landon wrote: > Hi, I'm a freshman in college and I'm going to be taking an intro to > programming course next semester which mainly uses Python, so I > thought it might be a good time to pick up Python beyond the scope of > the class as well. The text book for this class is Python for the > Absolute Beginner or something similar to that name. > > I was wondering if anyone had any opinions on what other titles I > could look into since this one seems from a glance at reviews to be > teaching mainly through game programming (a topic I'm not too > interested in) or if this one is a quality book by itself. Hi Landon, I've found the O'reilly books to be useful I have the Python Pocket reference, which is helpful for me to remember the parameters surrounding commands and all that. I've been known to peruse the "Learning Python" book by the same publisher and I really like "Programming Python" (though it is thoroughly hefty and runs about $60USD) But has excellent documentation and if I may put a word in for to check out if you would be at all interested in starting game programming. -Sween From hniksic at xemacs.org Mon Jan 14 06:53:30 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 14 Jan 2008 12:53:30 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <87prw4fyej.fsf@benfinney.id.au> Message-ID: <87tzlgvd1h.fsf@mulj.homelinux.net> Ben Finney writes: > What one is "in reality" calling is the '__new__' method of the Person > class. That function, in turn, is creating a new Person instance, and > calling the '__init__' method of the newly-created instance. Finally, > the '__new__' method returns that instance back to the caller. This is also not entirely correct. __new__ doesn't call __init__; if it did, there would be no way to call __new__ without also calling __init__ (pickle, among other things, does that and needs to do that to correctly implement its logic). "In reality" executing Person(...) invokes the __call__ method of type(Person) (normally the standard metatype called "type") bound to the Person type object. This is where the logic to call __new__ followed by __init__ is implemented, in code that does something close to this: obj = mytype.__new__(*args, **kwds) if isinstance(obj, mytype): mytype.__init__(obj, *args, **kwds) return obj From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 17 09:44:29 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 17 Jan 2008 15:44:29 +0100 Subject: Loop in a loop? In-Reply-To: References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <478f699d$0$17578$426a74cc@news.free.fr> Sacred Heart a ?crit : > On Jan 17, 1:35 pm, cokofree... at gmail.com wrote: >> for i in zip(array1, array2): >> print i >> >> Although I take it you meant four d, the issue with this method is >> that once you hit the end of one array the rest of the other one is >> ignored. > > Yes, small typo there. > > Okey, so if my array1 is has 4 elements, and array2 has 6, it won't > loop trough the last 2 in array2? How do I make it do that? Please gentlemen: Python has no builtin type named 'array', so s/array/list/g Just pad your shortest list. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 15 06:19:48 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 15 Jan 2008 12:19:48 +0100 Subject: common problem - elegant solution sought In-Reply-To: <5v3gg1F1kkla5U1@mid.dfncis.de> References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <478c96b1$0$29652$426a34cc@news.free.fr> Helmut Jarausch a ?crit : > Hi, > > I'm looking for an elegant solution of the following tiny but common > problem. > > I have a list of tuples (Unique_ID,Date) both of which are strings. > I want to delete the tuple (element) with a given Unique_ID, but > I don't known the corresponding Date. If you don't care about ordering, you could use a dict: L=[("a","070501"),("b","080115"),("c","071231")] d = dict(L) del d['b'] L = d.items() But I guess you care about ordering !-) Anyway, you can still use a dict to find out the date part: L=[("a","070501"),("b","080115"),("c","071231")] d = dict(L) t = ('b', d['b']) L.remove(t) Or you could build an 'index' list to find out the appropriate index: L=[("a","070501"),("b","080115"),("c","071231")] index = [key for key, val in L] pos = index.index('b') del L[pos] > My straight forward solution is a bit lengthy, e.g. > > L=[("a","070501"),("b","080115"),("c","071231")] > pos=-1 > found=-1 > for (Key,Date) in L : > pos+= 1 > if Key == "b" : > found= pos > break > > if found >= 0 : > del L[found] > > print L You could have used the enumerate(seq) function here. And since you're breaking out once the element deleted, you could as well delete it from within the loop: for pos, (key, date) in enumerate(L): if key == 'b': del L[pos] break Benchmarking left as an exercice to the reader !-) Also note that the "best" solution may depend on your real use case and dataset. From workitharder at gmail.com Sat Jan 5 16:35:08 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 5 Jan 2008 13:35:08 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> Message-ID: <61faa305-38ad-42c4-9cd1-09851848cb14@l6g2000prm.googlegroups.com> On Jan 5, 8:14 am, c... at mailinator.com wrote: > On Jan 5, 5:07 pm, c... at mailinator.com wrote: > > > Hello, Paul and Arnaud. > > While I think about your answers: do you think there is any way to > > avoid shuffle? > > It may take unnecessary long on a long list most of whose elements > > have the property. > > Umm... > You provide nice answers in the case many elements are picked from the > same list. > Any ideas for the case when the picker is called many times on a > program, but never twice with the same list? Here's my stab: from random import randint, seed from time import time from sys import stdout seed(time()) iterations = 0#DEBUG def pick_random(seq, prop=bool): temp = list(seq) global iterations#DEBUG while temp: iterations += 1#DEBUG i = randint(0, len(temp) - 1) if prop(temp[i]): return temp[i] else: del temp[i] def generate_list(length): l = list() for x in xrange(length): l.append(randint(0,1) * randint(1,1000)) return l count = 0 for x in xrange(1000): count += 1 print pick_random(generate_list(1000)), print print "AVERAGE ITERATIONS:", float(iterations) / count The average number of iterations is 1/p where p is the chance of your property being true. It's independent of list size! Just remove the DEBUG lines and it's ready for use. --Buck From paddy3118 at googlemail.com Mon Jan 7 03:04:53 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 7 Jan 2008 00:04:53 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <33417662-8246-4950-9b86-265aa1c63c69@c23g2000hsa.googlegroups.com> Message-ID: On Jan 5, 6:37 am, Paddy wrote: > On Jan 4, 7:55 pm, c... at mailinator.com wrote: > > > > > Hello, > > This is a question for the best method (in terms of performance > > only) to choose a random element from a list among those that satisfy > > a certain property. > > > This is the setting: I need to pick from a list a random element > > that satisfies a given property. All or none of the elements may have > > the property. Most of the time, many of the elements will satisfy the > > property, and the property is a bit expensive to evaluate. Chance of > > having the property are uniform among elements. > > > A simple approach is: > > > import random > > def random_pick(a_list,property): > > '''Returns a random element from a list that has the property > > > Returns None if no element has the property > > ''' > > random.shuffle(a_list) > > for i in a_list: > > if property(i): return i > > > but that requires to shuffle the list every time. > > > A second approach, that works if we know that at least one element of > > the list has the property, is: > > > import random > > def random_pick(a_list,property): > > '''Returns a random element from a list that has the property > > > Loops forever if no element has the property > > ''' > > while 1: > > i=random.choice(a_list) > > if property(i): return i > > > which is more efficient (on average) if many elements of the list have > > the property and less efficient if only few elements of the list has > > the property (and goes crazy if no element has the property) > > > Yet another one: > > > import random > > def random_pick(a_list,property): > > '''Returns a random element from a list that has the property > > ''' > > b_list=[x for x in a_list if property(x)] > > try: > > return random.choice(b_list) > > finally: return None > > > but this one checks the property on all the elements, which is no > > good. > > > I don't need strong random numbers, so a simple solution like: > > import random > > globalRNG=random.Random() > > > def random_pick(a_list,property): > > '''Returns a random element from a list that has the property > > > Works only if len(a_list)+1 is prime: uses Fermat's little theorem > > ''' > > a=globalRNG(1,len(a_list)) > > ind=a > > for i in xrange(len(a_list)): > > x=a_list[a-1] > > if property(x):return x > > ind*=a > > > but this works only if len(a_list)+1 is prime!!! Now this one could be > > saved if there were an efficient method to find a prime number given > > than a number n but not very much greater... > > > Any other ideas? Thanks everybody > > Caching might help. > > If random_pick is called several times with the same list(s) then > cache the result of > [property(i) for i in a_list] against a_list. > > If random_pick is called several times with list(s) whith multiple > instances of list items then cache > property(i) against i for i in a_list . > > You could do both. > > You might investigate wether property(i) could be implemented using a > faster algorithm, maybe table lookup, or interpolation from initial > table lookup. > > - Paddy. Here's a caching decorator that you could apply to function property: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498245 - Paddy. From PatrickMinnesota at gmail.com Wed Jan 9 21:10:03 2008 From: PatrickMinnesota at gmail.com (PatrickMinnesota) Date: Wed, 9 Jan 2008 18:10:03 -0800 (PST) Subject: Pygame w/ GUI Message-ID: <3566c2f9-c138-45d3-bc2d-7b2a2b3f78c7@q39g2000hsf.googlegroups.com> I know this isn't strictly a Python question, but I'm betting some here might be able to give me a hint. I have a few graphical programs doing some 2D data visualization using simple Pygame code for pseudo real-time animation. It's running under windows XP right now, but eventually it'll need to be cross- platform. As it is right now, it probably is, I just haven't tried it anywhere but XP. Now I want to wrap some simple GUI functions around it. I'm looking for some buttons, a text field or two and file system selection of data files. I figure many have done this and there is a better solution than to use Pygame constructs to implement such things. My question: I'm not seeing much support in Pygame for that stuff. It seems I should build buttons and file browsing in some other toolkit. Is that true? Or am I just to early on in the Pygame docs to see solutions? If I should use something else, am I going to be able to use Tkinter or WxPython in conjunction with my Pygame code? Or is there something else I should be looking at? Oh, and I'm running Python 2.5.1 Thanks for any thoughts. From lists at cheimes.de Wed Jan 23 02:49:20 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 23 Jan 2008 08:49:20 +0100 Subject: translating Python to Assembler In-Reply-To: References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: Wim Vander Schelden wrote: > Python modules and scripts are normally not even compiled, if they have > been, > its probably just the Python interpreter packaged with the scripts and > resources. No, that is not correct. Python code is compiled to Python byte code and execute inside a virtual machine just like Java or C#. It's even possible to write code with Python assembly and compile the Python assembly into byte code. You most certainly meant: Python code is not compiled into machine code. Christian From lists at cheimes.de Mon Jan 28 10:50:36 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 28 Jan 2008 16:50:36 +0100 Subject: validate string is valid maths In-Reply-To: <13pru0etgp7joc1@corp.supernews.com> References: <13pru0etgp7joc1@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > def rationalise_signs(s): > while "++" in s or "+-" in s or "-+" in s or "--" in s: > s = s.replace("++", "+") > s = s.replace("--", "+") > s = s.replace("+-", "-") > s = s.replace("-+", "-") > return s I assume it's faster to check the length of the string s after each iteration and compare it to the last iteration. When the string hasn't changed break out of the loop. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 17 03:58:51 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 17 Jan 2008 09:58:51 +0100 Subject: Replace stop words (remove words from a string) In-Reply-To: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> Message-ID: <478f189d$0$24730$426a74cc@news.free.fr> BerlinBrown a ?crit : > if I have an array of "stop" words, and I want to replace those values > with something else; in a string, how would I go about doing this. I > have this code that splits the string and then does a difference but I > think there is an easier approach: > > E.g. > > mystr = > kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsldfsd; > you forgot the quotes > if I have an array stop_list = [ "[BAD]", "[BAD2]" ] s/array/list/ > I want to replace the values in that list with a zero length string. > > I had this before, but I don't want to use this approach; I don't want > to use the split. > > line_list = line.lower().split() > res = list(set(keywords_list).difference(set(ENTITY_IGNORE_LIST))) res = mystr for stop_word in stop_list: res = res.replace(stop_word, '') From adonisv at REMOVETHISearthlink.net Wed Jan 9 21:46:29 2008 From: adonisv at REMOVETHISearthlink.net (Adonis Vargas) Date: Wed, 09 Jan 2008 21:46:29 -0500 Subject: Pygame w/ GUI In-Reply-To: <3566c2f9-c138-45d3-bc2d-7b2a2b3f78c7@q39g2000hsf.googlegroups.com> References: <3566c2f9-c138-45d3-bc2d-7b2a2b3f78c7@q39g2000hsf.googlegroups.com> Message-ID: <13ob1o7t81b7e0c@corp.supernews.com> PatrickMinnesota wrote: > I know this isn't strictly a Python question, but I'm betting some > here might be able to give me a hint. > > I have a few graphical programs doing some 2D data visualization using > simple Pygame code for pseudo real-time animation. It's running > under windows XP right now, but eventually it'll need to be cross- > platform. As it is right now, it probably is, I just haven't tried it > anywhere but XP. > > Now I want to wrap some simple GUI functions around it. I'm looking > for some buttons, a text field or two and file system selection of > data files. I figure many have done this and there is a better > solution than to use Pygame constructs to implement such things. > > My question: I'm not seeing much support in Pygame for that stuff. > It seems I should build buttons and file browsing in some other > toolkit. Is that true? Or am I just to early on in the Pygame docs > to see solutions? > > If I should use something else, am I going to be able to use Tkinter > or WxPython in conjunction with my Pygame code? Or is there something > else I should be looking at? > > Oh, and I'm running Python 2.5.1 > > Thanks for any thoughts. I do not have experience using pygame, but you can look at: http://pyui.sourceforge.net/ Creates an user interface with pygame as a possible back end. Hope this helps. Adonis From paddy3118 at googlemail.com Sat Jan 26 02:53:49 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 25 Jan 2008 23:53:49 -0800 (PST) Subject: [OT]: The Python Fan Message-ID: http://www.brightcove.tv/title.jsp?title=1390821847 :-) - Paddy. From ajcppmod at gmail.com Thu Jan 24 07:37:24 2008 From: ajcppmod at gmail.com (ajcppmod at gmail.com) Date: Thu, 24 Jan 2008 04:37:24 -0800 (PST) Subject: Test driven development Message-ID: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> Hi Sorry if this is a bit off topic but as unit testing is such a cornerstone of python development I thought a few of you may be able to share your knowledge/experiences. I like the concept of TDD but find it difficult to put into practice most of the time. I think this primarily because I tend to like top- down development and functional/object decomposition and TDD feels more like a bottom-up approach. So my question is when approaching a project that you want to employ test driven development on how and where do you start? And also if anyone uses top-down design with TDD I would be interested in how you do it (does it involve lots of mock objects/ is the first test you write the last one to pass)? Thanks Andy From soren.skou.nielsen at gmail.com Thu Jan 10 03:44:19 2008 From: soren.skou.nielsen at gmail.com (Soren) Date: Thu, 10 Jan 2008 00:44:19 -0800 (PST) Subject: FindWindowById returns None..... ? References: Message-ID: <0a3d6bf8-110a-4b1c-a2df-d8495d0b1204@s19g2000prg.googlegroups.com> On Jan 10, 9:43 am, Soren wrote: > Hi, > > I'm trying to split my GUI into several files since its beginning to > become a bit large.. I've placed a panel class inside gui2.py, but it > needs some information from a panel in gui1.py... if I import gui1 in > gui2 and try to find the panel by its ID, (using the Id generated in > gui1) I get a None value returned?? using findwindowbyid in gui1 on > the same ID works fine.. > > I'm guessing i'm doing this the wrong way, can anyone comment on this? > > Thanks, > Soren Wops.. and I'm using wxPython :) From arnodel at googlemail.com Sun Jan 20 20:12:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 20 Jan 2008 17:12:18 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <80e1aed1-1d75-4409-bbc3-d48f9c3656ab@e6g2000prf.googlegroups.com> Message-ID: On Jan 21, 1:07?am, Arnaud Delobelle wrote: > On Jan 20, 5:41?pm, dg.google.gro... at thesamovar.net wrote: > > > Ever since I learnt to program I've always loved writing solvers for > > the Countdown numbers game problem in different languages > > Ok so here's a challenge I just thought of: > > What is (or are) the set of 6 starting numbers which are such that the > smallest target they can't reach is maximal? Update: 2, 4, 5, 8, 9, 25 can reach any target between 100 and 999. The question remains if we lift the upper limit of 999... Time to really go to bed :) -- Arnaud From steve at mhomer.au Thu Jan 10 21:09:26 2008 From: steve at mhomer.au (Steve Brown) Date: Fri, 11 Jan 2008 13:09:26 +1100 Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: <13odjunti9pfq7f@corp.supernews.com> What I'm trying to do with the tests is pare them back so that the code explicitly and concisely documents the tests. It is important that the comments and doc strings NOT contain information about how Temperature Sense works because that is outside the scope of the test. More generally, comments like this i++ #increments i indicate that the author thinks that the most complex thing present is the syntax, a comment like this: i++ #next voltage indicates that the author thinks the most complex thing present is the variable mapping. For the readers and maintainers of these tests, the most complex thing present is the syntax, not the test logic, so if I need to add more documentation, it will look like this: # Temperature Sense Test # Lines starting with # are comments # Variables are case sensitive # Tab characters will break this file -- and go from there. Steve "Martin Marcher" wrote in message news:mailman.397.1199959984.896.python-list at python.org... > Russ P. wrote: > From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 28 10:43:26 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 28 Jan 2008 16:43:26 +0100 Subject: "just like Java" (was :Re: translating Python to Assembler) In-Reply-To: <7f6f3a93-4301-4a75-83d3-13d9a7c57cda@h11g2000prf.googlegroups.com> References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <4799de28$0$12358$426a74cc@news.free.fr> <7f6f3a93-4301-4a75-83d3-13d9a7c57cda@h11g2000prf.googlegroups.com> Message-ID: <479df81c$0$24179$426a74cc@news.free.fr> Paul Boddie a ?crit : > On 25 Jan, 14:05, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Christian Heimes a ?crit : >> >>> No, that is not correct. Python code is compiled to Python byte code and >>> execute inside a virtual machine just like Java or C#. >> I'm surprised you've not been flamed to death by now - last time I >> happened to write a pretty similar thing, I got a couple nut case >> accusing me of being a liar trying to spread FUD about Java vs Python >> respective VMs inner working, and even some usually sensible regulars >> jumping in to label my saying as "misleading"... > > Well, it is important to make distinctions when people are wondering, > "If Python is 'so slow' and yet everyone tells me that the way it is > executed is 'just like Java', where does the difference in performance > come from?" Your responses seemed to focus more on waving that issue > away and leaving the whole topic in the realm of mystery. The result: > "Python is just like Java apparently, but it's slower and I don't know > why." I'm afraid you didn't read the whole post : """ So while CPython may possibly be too slow for your application (it can indeed be somewhat slow for some tasks), the reasons are elsewhere (hint: how can a compiler safely optimize anything in a language so dynamic that even the class of an object can be changed at runtime ?) .""" I may agree this might not have been stated explicitily enough, but this was about JIT optimizing compilers. Also, a couple posts later - FWIW, to answer the OP "how does it comes it slower if it's similar to Java" question : """ Java's declarative static typing allow agressive just-in-time optimizations - which is not the case in Python due to it's higly dynamic nature. """ From bj_666 at gmx.net Wed Jan 30 04:48:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jan 2008 09:48:23 GMT Subject: Unicode literals to latin-1 References: Message-ID: <60avf7F1ps52dU3@mid.uni-berlin.de> On Wed, 30 Jan 2008 09:57:55 +0100, David.Reksten wrote: > How can I convert a string read from a database containing unicode > literals, such as "Fr\u00f8ya" to the latin-1 equivalent, "Fr?ya"? > > I have tried variations around > "Fr\u00f8ya".decode('latin-1') > but to no avail. In [388]: 'Fr\u00f8ya'.decode('unicode-escape') Out[388]: u'Fr\xf8ya' In [389]: print 'Fr\u00f8ya'.decode('unicode-escape') Fr?ya Ciao, Marc 'BlackJack' Rintsch From lists at cheimes.de Sat Jan 19 10:14:26 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 19 Jan 2008 16:14:26 +0100 Subject: finding memory leak in edgewall trac 0.11 In-Reply-To: References: Message-ID: <479213D2.2020701@cheimes.de> rupert.thurner wrote: > what would be a good means of finding where the 0.11 version of > edgewall trac uses excessive memory. see > http://groups.google.com/group/trac-dev/browse_thread/thread/116e519da54f16b > for some details, where jonas suggested > http://wingolog.org/archives/2007/11/27/reducing-the-footprint-of-python-applications > as reading. > > tiran already gave some hints on http://bugs.python.org/issue1871, but > also suggested to ask the general mailing list: > > Do you have classes with a __del__ method which may create reference > cycles? The GC can't break cycles when a __del__ method is involved. > > Are you keeping references to tracebacks, exception objects (except > Exception, err) or frames (sys._getframe()) I forgot one important point in my reply. The GC module contains some useful methods for debugging. Check gc.garbage. It should be empty. http://docs.python.org/lib/module-gc.html Christian From dblubaugh at belcan.com Tue Jan 22 10:53:03 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 22 Jan 2008 10:53:03 -0500 Subject: Has Anyone Worked with Gene Expression Programming ??????????????????????????? Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38021A5D9F@AWMAIL04.belcan.com> To Anyone, Has anyone worked with Gene Expression Programming??? Specifically, has anyone out there worked with pygep software package??? I have a few questions!!!! David Blubaugh -------------- next part -------------- An HTML attachment was scrubbed... URL: From mark.e.tolonen at mailinator.com Sun Jan 27 12:55:14 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Sun, 27 Jan 2008 09:55:14 -0800 Subject: REALLY simple xml reader References: Message-ID: "Simon Pickles" wrote in message news:mailman.1148.1201455326.896.python-list at python.org... > Hi > > Can anyone suggest a really simple XML reader for python? I just want to > be able to do something like this: > > xmlDoc = xml.open("file.xml") > element = xmlDoc.GetElement("foo/bar") > > ... to read the value of: > > > 42 > > > > Thanks > > Simon > > -- > Linux user #458601 - http://counter.li.org. > > > >>> from xml.etree import ElementTree as ET >>> tree=ET.parse('file.xml') >>> tree.find('bar').text '42' >>> --Mark From george.sakkis at gmail.com Fri Jan 11 23:55:07 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 20:55:07 -0800 (PST) Subject: Import and execfile() References: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> Message-ID: On Jan 11, 5:24 pm, Mike Meyer wrote: > On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis wrote: > > > I maintain a few configuration files in Python syntax (mainly nested > > dicts of ints and strings) and use execfile() to read them back to > > Python. This has been working great; it combines the convenience of > > pickle with the readability of Python. So far each configuration is > > contained in a single standalone file; different configurations are > > completely separate files. > > You know, I've been there before. It's kinda neat, but not something > you really want to put in the hands of most users. Well, I am almost the only user (of the config file, not the application) and the few others are developers too so that's not an issue in this case. > You can make the syntax cleaner by using classes to hold the values > instead of nested dicts, etc. That way you don't have to quote the > names of the values: > > class Foo: > bar = 1 > baz = 2 Actually I am using the dict() constructor instead of literals so it's as clean as with classes; IMO for nested options it's cleaner than nested classes: Env = dict( PORT = 6789, KEY = 123456789, EXE = '/usr/local/lib/myprog', LD_LIBRARY_PATH = ':'.join([ '/usr/lib', '/usr/local/lib', ]), OPTIONS = dict( n = None, min = 1, max = 15000, ) ) > > ====================== > > # some_config.py > > > # master_config.py is in the same directory as some_config.py > > from master_config import * > > > # override non-default options > > foo['bar']['baz] = 1 > > ... > > > ====================== > > # trying to set the configuration: > > CFG = {} > > execfile('path/to/some_config.py', CFG) > > > Traceback (most recent call last): > > ... > > ImportError: No module named master_config > > > I understand why this fails but I'm not sure how to tell execfile() to > > set the path accordingly. Any ideas ? > > Manipulate sys.path yourself? That's what Mitko suggested too, and indeed it works: import sys, os def setConfig(configfile): cfg = {} syspath = list(sys.path) try: sys.path.append(os.path.dirname(configfile)) execfile(configfile, cfg) finally: sys.path = syspath return cfg However this doesn't look very clean to me. Also it's not thread-safe; guarding it explicitly with a lock would make it even less clean. Ideally, I'd like to pass a new path to execfile without modifying the original (even for the few milliseconds that execfile() wlll probably take). With modules being singletons though, I don't think this is possible, or is it ? George From sgeiger at ncee.net Fri Jan 4 02:04:56 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Fri, 04 Jan 2008 01:04:56 -0600 Subject: linecache and glob In-Reply-To: <0e16ca26-9e34-4f97-83de-9ddc3693d085@i12g2000prf.googlegroups.com> References: <0e16ca26-9e34-4f97-83de-9ddc3693d085@i12g2000prf.googlegroups.com> Message-ID: <477DDA98.8070508@ncee.net> import linecache import glob # reading from one file print linecache.getline('notes/python.txt',4) 'http://www.python.org/doc/current/lib/\n' # reading from many files for filename in glob.glob('/etc/*'): print linecache.getline(filename,4) jo3c wrote: > hi everyone happy new year! > im a newbie to python > i have a question > by using linecache and glob > how do i read a specific line from a file in a batch and then insert > it into database? > > because it doesn't work! i can't use glob wildcard with linecache > > >>>> import linecache >>>> linecache.getline(glob.glob('/etc/*', 4) >>>> > > doens't work > > is there any better methods??? thank you very much in advance > > jo3c > -- 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 lloyd at paisite.com Sat Jan 12 14:24:32 2008 From: lloyd at paisite.com (lloyd at paisite.com) Date: Sat, 12 Jan 2008 14:24:32 -0500 (EST) Subject: =?UTF-8?Q?RE:=20Import=20and=20execfile()?= Message-ID: <45883.192.168.1.70.1200165872.webmail@192.168.1.70> Hello, > I maintain a few configuration files in Python syntax (mainly nested > dicts of ints and strings) and use execfile() to read them back to > Python. This has been working great; it combines the convenience of > pickle with the readability of Python. So far each configuration is > contained in a single standalone file; different configurations are > completely separate files. > Now I'd like to factor out the commonalities of the different > configurations in a master config and specify only the necessary > modifications and additions in each concrete config file. I tried the > simplest thing that could possibly work: I've been working with a similar problem; indeed, posted a question about it several weeks ago. I can't speak to the issue of factoring out commonalities, but I've been trying to find a really simple, elegant way to avoid the exec functions. My approaches have been variations in __import__() and loading as file, etc. Everything I've tried seems a bit kludgy. One issue, as I recall, was that __import__() became rather unreliable when you crossed directory boundaries. Question: Why do so many sources discourage the use of exec(), execfile(), etc.? Comment: The Karrigell Python web framework (http://karrigell.sourceforge.net/en/include.htm) has a truly elegant function for loading stuff like some_config.py called Include(). I haven't looked at the source, but it is very handy. I really wish it was basic Python function. All the best, Lloyd -------------- next part -------------- An HTML attachment was scrubbed... URL: From jpeng at block.duxieweb.com Sun Jan 20 23:21:19 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Mon, 21 Jan 2008 12:21:19 +0800 Subject: object scope In-Reply-To: <4794196A.2020901@block.duxieweb.com> References: <4794196A.2020901@block.duxieweb.com> Message-ID: <47941DBF.3070605@block.duxieweb.com> J. Peng ??: > Please see the code below,what's the scope for object "name"? > I thought it should be located in the while block, but it seems not > really,it can be accessed out of while (the db[name] statement).Thanks > in advance. > > sorry the before code seems be disordered,re-posted it. db = {} def newuser(): prompt = 'login desired: ' while 1: name = raw_input(prompt) if db.has_key(name): prompt = 'name taken, try another: ' continue else: break pwd = raw_input('passwd: ') db[name] = pwd From ryszard.szopa at gmail.com Sat Jan 12 17:23:52 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Sat, 12 Jan 2008 14:23:52 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> Message-ID: On Jan 12, 9:47 pm, Mike Meyer wrote: > The same way you call any object's methods if you know it's name": > > getattr(super_object, name)(*args, **kwargs) Thanks a lot for your answer! However, I am very surprised to learn that super_object.__getattr__(name)(*args, **kwargs) getattr(super_object, name)(*args, **kwargs) are not equivalent. This is quite odd, at least when with len() and .__len__, str() and .__str__. Do you maybe know what's the rationale behind not following that convention by getattr? Best regards, -- Richard From thegooddale at gmail.com Wed Jan 23 22:41:17 2008 From: thegooddale at gmail.com (Yansky) Date: Wed, 23 Jan 2008 19:41:17 -0800 (PST) Subject: Problems getting Python scripts to run on server Message-ID: <83ae0f82-e9af-433e-936d-d5b5600a315e@j20g2000hsi.googlegroups.com> Hi, I'm having a lot of problems getting any Python scripts to run on my website. I have put them in the cgi-bin directory and chmodded both the directory and files to 755. But when I try to access the script, I get a 404 error: http://forboden.com/cgi-bin/wp.py I also tried running them from another directory and giving the directory its own .htaccess file containing: Options +ExecCGI AddHandler cgi-script .py but again, they still wouldn't run. The odd thing is, its not that they don't run per se, but that I get a 404 error. When I tried the scripts in the other folder (the non cgi- bin folder), before I added a .htaccess file, I tried the scripts and sure enough it displayed the file source code. But when I added the .htaccess file, I got a 404 file not found error. I emailed my hosting company and they said: "Python is currently installed on the server and is running without any issues. The URL you have provided is not showing any errors on the server. I would advise checking over your scripting to ensure that the issue isn't there." Anyone have any ideas as to what's going wrong? From stefan.behnel-n05pAM at web.de Tue Jan 29 09:46:06 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 29 Jan 2008 15:46:06 +0100 Subject: Executing other python code In-Reply-To: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: <479F3C2E.6030104@web.de> Hi, Tim Rau wrote: > I'm working on a game, and I'd like players to be able to define thier > ships with scripts. Naturally, I don't want to give them the entire > program as thier romping ground. I would like to invoke a seperate > interpreter for these files, and give it a limited subset of the > functions in my game. What is the best way to achieve this effect? Depends. If you are concerned about security, this will be hard to achieve in Python. I imagine that this could be related to cheating prevention. If you are more concerned about namespace polution and making only a well defined API available to the scripts, go the module-import way and hand some API object over, either through an initialisation function or by injecting it into the module namespace, as Arnaud suggested. Stefan From hniksic at xemacs.org Thu Jan 17 01:55:29 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 17 Jan 2008 07:55:29 +0100 Subject: assigning values in python and perl References: Message-ID: <87tzlddjq6.fsf@mulj.homelinux.net> "J. Peng" writes: > $ cat t1.py > def test(x): > x = [4,5,6] > > a=[1,2,3] > test(a) > print a > > $ python t1.py > [1, 2, 3] > > $ cat t1.pl > sub test { > my $ref = shift; > @$ref = (4,5,6); > } @$ref = (4, 5, 6) intentionally assigns to the same list pointed to by the reference. That would be spelled as x[:] = [4, 5, 6] in Python. What Python does in your example is assign the same as Perl's $ref = [4, 5, 6]. So they're not so different after all. From bronger at physik.rwth-aachen.de Mon Jan 28 03:40:35 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 28 Jan 2008 09:40:35 +0100 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> <87lk6a8m8q.fsf@physik.rwth-aachen.de> <13pr24chv832660@corp.supernews.com> Message-ID: <87hcgy8hrw.fsf@physik.rwth-aachen.de> Hall?chen! Steven D'Aprano writes: > On Mon, 28 Jan 2008 08:04:05 +0100, Torsten Bronger wrote: > >>> Are you referring to the alternate syntax or to the decorator? Either >>> way, you could be saving 4 or 5 or more lines, if you have enough >>> arguments. >> >> Mostly, I write them in one or two lines, e.g. >> >> def __init__(self, id, kind, person, feedname): >> self.id, self.kind, self.person = id, kind, person > > It's not the number of lines that is important, but the amount of > redundant code, and the amount of redundant code is identical > whether you write it in one line or three. I doubt that there is redunancy. Don't be misled by the fact that the string "id" appears twice. The expession is minimal in both cases. The only difference is that in one case you have the string "id" twice, and in the other case you have a special syntax or even a new identifier. The information contents is the same. > The problem is that instance initialization frequently and > regularly breaks the principle "Don't Repeat Yourself". [...] I don't see why. It say "I want *this* parameter be turned into an instance variable of the same name". Why is this repeating myself? In my opinon, it would be repeating yourself if in *all* __init__s you want to have *all* parameters turned into instance variables of the same name. However, we all know that sometimes the names should be different, or you want to do some trivial transformation before the assignment. Granted that it's a frequent use case which may justify syntactic sugar, but the straightforward solution is so simple that I think a new syntax would make the language just slightly more complicated without simplifying anything really. > [...] > > Here's a thought... why assume that the convention is a prefix? What > about a suffix? > > @autoassign > def __init__(self, spam_, ham_, eggs): > pass > > [...] Since Python has very few reserved words, and they rarely > make good argument names, there should be far fewer conflicts with > an underscore suffix rather than a prefix. I use them rather frequently, and I see them regularly in the stdlib, so I think this would cause confusion. > I'd still prefer compiler support, preferably with a leading & as > syntax. Please, no! ;-) I like that Python tries to avoid hacker characters in the code in favour of english words. Please bear in mind that it is a frequent use case, so you will have it in virtually every __init__ in fresh Python code. I prefer to see instance variables be defined in an brain-friendly explicit way rather than single characters that hide it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From http Thu Jan 10 21:54:07 2008 From: http (Paul Rubin) Date: 10 Jan 2008 18:54:07 -0800 Subject: getting n items at a time from a generator References: Message-ID: <7x7iihcbsg.fsf@ruckus.brouhaha.com> Tim Roberts writes: > I have to say that I have found this to be a surprisingly common need as > well. Would this be an appropriate construct to add to itertools? I'm in favor. From tjreedy at udel.edu Thu Jan 24 17:13:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jan 2008 17:13:50 -0500 Subject: Reporting Python bugs (was: Can someone explain this unexpectedraw_input behavior?) References: <13ff90c7-60ee-4306-8459-890a2b2b178a@e25g2000prg.googlegroups.com> <8763xi7wme.fsf_-_@benfinney.id.au> Message-ID: "Ben Finney" wrote in message news:8763xi7wme.fsf_-_ at benfinney.id.au... | Mike Kent writes: | | > A bug issue has been opened in the Python Trac system for this. | | Wouldn't it be better to report it in the official Python bug tracker | , which is Roundup, not Trac? Has been by Skip: http://bugs.python.org/issue1927 From mikez302 at gmail.com Fri Jan 11 23:40:48 2008 From: mikez302 at gmail.com (mikez302) Date: Fri, 11 Jan 2008 20:40:48 -0800 (PST) Subject: IDLE won't start in Python 2.5 for Windows References: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> Message-ID: How would I go about cleaning the registry? What specifically should I look for? Should I use any registry cleaner programs? Where are the IDLE preference files stored? When I uninstalled Python, it seems like everything was gone except for a few personal .py and .pyc files. Elias From rschroev_nospam_ml at fastmail.fm Thu Jan 24 14:44:51 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 24 Jan 2008 19:44:51 GMT Subject: Test driven development In-Reply-To: <98f3ca4c-a7f0-4707-b09d-8012b86de96b@x69g2000hsx.googlegroups.com> References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> <53bae618-0a57-470e-b698-3f936ef7c0e7@s12g2000prg.googlegroups.com> <98f3ca4c-a7f0-4707-b09d-8012b86de96b@x69g2000hsx.googlegroups.com> Message-ID: Virgil Dupras schreef: > On Jan 24, 1:30 pm, Roel Schroeven > wrote: >> Virgil Dupras schreef: >> >>> I know what you mean by top-down vs. bottom-up and I used to have the >>> same dilemma, but now I would tend to agree with Albert. Your issue >>> with top-down or bottom-up is not relevant in TDD. The only thing that >>> is relevant is to reach your current milestone as soon as possible, >>> without caring about what you're going to do in the milestone after >>> that. >>> Not so long ago, I took the "bottom-up" approach to TDD, which was a >>> mistake because it leads to over-engineering (the end result is not so >>> bad since it's over-engineering that has good test coverage :) ) >> I don't regularly use TDD yet, and one of the reasons is that in many >> cases I'm unsure exactly how to use it in practice. I read "Test-driven >> development - A practical guide" (and I should re-read), but I feel it >> doesn't help my much in everyday situations. Somehow the examples in the >> book don't match very well with how I code (and I admit that perhaps the >> problem is more with me than with the book). >> >> One of the problems I have is something like what Andy describes: I need >> a function spam(), so I write tests for it. Then I start implementing >> the function and see that I need to write functions ham() and eggs(). >> Should I write unit tests for ham() and eggs(), or do I rely on the >> tests for spam()? If I don't write them, doesn't that make it more >> difficult to find out why the tests for spam() fail? >> >> Speaking about over-engineering, when I do TDD along the lines of the >> book I mentioned, I always feel that I'm over-engineering the tests. It >> all feels very unnatural though I'm convinced it shouldn't be like that. >> >> Can someone suggest other books to read about the subject, ideally >> something more focused on Python or C++ rather than Java? >> >> -- >> The saddest aspect of life right now is that science gathers knowledge >> faster than society gathers wisdom. >> -- Isaac Asimov >> >> Roel Schroeven > > I also have a book about TDD and it never was of much help either. All > techniques come from the initial workflow: Red - Green - Refactor. > > The problem you describe is a tricky problem. The way I feel it should > be solved is: > > - Write spam() (and its tests, of course). > - Then, at some point, in the re-factor phase, you split extract the > function ham() from spam(). Alright, do it and keep the tests as is > (all on spam()). > - Then at some other point, you extract eggs(). same thing. > - After a while (I don't know, 3 or 4 milestones), when it becomes > clear that ham() and eggs() are there to stay, start moving your tests > away from spam() by just mocking ham() and eggs() and just make sure > that spam() call them with the right arguments. The tests you had on > spam() that were relevant to ham() and eggs() are just performed > directly on them now. > > What I've been saying in my other message is: Don't do that too early, > because if it turns out that ham() and eggs() is not the optimal way > to do it, but foo() bar() and baz() is, it is *much* easier to do a > safe re-factoring with high level tests. That sounds reasonable. I'm getting the impression that reading that book led me to a too strict approach. I guess I just need to try somewhat harder to use TDD in my daily coding. Apart from books, are there other resources that can help beginners with TDD? Mailing lists, forums, newsgroups possibly? -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From lizm at rcsltd.co.uk Thu Jan 24 09:03:20 2008 From: lizm at rcsltd.co.uk (LizzyLiz) Date: Thu, 24 Jan 2008 06:03:20 -0800 (PST) Subject: csv to xls using python 2.1.3 References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> <4797763D.70604@websafe.com> Message-ID: On Jan 23, 5:15 pm, Larry Bates wrote: > FYI - Excel can read .CSV files directly and convert them to .XLS. > > -Larry Thanks Larry The customer wants 2 buttons - one for csv, one for xls. Kind regards Liz From cokofreedom at gmail.com Wed Jan 16 07:58:58 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 16 Jan 2008 04:58:58 -0800 (PST) Subject: no pass-values calling? References: <18c1e5f20801151909u4cdd227ah685741ea21734491@mail.gmail.com> Message-ID: On Jan 16, 1:21 pm, "Neil Cerutti" wrote: > On Jan 15, 2008 10:09 PM, J. Peng wrote: > > > Hello, > > > I saw this statement in Core Python Programming book, > > > All arguments of function calls are made by reference, meaning that > > any changes to these parameters within the function > > affect the original objects in the calling function. > > Yes, that's generally correct. But you must be careful about what is > meant by "changes to parameters". Assigning a new value to a parameter > name (inside the function, a parameter is just a local variable) does > not change the original object--it only rebinds the local variable to > a new object. > > In the following function, a is rebound with an assignment statement, > while b is mutated, i.e., changed, with an assignment statement. > > def f(a, b): > a = 12 > b.value = 14 > > Argument a will never be changed, while argument b will be. Python's > argument passing semantics are extremely simple. It's the assignment > statement that's tricky: some assignments mutate/change objects, and > some only rebind names. > > > Does this mean there is not pass-values calling to a function in > > python? only pass-reference calling? Thanks! > > Neither is quite true. Values are passed by binding parameter names to > their corresponding arguments. This is similar to pass-by-reference in > some cases (when the argument is mutated) but not in others (when the > argument is not mutated). Thinking of it as pass-by-reference may help > you to understand it, but bear in mind that Python's "references" may > be rebound to new objects, which is quite different from the usual > behavior of references. > > -- > Neil Cerutti So basically the scope is the reason for confusion a lot of the time? def some_name(): alist = [5] bint = 5 cstring = '5' ddictionary = {0:5} def other_name(alist, bint, cstring, ddictionary): alist = 4 bint = 4 cstring = '4' ddictionary = 4 print "other_name:", print alist, bint, cstring, ddictionary def another_name(alist, bint, cstring, ddictionary): alist[0] = 3 # bint cannot be changed it is immutable # cstring cannot be changed it is immutable ddictionary[0] = 3 print "another_name:", print alist, bint, cstring, ddictionary another_name(alist, bint, cstring, ddictionary) other_name(alist, bint, cstring, ddictionary) print "our entries are now:", print alist, bint, cstring, ddictionary From jokersmith at comcast.net Wed Jan 9 22:18:57 2008 From: jokersmith at comcast.net (Josh) Date: Wed, 9 Jan 2008 22:18:57 -0500 Subject: help with a problem from school?? Message-ID: Hello all I did a Google search and found this site and was hoping someone could help me with what I am sure is a simple question that I cannot figure out. Here goes: Given a simple straight through switch (SPST) with a supply of 14V, and the need to simulate its intended load of 14mA, what would you use to simulate this load? Please show your calculations used to support your answer. I appreciate anyone's help. Josh Smith jokersmith at comcast.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From bkamrani at gmail.com Tue Jan 15 20:21:02 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Tue, 15 Jan 2008 17:21:02 -0800 (PST) Subject: login to https (newbie) Message-ID: Hi Python gurus! Please help me how I can login to this page: https://www.boplats.se/user/login_hs.aspx?ReturnUrl=/HSS/Default.aspx I tried these two codes, but I don't seem to be successfull at all. (Both gave same result.) Many many thanks, /Ben ----------- import urllib2,urllib,cookielib urll = "https://www.boplats.se/user/login_hs.aspx?ReturnUrl=/HSS/ Default.aspx" cj = cookielib.CookieJar() opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj)) data = urllib.urlencode ( { "username" : "myuser" , "password" :"mypass" } ) fp = opener.open( urll,data ) print fp.read() ------------ OR th second code ------------ import urllib2 as __urllib2 import base64 as __base64 #-------------------------------------------------------------- def download_file(url, webuser = None, webpass = None): request = __urllib2.Request(url) if webuser: base64string = __base64.encodestring('%s:%s' % (webuser, webpass))[:-1] request.add_header("Authorization", "Basic %s" % base64string) htmlFile = __urllib2.urlopen(request) htmlData = htmlFile.read() htmlFile.close() return htmlData #-------------------------------------------------------------- if __name__ == "__main__": # Test #***************************** __url = "https://www.boplats.se/user/login_hs.aspx?ReturnUrl=/HSS/ Default.aspx" __webuser = "myuser" __webpass = "mypass" print download_file(__url, __webuser, __webpass) #***************************** From t_spens at yahoo.com Thu Jan 24 12:28:09 2008 From: t_spens at yahoo.com (Tim Spens) Date: Thu, 24 Jan 2008 09:28:09 -0800 (PST) Subject: Beginner Pyserial Question Message-ID: <862889.8569.qm@web45111.mail.sp1.yahoo.com> COM = 0 #for COM1 BAUD = 115200 class serial_port(): def __init__(self): self.start_time = None self.end_time = None self.asleep_duration = None self.device = serial.Serial() self.device.timeout = 1 self.device.baudrate = BAUD self.device.port = COM a_serial_port = serial_port() a_serial_port.device.open() ----- Original Message ---- From: "JAMoore84 at gmail.com" To: python-list at python.org Sent: Thursday, January 24, 2008 10:13:39 AM Subject: Re: Beginner Pyserial Question > My guess is that for whatever reason the 'first' serial port > (which is what you're asking for by specifying a 0 when > instantiating the Serial class) doesn't actually exist. Serial > device names under Windows are broken. I realize this. I tried connecting to different port "numbers", but I have not tried the serial.Serial(COM1). I wasn't sure if that worked, but I know a quick way to find out. > Try using the actual name of the com port (e.g. 'COM3' or > 'COM5') instead of 0. The com port used in Hyper Terminal is COM40. I have tried connecting to 39/40/41 to no avail. > Oh, if you end up having to use a com port higher than COM9, > that's broken in Windows as well, and you've got to sprinkle a > bunch of backslashes into the device name (I don't remember the > exact syntax). That might become an issue when I try to read COM40 for the GPS bluetooth transmission. This issue does not relate to why I cannot open smaller com ports, though. -- http://mail.python.org/mailman/listinfo/python-list ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From halcyon1981 at gmail.com Fri Jan 25 00:21:59 2008 From: halcyon1981 at gmail.com (David Erickson) Date: Thu, 24 Jan 2008 21:21:59 -0800 (PST) Subject: Email module, how to add header to the top of an email? References: <97c04812-3b66-4d84-9e92-21de72a3ca56@c23g2000hsa.googlegroups.com> Message-ID: <088eeaff-8251-49a4-9202-a9481f5e8aaa@x69g2000hsx.googlegroups.com> On Jan 24, 2:41 pm, Martin Marcher wrote: > On Thursday 24 January 2008 20:32 David Erickson wrote: > > > I have been using the Email module and Message class for awhile, > > however I have been unable to find a way to add a header to the top of > > the email similar to what is done with Received: headers... the > > add_header method only appends to the bottom. Is there someway this > > can be done? > > if by bottom you mean added as the "new last" header than you don't have to > care, afaik email headers do not have a notion of order > > e.g > > To: b... at example.com > From: al... at example.com > > is equal to > > From: al... at example.com > To: b... at example.com > > if by bottom you mean it's appended to the body...well that is a problem :) > > hth > martin Bottom of the headers... but I am looking to insert at the top, and re- ordering/inserting does matter depending on what type of header you are, received headers for example must be inserted at the top of the header list so you can watch the progression of the email. I was unable to find a clean way to do this via the API which seems very strange to me.. but perhaps I am just missing something? Thanks, -David From paddy3118 at googlemail.com Sat Jan 5 01:50:31 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 4 Jan 2008 22:50:31 -0800 (PST) Subject: Skill Resume Achievements, What Good Goes Here? References: Message-ID: On Jan 2, 3:59 pm, vbgunz wrote: > I spent some time working on a skill resume, the kind of resume > college students put together and realized, I am not in college and > everything I learned was self-taught. Of course I would like some real > world achievements but don't consider throw-away code an achievement > and am failing to really see any. I don't even wish to entertain the > thought of lying about anything. > > What are some achievements an employer may be looking for in someone > willing to start at ground level, entry level, intern, etc? What are > some real world achievements every n00b will need under his/her belt > in order to be taken seriously? You need to have written code that you expect others to either read or use. Others have pointed out the benefits of contributing to an open source project but code to be read might include code posted to newsgroups in answer to questions, or your blog entries. If you have no code fit to be read then what is a potential employer to do? (Personally, a college student showing an appreciation of doctests would impress). - Paddy. From paddy3118 at googlemail.com Wed Jan 9 01:52:22 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 8 Jan 2008 22:52:22 -0800 (PST) Subject: Collecting Rich Data Structures for students References: Message-ID: On Jan 9, 2:19 am, "kirby.ur... at gmail.com" wrote: > Greetings Pythoneers -- > > Some of us over on edu-sig, one of the community actives, > have been brainstorming around this Rich Data Structures > idea, by which we mean Python data structures already > populated with non-trivial data about various topics such > as: periodic table (proton, neutron counts); Monty Python > skit titles; some set of cities (lat, long coordinates); types > of sushi. > > Obviously some of these require levels of nesting, say > lists within dictionaries, more depth of required. > > Our motivation in collecting these repositories is to give > students of Python more immediate access to meaningful > data, not just meaningful programs. Sometimes all it takes > to win converts, to computers in general, is to demonstrate > their capacity to handle gobs of data adroitly. Too often, > a textbook will only provide trivial examples, which in the > print medium is all that makes sense. > > Some have offered XML repositories, which I can well > understand, but in this case we're looking specifically for > legal Python modules (py files), although they don't have > to be Latin-1 (e.g. the sushi types file might not have a > lot of romanji). > > If you have any examples you'd like to email me about, > kirby.ur... at gmail.com is a good address. > > Here's my little contribution to the mix:http://www.4dsolutions.net/ocn/python/gis.py > > Kirby Urner > 4D Solutions > Silicon Forest > Oregon I would think there was more data out there formatted as Lisp S- expressions than Python data-structures. Wouldn't it be better to concentrate on 'wrapping' XML and CSV data- sources? - Paddy. From asmodai at in-nomine.org Thu Jan 3 08:55:24 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 3 Jan 2008 14:55:24 +0100 Subject: Treating a unicode string as latin-1 In-Reply-To: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> References: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Message-ID: <20080103135524.GM67953@nexus.in-nomine.org> -On [20080103 14:36], Simon Willison (simon at simonwillison.net) wrote: >How can I tell Python "I know this says it's a unicode string, but I >need you to treat it like a bytestring"? Although it does not address the exact question it does raise the issue how you are using ElementTree. When I use the following: test.xml Bob\x92s Breakfast parse.py from xml.etree.ElementTree import ElementTree xmlfile = open('test.xml') tree = ElementTree() tree.parse(xmlfile) elem = tree.find('name') print type(elem.text) I get a string type back and not a unicode string. However, if you are mixing encodings within the same file, e.g. cp1252 in an UTF8 encoded file, then you are creating a ton of problems. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ When moved to complain about others, remember that karma is endless and it is loving that leads to love... From JAMoore84 at gmail.com Thu Jan 24 12:45:25 2008 From: JAMoore84 at gmail.com (JAMoore84 at gmail.com) Date: Thu, 24 Jan 2008 09:45:25 -0800 (PST) Subject: Beginner Pyserial Question References: <93223c7c-c891-424c-bc4f-00d61592663a@l32g2000hse.googlegroups.com> <13phgpma9fb3cb8@corp.supernews.com> <50bf1637-0954-4d35-9c16-76c3b9aabe05@y5g2000hsf.googlegroups.com> Message-ID: I've solved the problem- Thanks for steering me in the right direction. The problem is that your traditional "COM1" does not exist on this computer (Thanks Grant). A trip to the Device manager listed all the COM ports on the computer. After successfully connecting to COM7 (port = serial.Serial(6)), I realized the reason I couldn't connect to COM40 was because it was tied up with hyper terminal. after closing everything, I was able to issue a readline and collect data. Thanks for the help! jimmy From gowricp at gmail.com Fri Jan 11 20:54:03 2008 From: gowricp at gmail.com (Gowri) Date: Fri, 11 Jan 2008 17:54:03 -0800 (PST) Subject: converting JSON to string References: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> <13og5g06rvrtefa@corp.supernews.com> Message-ID: Hi Adonis, Thanks so much. Appreciate it :) From david.hotham at blueyonder.co.uk Mon Jan 28 16:31:05 2008 From: david.hotham at blueyonder.co.uk (david.hotham at blueyonder.co.uk) Date: Mon, 28 Jan 2008 13:31:05 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Message-ID: <92b67efe-c437-40bc-89fc-bbdd85d6e718@s19g2000prg.googlegroups.com> I also had a go at this problem for a bit of python practice, about 6 months ago. I tried a few optimizations and my experience was that with only 6 seeds, a hash table was very effective. So effective, in fact, that it made all other optimizations more or less pointless. Code below. Arguments are seeds first, then targets. Like this: C:\utils>countdown.py 7 8 50 8 1 3 923 made target! 50 * 8 = 400 400 - 1 = 399 399 / 3 = 133 133 * 7 = 931 931 - 8 = 923 Took 0.421 seconds from time import time from bisect import insort from sys import argv #------------------------------------------------------------------------------ # Hash table is a global variable #------------------------------------------------------------------------------ global hash_table #------------------------------------------------------------------------------ # countdown.py # # Python script to solve the Countdown numbers game # # Remarks on optimization: # # - Without the hash table, the following all proved beneficial: # - Keep a list of numbers used so far, and never create a number that # you've already used # - Make sure only to return unique pairs from the generate_pairs function # - Don't ever perform two consecutive substractions # - (Don't ever perform two consecutive divisions would also be valid, # though it's not something that happens a lot so the benefit is small) # # - These tricks work by avoiding performing the same search more than once # # - With only six seeds, it's possible to implement a perfect hash table that # remembers every list that we try to solve (and indeed this is what the # implementation here does) # # - With that hash table, the optimizations above become largely redundant, so # for the sake of simplicity I've removed them # # - Solving for larger numbers of seeds would require a smarter approach, as # it would soon become infeasible to maintain a complete hash table. Then # the tricks above might be useful again. # #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # Returns all useful combinations of two numbers, and a string representing # the operation used to get there. #------------------------------------------------------------------------------ def generate_combinations(higher_number, lower_number): #-------------------------------------------------------------------------- # Useful operations are: # - addition (always) # - subtraction (of the lower number from the higher number, so long as # they are not equal) # - multiplication (so long as not multiplying by one) # - division (if it's exact, and not by one) #-------------------------------------------------------------------------- yield "+", higher_number + lower_number if (higher_number != lower_number): yield "-", higher_number - lower_number if (lower_number != 1): yield "*", higher_number * lower_number if ((higher_number % lower_number) == 0): yield "/", higher_number / lower_number #------------------------------------------------------------------------------ # Returns all pairs from a list of seeds. # # Pairs always have the first number lower than or equal to the second number, # provided that the list is ordered on entry (as it should be). #------------------------------------------------------------------------------ def generate_pairs(seeds): for ii in xrange(len(seeds)): for higher_num in seeds[ii+1:]: yield seeds[ii], higher_num #------------------------------------------------------------------------------ # Solves a seed list. Takes pairs, combines them, and recursively calls # solve_list again with the new shorter list. # # Seeds should be sorted on entry. #------------------------------------------------------------------------------ def solve_list(seeds, target, depth, solution_so_far): #-------------------------------------------------------------------------- # Loop through possible pairs. #-------------------------------------------------------------------------- for lower_num, higher_num in generate_pairs(seeds): #---------------------------------------------------------------------- # Make a copy of the list, and remove this pair. # # Taking a copy appears to be quicker than using the original list and # then reinstating the chosen pair later. #---------------------------------------------------------------------- new_seeds = seeds[:] new_seeds.remove(lower_num) new_seeds.remove(higher_num) #---------------------------------------------------------------------- # Try out all possible combinations of our pair. #---------------------------------------------------------------------- for operation, combination in generate_combinations(higher_num, lower_num): #------------------------------------------------------------------ # If we hit our target, we're happy. # # Else if the list has gotten too short already, move on. # # Else make a new, shorter, list containing our new value. # # If we've already tried to solve the new list, there's no point in # trying again. # # Else try to solve the shorter list. #------------------------------------------------------------------ if combination == target: print "made target!" print "%s%d %s %d = %d\n" % (solution_so_far, higher_num, operation, lower_num, combination) return(0) elif (depth > 0): insort(new_seeds, combination) seeds_tuple = tuple(new_seeds) if (seeds_tuple in hash_table): pass else: hash_table[seeds_tuple] = 1 new_soln_so_far = ("%s%d %s %d = %d\n" % (solution_so_far, higher_num, operation, lower_num, combination)) if (solve_list(new_seeds, target, depth - 1, new_soln_so_far) == 0): #------------------------------------------------------ # Success! #------------------------------------------------------ return(0) #-------------------------------------------------------------- # Remove the value that we made out of our number pair, in # preparation for the next try. #-------------------------------------------------------------- new_seeds.remove(combination) #-------------------------------------------------------------------------- # Didn't solve it. #-------------------------------------------------------------------------- return(1) #------------------------------------------------------------------------------ # OK, let's go. Get the puzzle, and solve it. The last argument is the target # and the others are the seeds. #------------------------------------------------------------------------------ original_seeds = map(int, argv[1:-1]) target = int(argv[-1]) start_time = time() failed = 1; if target in original_seeds: print "Target is amongst seeds!" else: original_seeds.sort() #-------------------------------------------------------------------------- # First look for one-step solutions, then for two-step solutions, etc. # That way we always get a shortest solution first. #-------------------------------------------------------------------------- for depth in xrange(len(original_seeds)): hash_table = {} failed = solve_list(original_seeds, target, depth, "") if (failed == 0): break if (failed != 0): print "No solution!" print "Took %.3f seconds" % (time() - start_time) From David.Reksten at sweco.no Thu Jan 10 06:43:09 2008 From: David.Reksten at sweco.no (David.Reksten at sweco.no) Date: Thu, 10 Jan 2008 12:43:09 +0100 Subject: SV: Conventions for dummy name In-Reply-To: <87sl1613c8.fsf@physik.rwth-aachen.de> References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de><873at6k2qt.fsf_-_@benfinney.id.au> <87sl1613c8.fsf@physik.rwth-aachen.de> Message-ID: <6A539E6F80E48B40A81F5169256139D301D98242@srvmail02.nettverk.int> Torsten Bronger wrote: >Hall?chen! > >Ben Finney writes: > >> "Diez B. Roggisch" writes: >> >>> The underscore is used as "discarded" identifier. So maybe >>> >>> for _ in xrange(10): >>> ... >> >> The problem with the '_' name is that it is already well-known and >> long-used existing convention for an entirely unrelated purpose: >> in the 'gettext' i18n library, the '_' function to get the >> locally-translated version of a text string. > >Right, that's because I've used "__" where not all returning values >are interesing to me such as > >a, b, __ = function_that_returns_three_values(x, y) Variable name "dummy" serves the same purpose, such as: a, b, dummy = function_that_returns_three_values(x, y) According to http://linux.die.net/man/1/pylint it is also possible to use the option --dummy-variables-rgx= to further specify which variable not to report as unused. As far as I can tell, it defaults to '_|dummy'. .david From arnodel at googlemail.com Wed Jan 23 18:51:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 15:51:10 -0800 (PST) Subject: Creating new types and invoking super References: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> Message-ID: <9eeb9667-f362-4ce2-971a-42ef639c8f86@c4g2000hsg.googlegroups.com> On Jan 23, 10:18?pm, "Guilherme Polo" wrote: > 2008/1/23, Arnaud Delobelle : > > > The only way I can think of would be to create a metaclass, but I > > don't think it's worth it. ?super(A, obj).__init__() isn't that bad! > > Metaclass doesn't apply here because metaclass is related to > class-construction. This is related to instance initialization, and > I'm creating the types as the user asks. Not completely clear to me what you want but here is a 'proof of concept': ========== class callsuper(object): def __init__(self, f): self.f = f def __get__(self, obj, cls=None): def newfunc(*args, **kwargs): super(self.cls, obj).__init__() return self.f(obj, *args, **kwargs) return newfunc class Type(type): def __init__(self, name, bases, attrs): for attrname, attr in attrs.iteritems(): if isinstance(attr, callsuper): attr.cls = self class A: __metaclass__ = Type def __init__(self): print "init A" class B(A): @callsuper def __init__(self): print "init B" ========== >>> b=B() init A init B From arnodel at googlemail.com Wed Jan 9 15:52:24 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 9 Jan 2008 12:52:24 -0800 (PST) Subject: Another dumb scope question for a closure. References: Message-ID: On Jan 9, 8:24?pm, Mike Meyer wrote: > On Wed, 9 Jan 2008 13:47:30 -0500 (EST) "Steven W. Orr" wrote: > > > > > So sorry because I know I'm doing something wrong. > > > 574 > cat c2.py > > #! /usr/local/bin/python2.4 > > > def inc(jj): > > ? ? ?def dummy(): > > ? ? ? ? ?jj = jj + 1 > > ? ? ? ? ?return jj > > ? ? ?return dummy > > > h = inc(33) > > print 'h() = ', h() > > 575 > c2.py > > h() = > > Traceback (most recent call last): > > ? ?File "./c2.py", line 10, in ? > > ? ? ?print 'h() = ', h() > > ? ?File "./c2.py", line 5, in dummy > > ? ? ?jj = jj + 1 > > UnboundLocalError: local variable 'jj' referenced before assignment > > > I could have sworn I was allowed to do this. How do I fix it? > > Nope. This is one of the things that makes lisper's complain that > Python doesn't have "real closures": you can't rebind names outside > your own scope (except via global, which won't work here). Note that the 'nonlocal' keyword solves this problem in py3k: 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. >>> def inc(j): ... def f(): ... nonlocal j ... j += 1 ... return j ... return f ... >>> i = inc(3) >>> i() 4 >>> i() 5 >>> -- Arnaud From jzgoda at o2.usun.pl Wed Jan 23 04:12:07 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 23 Jan 2008 10:12:07 +0100 Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? In-Reply-To: References: Message-ID: Gary Herron napisa?(a): > However there *is* a (subtle) difference between > not f > and > (not f and 1) or 0 > > The first produces a boolean value, and the second produces an int > value, but since one is a subclass of the other, you'd have to write > quite perverse code care about the difference. Twisted sems to be perverted to the root. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From agnel.joel at gmail.com Sun Jan 6 01:01:19 2008 From: agnel.joel at gmail.com (Joel) Date: Sat, 5 Jan 2008 22:01:19 -0800 (PST) Subject: Boa constructor debugging - exec some code at breakpoint? Message-ID: <7f96223d-e5bd-4bbc-a242-75826eeb100a@d70g2000hsb.googlegroups.com> Hey there.. I'm using boa constructor to debug a python application. For my application, I need to insert break points and execute some piece of code interactively through shell or someother window when the breakpoint has been reached. Unfortunately the shell I think is a seperate process so whatever variables are set while executing in debugger dont appear in the shell when I try to print using print statement. Can anyone tell me how can I do this? Really appreciate any support, Thanks Joel P.S. Please CC a copy of reply to my email ID if possible. From gagsl-py2 at yahoo.com.ar Tue Jan 22 19:49:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 Jan 2008 22:49:30 -0200 Subject: Submitting with PAMIE References: <04c92035-4b27-467d-87b7-86665e09072f@e10g2000prf.googlegroups.com> Message-ID: En Tue, 22 Jan 2008 15:39:33 -0200, escribi?: > Hi I really need help. I've been looking around for an answer forever. > I need to submit a form with no name and also the submit button has no > name or value. How might I go about doing either of these. Thanks I think you'll have more luck in a specific forum like the PAMIE User Group at http://tech.groups.yahoo.com/group/Pamie_UsersGroup/ -- Gabriel Genellina From israelu at elbit.co.il Tue Jan 15 04:43:22 2008 From: israelu at elbit.co.il (iu2) Date: Tue, 15 Jan 2008 01:43:22 -0800 (PST) Subject: print >> to a derived file Message-ID: Hi, I'm trying to write data to both a file and the console, so I did: class File_and_console(file): def write(self, s): file.write(self, s) print s, >>> f = File_and_console('1.txt', 'w') >>> f.write('hello') hello >>> print >>f, 'world' >>> the 'write' method works, but 'print >>' doesn't, it writes only to the file. It doesn't actually call File_and_console.write Why? How can I fix it? Thanks iu2 From asmodai at in-nomine.org Wed Jan 2 07:42:18 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 2 Jan 2008 13:42:18 +0100 Subject: Extracting files from an ISO image? In-Reply-To: <34a84caa-5387-40a2-a808-5e7bd325023e@w47g2000hsa.googlegroups.com> References: <34a84caa-5387-40a2-a808-5e7bd325023e@w47g2000hsa.googlegroups.com> Message-ID: <20080102124218.GC67953@nexus.in-nomine.org> -On [20080102 13:11], Ant (antroy at gmail.com) wrote: >2) Is there a module out there for extracting icons from a Windows >exe? This might be a good start: http://groups.google.com/group/comp.lang.python/browse_thread/thread/be829b454c945a89 -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ When you meet a master in the street, do not speak, do not be silent. Then how will you greet him? From arnodel at googlemail.com Thu Jan 17 22:15:55 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 17 Jan 2008 19:15:55 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> <657961e1-44ce-4fef-b3b7-5662878f28d8@f47g2000hsd.googlegroups.com> Message-ID: <5c1818a6-b96b-4dce-a2f4-1f9dfeda4c01@l32g2000hse.googlegroups.com> On Jan 17, 11:59?pm, Paul Hankin wrote: > Instead of counting the exceptions, we can limit the padding iterables > by using an iterator that returns len(iterables) - 1 padding > generators, use a sort of lazy chain, and then just izip. > > from itertools import izip, repeat > > def chain_next(xs, yg): > ? ? for x in xs: yield x > ? ? for y in yg.next(): yield y > > def izippad(*xs, **kw): > ? ? padder = repeat(kw.get('padding', None)) > ? ? padder_gen = repeat(padder, len(xs) - 1) > ? ? return izip(*[chain_next(x, padder_gen) for x in xs]) I have had the need for such a 'padded zip' before and my implementation was eerily similar: from itertools import repeat, chain, izip def repeatnext(iterator): val = iterator.next() while True: yield val def longzip(default, *iterables): defaultgen = repeat(default, len(iterables) - 1) return izip(*[chain(it, repeatnext(defaultgen)) for it in iterables]) -- Arnaud From sromero at gmail.com Mon Jan 21 02:41:13 2008 From: sromero at gmail.com (Santiago Romero) Date: Sun, 20 Jan 2008 23:41:13 -0800 (PST) Subject: Sorting a list depending of the indexes of another sorted list Message-ID: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> Hi ... I have the following DNS MX records info: domain.com preference 10 host mx1.domain.com preference 30 host anotherhost.domain.com preference 20 host mx2.domain.com I'm storing this info in 2 lists: preferences = [10, 30, 20] hosts = [ "mx1.domain.com", "anotherhost.domain.com", "mx2.domain.com"] (I was about to use a dict of preferences : domain, but it's possible to find 2 mx records with the same preference, so keys wouldnt be unique). I'm trying to sort both lists so that they end like this: preferences = [10, 20, 30] hosts = [ "mx1.domain.com", "mx2.domain.com", "anotherhost.domain.com" ] I want to sort hosts list depending on the numeric order of "preferences". And finally ... do you think there is a better python structure to store this data and sort it in a more easy way? Thanks. From donn.ingle at gmail.com Sun Jan 13 07:27:54 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 14:27:54 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <4789FE1C.9000002@v.loewis.de> References: <200801131351.59005.donn.ingle@gmail.com> <4789FE1C.9000002@v.loewis.de> Message-ID: <200801131427.54672.donn.ingle@gmail.com> > So on *your* system, today: what encoding are the filenames encoded in? > We are not talking about arbitrary files, right, but about font files? > What *actual* file names do these font files have? > > On my system, all font files have ASCII-only file names, even if they > are for non-ASCII characters. I guess I'm confused by that. I can ls them, so they appear and thus have characters displayed. I can open and cat them and thus the O/S can access them, but I don't know whether their characters are strictly in ascii-limits or drawn from a larger set like unicode. I mean, I have seen Japanese characters in filenames on my system, and that can't be ascii. You see, I have a large collection of fonts going back over 10 years and they came from usenet years ago and so have filenames mangled all to hell. I can't always *type* some of their names and have to use copy/paste to, for example, ls one of them. Again, it's working from ignorance (my own) : I assume filenames in different countries will be in character sets that I have never (nor will I ever) see. But I have to cover them somehow. > > Or is that a waste of time because os.listdir() has already tried > > something similar (and prob. better)? > "better" is a difficult notion here. Is it better to produce some > result, possibly incorrect, or is it better to give up? I think I see, combined with your previous advice - I will keep byte strings alongside unicode and where I can't get to the unicode for that string, I will keep an 'ignore' or 'replace' unicode, but I will still have the byte string and will access the file with that anyway. > If the user has set up his machine correctly: yes. Meaning, I am led to assume, the LANG variable primarily? \d From dg.google.groups at thesamovar.net Sun Jan 27 14:10:01 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Sun, 27 Jan 2008 11:10:01 -0800 (PST) Subject: explicit protocols and duck typing Message-ID: <5e28034f-a20f-4aa7-b299-9c9132ef2566@c4g2000hsg.googlegroups.com> Hi all, As I understand it, the idea behind duck typing is that you just take an object and if it has the methods you want to use you use it assuming it to be the right type of object. I'm interested in extending this idea a bit, but I feel the sort of thing I have in mind has already been thought of. So for example, in the program I'm writing a 'state variable' specifier can be either an integer or a string (the string name is mapped to an integer by another function getvarindex(name)). In this case, I can't do duck typing by seeing if the object has a method or not, because both of the types are built in types. I don't want to have to force the user to have objects like StateVariableSpecifier(name). Now at the moment, what I'm doing is accepting anything as a state variable specifier, and just passing it through the getvarindex function when I want to use it. This sort of specifies a protocol for state variable specifiers without making it explicit (like the sequence or mapping protocols built in to Python). What I'm wondering though is whether there is any value in making this more explicit? Say, have a class which makes explicit the various relationships involved, such as that the type of a state variable specifier can be correct or incorrect (it has to be an int or a string), that the value has to be correct (the integer has to be between 0 and n for some n, and the string has to be in a dict of names), and that there is a relationship between state variable specifiers (int, string) and the underlying data type (the index of the variable in an array). Making it more explicit seems like a good idea, the question is in what way to make it more explicit. I can make it explicit just by documenting the behaviour, or I can make it explicit by adding code that enforces certain ways of using things. For this simple example, it seems like just documenting it is the best route, but I have similar issues with other more complicated parts of the code. At the moment, a model for instance can be a Model object, an Equation object or a tuple of functions, but this could be subject to change in the future. The issue I want to address is the long term maintainability of the code when possibly many people might be contributing, the transparency for other users, and the ease of documenting it. Any opinions? Dan Goodman From steven at REMOVE.THIS.cybersource.com.au Wed Jan 9 21:10:56 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 10 Jan 2008 02:10:56 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: On Wed, 09 Jan 2008 21:26:05 +0100, Bruno Desthuilliers wrote: > hint: how can a compiler safely optimize anything in a language so > dynamic that even the class of an object can be changed at runtime ? Is that a trick question? By finding things to optimize that *can't* change at runtime. E.g. a keyhole optimizer that detects when you write something like this: def foo(): x = 1 + 2 return x and optimizes it to this: >>> import dis >>> dis.dis(foo) 2 0 LOAD_CONST 3 (3) 3 STORE_FAST 0 (x) 3 6 LOAD_FAST 0 (x) 9 RETURN_VALUE (Only in CPython version 2.5 or better.) Okay, okay, so constant folding isn't going to save you a lot of time (unless your constant is being re-calculated millions of times) but it's still an optimization. There are others, some have been done (e.g. optimize away the quadratic behaviour for string concatenation in some limited cases), some are possible but rejected by the BDFL (e.g. tail- call optimization), presumably there are some possible but not yet implemented or even discovered (which is the point of the PyPy project). You are correct that optimizing Python is hard. However, in many cases, the problem is not that Python is too slow, but the specific algorithm chosen by the programmer is slow, e.g. no compiler optimization is going to turn an O(n**2) algorithm into an O(1) algorithm. The Original Poster says it takes one or two seconds to process an 800x600 GIF. That sounds believable: on my PC, it takes about five seconds to loop over range(800*600) and do a tiny bit of processing. Something like Psycho might speed that up a lot, possibly by an order of magnitude or two. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Jan 17 21:59:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 18 Jan 2008 02:59:16 -0000 Subject: "Code Friendly" Blog? References: <0fd979c6-5a11-4989-9438-51a7b20ecd23@n20g2000hsh.googlegroups.com> Message-ID: <13p05g42jckem5d@corp.supernews.com> On Thu, 17 Jan 2008 16:18:37 -0800, Hai Vu wrote: > On Jan 17, 2:50 pm, Miki wrote: >> Hello, >> >> Posting code examples to blogger.com hosted blog is not fun (need to >> remember alway escape < and >). >> Is there any free blog hosting that is more "code friendly" (easy to >> post code snippets and such)? >> >> Thanks, >> -- >> Miki http://pythonwise.blogspot.com > > how about bracketing your code in the
 tags?

And how will that help with the problem the Original Poster asked about?



-- 
Steven



From lists at cheimes.de  Wed Jan  2 03:41:00 2008
From: lists at cheimes.de (Christian Heimes)
Date: Wed, 02 Jan 2008 09:41:00 +0100
Subject: os.tmpfile()
In-Reply-To: <32714577.240331199246555557.JavaMail.root@hrndva-web18-z01>
References: <32714577.240331199246555557.JavaMail.root@hrndva-web18-z01>
Message-ID: <477B4E1C.7040401@cheimes.de>

jyoung79 at kc.rr.com wrote:
> Can anyone elaborate on how 'os.tmpfile()' works?  I was thinking it would create some sort of temporary file I could quickly add text too and then when I was finished would automatically get rid of it.  Here's my questions:

Please don't use os.tmpfile(). It's not safe and exists only for legacy
reasons. The tempfile module contains methods to create safe temporary
files and directories.

Christian


From steve at holdenweb.com  Thu Jan 31 06:09:21 2008
From: steve at holdenweb.com (Steve Holden)
Date: Thu, 31 Jan 2008 06:09:21 -0500
Subject: Design question - Sharing of single object by multiple processes
In-Reply-To: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com>
References: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com>
Message-ID: <47A1AC61.7080007@holdenweb.com>

Mike D wrote:
> Hello, I've just picked up the Python language and am really enjoying it.
> 
> I've just signed up to this mailing list and I'm looking forward to 
> taking part in some discussions.
> 
> My first post is a question I've been pondering for the last couple of days:
> 
> For relatively static data (such as a list), is it possible to load a 
> single instance and have many python processes access it?
> 
First there's the problem of having multiple processes access any kind 
of shared resource. So your question makes me wonder whether you mean 
processes, or threads. Are you *sure* you mean processes?

> I want to have an object in memory. This object will be loaded on 
> application start up and will contain a list of objects. These will be 
> obtained from (most likely) the file system.
> 
So "application startup" is different from "process startup"? Your 
application is a group of co-operating processes? Really?

> My reasoning is: I want to prevent a file system or database fetch each 
> time as it seems unnecessary.
> 
It might also seem unnecessary to start the Python interpreter for each 
process, but you are going to have to ...

> Is this possible? In Java I'm pretty sure this could implemented with an 
> object factory and static methods. My understanding is that python 
> invokes a separate process for each request however.
> 
Your understanding is clearly informed by some information you have 
omitted to share with us.

> If possible, what would be a good way of providing a new structure as it 
> is updated.
> 
> If anyone could give me some advice or point me in the correct direction 
> I'd really appreciate it.
> 
> Thanks in advance,
> 
More answers, please. There are mechanisms such as Pyro (Python remote 
objects) that allow inter-process method calls, but I am far from 
convinced that's what you really want (or need, anyway). Perhaps yo 
could let us know a little more about what it really is you are trying 
to do, and convince me, at least, that this isn't just a case of 
premature optimization.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/


From JO3chiang at gmail.com  Mon Jan  7 20:33:01 2008
From: JO3chiang at gmail.com (jo3c)
Date: Mon, 7 Jan 2008 17:33:01 -0800 (PST)
Subject: Python's great, in a word
References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com>
Message-ID: <0bc9c789-64f4-4656-8c1b-b9343c117240@s19g2000prg.googlegroups.com>

On Jan 7, 9:09 pm, MartinRineh... at gmail.com wrote:
> I'm a Java guy who's been doing Python for a month now and I'm
> convinced that
>
> 1) a multi-paradigm language is inherently better than a mono-paradigm
> language
>
> 2) Python writes like a talented figure skater skates.
>
> Would you Python old-timers try to agree on a word or two that
> completes:
>
> The best thing about Python is _______.
>
> Please, no laundry lists, just a word or two. I'm thinking "fluid" or
> "grace" but I'm not sure I've done enough to choose.

skimpythong!!


From george.sakkis at gmail.com  Tue Jan 15 18:53:51 2008
From: george.sakkis at gmail.com (George Sakkis)
Date: Tue, 15 Jan 2008 15:53:51 -0800 (PST)
Subject: Data mapper - need to map an dictionary of values to a model
References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com>
Message-ID: <2d59f289-2def-43a8-93b7-f326b8f12066@z17g2000hsg.googlegroups.com>

On Jan 14, 7:56 pm, Luke  wrote:

> I am writing an order management console. I need to create an import
> system that is easy to extend. For now, I want to accept an dictionary
> of values and map them to my data model. The thing is, I need to do
> things to certain columns:
>
> - I need to filter some of the values (data comes in as YYYY-MM-
> DDTHH:MM:SS-(TIMEZONE-OFFSET) and it needs to map to Order.date as a
> YYYY-MM-DD field)
> - I need to map parts of an input column to more than one model param
> (for instance if I get a full name for input--like "John Smith"--I
> need a function to break it apart and map it to
> Order.shipping_first_name and Order.shipping_last_name)
> - Sometimes I need to do it the other way too... I need to map
> multiple input columns to one model param (If I get a shipping fee, a
> shipping tax, and a shipping discount, I need them added together and
> mapped to Order.shipping_fee)
>
> I have begun this process, but I'm finding it difficult to come up
> with a good system that is extensible and easy to understand. I won't
> always be the one writing the importers, so I'd like it to be pretty
> straight-forward. Any ideas?
>
> Oh, I should also mention that many times the data will map to several
> different models. For instance, the importer I'm writing first would
> map to 3 different models (Order, OrderItem, and OrderCharge)
>
> I am not looking for anybody to write any code for me. I'm simply
> asking for inspiration. What design patterns would you use here? Why?

The specific transformations you describe are simple to be coded
directly but unless you constrain the set of possible transformations
that can take place, I don't see how can this be generalized in any
useful way. It just seems too open-ended.

The only pattern I can see here is breaking down the overall
transformation to independent steps, just like the three you
described. Given some way to specify each separate transformation,
their combination can be factored out. To illustrate, here's a trivial
example (with dicts for both input and output):

class MultiTransformer(object):
    def __init__(self, *tranformers):
        self._tranformers = tranformers

    def __call__(self, input):
        output = {}
        for t in self._tranformers:
            output.update(t(input))
        return output

date_tranformer = lambda input: {'date' : input['date'][:10]}
name_tranformer = lambda input: dict(
                           zip(('first_name', 'last_name'),
                           input['name']))
fee_tranformer = lambda input: {'fee' : sum([input['fee'],
                                             input['tax'],
                                             input['discount']])}
tranformer = MultiTransformer(date_tranformer,
                              name_tranformer,
                              fee_tranformer)
print tranformer(dict(date='2007-12-22 03:18:99-EST',
                      name='John Smith',
                      fee=30450.99,
                      tax=459.15,
                      discount=985))
# output
#{'date': '2007-12-22', 'fee': 31895.140000000003,
  'first_name': #'J', 'last_name': 'o'}


You can see that the MultiTransformer doesn't buy you much by itself;
it just allows dividing the overall task to smaller bits that can be
documented, tested and reused separately. For anything more
sophisticated, you have to constrain what are the possible
transformations that can happen. I did something similar for
transforming CSV input rows (http://pypi.python.org/pypi/csvutils/) so
that it's easy to specify 1-to-{0,1} transformations but not 1-to-many
or many-to-1.

HTH,
George


From peng.kyo at gmail.com  Wed Jan 16 01:51:10 2008
From: peng.kyo at gmail.com (J. Peng)
Date: Wed, 16 Jan 2008 14:51:10 +0800
Subject: no pass-values calling?
In-Reply-To: 
References: 
	<13or6esikdrqa33@corp.supernews.com>
	
	
Message-ID: <18c1e5f20801152251q5fcb2dd5ne55db03b10750ddb@mail.gmail.com>

On Jan 16, 2008 2:30 PM, Steven D'Aprano
 wrote:
> On Wed, 16 Jan 2008 13:59:03 +0800, J. Peng wrote:
>
> > Hi,
> >
> > How to modify the array passed to the function? I tried something like
> > this:
> >
> >>>> a
> > [1, 2, 3]
> >>>> def mytest(x):
> > ...   x=[4,5,6]
>
>
> This line does NOT modify the list [1, 2, 3]. What it does is create a
> new list, and assign it to the name "x". It doesn't change the existing
> list.
>

Sounds strange.
In perl we can modify the variable's value like this way:

$ perl -le '
> $x=123;
> sub test {
>     $x=456;
> }
> test;
> print $x '
456


From gagsl-py2 at yahoo.com.ar  Tue Jan 29 18:06:23 2008
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Tue, 29 Jan 2008 21:06:23 -0200
Subject: object vs class oriented -- xotcl
References: 
	
	<2dfb6cd3-921a-4692-9627-d35bda40a93e@v29g2000hsf.googlegroups.com>
Message-ID: 

En Tue, 29 Jan 2008 16:22:24 -0200, William Pursell  
 escribi?:

> I'm fairly excited at the idea of being able to
> do per-object mixins in xotcl.  I guess it would
> look like this in python:
>
> BROKEN CODE:
> a = object()
> a.__class__.append( foo )
> a.__class__.append( bar )
>
> In python, if you want an object to me a member
> of 2 classes, it seems that you have no choice but
> to declare a new class that inherits from both.  eg:
>
> class foobar( foo, bar):
>   pass
> a = foobar()
>
> Is it possible to make an object be a member
> of 2 classes without defining such a class?  I
> believe "per object mixin" is the correct
> term for such an animal.  The first several google
> hits on that phrase all reference xotcl, so I'm
> not sure if that is an xotcl inspired vocabulary
> that isn't really standard.

No, an instance can be of only one class at a time. But you can generate  
dynamically the foobar class:
foobar = type("foobar", (foo,bar), {})
and provided `a` is an instance of any other user defined class (not bare  
object), this works:
a.__class__ = foobar
Or simply a = foobar()

If you are going to use this heavily, I suggest a "class cache" in order  
to avoid creating as many classes.

-- 
Gabriel Genellina



From services.wosg at gmail.com  Thu Jan 17 09:52:48 2008
From: services.wosg at gmail.com (WOSG Services)
Date: Thu, 17 Jan 2008 06:52:48 -0800 (PST)
Subject: Boost your business with Quality Web & Design Services at Bargain 
	Prices!
Message-ID: 

Web Outsourcing Services Group (WOSG) is a pioneering and China-based
service provider, committed to delivering quality web & design, SEO
and internet marketing services to clients around the world.

WOSG's strength lies in our skillful staff and lower rates in China.
We have over 60 strictly selected designers and programmers; many of
our designers come from China's top design and web companies, who
conduct design work for famous international brands like Sony, Nike,
Lenovo, L'Oreal etc. In addition, A dedicated Customer Service
Assistant will be assigned to each client as a single point of
contact. Our aim is to help our customers harness the power of
outsourcing and take advantage of China's quality brainpower via our
services.

The rates for our professional services start from as low as $9 per
hour. Quality services at bargain prices, Best value for money!

We can provide following services for your business:

Custom Website Design & Redesign
Graphic and Multimedia Design (Logo,Banner, Flash, etc)
Web Application Development
Search Engine Optimization & Internet Marketing

We have served many clients like you around the world. Although we
are
not the cheapest service provider on the internet, we do work hard to
balance quality and cost therefore maximizes your Return of
Investment.

You can learn more about us by downloading our flyer in PDF format
at:
http://www.WebOutsourcingServices.com/images/WOSG-Brochure-Sheet.pdf
You can also read our case study and browse our portfolio at
http://www.WebOutSourcingServices.com

Contact us via E-mail: Services at WebOutSourcingServices.com

Note: please don't reply this messeage since it is an automatic mail


From ggpolo at gmail.com  Wed Jan 16 14:56:06 2008
From: ggpolo at gmail.com (Guilherme Polo)
Date: Wed, 16 Jan 2008 17:56:06 -0200
Subject: paramiko
In-Reply-To: <685fabb3-c9e8-47ac-84f2-405b831bccad@v4g2000hsf.googlegroups.com>
References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp>
	
	<8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com>
	
	<8ceaad4c-c725-4093-a204-ab09162d4629@c23g2000hsa.googlegroups.com>
	
	<685fabb3-c9e8-47ac-84f2-405b831bccad@v4g2000hsf.googlegroups.com>
Message-ID: 

2008/1/16, Tarun Kapoor :
> On Jan 16, 12:22 pm, "Guilherme Polo"  wrote:
> > 2008/1/16, Tarun Kapoor :
> >
> >
> >
> > > On Jan 16, 11:38 am, "Guilherme Polo"  wrote:
> > > > 2008/1/16, Tarun Kapoor :
> >
> > > > >     # now, connect and use paramiko Transport to negotiate SSH2 across
> > > > > the connection
> > > > >     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > > > >     sock.connect((hostname, port))
> >
> > > > >     t = paramiko.Transport(sock)
> > > > >     t.start_client()
> > > > >     key = t.get_remote_server_key()
> >
> > > > >     event = threading.Event()
> > > > >     t.auth_password(username=username, password=password, event=event)
> > > > >     event.wait()
> >
> > > > >     if not t.is_authenticated():
> > > > >         print "not authenticated"
> >
> > > > > output:
> > > > > not authenticated
> >
> > > > This is a different problem I guess, now you are usin get_remote_server_key.
> > > > And why are you creating event after calling start_client without
> > > > specifying it ?
> >
> > > > > On Jan 16, 11:11 am, "Guilherme Polo"  wrote:
> > > > > > 2008/1/16, Tarun Kapoor :
> >
> > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to
> > > > > > > the remote server using an SFTP client I have just to make sure that
> > > > > > > username and password are working.. This is the code.
> >
> > > > > > >     # now, connect and use paramiko Transport to negotiate SSH2 across the
> > > > > > > connection
> >
> > > > > > >     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> >
> > > > > > >     sock.connect((hostname, port))
> >
> > > > > > >     t = paramiko.Transport(sock)
> >
> > > > > > >     event = threading.Event()
> >
> > > > > > >     t.start_client(event)
> >
> > > > > > >     event.wait(15)
> >
> > > > > > >     if not t.is_active():
> >
> > > > > > >         print 'SSH negotiation failed.'
> >
> > > > > > >         sys.exit(1)
> >
> > > > > > >     else:
> >
> > > > > > >         print "SSH negotiation sucessful"
> >
> > > > > > >     event.clear()
> >
> > > > > > >     t.auth_password(username=username, password=password,event=event)
> >
> > > > > > >     if not t.is_authenticated():
> >
> > > > > > >         print "not authenticated"
> >
> > > > > > > output:
> >
> > > > > > > SSH negotiation successful
> >
> > > > > > > not authenticated
> >
> > > > > > > Tarun
> >
> > > > > > > Waterstone Capital Management
> >
> > > > > > > 2 Carlson Parkway, Suite 260
> >
> > > > > > > Plymouth, MN 55447
> >
> > > > > > > Direct: 952-697-4123
> >
> > > > > > > Cell:    612-205-2587
> > > > > > >  Disclaimer This e-mail and any attachments is confidential and intended
> > > > > > > solely for the use of the individual(s) to whom it is addressed. Any views
> > > > > > > or opinions presented are solely those of the author and do not necessarily
> > > > > > > represent those of Waterstone Capital Management, L.P and affiliates. If you
> > > > > > > are not the intended recipient, be advised that you have received this
> > > > > > > e-mail in error and that any use, dissemination, printing, forwarding or
> > > > > > > copying of this email is strictly prohibited. Please contact the sender if
> > > > > > > you have received this e-mail in error. You should also be aware that
> > > > > > > e-mails are susceptible to interference and you should not assume that the
> > > > > > > contents of this e-mail originated from the sender above or that they have
> > > > > > > been accurately reproduced in their original form. Waterstone Capital
> > > > > > > Management, L.P. and affiliates accepts no responsibility for information,
> > > > > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt,
> > > > > > > please verify the authenticity with the sender.
> > > > > > > --
> > > > > > >http://mail.python.org/mailman/listinfo/python-list
> >
> > > > > > You are missing an event.wait() after t.auth_password.
> > > > > > Also, why are you passing this magic value "15" to event.wait() ? That
> > > > > > parameter is passed to class _Verbose to indicate if debug messages
> > > > > > should be displayed or not, so typical values would be 0/1 or
> > > > > > False/True.
> >
> > > > > > --
> > > > > > -- Guilherme H. Polo Goncalves
> >
> > > > > --
> > > > >http://mail.python.org/mailman/listinfo/python-list
> >
> > > > --
> > > > -- Guilherme H. Polo Goncalves
> >
> > > ok here is the problem... I don't know what is the correct way... The
> > > only demos i have from the paramiko library use a hostkeyfile. since i
> > > don't have that i thought i would use the get_remote_key to get the
> > > key and then connect it using the code in the demo.. But clearly
> > > nothing is working...I should not HAVE to use the key since i should
> > > be able to authenticate using the password...
> >
> > > Can you please suggest the right way to go ?
> >
> > You don't need to use key to authenticate using username and password,
> > indeed. And you don't. Your first email was almost correct, you just
> > needed to add event.wait() after t.auth_password. It worked here after
> > doing that change. You can check out my version:
> >
> > import sys
> > import socket
> > import paramiko
> > import threading
> >
> > if len(sys.argv) != 4:
> >     print "%s hostname user password" % sys.argv[0]
> >     sys.exit(1)
> >
> > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > sock.connect((sys.argv[1], 22))
> >
> > t = paramiko.Transport(sock)
> > event = threading.Event()
> > t.start_client(event)
> >
> > event.wait()
> >
> > if not t.is_active():
> >     print 'SSH negotiation failed.'
> >     sys.exit(1)
> > else:
> >     print "SSH negotiation sucessful"
> >
> > event.clear()
> > t.auth_password(username=sys.argv[2], password=sys.argv[3], event=event)
> > event.wait()
> > if not t.is_authenticated():
> >     print "Authentication failed."
> > else:
> >     print "Authenticated!"
> >
> > t.close()
> >
> >
> >
> > > Thanks for your time !
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
> >
> > --
> > -- Guilherme H. Polo Goncalves
>
> ok i tried the exact same code and here is the output
> SSH negotiation sucessful
> Authentication failed.
>
>
> I am positive that the username and paddword are correct. !

I believe paramiko supports only ssh2, so be sure to check if your
server is not running ssh1.

> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
-- Guilherme H. Polo Goncalves


From redawgts at gmail.com  Wed Jan  2 01:40:38 2008
From: redawgts at gmail.com (redawgts)
Date: Tue, 1 Jan 2008 22:40:38 -0800 (PST)
Subject: os.tmpfile()
References: 
Message-ID: <14af71a6-6847-42a5-b83c-24c3da41a51b@p69g2000hsa.googlegroups.com>

Try this:

>>> import os
>>> c = os.tmpfile()
>>> c.write('dude')
>>> c.seek(0)
>>> c.read()
'dude'


From bearophileHUGS at lycos.com  Wed Jan  2 16:28:47 2008
From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com)
Date: Wed, 2 Jan 2008 13:28:47 -0800 (PST)
Subject: Two candies
References: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com>
	
Message-ID: <736e51b5-d7f6-4523-89f1-df62256ce7c0@s19g2000prg.googlegroups.com>

First of all, thank you Raymond for your answer, and a happy new year
to you and to all the Python group :-)

Raymond:
>#3 is a fine choice.  It is memory efficient -- the repeat() itertool takes-up only a few bytes.  It doesn't need psyco, you already have to fast C routines talking to each other without having to go through the interpreter loop.<

In my code I have found otherwise, so to be more sure I have just done
few benchmarks on a Pentium3 CPU, 256 MB RAM, ActivePython 2.5.1.1, on
Win.

It may sound unfair, but I think it's useful to have some basic
reference timing, so I taken timings from a program written in D
language too (it's like a better C++ mixed with some Python and other
things), this is the D code:

import std.stdio, std.conv, std.string, std.c.stdlib, std.c.time;
void main(string[] args) {
    int n = toInt(args[1].replace("_", ""));
    auto t0 = clock();
    if (args[2].strip() == "1")
        auto a = new int[n];
    else
        auto a = cast(int*)calloc(n, int.sizeof);
    auto t1 = clock();
    writefln("%.2f s", (t1-t0)/cast(double)CLOCKS_PER_SEC);
}

As input it takes n and 1 or 2,
"Warm" timings:

     n      time-1  time-2
 1_000_000    0.04    0.04
10_000_000    0.44    0.42
30_000_000    1.32    1.26

In both cases the a array is initialized to all 0.
D "int" is 4 always bytes. The memory used by this little program is
essentially what you ask for, so it is 4 MB for n = 1 million, 40 MB
for n = 10 millions, and 120 MB for n = 30 millions (plus few other
small things, like the stack, etc. All the other extra memory is
probably less than 800 KB.).


This is the Python code, as input it takes n and 1, 2 or 3:

from array import array
from itertools import repeat
from time import clock
from sys import argv

def main():
    n = int(argv[1].replace("_", ""))
    choice = int(argv[2])
    assert choice in [1, 2, 3]

    if choice == 1:
        t0 = clock()
        a = array("l", xrange(n))
        t1 = clock()
    if choice == 2:
        t0 = clock()
        a = array("l", [0] * n)
        t1 = clock()
    if choice == 3:
        t0 = clock()
        a = array("l", repeat(0, n))
        t1 = clock()

    print round(t1 - t0, 2), "s"
    assert len(a) == n

main()


"Warm" timings:

Time (seconds):
     n         #1      #2      #3
 1_000_000   1.98    0.79    1.91
10_000_000  21.73    7.97   21.13
30_000_000  70.     28.55   65.3

Approximate peak MB RAM used:
     n        #1     #2      #3
 1_000_000     9   10.3     6.6
10_000_000    60   81      64
30_000_000   184  210+    200+

At runtime the Python interpreter plus other little things take some
memory, about 1.7 MB.
In the cases with the "+" sign the RAM was not enough, and I've had
swaps, so timings are probably different if you have more RAM (but I
think this benchmark is significant anyway, because IMHO an array of
integers of 120 MB isn't supposed to make your OS swap your 256 MB of
memory if you allocate it properly).
To me it seems that array("l",repeat(0,n)) eats lot of memory, and
it's quite slower than array("l",[0]*n) too. (I presume
array("l",repeat(0,n)) converts the python int 0 to the signed 4-byte
int over and over again...). So I belive still an allocate-like method
may be useful to the array object. It may allocate the data structure
with n=30 millions in probably less than 2 seconds. In the meantime
such arrays I presume I'll use an external numerical lib :-)

Bye,
bearophile


From python.list at tim.thechases.com  Wed Jan  9 15:12:24 2008
From: python.list at tim.thechases.com (Tim Chase)
Date: Wed, 09 Jan 2008 14:12:24 -0600
Subject: problem of converting a list to dict
In-Reply-To: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com>
References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com>
Message-ID: <47852AA8.4070206@tim.thechases.com>

> mylist=['','tom=boss','mike=manager','paul=employee','meaningless']
> 
> I'd like to remove the first and the last item as they are irrevalent,
> and convert it to the dict:
> {'tom':'boss','mike':'manager','paul':'employee'}
> 
> I tried this but it didn't work:
> 
> mydict={}
> for i in mylist[1:-1]:
> 	a=i.split('=')		# this will disect each item of mylist into a 2-item
> list
> 	mydict[a[0]]=a[1]
> 
> and I got this:
>   File "srch", line 19, in 
>     grab("a/tags1")
>   File "srch", line 15, in grab
>     mydict[mylist[0]]=mylist[1]
> IndexError: list index out of range

This can be rewritten a little more safely like

   mydict = dict(pair.split('=',1)
     for pair in mylist
     if '=' in pair)

Some of John Machin's caveats still apply:
(2) a[0] is empty or not what you expect (a person's name)
(3) a[1] is empty or not what you expect (a job title)
(consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = '
boss')
(4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...]

to which I'd add

(5) what happens if you have more than one equals-sign in your 
item?  ("bob=robert=manager" or "bob=manager=big-cheese")


#2 and #3 can be ameliorated a bit by

   import string
   mydict = dict(
     map(string.strip,pair.split('=',1))
     for pair in mylist
     if '=' in pair)

which at least whacks whitespace off either end of your keys and 
values.  #4 and #5 require a clearer definition of the problem.

-tkc




From cwitts at gmail.com  Fri Jan  4 02:27:55 2008
From: cwitts at gmail.com (Chris)
Date: Thu, 3 Jan 2008 23:27:55 -0800 (PST)
Subject: Problem reading csv files
References: <1788604d-5fed-435a-a9f3-f7e9f652b5a3@s12g2000prg.googlegroups.com>
Message-ID: <8e393f84-f0c1-4cd3-bd9e-a454cbebdd80@i29g2000prf.googlegroups.com>

On Jan 4, 6:24 am, Ramashish Baranwal 
wrote:
> Hi,
>
> I am trying to read a csv file using csv.reader. The file is created
> using Open Office and saved in Excel format.
>
> import csv
>
> reader = csv.reader(open('test.xls'))
> for row in reader:
>     print row
>
> It however throws the exception _csv.Error:
> : line contains NULL byte
>
> Any idea whats going wrong here?
>
> Thanks in advance,
> Ram

XLS != CSV
XLS is M$'s format for spreadsheets whereas CSV is essentially a text
document with comma-delimited fields.  If you open it up in OpenOffice
and go File -> Save As then in the 'Save as type:' drop-down list
select 'Text CSV (.csv)' and ofc change your code to point to the new
file.

If you want to retain it in XLS Format and rather parse that, take a
look at 'xlrd' and 'pyExcelerator'


From jgardner at jonathangardner.net  Thu Jan 24 16:30:37 2008
From: jgardner at jonathangardner.net (Jonathan Gardner)
Date: Thu, 24 Jan 2008 13:30:37 -0800 (PST)
Subject: Ignore exceptions
References: 
Message-ID: <8448fdcb-3ee5-4173-a841-0e844e54d9ba@e4g2000hsg.googlegroups.com>

On Jan 24, 12:13 pm, SMALLp  wrote:
> Hy. Is there any way to make interrupter ignore exceptions. I'm  working
> on bigger project and i used to put try catch blocks after writing and
> testing code what's boring and it's easy to make mistake. I remember of
> something like that in C++ but I cant find anythin like that for python.
>

Hello. Two points with exceptions.

* Only write try blocks when you are actually going to do something
interesting with the exception. Otherwise, let the exception bubble
up.

* If you have unwanted exceptions, fix the root cause of the exception
rather than try to hide the exception. The exception is saying
something is wrong and needs attention. Provide that attention.

I have seen too many people write code in Java that simply masks all
exceptions because they don't want to write the interface to their
functions that describes what exceptions are possible. I have seen
comments around this code saying, "This should always work." Of
course, it doesn't always work and when it doesn't work, they don't
know about it and they don't even know how to tell what went wrong.

The emotion driving this exception masking practice I see in the Java
world is laziness, not correctness. This is not the good form of
laziness (where you want to write good code so you end up doing less
work) but the bad form (where you don't want to work at all).

There is no need to mask exceptions in Python. In fact, it is more
work to mask exceptions, and you should feel bad about all the extra
typing you are doing.

Once again: All try blocks should do something interesting when they
catch an exception. No exception should be ignored or thrown away.

A few sample good uses of try/except blocks:

(1) Do something else if an expected exception occurs.

  try:
    # There is a good chance an exception will be thrown. If so, I
want to do something else.
    d['foo'] += 5
  except KeyError:
    d['foo'] = 5

(2) Show a friendly error message when an exception occurs over a
significant chunk of the program. (Useful for websites and GUI apps.)

  try:
    # There is a very complicated piece of code. Any of a million
exceptions could occur.
    ...
  except:
    # Show a nicely formatted error message with hints on how to debug
the error.
    ...

Here are some bad examples:

(BAD)

   try:
     # I don't know what is happening in here, but it always throws an
exception.
     # I don't want to think about it because it makes my brain hurt.
     ...
   except:
     pass

(WORSE) The alternate form--try N times, masking the error each time--
is equally bad.

  while True:
    try:
      # Something could go wrong. What could go wrong? Who cares?
      ...
      break
    except:
      # We'll just keep trying forever....
      pass


From Matthew_WARREN at bnpparibas.com  Mon Jan 28 11:31:50 2008
From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com)
Date: Mon, 28 Jan 2008 16:31:50 +0000
Subject: validate string is valid maths
In-Reply-To: <13pru0etgp7joc1@corp.supernews.com>
Message-ID: 


Ok, I was thinking along the same lines myself, replacing ++ etc.. until no
more replacements are made.

I hadnt considered creating a table of pairs and replacements though, or
realised that the same replace method would work in that case. handy :)

The dictionary is unordered; would differences in the order of replacements
being made effect the final outcome?

IE

*/*

replaced in order of */ then /* would give (using table below)

*/ => **
/* => **

But in the order /* then */

*/*


/* => */
*/ => *

I've tried testing, but I'm not certain wether repeated iterations over a
dict return different sequences of key,value pairs or wether I'll be
getting the same (but arbitrary) sequence each time even though they are
unordered, etc

So for testing, what could I do to guarantee the next iteration over the
dict will give keys/pairs in a different sequence to last time?


...actually, whenever I iterate over the dict say with for k,v in n.items()
I get exactly the same sequence each time.  For once I want to exploit the
dict's unorderedness and it's decided its going to be all ordered...

Matt.




                                                                                                                   
           Internet                                                                                                
           steve at REMOVE-THIS-cybersource.com.au                                                                    
                                                                                                                To 
                                                                        python-list                                
           Sent by:                                                                                             cc 
           python-list-bounces+matthew.warren=uk.bnpparibas.com@                                                   
           python.org                                                                                      Subject 
                                                                        Re: validate string is valid maths         
           28/01/2008 15:43                                                                                        
                                                                                                                   
                                                                                                                   
                                                                                                                   
                                                                                                                   
                                                                                                                   
                                                                                                                   




On Mon, 28 Jan 2008 15:10:54 +0000, Matthew_WARREN wrote:

> Hi pythoners.
>
> I am generating strings of length n, randomly from the symbols
>
> +-/*0123456789
>
> What would be the 'sensible' way of transforming the string, for example
> changing '3++++++8' into 3+8

That's easy: replace pairs of + into a single +, repeatedly until there's
nothing left to replace. And so forth. Here's an untested function. It's
probably not even close to optimal, but for playing around it is probably
fine.

def rationalise_signs(s):
    while "++" in s or "+-" in s or "-+" in s or "--" in s:
        s = s.replace("++", "+")
        s = s.replace("--", "+")
        s = s.replace("+-", "-")
        s = s.replace("-+", "-")
    return s




> or '3++--*-9' into '3+-9' such that  eval(string) will always return a
> number?
>
> in cases where multiple symbols conflict in meaning (as '3++--*-9' the
> earliest valid symbols in the sequence should be preserved

You have four symbols, so there are just 4*4=16 sets of two symbols.
Probably the easiest way is to just list them and their replacements out
in a table:

table = {"++": "+", "+-": "-", "+*": "+", "+/": "+",
    "-+": "-", "--": "+", "-*": "-", "-/": "-",
    "*+": "*", "**": "*", "*/": "*",
    "/+": "/", "/*": "/", "//": "/", }

Notice that both *- and /- don't get changed.



# Untested.
def rationalise_signs(s):
    prev = ''
    while s != prev:
        prev = s
        for key, value in table.items():
            s = s.replace(key, value)
    return s



--
Steven
--
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  Sat Jan 26 19:20:21 2008
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Sat, 26 Jan 2008 22:20:21 -0200
Subject: Text-based data inspector for Python?
References: 
	
	
Message-ID: 

En Fri, 25 Jan 2008 12:28:08 -0200, kj  escribi?:

> The one thing I couldn't
> find, and would greatly miss if not available, is the ability to
> set breakpoints by inserting a particular indication right in the
> code.  In the Perl debugger one can insert something like the
> following anywhere in the code:
>
>   $DB::single = 1;
>
> When such a line executes, the debugger immediately switches to
> single-step mode.  It's a very flexible technique, and I like it

I think that pdb.set_trace() does what you want.

-- 
Gabriel Genellina



From mwilson at the-wire.com  Thu Jan 17 19:27:20 2008
From: mwilson at the-wire.com (Mel)
Date: Thu, 17 Jan 2008 19:27:20 -0500
Subject: "Code Friendly" Blog?
References: 
	<0fd979c6-5a11-4989-9438-51a7b20ecd23@n20g2000hsh.googlegroups.com>
Message-ID: 

Hai Vu wrote:
> On Jan 17, 2:50 pm, Miki  wrote:
>> Hello,
>>
>> Posting code examples to blogger.com hosted blog is not fun (need to
>> remember alway escape < and >).
>> Is there any free blog hosting that is more "code friendly" (easy to
>> post code snippets and such)?
>>
>> Thanks,
>> --
>> Miki http://pythonwise.blogspot.com
> 
> how about bracketing your code in the 
 tags?
> 
> Something like this:
> 
> import sys, os, shutil
> 
> def getDir(fullPath):
>     dirName, fileName = os.path.split(fullPath)
>     return dirName
> 
That won't help the escape problem, though it will preserve vital Python whitespace. HTML has to be interpreting '<' characters to recognize the '
'. Mel. From ggpolo at gmail.com Mon Jan 7 08:54:18 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 11:54:18 -0200 Subject: code doesn't reference immutables? In-Reply-To: <5e6d3674-fddb-402f-9e5c-19afcd7fcc22@i7g2000prf.googlegroups.com> References: <5e6d3674-fddb-402f-9e5c-19afcd7fcc22@i7g2000prf.googlegroups.com> Message-ID: 2008/1/7, MartinRinehart at gmail.com : > >From the manual: > > "code objects are immutable and contain no references (directly or > indirectly) to mutable objects" (3.2) > > I thought my code worked with both mutable and immutable objects. > Whassup? > What was your intention quoting this half-phrase ? >From the same place, Python Reference Manual, 3.2: Code objects: Code objects represent byte-compiled executable Python code, or bytecode. The difference between a code object and a function object is that the function object contains an explicit reference to the function's globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From apatheticagnostic at gmail.com Fri Jan 18 11:44:26 2008 From: apatheticagnostic at gmail.com (apatheticagnostic) Date: Fri, 18 Jan 2008 08:44:26 -0800 (PST) Subject: how to resolve Windows pathnames into cygwin ones References: Message-ID: <2ba97fb6-6bef-44aa-937b-2aa9582e4341@e4g2000hsg.googlegroups.com> On Jan 18, 11:10 am, "mgier... at gmail.com" wrote: > I am looking for a function to resolve 'F:/foo/bar' into '/cygdrive/f/ > foo/bar'. I get the original dirpath from tkFileDialog.askdirectory in > a Windows form and none of os.path.* functions seem to resolve it to a > cygwin form. Rather they _append_ it to the current directory, > resulting at best in a monster '/cygdrive/c/whatever/f/foo/bar'. > It's all being developed under cygwin currently (so it is a kind of > mixed environment), but I would like the fix to work correctly in any > environment. > > Thanks, > Marcin Well, you could write it yourself.... (assuming path is a string, here's a first go at it...) def path_into_cygpath(path): drive, destination = path.split(':') newpath = '/cygdrive/' + drive.lower() + destination return newpath From bearophileHUGS at lycos.com Thu Jan 17 09:37:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 17 Jan 2008 06:37:15 -0800 (PST) Subject: Replace stop words (remove words from a string) References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> Message-ID: <2a0b933f-1c41-4b7c-b213-9781286d6e0a@c23g2000hsa.googlegroups.com> Raymond Hettinger: > Regular expressions should do the trick. > >>> stoppattern = '|'.join(map(re.escape, stoplist)) > >>> re.sub(stoppattern, '', mystr) If the stop words are many (and similar) then that RE can be optimized with a trie-based strategy, like this one called "List": http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm "List" is used by something more complex called "Optimizer" that's overkill for the OP problem: http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/Optimizer.pm I don't know if a Python module similar to "List" is available, I may write it :-) Bye, bearophile From gagsl-py2 at yahoo.com.ar Tue Jan 1 14:37:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Jan 2008 17:37:15 -0200 Subject: Newbie: Why doesn't this work References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> Message-ID: En Tue, 01 Jan 2008 16:57:41 -0200, escribi?: > Gabriel, if I understand it properly, it is necessary to define get/ > set/del/doc methods for each attribute for which I want to set the > "property" data descriptor (which triggers get/set/del/doc function > calls upon access to defined attribute). Yes. Not all of them, just what you need (by example, a read-only property doesn't require a set method; I think the get() docstring is used if no explicit doc is provided; most of the time I don't care to define del...) You don't "have" to define anything you don't need; moreover, you don't have to define a property if you don't actually need it. The very first example in the builtin functions documentation for "property" is a bad example: if all your property does is to wrap a stored attribute, forget about the property and use the attribute directly. > My question is: is it possible to set the "property" for any attribute > when I do not know what will be the name of the attribute in the > future? Uhm... I don't understand the question. Perhaps if you think of a concrete case...? -- Gabriel Genellina From donn.ingle at gmail.com Thu Jan 24 11:58:35 2008 From: donn.ingle at gmail.com (Donn Ingle) Date: Thu, 24 Jan 2008 18:58:35 +0200 Subject: piping into a python script References: Message-ID: Paddy wrote: > fileinput is set to process each file a line at a time unfortunately. Wow. So there seems to be no solution to my OP. I'm amazed, I would have thought a simple list of strings, one from stdin and one from the args, would be easy to get. I *really* don't want to open each file, that would be insane. Perhaps I shall have to forgo the stdin stuff then, after all. \d From lasses_weil at klapptsowieso.net Sun Jan 27 18:35:51 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 28 Jan 2008 00:35:51 +0100 Subject: Python Genetic Algorithm In-Reply-To: References: Message-ID: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> Max wrote: > In GAs, you operate on a Population of solutions. Each Individual from > the Population is a potential solution to the problem you're > optimizing, and Individuals have what's called a chromosome - a > specification of what it contains. For example, common chromosomes are > bit strings, lists of ints/floats, permutations...etc. I'm stuck on > how to implement the different chromosomes. I have a Population class, > which is going to contain a list of Individuals. Each individual will > be of a certain chromosome. I envision the chromosomes as subclasses > of an abstract Individual class, perhaps all in the same module. I'm > just having trouble envisioning how this would be coded at the > population level. Presumably, when a population is created, a > parameter to its __init__ would be the chromosome type, but I don't > know how to take that in Python and use it to specify a certain class. > I'm not sure I'm following you here. So a "chromosome" is bit of functionality, right? So basically it is a function. So my advice would be to write these functions and store it to the "indivuals"-list like so: class Population(object): def __init__(self, *individuals): self.individuals = list(individuals) Then you can say: p = Population(indiv1, indiv2, indiv3) for individual in p.individual: individual(whatever_your_problem) (Don't know if this is the way GA's are supposed to work) You can also create callable classes (that is, classes that implement the __call__ method), and use instances of these as the individuals. For example you can create a Permutation class that returns a permutation (defined in it's __init__()) when it's __call__ method is called. (Am I making sense?) This is just generic advice, maybe this helps and maybe it doesn't at all. :) > I'm doing something similar with my crossover methods, by specifying > them as functions in a module called Crossover, importing that, and > defining > > crossover_function = getattr(Crossover, "%s_crossover" % xover) > > Where xover is a parameter defining the type of crossover to be used. > I'm hoping there's some similar trick to accomplish what I want to do > with chromosomes - or maybe I'm going about this completely the wrong > way, trying to get Python to do something it's not made for. Any help/ > feedback would be wonderful. > This isn't too bad, but for such things dictionaries are your Go-To datatype. Just have a dictionary of xover-functions handy and call the thusly: crossover_function = Crossover.function[xover] > Thanks, > Max Martin If that helps :) regards /W From victorsubervi at gmail.com Fri Jan 4 11:39:50 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 4 Jan 2008 12:39:50 -0400 Subject: How Does This Static Variable Work? In-Reply-To: <51302a8c0801040834w6e9bf720l37d90a2884b19253@mail.gmail.com> References: <4dc0cfea0801040717u9bc67ccr80447dc375502445@mail.gmail.com> <51302a8c0801040834w6e9bf720l37d90a2884b19253@mail.gmail.com> Message-ID: <4dc0cfea0801040839w21da20bbn24cdf518e5905a10@mail.gmail.com> Thanks. I'll study that. Victor On Jan 4, 2008 12:34 PM, Neil Cerutti wrote: > On Jan 4, 2008 10:17 AM, Victor Subervi wrote: > > > Hi; > > I read this example somewhere, but I don't understand it <:-) Can > > someone please explain how static variables work? Or recommend a good > > how-to? > > > > > > import random > > > > def randomwalk_static(last=[1]): # init the "static" var(s) > > > > rand = random.random() # init a candidate value > > > > Simulating C's static local variables is the (in)famous application for > this case of optimization in Python's design. > > Consult the following entry in the Python General Programming FAQ for > further information. > > > http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects > > -- > Neil Cerutti > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sinisterguy at gmail.com Fri Jan 11 15:29:24 2008 From: sinisterguy at gmail.com (lukas) Date: Fri, 11 Jan 2008 12:29:24 -0800 (PST) Subject: os.rename() problems on OS X Message-ID: <02de1e94-ff7b-4304-a7f6-0393fde975ae@q77g2000hsh.googlegroups.com> hello, i recently had the job of having to rename about 200 files. The source for the renaming was a bunch of names in a file. I know next to nothing when it comes to bash scripting (which would have seemed the obvious choice) so i used python. The files i was renaming were canon raw files (.CR2). my problem is that after i rename the files, OS X will no longer render the thumbnails for the files, and preview is no longer the default app for viewing them. Does anyone have an idea as to why this is? Thanks for the help :) -Lukas From johnthawk at excite.com Wed Jan 23 07:57:21 2008 From: johnthawk at excite.com (johnthawk at excite.com) Date: Wed, 23 Jan 2008 07:57:21 -0500 (EST) Subject: Icon in a gtk.Entry Message-ID: <20080123125721.28332B57EE@xprdmxin.myway.com> Hello all, I have two thing I wish to accomplish, First, put an icon in a gtk.Entry as in many search boxes. Second put a gtk.Checkbox in a gtk.ComboboxEntry. On the later I thought I could get a handle to the Combobox tree and then add a column and then column span column 1 back into column 0 , thus a gtk.ToggelRender would be visible in column 0. But I had no luck getting a handle to the Combobox tree. Any help would be greatly appreciated. Have a nice day. John _______________________________________________ Join Excite! - http://www.excite.com The most personalized portal on the Web! From george.sakkis at gmail.com Wed Jan 23 14:27:34 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 23 Jan 2008 11:27:34 -0800 (PST) Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? References: Message-ID: On Jan 23, 4:06 am, Gary Herron wrote: > However there *is* a (subtle) difference between > not f > and > (not f and 1) or 0 > > The first produces a boolean value, and the second produces an int > value, but since one is a subclass of the other, you'd have to write > quite perverse code care about the difference. Even if for some reason I did want the result to be int, I would write it as "int(not f)". George From http Thu Jan 31 11:24:44 2008 From: http (Paul Rubin) Date: 31 Jan 2008 08:24:44 -0800 Subject: How to identify which numbers in a list are within each others' range References: <6b4ac79b-6267-438d-8b28-aa4bba78a586@i3g2000hsf.googlegroups.com> Message-ID: <7x63xavu7n.fsf@ruckus.brouhaha.com> erikcw writes: > 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. This sounds like a homework problem, so the first thing I'll suggest is that you figure out exactly what it means for two of those intervals to overlap. That should let you write a simple program that gets the right answer, but that can run slowly if the number of lists gets large. The next thing to do after that is figure out how to speed it up, if necessary. But do the first part first. From massi_srb at msn.com Sun Jan 13 10:22:59 2008 From: massi_srb at msn.com (Massi) Date: Sun, 13 Jan 2008 07:22:59 -0800 (PST) Subject: wxpython-wx.CheckListBox: changing item bacgkground color Message-ID: <1c6feae5-1188-4e00-9ba5-b7d8a1b0302e@s19g2000prg.googlegroups.com> Hi everyone! In my application (under windows) I'm using a wx.checklistbox. I would like the background color of an item to become red whenever an EVT_LISTBOX_DCLICK occurs. Is there any simple way to achieve it? Thanks in advance. From lepto.python at gmail.com Mon Jan 14 21:25:22 2008 From: lepto.python at gmail.com (oyster) Date: Tue, 15 Jan 2008 10:25:22 +0800 Subject: jpype with JFreeChart, anyone interested to help? Message-ID: <6a4f17690801141825t74737c17h1e83285b487e17c8@mail.gmail.com> Thanx However I knew Chaco and matplotlib, and I use matplotlib during my school days. And as I have pointed out, they are for "plot", but not "chart". If you don't know the difference between plot and chart, you can have a look at at http://www.jfree.org/jfreechart, http://www.rmchart.com Yes, it is true we can use plot lib to draw chart, but that is tedious. 2008/1/15, python-list-request at python.org : > From: Peter Wang > To: python-list at python.org > Date: Mon, 14 Jan 2008 07:58:02 -0800 (PST) > Subject: Re: jpype with JFreeChart, anyone interested to help? > On Jan 14, 6:51 am, oyster wrote: > > As you may know, there is no beautiful and free chart(notplot, you > > can find the examples athttp://www.jfree.org/jfreechart,http://www.rmchart.com) module for python than runs on > > windows/linux/mac osx. > > Actually, may I humbly suggest two: > > Chaco: http://code.enthought.com/chaco/gallery/index.shtml > > matplotlib: http://matplotlib.sourceforge.net/ > > > -Peter > > > From gowricp at gmail.com Wed Jan 16 05:36:50 2008 From: gowricp at gmail.com (Gowri) Date: Wed, 16 Jan 2008 02:36:50 -0800 (PST) Subject: searching an XML doc References: <327368a7-694f-4f30-8f76-db0569ed4a5c@k2g2000hse.googlegroups.com> <2d290754-4a44-427f-9287-134210b217d5@q77g2000hsh.googlegroups.com> Message-ID: <7a48ed44-05f8-4943-b034-0073d0858156@21g2000hsj.googlegroups.com> Hi Gerard, I don't know what to say :) thank you so much for taking time to post all of this. truly appreciate it :) From jr9445 at ATT.COM Fri Jan 18 12:39:55 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 18 Jan 2008 11:39:55 -0600 Subject: How to use only a sub shell to execute many commands in python 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 raocheng > Sent: Friday, January 18, 2008 6:31 AM > To: python-list at python.org > Subject: How to use only a sub shell to execute many commands in python > > Please see the following code. > Suppose I have many shell commands to be executed. And I don't want to > fork a sub shell for each command(eg: status,output = > commands.getstatusoutput(cmd)) because it is too expensive. I want to > use only one sub shell to execute all these commands and want to get > each command's output. How can I accomplish this task ? Thanks in > advance. > > =========================================== > #!/usr/bin/env python > import os > fi, fo = os.popen2( > ''' > while read line > do > eval $line > done > ''', 't') > > #Suppose I have many commands to execute, but I don't want to fork a > sub shell for each command > cmds = ['date','uptime','pwd','ls -rltF','who'] > > for cmd in cmds: > #pseudocode > fi.executeCmd(cmd) > output = fo.readResult() > > print output Have each command write to a unique temp file. Create temp files in python cmd = 'date > /tmp/date_temp 2>&1 ; uptime > /tmp/uptime_temp 2>&1; ...' execute cmd for file in tempfiles: ... You can also get the return value of each command cmd = 'date > /tmp/date_temp 2>&1; echo $? >> /tmp/date_temp; uptime > /tmp/uptime_temp 2>&1; echo $? >> ...' ***** 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. GA622 From hniksic at xemacs.org Mon Jan 14 13:47:41 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 14 Jan 2008 19:47:41 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <873at0mkv7.fsf@mulj.homelinux.net> Message-ID: <87ve5wkzw2.fsf@mulj.homelinux.net> "Reedick, Andrew" writes: >> Only if by "construct" you mean "allocate". __init__ starts out >> with an empty object and brings it to a valid state, therefore >> "constructing" the object you end up with. That operation is >> exactly what other languages call a constructor. > > Nah. Most other languages combine the constructor and an init > function. Maybe so, but the standard term for what Python calls __init__ is still "constructor". > Also, how can a constructor require 'self' as an argument...? > __init__(self, ...) Think of it as the equivalent of Java's and C++'s "this", except it's explicit in the argument list. "Explicit is better than implicit" and all that. :-) From arnodel at googlemail.com Tue Jan 1 15:26:23 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 1 Jan 2008 12:26:23 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <6aba9463-f0ea-43a2-b8de-9c7026c4d14e@e4g2000hsg.googlegroups.com> <5c6a5515-a6ee-455d-83d4-48b2a2ae46c3@n20g2000hsh.googlegroups.com> <579f378d-d948-4c99-8507-a8c4e9a28096@i29g2000prf.googlegroups.com> <74a7edcf-f4ea-4835-b08e-499faaed8d81@i12g2000prf.googlegroups.com> Message-ID: <6cfa4965-ed8f-4d70-a688-170bf557b7d4@m34g2000hsf.googlegroups.com> On Jan 1, 6:48?pm, "Gabriel Genellina" wrote: > En Tue, 01 Jan 2008 15:45:00 -0200, bukzor ? > escribi?: [...] > >> I'm confused by what you mean by 'early binding'. Can you give a quick- > >> n-dirty example? > > Is an 'early bound' variable synonymous with a 'static' variable (in > > C)? > > No. It means, in which moment the name gets its value assigned. Usually ? > Python does "late binding", that is, names are resolved at the time the ? > code is executed, not when it's compiled or defined. > Consider this example: > > z = 1 > def foo(a) > ? ?print a+z > foo(3) # prints 4 > z = 20 > foo(3) # prints 23 > > The second time it prints 23, not 4, because the value for z is searched ? > when the code is executed, so the relevant value for z is 20. > Note that if you later assign a non-numeric value to z, foo(3) will fail. > > If you want to achieve the effect of "early binding", that is, you want to ? > "freeze" z to be always what it was at the time the function was defined, ? > you can do that using a default argument: > > z = 1 > def foo(a, z=z) > ? ?print a+z > z = None > foo(3) # prints 4 > > This way, foo(3) will always print 4, independently of the current value ? > of z. Moreover, you can `del z` and foo will continue to work. > > This is what I think Chris Mellon was refering to. This specific default ? > argument semantics allows one to achieve the effect of "early binding" in ? > a language which is mostly "late binding". If someone changes this, he has ? > to come with another way of faking early binding semantics at least as ? > simple as this, else we're solving an [inexistant for me] problem but ? > creating another one. > > -- > Gabriel Genellina Let me say again that I believe the current behaviour to be the correct one. But I don't think this 'early binding' is critical for this sort of example. There are lots of ways to solve the problem of having persistent state across function calls, for example: * using classes * using modules * or simply nested functions: def getfoo(z): def foo(a): print a + z return foo >>> z = 1 >>> foo = getfoo(z) >>> z = None >>> foo(3) 4 And with nonlocal, we could even modify z inside foo and this change would persist across calls. This will be a much cleaner solution than the current def bar(x, y, _hidden=[startvalue]). Also, note that it's easy to implement default arguments in pure python-without-default-arguments using a decorator: def default(**defaults): defaults = defaults.items() def decorator(f): def decorated(*args, **kwargs): for name, val in defaults: kwargs.setdefault(name, val) return f(*args, **kwargs) return decorated return decorator Here is your example: >>> z=1 >>> @default(z=z) ... def foo(a, z): ... print a + z ... >>> z=None >>> foo(3) 4 Another example, using mutables: >>> @default(history=[]) ... def bar(x, history): ... history.append(x) ... return list(history) ... >>> map(bar, 'spam') [['s'], ['s', 'p'], ['s', 'p', 'a'], ['s', 'p', 'a', 'm']] -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Sun Jan 20 17:18:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 20 Jan 2008 22:18:34 -0000 Subject: Looping through the gmail dot trick References: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> Message-ID: <13p7i5qaihgte12@corp.supernews.com> On Sun, 20 Jan 2008 21:13:03 +0000, Neil Hodgson wrote: > Martin Marcher: > >> are you saying that when i have 2 gmail addresses >> >> "foo.bar at gmail.com" and >> "foobar at gmail.com" >> >> they are actually treated the same? That is plain wrong and would break >> a lot of mail addresses as I have 2 that follow just this pattern and >> they are delivered correctly! > > This is a feature of some mail services such as Gmail, not of email > addresses generically. One use is to provide a set of addresses given > one base address. '+' works as well as '.' so when I sign up to service > monty I give them the address nyamatongwe+monty at gmail.com. Then when I > receive spam at nyamatongwe+monty, I know who to blame and what to > block. Technically, everything in the local part of the address (the bit before the @ sign) is supposed to be interpreted *only* by the host given in the domain (the bit after the @ sign). So if Gmail wants to interpret "foo.bar at gmail.com" and "foobar at gmail.com" the same, they can. Or for that matter, "raboof at gmail.com". Although that would be silly. Postfix, I think, interpets "foo+bar" the same as "foo". -- Steven From nagle at animats.com Mon Jan 14 19:26:51 2008 From: nagle at animats.com (John Nagle) Date: Mon, 14 Jan 2008 16:26:51 -0800 Subject: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug Message-ID: <478bfcb0$0$36378$742ec2ed@news.sonic.net> I passed a dict for the "env" variable to Popen with Unicode strings for the dictionary values. Got: File "D:\Python24\lib\subprocess.py", line 706, in _execute_child TypeError: environment can only contain strings It turns out that the strings in the "env" parameter have to be ASCII, not Unicode, even though Windows fully supports Unicode in CreateProcess. John Nagle From stefan.behnel-n05pAM at web.de Sun Jan 27 04:30:42 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 27 Jan 2008 10:30:42 +0100 Subject: Sorting Large File (Code/Performance) In-Reply-To: References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <690cb460-fa8a-49a1-a6fa-69cdf480a918@i3g2000hsf.googlegroups.com> <7xir1hznuu.fsf@ruckus.brouhaha.com> Message-ID: <479C4F42.3010500@web.de> Gabriel Genellina wrote: > use the Windows sort command. It has been > there since MS-DOS ages, there is no need to download and install other > packages, and the documentation at > http://technet.microsoft.com/en-us/library/bb491004.aspx says: > > Limits on file size: > The sort command has no limit on file size. Sure, since no-one can ever try it with more than 640k, it's easy to state that there is no limit. :) Stefan From basilisk96 at gmail.com Tue Jan 8 22:11:24 2008 From: basilisk96 at gmail.com (Basilisk96) Date: Tue, 8 Jan 2008 19:11:24 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <5cf4c5bb-01b1-4ece-a09a-24c4491764b1@f47g2000hsd.googlegroups.com> On Jan 7, 8:09 am, MartinRineh... at gmail.com wrote: > I'm a Java guy who's been doing Python for a month now and I'm > convinced that > > 1) a multi-paradigm language is inherently better than a mono-paradigm > language > > 2) Python writes like a talented figure skater skates. > > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is _______. > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > "grace" but I'm not sure I've done enough to choose. Here's a new word - ...its humanicity factor. That definition, according to me, is: "its ability to let you *quickly* formulate and solve your problem in the way that YOU see it, not as the computer sees it." Did programmers stop writing programs on punch cards because they ran out of punch paper? Cheers, -Basilisk96 From halcyon1981 at gmail.com Thu Jan 24 14:32:02 2008 From: halcyon1981 at gmail.com (David Erickson) Date: Thu, 24 Jan 2008 11:32:02 -0800 (PST) Subject: Email module, how to add header to the top of an email? Message-ID: <97c04812-3b66-4d84-9e92-21de72a3ca56@c23g2000hsa.googlegroups.com> I have been using the Email module and Message class for awhile, however I have been unable to find a way to add a header to the top of the email similar to what is done with Received: headers... the add_header method only appends to the bottom. Is there someway this can be done? Thanks David From dima.hristov at gmail.com Mon Jan 21 06:53:06 2008 From: dima.hristov at gmail.com (DHR) Date: Mon, 21 Jan 2008 03:53:06 -0800 (PST) Subject: Q: paramiko/SSH/ how to get a remote host_key Message-ID: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> I'm trying to run the simpliest example form paramiko readme(Homepage: http://www.lag.net/paramiko/), and cannot find out how to get the remote SSH server host_key. This is the code. It is supposed to connect to a remote SSH host and execute an 'ls' command: import paramiko, base64 key = paramiko.RSAKey(data=base64.decodestring('AAA...')) client = paramiko.SSHClient() client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key) client.connect('227.112.168.273', username='uname', password='pass') stdin, stdout, stderr = client.exec_command('ls') for line in stdout: print '... ' + line.strip('\n') client.close() Now, if I understand it correctly I need to get somehow the host_key from the server and write it insted of the 'AAA...' thing. Is there a command to get the host_key from a remote SSH server? From mwm-keyword-python.b4bdba at mired.org Thu Jan 10 22:14:31 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 22:14:31 -0500 Subject: Detecting OS platform in Python In-Reply-To: References: Message-ID: <20080110221431.63082666@bhuda.mired.org> On Thu, 10 Jan 2008 18:37:59 -0800 (PST) Devraj wrote: > Hi everyone, > > My Python program needs reliably detect which Operating System its > being run on, infact it even needs to know which distribution of say > Linux its running on. The reason being its a GTK application that > needs to adapt itself to be a Hildon application if run on devices > like the N800. I don't think it can be done. For most Unix system, os.uname() will give you the information you want: >>> os.uname() ('FreeBSD', 'bhuda.mired.org', '6.2-STABLE', 'FreeBSD 6.2-STABLE #6: Sun Jun 3 04:17:59 EDT 2007 mwm at bhuda.mired.org:/usr/src/sys/amd64/compile/BHUDA', 'amd64') (let's see - OS name, the system name, the release level, complete build information, down to the configuration file for the build and build number for that configuration, and the hardware type it was built for). For GNU/Linux systems, it won't, because it's a kernel facility, and kernels don't know what distribution they're part of: Linux student.mired.org 2.6.12-9-386 #1 Mon Oct 10 13:14:36 BST 2005 i686 GNU/Linux (kernel name, system name, kernel version and build information, platform, and operating system). GNU/Linux distributions are collections of lots of people software, so each has it's own way to state what "distribution" it is. I believe there's some sort of standard - except not everybody follows it. So you wind up using a series of heuristics to chase this information down. > I have been searching around for an answer to this, and did find some > messages on a lists that suggested the use of sys.platform to detect > platform, with counter posts saying that it didn't work on Windows > etc. Oh, you want it to work on Windows? Hmmm. [snotty comment about Windows deleted]. Does the underlying platform claim to be POSIX.2 compliant? If so, then os.uname() should work on it, but as indicated, that may well not be complete. On the other hand, trying to figure out what features you have available by guessing based on the platform type is generally the wrong way to approach this kind of problem - only in part because you wind up reduced to a series of heuristics to figure out the platform. And once you've done that, you could wind up being wrong. Generally, you're better of probing the platform to find out if it has the facilities you're looking for. For python, that generally means trying to import the modules you need, and catching failures; or possibly looking for attributes on modules if they adopt to the environment around them. I'm not a GTK programmer, and have never even heard of Hildon. Is there some associated module you could try and import that doesn't exist on the N800? I.e.: try: import gtk mygui = 'gtk' except ImportError: import Hildon mygui = 'Hildon' or maybe something like: import gtk mygui = 'gtk' if not hasattr(gtk, 'Hildon') else 'Hildon' http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From danielatdaveschool at gmail.com Wed Jan 16 00:53:20 2008 From: danielatdaveschool at gmail.com (danielatdaveschool at gmail.com) Date: Tue, 15 Jan 2008 21:53:20 -0800 (PST) Subject: Image to browser References: <8c014bd1-7040-4ba3-9206-e1567c4a391a@n20g2000hsh.googlegroups.com> <1d223aa2-1297-4b01-854a-2a502f5f0ed1@l1g2000hsa.googlegroups.com> Message-ID: <45a7516d-0014-4d6d-9d1f-385727c846ae@i7g2000prf.googlegroups.com> On Jan 16, 12:38 am, Justin Ezequiel wrote: > On Jan 16, 1:19 pm, danielatdavesch... at gmail.com wrote: > > > > > On Jan 16, 12:16 am, danielatdavesch... at gmail.com wrote: > > > > Im using mod_python and apache2 using psp for output of page, i open a > > > file and resize it with the following code > > > > <% > > > import Image, util > > > > fields = util.FieldStorage(req) > > > filename = fields.getlist('src')[0] > > > > path = '/var/www/content/' + filename > > > size = 128, 128 > > > > im = Image.open(path) > > > print im.resize(size, Image.ANTIALIAS) > > > %> > > > > so for one, I dont think print does much with psp as far as i can > > > tell, i cant even do a print 'hello world', it has to be a > > > req.write('hello world'), but i cant req.write the im.resize. The > > > manual for im.resize states that its return can go ahead and be > > > streamed via http but I get a blank page when im expecting to see > > > image characters dumped to my screen. Python doesn't throw up any > > > errors. Im not sure where else to look or what to do. > > > > Thanks for any help, > > > Daniel > > > its worth noting that ive tried using > > print "Content-Type: image/jpeg\n" > > before the print im.resize and still no luck > > If you're using the Image module from PIL then im.resize(...) returns > an Image instance. > I have not used mod_python and psp, but try the following: > > >>> import Image > >>> i = Image.open('server.JPG') > >>> r = i.resize((32,32)) > >>> from StringIO import StringIO > >>> b = StringIO() > >>> r.save(b, 'JPEG') > >>> b.seek(0) > >>> req.write("Content-Type: image/jpeg\r\n\r\n") > >>> req.write(b.read()) > > There's a r.tostring(...) method but I don't see how to make that > return a JPEG stream. brilliant, at least to me anyway, it works as long as i remove the req.write("content-type... now i have a lot to look up, i tried something similar to this before that i found on the web but no luck. i guess whats going on is it gets saved to this pseudo file thats just a string existing in memory, and then the pointer gets set to the begining of the string for the upcoming read() ? i dunno, but something else to learn about. I must admit i was hoping for something a little more elegant. Thanks for your help! From python at rolfvandekrol.nl Mon Jan 21 09:15:12 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Mon, 21 Jan 2008 15:15:12 +0100 Subject: stdin, stdout, redmon In-Reply-To: <4794a5e3$0$9014$426a74cc@news.free.fr> References: <4794a5e3$0$9014$426a74cc@news.free.fr> Message-ID: <4794A8F0.7020400@rolfvandekrol.nl> According to various tutorials this should work. |import sys data = sys.stdin.readlines() print "Counted", len(data), "lines."| Please use google before asking such questions. This was found with only one search for the terms 'python read stdin' Rolf Bernard Desnoues wrote: > Hi, > > I've got a problem with the use of Redmon (redirection port monitor). I > intend to develop a virtual printer so that I can modify data sent to > the printer. > Redmon send the data flow to the standard input and lauchs the Python > program which send modified data to the standard output (Windows XP and > Python 2.5 context). > I can manipulate the standard output. > > "import sys > sys.stdout.write(data)" > > it works. > But how to manipulate standard input so that I can store data in a > string or in an object file ? There's no "read" method. > > "a = sys.stdin.read()" doesn't work. > "f = open(sys.stdin)" doesn't work. > > I don't find anything in the documentation. How to do that ? > Thanks in advance. > > Bernard Desnoues > Librarian > Biblioth?que de g?ographie - Sorbonne From gagsl-py2 at yahoo.com.ar Mon Jan 21 00:45:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 03:45:30 -0200 Subject: object scope References: <13p8803q11tm32d@corp.supernews.com> <47942AB5.4040301@block.duxieweb.com> Message-ID: En Mon, 21 Jan 2008 03:16:37 -0200, J. Peng escribi?: > Dennis Lee Bieber ??: >> The scope of "name" is the entire function; lacking a "global name" >> statement, AND being on the left side of an assignment, it is a function >> local name. > > Thank you. Does python have so-called 'block scope' object? > or if you can,please show me the doc for python's object scope. See http://docs.python.org/ref/naming.html -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Mon Jan 28 02:52:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 28 Jan 2008 07:52:14 -0000 Subject: Using a dict as if it were a module namespace References: <13podkpqqvef674@corp.supernews.com> Message-ID: <13pr2def4b48uc6@corp.supernews.com> On Sun, 27 Jan 2008 11:16:00 -0700, Steven Bethard wrote: > Why not mess with the namespace inside the setup code? E.g.:: [snip] Ah, thanks, good thinking. It's not perfect, but it should be close enough for what I'm trying to do. -- Steven who still wishes you could explicitly pass a namespace to timeit.Timer... From arnodel at googlemail.com Fri Jan 4 18:12:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 4 Jan 2008 15:12:47 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> <13ntbv51tqcm7c@corp.supernews.com> Message-ID: <1b73b614-f71c-4985-988a-7852ef39715f@j78g2000hsd.googlegroups.com> On Jan 4, 10:15?pm, Steven D'Aprano wrote: > On Fri, 04 Jan 2008 09:29:50 -0800, bukzor wrote: > > Why cant you implement < for complex numbers? Maybe I'm being naive, but > > isn't this the normal definition? > > ? ? a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) > > No, it is not. Mathematically speaking, it is an order, and a very useful one. Only it's a partial order, which means that if a != b then they are not necessarily ordered (e.g. 1 and i). This is not ideal for sorting. What you need is a total order, where any two distinct elements are comparable. > Ordered comparisons are not defined for complex numbers. You can't define a total order which is compatible with addition and multiplication, but this restriction is not required to implement sets of complex numbers. Any total order will do, the easiest to pick being lexicographical as already pointed out, i.e. a+bi < c + di iff a < c or a == c and b < d > Which is bigger, 4+2j or 2+4j? 4+2j, lexicographically! -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 00:20:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 27 Jan 2008 05:20:55 -0000 Subject: how to make format operator % work with unicode as expected References: Message-ID: <13po55nc0q0s06@corp.supernews.com> On Sun, 27 Jan 2008 04:06:45 +0000, Peter Pei wrote: > I probably should mention that what I want is to make all parts of the > string aligned, and look like table. I am not looking for other ways to > make it table-alike, but only interested in making % work with unicode > -counting characters not bytes... % already works with unicode. Just give it unicode arguments: >>> print u"x y z %s 1 2 3" % u"Les mis?rables" x y z Les mis?rables 1 2 3 -- Steven From aquorang at yahoo.com Thu Jan 3 23:53:57 2008 From: aquorang at yahoo.com (aquorang at yahoo.com) Date: Thu, 3 Jan 2008 20:53:57 -0800 (PST) Subject: i want to share my secrets with u......... Message-ID: <5a30516f-6f56-4431-911c-f784e826ccf1@i7g2000prf.googlegroups.com> i want to share my secrets with u......... how to create miracles in your own life? http://www.freewebs.com/aquorang/ http://indianfriendfinder.com/go/g926592-pmem http://bigchurch.com/go/g926592-pmem From paddy3118 at googlemail.com Thu Jan 24 01:07:58 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 23 Jan 2008 22:07:58 -0800 (PST) Subject: Terminology: "script" versus "program" (was: Linux Journal Survey) References: <1666950d-e9a5-4b7c-a614-5bba90e5b4ca@y5g2000hsf.googlegroups.com> <87ir1j7r9k.fsf_-_@benfinney.id.au> Message-ID: On 24 Jan, 04:59, Ben Finney wrote: > George Sakkis writes: > > 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. > > I agree entirely. > > The term "script" has the strong connotation of a limited-purpose > program designed to solve a problem expressed almost entirely as a > simple series of steps. Languages that are often used to write such > scripts are usually referred to as "scripting languages", which > becomes a denigration because such a language need not have support > for much else. > > In contrast, the term "program" (and hence "programming language") > implies support for a much broader set of practices and solutions. > > This term seems quite prevalent among the Python core developers, > unfortunately. The 'distutils' module even has the term 'script' used > in its interface, to refer to the programs that are to be distributed. > > -- > \ "Money is always to be found when men are to be sent to the | > `\ frontiers to be destroyed: when the object is to preserve them, | > _o__) it is no longer so." -- Voltaire, _Dictionnaire Philosophique_ | > Ben Finney Hi George, Ben, In the past I have taken the high ground by arguing that the usual tasks associated with scripting are very important and that languages like Python/Ruby can script as well as write substantial programs in the non-scripting sense. Therefore, if their language of choice does not encompass scripting then it is a lesser language. 'They' may look down on scripting but a lot of that is a mixture of ignorance and envy :-) - Paddy. From arnodel at googlemail.com Tue Jan 22 15:20:56 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 12:20:56 -0800 (PST) Subject: question References: Message-ID: <89b4586c-1d1f-4118-9092-62cdf2a8a7f7@e4g2000hsg.googlegroups.com> On Jan 22, 7:58?pm, wrote: > I'm still learning Python and was wanting to get some thoughts on this. ?I apologize if this sounds ridiculous... ?I'm mainly asking it to gain some knowledge of what works better. ?The main question I have is if I had a lot of lists to choose from, what's the best way to write the code so I'm not wasting a lot of memory? ?I've attempted to list a few examples below to hopefully be a little clearer about my question. > > Lets say I was going to be pulling different data, depending on what the user entered. ?I was thinking I could create a function which contained various functions inside: > > def albumInfo(theBand): > ? ? def Rush(): > ? ? ? ? return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > > ? ? def Enchant(): > ? ? ? ? return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > > ? ? ... > > The only problem with the code above though is that I don't know how to call it, especially since if the user is entering a string, how would I convert that string into a function name? ?For example, if the user entered 'Rush', how would I call the appropriate function --> ?albumInfo(Rush()) > > But if I could somehow make that code work, is it a good way to do it? ?I'm assuming if the user entered 'Rush' that only the list in the Rush() function would be stored, ignoring the other functions inside the albumInfo() function? > > I then thought maybe just using a simple if/else statement might work like so: > > def albumInfo(theBand): > ? ? if theBand == 'Rush': > ? ? ? ? return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > ? ? elif theBand == 'Enchant': > ? ? ? ? return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > ? ? ... > > Does anyone think this would be more efficient? > > I'm not familiar with how 'classes' work yet (still reading through my 'Core Python' book) but was curious if using a 'class' would be better suited for something like this? ?Since the user could possibly choose from 100 or more choices, I'd like to come up with something that's efficient as well as easy to read in the code. ?If anyone has time I'd love to hear your thoughts. > > Thanks. > > Jay What you want is a dictionary: albumInfo = { 'Rush': 'Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'], 'Enchant': ['A Blueprint of the World', 'Wounded', 'Time Lost'], ... } then to find the info just do: >>> albumInfo['Enchant'] ['A Blueprint of the World', 'Wounded', 'Time Lost'] It also makes it easy to add a new album on the fly: >>> albumInfo["Lark's tongue in Aspic"] = [ ... ] Hope that helps. -- Arnaud From roger.miller at nova-sol.com Thu Jan 24 17:55:43 2008 From: roger.miller at nova-sol.com (Roger Miller) Date: Thu, 24 Jan 2008 14:55:43 -0800 (PST) Subject: Ignore exceptions References: <8448fdcb-3ee5-4173-a841-0e844e54d9ba@e4g2000hsg.googlegroups.com> Message-ID: <244a3456-84d3-4328-b30a-59fae999bada@u10g2000prn.googlegroups.com> On Jan 24, 11:30 am, Jonathan Gardner wrote: > .... > A few sample good uses of try/except blocks: > > (1) Do something else if an expected exception occurs. > ... > (2) Show a friendly error message when an exception occurs over a > significant chunk of the program. (Useful for websites and GUI apps.) > ... I'd add (3) Clean-up handlers. These don't actually handle the problem, they just free resources, close files, etc. before re-raising the exception for someone else to worry about. From jimgardener at gmail.com Tue Jan 8 10:32:21 2008 From: jimgardener at gmail.com (jimgardener) Date: Tue, 8 Jan 2008 07:32:21 -0800 (PST) Subject: copy a numpy array Message-ID: hi, (i posted this to numpy discussion grp couple of days back ..but it fails to appear..)since it is needed for my work i would appreciate if anyone can help me with this question i have two ndarrays of 1000 elements each and want to copy all elements from srcarray to destarray srcarray=numpy.array( [3973334.8381791776,........,382999.6748692277] ) arrsize=1000 destarray=zeros(arrsize) i copied all items from src to dest by using destarray[0:arrsize]=srcarray[0:arrsize] i don't know if this is the right way to do the copying. is there a better(efficient?) way ? jim From kyosohma at gmail.com Thu Jan 24 15:27:27 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 24 Jan 2008 12:27:27 -0800 (PST) Subject: Ignore exceptions References: Message-ID: <3b926cf2-a07a-48b8-8941-c2701517ab86@k2g2000hse.googlegroups.com> On Jan 24, 2:13 pm, SMALLp wrote: > Hy. Is there any way to make interrupter ignore exceptions. I'm working > on bigger project and i used to put try catch blocks after writing and > testing code what's boring and it's easy to make mistake. I remember of > something like that in C++ but I cant find anythin like that for python. > > SMALLp See the try statement: http://docs.python.org/ref/try.html http://www.network-theory.co.uk/docs/pytut/HandlingExceptions.html http://docs.python.org/api/exceptionHandling.html Mike From tom at nextstate.net Mon Jan 7 10:08:28 2008 From: tom at nextstate.net (Tom Brown) Date: Mon, 07 Jan 2008 07:08:28 -0800 Subject: dealing with binary files In-Reply-To: References: <47822DA4.9020401@fmed.uba.ar> Message-ID: <1199718508.4558.30.camel@chi> On Mon, 2008-01-07 at 11:57 -0200, Guilherme Polo wrote: > 2008/1/7, Gerardo Herzig : > > Hi all. Im trying to read a binary data from an postgres WAL archive. > > If i make a > > xfile = open('filename', 'rb').xreadlines() > > line = xfile.next() > > > > i see this sort of thing: > > ']\xd0\x03\x00\x01\x00\x00\x00\r\x00\x00\x00\x00\x00\x00JM//DI+,D\x00\x00\x00\x01$\x00\x00\x00\x7f\x06\x00\x00y\r\t\x00\x02\x0f\t\x00\x00\x00\x10\x00)\x00\x01\x00\x12\x08 > > \x00^\xc2\x0c\x00\x08\x00\x00\x003001({\xe8\x10\r\x00\x00\x00\xe4\xff\xffI\x10?l\x01@\x00\x00\x00$\x00\x00\x00\x00\n' > > > > This file suppose to have some information about database activity, but > > at this point i cant do more than this, because i cant figure out what > > to do in order to have some 'readable' text. > > > > Im guessing is some C code, im reading the struct module to see if it > > helps, but im not into C programming, and im lost at the start of my > > problem. > > You are looking at the correct module, struct. But in order to > understand or even correctly extract data from a binary file, you need > to know its structure. There should be some document describing the > Postgre WAL file format. > "The log record headers are described in access/xlog.h" http://www.postgresql.org/docs/8.2/interactive/wal-internals.html From mr.cerutti at gmail.com Wed Jan 9 08:42:57 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 9 Jan 2008 08:42:57 -0500 Subject: alternating string replace In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <51302a8c0801090542t3b9e6b0dm95ba7ddb42d067cf@mail.gmail.com> On Jan 9, 2008 5:34 AM, cesco wrote: > Hi, > > say I have a string like the following: > s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... > > Thanks in advance Hum, hum... If I had a hammer... from pyparsing import * word = Word(alphas) sep = Literal('_').suppress() pair = Group(word + sep + word) pairs = delimitedList(pair, '_') print ','.join(':'.join(t) for t in pairs.parseString('hi_cat_bye_dog').asList()) -- Neil Cerutti From matt at tplus1.com Fri Jan 18 19:43:20 2008 From: matt at tplus1.com (Matthew Wilson) Date: Sat, 19 Jan 2008 00:43:20 GMT Subject: I don't understand what is happening in this threading code Message-ID: In this code, I tried to kill my thread object by setting a variable on it to False. Inside the run method of my thread object, it checks a different variable. I've already rewritten this code to use semaphores, but I'm just curious what is going on. Here's the code: import logging, threading, time logging.basicConfig(level=logging.DEBUG, format="%(threadName)s: %(message)s") class Waiter(threading.Thread): def __init__(self, hot_food): super(Waiter, self).__init__() self.should_keep_running = True self.hot_food = hot_food def run(self): while self.should_keep_running: logging.debug("Inside run, the id of should_keep_running is %s." % id(self.should_keep_running)) self.hot_food.acquire() def cook_food(hot_food): i = 5 while i >= 0: logging.debug("I am cooking food...") time.sleep(1) hot_food.release() logging.debug("Andiamo!") i -= 1 def main(): hot_food = threading.Semaphore(value=0) chef = threading.Thread(name="chef", target=cook_food, args=(hot_food, )) chef.start() w = Waiter(hot_food) logging.debug("Initially, the id of w.should_keep_running is %s." % id(w.should_keep_running)) w.start() logging.debug("After start, the id of w.should_keep_running is %s." % id(w.should_keep_running)) # Wait for the chef to finish work. chef.join() # Now try to kill off the waiter by setting a variable inside the waiter. w.should_keep_running = False logging.debug("Now, the id of w.should_keep_running is %s." % id(w.should_keep_running)) if __name__ == "__main__": main() And here's what I get when I execute it. I have to suspend the process with CTRL=Z and then kill -9 it. $ python foo.py MainThread: Initially, the id of w.should_keep_running is 135527852. MainThread: After start, the id of w.should_keep_running is 135527852. chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! Thread-1: Inside run, the id of should_keep_running is 135527852. MainThread: Now, the id of w.should_keep_running is 135527840. [1]+ Stopped python foo.py $ kill -9 %1 [1]+ Stopped python foo.py The memory address of should_keep_running seems to change when I set it from True to False, and inside the run method, I keep checking the old location. I am totally baffled what this means. Like I said earlier, I already rewrote this code to use semaphores, but I just want to know what is going on here. Any explanation is welcome. TIA Matt From paddy3118 at googlemail.com Mon Jan 7 14:54:27 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 7 Jan 2008 11:54:27 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com><7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com><8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com><13o06hleh4dkj45@corp.supernews.com> Message-ID: On Jan 7, 7:26 pm, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of Paddy > > Sent: Monday, January 07, 2008 12:52 PM > > To: python-l... at python.org > > Subject: Re: dictionary/hash and '1' versus 1 > > > Or how using different operators for similar operations on different > > types causes confusion. > > i.e. == versus eq; > versus gt > > If Perl had, for example, a complex number 'base' type would that need > > yet another set of operators? > > The real question is: what's the simplest way to implement complex > numbers without sacrificing understanding, accuracy, and convenience? I > would say, no new operators. Imaginary numbers are numbers and should > use numeric operations which means overloaded match operators. > > As background: In order to keep things simple, Perl's string operators > are string-like. Math operators are math. > '2' * 5 = 10 > '2' x 5 = '22222' ('x' is a char, so think strings) > ==, >, >=, <, <= > eq, gt, ge, lt, le (string abbreviations for equal, greater > than, etc.) > '1' + 1 = 2 > '1' . 1 = 11 (Think period at the end of a sentence, which > implies stringing strings together.) > > > Well enough Perl vs Python. The thing is, that when writing in another > > programming language you have to use its idioms or you end up fighting > > the language in attempt to make it work like another language you are > > more familiar with. In Python strings won't ever automatically change > > to numbers. > > Agreed. However looking towards the future (new versions of > Perl/Python, new languages, new paradigms) is it worth asking whether > it's better/clearer/easier/more_accurate to > a) type cast the data: a + b (a and b must be of the same type) > > a.1) explicitly type cast the data: str(a) + str(b) > (if a and b are different types) > b) type cast by operator: '1' + 1 = 2; '1' . 1 = '11' > c) go really old school with: concat('1', 1); add('1', 1) > > IMO, since Python is strongly but dynamically typed, a) is the 'worst' > solution. If you forget to type cast, you're boned, since you probably > won't find the problem until the code block is actually executed and an > exception is thrown. You could defensively type cast everything, but > that can clutter the code, and cluttered code is harder to understand > and keep bug free. With b) or c), the compiler will type cast as you > intended. Again, just my opinion. > > Anyway, it's little things like '1' + 1 that will probably prevent > programming syntax from ever being similar to naturally spoken language. > I guess it comes down to the differences in fundamental principles of Perl and Python. Perl is developed to "Do what I mean", whereas Python would be more like "Do as I say". Perl strives to be more like a spoken language, Python strives to have a core set of powerful & composable ideas. On your specific example I'd guess that both schemes work well its just that I am more comfortable with Pythons one set of more overloaded operators and vice-versa for yourself, leading us both to have problems when we switch between Perl and Python :-) - Paddy. From sromero at gmail.com Wed Jan 9 12:55:28 2008 From: sromero at gmail.com (Santiago Romero) Date: Wed, 9 Jan 2008 09:55:28 -0800 (PST) Subject: printing dots in simple program while waiting References: Message-ID: <4e3bde5c-7efb-4f0a-af33-973dff850e0c@l6g2000prm.googlegroups.com> On 9 ene, 17:48, John wrote: > i want to print something like: > > (1sec) working... > (2sec) working.... > (3sec) working..... > > where the 'working' line isn't being printed each second, but the dots > are being added with time. > > something like: > > import time > s = '.' > print 'working' > while True: > print s > time.sleep(1) > > however, this doesn't work since it prints: > > working > . > . Change > print s to > print s, (With the ending ",", which sends NO linefeed to stdout) Bye :) From lists at cheimes.de Sat Jan 19 18:18:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 20 Jan 2008 00:18:09 +0100 Subject: Python 3000 and import __hello__ In-Reply-To: References: Message-ID: <47928531.7030806@cheimes.de> Brad wrote: > Just playing around with Python3000 a2 release on Windows XP 32-bit x86. > > import __hello__ > > doesn't print 'hello world...' as it does on 2.5 > > The import doesn't fail or generate errors... just no output. Perhaps > this is by design? I changed the __hello__ frozen module a while ago. The print was unreliable for some new unit tests. Christian From cokofreedom at gmail.com Thu Jan 17 11:08:13 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 17 Jan 2008 08:08:13 -0800 (PST) Subject: Is this a bug, or is it me? References: <87myr4o3sg.fsf@mulj.homelinux.net> Message-ID: On Jan 17, 4:59 pm, "Neil Cerutti" wrote: > On Jan 17, 2008 10:44 AM, Hrvoje Niksic wrote: > > > "Neil Cerutti" writes: > > > > You cannot access a class's class variables in it's class-statement > > > scope, since the name of the type is not bound until after the class > > > statement is completed. > > > But they are still available as locals, so you can access them using > > their names, like this: > > > >>> class C: > > ... a = 1 > > ... b = 2 > > ... print a+b > > ... > > 3 > > Thanks! I had never tried that before. That actually solved my default > method argument problem. > > > > > The question is, why doesn't the OP's code snippet work? It seems > > that the generator expression can't read the surrounding locals(). > > But when you change the generator expression to a list comprehension > > using a pair of [] around it, it starts working. Compare: > > > class C(object): > > d = {} > > for a in 1, 2, 3: > > ignore = list((a, b) for b in (4, 5, 6)) > > > Traceback (most recent call last): > > File "", line 1, in > > File "", line 4, in C > > File "", line 4, in > > NameError: global name 'a' is not defined > > > with: > > > class C(object): > > d = {} > > for a in 1, 2, 3: > > ignore = [(a, b) for b in (4, 5, 6)] > > > It seems that generator expressions and list comprehensions have > > subtly different scoping rules. Whether this is a bug or not is a > > good question. > > Generator expressions, unlike list comprehensions, have their own > scope so that they don't "leak" names to the enclosing scope. The > Python rule forbidding access to the locals of enclosing scopes is > preventing the class names from working in the generator expression. > > -- > Neil Cerutti Ah, that explains why my random suggestion worked but was not helpful :) I feel like I am learning a lot today! From DustanGroups at gmail.com Thu Jan 31 17:57:07 2008 From: DustanGroups at gmail.com (Dustan) Date: Thu, 31 Jan 2008 14:57:07 -0800 (PST) Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> <58d1bc12-206f-4cec-ad86-928d16e962f5@i3g2000hsf.googlegroups.com> <8d69e9e8-c892-4c65-ac54-c184ce303a2e@i3g2000hsf.googlegroups.com> <87zlumjex9.fsf@benfinney.id.au> Message-ID: On Jan 31, 7:35 am, Ben Finney wrote: > Dustan writes: > > On Jan 30, 7:02 pm, FireNWater wrote: > > > Thank you for the explanation. . . I think I now have a (foggy) > > > understanding of hash tables. It seems to be a way to create order > > > (an index) out of disorder (random numbers or characters) behind > > > the scenes. . > > > The key thing to realize is, quite simply, don't rely on order in a > > dictionary. > > The poster to which you replied is using "order" as contrasted with > "disorder". Clearly dictionaries *do* have order that can be relied > upon. He was referring to the index. So was I, as in: Don't rely on the index, because the size of the dictionary can vary, and therefore, the index can vary, and therefore, the programmer must recognize that the order of looping can vary. If you're referring to the actual order of looping, then I and every good Python Guru (of which I am not one) disagrees with you. If not, then you're confusing the different meanings of "order" in this context. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 25 07:55:40 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 25 Jan 2008 13:55:40 +0100 Subject: object vs class oriented -- xotcl In-Reply-To: <13pi0mmk525f325@corp.supernews.com> References: <13pi0mmk525f325@corp.supernews.com> Message-ID: <4799dbf0$0$16980$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Thu, 24 Jan 2008 12:35:44 -0800, William Pursell wrote: > >> The ability to have an object change class is >> certainly (to me) a novel idea. Can I do it in Python? > > Yes, mostly. Example: > (snip) > > If you actually play around with this, you'll soon find the limitations. > For instance: > >>>> s.__class__ = int > Traceback (most recent call last): > File "", line 1, in > TypeError: __class__ assignment: only for heap types > Other limitations may appear with frameworks relying on metaprogramming features for their inner working so users don't have to worry about boilerplate - something you'll often find in recent web frameworks, orms etc... Mostly, the point with dynamically changing the class of an object (whether or not your in the above situation) is that you must ensure consistant state by yourself, which sometimes happens to be far less trivial than it seems at first look. I once tried to implement the State pattern this way (in real-life code), and while it worked, it ended being more complicated (and brittle) than implementing it the canonical way. So while it *may* be a good solution, I'd advise you to carefully check the concrete use case before using this feature. From aafshar at gmail.com Wed Jan 2 05:56:54 2008 From: aafshar at gmail.com (Ali) Date: Wed, 2 Jan 2008 02:56:54 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <13ndpflarf19i9c@corp.supernews.com> Message-ID: <8e29e3f8-831b-4b4f-8d8b-2fd681b51b37@e23g2000prf.googlegroups.com> On Dec 30 2007, 12:27 am, Steven D'Aprano wrote: > In the absence of a better solution, I'm very comfortable with keeping > the behaviour as is. Unfortunately, there's no good solution in Python to > providing functions with local storage that persists across calls to the > function: ... (4) Instances handle this pretty well, just s/functions/methods/. From PatrickMinnesota at gmail.com Wed Jan 2 14:08:28 2008 From: PatrickMinnesota at gmail.com (PatrickMinnesota) Date: Wed, 2 Jan 2008 11:08:28 -0800 (PST) Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <13nn9k48n7ohr95@corp.supernews.com> <69337707-ff18-4b39-af0a-78cf0a14b667@1g2000hsl.googlegroups.com> Message-ID: <4715e05f-456b-4274-9718-b6c009af7698@1g2000hsl.googlegroups.com> On Jan 2, 9:33 am, Aaron Watters wrote: > > I must admit I feel a hint of amusement though at your comment above, when > > it's sent from precisely the sort of setup you appear bemused by - since > > you appear to have already bought into it without realising ! :-D > > Ok, so if we include yahoo mail and gmail in "cloud computing" then I > guess > usenet is also cloud computing. How about ftp? ssh? nfs? Oh I get > it. It's > another meaningless marketing buzz phrase. > > I mean, really, I've been using web-mail and various varieties of > remote > storage for over a decade. What is *new* about the concept? (I see > some > hints above, but it's mixed in with a lot of other stuff...) > > -- Aaron Watters > > ===http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=fud Aaron - I would say that the biggest difference between what people have been doing for decades and what is now being referred to as 'cloud computing' is the applications. The idea of the cloud is that the application, like a word processor for instance, is not running or installed on your computer. It's running on Google's servers, or Zoho's servers etc. Your data is also stored on their servers. So yeah, it's kind of like the old diskless X-Terminal setup and is totally contrary to how companies like Microsoft would like the world to work. The other main difference seems to be that 'cloud computing' runs under a different revenue model than traditional applications like Microsoft Office. Google Apps, in it's most basic form is free and so are most of the others. They are monetizing in a different way than Microsoft does when it sells you Office for $500 or whatever. From jarausch at igpm.rwth-aachen.de Wed Jan 30 07:32:00 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 30 Jan 2008 13:32:00 +0100 Subject: Tkinter - incremental input ? Message-ID: <60b922F1pnj4bU1@mid.dfncis.de> Hi, I don't want to reinvent the wheel but I cannot find it so far. Many editors have a so-called incremental search feature. As you type characters, elements of a set of strings which fit so far are displayed or at least, the first one of these is displayed. Now I want to do something similar in Tkinter - an Entry widget which displays possible 'completions' e.g. given the list of names (...,'Hardy','Helmut',..) As soon as enter the character 'H' the string 'Hardy' would be displayed in the Entry widget - but the cursor is still at position 2 (given 'H' is a position 1) Furthermore, as soon as I enter 'e', it would change the text to 'Helmut', and so on. While I can bind '' to a callback, I haven't figured out how to get (and later on set) the cursor within the Entry widget. In other words I need to know at which character position the last character was entered. Currently I can only see the brute force method: keeping track of all cursor positioning means like , , the '<-' and '->' keys and mouse clicks. Is there an easier method? Many thanks for a hint or even a pointer to an example, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From MartinRinehart at gmail.com Mon Jan 7 08:32:34 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Mon, 7 Jan 2008 05:32:34 -0800 (PST) Subject: code doesn't reference immutables? Message-ID: <5e6d3674-fddb-402f-9e5c-19afcd7fcc22@i7g2000prf.googlegroups.com> >From the manual: "code objects are immutable and contain no references (directly or indirectly) to mutable objects" (3.2) I thought my code worked with both mutable and immutable objects. Whassup? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 14 19:26:53 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 15 Jan 2008 01:26:53 +0100 Subject: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net> Message-ID: <5v2cudF1k5a1oU1@mid.individual.net> John Nagle wrote: > It turns out that the strings in the "env" parameter have to be > ASCII, not Unicode, even though Windows fully supports Unicode in > CreateProcess. Are you sure it supports Unicode, not UTF8 or UTF16? Probably using something like u"thestring".encode("utf16") will help. Regards, Bj?rn -- BOFH excuse #31: cellular telephone interference From http Fri Jan 18 12:58:57 2008 From: http (Paul Rubin) Date: 18 Jan 2008 09:58:57 -0800 Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <7xve5ruiam.fsf@ruckus.brouhaha.com> David Sanders writes: > The data files are large (~100 million lines), and this code takes a > long time to run (compared to just doing wc -l, for example). wc is written in carefully optimized C and will almost certainly run faster than any python program. > Am I doing something very inefficient? (Any general comments on my > pythonic (or otherwise) style are also appreciated!) Is > "line.split()" efficient, for example? Your implementation's efficiency is not too bad. Stylistically it's not quite fluent but there's nothing to really criticize--you may develop a more concise style with experience, or maybe not. One small optimization you could make is to use collections.defaultdict to hold the counters instead of a regular dict, so you can get rid of the test for whether a key is in the dict. Keep an eye on your program's memory consumption as it runs. The overhead of a pair of python ints and a dictionary cell to hold them is some dozens of bytes at minimum. If you have a lot of distinct keys and not enough memory to hold them all in the large dict, your system may be thrashing. If that is happening, the two basic solutions are 1) buy more memory; or, 2) divide the input into smaller pieces, attack them separately, and merge the results. If I were writing this program and didn't have to run it too often, I'd probably use the unix "sort" utility to sort the input (that utility does an external disk sort if the input is large enough to require it) then make a single pass over the sorted list to count up each group of keys (see itertools.groupby for a convenient way to do that). From mr.cerutti at gmail.com Wed Jan 16 08:14:23 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 16 Jan 2008 08:14:23 -0500 Subject: no pass-values calling? In-Reply-To: References: <18c1e5f20801151909u4cdd227ah685741ea21734491@mail.gmail.com> Message-ID: <51302a8c0801160514m6c8f9b3dm2e98094e44daec68@mail.gmail.com> On Jan 16, 2008 7:58 AM, wrote: > On Jan 16, 1:21 pm, "Neil Cerutti" wrote: > > In the following function, a is rebound with an assignment statement, > > while b is mutated, i.e., changed, with an assignment statement. > > > > def f(a, b): > > a = 12 > > b.value = 14 > > > > Argument a will never be changed, while argument b will be. Python's > > argument passing semantics are extremely simple. It's the assignment > > statement that's tricky: some assignments mutate/change objects, and > > some only rebind names. > > So basically the scope is the reason for confusion a lot of the time? No, my hypothesis is that Python's assignment statement semantics are the tricky part--once you understand them, the utter simplicity of Python's argument passing semantics will be evident. -- Neil Cerutti From arne.k.h at gmail.com Wed Jan 23 11:06:10 2008 From: arne.k.h at gmail.com (Arne) Date: Wed, 23 Jan 2008 08:06:10 -0800 (PST) Subject: Trouble writing to database: RSS-reader References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> <4794e0f9$0$4429$426a74cc@news.free.fr> <739742b0-7d3d-4039-b793-ccefae4be721@1g2000hsl.googlegroups.com> Message-ID: On Jan 21, 11:25?pm, "Gabriel Genellina" wrote: > En Mon, 21 Jan 2008 18:38:48 -0200, Arne escribi?: > > > > > On 21 Jan, 19:15, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > >> This should not prevent you from learning how to properly parse XML > >> (hint: with an XML parser). XML is *not* a line-oriented format, so you > >> just can't get nowhere trying to parse it this way. > > >> HTH > > > Do you think i should use xml.dom.minidom for this? I've never used > > it, and I don't know how to use it, but I've heard it's useful. > > > So, I shouldn't use this techinicke (probably wrong spelled) trying to > > parse XML? Should i rather use minidom? > > > Thank you for for answering, I've learnt a lot from both of you, > > Desthuilliers and Genellina! :) > > Try ElementTree instead; there is an implementation included with Python ? > 2.5, documentation ?athttp://effbot.org/zone/element.htmand another ? > implementation available athttp://codespeak.net/lxml/ > > import xml.etree.cElementTree as ET > import urllib2 > > rssurl = 'http://www.jabber.org/news/rss.xml' > rssdata = urllib2.urlopen(rssurl).read() > rssdata = rssdata.replace('&', '&') # ouch! > > tree = ET.fromstring(rssdata) > for item in tree.getiterator('item'): > ? ?print item.find('link').text > ? ?print item.find('title').text > ? ?print item.find('description').text > ? ?print > > Note that this particular RSS feed is NOT a well formed XML document - I ? > had to replace the & with & to make the parser happy. > > -- > Gabriel Genellina This look very interesting! But it looks like that no documents is well-formed! I've tried several RSS-feeds, but they are eighter "undefined entity" or "not well-formed". This is not how it should be, right? :) From sromero at gmail.com Mon Jan 21 02:45:01 2008 From: sromero at gmail.com (Santiago Romero) Date: Sun, 20 Jan 2008 23:45:01 -0800 (PST) Subject: How to use py2exe ... Message-ID: Hi... I'm a Linux user, and I would like some windows-friends to test a game I'm writing with python+pygame without they needing to install python, pygame, and so on. I've heard about py2exe and pygame2exe, but I'm not sure on how to use them to create: a.- standalone exe files with a single .py program. Example: myprogram.py or b.- exe files containing all my source code + data directories (png files, data files, and so). Example: main.py, doc/README, src/*.py and data/* The problem is I'm not sure on how to use py2exe and pygame2exe to build the executables... And finally, a question: if I want to provide source code separately ... can I include .pyc files instead of .py files? From paul at boddie.org.uk Wed Jan 9 05:40:16 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 9 Jan 2008 02:40:16 -0800 (PST) Subject: how to open a file in some application using Tkinter i am using TKINTER to create GUI application i want to know how to open a word document in open office or any other applicatio References: Message-ID: <7b989c2e-7b7e-46be-b290-0c9203afcb46@f47g2000hsd.googlegroups.com> On 9 Jan, 09:24, Fredrik Lundh wrote: > [Opening files in applications] > on windows, you can use the "os.startfile" function: > > import os > os.startfile("mydocument.doc") > > (this is the same as double-clicking on a document in the file explorer) > > on other platforms, use os.system() and specify what application to run: > > import os > os.system("someapp mydocument.doc") Or try the desktop module which uses os.startfile on Windows, but employs mechanisms appropriate for other desktop environments elsewhere: http://www.python.org/pypi/desktop This code should do the trick: import desktop desktop.open("mydocument.doc") This assumes that your desktop environment knows how to handle .doc files, of course. Paul From LinkExchange.AB at gmail.com Sat Jan 19 10:56:43 2008 From: LinkExchange.AB at gmail.com (LinkExchange.AB at gmail.com) Date: Sat, 19 Jan 2008 07:56:43 -0800 (PST) Subject: Ruby Programming Message-ID: <5b554594-158f-4efe-9cd2-1fb66d150781@d4g2000prg.googlegroups.com> iTechArt has specialized in Ruby on Rails (ROR) development and provides a complete software outsourcing services for web development solutions based on Ruby. We suggest use Ruby framework for developing database-backed web applications with Ajax on front-end because it's a great fit for practically any type of web application: collaboration, community, e-commerce, content management and statistics. Ruby development environment and technologies: * Ruby On Rails development framework * MySQL, PostgreSQL, SQLite, Oracle, MS SQL Server, DB2 * RadRails IDE, ActionWebservice for Ruby * Linux, Apache, lighttpd * OOP and software development * Search engines optimization http://www.itechart.com/Pages/Subsections/RubyDevelopment.aspx From kent at kentsjohnson.com Mon Jan 21 17:50:18 2008 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 21 Jan 2008 22:50:18 GMT Subject: Prioritization function needed (recursive help!) In-Reply-To: <51180fda-304d-4f7e-812a-32032585675b@e23g2000prf.googlegroups.com> References: <51180fda-304d-4f7e-812a-32032585675b@e23g2000prf.googlegroups.com> Message-ID: <479521A1.4080105@kentsjohnson.com> rh0dium wrote: > Hi all, > > I need some help on writing a recursive priority function > > Given a list = [ A, B, C, D] > > Where the following constraints are in place: > > A depends on [B, C] > C depends on [B] > > Figure out real order that prioritizes these. You need a topological sort. http://en.wikipedia.org/wiki/Topological_sort Two Python implementations: http://pypi.python.org/pypi/topsort/0.9 http://www.bitformation.com/art/python_toposort.html Kent From erexsha at gmail.com Fri Jan 18 20:10:39 2008 From: erexsha at gmail.com (Arash Arfaee) Date: Fri, 18 Jan 2008 17:10:39 -0800 Subject: psyco on mac Message-ID: <266557d0801181710p5eb54420h79def10af5135985@mail.gmail.com> Hello, I have problem installing psyco on my mac. Can anybody help me? Thanks, Arash From nick at craig-wood.com Fri Jan 25 04:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 25 Jan 2008 03:30:03 -0600 Subject: piping into a python script References: <5vrovvF1njt09U6@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Thu, 24 Jan 2008 17:17:25 +0200, Donn Ingle wrote: > > > Given these two examples: > > 1. > > ./fui.py *.py > > 2. > > ls *.py | ./fui.py > > > > How can I capture a list of the arguments? > > I need to get all the strings (file or dir names) passed via the normal > > command line and any that may come from a pipe. > > > > There is a third case: > > 3. > > ls *.jpg | ./fui.py *.png > > Where I would be gathering strings from two places. > > > > I am trying to write a command-line friendly tool that can be used in > > traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. > > > > I have tried: > > 1. pipedIn = sys.stdin.readlines() > > Works fine for example 2, but example 1 goes into a 'wait for input' mode > > and that's no good. Is there a way to tell when no input is coming from a > > pipe at all? > > Usually Linux tools that can get the data from command line or files treat > a single - as file name special with the meaning of: read from stdin. > > So the interface if `fui.py` would be: > > 1. ./fui.py *.a > 2. ls *.a | ./fui.py - > 3. ls *.a | ./fui.py *.b - Did anyone mention the (standard library) fileinput module? (I missed the start of this thread.) http://docs.python.org/lib/module-fileinput.html 11.2 fileinput -- Iterate over lines from multiple input streams This module implements a helper class and functions to quickly write a loop over standard input or a list of files. The typical use is: import fileinput for line in fileinput.input(): process(line) This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From timr at probo.com Tue Jan 22 01:14:10 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 22 Jan 2008 06:14:10 GMT Subject: py2exe and modules question References: Message-ID: <312bp39rg1h896jrufcmhjicrrvs455t4n@4ax.com> azrael wrote: > >I'm working on an application and i'm having some questions. I am >working with python 2.5, numpy and PIL. does anyone know if there are >some problems while compiling the source because of the modules.. It >has to be closed source. What does that mean to you? >I didn't try Py2exe but I heard about it. Is there any other and >better way to compile the source. It isn't really "compiled". What all of the Python-to-executable apps do is bundle up your script, all of its modules, the Python interpreter DLL, and any DLLs they might need, and shove them in a single file (.zip, in the py2exe case). The parts get extracted for execution. The distribution will still contain the .pyc files, and there are tools that can decompile a .pyc without much trouble. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ggpolo at gmail.com Mon Jan 7 13:48:28 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 16:48:28 -0200 Subject: any() and all() shorthand In-Reply-To: References: Message-ID: 2008/1/7, castironpi at gmail.com : > any( iterab ) and all( iterab ) > > as shorthand for reduce( operator.or_, iterab ) and > reduce( operator.and_, iterab ). > > What do you think? > -- > http://mail.python.org/mailman/listinfo/python-list > You are too late, any and all are built-in into python 2.5 -- -- Guilherme H. Polo Goncalves From boblatest at yahoo.com Wed Jan 9 06:21:36 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 11:21:36 GMT Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <87ejcri96v.fsf@mulj.homelinux.net> <87abnfi84i.fsf@mulj.homelinux.net> Message-ID: <5ujp20F1ehvg2U2@mid.dfncis.de> Hrvoje Niksic wrote: > keywords[:] = (s for s in keywords if s) Looks good but is so far beyond my own comprehension that I don't dare include it in my code ;-) robert From n.s.buttar at gmail.com Sun Jan 27 13:40:40 2008 From: n.s.buttar at gmail.com (Navtej Singh) Date: Mon, 28 Jan 2008 00:10:40 +0530 Subject: REALLY simple xml reader In-Reply-To: References: Message-ID: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> check the implementation of XMLNode class here http://hsivonen.iki.fi/group-feed/flickrapi.py HTH N On Jan 27, 2008 11:05 PM, Simon Pickles wrote: > Hi > > Can anyone suggest a really simple XML reader for python? I just want to > be able to do something like this: > > xmlDoc = xml.open("file.xml") > element = xmlDoc.GetElement("foo/bar") > > ... to read the value of: > > > 42 > > > > Thanks > > Simon > > -- > Linux user #458601 - http://counter.li.org. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From Lie.1296 at gmail.com Tue Jan 15 17:02:43 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 15 Jan 2008 14:02:43 -0800 (PST) Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> <87ir1wf1wi.fsf@mulj.homelinux.net> <87k5mbd8bv.fsf@benfinney.id.au> Message-ID: I've been in this Python mailing list for a few days, and I've noticed several things here: There are too many fundamentalist! Don't play stupid and all, don't be a fundamentalist. It might be true that __init__ isn't a constructor and __new__ might be the constructor (some people even claimed __new__ is also not a constructor). >From the base definition of a constructor: constructor is the creator of an object. In this case, __new__ is technically the constructor while __init__ is an initializer. However, it is also to be noted that __init__ is what makes an object meaningful, and that makes it a constructor in a sense (while still technically a constructor). Without initialization, an object is meaningless, even if the definition of the initializer is to leave it as it is. Python creates object by doing something like this: a = anObject(arg1, arg2, arg3) These arguments is then passed to __new__ and __init__ for their arguments in its sake of creating and initializing the object. Then anObject() returns an instance of anObject. >From an outsider's point of view, there is no difference between __new__ and __init__ since they're "implementation details" (in other languages, these are private functions[1] that is invisible to outsiders, Python doesn't like privacy but the semantic of being implementation detail still exist). For an outsider, there is absolutely no need to know that __new__ and __init__ exists, they just need to know anObject()'s arguments, which is the public view of the constructor and initializer[2]. [1] Well, for fundamentalists: constructors aren't usually private though, usually they're Friend or Protected Friend which prohibits outsiders from calling it but allow other classes inheriting from it to call them. [2] In this sense, from outsider's POV anObject() is the constructor. If you can't be convinced with this argument, then I'd give you another that's a bit more Pythonic: DUCK TYPING: If it looks like a duck, walks like a duck, and quacks like a duck, it is a duck! >From the class programmer's point of view, __init__ acts like an object constructor in other languages, there is no significant difference between __init__ and constructor in other languages. The fact that __init__ works with side-effect as opposed to returning the object is not a significant point and can be considered as an implementation difference (I'm not aware of any major programming language that returns an instance of itself in its return value [except for Python]). For example, in VB.NET, there is no doubt that Sub New() is a constructor, despite New() works only by side effect, and returning anything results in an error (since it is a Sub or a method in Python's dictionary). Not only VB, C++ and C# also use side effect in its constructors and doesn't return a value. In this sense, VB's New, C ++ constructor, and C# constructor is equal to Python's __init__, thus the Duck Typing spirit applies here. From brzrkr0 at gmail.com Thu Jan 3 12:39:41 2008 From: brzrkr0 at gmail.com (brzrkr0 at gmail.com) Date: Thu, 3 Jan 2008 09:39:41 -0800 (PST) Subject: C++ equivalent of comp.lang.python? Message-ID: <60597295-1493-493c-969c-a14dd7da98a3@s19g2000prg.googlegroups.com> Hopefully this isn't too OT. One thing I like about comp.lang.python is the breadth of topics discussed here. People can ask about Python installation and configuration issues on specific platforms, compare third party libraries, ask for book recommendations, and discuss current Python projects. Lurking here has greatly increased my understanding of Python over the last year or so. I also do a lot of C++ development, but I've never found a similar discussion group for that language. comp.lang.c++ isn't what I'm looking for. I find it hard to get practical advice on that group because its focus is so narrow. I frequently see posters there redirect people to one of the OS-specific C++ groups, but most of my projects are cross-platform, so hanging out on one of those doesn't make sense either. As an example, I was recently trying to get information about writing cross-platform code for dynamic linking, but I couldn't find anywhere appropriate to ask about it. For those of you who work in C++, where do you go to discuss it online? I'm interested in any newsgroups, mailing lists, or web boards you can recommend. Thanks, Casey From marcroy.olsen at gmail.com Tue Jan 29 03:45:54 2008 From: marcroy.olsen at gmail.com (marcroy.olsen at gmail.com) Date: Tue, 29 Jan 2008 00:45:54 -0800 (PST) Subject: Intra-package References?? (again) Message-ID: Hi Python list, I have been struggleling with this before, but have never been able to find a good solution. The thing I dont understand is, I follow the guide here: http://docs.python.org/tut/node8.html#SECTION008420000000000000000 And have the same setup as the packages howto here:http:// docs.python.org/tut/node8.html#SECTION008400000000000000000 But when I want to use Intra-package References, I need to put the path to the packages explicit like this: #sys.path.append('/path/to/pack/') Before I can make import like this: #from Sound.Effects import echo from within the karaoke.py (just to stay with the tut) If I print the sys.path from the same file, I can see that #/path/to/pack/Sound/Filters/ is in the path. Is there something that I completely is missing or could someone please show me how, by example, how I use Intra-package References. Best regards Marc From jr9445 at ATT.COM Fri Jan 11 13:01:13 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 11 Jan 2008 12:01:13 -0600 Subject: reading a specific column from file In-Reply-To: <4fb9145b-6930-4d89-a4a3-ddd3504373aa@e23g2000prf.googlegroups.com> References: <4fb9145b-6930-4d89-a4a3-ddd3504373aa@e23g2000prf.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 Ivan Novick > Sent: Friday, January 11, 2008 12:46 PM > To: python-list at python.org > Subject: Re: reading a specific column from file > > > You say you would like to "read" a specific column. I wonder if you > meant read all the data and then just seperate out the 3rd column or > if you really mean only do disk IO for the 3rd column of data and > thereby making your read faster. The second seems more interesting > but much harder and I wonder if any one has any ideas. Do what databases do. If the columns are stored with a fixed size on disk, then you can simply compute the offset and seek to it. If the columns are of variable size, then you need to store (and maintain) the offsets in some kind of index. ***** 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 azam.farooq3 at gmail.com Thu Jan 24 03:43:11 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Thu, 24 Jan 2008 00:43:11 -0800 (PST) Subject: ENMAC Mobile Phones, iPods EQ100 www.enmac.com.hk Message-ID: <1bd560ad-b579-49e5-abeb-2111d2843aa6@e25g2000prg.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 sjmachin at lexicon.net Wed Jan 23 15:02:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 12:02:57 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> <12d19814-b7b9-44b0-aee3-299befac7279@i12g2000prf.googlegroups.com> Message-ID: <66446d1e-189c-4c24-bd7a-83cbd66deb60@i12g2000prf.googlegroups.com> On Jan 24, 6:57 am, ryan k wrote: > So yea i will just have to count dashes. Read my lips: *you* counting dashes is dumb. Writing your code so that *code* is counting dashes each time it opens the file is smart. From mr.cerutti at gmail.com Mon Jan 14 13:43:47 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Mon, 14 Jan 2008 13:43:47 -0500 Subject: __init__ explanation please In-Reply-To: References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <873at0mkv7.fsf@mulj.homelinux.net> Message-ID: <51302a8c0801141043s7d11c0b7t3c25e7662cf4dfd7@mail.gmail.com> On Jan 14, 2008 12:08 PM, 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 Hrvoje Niksic > > Sent: Monday, January 14, 2008 11:29 AM > > Only if by "construct" you mean "allocate". __init__ starts out with > > an empty object and brings it to a valid state, therefore > > "constructing" the object you end up with. That operation is exactly > > what other languages call a constructor. > > Nah. Most other languages combine the constructor and an init function. > Normally with c++ I'll have the constructor call an Init() function so I > can re-initialize the object as needed. Python has explicitly split the > two. > Besides, the Python docs say that __new__ is the constructor and > __init__ may or may not be called after the instance is created: The documentation of __new__ carefully refrains from calling __new__ a constructor. Both __new__ and __init__ mention the object constructor expression, e.g., "list()". > __init__( self[, ...]) > Called when the instance is created. > ... > As a special constraint on constructors, no value may be > returned; Once again, the documentation is referring to constructor expressions. As you noted, __init__ may return a value when not called by a constructor expression. C++'s constructor initialization lists are the closest thing to Python's __new__. They can perform tasks for which Python might need __new__. For example, a class member that's a reference must be initialized in the initialization list, because it cannot be set once the body of the constructor begins. -- Neil Cerutti From jr9445 at ATT.COM Wed Jan 9 15:34:26 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 9 Jan 2008 14:34:26 -0600 Subject: problem of converting a list to dict In-Reply-To: References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com><962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.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 John Machin > Sent: Wednesday, January 09, 2008 3:02 PM > To: python-list at python.org > Subject: Re: problem of converting a list to dict > > On Jan 10, 6:52 am, "Reedick, Andrew" wrote: > > > > A bigger hint: > > a=i.split('=') > > print "'%s' splits into " % (i), a > > consider: > (1) using %r instead of '%s' Eh, personal preference depending on how sure you are of the data's type. > (2) omitting the redundant space after 'into' Some of us coming in from other languages and still aren't used to the comma adding an unwanted space after everything. I've been tempted to root around in Python's source code to fix the problem. > (3) losing the redundant () around i For me, the () is there for readability. Python's sprintf syntax is odd to begin with, and something like print "'%s' splits into " % i, a, b, c means either 1) you really do want to append b and c after the sprintf, or print "'%s' splits into " % (a), b, c 2) that the formatting string is missing a few things print "'%s' splits into " % (a, b, c) ## Ooops! forgot to change it to "%s %5.2d %6.3f" ***** 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. GA622 From steve at REMOVE-THIS-cybersource.com.au Mon Jan 21 17:09:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 22:09:29 -0000 Subject: Bug in __init__? References: <88580064-3590-471e-8036-a631dd5a38b4@i3g2000hsf.googlegroups.com> <50ed76e4-f865-4821-935f-310c96b0ecb9@e23g2000prf.googlegroups.com> Message-ID: <13pa60pgj3hur7d@corp.supernews.com> On Mon, 21 Jan 2008 17:38:10 -0200, Gabriel Genellina wrote: > En Mon, 21 Jan 2008 05:59:38 -0200, escribi?: > >> Is there no way of adding a possible warning message (that obviously >> could be turned off) to warn users of possible problems linked to using >> mutable types as parameters? >> >> Seems to me this could save users a few minutes/hours of headaches and >> headscratching. (The biggest issue affecting new programmers these >> days!) > > Most objects are mutable, such warning would happen so often that would > become useless. Not at all, for two reasons: (1) Using mutable defaults in function definitions is relatively unusual. Defaults like None, 0, 1 are far more common. (2) We can copy the behaviour of the warnings module. Possibly even use the warnings module. By default warnings are only shown once per session. > The only immutable objects are numbers, strings, tuples, None and a few > esoteric types; all other instances, including instances of all user > defined classes, are mutable unless explicitely their attributes are > read-only. It is true that Python doesn't have a cheap way of recognising mutable instances except by trying to mutate them. However, there is a case for having it issue a warning the first time in a session it spots a default list or dict, which would catch 99% of cases that newbies use a mutable default. Newbies being newbies, 30% of them will completely ignore the warning and bitch about the "bug", but that's better than the 80% that we have now :-) -- Steven From bearophileHUGS at lycos.com Sat Jan 26 05:02:31 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 26 Jan 2008 02:02:31 -0800 (PST) Subject: Generational Interfaces References: <1b7b3b47-72f0-4a5d-9185-4903e75dba47@d70g2000hsb.googlegroups.com> Message-ID: <833108f1-d5fa-4e10-b458-344551ec35bd@d4g2000prg.googlegroups.com> I think they can be called "soft interfaces" or "heuristic interfaces", it's an example of machine learning. I think it's not easy to apply such idea to a statically typed language, but probably it can be done on Java. I presume in the future GUI will learn more about the usage patterns of their users, data structures of long- running programs will adapt to their average usage in each specific point of the program, and maybe class interfaces too will become smarter, as you say :-) I think your idea can be implemented in Python too, so you just have to try to use it in some project of yours developed with some Agile programming style, so you can tell us if it's nice to use :-) Bye, bearophile From lizm at rcsltd.co.uk Thu Jan 24 08:59:52 2008 From: lizm at rcsltd.co.uk (LizzyLiz) Date: Thu, 24 Jan 2008 05:59:52 -0800 (PST) Subject: csv to xls using python 2.1.3 References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> Message-ID: Unfortunately we have to stick with python 2.1.3 for this project. From dzizes451 at gmail.com Wed Jan 30 12:32:02 2008 From: dzizes451 at gmail.com (dzizes) Date: Wed, 30 Jan 2008 09:32:02 -0800 (PST) Subject: Python plugins for netbeans 6 IDE? In-Reply-To: <46F5F8FE.2020208@sbcglobal.net> References: <46F5F8FE.2020208@sbcglobal.net> Message-ID: <15186891.post@talk.nabble.com> Did you managed to work out NetBeans and Python? Ken McDonald wrote: > > Do any such exist? And do you find them worthwhile? I couldn't see any > browsing the netbeans pages, but that doesn't mean they're not out > there... > > Thanks, > Ken > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Python-plugins-for-netbeans-6-IDE--tp12843005p15186891.html Sent from the Python - python-list mailing list archive at Nabble.com. From gherron at islandtraining.com Thu Jan 17 03:47:13 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 17 Jan 2008 00:47:13 -0800 Subject: Replace stop words (remove words from a string) In-Reply-To: <01be01c858e4$c6b8b280$542a1780$@com> References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> <01be01c858e4$c6b8b280$542a1780$@com> Message-ID: <478F1611.4080001@islandtraining.com> Karthik wrote: > How about - > > for s in stoplist: > string.replace(mystr, s, "") > That will work, but the string module is long outdated. Better to use string methods: for s in stoplist: mystr.replace(s, "") Gary Herron > Hope this should work. > > -----Original Message----- > From: python-list-bounces+karthik3186=gmail.com at python.org > [mailto:python-list-bounces+karthik3186=gmail.com at python.org] On Behalf Of > BerlinBrown > Sent: Thursday, January 17, 2008 1:55 PM > To: python-list at python.org > Subject: Replace stop words (remove words from a string) > > if I have an array of "stop" words, and I want to replace those values > with something else; in a string, how would I go about doing this. I > have this code that splits the string and then does a difference but I > think there is an easier approach: > > E.g. > > mystr = > kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsldf > sd; > > if I have an array stop_list = [ "[BAD]", "[BAD2]" ] > > I want to replace the values in that list with a zero length string. > > I had this before, but I don't want to use this approach; I don't want > to use the split. > > line_list = line.lower().split() > res = list(set(keywords_list).difference(set(ENTITY_IGNORE_LIST))) > > > From bignose+hates-spam at benfinney.id.au Sun Jan 27 22:33:42 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 28 Jan 2008 14:33:42 +1100 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <8763xe8vzd.fsf@benfinney.id.au> "Russ P." writes: > On Jan 27, 5:13 pm, Wildemar Wildenburger > wrote: > > class Server(object): > > def __init__(self, self.host, self.port, > > self.protocol, self.bufsize, self.timeout): > > pass > > > > ? > > That makes sense to me. Not to me. 'self' is a name that doesn't exist until *after* that 'def' statement is completed; in any other statement, that would mean 'self.foo' in the same statement would raise a NameError. Special-casing it for a function declaration complicates the language for little gain: the rules of what is valid when become more complicated. Special cases aren't special enough to break the rules. -- \ "I took a course in speed waiting. Now I can wait an hour in | `\ only ten minutes." -- Steven Wright | _o__) | Ben Finney From fredrik at pythonware.com Wed Jan 9 15:59:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 21:59:34 +0100 Subject: ISO books of official Python docs In-Reply-To: References: Message-ID: Doug Morse wrote: > Several of the O'Reilly & Assoc. books -- such as Python in a Nutshell, The > Python Standard Library, etc -- are in large part reproductions of the > official docs and references. if you're using "reproduction" to mean "copy", I think you owe both me and Alex a big apology. From gagsl-py2 at yahoo.com.ar Wed Jan 30 08:24:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jan 2008 05:24:14 -0800 (PST) Subject: Removing hidden files and folders with python ... References: Message-ID: <001c398a-d48a-431b-95b1-da407da96122@i3g2000hsf.googlegroups.com> On 30 ene, 06:21, Konrad M?hler wrote: > I try to delete a whole directory-tree using shutil.rmtree(...) > But there are always the hidden files and folders (e.g. from the svn > .svn) left. > > How can I delete -all- files and folders (also the hidden) with python? I assume you use Windows. You have to reset the "readonly", "system" and "hidden" directory attributes. os.chmod can reset the first one, but for the others you have to use ctypes or the pywin32 package to call the SetFileAttributes function. Of course there is system too: os.system("attrib -r -h -s filename") You could use rmtree once, apply the above on the remaining files and directories -if any- and try rmtree again. -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Tue Jan 15 16:38:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 15 Jan 2008 21:38:32 -0000 Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: <13oq9uo2rjruhb6@corp.supernews.com> On Tue, 15 Jan 2008 11:25:25 -0500, Colin J. Williams wrote: > I'm sorry, there appears to be a bug: # tSet.py > import sets > s1= sets.Set([1, 2, 3]) > s1.union_update([3, 4,5]) > print(s1) > s2= sets.Set([6, 7, 8]) > s1 |+ s2 # This fails: > exceptions.TypeError: bad operand type for unary +: 'Set' And so it should fail. Did you mean |= instead of |+ ? -- Steven From mani.sabri at gmail.com Tue Jan 29 02:06:49 2008 From: mani.sabri at gmail.com (mani) Date: Mon, 28 Jan 2008 23:06:49 -0800 (PST) Subject: Embeding python with mingw on win32 and python 2.4.4 References: <563a8060-8d79-4bc8-8306-9a5d77bfae5e@i72g2000hsd.googlegroups.com> Message-ID: <1eb2d4eb-e229-4230-a0e6-13dacf3a644e@s13g2000prd.googlegroups.com> It's me answering my self. I found the solution in http://groups.google.com/group/comp.lang.python/browse_thread/thread/4d80df2e53dfa127/de87533c05d8021c?lnk=gst&q=Py_Initialize+undefined+reference#de87533c05d8021c It was the problem of gcc arguments order. From faber at linuxnj.com Sat Jan 12 10:29:30 2008 From: faber at linuxnj.com (Faber J. Fedor) Date: Sat, 12 Jan 2008 10:29:30 -0500 Subject: where do my python files go in linux? In-Reply-To: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> Message-ID: <20080112152930.GA28685@neptune.faber.nom> On 12/01/08 12:02 +0100, Jorgen Bodde wrote: > Hi All, > > I am trying to make a debian package. I am following the tutorial by > Horst Jens (http://showmedo.com/videos/video?name=linuxJensMakingDeb&fromSeriesID=37) > and it is very informative. However one thing my app has and his > doesn't, is multiple python files which need to be executed. For > example > > {dir}/app > app.py > > app.py calls a lot of modules in {dir}/app. Horst says the python file > goes in /usr/bin/app.py which is ok with me, but I have multiple > python files, and I decided to use an app.sh script to call my python > files. In the /usr/bin I do not see subdirs so I assume that is not > really desirable. > > Question 1. Where do I put the bulk of python scripts in a normal > linux environment? I would think you'd create a directory /usr/bin/app and then symlink /usr/bin/app.py to /usr/bin/app/app.py. > Question 2. Should I use *.pyc rather then *.py files to speed up > executing as the user cannot write to /usr/bin or any other dir in the > system and everytime my app runs it will recompile it That would make sense. > Thanks for any advice or maybe a good tutorial how to set up files in > a linux environment http://www.pathname.com/fhs/ (couldn't find a more recent version, sorry.) -- Regards, Faber Fedor President Linux New Jersey, Inc. 908-320-0357 800-706-0701 http://www.linuxnj.com -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From __peter__ at web.de Mon Jan 7 09:40:40 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 7 Jan 2008 15:40:40 +0100 Subject: introspection question References: Message-ID: Alex K wrote: > What would be the simplest way of enumerating all methods and members > (including inherited) of a given object? Thank you. inspect.getmembers() Peter From kyosohma at gmail.com Wed Jan 2 10:49:20 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 2 Jan 2008 07:49:20 -0800 (PST) Subject: how to get playtime ( playback time ) of movie files? References: <7ab948ea-0ea9-47ab-80ff-73a95a4d958d@d21g2000prf.googlegroups.com> Message-ID: On Jan 2, 6:39 am, "Geon." wrote: > hi.. i want get playtime of movie files ( avi , mpeg , wav , mov > etc... ) > > how to get ?? > > please help me .. Take a look at PyMedia: http://pymedia.org/ Mike From nick at craig-wood.com Mon Jan 14 06:30:04 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 14 Jan 2008 05:30:04 -0600 Subject: where do my python files go in linux? References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> Message-ID: Jeroen Ruigrok van der Werven wrote: > -On [20080112 12:03], Jorgen Bodde (jorgen.maillist at gmail.com) wrote: > >app.py calls a lot of modules in {dir}/app. Horst says the python file > >goes in /usr/bin/app.py which is ok with me, but I have multiple > >python files, and I decided to use an app.sh script to call my python > >files. In the /usr/bin I do not see subdirs so I assume that is not > >really desirable. > > Personally I'd be loathe to put app.py in /usr/bin. This directory is normally > reserved for OS-specific binaries. For personal/system-extended stuff I'd use > /usr/local/bin or whatever your system mandates. I'd agree with that, except for the fact that he is making a .deb to be installed by the package manager. In Debian... /usr/bin is for stuff installed by the package manager which becomes effectively part of the OS. The package manager tracks every file it installes to ensure ovewrites can't happen etc... /usr/local/bin is for stuff installed from source, not using the package manager. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From kar1107 at gmail.com Sat Jan 26 04:03:40 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Sat, 26 Jan 2008 01:03:40 -0800 (PST) Subject: finding child cpu usage of a running child References: Message-ID: <4489d6b7-2462-4740-88ea-4fdd2739a84e@q39g2000hsf.googlegroups.com> On Jan 25, 11:59 pm, Paddy wrote: > On Jan 26, 5:43 am, Karthik Gurusamy wrote: > > > > > Hi, > > > Wondering if there is a way to measure a child process's cpu usage > > (sys and user) when the child is still running. I see os.times() > > working fine in my system (Linux 2.6.9-42.7.ELsmp), but it gives valid > > data only after the child has exited. When the child is alive, > > os.times() data for child is zero for both child-sys and child-user > > cpu. > > > My script (process P1) launches child process P2 (using > > popen2.Popen3). P2 is a long running process (big compilation). Every > > minute or so, from P1, I want to measure how much cpu P2 has consumed > > and based on that I can make some estimate on the completion time of > > P2 (I have a rough idea how much total cpu P2 needs to complete). > > > I understand it may be too expensive to update this information to the > > parent process when any of the child/grand-child completes; but > > wondering if any there is any way to get this info; the expensive > > operations is on-demand only when the request is made. > > > Thanks, > > Karthik > > I had a similar requirement in December and found: > http://lilypond.org/~janneke/software/ > > proc-time.c and proc-time.py poll /proc/.... files whilst command > is running to get stats. Great, thanks. From proc-time.py looks like all I want are the fields 13 to 16 of /proc//stat. And I see them updated in real time (probably the kernel does it on a periodic interrupt). Thanks, Karthik > > Enjoy, - Paddy. From paul at boddie.org.uk Fri Jan 25 18:17:24 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 25 Jan 2008 15:17:24 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> Message-ID: <45a8d4a7-d24d-461e-9783-59a7d697a041@q77g2000hsh.googlegroups.com> On 25 Jan, 22:06, "Lorenzo E. Danielsson" wrote: > > What you need then is something like SVGAlib (http;//svgalib.org). Only > really old people like myself know that it exists. I've never heard of > any Python bindings for it, but that might be where you come in. I > haven't looked at SVGAlib for years, and I'm not sure about the state of > the video drivers. I suggest you look at that first. I believe that SVGAlib was superseded by GGI and other projects, and I recall that SVGAlib was considered to be something of a nightware with respect to how it handles various resources. Certainly, I haven't been very impressed by the behaviour of software using it. > You could also look at GGI (http://ggi-project.org). GGI has different > output targets. IIRC, one of them is directfb. To tell you the truth > I've never really used GGI. There seems to be a python wrapper for GGI, > although it is fairly old. Maybe you could look at the code for some ideas. I've had to build software using GGI, and the biggest problem has been getting packages for it. That said, it seemed to work fairly acceptably once built and installed. Meanwhile, some people favour Allegro [1] for this kind of work, and I've been confronted with newly developed software which uses Allegro, so it's arguably in a different maintenance state than something like SVGAlib or GGI. > You should also be able to compile SDL to be able to use directfb as a > target. If your libSDL handles it, then that should apply to wrapper > libraries as well, including pygame. I've never tried running SDL apps > this way, but if it works well, that would probably be your 'best' option. I'd agree with these sentiments; SDL seems to be the best supported technology of this kind in the Python universe, and one of the most widely deployed in general; I've felt quite comfortable building software against it. It would be very interesting to see whether a framebuffer-based SDL could support Pygame, and I imagine that the Pygame mailing list might already have some answers in its archives on this topic. Paul [1] http://www.talula.demon.co.uk/allegro/ From nagle at animats.com Fri Jan 18 01:32:25 2008 From: nagle at animats.com (John Nagle) Date: Thu, 17 Jan 2008 22:32:25 -0800 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. In-Reply-To: <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> References: <478FAC5A.50206@animats.com> <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> Message-ID: <479046a5$0$36403$742ec2ed@news.sonic.net> Irmen de Jong wrote: > Christian Heimes wrote: >> John Nagle wrote: >>> It's possible to use "pickle" for interprocess communication over >>> pipes, but it's not straightforward. >> >> IIRC the processing module uses pickle for IPC. Maybe you can get some >> idea by reading its code? >> >> http://pypi.python.org/pypi/processing/0.40 >> "Processing" is useful, but it uses named pipes and sockets, not ordinary pipes. Also, it has C code, so all the usual build and version problems apply. > So does Pyro: http://pyro.sourceforge.net/ > > However Pyro uses TCP-IP sockets for communication. > > It uses a small header that contains the size of the message and a few > other things, and then the (binary by default) pickle stream. I'd thought I might have to add another layer of encapsulation to delimit "pickled" sections, but it turns out that's not necessary. So it doesn't take much code to do this, and it's all Python. I may release this little module. John Nagle From martin at librador.com Tue Jan 8 12:35:31 2008 From: martin at librador.com (Martin Vilcans) Date: Tue, 8 Jan 2008 19:35:31 +0200 Subject: I'm searching for Python style guidelines In-Reply-To: References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: On 1/7/08, Guilherme Polo wrote: > 2008/1/7, MartinRinehart at gmail.com : > > Anything written somewhere that's thorough? Any code body that should > > serve as a reference? > > PEP 8 > http://www.python.org/dev/peps/pep-0008/ The problem with PEP 8 is that even code in the standard libraries doesn't follow the recommendations regarding the naming of functions for example. The recommendation is to_separate_words_with_underscore, but some code uses lowerCamelCase instead. I tended to dislike the underscore convention, but after forcing myself to use it for a while I'm starting to appreciate its beauty. -- martin at librador.com http://www.librador.com From mr.cerutti at gmail.com Tue Jan 8 13:10:01 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Tue, 8 Jan 2008 13:10:01 -0500 Subject: I'm searching for Python style guidelines In-Reply-To: References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: <51302a8c0801081010x5f5110fn23594d83592b0036@mail.gmail.com> On Jan 8, 2008 12:35 PM, Martin Vilcans wrote: > On 1/7/08, Guilherme Polo wrote: > > 2008/1/7, MartinRinehart at gmail.com : > > > Anything written somewhere that's thorough? Any code body that should > > > serve as a reference? > > > > PEP 8 > > http://www.python.org/dev/peps/pep-0008/ > > The problem with PEP 8 is that even code in the standard libraries > doesn't follow the recommendations regarding the naming of functions > for example. The recommendation is to_separate_words_with_underscore, > but some code uses lowerCamelCase instead. > > I tended to dislike the underscore convention, but after forcing > myself to use it for a while I'm starting to appreciate its beauty. Conventions get broken when there's a good reason, e.g., elegant looking "deque" instead of clumsy looking "Deque". -- Neil Cerutti From Lie.1296 at gmail.com Mon Jan 14 14:09:43 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 14 Jan 2008 11:09:43 -0800 (PST) Subject: How to get user home directory on Windows References: <478ab8a1$0$20930$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <64437192-cb78-4659-a06b-febe1b8ea9b5@u10g2000prn.googlegroups.com> On Jan 14, 8:21?am, "Martin P. Hellwig" wrote: > Giampaolo Rodola' wrote: > > Hi all, > > I'm trying to use the pywin32 extension to find out the user's home > > directory but currently I didn't find a solution yet. > > What I'd need to do is not getting the home directory of the currently > > logged in user but something like: > > >>>> get_homedir("frank") > > "C:\home\users\frank" > >>>> get_homedir("josh") > > "C:\home\users\josh" > > > Is there a way to do that? > > I tried to search through the Pywin32 documentation with no luck. > > In addition I'm not practiced with the Windows API at all. > > Well, windows, to my knowledge, uses the same base path for all profiles > (this is not true for the My Documents folder which can differ). So what > you could do is get the location from the ALLUSERPROFILE environment > variable, go one folder higher and iterate through that. > Ignoring the folders for the 'pseudo' users: 'All Users', 'Default > User', 'LocalService' and 'NetworkService'. > > hth > -- > mph There is one problem with that, sometimes the folders for the users are not the same with the user name, usually because of deleting user name without deleting the profile, then recreate a user with similar name. It doesn't happens everytime, but it could. Possibly it is possible to get the SID of the user name (using the way described in Tim Golden's Microsoft Link' post), then find the user directory from the registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft \Windows NT\CurrentVersion\ProfileList\[PUT SID HERE]\Profile Image Path From siona at chiark.greenend.org.uk Wed Jan 16 09:31:05 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 16 Jan 2008 14:31:05 +0000 (GMT) Subject: UTF-8 in basic CGI mode References: <1f8a4051-27cb-48aa-a0ab-793f59ab3845@s13g2000prd.googlegroups.com> Message-ID: coldpizza wrote: >I am using this 'word' variable like this: > >print u'''''' % (word) > >and apparently this causes exceptions with non-ASCII strings. > >I've also tried this: >print u'''''' % >(word.encode('utf8')) >but I still get the same UnicodeDecodeError.. Your 'word' is a byte string (presumably UTF8 encoded). When python is asked to insert a byte string into a unicode string (as you are doing with the % operator, but the same applies to concatenation with the + operator) it attempts to convert the byte string into unicode. And the default encoding is 'ascii', and the ascii codec takes a very strict view about what an ASCII character is -- and that is that only characters below 128 are ASCII. To get it to work, you need to *decode* word. It is already UTF8 (or something) encoded. Under most circumstances, use encode() to turn unicode strings to byte strings, and decode() to go in the other direction. -- \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 vangale at gmail.com Thu Jan 31 15:23:51 2008 From: vangale at gmail.com (Van Gale) Date: Thu, 31 Jan 2008 14:23:51 -0600 Subject: sending a handmade SOAP request References: <21d3ff54-d20f-45dd-951b-0508682fc472@e6g2000prf.googlegroups.com> Message-ID: On Thu, 31 Jan 2008 11:03:26 -0800, Bernard wrote: > Hey y'all, > > Is there a way to POST a handmade SOAP request *without* using any > libraries like SOAPpy? Yes, it's quite easy to SOAP by hand. I use Oren Tirosh's ElementBuilder class (on top of lxml instead of ElementTree) to build the SOAP request and the xpath capabilities in lxml to pull out the data I need from the response. http://www.tothink.com/python/ElementBuilder/ http://codespeak.net/lxml/ An incomplete example for contructing a request looks something like this: body = Element('soap:Envelope', { 'xmlns:soap': nss['soap']}, Element('soap:Header'), Element('soap:Body', { 'xmlns:msgs': nss['msgs'] }, Element('msgs:login', Element('msgs:passport', { 'xmlns:core': nss['core'] }, Element('core:password', password), Element('core:account', account))))) I use httplib2 for sending the HTTP requests: http://code.google.com/p/httplib2/ Incomplete example: headers['SOAPAction'] = action headers['Content-length'] = str(len(etree.tostring(body))) response, content = self._client.request( self.ns_uri, "POST", body=etree.tostring(body), headers=self._headers) if response.status == 500 and not \ (response["content-type"].startswith("text/xml") and \ len(content) > 0): raise HTTPError(response.status, content) if response.status not in (200, 500): raise HTTPError(response.status, content) doc = etree.parse(StringIO(content)) if response.status == 500: faultstring = doc.findtext(".//faultstring") raise HTTPError(response.status, faultstring) Now it's just a matter of using xpath expressions to dig into the "doc" structure for the bits you need. From python.list at tim.thechases.com Wed Jan 30 09:06:28 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 30 Jan 2008 08:06:28 -0600 Subject: find nearest time in datetime list In-Reply-To: <47a07fa6$1_1@news.bluewin.ch> References: <47a07fa6$1_1@news.bluewin.ch> Message-ID: <47A08464.10901@tim.thechases.com> Boris Borcic wrote: > min(DTlist,key=lambda date : abs(dt-date)) In Python2.4: Traceback (most recent call last): File "", line 1, in ? TypeError: min() takes no keyword arguments Looks like min() only started taking keywords (key) from Python2.5 forward. But the min() solution is good if you're running 2.5 -tkc From stephen at theboulets.net Wed Jan 9 00:42:21 2008 From: stephen at theboulets.net (Stephen_B) Date: Tue, 8 Jan 2008 21:42:21 -0800 (PST) Subject: Default location of python on OS X References: <1519661f-97bd-4fdd-b2d5-a46dd9a81c81@e25g2000prg.googlegroups.com> Message-ID: On Jan 8, 11:33 pm, Tommy Nordgren wrote: > > I still have a "/Library/Python/2.3" and a "/Library/Python/2.5". > > > Thanks. > > > Stephen > Leopard INCLUDES Python 2.5, there is no need to install it. Thanks -- that made the decision easy. I didn't need all those MacPythons. Stephen From gdamjan at gmail.com Fri Jan 11 11:23:55 2008 From: gdamjan at gmail.com (Damjan) Date: Fri, 11 Jan 2008 17:23:55 +0100 Subject: virtualpython / workingenv / virtualenv ... shouldn't this be part of python Message-ID: <4787981c$0$90268$14726298@news.sunsite.dk> There are several attempts to allow python to work with per user (or even per session) 'site-packages' like virtualpython / workingenv / virtualenv. But they all have their own shortcomings and quirks. My question is, shoudn't it be enough to set PYTHONPATH and everything automagically to work then? Is there some work done on this for python 3.0 or 2.6 perhaps? -- damjan From hexamorph at gmx.net Fri Jan 25 17:09:38 2008 From: hexamorph at gmx.net (Hexamorph) Date: Fri, 25 Jan 2008 23:09:38 +0100 Subject: looking for a light weighted library/tool to write simple GUI above the text based application In-Reply-To: <479A4F71.9060501@gmail.com> References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> <479A4F71.9060501@gmail.com> Message-ID: <479A5E22.30703@gmx.net> Lorenzo E. Danielsson wrote: > petr.jakes.tpc at gmail.com wrote: >> I think I was not specific/clear enough in my first posting. I know >> the curses library ( http://pyncurses.sourceforge.net ). It AFIK >> provides TUI (short for: Text User Interface or Textual User >> Interface). My needs are GUI, I mean "a nice VGA pictures" on the VGA >> LCD 10" display. >> >> Petr > > What you need then is something like SVGAlib (http;//svgalib.org). Only > really old people like myself know that it exists. I've never heard of > any Python bindings for it, but that might be where you come in. I > haven't looked at SVGAlib for years, and I'm not sure about the state of > the video drivers. I don't think that there's a Python binding for it. Svgalib never has gained enough popularity for anybody to write such bindings. However, as long as the video card supports VGA or VESA it should work. Another possibility might be using Xvesa (KDrive) which is a really tiny self-containing X server for VGA/SVGA/FBdev. With this you can atleast use simple GUI toolkits like Athena or TK or even use Xlib directly (if you don't fear that adventure) See: http://www.xfree86.org/current/Xvesa.1.html http://www.pps.jussieu.fr/~jch/software/kdrive.html HTH From Scott.Daniels at Acm.Org Tue Jan 1 13:12:40 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 01 Jan 2008 10:12:40 -0800 Subject: using super In-Reply-To: <4649f96c-10af-4dd1-864c-f0690cec1980@p69g2000hsa.googlegroups.com> References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> <13nk5l6oah7mh9b@corp.supernews.com> <4649f96c-10af-4dd1-864c-f0690cec1980@p69g2000hsa.googlegroups.com> Message-ID: <13nl0cg1sj0mpea@corp.supernews.com> iu2 wrote: > On Jan 1, 12:32 pm, Steven D'Aprano cybersource.com.au> wrote: >> import read_my_mind_and_do_what_I_want >> first. (Module expected in Python 9.7, due out in 2058.) > > That's because it seems to you like some esoteric feature. > To me it seems natural with OO. And the language should not bend to the sense of "natural" of one with a minor commitment to building that language. If this really is a great idea, implement it, put it out, support it and respond to the rigors of real use. You'll not convince me, but you needn't. Too many people want to go to a PEP (or even skip that step) once they have an idea they think might be good. The lesson I take from the histories of Ada and C++ are that "the less in the language the better." It is not enough that a language be chock-a-block with good ideas; each idea in the language must be compelling enough to counter-balance the mass that adding that idea adds. >> "Special cases aren't special enough to break the rules." > > I thought about this mechanism each time I had to call a base class > method. Lisp has it, out of the box. May be it's not so special... We accept this seems natural to you. You don't seem to understand why others might not think so. I fear this is the kind of thing that separates programmers into two classes: the smart ones that can set up the chains, and the others to whom you say "don't worry your pretty little head about it; it all happens auto-magically." Python is remarkably free of such things, and I am loathe to give that up. The value reduced auto-magic is that the users of the language can learn smoothly, rather than climbing steep mountains of understanding. Since you are relatively new to the language (I presume so, since you left self out of several method definitions), see how the language works on its terms first, before suggesting how to make it more like some other language you like. The explicit super call inside a method, and the disposition of its results makes experimentation with different ways to use the result tempting. There is a temptation to play with the arguments as well, that runs afoul of the vagaries of multiple inheritance, that is the reason that I said "if they don't want to understand super, then just explicitly name the superclass." --Scott David Daniels Scott.Daniels at Acm.Org From kar1107 at gmail.com Tue Jan 1 03:25:25 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 1 Jan 2008 00:25:25 -0800 (PST) Subject: pexpect ssh login and ls | grep References: <3eb81375-3e4a-4e0f-a4e7-bbb1d6cd0f8c@s19g2000prg.googlegroups.com> Message-ID: On Dec 31 2007, 6:46 pm, crybaby wrote: > 1) what are these characters: > \x1b]0; > ~\x07\x1b[?1034h > > in line '\x1b]0;my at mycomp2:~\x07\x1b[?1034h[my at mycomp2 ~]'? These are probably escape sequences in your shell prompt string. Typically they are interpreted by the terminal, like xterm, to update title bar. > > 2) Also, how come I don't get 0 or 2(excuting ls command exit code) > from result.split('\r\n')[0] or result.split('\r\n')[1] ? I don't think your expect worked fine to capture the desired output. > > This is what I get:>>> import pexpect > >>> child=pexpect.spawn('ssh my at mycomp2') > >>> child.sendline("ls mytest.log > /dev/null 2>&1; echo $?") > 41 > >>> child.before > >>> print child.before > None > >>> print child.after > None before/after makes sense only after an expect. At this point there is only a sendline; not expect. So the above None output is expected. > >>> child.expect([pexpect.TIMEOUT, '\$ ']) > 1 1 implies it matched the second pattern. You want to use raw strings. r'\$' or else the re sent down is a plain $ which re interprets as end of buffer. Most important here is your prompt doesn't end with a $ (it's something like [my at mycomp2 ~]). Thus make it, child.expect(r'.*]') Try the ls command and rest of the statements. Karthik > >>> result=child.before > >>> print result.split('\r\n')[1] > [my at mycomp2 ~] > >>> print result.split('\r\n')[0] > > Last login: Mon Dec 31 20:52:09 2007 from com1>>> print result.split('\r\n') > > ['Last login: Mon Dec 31 20:52:09 2007 from com1\r', > '\x1b]0;my at mycomp2:~\x07\x1b[?1034h[my at mycomp2 ~]'] From bearophileHUGS at lycos.com Tue Jan 15 14:27:04 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 15 Jan 2008 11:27:04 -0800 (PST) Subject: Data mapper - need to map an dictionary of values to a model References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com> <05398cdb-4c75-499b-bb52-d5de627a0906@j20g2000hsi.googlegroups.com> <49753620-df70-4f1a-95bc-7b23667d9edc@s13g2000prd.googlegroups.com> Message-ID: <5da17900-4404-407a-a406-b25a01035a96@l32g2000hse.googlegroups.com> Luke: > I'm not familiar with this pattern. I will search around, but if you > have any links or you would like to elaborate, that would be > wonderful. :) It's not a pattern, it's a little thing: def line_filter(filein, params): for line in filein: if good(line, params): yield extract(line, params) That equals to this too: def line_filter(filein, params): return (extract(line, params) for line in filein if good(line, params)) But probably that's not enough to solve your problem, so other people can give you a better answer. Bye, bearophile From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 04:15:32 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 10:15:32 +0100 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> Message-ID: <478733a9$0$18055$426a34cc@news.free.fr> Ross Ridge a ?crit : > Bruno Desthuilliers wrote: >> And the reference implementation of Python (CPython) is not >> interpreted, it's compiled to byte-code, which is then executed by a VM >> (just like Java). > > Ed Jensen a ?crit : >> Wow, this is pretty misleading. > > Bruno Desthuilliers wrote: >> Ho yes ??? Why so, please ? Care to point to anything *wrong* in the >> above statement ? > > Python's byte-code interpreter is not "just like" Java's virtual machine. of course it's not "just like" - different languages, different byte-codes, different implementations. What is "just like" is the byte-code/VM scheme. Thought this was obvious to anyone able to parse a simple sentence. > You're deliberately trying to mislead people into thinking Python performs > similarily to Java. I don't know what you're smoking, but you should perhaps stop - because this seems to drive you into parano?d delirium. From arnodel at googlemail.com Tue Jan 29 08:07:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 29 Jan 2008 05:07:17 -0800 (PST) Subject: extending Python - passing nested lists References: Message-ID: <3ddeaf07-3f4b-4d68-a176-9205fa4d234b@k39g2000hsf.googlegroups.com> On Jan 29, 12:48?pm, Christian Meesters wrote: > Think, that I'm still at the wrong track. Point is that I cannot find any > examples and don't know where to start here. > Perhaps my problem boils down to two questions: > I'd like to pass lists (in some cases nested ones) from Python to C and > convert those Python-lists to C-arrays (e. g. of doubles). My second wish > is to return a C-array of longs to a Python list. > > My approach so far: > > static PyObject *_foo(PyObject *self, PyObject *args) { > ? double *v; > ? if (!PyArg_Parse(args, "(d)", &v)) > ? ? return NULL; > ? // then I can't access v like v[1] ... I'm not a C API guru and I may not understand properly what info you are looking for but from http://docs.python.org/api/sequence.html: PyObject* PySequence_GetItem( PyObject *o, Py_ssize_t i) Return value: New reference. Return the ith element of o, or NULL on failure. This is the equivalent of the Python expression "o[i]". > ? > ? // then return *v > ? return with something like PyBuildValue (but didn't get so far) This allows you to create a list (from http://docs.python.org/api/listObjects.html): PyObject* PyList_New( Py_ssize_t len) Return value: New reference. Return a new list of length len on success, or NULL on failure. Note: If length is greater than zero, the returned list object's items are set to NULL. Thus you cannot use abstract API functions such as PySequence_SetItem() or expose the object to Python code before setting all items to a real object with PyList_SetItem(). ...and this allows you to populate it (from http://docs.python.org/api/listObjects.html): int PyList_Append( PyObject *list, PyObject *item) Append the object item at the end of list list. Return 0 if successful; return -1 and set an exception if unsuccessful. Analogous to list.append(item). > > } > > Can somebody give me a hint here, please? Passing simple arguments to and > fro (e. g. single integer values) is no problem, but lists of unknown size? HTH -- Arnaud From bj_666 at gmx.net Thu Jan 10 18:44:01 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Jan 2008 23:44:01 GMT Subject: adding methods at runtime References: <940fcb28-764e-46ab-a627-aff513e009e1@j78g2000hsd.googlegroups.com> Message-ID: <5unou0F1ifu47U1@mid.uni-berlin.de> On Thu, 10 Jan 2008 14:55:18 -0800, zslevi at gmail.com wrote: > Can I access the class attributes from a method added at runtime? (My > experience says no.) > I experimented with the following code: > > [Code snipped] > > So it seems to me, if you add a method to an instance, the method will > not get "self" as parameter. You are not adding a method but a function. Take a look at `types.MethodType()` to create a method from a function, instance, and class. Ciao, Marc 'BlackJack' Rintsch From robert.kern at gmail.com Wed Jan 23 16:29:50 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 23 Jan 2008 15:29:50 -0600 Subject: When is min(a, b) != min(b, a)? In-Reply-To: References: <13p9hdmh7c08abe@corp.supernews.com> Message-ID: Russell E. Owen wrote: > In article , > Christian Heimes wrote: > >> Grant Edwards wrote: >>> In many applications (e.g. process control) propogating NaN >>> values are way too useful to avoid. Avoiding NaN would make a >>> lot of code far more complicated than would using them. >> NaNs are very useful for experienced power users but they are very >> confusing for newbies or developers without a numerical background. >> >> It's very easy to create an inf or nan in Python: >> >> inf = 1E+5000 >> ninf = -inf >> nan = inf * 0. >> >> 1E5000 creates a nan because it is *much* bigger than DBL_MAX (around >> 1E+308). In fact it is even larger than LDBL_MAX (around 1E+4932). > > Isn't it safer to use float("inf"), float("-inf") and float("nan") to > create the necessary items? In currently-released versions of Python, these are not portable. float(some_string) just passes the string to the platform's conversion function. There is no standard defining what to do with "nan" or "inf". On Linux, these work as intended, but on Windows, they are errors. Christian is working on a branch to standardize these forms for Python 2.6. See "math and numerical fixes" in this thread. -- 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 i.shoba3 at gmail.com Wed Jan 16 11:34:52 2008 From: i.shoba3 at gmail.com (i.shoba3 at gmail.com) Date: Wed, 16 Jan 2008 08:34:52 -0800 (PST) Subject: Internet Message-ID: Internet You are using internet %%%%%%%%%%%%%%%%%%%% http://padmagirl.blogspot.com %%%%%%%%%%%%%%%%%%%%% From cptnwillard at gmail.com Thu Jan 17 10:22:12 2008 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Thu, 17 Jan 2008 07:22:12 -0800 (PST) Subject: Is this a bug, or is it me? References: <4044206c-9fd8-4dc1-8fe9-61edb314b9f5@k39g2000hsf.googlegroups.com> Message-ID: On Jan 17, 4:14 pm, cokofree... at gmail.com wrote: > > Do not use those names...really poor choice... This is not the way it looks it my code. I simplified it, with generic names, in order to point out something that does not work... The only question here is why? From jr9445 at ATT.COM Wed Jan 16 14:33:27 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 16 Jan 2008 13:33:27 -0600 Subject: Creating unique combinations from lists In-Reply-To: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.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 breal > Sent: Wednesday, January 16, 2008 2:15 PM > To: python-list at python.org > Subject: Creating unique combinations from lists > > I have three lists... for instance > > a = ['big', 'small', 'medium']; > b = ['old', 'new']; > c = ['blue', 'green']; > > I want to take those and end up with all of the combinations they > create like the following lists > ['big', 'old', 'blue'] > ['small', 'old', 'blue'] > ['medium', 'old', 'blue'] > ['big', 'old', 'green'] > ['small', 'old', 'green'] > ['medium', 'small', 'green'] > ['big', 'new', 'blue'] > ['small', 'new', 'blue'] > ['medium', 'new', 'blue'] > ['big', 'new', 'green'] > ['small', 'new', 'green'] > ['medium', 'new', 'green' ] > > I could do nested for ... in loops, but was looking for a Pythonic way > to do this. Ideas? http://www.python.org/dev/peps/pep-0202/ From martin at v.loewis.de Wed Jan 16 23:59:44 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 Jan 2008 05:59:44 +0100 Subject: Hebrew in idle ans eclipse (Windows) In-Reply-To: References: Message-ID: <478ee0c0$0$4589$9b622d9e@news.freenet.de> > What do I need to do run my app like IDLE does? Can you please show the fragment of your program that prints these strings? Regards, Martin From rupert.thurner at gmail.com Thu Jan 24 11:08:49 2008 From: rupert.thurner at gmail.com (rupert.thurner) Date: Thu, 24 Jan 2008 08:08:49 -0800 (PST) Subject: finding memory leak in edgewall trac 0.11 References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> <0c6fc35d-91d2-4767-968d-e6eb56096eba@z17g2000hsg.googlegroups.com> <4f9304e4-3847-41ee-8064-b881f7b9e073@f47g2000hsd.googlegroups.com> Message-ID: <8c32936d-00fe-46f6-ac10-33321d5a84ce@d21g2000prf.googlegroups.com> On Jan 20, 2:59?pm, Christian Heimes wrote: > rupert.thurner wrote: > > i forgot to mention that i cannot see any explicit sys._getframe(), or > > __del__ in the genshi code, while the ones intrac-core seemed to be > > there in 0.10.4. > > Does the code keep a reference to a traceback object or an attribute of > a traceback object? > > Christian if there is no other possibility but doing it with sys.exc_traceback, sys.last_traceback, sys.exc_info, the answer is no for genshi. From steve at holdenweb.com Thu Jan 31 17:00:44 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 17:00:44 -0500 Subject: Design question - Sharing of single object by multiple processes In-Reply-To: <2b54d4370801311208s4af458cdp8cea665a04c3bd7a@mail.gmail.com> References: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> <47A1AC61.7080007@holdenweb.com> <2b54d4370801311206j457ef51cm33d2a2420b11e688@mail.gmail.com> <2b54d4370801311208s4af458cdp8cea665a04c3bd7a@mail.gmail.com> Message-ID: Mike D wrote: > Steve, > > Thanks for the response. My question really comes down to, as you > suggested, premature optimization. > > It is more for my own understanding than a current practical use. > > If an object is loaded into memory and other threads(or processes) can > recieve a pointer to this location, would this not be more efficient > than to load a new one for every unique request? Wouldn't a method such > as this prevent bottle necks in a read heavy environment? > In theory, yes. In practice there are problems, since modern operating systems are explicitly designed to place barriers between the address spaces of different processes. Even supposing you could access another Python process's space freely you would then have issues like: * does a reference from a foreign process add to an object's reference count? * if so, what happens if the foreign process terminates without decrementing the reference count * otherwise waht happens if the owning process disposes of the object while the foreign process stil wants to refer to it. I don't wish to be unkind, but these are well-known issues of inter-process information sharing, and while superficial solutions can seem easy, the more you think about and work on them the more obvious it becomes that these are hard problems in the general case. Which will hopefully at least encourage you that you are addressing the real issues of computing, even though there's a lot to do. > [...] regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From __peter__ at web.de Tue Jan 22 14:58:37 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 Jan 2008 20:58:37 +0100 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: Arnaud Delobelle wrote: > On Jan 22, 4:10?pm, Alan Isaac wrote: > >> >> >> fwiw, >> Alan Isaac > > Thanks. So I guess I shouldn't take the code snippet I quoted as a > specification of izip but rather as an illustration. You can be bolder here as the izip() docs explicitly state """ Note, the left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using "izip(*[iter(s)]*n)". """ and the bug report with Raymond Hettinger saying """ Left the evaluation order as an unspecified, implementation specific detail. """ is about zip(), not izip(). Peter From teddyber at gmail.com Fri Jan 11 14:47:07 2008 From: teddyber at gmail.com (teddyber) Date: Fri, 11 Jan 2008 11:47:07 -0800 (PST) Subject: split parameter line with quotes References: Message-ID: <2515c260-680f-4d27-9f0d-a7bf1dd1f8cf@21g2000hsj.googlegroups.com> On 11 jan, 20:28, Nanjundi wrote: > On Jan 11, 1:50 pm, teddyber wrote: > > > Hello, > > > first i'm a newbie to python (but i searched the Internet i swear). > > i'm looking for some way to split up a string into a list of pairs > > 'key=value'. This code should be able to handle this particular > > example string : > > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > > i know i can do that with some regexp (i'm currently trying to learn > > that) but if there's some other way... > > > thanks > > This is unconventional and using eval is not SAFE too.>>> s = 'qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,3des",maxbuf=1024,charset="utf-8",algorithm="md5-sess"' > >>> d = eval(' dict(%s)' % s) > >>> d.items() thanks for that. The problem is i don't have charset="utf-8" but charset=utf-8. Sometimes " sometimes not! > > [('algorithm', 'md5-sess'), ('maxbuf', 1024), ('charset', 'utf-8'), > ('cipher', 'rc4-40,rc4-56,rc4,des,3des'), ('qop', 'auth,auth-int,auth- > conf')]>>> for k,v in d.iteritems(): print k, '=', v > > ... > algorithm = md5-sess > maxbuf = 1024 > charset = utf-8 > cipher = rc4-40,rc4-56,rc4,des,3des > qop = auth,auth-int,auth-conf > > For safe eval, take a look athttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 > > -N From fredrik at pythonware.com Wed Jan 9 07:14:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 13:14:26 +0100 Subject: Learning Python via a little word frequency program In-Reply-To: <226043.88503.qm@web56404.mail.re3.yahoo.com> References: <226043.88503.qm@web56404.mail.re3.yahoo.com> Message-ID: Andrew Savige wrote: > Neat. Is there any way to use sorted() with multiple sort keys? ... sure! just return the "composite key" as a tuple: # sort on descending count, ascending name deco = sorted(freq.items(), key=lambda x: (-x[1], x[0])) (when comparing tuples, Python first compares the first item from each tuple. if they're equal, it continues with the second item, and so on). From fredrik at pythonware.com Sat Jan 5 12:07:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 05 Jan 2008 18:07:31 +0100 Subject: Question on os.tempnam() vulnerability In-Reply-To: <13nvb525r3m6m39@corp.supernews.com> References: <13nt81gftkfa32d@corp.supernews.com> <13nv5m68qeknk1f@corp.supernews.com> <477FA9B5.9050609@v.loewis.de> <13nvb525r3m6m39@corp.supernews.com> Message-ID: Grant Edwards wrote: >> IOW, it's the same approach as on Unix. > > Not really. Under Unix you can safely create a temp file with > a name that can be used to open the file. Unless I'm missing something, it's not possible to do this in a safe way in the shared temp directory; you can do that only by creating a file in a directory that's under full control of your user. And *that* approach works on Windows as well, of course. From elind at spamcop.net Tue Jan 15 10:04:21 2008 From: elind at spamcop.net (Erik Lind) Date: Tue, 15 Jan 2008 10:04:21 -0500 Subject: A question about event handlers with wxPython References: <478c3bb2$0$5150$4c368faf@roadrunner.com> <2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com> Message-ID: <478ccbc3$0$11000$4c368faf@roadrunner.com> > def HandleSomething(self, event): > generating_control = event.GetEventObject() > print generating_control > > HTH, Thank you.That is what I was looking for, but as often seems the case, one thing exposes another. Is there any way to listen for events without specifically binding to a handler (it seems one cannot bind an event to two handlers?)? One could do so with globals, but I'm trying to avoid that. For example, "press any button to stop" def HandleSomething(self, event): ................. while generating_control: == something: run else stop From amoghhooshdar at gmail.com Fri Jan 25 06:22:00 2008 From: amoghhooshdar at gmail.com (Amogh Hooshdar) Date: Fri, 25 Jan 2008 16:52:00 +0530 Subject: any library for SOAP 1.1 or SOAP 1.2? Message-ID: <78c462ad0801250322y12d211c1uf53023bc04bbb9bc@mail.gmail.com> Hi, I wish to know which python library is popular for SOAP related programming, especially for sending SOAP requests and parsing SOAP responses. I can't find any such library in the Python standard library but I could find ZSI and soap.py libraries. However, ZSI does not support SOAP 1.2. Does anyone know about a library that supports SOAP 1.2 also? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 21 13:24:09 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 19:24:09 +0100 Subject: Trouble writing to database: RSS-reader In-Reply-To: <13p9n6ea0nui559@corp.supernews.com> References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> <13p9n6ea0nui559@corp.supernews.com> Message-ID: <4794e301$0$4429$426a74cc@news.free.fr> Dennis Lee Bieber a ?crit : > On Mon, 21 Jan 2008 08:12:43 -0800 (PST), Arne > declaimed the following in comp.lang.python: > >> The problem is that i cant find the data in the database! If i watch >> my program while im running it, i can see that it sucsessfuly >> downloads the .xml-file from the web and saves it in the buffer. >> > Did you COMMIT the transaction with the database? Did you READ the code ?-) NB : Yes, he did. The problem*s* are elsewhere. From asmodai at in-nomine.org Tue Jan 8 03:59:50 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 09:59:50 +0100 Subject: Look for a string on a file and get its line number In-Reply-To: <9889cbd0-c19e-4b76-8c41-aa621a188661@e4g2000hsg.googlegroups.com> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <9889cbd0-c19e-4b76-8c41-aa621a188661@e4g2000hsg.googlegroups.com> Message-ID: <20080108085949.GH75977@nexus.in-nomine.org> -On [20080108 09:51], John Machin (sjmachin at lexicon.net) wrote: >Make that >= > >| >>> 'fubar'.find('fu') Or even just: if 'my-string' in line: ... Same caveat emptor applies though. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ We're walking this earth. We're walking this shining earth... From jairtrejo at yahoo.com.mx Tue Jan 1 20:14:51 2008 From: jairtrejo at yahoo.com.mx (Jair Trejo) Date: Tue, 1 Jan 2008 19:14:51 -0600 (CST) Subject: PyCairo, PIL and StringIO In-Reply-To: Message-ID: <366566.9612.qm@web52211.mail.re2.yahoo.com> I'm doing some image processing in PIL, and I want to display the results in a GTK window using PyCairo, so I create a Cairo image surface from the PIL Image like this: mfile = StringIO.StringIO() final.save(mfile, format="PNG") ima = cairo.ImageSurface.create_from_png(mfile) mfile.close() return ima Where final is a PIL image. The problem is, I get a IOError: error while reading from Input Stream. ?Any idea of why is this happening? I tried saving to a temporary file, i.e., replace the above code with: final.save('final.png') ima = cairo.ImageSurface.create_from_png('final.png') Instead of a StringIO object, and it works just fine. ____________________________________________________________________________________ ?Capacidad ilimitada de almacenamiento en tu correo! No te preocupes m?s por el espacio de tu cuenta con Correo Yahoo!: http://correo.yahoo.com.mx/ From grante at visi.com Mon Jan 28 12:15:31 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 28 Jan 2008 17:15:31 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> <6067h9F1otsbrU1@mid.individual.net> Message-ID: <13ps3djqrl4ap5b@corp.supernews.com> >> The script is essentially gone. I'd like to know how to read >> the pyc files, but that's getting away from my point that >> there is a link between python scripts and assembler. At this >> point, I admit the code above is NOT assembler, but sooner or >> later it will be converted to machine code by the interpreter No it won't. In any of the "normal" implementations, bytecodes are not converted to machine code by the interpreter. Rather, the interpreter simulates a machine that runs the byte codes. >> and the OS and that can be disassembled as assembler. No it can't. The result of feeding bytecodes to the VM isn't output of machine code. It's changes in state of _data_ structures that are independate of the processor's instruction set. > Yes. But the interpreter doesn't convert the entire file to machine > language. It reads one instruction after another and, amongst other > things, outputs corresponding machine code which "does" what's > intended by the byte code instruction. No, it doesn't output corresponding machine code (that's what some Java JIT implementations do, but I'm not aware of any Python implementations that do that). The virtual machine interpreter just does the action specified by the bytecode. -- Grant Edwards grante Yow! Nipples, dimples, at knuckles, NICKLES, visi.com wrinkles, pimples!! From imvmifvm at gmail.com Tue Jan 1 03:25:37 2008 From: imvmifvm at gmail.com (imvmifvm at gmail.com) Date: Tue, 1 Jan 2008 08:25:37 +0000 (UTC) Subject: M I-5'Per secution ' the BB C, televis ion an d rad io Message-ID: -=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-= -= the BBC, television and radio. -= -=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-= The first incident in June 1990 was when a BBC newsreader made what. seemed to be a reaction. to something which had happened in my home, and out of context of what they were reading. My first reaction was. disbelief; nothing of the sort had ever happened before,. the idea that such a thing could occur had not crossed my. mind, yet there was no doubt of what had just taken. place. My disbelief eroded as this recurred time after time. Besides the news, offenders. included shows such as Crimewatch (!), Newsnight, and "entertainment" shows. There seems to. be very little moral understanding among the people who make. these programmes; they just assume they will never. be caught, so they carry on without a thought for the illegality or amorality of what they do. The only time I. ever heard a word raised in doubt was. by Paxman being interviewed by someone else (I think by Clive Anderson) back in 1990; referring to the "watching" he said it. troubled him, and when asked by the host what you could do about. it, replied "Well, you could just switch it off" (meaning the. surveillance monitor in the studio). He. clearly didn't let his doubts stand in the way of continued surreptitious spying from his own or other. people's shows, though. Now you're convinced this is. a troll, aren't you? This story has been the subject of much debate on the. uk.* Usenet newsgroups for over a year, and some readers believe. it to be an invention (it has even been suggested that a group of psychology students are responsible!), others. think it symptomatic of a derangement of the author, and a few give it. credence. Quite a few people do know part or all. of the story already, so this text will fill in the. gaps in their knowledge. For the rest, what may persuade you of the third possibility is that some of the incidents. detailed are checkable against any archives. of radio and TV programmes that exist; that the incidents involve named people (even. if those hiding in the shadows have not made their. identity or affiliations evident), and those people may be persuaded to come out with the truth;. and that the campaign of harassment is continuing today both in the UK and on the. American continent, in a. none-too-secret fashion; by its nature the significant risk of exposure. increases with time. On several occasions people said to my face that harassment from the. TV was happening. On the first day I worked in. Oxford, I spent the evening in the local pub with the company's technical director. Ian, and Phil, another employee. Ian made a few references to me and said to. Phil, as if in an aside, "Is he the bloke who's been. on TV?" to which Phil replied, "Yes, I think. so". I. made a number of efforts to find the bugs, without success; last year we employed professional. counter-surveillance people to scan for bugs (see later) again without result. In. autumn 1990 I disposed of my TV and watched virtually no. television for the next three years. But harassment from TV stations has gone. on for over six years and continues to this day. This is something that many people. obviously know is happening; yet the TV staff have the morality of. paedophiles, that because they're getting away with it they. feel no wrong. Other people who were involved in the. abuse in 1990 were DJs on BBC radio stations,. notably disc jockeys from Radio 1 and other stations (see the following section). Again, since they don't have sense in. the first place they can't be expect to have the moral sense not to be part of. criminal harassment. 343 From petr.jakes.tpc at gmail.com Tue Jan 1 13:57:41 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Tue, 1 Jan 2008 10:57:41 -0800 (PST) Subject: Newbie: Why doesn't this work References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> Message-ID: Hi all, I am trying to understand new-style classes in Python and I have found your postings here. Gabriel, if I understand it properly, it is necessary to define get/ set/del/doc methods for each attribute for which I want to set the "property" data descriptor (which triggers get/set/del/doc function calls upon access to defined attribute). My question is: is it possible to set the "property" for any attribute when I do not know what will be the name of the attribute in the future? Thanks for your reply Petr Jakes From anne.nospam01 at wangnick.de Mon Jan 7 16:54:08 2008 From: anne.nospam01 at wangnick.de (anne.nospam01 at wangnick.de) Date: Mon, 7 Jan 2008 13:54:08 -0800 (PST) Subject: What is the encoding of __file__? Message-ID: <736ae822-54a9-4ee6-91fe-92c2c6eb43db@21g2000hsj.googlegroups.com> Dear all, can someone quickly tell me what the encoding of __file__ is? I can't find it in the documentation. BTW, I'm using Python 2.5.1 on WIndows XP and Vista. Kind regards, Sebastian From haraldarminmassa at gmail.com Mon Jan 21 04:57:32 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Mon, 21 Jan 2008 01:57:32 -0800 (PST) Subject: building psycopg2 on windows using mingw, "cannot find -lpq" Message-ID: The compile works, BUT linking fails: 2.5\Release\psycopg\_psycopg.def -Lc:\python25\libs -Lc: \python25\PCBuild -Lc:/p ostgres/83RC2/lib -lpython25 -lpq -lws2_32 -ladvapi32 -o build \lib.win32-2.5\psy copg2\_psycopg.pyd c:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot find -lpq collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 if I google for the error "ld.exe: cannot find -lpq" there is allways the information that the lib-dir of libpq is missing; but : -Lc:/postgres/83RC2/lib is clearly in the commandline, and within c:/postgres/83RC2/lib there is one libqp.lib What am I missing? any hints? Best wishes, Harald (complete output: c:\mingw\bin\gcc.exe -mno-cygwin -shared -s build \temp.win32-2.5\Release\psycopg \psycopgmodule.o build\temp.win32-2.5\Release\psycopg\pqpath.o build \temp.win32- 2.5\Release\psycopg\typecast.o build\temp.win32-2.5\Release\psycopg \microprotoco ls.o build\temp.win32-2.5\Release\psycopg\microprotocols_proto.o build \temp.win3 2-2.5\Release\psycopg\connection_type.o build\temp.win32-2.5\Release \psycopg\con nection_int.o build\temp.win32-2.5\Release\psycopg\cursor_type.o build \temp.win3 2-2.5\Release\psycopg\cursor_int.o build\temp.win32-2.5\Release\psycopg \lobject_ type.o build\temp.win32-2.5\Release\psycopg\lobject_int.o build \temp.win32-2.5\R elease\psycopg\adapter_qstring.o build\temp.win32-2.5\Release\psycopg \adapter_pb oolean.o build\temp.win32-2.5\Release\psycopg\adapter_binary.o build \temp.win32- 2.5\Release\psycopg\adapter_asis.o build\temp.win32-2.5\Release\psycopg \adapter_ list.o build\temp.win32-2.5\Release\psycopg\adapter_datetime.o build \temp.win32- 2.5\Release\psycopg\_psycopg.def -Lc:\python25\libs -Lc: \python25\PCBuild -Lc:/p ostgres/83RC2/lib -lpython25 -lpq -lws2_32 -ladvapi32 -o build \lib.win32-2.5\psy copg2\_psycopg.pyd c:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot find -lpq collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 ) From bearophileHUGS at lycos.com Wed Jan 2 07:39:19 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 2 Jan 2008 04:39:19 -0800 (PST) Subject: Two candies Message-ID: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com> Two little things I may like added. 1) A fast and memory efficient way to create an array.array at a certain size. At the moment I can see some ways to do it: from array import array from itertools import repeat a = array("l", xrange(n)) #1 a = array("l", [0]*n)) #2 a = array("l", repeat(0, n)) #3 - #1 doesn't initialize it to a constant, and to me it seems not memory efficient. - #2 is faster, but I think it requires twice the memory (so it's not good when a has to be quite large). - #3 interacts badly with Psyco (Psyco doesn't digest itertools at all), and it seems not memory efficient. So a simple syntax can be added, like a method a.allocate(item, n), that takes an item and the length of the array to create: a = array("l") a.allocate(0, n) (Note: I know about external numerical packages). In alternative Psyco may be improved a bit, so the #3 syntax may become the standard (efficient in memory and space) one. --------------------------- 2) When I use MatchObjects I have to look at the docs to remember the difference between group() and groups() etc. So I suggest to add a __getitem__ method to MatchObject, so this: mo[3] Equals to: mo.group(3) Bye, bearophile From suray.sathish at gmail.com Sat Jan 26 08:40:07 2008 From: suray.sathish at gmail.com (suray.sathish at gmail.com) Date: Sat, 26 Jan 2008 05:40:07 -0800 (PST) Subject: trisha nake out Message-ID: <6c7f46b7-ae42-4484-a660-cf23ec300dab@s8g2000prg.googlegroups.com> trisha nake out asin hot photos namitha bathing videos ____________________________ http://www.geocities.com/terfavet/ http://www.geocities.com/terfavet/ http://www.geocities.com/terfavet/ From fredrik at pythonware.com Wed Jan 9 14:01:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 20:01:24 +0100 Subject: Another dumb scope question for a closure. In-Reply-To: References: Message-ID: Steven W. Orr wrote: > So sorry because I know I'm doing something wrong. > > 574 > cat c2.py > #! /usr/local/bin/python2.4 > > def inc(jj): > def dummy(): > jj = jj + 1 > return jj > return dummy > > h = inc(33) > print 'h() = ', h() > 575 > c2.py > h() = > Traceback (most recent call last): > File "./c2.py", line 10, in ? > print 'h() = ', h() > File "./c2.py", line 5, in dummy > jj = jj + 1 > UnboundLocalError: local variable 'jj' referenced before assignment http://docs.python.org/ref/naming.html has the answer: "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block." > I could have sworn I was allowed to do this. How do I fix it? use a class to hold state, like everyone else does? From mr.cerutti at gmail.com Fri Jan 4 15:57:49 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 4 Jan 2008 15:57:49 -0500 Subject: MRO Error on Multiple Inheritance? In-Reply-To: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> References: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> Message-ID: <51302a8c0801041257n5aa792cdr26eec78250f2a537@mail.gmail.com> On Jan 4, 2008 3:03 PM, Ming wrote: > I'm working through Wesley Chun's CPP2e and got this error on 13.11.1, > pp 548 where his interpreter snippet shows no problems: > > ActivePython 2.5.1.1 (ActiveState Software Inc.) b > Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [ > win32 > Type "help", "copyright", "credits" or "license" f > >>> class A(object): pass > ... > >>> class B(A): pass > ... > >>> class C(B): pass > ... > >>> class D(A, B): pass > ... > Traceback (most recent call last): > File "", line 1, in > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases A, B The mro of new-style classes changed between Python 2.2 and 2.3. Perhaps Mr. Chun's code was written for 2.2. See http://www.python.org/download/releases/2.3/mro/ -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Jan 22 13:48:03 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 19:48:03 +0100 Subject: Beginners question about debugging (import) In-Reply-To: References: Message-ID: <5vms34F1muqaaU1@mid.uni-berlin.de> Albert van der Horst schrieb: > I'm starting with Python. First with some interactive things, > working through the tutorial, > then with definitions in a file called sudoku.py. > Of course I make lots of mistakes, so I have to include that file > time and again. > > I discovered (the hard way) that the second time you invoke > from sudoku.py import * > nothing happens. > > There is reload. But it only seems to work with > import sudoku > > Now I find myself typing ``sudoku.'' all the time: > > x=sudoku.sudoku() > y=sudoku.create_set_of_sets() > sudoku.symbols > > Is there a more convenient way? > > (This is a howto question, rather difficult to get answered > from the documentation.) import sudoku as s However, I find it easier to just create a test.py and run that from the shell. For the exact reason that reload has it's caveats and in the end, more complex testing-code isn't really feasible anyway. If you need to, drop into the interactive prompt using python -i test.py Diez From aawood at gmail.com Thu Jan 10 17:24:03 2008 From: aawood at gmail.com (Adrian Wood) Date: Thu, 10 Jan 2008 22:24:03 +0000 Subject: Fwd: Python-list Digest, Vol 52, Issue 128 In-Reply-To: References: Message-ID: <25e4147e0801101424m4e932775l2217cf03327b53c5@mail.gmail.com> Fredrik Lundh wrote: > > Adrian Wood wrote: > > > > I can call man.state() and then woman.state() or Person.state(man) and > > Person.state(woman) to print the status of each. This takes time and > > space however, and becomes unmanageable if we start talking about a > > large number of objects, and unworkable if there is an unknown number. > > What I'm after is a way to call the status of every instance of Man, > > without knowing their exact names or number. > > > > I've gone through the relevant parts of the online docs, tried to find > > information elsewhere online, and looked for code samples, but the > > ionformation either isn't there, or just isn't clicking with me. I've > > tried tracking the names of each object in a list, and even creating > > each object within a list, but don't seem to be able to find the right > > syntax to make it all work. > > For a start, how about: > > class Person: > ... your class ... > > persons = [] > > man = Person() > persons.add(man) > > woman = Person() > persons.add(woman) > > for p in persons: > print p, p.state() It didn't like using .add for some reason, but once I swapped out all instances of that for .append that worked a treat! Thank you very much, I'll check out your other suggestions later once I feel comfortable with what I have so far. From williampaul28 at yahoo.com Sat Jan 19 14:53:52 2008 From: williampaul28 at yahoo.com (william paul) Date: Sat, 19 Jan 2008 11:53:52 -0800 (PST) Subject: python scripts with IIS Message-ID: <277841.5689.qm@web38406.mail.mud.yahoo.com> Thank you, William ----- Original Message ---- From: Rolf van de Krol To: python-list at python.org Sent: Saturday, January 19, 2008 5:33:59 PM Subject: Re: python scripts with IIS Adding the following lines before your print statement should do the trick. IIS complains about the headers, so adding headers should help. print "Content-Type: text/html" # HTML is following print # blank line, end of headers william paul wrote: > > Hello: > > I am trying to configure IIS to work with Python scripts: > > I've added in the Home Directory/Configuration the .py extention and > the path to the python.exe as: c:\Python24\python.exe %S %S > The python script has 1 line: > print "This is a test for python scripts with IIS" > > When I launch the file using IE I get the message: > > *CGI Error* > The specified CGI application misbehaved by not returning a complete > set of HTTP headers. The headers it did return are: > > This is a test for python scripts with IIS > > How can I remove the CGI error? > > Thank you > > William > > ------------------------------------------------------------------------ > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try > it now. > -- http://mail.python.org/mailman/listinfo/python-list ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Jan 25 22:08:42 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 19:08:42 -0800 (PST) Subject: ElementTree.fromstring(unicode_html) References: <58b4d6e5-da52-4247-9892-3fbcfd0f1979@m34g2000hsb.googlegroups.com> Message-ID: <56204596-13dc-4a18-b844-dec882b247e1@d21g2000prf.googlegroups.com> On Jan 26, 1:11 pm, globophobe wrote: > This is likely an easy problem; however, I couldn't think of > appropriate keywords for google: > > Basically, I have some raw data that needs to be preprocessed before > it is saved to the database e.g. > > In [1]: unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f > \u3044\r\n' > > I need to turn this into an elementtree, but some of the data is > japanese whereas the rest is html. This string contains a
. >>> import unicodedata as ucd >>> s = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f\u3044\r\n' >>> [ucd.name(c) if ord(c) >= 128 else c for c in s] ['HIRAGANA LETTER SA', 'HIRAGANA LETTER MU', 'HIRAGANA LETTER I', 'FULLWIDTH SOLIDUS', u'\r', u'\n', 'HIRAGANA LETTER TU', 'HIRAGANA LETTER ME', 'HIRAGANA LETTER TA', 'HIRAGANA LETTER I', u'\r', u'\n'] >>> Where in there is the
?? From paddy3118 at googlemail.com Wed Jan 9 11:09:53 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 08:09:53 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <5cf4c5bb-01b1-4ece-a09a-24c4491764b1@f47g2000hsd.googlegroups.com> <7486a4ff-e801-4036-86d3-2ad0aaf542df@v29g2000hsf.googlegroups.com> Message-ID: <8d49b1db-becd-4838-b2ce-a600e8ffa072@z17g2000hsg.googlegroups.com> On Jan 9, 1:02 pm, MartinRineh... at gmail.com wrote: > Thanks to all for many helpful suggestions. > > Python, by the way, is verbose when compared to APL. (Seehttp://catpad.net/michael/apl/if you don't believe this.) You need to > stick in an adverb (maybe "gracefully concise") as standalone > "concise" is owned by APL. > > Basilisk96 wrote: > > Did programmers stop writing programs on punch cards because they ran > > out of punch paper? > > If you drive on the NYS Thruway, you still get a punch card when you > enter. You turn it in when you pay your toll. I didn't reread my blog post! I meant Python is *succinct* with definition: http://www.askoxford.com/concise_oed/succinct?view=uk "Briefly and clearly expressed". (I should engage brain before typing). - Paddy. From deets at nospam.web.de Thu Jan 3 04:44:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 10:44:38 +0100 Subject: Cloning Environments References: Message-ID: <5u3p46F1g2f9sU1@mid.uni-berlin.de> gamename wrote: > Hi, > > I have several machines running Linux (mostly fedora6) and Windows > (mostly XP). I'm thinking of using easy_install to create as uniform > an environment as possible for all of them. Cloning the environment, > to put it another way. > > Is there a good example somewhere showing how to do this? I'm new to > easy_install and relatively new to python. You might be interested in workingenv.py/virtualenv.py Diez From lasses_weil at klapptsowieso.net Mon Jan 28 17:34:07 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 28 Jan 2008 23:34:07 +0100 Subject: Python Genetic Algorithm In-Reply-To: References: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net><13pqbvn8ckilnfc@corp.supernews.com> <479dc95e$0$9103$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <479e585f$0$5950$9b4e6d93@newsspool3.arcor-online.net> Blubaugh, David A. wrote: > Have you ever worked with Gene Expression Programming???? > No. Why? /W From sipickles at hotmail.com Sun Jan 27 12:35:16 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Sun, 27 Jan 2008 17:35:16 +0000 Subject: REALLY simple xml reader Message-ID: Hi Can anyone suggest a really simple XML reader for python? I just want to be able to do something like this: xmlDoc = xml.open("file.xml") element = xmlDoc.GetElement("foo/bar") ... to read the value of: 42 Thanks Simon -- Linux user #458601 - http://counter.li.org. From steveo at syslang.net Thu Jan 17 10:22:14 2008 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 17 Jan 2008 10:22:14 -0500 (EST) Subject: class closure question Message-ID: I want to indirectly change the value of a variable. #! /usr/bin/python foo = [44] bar = foo bar[0] = 55 print 'bar = ', bar print 'foo = ', foo This works fine. bar = [55] foo = [55] But I want to do the same with a class value. #! /usr/bin/python S = None dd = { 'class': [S] } class C1(object): def __init__(self): print 'Hello from C1' def mkclass(base): class zzz(base): pass return zzz dd['class'][0] = mkclass( C1 ) print "dd['class'][0].__bases__ = ", dd['class'][0].__bases__ print 'S = ', S The answer is not what I want: dd['class'][0].__bases__ = (,) S = None The goal is for S to be set to the returned class from mkclass. Can someone help? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From khoard at gmail.com Wed Jan 23 12:17:52 2008 From: khoard at gmail.com (FireNWater) Date: Wed, 23 Jan 2008 09:17:52 -0800 (PST) Subject: Core Python Programming . . . References: <7xir1q29j5.fsf@ruckus.brouhaha.com> <40385ed1-6594-403e-934d-3d54a294101e@e25g2000prg.googlegroups.com> Message-ID: On Jan 22, 5:00 pm, wesley chun wrote: > > > 6-11 Conversion. > > > (a) Create a program that will convert from an integer to an > > > Internet Protocol (IP) address in the four-octet format of WWW.XXX.YYY.ZZZ > > > (b) Update your program to be able to do the vice verse of the above. > > > I think it's is asking to convert a 32-bit int to the dotted form. > > > It's a little known fact, but IP addresses are valid in non-dotted > > long-int form. Spammers commonly use this trick to disguise their IP > > addresses in emails from scanners. > > that is correct. don't read too much into it. i'm not trying to > validate anything or any format, use old or new technology. it is > simply to exercise your skills with numbers (specifically 32-bit/4- > byte integers), string manipulation, and bitwise operations. if you > wish to use different sizes of numbers, forms of addressing, IPv6, > etc., that's up to you. don't forget about part (b), which is to take > an IP address and turn it into a 32-bit integer. > > enjoy! > -- wesley > > ps. since you're on p. 248, there is also a typo in the piece of code > right above this exercise, Example 6.4, which is tied to exercise > 6-7. "'fac_list'" should really be "`fac_list`", or even better, > "repr(fac_list)". see the Errata at the book's websitehttp://corepython.com > for more details. > > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, cahttp://cyberwebconsulting.com Well, I think I may be way off on this one. . . here's what I came up with. . . . def int_to_IP(int): '''Function accepts an integer and returns a string in the format WWW.XXX.YYY.ZZZ''' string = str(int) return (string[0]*3 + '.' + string[1]*3 + '.' + string[2]*3 + '.' + string[3]*3) number = int(raw_input('Enter the number(4 digits): ')) print (int_to_IP(number)) From paddy3118 at googlemail.com Thu Jan 10 01:03:42 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 22:03:42 -0800 (PST) Subject: Collecting Rich Data Structures for students References: <8b4e7954-b666-4515-9ae2-821d979ebd7f@m34g2000hsf.googlegroups.com> Message-ID: On Jan 9, 11:05 pm, "kirby.ur... at gmail.com" wrote: > On Jan 9, 8:15 am, Paddy wrote: > > > > > On Jan 9, 6:52 am, Paddy wrote: > > > > On Jan 9, 2:19 am, "kirby.ur... at gmail.com" > > > wrote: > > > > > Greetings Pythoneers -- > > > > > Some of us over on edu-sig, one of the community actives, > > > > have been brainstorming around this Rich Data Structures > > > > idea, by which we mean Python data structures already > > > > populated with non-trivial data about various topics such > > > > as: periodic table (proton, neutron counts); Monty Python > > > > skit titles; some set of cities (lat, long coordinates); types > > > > of sushi. > > > > > Obviously some of these require levels of nesting, say > > > > lists within dictionaries, more depth of required. > > > > > Our motivation in collecting these repositories is to give > > > > students of Python more immediate access to meaningful > > > > data, not just meaningful programs. Sometimes all it takes > > > > to win converts, to computers in general, is to demonstrate > > > > their capacity to handle gobs of data adroitly. Too often, > > > > a textbook will only provide trivial examples, which in the > > > > print medium is all that makes sense. > > > > > Some have offered XML repositories, which I can well > > > > understand, but in this case we're looking specifically for > > > > legal Python modules (py files), although they don't have > > > > to be Latin-1 (e.g. the sushi types file might not have a > > > > lot of romanji). > > > > > If you have any examples you'd like to email me about, > > > > kirby.ur... at gmail.com is a good address. > > > > > Here's my little contribution to the mix:http://www.4dsolutions.net/ocn/python/gis.py > > > > > Kirby Urner > > > > 4D Solutions > > > > Silicon Forest > > > > Oregon > > > > I would think there was more data out there formatted as Lisp S- > > > expressions than Python data-structures. > > > Wouldn't it be better to concentrate on 'wrapping' XML and CSV data- > > > sources? > > > > - Paddy. > > > The more I think on it the more I am against this- data should be > > stored in programming language agnostic forms but which are easily > > made available to a large range of programming languages. > > If the format is easily parsed by AWK then it is usually easy to parse > > in a range of programming languages. > > > - Paddy. > > It's OK to be against it, but as many have pointed out, it's often > just one value adding step to go from plaintext or XML to something > specifically Python. > > Sometimes we spare the students (whomever they may be) this added > step and just hand them a dictionary of lists or whatever. We > may not be teaching parsing in this class, but chemistry, and > having the info in the Periodic Table in a Python data structure > maybe simply be the most relevant place to start. > > Many lesson plans I've seen or am working on will use these .py > data modules. > > Kirby Then I'd favour the simple wrappings of bearophile and Frederik Lundhs replies where it is easy to extract the original datamaybe for updating , or for use in another language. - Paddy. From hniksic at xemacs.org Wed Jan 16 02:22:41 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 16 Jan 2008 08:22:41 +0100 Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> <13orb15pqgk4h96@corp.supernews.com> Message-ID: <87abn6fd4u.fsf@mulj.homelinux.net> "J. Peng" writes: > we create a new list and assign it to x for future use. How to > destroy the before list [1,2,3]? does python destroy it > automatically? Yes, Python detects that the older list is no longer in use (if that is indeed the case), and destroys it automatically. If you're curious how that works, take a look at http://en.wikipedia.org/wiki/Reference_counting From fredrik at pythonware.com Fri Jan 11 07:27:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jan 2008 13:27:53 +0100 Subject: reading a specific column from file In-Reply-To: References: Message-ID: cesco wrote: > I have a file containing four columns of data separated by tabs (\t) > and I'd like to read a specific column from it (say the third). Is > there any simple way to do this in Python? use the "split" method and plain old indexing: for line in open("file.txt"): columns = line.split("\t") print columns[2] # indexing starts at zero also see the "csv" module, which can read all sorts of comma/semicolon/tab-separated spreadsheet-style files. > I've found quite interesting the linecache module the "linecache" module seems to be quite popular on comp.lang.python these days, but it's designed for a very specific purpose (displaying Python code in tracebacks), and is a really lousy way to read text files in the general case. please unlearn. From chris.arndt at web.de Sat Jan 5 09:46:57 2008 From: chris.arndt at web.de (Christopher Arndt) Date: Sat, 5 Jan 2008 06:46:57 -0800 (PST) Subject: =?ISO-8859-1?Q?ANN:_n=E4chstes_Treffen_von_pyCologne_am_9.1.2008_18:?= =?ISO-8859-1?Q?30_Uhr?= Message-ID: Hallo liebe Pythonfreunde, das n?chste Treffen von pyCologne, der Python User Group K?ln, findet statt: Datum: Mittwoch, den 9.1.2008 Uhrzeit: 18:30 Uhr c.t. Ort: Pool 0.14, Benutzerrechenzentrum (RRZK-B) der Universit?t K?ln, Berrenrather Str. 136, 50937 K?ln Das Programm f?r das n?chste Treffen lautet: * Vortrag ?ber MoinMoin (Reimar Bauer) * Vortrag ?ber das Publisher/Subscriber-Pattern (Observer-Pattern) (Christopher Arndt) * Diskussion: Weitere Vorgehensweise und Verwendung des pyCologne Logos Ab ca. 20:30 Uhr werden wir den Abend gem?tlich in einem nahe gelegenen Restaurant/Kneipe ausklingen lassen. Weitere Information zu pyCologne, inkl. Wegbeschreibung, Fotos und Protokollen vergangener Treffen usw., findet ihr auf unserer Seite im deutschen Python Wiki: http://wiki.python.de/pyCologne Bis bald, Christopher Arndt From azam.farooq3 at gmail.com Thu Jan 31 02:51:19 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Wed, 30 Jan 2008 23:51:19 -0800 (PST) Subject: Do You Want a GSM Mobile with Amazing Features? Please click here Message-ID: <209fc8f2-058b-4a69-88a7-a8bdd4566b0f@v4g2000hsf.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 mrmakent at cox.net Wed Jan 23 15:27:56 2008 From: mrmakent at cox.net (Mike Kent) Date: Wed, 23 Jan 2008 12:27:56 -0800 (PST) Subject: Can someone explain this unexpected raw_input behavior? Message-ID: It's often useful for debugging to print something to stderr, and to route the error output to a file using '2>filename' on the command line. However, when I try that with a python script, all prompt output from raw_input goes to stderr. Consider the following test program: === Start test.py === import sys def main(): print "Hello world" raw_input("Press ENTER") print "Goodbye world" if __name__ == "__main__": main() === End test.py === If I run it with the command line 'python2.5 test.py', I get the following output: Hello world Press ENTER <=== This appeared,the program paused, I press ENTER, and the program continued Goodbye world However, if I run it with the command line 'python2.5 test.py 2>/dev/ null' (I'm routing stderr output to /dev/null), I instead get: Hello world <=== No output appeared, the program paused, I press ENTER, and the program continued Goodbye world This indicates to me that the prompt output of raw_input is being sent to stderr. I did check the source code for raw_input, and it appears to be sending it to stdout as expected. I get this behavior on multiple OS platforms, with multiple versions of Python. I am building python on these platforms myself, but to my knowledge, I am not doing anything special which could account for this behavior. Any suggestions or pointers on how to get the expected behavior out of raw_input? From gherron at islandtraining.com Sat Jan 26 12:53:27 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 26 Jan 2008 09:53:27 -0800 Subject: Beginner String formatting question In-Reply-To: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> References: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> Message-ID: <479B7397.7070906@islandtraining.com> JAMoore84 at gmail.com wrote: > Hi all, > > I am trying to write a simple program that will accept an integral > "time" input in the HHMMSS format and output a "HH:MM:SS" form. My > code is as follows: > ======================== > import string > > def FormatTime(time): > '''Converts an HHMMSS string to HH:MM:SS format.''' > > timeString = str(time) #converts the num to string > > hours = [timeString[0], timeString[1]] > minutes = [timeString[2], timeString[3]] > seconds = [timeString[4], timeString[5]] > > Ftime = "%s:%s:%s",(hours,minutes,seconds) > clock = Ftime.join() > > return clock > =========================== > > when I run it from IDLE, I get this: > > >>>> Format.FormatTime(time) >>>> > ['1', '1', ':', '2', '2', ':', '3', '3'] > ['1', '1', ':', '2', '2', ':', '3', '3'] > The code you posted did not produce the output you are showing. You'll have to be more careful with your posting if you expect to get a useful answer. Beyond that, there are a bundle of errors in the code that will prevent it from working: If you want to carve a string into substrings, use this kind of syntax hours = timeString[0:2] minutes = timeString[2:4] seconds = timeString{4:6] If you want to combine small strings into longer strings you've got several choices: output = hours + ':' + ... or output = "%s:%s:%s" % (hours, ...) #NOTICE the % operator between the format string and value tuple Since both of those produce a string as output, you have no need of a join, BUT if you do decide to produce a list of strings that you want to join into a longer string, you need to use join correctly: parts = [hours,minutes,seconds] output = ':'.join(parts) Another error: If your time starts with an hour that is just a single digit, then your string will be only 5 digits long (there will be no leading zero). In that case, all the extraction of individual fields based on indexing into the string will be off by one. > My questions- > 1) Why is this function printing out twice? > Show us your real code. > 2)It may be a formatting issue, but I want to have the output as > "HH:MM:SS", rather than having it broken out into each cell. I > thought the 'join' command would do this, but I must not be using it > properly/understanding something. > See the example above. > 3)as a side note, I've noticed that the parameter "time" passed in > must be passed in as a string, otherwise I receive an error that > "time" is unsubscriptable. Am I unable to pass in an int and then > convert it to a string within the function with str()? > Of course you can pass any type into a function. Then you have to write the program to operate correctly on whatever the input type is. > I've been at this for a while, so I may not be able to see the forest > through the trees at this point. I'd greatly appreciate any > suggestions or instruction on these mistakes. > My guess is that's why the code you show does not match the output you present. > Best, > > Jimmy > Gary Herron From mario at ruggier.org Wed Jan 2 05:57:17 2008 From: mario at ruggier.org (mario) Date: Wed, 2 Jan 2008 02:57:17 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> Message-ID: <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> On Jan 2, 10:44 am, John Machin wrote: > > Two things for you to do: > > (1) Try these at the Python interactive prompt: > > unicode('', 'latin1') > unicode('', 'mbcs') > unicode('', 'raboof') > unicode('abc', 'latin1') > unicode('abc', 'mbcs') > unicode('abc', 'raboof') $ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> unicode('', 'mbcs') u'' >>> unicode('abc', 'mbcs') Traceback (most recent call last): File "", line 1, in LookupError: unknown encoding: mbcs >>> Hmmn, strange. Same behaviour for "raboof". > (2) Read what the manual (Library Reference -> codecs module -> > standard encodings) has to say about mbcs. Page at http://docs.python.org/lib/standard-encodings.html says that mbcs "purpose": Windows only: Encode operand according to the ANSI codepage (CP_ACP) Do not know what the implications of encoding according to "ANSI codepage (CP_ACP)" are. Windows only seems clear, but why does it only complain when decoding a non-empty string (or when encoding the empty unicode string) ? mario From deets at nospam.web.de Tue Jan 22 09:15:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 15:15:43 +0100 Subject: isgenerator(...) - anywhere to be found? References: Message-ID: <5vmc4fF1n9pk6U1@mid.uni-berlin.de> Jean-Paul Calderone wrote: > On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" > wrote: >>For a simple greenlet/tasklet/microthreading experiment I found myself in >>the need to ask the question >> >>isgenerator(v) >> >>but didn't find any implementation in the usual suspects - builtins or >>inspect. >> >>I was able to help myself out with a simple (out of my head, hope its >> >>def isgenerator(v): >> def _g(): yield >> return type(v) == type(_g()) >> >>But I wonder why there is no such method already available? >> > > Why do you need a special case for generators? If you just pass the > object in question to iter(), instead, then you'll either get back > something that you can iterate over, or you'll get an exception for > things that aren't iterable. Because - as I said - I'm working on a micro-thread thingy, where the scheduler needs to push returned generators to a stack and execute them. Using send(), which rules out iter() anyway. Diez From bladedpenguin at gmail.com Sat Jan 26 01:45:07 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 22:45:07 -0800 (PST) Subject: Doesn't know what it wants References: Message-ID: <11ab7fac-2dec-496f-bb1a-4eeafd3b00ec@v46g2000hsv.googlegroups.com> On Jan 26, 1:32 am, Jeroen Ruigrok van der Werven wrote: > -On [20080126 06:26], Tim Rau (bladedpeng... at gmail.com) wrote: > > >Line 147 reads: > > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) > > I think it expects something like: > > # badly named variable, pick something better depending on context > temp = vec2d(0, 0) > cp.cpMomentForCircle(self.mass, .2, 0, temp) > > I am curious about your use of double braces for vec2d though. Why ((0,0)) and > not (0, 0)? the double parens are a tuple being passed as an argument. vec2d is not a constructor that cares whether it gets a tuple or a pair of ints. I choose tuple for consistency with the rest of my code. Isn't what it gets the value returned by the constructor, no matter whether you assign it to an intermediate value first? I tried it, and the result is the same. From jim.hefferon at gmail.com Sat Jan 12 07:22:18 2008 From: jim.hefferon at gmail.com (Jim) Date: Sat, 12 Jan 2008 04:22:18 -0800 (PST) Subject: Great Python books for the beginner References: Message-ID: Look at http://www.python.org/doc/ . The tutorial is quite good. Jim From asmodai at in-nomine.org Fri Jan 18 01:56:36 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 18 Jan 2008 07:56:36 +0100 Subject: [OT] "Code Friendly" Blog? In-Reply-To: References: Message-ID: <20080118065636.GQ61556@nexus.in-nomine.org> -On [20080117 23:56], Miki (miki.tebeka at gmail.com) wrote: >Is there any free blog hosting that is more "code friendly" (easy to >post code snippets and such)? I personally use a Wordpress installation on my own machine with an additional plugin for syntax highlighting. http://wordpress.org/extend/plugins/wp-syntax/ IIRC it uses
 for highlighting Python for example.
It works quite well.

If you can host stuff yourself you might even like to check out
http://textpress.pocoo.org/ - a beginning Python solution. :)

-- 
Jeroen Ruigrok van der Werven  / asmodai
????? ?????? ??? ?? ??????
http://www.in-nomine.org/ | http://www.rangaku.org/
Buried deep are the Souls that are waiting for you...


From IanJSparks at gmail.com  Thu Jan 10 11:50:36 2008
From: IanJSparks at gmail.com (IanJSparks)
Date: Thu, 10 Jan 2008 08:50:36 -0800 (PST)
Subject: PIL rotate : Rotate By Shear / Paeth Rotation?
Message-ID: 

I've been doing some image rotation with PIL and comparing the images
with imagemagick's convert -rotate output.

Imagemagick uses an RBS / Paeth rotation algorithm that appears to
give better results than PIL's rotate method.

However, I love PIL and don't want to have to shell out to imagemagick
or use it's python bindings if I can stay with my beloved Python
Imaging Library.

Has anyone implemented RBS using PIL? Anyone looked at doing it and
backed away?



From http  Mon Jan 21 22:47:43 2008
From: http (Paul Rubin)
Date: 21 Jan 2008 19:47:43 -0800
Subject: pairs from a list
References: <4idlj.14026$k15.6829@trnddc06>
Message-ID: <7xir1mplls.fsf@ruckus.brouhaha.com>

Alan Isaac  writes:
> (Of course the print statement is just illustrative.)
> What is the fastest way? (Ignore the import time.)

You have to try a bunch of different ways and time them.  One
idea (untested):

    def pairs(seq):
       while True:
           yield (seq.next(), seq.next())


From sjmachin at lexicon.net  Sun Jan 13 00:46:22 2008
From: sjmachin at lexicon.net (John Machin)
Date: Sat, 12 Jan 2008 21:46:22 -0800 (PST)
Subject: Elementary string-formatting
References: 
Message-ID: 

On Jan 13, 3:15 pm, Odysseus  wrote:
[snip]
>
> P.S. Is there a preferable technique for forcing floating-point division
> of two integers to that used above, multiplying by "100.0" first? What
> about if I just wanted a ratio: is "float(n / m)" better than "1.0 * n /
> m"?

> Odysseus

You obviously haven't tried float(n / m), or you wouldn't be asking.
Go ahead and try it.

"Preferable" depends on whether you want legibility or speed.

Most legible and slowest first:
1. float(n) / float(m)
2. n / float(m)
3. 1.0 * n / m
# Rationale so far: function calls are slow
4. If you have a lot of this to do, and you really care about the
speed and m (the denominator) is constant throughout, do fm = float(m)
once, and then in your loop do n / fm for each n -- and make sure you
run properly constructed benchmarks ...

Recommendation: go with (2) until you find you've got a program with
a real speed problem (and then it probably won't be caused by this
choice).

HTH,
John


From scrdhrt at gmail.com  Fri Jan 18 05:13:29 2008
From: scrdhrt at gmail.com (Sacred Heart)
Date: Fri, 18 Jan 2008 02:13:29 -0800 (PST)
Subject: Python Tutorial.
References: <2537f4eb-c047-4eae-9d26-93c7498b5840@f47g2000hsd.googlegroups.com>
Message-ID: <04e2e0f1-9b35-48d0-a87c-647e139d9fe5@y5g2000hsf.googlegroups.com>

On Jan 17, 11:30 pm, Rizwan  wrote:
> Hiya,
>
> I found one good website for python tutorial. just thought to share
> with community.
>
> Hope you all also like it..
>
>  http://python.objectis.net
>
> -MR

Thanks, looks like a nice collection of links. I've bookmarked the
page.

R,
SH


From grahn+nntp at snipabacken.dyndns.org  Thu Jan 17 04:36:45 2008
From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn)
Date: 17 Jan 2008 09:36:45 GMT
Subject: Great Python books for the beginner
References: 
	<1a4d8dae-4722-4a10-a638-ac1b2d85227a@i72g2000hsd.googlegroups.com>
	
	<5e57822c-bd98-41fb-971b-1c8ad7ca5df0@s8g2000prg.googlegroups.com>
Message-ID: 

On Sat, 12 Jan 2008 13:12:19 -0800 (PST), bruno.desthuilliers at gmail.com  wrote:
> On 12 jan, 21:04, Landon  wrote:
>> One thing I wonder about is the examples these books use to teach the
>> concepts. I found myself really attached to K&R because the end of
>> section projects were utilities that I would find be able to find
>> useful in day to day work such as a version of wc and a program that
>> would take collapse all consecutive whitespace in a document into one
>> space. I could just use the projects from K&R, but I imagine a Python
>> book would have a better selection that highlight Python's abilities.
>
> It wouldn't make any sens to port the K&R stuff to Python - different
> languages, different uses, different problems... I mean, C is a low-
> level language, mostly useful for low-level system programming, while
> Python is a very high level language mostly useful for application
> programming and Q&D scripting.

I tend to ignore exercises, sadly, but back in the days before Perl,
and on Unix, it was useful to write small utilities like that in C.
Maybe the K&R exercises reflect that.

(And the 'K' in K&R became the 'k' in awk, so these people were
clearly very interested in this application area -- and interested
in easier ways to do it than by C programming.)

  Unix bigot mode: it seems to me to be harder and more tedious to
  learn programming in a GUI environment like Windows. On Unix small
  home-grown filter-like programs are useful: you have a good shell to
  run them in, and you have a wealth of other utilities to connect
  them to via pipes.

/Jorgen

-- 
  // Jorgen Grahn           R'lyeh wgah'nagl fhtagn!


From berteun at NO_SPAMdds.nl  Wed Jan 30 18:09:16 2008
From: berteun at NO_SPAMdds.nl (Berteun Damman)
Date: Wed, 30 Jan 2008 23:09:16 +0000 (UTC)
Subject: Dictionary Keys question
References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com>
Message-ID: 

On Wed, 30 Jan 2008 14:47:36 -0800 (PST), FireNWater  wrote:
> I'm curious why the different outputs of this code.  If I make the
> dictionary with letters as the keys, they are not listed in the
> dictionary in alphabetical order, but if I use the integers then the
> keys are in numerical order.
>
> I know that the order of the keys is not important in a dictionary,
> but I was just curious about what causes the differences.  Thanks!!

I don't know the exact way Python's hash function works, but I can take
a guess. I'm sorry if I explain something you already know.

A hash is for quickly looking up data. Yet, you don't want to waste too
much memory. So there is a limit number of spaces allocated, in which to
store objects. This number of spaces can be thought of as a list. Then,
if you put something into the dict, Python computes the 'hash' of this
object, which basically forms the index in the list where to store it.
So every object should be mapped onto some index within the list. (If
you retrieve it, the hash is computed again, and the value on that index
is looked up, like list indexing, these are fast operations.)

Say, if you have 100 spaces, and someone puts in integer in the list,
the hashfunction used might be % 100. So the first 100 integers would
always be placed at consecutive places. For strings however, a more
complicated hash-function would be used, which takes into account more
characters, so strings don't end up in order.

For integers, if you put in integers that are spread very widely apart,
they won't end up in order either (see the mod 100 example, 104 will
come before 10).

If you replace the list2 in your example by:
list2 = [10000 * x for x in range(1,9)]

You will see that this one doesn't end up in order either. So, there's
no exception for integers when it comes to the order, yet the particular
properties of the hash function will cause sequential integers to end up
in order under some circumstances.

Berteun

PS:
What happens if two values map onto the same space is of course an
obvious question, and the trick is choosing your hashfunction so this
occurs not very often on average. If it happens there are several
strategies. Wikipedia probably has an explanation of how hash-functions
can work in such a case.


From srikrishnamohan at gmail.com  Wed Jan 23 09:57:09 2008
From: srikrishnamohan at gmail.com (km)
Date: Wed, 23 Jan 2008 20:27:09 +0530
Subject: A GUI framework for running simulations
In-Reply-To: 
References: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com>
	
Message-ID: 

Hi,

check SimPy module
 and then
http://www.showmedo.com/videos/series?name=pythonThompsonVPythonSeries

KM

On Jan 23, 2008 8:10 PM, Guilherme Polo  wrote:

> 2008/1/23, ram.rachum at gmail.com :
> > Hello! I am currently working on writing a simulation engine for
> > special relativity physics. I'm writing it in Python, of course. I'm
> > doing fine with the engine, but I want a GUI framework in which I
> > could use it conveniently, and test different setups on it. I'm not so
> > strong with GUI programming. I looked at Tkinter, I looked at
> > WxPython, I looked at PythonCard. It all looks pretty daunting.
> >
> > My question is, does there exist a GUI package that is intended
> > specifically for simulations? I saw a program called Golly, which is a
> > simulation for Conway's Game of Life. Its GUI had most of the features
> > I needed. For example, you can load a setup, there are "play" and
> > "stop" buttons, you can change a setup and save it, etc.
> >
>
> Golly uses wxWidgets, and if you are planning to use Python then you
> would be using wxPython.
>
> > So does anyone know of a general GUI framework for running
> > simulations?
>
> All them serves this purpose. The main part of your gui application
> will be a custom widget that you will need to do yourself.
>
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
>
> --
> -- Guilherme H. Polo Goncalves
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From lists at cheimes.de  Fri Jan 11 11:45:01 2008
From: lists at cheimes.de (Christian Heimes)
Date: Fri, 11 Jan 2008 17:45:01 +0100
Subject: virtualpython / workingenv / virtualenv ... shouldn't this be
	part of   python
In-Reply-To: <4787981c$0$90268$14726298@news.sunsite.dk>
References: <4787981c$0$90268$14726298@news.sunsite.dk>
Message-ID: 

Damjan wrote:
> My question is, shoudn't it be enough to set PYTHONPATH and everything
> automagically to work then? Is there some work done on this for python 3.0
> or 2.6 perhaps?

I'm working on a PEP for a per user site dir for 2.6 and 3.0

Christian



From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Wed Jan  9 07:27:55 2008
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Wed, 09 Jan 2008 13:27:55 +0100
Subject: Learning Python via a little word frequency program
In-Reply-To: <43a9a28c-0713-4789-b4f0-4e6ba0e8bbfd@u10g2000prn.googlegroups.com>
References: 
	<43a9a28c-0713-4789-b4f0-4e6ba0e8bbfd@u10g2000prn.googlegroups.com>
Message-ID: <4784bdcb$0$1225$426a34cc@news.free.fr>

Ant a ?crit :
>> I'm interested to learn how more experienced Python folks would solve
>> this little problem.
> 
> I think I'd do the following:
> 
> from collections import defaultdict
> 
> names = "freddy fred bill jock kevin andrew kevin kevin jock"
> freq = defaultdict(lambda: 0)
> 
> for name in names.split():
>     freq[name] += 1
> 
> pairs = [(v, k) for k, v in freq.iteritems()]
> 
> for v, k in reversed(sorted(pairs)):
>     print "%-10s: %d" % (k, v)
> 
> 
> defaultdict makes the frequency accumulation neater.
> 
> reversed(sorted(pairs)) avoids the little -v hack and makes it more
> obvious what you are doing.

But fails to implement the specs (emphasis is mine):
"""
   produce a frequency table of names, sorted descending by frequency.
   *then ascending by name*. For the above data, the output should be:

     kevin     : 3
     jock      : 2
     andrew    : 1
     bill      : 1
     fred      : 1
     freddy    : 1
"""

With your solution, you get:

kevin     : 3
jock      : 2
freddy    : 1
fred      : 1
bill      : 1
andrew    : 1




From bj_666 at gmx.net  Fri Jan 11 20:08:22 2008
From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch)
Date: 12 Jan 2008 01:08:22 GMT
Subject: encrypting python modules
References: <47873a78$0$85785$e4fe514c@news.xs4all.nl>
	<87sl14getd.fsf@benfinney.id.au>
Message-ID: <5uqi86F6710oU1@mid.uni-berlin.de>

On Sat, 12 Jan 2008 09:47:26 +1100, Ben Finney wrote:

> Trying to make bits uncopyable and unmodifiable is like trying to make
> water not wet.

Certainly not.  I can put water into the freezer, but I have no idea how
to make bits uncopyable and unmodifiable while still delivering them to
the clients for execution.  ;-)

Ciao,
	Marc 'BlackJack' Rintsch


From gagsl-py2 at yahoo.com.ar  Tue Jan 22 00:24:40 2008
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Tue, 22 Jan 2008 03:24:40 -0200
Subject: read files
References: 
	<7xbq7e5wxt.fsf@ruckus.brouhaha.com>
Message-ID: 

En Tue, 22 Jan 2008 02:03:10 -0200, Paul Rubin  
<"http://phr.cx"@NOSPAM.invalid> escribi?:

> "J. Peng"  writes:
>>         print line,
>
> Do you really want all the lines crunched together like that?  If not,
> leave off the comma.

Remember that Python *keeps* the end-of-line charater at the end of each  
line; if you leave out the comma, you'll print them doubly spaced.

-- 
Gabriel Genellina



From joemystery123 at gmail.com  Tue Jan  1 12:51:15 2008
From: joemystery123 at gmail.com (crybaby)
Date: Tue, 1 Jan 2008 09:51:15 -0800 (PST)
Subject: pexpect ssh login and ls | grep
References: <3eb81375-3e4a-4e0f-a4e7-bbb1d6cd0f8c@s19g2000prg.googlegroups.com>
	<477a6eec$0$17448$bf4948fe@news.tele2.nl>
Message-ID: <1c62b205-e2dd-4bb9-ac99-e14ce652afab@21g2000hsj.googlegroups.com>

I don't get 0 or 2(excuting ls command exit code)
from result.split('\r\n')[0] or result.split('\r\n')[1].  I have to
try another method.

Regular shell ssh login:

[joe at com1 ~]$ ssh my at mycomp2
Last login: Mon Dec 31 20:51:09 2007 from com1
[my at mycomp2 ~]$

Pexpect Login:
>>> import pexpect
>>> child=pexpect.spawn("ssh my at mycomp2")
>>> child.sendline("ls mytest.log > /dev/null 2>&1; echo $? ")
42
>>> child.expect([pexpect.TIMEOUT, r"\$"])
1
>>> result1=child.before
>>> result2=child.after
>>> print result1
Last login: Tue Jan  1 11:22:05 2008 from com1
[my at mycomp2 ~]
>>> print result2
$
>>> print result1.split('\r\n')[1]
[my at mycomp2 ~]
>>> print result1.split('\r\n')[0]
Last login: Tue Jan  1 11:22:05 2008 from com1

thanks.


From http  Fri Jan 18 14:55:42 2008
From: http (Paul Rubin)
Date: 18 Jan 2008 11:55:42 -0800
Subject: Core Python Programming . . .
References: 
Message-ID: <7xir1q29j5.fsf@ruckus.brouhaha.com>

FireNWater  writes:
> 1) convert a 4-digit Integer (WXYZ) to an IP address (WWW.XXX.YYY.ZZZ)
> 
> or
> 
> 2) convert an 8-digit Integer (WWWXXXYYYZZZ) to (WWW.XXX.YYY.ZZZ)
> 
> Thanks for anyone with the clue!!!

Without being able to see the exercise I suspect it's turn a 4-byte
string (i.e. 32 bits) into an IP address (int8.int8.int8.int8).
Or, it might be turn a 32-bit int into such an address.


From ricaraoz at gmail.com  Thu Jan 31 07:39:16 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Thu, 31 Jan 2008 09:39:16 -0300
Subject: REALLY simple xml reader
In-Reply-To: <60do34F1q1qmlU1@mid.uni-berlin.de>
References: 	<1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com>			
	<60do34F1q1qmlU1@mid.uni-berlin.de>
Message-ID: <47A1C174.7060302@bigfoot.com>

Diez B. Roggisch wrote:
> Ricardo Ar?oz schrieb:
>> Thanks Ivan, it seems a elegant API, and easy to use.
>> I tried to play a little with it but unfortunately could not get it off
>> the ground. I kept getting
>>>>> root = et.fromstring(doc)
>> Traceback (most recent call last):
>>   File "", line 1, in 
>>   File "E:\Python25\lib\xml\etree\ElementTree.py", line 963, in XML
>>     parser.feed(text)
>>   File "E:\Python25\lib\xml\etree\ElementTree.py", line 1245, in feed
>>     self._parser.Parse(data, 0)
>> ExpatError: XML or text declaration not at start of entity: line 2, column 0
> 
> That's a problem in your XML not being XML. Has nothing to do with 
> element-tree - as one sees from the error-message "ExpatError". If you 
> show it to us, we might see why.
> 

Sure,

doc = """


expenses: january 2002

  
    31.19
    200213
    Walking Store
    shoes
  

  
    1549.58
    200217
    Bob's Bolts
  

  
    40
    200218
    pocket money
  

  
    25
    200218
  

  
    188.20
    200218
    Boston Endodontics
    cavity
  

  
    10.58
    2002110
    Exxon Saugus
    gasoline
  

  
    909.56
    2002114
    Honda North
    car repairs
  

  
    24.30
    2002115
    Johnny Rockets
    lunch
  

"""
I thought this was proper XML as it comes straight out from an O'Reilly
XML book.

Cheers


From brad at 16systems.com  Sun Jan  6 17:37:03 2008
From: brad at 16systems.com (Brad)
Date: Sun, 06 Jan 2008 17:37:03 -0500
Subject: Patches to Python 2.5.1
Message-ID: 

I was just looking through the 2.5.1 source code. I noticed a few 
mis-spellings in the comments. No big deal really. Can patches be 
submitted that correct the spelling errors or should they just be 
pointed out to some mailing list?

Thanks,
Brad


From vriolk at gmail.com  Sun Jan 27 12:06:09 2008
From: vriolk at gmail.com (coldpizza)
Date: Sun, 27 Jan 2008 09:06:09 -0800 (PST)
Subject: py3k feature proposal: field auto-assignment in constructors
Message-ID: 

There is a pattern that occurs fairly often in constructors in Python
and other OOP languages.

Let's take an example:

class Server(object):
    def __init__(self, host, port, protocol, bufsize, timeout):
        self.host = host
        self.port = port
        self.protocol = protocol
        self.bufsize = bufsize
        self.maxthreads = maxthreads
        self.timeout = timeout

Imho, in the class above the assignment to instance fields does not
contain much programming logic and therefore can be safely 'abstracted
away' by the language itself with a syntax which would look something
like this:

class Server(object):
    def __init__(self, @host, @port, @protocol, @bufsize, @timeout):
        pass

This would be equivalent to the first example above, yet it does not
obfuscate the code in any way. Or does it? It does look much cleaner
to me.

Of course, the ampersand is just an arbitrary choice and might have
bad connotations for those who read it as 'take address of' but @ has
some allusion to delegates which maybe is ok.

I am not an experienced programmer and I am not sure if this is
necessarily a good idea, so I wanted to get some feedback from more
experienced Pythonistas before submitting it elsewhere.




From steve at REMOVE-THIS-cybersource.com.au  Sat Jan 12 00:17:59 2008
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: Sat, 12 Jan 2008 05:17:59 -0000
Subject: Magic function
References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com>
	<13og1lgcespv6c2@corp.supernews.com>
	
	<13oga52q3f2gg1c@corp.supernews.com>
	
Message-ID: <13ogjc7bt5175dd@corp.supernews.com>

On Fri, 11 Jan 2008 19:36:24 -0800, Michael Tobis wrote:

> On Jan 11, 8:40 pm, Steven D'Aprano  cybersource.com.au> wrote:
> 
>> Read the OP's post again. His (her?) users aren't expected to create
>> the toolkit, merely to use it. To create good toolkits you need both a
>> master programmer and an expert in the field. It is an advantage if
>> they are the same person. But to use such a good toolkit, you shouldn't
>> need to be a master programmer.
> 
> It appears we are in agreement, then.
> 
> But that leaves me in a position where I can't understand your
> complaint. There's no reason I can see for the sort of compromise you
> ask for.

What compromise do you think I'm asking for?

I'm suggesting that the scientists be given a brief, introductory 
education in *how to use their tool*, namely, Python.

Instead of creating some sort of magic function that "just works" (except 
when it doesn't) by doing some sort of implicit "grab every object of 
type Obj() you can find and do processing on that", stick to the more 
reliable and safer technique of having the programmer explicitly provide 
the objects she wants to work with.


> Clean abstractions benefit from their cleanliness.

An automatic "run()" that uses a bunch of stuff you can't see as input is 
not a clean abstraction. "Do What I Mean" functions have a long and 
inglorious history of not doing what the user meant.

There's a fundamental difference between (say) Python's automatic garbage 
collection and what the OP is suggesting. Explicitly deleting variables 
is almost always the sort of trivial incantation you rightly decry. The 
computer can tell when a variable is no longer reachable, and therefore 
is safe to delete. But the computer can't safely tell when the user wants 
to use a variable as input to a function. The user needs to explicitly 
tell the computer what is input and what isn't.

The OP is suggesting taking that decision out of the hands of the user, 
and making every variable of type Obj automatically input. If you think 
that's a good idea, consider a programming tool kit with a function sum() 
which inspects every variable you have and adds up every one that is a 
number.



> It's not clear that this is the sort of application where cutting
> corners makes sense, so I don't see how your advice is justified.

Sorry, are you suggesting that training the scientists to use their tools 
is cutting corners? Because I'd call the OP's suggestion to use magic 
functions a dangerous, ill-conceived cut corner.


-- 
Steven


From gherron at islandtraining.com  Sat Jan 12 15:52:05 2008
From: gherron at islandtraining.com (Gary Herron)
Date: Sat, 12 Jan 2008 12:52:05 -0800
Subject: sqlite3 is it in the python default distro?
In-Reply-To: 
References: 
Message-ID: <47892875.1080207@islandtraining.com>

Martin Marcher wrote:
> Hello,
>
> I can see that sqlite is in the standard lib documentation:
> http://docs.python.org/lib/module-sqlite3.html
>
> however debian and ubuntu (and gentoo according to the packages info) seem
> _not_ to include it. 
>
> Now 2 question arise:
>
> a) Is sqlite included in the python default distribution
> b) In real life can I consider (on linux) that an installation of python
> includes the sqlite stuff?
>
> thanks
> martin
>
>   
As I understand it, Python2.5 includes the *module* which can be
imported to access an sqlite installation, but it does not include the
sqlite installation itself.   That should be installed separately.   (I
suppose a distro of Linux could package them together, but I don't  know
of one that does, and such is not the intent of Python.)

Gary Herron



From goon12 at gmail.com  Tue Jan 29 13:59:27 2008
From: goon12 at gmail.com (Joe Riopel)
Date: Tue, 29 Jan 2008 13:59:27 -0500
Subject: noob stuck on reading double
In-Reply-To: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk>
References: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk>
Message-ID: <6a2ccd190801291059q1a18c70co8e9db881c6994f63@mail.gmail.com>

On Jan 29, 2008 1:35 PM, Hannah Drayson  wrote:
> It imports as a string of rubbish...
> i.e.
>
> 
> >>> text = f.read()
> >>> print text
> ?F?C??y??>?
> @??I at g[??B8~??????Q???Q???Q???Q???Q???Q???Q???Q???Q???Q????=N@???????????????????/???8@@@@?Q at E??/??T at N#????S@?????Q???Q???Q???Q???Q???????????R[???Q???????
> >>> unpack('d', text)
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/struct.py", line 87, in unpack
>     return o.unpack(s)
> struct.error: unpack requires a string argument of length 8

When reading the file, try using
file = open('data.bin', 'rb')
file.seek(0)
raw = file.read()

Do the unpack on "raw".

From deets at nospam.web.de  Tue Jan 22 09:17:14 2008
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Tue, 22 Jan 2008 15:17:14 +0100
Subject: isgenerator(...) - anywhere to be found?
References: <5vm8t3F1m1797U1@mid.uni-berlin.de>
	
Message-ID: <5vmc7aF1n9pk6U2@mid.uni-berlin.de>

Stefan Rank wrote:

> on 22.01.2008 14:20 Diez B. Roggisch said the following:
>> 
>> def isgenerator(v):
>>     def _g(): yield
>>     return type(v) == type(_g())
>> 
>> But I wonder why there is no such method already available?
> 
> 
> This tests for generator objects, and you could also use::
> 
>    return type(v) is types.GeneratorType
> 
> I think that this is pretty direct already.

Not as nice as it could be, but certainly way less hackish than my approach.
Thanks!

> I also need to test for generator functions from time to time for which
> I use::
> 
>    def _isaGeneratorFunction(func):
>        '''Check the bitmask of `func` for the magic generator flag.'''
>        return bool(func.func_code.co_flags & CO_GENERATOR)

Not sure if that's not a bit too much on the dark magic side.. but good to
know that it exists.

Diez


From florencio.cano at gmail.com  Thu Jan 10 15:32:18 2008
From: florencio.cano at gmail.com (Florencio Cano)
Date: Thu, 10 Jan 2008 21:32:18 +0100
Subject: XML+Logs to Latex. XSLT?
In-Reply-To: 
References: 
	
Message-ID: 

2008/1/10, Fredrik Lundh :
> Florencio Cano wrote:
>
> > I'm thinking about implementing a script in Python to do this task. I
> > have a XML log and logs from other programs. My aim is to do a report
> > about all this information. I'm thinking in using Python to transform
> > the plain logs to XML and combine them with the XML document I have
> > and later use some kind of XSLT to transform the whole XML document to
> > Latex. What do you think about that? I have not worked with XSLT
> > before and I don't know if this would be a correct use.
> > How will you do the job?
>
> why not do it all in Python?

Yes. For sure. I though XSLT was something like XML not other
"language" and that Python will have any library that uses XSLT to do
transformation...but, what you suggest is:

- First process the XML document with Python (sax?) and do the first
Latex document.
- Second process each log with Python and insert the information in
the Latex document created in first step.

Do you think this approach is the best? Fastest, clearest, more
maintenable? Is this the way you will do it? It seems good for me but
I would like to do this properly.

-- 
Florencio Cano Gabarda


From tijotomjoy at gmail.com  Thu Jan 10 23:51:50 2008
From: tijotomjoy at gmail.com (tijo)
Date: Thu, 10 Jan 2008 20:51:50 -0800 (PST)
Subject: Help needed
References: 
	<0da27dc1-785a-4796-a5a3-6ba1a0290cab@e25g2000prg.googlegroups.com>
Message-ID: <66390246-aada-40fe-b8d3-4816771b950f@i3g2000hsf.googlegroups.com>

Hi mate
i created the socket and the connection with tcp and udp i dont know
how to check the bytes send and time
could you help me with this

cheers
tijo


From gherron at islandtraining.com  Sat Jan 12 14:31:56 2008
From: gherron at islandtraining.com (Gary Herron)
Date: Sat, 12 Jan 2008 11:31:56 -0800
Subject: Simple List division problem
In-Reply-To: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com>
References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com>
Message-ID: <478915AC.8000205@islandtraining.com>

marcstuart wrote:
> How do I divide a list into a set group of sublist's- if the list is
> not evenly dividable ?
> consider this example:
>
> x = [1,2,3,4,5,6,7,8,9,10]
> y = 3      # number of lists I want to break x into
> z = y/x
>
>
> what I would like to get is 3 sublists
>
> print z[0] = [1,2,3]
> print z[2] = [4,5,6]
> print z[3] = [7,8,9,10]
>
> obviously not even, one list will have 4 elements, the other 2 will
> have 3.,
> the overriding logic, is that I will get 3 lists and find a way for
> python to try to break it evenly, if not one list can have a greater
> amount of elements
>
> Would I use itertools ? How would I do this ?
>
> Thanks
>   

Calculate the size of a normal sublist, and the amount of extra that
goes with the last sublist.
Then extract y-1 normal sized sublists and one possibly larger sublist.

>>> x = [1,2,3,4,5,6,7,8,9,10]
>>> y = 3
>>> s = len(x)/y
>>> s                        # size of normal sublists
3
>>> e = len(x) - y*s  # extra elements for last sublist
>>> e
1
>>> z = [x[s*i:s*i+s] for i in range(y-1)] + [x[-s-e:]] #extract y-1
normal + 1 larger sublists
>>> z
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]

Done!

Gary Herron







From sromero at gmail.com  Tue Jan  8 10:05:21 2008
From: sromero at gmail.com (Santiago Romero)
Date: Tue, 8 Jan 2008 07:05:21 -0800 (PST)
Subject: Converting a bidimensional list in a bidimensional array
Message-ID: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com>


 Hi :)

 First of all, I must apologize for my poor english :)

 I'm starting with python and pygame and for testing (and learning)
purposes I wrote an small "Map Editor" for a small game project I'm
going to start next month.

 The tilemap editor is working fine, but reading Guido's Van Rossum
PYTHON TUTORIAL I found that my game map is "wasting" memory by using
about 16 bytes for each item in it, because every item in a python
list takes 16 bytes in memory. In the same tutorial, I found
references to the "array()" function of the "array" module.

 I'm trying to change my current working source code so that it works
with an array instead of using a list, but I'm not managing to do it.

 My tilemap is something like (think on 0=empty, 1=floor, 2=rock, and
so...):

[
[0 ,0, 0, 0, 0, 0, 0, 0 ,0],
[0 ,0, 0, 0, 0, 0, 0, 0 ,0],
[2 ,0, 0, 0, 0, 2, 2, 0 ,0],
(...)
[2 ,2, 0, 0, 2, 2, 2, 0 ,0],
[1 ,1, 1, 1, 1, 1, 1, 1 ,1],
]

 This is how I create the tilemap (and the clipboard, a copy of my
tilemap):

    def __init__( self, bw, bh, tiles ):
      self.width, self.height = bw, bh
      self.tilemap = []
      self.clipboard = []
      (...)
      for i in range(bh):
         self.tilemap.append([0] * bw)
         self.clipboard.append([0] * bw)


 And that's how I'm using it (the functions I'm having trouble to
convert to use the array):

   #-------------------------------------
   def CopyToClipboard( self ):
      for j in range( self.height ):
         self.clipboard[j][:] = self.tilemap[j][:]

   #-------------------------------------
   def Draw( self, clear=1 ):
      screen = pygame.display.get_surface()
      if clear: self.Clear()

      for j in range(self.GetHeight()):
         for i in range(self.GetWidth()):
            self.DrawBlock( i, j )

   #-------------------------------------
   def DrawBlock( self, x, y ):
      screen = pygame.display.get_surface()
      xd = (x * self.TileWidth()) + self.originx;
      yd = (y * self.TileHeight()) + self.originy;
      b = self.tilemap[y][x]
      self.tileset.tiles[b].Draw( screen, xd, yd )

   #-------------------------------------
   def ResizeWidth( self, new ):
      bw, bh = self.GetWidth(), self.GetHeight()

      if new > bw:
         for j in range(bh):
            for i in range(new-bw):
               self.tilemap[j].append( 0 )
               self.clipboard[j].append( 0 )
         self.SetWidth( new )

      elif new < bw:
         for j in range(bh):
            for i in range(bw-new):
               del self.tilemap[j][-1]
               del self.clipboard[j][-1]
         self.SetWidth( new )

   #-------------------------------------
   def ResizeHeight( self, new ):
      bw, bh = self.GetWidth(), self.GetHeight()

      if new > bh:
         for i in range(new-bh):
            self.tilemap.append([0] * bw)
            self.clipboard.append([0] * bw)
         self.SetHeight( new )

      elif new < bh:
         for i in range(1,bh-new):
             del self.tilemap[-1]
         self.SetHeight( new )



In fact, I'm even unable to create the array correctly:


 I've tried:

      self.tilemap = array('H', [])

      for i in range(bh):
         self.tilemap.append([0] * bw)

 and:

      for i in range(bh):

         for j in range(bw):
            self.tilemap[i].append(0)


 But I receive errors like (either defining or using the array):

 b = self.tilemap[y][x]
TypeError: 'int' object is unsubscriptable

 or:

self.tilemap.append( [0] * bw )
TypeError: an integer is required



 So ... please ... any idea on how to convert my "python object" array
of lists to a bidimensional array and how to use it to index [y][x]
elements, or even resize it with the ResizeWidth() and Height()
functions?

 Thanks everybody.


PS: Please, think that I come from C/C++ so I still have some "C ways
of doing things" while there are better/faster ways to do the same in
Python. Feel free also to correct any "C-Style" programming way that
you can find in my source code above... :-)


From geraint.williams at gmail.com  Sun Jan  6 18:09:13 2008
From: geraint.williams at gmail.com (GHZ)
Date: Sun, 6 Jan 2008 15:09:13 -0800 (PST)
Subject: Noob question
References: <17e045f1-7891-4afc-a98b-42dffdc45dd4@41g2000hsy.googlegroups.com>
Message-ID: 

Had the same issue.  What you want is: reload()


From robert.kern at gmail.com  Sat Jan  5 06:05:44 2008
From: robert.kern at gmail.com (Robert Kern)
Date: Sat, 05 Jan 2008 05:05:44 -0600
Subject: Fortran to Python
In-Reply-To: <20080105103643.GT82115@nexus.in-nomine.org>
References: 	<13nstth7a3km06c@corp.supernews.com>
	<20080105103643.GT82115@nexus.in-nomine.org>
Message-ID: 

Jeroen Ruigrok van der Werven wrote:
> -On [20080104 19:21], Dennis Lee Bieber (wlfraed at ix.netcom.com) wrote:
>> 	If the FORTRAN is using single precision reals, I'd expect a
>> slow-down in Python just on that alone, as Python uses doubles as the
>> only float type. There is also the overhead of object access for each.
> 
> In this case it uses complex*16 and real*8. Is a real*8 a single precision
> real?

Double precision. These map to the Python complex and float types exactly.

-- 
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 ggpolo at gmail.com  Mon Jan  7 14:29:03 2008
From: ggpolo at gmail.com (Guilherme Polo)
Date: Mon, 7 Jan 2008 17:29:03 -0200
Subject: any() and all() shorthand
In-Reply-To: <2e589a86-02cf-4903-98aa-c28be2b0b48f@1g2000hsl.googlegroups.com>
References: 
	
	<2e589a86-02cf-4903-98aa-c28be2b0b48f@1g2000hsl.googlegroups.com>
Message-ID: 

2008/1/7, castironpi at gmail.com :
> > You are too late, any and all are built-in into python 2.5
>
> Hi, excellent.  Now how about something more generic, possibly:
>
> [ x.y() for x or _next_ in c ]
>
> where the context of _next_ is limited in complexity, and/or can only
> occur in a generator?

Would you care to explain what that syntax supposedly means ? By
_next_ you mean something like the next method in generators ? _next_
executes if x is false ? so whatever _next_ returns is named as x, so
you can call x.y() ? I really didn't get your new syntax inside that
list comprehension, neither its uses.

> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
-- Guilherme H. Polo Goncalves


From dpsanders at gmail.com  Fri Jan 18 12:15:58 2008
From: dpsanders at gmail.com (David Sanders)
Date: Fri, 18 Jan 2008 09:15:58 -0800 (PST)
Subject: Efficient processing of large nuumeric data file
Message-ID: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com>

Hi,

I am processing large files of numerical data.  Each line is either a
single (positive) integer, or a pair of positive integers, where the
second represents the number of times that the first number is
repeated in the data -- this is to avoid generating huge raw files,
since one particular number is often repeated in the data generation
step.

My question is how to process such files efficiently to obtain a
frequency histogram of the data (how many times each number occurs in
the data, taking into account the repetitions).  My current code is as
follows:

-------------------
#!/usr/bin/env python
# Counts the occurrences of integers in a file and makes a histogram
of them
# Allows for a second field which gives the number of counts of each
datum

import sys
args = sys.argv
num_args = len(args)

if num_args < 2:
	print "Syntaxis: count.py archivo"
	sys.exit();

name = args[1]
file = open(name, "r")

hist = {}   # dictionary for histogram
num = 0

for line in file:
	data = line.split()
	first = int(data[0])

	if len(data) == 1:
		count = 1
	else:
		count = int(data[1])    # more than one repetition

	if first in hist:       # add the information to the histogram
		hist[first]+=count
	else:
		hist[first]=count

	num+=count

keys = hist.keys()
keys.sort()

print "# i  fraction   hist[i]"
for i in keys:
	print i, float(hist[i])/num, hist[i]
---------------------

The data files are large (~100 million lines), and this code takes a
long time to run (compared to just doing wc -l, for example).

Am I doing something very inefficient?  (Any general comments on my
pythonic (or otherwise) style are also appreciated!)  Is
"line.split()" efficient, for example?

Is a dictionary the right way to do this?  In any given file, there is
an upper bound on the data, so it seems to me that some kind of array
(numpy?) would be more efficient, but the upper bound changes in each
file.

Thanks and best wishes,
David.


From kyosohma at gmail.com  Wed Jan 16 14:06:45 2008
From: kyosohma at gmail.com (Mike Driscoll)
Date: Wed, 16 Jan 2008 11:06:45 -0800 (PST)
Subject: A question about event handlers with wxPython
References: <478c3bb2$0$5150$4c368faf@roadrunner.com>
	<2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com>
	<478ccbc3$0$11000$4c368faf@roadrunner.com>
	
	<478d15b4$0$18437$4c368faf@roadrunner.com>
	<0571a7cd-f7f6-44b4-a4d5-e427de93590a@c4g2000hsg.googlegroups.com>
	<478e5251$0$22656$4c368faf@roadrunner.com>
Message-ID: <71dd1ea4-80a1-4a3d-99ae-e9a9c175790b@q77g2000hsh.googlegroups.com>

On Jan 16, 12:45 pm, "Erik Lind"  wrote:
> "Mike Driscoll"  wrote in message
>
> news:0571a7cd-f7f6-44b4-a4d5-e427de93590a at c4g2000hsg.googlegroups.com...
>
> > On Jan 15, 2:20 pm, "Erik Lind"  wrote:
> >> That all looks cool. I will experiment more. I'm a bit slow on this as
> >> only
> >> two weeks old so far.
>
> >> Thanks for the patience
>
> > No problem. I'm pretty slow with some toolkits too...such as
> > SQLAlchemy. Ugh.
>
> > Mike
>
> BTW,
>
> The wxPython group that you mentioned....is thathttp://wxforum.shadonet.com/   ?

I think those are C++ users using the pure C++ wx. I meant the
following:

http://wxpython.org/maillist.php

Mike


From colinlandrum at gmail.com  Wed Jan  2 03:39:21 2008
From: colinlandrum at gmail.com (hubritic)
Date: Wed, 2 Jan 2008 00:39:21 -0800 (PST)
Subject: pyparsing question
References: <8df809a0-1950-4250-a968-2d366f64cdb4@d21g2000prf.googlegroups.com>
	<1115f571-ecd9-4660-9813-b71ae636ac56@d4g2000prg.googlegroups.com>
Message-ID: 

On Jan 1, 4:18 pm, John Machin  wrote:
> On Jan 2, 10:32 am, hubritic  wrote:
>
> > The data I have has a fixed number of characters per field, so I could
> > split it up that way, but wouldn't that defeat the purpose of using a
> > parser?
>
> The purpose of a parser is to parse. Data in fixed columns does not
> need parsing.
>
> >  I am determined to become proficient with pyparsing so I am
> > using it even when it could be considered overkill; thus, it has gone
> > past mere utility now, this is a matter of principle!
>
> An extremely misguided "principle".  Would you use an AK47 on the
> flies around your barbecue? A better principle is to choose the best
> tool for the job.

Your principle is no doubt the saner one for the real world, but your
example of AK47 is a bit off.
We generally know enough about an AK47 to know that it is not
something to kill flies with. Consider, though, if
someone unfamiliar with the concept of guns and mayhem got an AK47 for
xmas and was only told that it was
really good for killing things. He would try it out and would discover
that indeed it kills all sorts of things.
So he might try killing flies. Then he would discover the limitations;
those already familiar with guns would wonder
why he would waste his time.


From pavlovevidence at gmail.com  Sun Jan  6 11:36:57 2008
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sun, 6 Jan 2008 11:36:57 -0500
Subject: list property fires get on append
References: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com>
	
	
Message-ID: <930rlf.mc3.ln@127.0.0.1>

On Sun, 06 Jan 2008 00:31:13 -0800, Soviut wrote:
> I figured that an append would be treated as a set since I'm adding to
> the list.  But what you say makes sense, although I can't say I'm happy
> with the behaviour.  Is there any way I can get the append to fire a
> set?  I'm thinking of properties from my C# background where i believe
> that manipulation such this would be considered a set.

You'd have to have to hook into the container object itself to detect the 
modification.  This might be pretty workable for you since it's an 
internal object.  Basically, instead of using a list, use a special list-
like object that notifies it's owner when it changes.  Here's a simple 
example to point you in the right direction:


class NotifierList(list):
     def __init__(self,*args,**kwargs):
         super(NotifierList,self).__init__(*args,**kwargs)
         self.watchers = []
     def add_watcher(self,watcher):
         self.watchers.append(watcher)
     def _notify_watchers(self):
         for watcher in self.watchers:
             watcher.object_changed(self)
     def append(self,value):
         super(NotifierList,self).append(value)
         self._notify_watchers()
     # override all other mutating calls, including __setitem__
     # left as exercise


class Hierarchy(object):
    def __init__(self):
        self.children = NotifierList()
        self.children.add_watcher(self)
    def object_changed(self,obj):
        print "self.children modified"
    # no need to make children a property then
    # unless you want to trap rebinding it to new object also


A couple other minor suggestions:

print is a statement, not a function.  You should write

print "GETTING"

not

print("GETTING")

The latter works, but it will cease to work if you want to print more 
than one thing.  Note that print is scheduled to become a function in 
Python 3.0, but for now it's a statement.

Based on the name of your class and typical usage, I'm guessing that you 
probably want _children to be an instance attribute rather than a class 
attribute, so I redid it that way, but .)


P.S. Is calling a method called "firing" in C#?


Carl Banks


From cokofreedom at gmail.com  Mon Jan 21 05:09:09 2008
From: cokofreedom at gmail.com (cokofreedom at gmail.com)
Date: Mon, 21 Jan 2008 02:09:09 -0800 (PST)
Subject: Default attribute values pattern
References: 
	
	<4794697f$0$16980$426a74cc@news.free.fr>
Message-ID: <41f8394c-342c-42dc-9bf2-a737b572aff9@c4g2000hsg.googlegroups.com>

> Grab(argdict, key, default) is argdict.pop(key, default)

"pop() raises a KeyError when no default value is given and the key is
not found."

> def grab(kw, key, default=None):
>    try:
>      return kw.pop(key)
>    except KeyError:
>      return default

So Bruno's technique seems to me to be the correct one as it catches
the KeyError.


From browerg at verizon.net  Wed Jan 16 18:02:17 2008
From: browerg at verizon.net (browerg at verizon.net)
Date: Wed, 16 Jan 2008 17:02:17 -0600 (CST)
Subject: scope question in a switch mixin
Message-ID: <3170329.6449001200524538128.JavaMail.root@vms061.mailsrvcs.net>

John,
Thanks for writing, and I'm sorry it's taken so long to get back to you. Python is fun for me -- dinner guests and my boss got in the way.

>> The code ... is the result of noodling around with switches as a learning tool. I've played with python for a few years, but I'm self-taught, so . . .
>> My question is, why are modules imported at the top of the program not visible to the functions Switch builds? There is
>> no problem when the import is in the function, but I thought initially that imports at the top would be in its globals.

>John wrote:
>The global namespace of the to-be-exec'ed code is the dictionary that 
>you supply. That dictionary doesn't contain "math".

Thank you for the guidance about namespaces and exec.

>It's a long time since exec has been documented as a *function*. Why? 
>Because it isn't:

. . . and the code snip.

>What book/tutorial did you get that from?

Hey, I'm not going to pass that off on anyone. As usual, self-education means missing a lot. 

I'm exploring your suggestions and working on my code. 

Thanks again.

George



From peanut.sam at googlemail.com  Thu Jan  3 23:17:39 2008
From: peanut.sam at googlemail.com (Sam Garson)
Date: Fri, 4 Jan 2008 04:17:39 +0000
Subject: Im back...
Message-ID: <4e1ac4910801032017t775cc499w6d9d600f3725221a@mail.gmail.com>

Hi there same project I am afraid...

I want to put the text from the selection of a listbox into a Label when the
the selection is clicked.

I have it so it is put in, but it is put in when I click on the
*next*selection...as in it defines the variable when I click on the
desired the
selection, but it puts it into the label when i click on the *next* item.
It is best if you  have a look. Here is the whole program

[start python code; possibly wrapped by browser]


#!/user/bin/python

from Tkinter import *

def insert():
    name = ent.get()
    box.insert(0, name)
    ent.delete(0, END)

def DeleteCurrent(event):
    box.delete(ANCHOR)

def putLabel(event):
    selection = box.get(ANCHOR)
    v.set(str(selection))

root = Tk()

ent = Entry(root, fg = '#3a3a3a', bg = 'white', relief = 'groove')
ent.grid(row = 0, padx = 3, pady = 3)

button = Button(root, text = "Remember", command = insert, relief =
'groove', fg = '#3a3a3a')
button.grid(row = 0, column = 1, padx = 3, pady = 3)

box = Listbox(root, bg = '#ebe9ed', relief = 'groove', height = 15)
box.selectmode = BROWSE
box.grid(row = 2, columnspan = 2, sticky = W+E, padx = 3)
box.bind("", DeleteCurrent)
box.bind("", putLabel)

v = StringVar()

current = Label(root, textvariable = v)
current.grid(row = 3, columnspan = 2, sticky = W+E, padx = 3)


root.mainloop()


[end python code]

how do i make it so it puts it into the variable *when* i click it? Any help
will be greatly appreciated!


Thanks,

Sam
-- 
I intend to live forever - so far, so good.

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

From paul at boddie.org.uk  Sat Jan 19 11:11:32 2008
From: paul at boddie.org.uk (Paul Boddie)
Date: Sat, 19 Jan 2008 08:11:32 -0800 (PST)
Subject: Using "pickle" for interprocess communication - some notes and 
	things that ought to be documented.
References: <478FAC5A.50206@animats.com>
	 
	<478ff1e6$0$85790$e4fe514c@news.xs4all.nl>
	<479046a5$0$36403$742ec2ed@news.sonic.net> 
	<3b14e57b-9461-4e1c-9bde-fdde99f87617@z17g2000hsg.googlegroups.com> 
	<47921ea4$0$36366$742ec2ed@news.sonic.net>
Message-ID: <96402e46-ea4f-46e6-88e8-fa2e60ab3221@i3g2000hsf.googlegroups.com>

On 19 Jan, 17:06, John Nagle  wrote:
> Paul Boddie wrote:
> > Unlike your approach, pprocess employs the fork system call.
>
>      Unfortunately, that's not portable.  Python's "fork()" is
> "Availability: Macintosh, Unix."  I would have preferred
> to use "fork()".

There was a discussion some time ago about providing a fork
implementation on Windows, since Cygwin attempts/attempted to provide
such support [1] and there's a Perl module which pretends to provide
fork (using threads if I recall correctly), but I'm not sure whether
anyone really believed that it was workable. I believe that on modern
releases of Windows it was the ZwCreateProcess function which was
supposed to be usable for this purpose, but you then apparently have
to add a bunch of other things to initialise the new process
appropriately.

Of course, for the purposes of pprocess - providing a multiprocess
solution which should be as easy to use as spawning threads whilst
having some shared, immutable state hanging around that you don't want
to think too hard about - having fork is essential, but if you're
obviously willing to split your program up into different components
then any of the distributed object technologies would be good enough.

Paul

[1] http://www.cygwin.com/ml/cygwin/2002-01/msg01826.html


From bignose+hates-spam at benfinney.id.au  Wed Jan 23 22:23:01 2008
From: bignose+hates-spam at benfinney.id.au (Ben Finney)
Date: Thu, 24 Jan 2008 14:23:01 +1100
Subject: Can someone explain this unexpected raw_input behavior?
References: 
	
	
Message-ID: <87myqv7vqi.fsf@benfinney.id.au>

Mike Kent  writes:

> Consider an interactive program, that asks the user several
> questions, and displays paragraphs of information based on those
> questions. The paragraphs are output using print, and the questions
> are asked via raw_input.

Okay so far.

> You want to do some simple debugging of the program by printing some
> debugging statements via 'print >>sys.stderr', and you don't want
> the debug output mixed in with the normal output on the screen, so
> you try to route the debugging output to a file by adding
> '2>filename' to the end of the command line.

This issue isn't specific to Python. "Program stops to ask questions
from the user" is not compatible with "Can safely redirect output of
the program to a file".

Either one, or both, of those requirements will have to be
compromised, or dropped completely.

-- 
 \                           "Holy hole in a donut, Batman!"  -- Robin |
  `\                                                                   |
_o__)                                                                  |
Ben Finney


From peanut.sam at googlemail.com  Wed Jan  9 08:09:06 2008
From: peanut.sam at googlemail.com (Sam Garson)
Date: Wed, 9 Jan 2008 13:09:06 +0000
Subject: Newbie question: Classes
In-Reply-To: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com>
References: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com>
Message-ID: <4e1ac4910801090509k4be7eff3g9d8ac1f113e26e44@mail.gmail.com>

OK i've kind of got that. The only thing left is calling the class.

"
class Remember:

    def __init__(self, master):

        self.ent = Entry(self, ...

root = Tk()

app = Remember(root)
"
I get the error "Remember instance has no attribute 'tk' "...???




On Jan 8, 2008 7:36 PM, Sam Garson  wrote:

> Hello all
>
> Basically, I have created a program using tkinter without using any class
> structure, simply creating widgets and functions (and finding ways around
> passing variables from function to function, using global variables etc).
> The program has become rather large ( lines?) I am trying to now put it into
> a class structure, because I hear it is easier to handle.
>
> So basically, I put all the stuff into a class, making the widgets in the
> "def __init__(self, root)" (root being my Tk() ) and then I have had to put
> a "self." in front of any instance of any variable or widget. Is this right?
> it seems like nothing is any easier (except having variables locally). Is
> this right? Should I be creating more classes for different things or what?
>
> I can upload the .py if you want.
>
> Thanks,
>
> Sam
>
> --
> I intend to live forever - so far, so good.
>
> SaM




-- 
I intend to live forever - so far, so good.

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

From dblubaugh at belcan.com  Wed Jan 30 19:40:24 2008
From: dblubaugh at belcan.com (Blubaugh, David A.)
Date: Wed, 30 Jan 2008 19:40:24 -0500
Subject: Why the HELL has nobody answered my question
	!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
In-Reply-To: 
References: 
Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com>

I do not understand why no one has answered the following question:

Has anybody worked with Gene Expression Programming????   


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: Wednesday, January 30, 2008 6:10 PM
To: python-list at python.org
Subject: Python-list Digest, Vol 52, Issue 437

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.




From steve at REMOVE-THIS-cybersource.com.au  Fri Jan 25 06:35:32 2008
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: Fri, 25 Jan 2008 11:35:32 -0000
Subject: global/local variables
References: 
	<13pia51grjfo2ed@corp.supernews.com>
	<4d161c89-7e33-4ddc-851f-bc9beb537229@q21g2000hsa.googlegroups.com>
	<13pjekb7r9jja4c@corp.supernews.com>
	<8d7caad9-fcc3-4bb5-bd7b-dd71e6bd6099@d4g2000prg.googlegroups.com>
Message-ID: <13pjic4h1fag948@corp.supernews.com>

On Fri, 25 Jan 2008 03:28:05 -0800, Tim Rau wrote:

>> Because you don't assign to allThings, and therefore it is treated as
>> global.
>>
>>
> Hmm.... so I can't assign to globals in a  local environment? How do I
> make it see that I'm assigning to a global?

I thought somebody had already mentioned this... possibly even me... 

You can declare a name as global by using the global statement:

def foo():
    global x
    x += 1


-- 
Steven


From MartinRinehart at gmail.com  Fri Jan 11 14:50:52 2008
From: MartinRinehart at gmail.com (MartinRinehart at gmail.com)
Date: Fri, 11 Jan 2008 11:50:52 -0800 (PST)
Subject: Newbie wants to get visual
Message-ID: <63e25138-2a02-471f-b42b-f3af2c69b6a8@f47g2000hsd.googlegroups.com>

I'm ready to start coding the parser for my Decaf (beginners)
language. I think that a "visual" parser (one that shows what it's
doing as it does it) would be nice. (And I think that it would help
the parser author by saving the requirement for a bazillion print
statements while debugging the tool.)

Can someone point me toward the easiest possible way to get GUI? I've
got the Rappin/Dunn book re wxPython, but suspect that this may be
overkill for what I want. If I could do something that would work in a
browser window, that would be wonderful.


From sjmachin at lexicon.net  Wed Jan  9 13:25:20 2008
From: sjmachin at lexicon.net (John Machin)
Date: Wed, 9 Jan 2008 10:25:20 -0800 (PST)
Subject: How does unicode() work?
References: <5ujt96F1i6h37U1@mid.dfncis.de>  
	<1199888091.3474.9.camel@dot.uniqsys.com>  
	
Message-ID: 

On Jan 10, 1:55 am, Carsten Haese  wrote:
> On Wed, 2008-01-09 at 15:33 +0100, Fredrik Lundh wrote:
> > When mixing Unicode with byte strings, Python attempts to decode the
> > byte string, not encode the Unicode string.
>
> Ah, I did not realize that. I never mix Unicode and byte strings in the
> first place, and now I know why. Thanks for clearing that up.
>

When mixing unicode strings with byte strings, Python attempts to
decode the str object to unicode, not encode the unicode object to
str. This is fine, especially when compared with the alternative, so
long as the str object is (loosely) ASCII. If the str object contains
a byte such that ord(byte) > 127, an exception will be raised.

When mixing floats with ints, Python attempts to decode the int to
float, not encode the float to int. This is fine, especially when
compared with the alternative, so long as the int is not humungous. If
the int is huge, you will lose precision without any warning or any
exception being raised.

Do you avoid mixing ints and floats?


From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Thu Jan 17 11:38:58 2008
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Thu, 17 Jan 2008 17:38:58 +0100
Subject: Loop in a loop?
In-Reply-To: <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com>
References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com>
	
	<48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com>
	<55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com>
Message-ID: <478f8472$0$24708$426a74cc@news.free.fr>

cokofreedom at gmail.com a ?crit :
(snip)
> couldn't you just do something like
> 
> if len(array1) is not len(array2):

*never* use the identity operator to test equality ! The fact that 
CPython memoize small integers is an implementation detail, *not* a part 
of the language specification.

>     if len(array1) < len(array2):
>         max_length = len(array2) - len(array1)
>         array1.extend([None for i in xrange(0, max_length)])
>     elif len(array1) > len(array2):
>         max_length = len(array1) - len(array2)
>         array2.extend([None for i in xrange(0, max_length)])


Never heard of the builtin max() function ?-)

def pad(*lists, **kw):
    padding = kw.get('padding', None)
    lists_lens = [len(alist) for alist in lists]
    padlen = max(lists_lens)
    return [
             alist + ([padding] * (padlen - list_len))
             for list_len, alist in zip(lists_lens, lists)
           ]

for i in zip(*pad(range(3), range(5, 10))):
    print i


Now there are very certainly smart solutions using itertools, but the 
one I cooked is way too ugly so I'll leave this to itertools masters !-)


From steve at holdenweb.com  Thu Jan 31 17:03:03 2008
From: steve at holdenweb.com (Steve Holden)
Date: Thu, 31 Jan 2008 17:03:03 -0500
Subject: best(fastest) way to send and get lists from files
In-Reply-To: <4A1A35F8C85B294296F1911569C1137D034B5B57@MAIL2.AD.Brown.Edu>
References: <4A1A35F8C85B294296F1911569C1137D034B5B57@MAIL2.AD.Brown.Edu>
Message-ID: 

Abrahams, Max wrote:
> I've looked into pickle, dump, load, save, readlines(), etc.
> 
> Which is the best method? Fastest? My lists tend to be around a thousand to a million items.
> 
> Binary and text files are both okay, text would be preferred in general unless there's a significant speed boost from something binary.
> 
> thanks

benchmarks are the only reliable way to get this information for your 
particular tasks.

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  Thu Jan 24 06:50:21 2008
From: python.list at tim.thechases.com (Tim Chase)
Date: Thu, 24 Jan 2008 05:50:21 -0600
Subject: Designing website
In-Reply-To: <248758f0-6d8b-4e91-9c3c-a6a0314bebcb@q77g2000hsh.googlegroups.com>
References: <248758f0-6d8b-4e91-9c3c-a6a0314bebcb@q77g2000hsh.googlegroups.com>
Message-ID: <47987B7D.9080101@tim.thechases.com>

> I am planning to design a website using windows, apache, mysql,
> python.

You don't mention what sort of website...low-volume or
high-volume, basic text or graphic-intensive, simple design or
complex web-application logic.  Each of these factors into one's
choice.

> But I came to know that python cgi is very slow. I came across
> mod_python also but no good documentation are available for learning
> mod_python. Suggest me a good solution for this as I don't know other
> languages like PHP; I prefer python.

If you're coming from CGI development and planning a small app,
I'll give a plug for the WebStack[1] framework which basically
reduces just about every option out there (CGI, mod_python,
built-in BaseHTTPServer, and several othes) to a common API.

However, I'd also recommend looking into one of the more powerful
frameworks that abstracts away the server interface a bit more.
I'm personally a Django[2] guy, but for some folks CherryPy[3],
Pylons[4], TurboGears[5] or Zope[6] fills the bill.

They do the grunt work of interfacing with your web-server
(whether through mod_python, FastCGI or WSGI, or possibly other
options such as a Twisted[7] internal server) as well as make a
lot of other web-development aspects easier through separation of
concerns.  In most, business logic is kept separate from
presentation logic which are both kept separate from the data
layer.  This allows developers to focus on a particular aspect at
a time.

There are also deployment issues.  If you have your own server,
it's not a big deal.  However, if you're looking for cheap
low-end shared hosting, the resources made available on such a
machine are usually a bit constrained for these more powerful
schemes.  Sadly, this does make PHP look inviting for deployment
on low-end hosting services despite its warty language.

HTH,

-tkc

[1] http://www.boddie.org.uk/python/WebStack.html
[2] http://www.djangoproject.com
[3] http://www.cherrypy.org
[4] http://pylonshq.com
[5] http://turbogears.org
[6] http://zope.org
[7] http://twistedmatrix.com








From aspineux at gmail.com  Mon Jan 14 13:39:56 2008
From: aspineux at gmail.com (aspineux)
Date: Mon, 14 Jan 2008 10:39:56 -0800 (PST)
Subject: short path evaluation, why is f() called here: dict(a=1).get('a', 
	f())
Message-ID: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com>


This append in both case

dict(a=1).get('a', f())
dict(a=1).setdefault('a', f())

This should be nice if f() was called only if required.

Regards.



From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Tue Jan 29 12:53:48 2008
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Tue, 29 Jan 2008 18:53:48 +0100
Subject: Trying to understand Python web-development
In-Reply-To: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com>
References: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com>
Message-ID: <479f6824$0$25381$426a74cc@news.free.fr>

walterbyrd a ?crit :
> I don't know much php either, but running a php app seems straight
> forward enough.

Mmm... As long as the whole system is already installed and connfigured, 
*and* matches your app's expectations, kind of, yes.

> Python seems to always use some sort of development environment vs
> production environment scheme.

s/Python/some frameworks/

> For development, you are supposed to
> run a local browser and load 127.0.0.1:5000 - or something like that.
> Then to run the same thing in a development environment,

I suppose you meant "in a production environment" ?

> I have to
> configure some files, or touch all the files, restart the web-server,
> or something. Why is that?

Developping directly on a production server is defiinitively a no-no, 
whatever the language. So you *always* develop un a development 
environment. In PHP, this imply having a running HTTP server - usually 
Apache - correctly configured. Some Python frameworks, OTHO, ship with 
their own lightweight Python-based http server, which usually makes 
things far easier. Since quite a lot of web programmers already have 
Apache running on port 80, the framework's own server usually runs (by 
default) on another port. Also, most of the time, on the production 
server, you choose some other more appropriate deployement solution - 
which may or not include Apache - depending on the context. So the nice 
point here is that:
1/ you have way more freedom wrt/ possible deployment solutions
2/ you don't have to replicate the whole damn thing (if ever possible) 
on your local machine to develop the app.

Of course, the actions to be taken when updating your app on the 
production server greatly depends on the deployment solution.

> Python also seems to require some sort of "long running processes" I
> guess that the python interpretor has to running all of time.

s/Python/some frameworks/

You can write web apps in Python using plain cgi, you know. It's just 
very inefficient due to how cgi works - to make a long story short: the 
system has to launch a new process for each request calling your script, 
and you have to rebuild the whole damn world each time your script is 
called. Note that PHP suffers at least from the second problem, which 
can make it somewhat inefficient for some kind of applications.

The point of long running processes is that most of the world is only 
built at startup and stays here between requests.

> I am not really sure about what wsgi is supposed to accomplish.

First and mainly, allow Python-based web apps to be independant from the 
deployment solution, by adding an indirection level. Instead of having

[yourapp]<-->[http_server]

which only work for the http server you targeted, you have

[yourapp]<-->[wsgi]<-->[http_server.wsgi_adapter]<-->[http_server]

which works for any http server for which a specific wsg adapter exists.

There are also some other benefits since, the way wsgi works, the [wsgi] 
part of the above schema can include quite a lot of other things, 
sometimes without your application being aware of it (you may want to 
look for 'wsgi middleware' for more on this).


HTH


From mr.cerutti at gmail.com  Thu Jan 17 10:59:06 2008
From: mr.cerutti at gmail.com (Neil Cerutti)
Date: Thu, 17 Jan 2008 10:59:06 -0500
Subject: Is this a bug, or is it me?
In-Reply-To: <87myr4o3sg.fsf@mulj.homelinux.net>
References: 
	
	<87myr4o3sg.fsf@mulj.homelinux.net>
Message-ID: <51302a8c0801170759xdba420jcc17cd22f679ee01@mail.gmail.com>

On Jan 17, 2008 10:44 AM, Hrvoje Niksic  wrote:
> "Neil Cerutti"  writes:
>
> > You cannot access a class's class variables in it's class-statement
> > scope, since the name of the type is not bound until after the class
> > statement is completed.
>
> But they are still available as locals, so you can access them using
> their names, like this:
>
> >>> class C:
> ...   a = 1
> ...   b = 2
> ...   print a+b
> ...
> 3

Thanks! I had never tried that before. That actually solved my default
method argument problem.

> The question is, why doesn't the OP's code snippet work?  It seems
> that the generator expression can't read the surrounding locals().
> But when you change the generator expression to a list comprehension
> using a pair of [] around it, it starts working.  Compare:
>
> class C(object):
>     d = {}
>     for a in 1, 2, 3:
>         ignore = list((a, b) for b in (4, 5, 6))
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 4, in C
>   File "", line 4, in 
> NameError: global name 'a' is not defined
>
> with:
>
> class C(object):
>     d = {}
>     for a in 1, 2, 3:
>         ignore = [(a, b) for b in (4, 5, 6)]
>
> It seems that generator expressions and list comprehensions have
> subtly different scoping rules.  Whether this is a bug or not is a
> good question.

Generator expressions, unlike list comprehensions, have their own
scope so that they don't "leak" names to the enclosing scope. The
Python rule forbidding access to the locals of enclosing scopes is
preventing the class names from working in the generator expression.

-- 
Neil Cerutti 


From jr9445 at ATT.COM  Fri Jan  4 10:50:03 2008
From: jr9445 at ATT.COM (Reedick, Andrew)
Date: Fri, 4 Jan 2008 09:50:03 -0600
Subject: dictionary/hash and '1' versus 1
In-Reply-To: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com>
References: 
	<7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com>
Message-ID: 

> From: Stephen Hansen [mailto:apt.shansen at gmail.com] 
> Sent: Thursday, January 03, 2008 7:39 PM
> To: Reedick, Andrew
> Cc: python-list at python.org
> Subject: Re: dictionary/hash and '1' versus 1
>
>
>
> Well one important thing to learn while learning Python is that while the  
> language is dynamically typed-- it is also /strongly/ typed. Every piece
> of data has an explicit type and it doesn't change unless you change it.

	Meh, mixing dynamic and strong typing is a mixed blessing.  You don't find out that you screwed up the data types until the code block is actually executed.  Reminds me of Nostradamus.  He may have predicted the future[1], but the predictions are so vague/convoluted that you can only figure out the predictions in hindsight.


> It relies on duck typing a lot, and doesn't care if you mix and match 
> (even partially) compatible types as long as the operations are there,
> but one type will always be distinct and remain that type until you
> explicitly convert it.
>
> A single integer is distinctly different from a sequence of characters in
> some encoding that may just happen to contain representations of a
> number.... so they'll hash differently :)

	Depends on the context.  The machine encoding may be different, but in human terms they "should" be the same.  Perl managed to achieve an impressive blend of presenting data as human friendly or as machine bits when it made sense to do so.  So much so, that Perl is probably the only language I've used that will do what you mean instead of what you say.  Nice, but frightening in some ways.


> One type will basically never implicitly convert into another type.
>
> To me, this sounds like the function should have converted the type 
> explicitly on return. Or maybe you need to convert it explicitly on
> receipt.

	Type casting is easy, IFF you remember to do so.  The problem was that I missed the fact that one (important) function was returning a string instead of an int, and since Python supports heterogenous data structures, the human has to remember to keep the key's data type homongenous.
	That and Perl does so much automatic type conversion in such a sensible way, that I stopped worrying about mixing data types, which is making the Python transition a tad more error prone.  Because of Perl, I almost consider automatic type casting to be the next "you don't have to manage your own memory" that people loved about Java.  =O


> But if you are in a use-case where you really don't care and only 
> want to hash strings, you can create a dict subclass easily that
> overrides __setitem__ to always str() the input. Check out the
> UserDict class.

	UserDict looks like it could be useful.  Thanks for the info.


> A similar method lets you make 'case-insensitive' dicts, for example.
>
> Were such a thing to happen automagically, you could get some 
> weird situations, such as "assert (key in dict) == (key in dict.keys())" 
> failing.

	I'm assuming that you would just need to overload the 'in' operator and .keys() method to be case insensitive also.




[1]  No, he didn't.


*****

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 bborcic at gmail.com  Mon Jan 28 11:46:14 2008
From: bborcic at gmail.com (Boris Borcic)
Date: Mon, 28 Jan 2008 17:46:14 +0100
Subject: optional static typing for Python
In-Reply-To: <69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com>
References: 
	<479da584$0$25625$426a74cc@news.free.fr>
	<69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com>
Message-ID: <479e0709_5@news.bluewin.ch>

Wish you'd opted out of typing all that static.

BB

Russ P. wrote:
(...)
> 
> What is that supposed to mean?
> 
> Oh, I almost forgot. I'm supposed to sit here and be polite while
> clueless dolts make wise cracks. Sorry, but I haven't yet mastered
> that level of self-control.
> 
> I would just like to thank you for reminding me about what losers hang
> out perpetually on sites like this one, thinking they are in some kind
> of real "community." Being reminded of that will help prevent me from
> becoming such a loser myself. No, I didn't say that all the "regulars"
> here are losers, but you most certainly are.
> 
> Do you have a job? How about a life? Have you ever been "with" a
> woman? How in the world is it that every time I come to this site, I
> see your sorry ass hanging around yet again? I can't even imagine how
> "pointless" your life must be if you have that much time to spend
> "hanging around" on comp.lang.python -- and being an a--hole to boot.
> 
> Yeah, Lord have mercy -- on losers like you.
> 
> And thanks for reminding me to quit wasting so much time here. I've
> been doing way too much of that lately.


From paul at boddie.org.uk  Fri Jan 25 09:45:45 2008
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 25 Jan 2008 06:45:45 -0800 (PST)
Subject: "just like Java" (was :Re: translating Python to Assembler)
References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com>
	 
	
	<4799de28$0$12358$426a74cc@news.free.fr>
Message-ID: <7f6f3a93-4301-4a75-83d3-13d9a7c57cda@h11g2000prf.googlegroups.com>

On 25 Jan, 14:05, Bruno Desthuilliers  wrote:
> Christian Heimes a ?crit :
>
> > No, that is not correct. Python code is compiled to Python byte code and
> > execute inside a virtual machine just like Java or C#.
>
> I'm surprised you've not been flamed to death by now - last time I
> happened to write a pretty similar thing, I got a couple nut case
> accusing me of being a liar trying to spread FUD about Java vs Python
> respective VMs inner working, and even some usually sensible regulars
> jumping in to label my saying as "misleading"...

Well, it is important to make distinctions when people are wondering,
"If Python is 'so slow' and yet everyone tells me that the way it is
executed is 'just like Java', where does the difference in performance
come from?" Your responses seemed to focus more on waving that issue
away and leaving the whole topic in the realm of mystery. The result:
"Python is just like Java apparently, but it's slower and I don't know
why."

It's true in one sense that the statement "Python modules and scripts
are normally not even compiled" is incorrect, since modules at least
are compiled to another representation. However, if we grant the
author of that statement the benefit of his ambiguity, we can also
grant his statement a degree of tolerance by observing that modules
are not compiled to native code, which is the only experience some
people have with compilation and its results.

As was pointed out in that previous discussion, CPython instructions
are arguably less well-suited than Java instructions for translation
to CPU instructions. This alone should make people wonder about how
close CPython and the more prominent Java virtual machines are, as
well as the considerations which led the Java virtual machine
architecture to be designed in the way that it was.

Paul


From tarun.kap at gmail.com  Wed Jan 16 15:14:36 2008
From: tarun.kap at gmail.com (Tarun Kapoor)
Date: Wed, 16 Jan 2008 12:14:36 -0800 (PST)
Subject: paramiko
References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> 
	
	<8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com>
	
	<8ceaad4c-c725-4093-a204-ab09162d4629@c23g2000hsa.googlegroups.com>
	
	<685fabb3-c9e8-47ac-84f2-405b831bccad@v4g2000hsf.googlegroups.com>
	
Message-ID: <3019696f-cf50-43e2-8534-2ef4ae4de5d9@y5g2000hsf.googlegroups.com>

On Jan 16, 1:56 pm, "Guilherme Polo"  wrote:
> 2008/1/16, Tarun Kapoor :
>
>
>
> > On Jan 16, 12:22 pm, "Guilherme Polo"  wrote:
> > > 2008/1/16, Tarun Kapoor :
>
> > > > On Jan 16, 11:38 am, "Guilherme Polo"  wrote:
> > > > > 2008/1/16, Tarun Kapoor :
>
> > > > > >     # now, connect and use paramiko Transport to negotiate SSH2 across
> > > > > > the connection
> > > > > >     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > > > > >     sock.connect((hostname, port))
>
> > > > > >     t = paramiko.Transport(sock)
> > > > > >     t.start_client()
> > > > > >     key = t.get_remote_server_key()
>
> > > > > >     event = threading.Event()
> > > > > >     t.auth_password(username=username, password=password, event=event)
> > > > > >     event.wait()
>
> > > > > >     if not t.is_authenticated():
> > > > > >         print "not authenticated"
>
> > > > > > output:
> > > > > > not authenticated
>
> > > > > This is a different problem I guess, now you are usin get_remote_server_key.
> > > > > And why are you creating event after calling start_client without
> > > > > specifying it ?
>
> > > > > > On Jan 16, 11:11 am, "Guilherme Polo"  wrote:
> > > > > > > 2008/1/16, Tarun Kapoor :
>
> > > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to
> > > > > > > > the remote server using an SFTP client I have just to make sure that
> > > > > > > > username and password are working.. This is the code.
>
> > > > > > > >     # now, connect and use paramiko Transport to negotiate SSH2 across the
> > > > > > > > connection
>
> > > > > > > >     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>
> > > > > > > >     sock.connect((hostname, port))
>
> > > > > > > >     t = paramiko.Transport(sock)
>
> > > > > > > >     event = threading.Event()
>
> > > > > > > >     t.start_client(event)
>
> > > > > > > >     event.wait(15)
>
> > > > > > > >     if not t.is_active():
>
> > > > > > > >         print 'SSH negotiation failed.'
>
> > > > > > > >         sys.exit(1)
>
> > > > > > > >     else:
>
> > > > > > > >         print "SSH negotiation sucessful"
>
> > > > > > > >     event.clear()
>
> > > > > > > >     t.auth_password(username=username, password=password,event=event)
>
> > > > > > > >     if not t.is_authenticated():
>
> > > > > > > >         print "not authenticated"
>
> > > > > > > > output:
>
> > > > > > > > SSH negotiation successful
>
> > > > > > > > not authenticated
>
> > > > > > > > Tarun
>
> > > > > > > > Waterstone Capital Management
>
> > > > > > > > 2 Carlson Parkway, Suite 260
>
> > > > > > > > Plymouth, MN 55447
>
> > > > > > > > Direct: 952-697-4123
>
> > > > > > > > Cell:    612-205-2587
> > > > > > > >  Disclaimer This e-mail and any attachments is confidential and intended
> > > > > > > > solely for the use of the individual(s) to whom it is addressed. Any views
> > > > > > > > or opinions presented are solely those of the author and do not necessarily
> > > > > > > > represent those of Waterstone Capital Management, L.P and affiliates. If you
> > > > > > > > are not the intended recipient, be advised that you have received this
> > > > > > > > e-mail in error and that any use, dissemination, printing, forwarding or
> > > > > > > > copying of this email is strictly prohibited. Please contact the sender if
> > > > > > > > you have received this e-mail in error. You should also be aware that
> > > > > > > > e-mails are susceptible to interference and you should not assume that the
> > > > > > > > contents of this e-mail originated from the sender above or that they have
> > > > > > > > been accurately reproduced in their original form. Waterstone Capital
> > > > > > > > Management, L.P. and affiliates accepts no responsibility for information,
> > > > > > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt,
> > > > > > > > please verify the authenticity with the sender.
> > > > > > > > --
> > > > > > > >http://mail.python.org/mailman/listinfo/python-list
>
> > > > > > > You are missing an event.wait() after t.auth_password.
> > > > > > > Also, why are you passing this magic value "15" to event.wait() ? That
> > > > > > > parameter is passed to class _Verbose to indicate if debug messages
> > > > > > > should be displayed or not, so typical values would be 0/1 or
> > > > > > > False/True.
>
> > > > > > > --
> > > > > > > -- Guilherme H. Polo Goncalves
>
> > > > > > --
> > > > > >http://mail.python.org/mailman/listinfo/python-list
>
> > > > > --
> > > > > -- Guilherme H. Polo Goncalves
>
> > > > ok here is the problem... I don't know what is the correct way... The
> > > > only demos i have from the paramiko library use a hostkeyfile. since i
> > > > don't have that i thought i would use the get_remote_key to get the
> > > > key and then connect it using the code in the demo.. But clearly
> > > > nothing is working...I should not HAVE to use the key since i should
> > > > be able to authenticate using the password...
>
> > > > Can you please suggest the right way to go ?
>
> > > You don't need to use key to authenticate using username and password,
> > > indeed. And you don't. Your first email was almost correct, you just
> > > needed to add event.wait() after t.auth_password. It worked here after
> > > doing that change. You can check out my version:
>
> > > import sys
> > > import socket
> > > import paramiko
> > > import threading
>
> > > if len(sys.argv) != 4:
> > >     print "%s hostname user password" % sys.argv[0]
> > >     sys.exit(1)
>
> > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > > sock.connect((sys.argv[1], 22))
>
> > > t = paramiko.Transport(sock)
> > > event = threading.Event()
> > > t.start_client(event)
>
> > > event.wait()
>
> > > if not t.is_active():
> > >     print 'SSH negotiation failed.'
> > >     sys.exit(1)
> > > else:
> > >     print "SSH negotiation sucessful"
>
> > > event.clear()
> > > t.auth_password(username=sys.argv[2], password=sys.argv[3], event=event)
> > > event.wait()
> > > if not t.is_authenticated():
> > >     print "Authentication failed."
> > > else:
> > >     print "Authenticated!"
>
> > > t.close()
>
> > > > Thanks for your time !
> > > > --
> > > >http://mail.python.org/mailman/listinfo/python-list
>
> > > --
> > > -- Guilherme H. Polo Goncalves
>
> > ok i tried the exact same code and here is the output
> > SSH negotiation sucessful
> > Authentication failed.
>
> > I am positive that the username and paddword are correct. !
>
> I believe paramiko supports only ssh2, so be sure to check if your
> server is not running ssh1.
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> -- Guilherme H. Polo Goncalves


The server is running SSH2.
Can you think of any other ideas to troubleshoot ?



From odysseus1479-at at yahoo-dot.ca  Sun Jan 13 04:40:55 2008
From: odysseus1479-at at yahoo-dot.ca (Odysseus)
Date: Sun, 13 Jan 2008 09:40:55 GMT
Subject: Elementary string-formatting
References: 
	
Message-ID: 

In article 
,
 John Machin  wrote:


> 
> You obviously haven't tried float(n / m), or you wouldn't be asking.

True, it was a very silly idea.

> Most legible and slowest first:
> 1. float(n) / float(m)
> 2. n / float(m)
> 3. 1.0 * n / m

> Recommendation: go with (2) until you find you've got a program with
> a real speed problem (and then it probably won't be caused by this
> choice).

I had actually used n / float(m) at one point; somehow the above struck 
me as an improvement while I was writing the message. Thanks for the 
reality check.

-- 
Odysseus


From fredrik at pythonware.com  Sun Jan  6 03:03:59 2008
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Sun, 06 Jan 2008 09:03:59 +0100
Subject: list property fires get on append
In-Reply-To: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com>
References: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com>
Message-ID: 

ian at neustyle.com wrote:

> I've created a class that has a property which points at a private
> list.  When I try to use the append() function on this list property,
> the fget method is fired rather than the fset method.  If I directly
> set my property to a literal list, the set method fires.

> # this fires a get for some reason
> hierarchy.children.append( Hierarchy.Hierarchy())

that's the expected behaviour: you're *fetching* the "children" 
attribute in order to modify it, you're not replacing it.

reading up on Python's object model might be helpful.





From ashok.raavi at gmail.com  Tue Jan 29 08:33:25 2008
From: ashok.raavi at gmail.com (ashok raavi)
Date: Tue, 29 Jan 2008 19:03:25 +0530
Subject: [HELP] SMTPlib not sending my mail
In-Reply-To: <1201596148.7850.2.camel@lars-laptop.ez.no>
References: 
	
	<1201596148.7850.2.camel@lars-laptop.ez.no>
Message-ID: <2aa122da0801290533x7e30467csfbc60fe976d3855e@mail.gmail.com>

i  checked it after your mail..

it is giving the following warning: no entropy for TLS key generation:
disabling TLS support

which was addressed here "
http://www.howtoforge.com/forums/showthread.php?t=781"

after adding the line "tlsmgr unix - - n 1000? 1 tlsmgr"  to
/etc/postfix/master.cf it started working.

Thank you.


On 1/29/08, Lars Johansen  wrote:
>
> have you checked your mail server logs ?
>
> tir, 29.01.2008 kl. 00.24 -0800, skrev ashok.raavi:
> > Hi,
> >
> > I am also facing the same problem, smtplib used to send mail a while
> > back but it stopped sending mails.
> >
> > when i run this in interpreter
> > >>> import smtplib
> > >>> s = smtplib.SMTP("localhost")
> > >>> s.sendmail(from, to, "message")
> > {}
> > >>>
> >
> > though it is not giving any error, it is not sending mail.
> >
> > Any help is appreciated.
> >
> > ornto wrote:
> > > Hi, I'm trying to create an application which checks a
> > > dynamic web site and on certain events sends an email to me.
> > > My problem though is with the email task. By now I made this
> > >   simple test code:
> > >
> > > #prova invio email
> > > smtpserver = smtplib.SMTP(mailserver)
> > > messaggio= "Messaggio di prova"
> > > print mail
> > > print messaggio
> > > smtpresult=smtpserver.sendmail("Watcher",mail,messaggio)
> > > if smtpresult:
> > >      print smtpresult
> > > smtpserver.quit()
> > >
> > > "mailserver" and "mail" values are loaded from a ini file
> > > and they're correct.
> > > The call to smtpserver gives back no errors (smtpresult
> > > remains empty).
> > > The running enviroment gives no error.
> > > So, it looks like that the program works alloright, sending
> > > the mail- BUT, I receive no mail! I've tried to change the
> > > smtp server with another one which still works with my isp,
> > > with no luck. If I try a smtp which doesn't give me access,
> > > I correctly receive an error from the program.
> > > What might be the problem?
>
>


-- 
ashok raavi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at REMOVE-THIS-cybersource.com.au  Mon Jan 14 06:09:26 2008
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: Mon, 14 Jan 2008 11:09:26 -0000
Subject: encrypting python modules
References: <47873a78$0$85785$e4fe514c@news.xs4all.nl>
	<13og1dbe4qcfs2b@corp.supernews.com>
	<478b220e$0$85788$e4fe514c@news.xs4all.nl>
Message-ID: <13omgn69naf1se8@corp.supernews.com>

On Mon, 14 Jan 2008 09:49:49 +0100, Paul Sijben wrote:

>> How often do these things *actually* happen?
>> 
>> Of those that actually do it, how many are clueless enough that when
>> they run into problems they blame you for it? (And remember that you
>> won't even find out about the non-clueless ones.)
>> 
>> 
> This is a rethorical question, right?

No, it's a serious question. You distribute Python code, and you're 
worried that your users will modify the source code and then neglect to 
mention it when they report bugs which they introduced.

Before you build an elephant-proof fence around your house, it is quite 
reasonable to ask whether or not there are actually elephants in your 
neighbourhood.



-- 
Steven


From d.l.goldsmith at gmail.com  Tue Jan  8 13:25:35 2008
From: d.l.goldsmith at gmail.com (dgoldsmith_89)
Date: Tue, 8 Jan 2008 10:25:35 -0800 (PST)
Subject: Open source English dictionary to use programmatically w/ python
References: 
	 
	 
	
Message-ID: <0d2c14d8-b7f8-40be-b13c-05b9dadaaa65@i7g2000prf.googlegroups.com>

On Jan 7, 3:50 pm, "mensana... at aol.com"  wrote:
> On Jan 7, 5:10 pm, dgoldsmith_89  wrote:
>
>
>
> > On Jan 7, 2:54 pm, "mensana... at aol.com"  wrote:
>
> > > On Jan 7, 4:37 pm, dgoldsmith_89  wrote:
>
> > > > Can anyone point me to a downloadable open source English dictionary
> > > > suitable for programmatic use with python: I'm programming a puzzle
> > > > generator, and I need to be able to generate more or less complete
> > > > lists of English words, alphabetized.  Thanks!  DG
>
> > >www.puzzlers.orghasnumerousword lists & dictionarys in text
> > > format that can be downloaded. I recommend you insert them into
> > > some form of database. I have most of them in an Access db and
> > > it's 95 MB. That's a worse case as I also have some value-added
> > > stuff, the OSPD alone would be a lot smaller.
>
> > > 
>
> > Sorry for my ignorance: I can query an Access DB w/ standard SQL
> > queries (and this is how I would access it w/ Python)?
>
> Yes, if you have the appropriate way to link to the DB.
> I use Windows and ODBC from Win32. I don't know what you
> would use on a Mac.
>
> As Paul McGuire said, you could easily do this with SqlLite3.
> Personnaly, I always use Access since my job requires it
> and I find it much more convenient. I often use Crosstab
> tables which I think SqlLite3 doesn't support. Typically,
> I'll write complex queries in Access and simple select SQL
> statements in Python to grab them.
>
> Here's my anagram locator. (the [signature] is an example
> of the value-added I mentioned).
>
> ##  I took a somewhat different approach. Instead of in a file,
> ##  I've got my word list (562456 words) in an MS-Access database.
> ##  And instead of calculating the signature on the fly, I did it
> ##  once and added the signature as a second field:
> ##
> ##  TABLE CONS_alpha_only_signature_unique
> ##  --------------------------------------
> ##  CONS       text      75
> ##  signature  text      26
> ##
> ##  The signature is a 26 character string where each character is
> ##  the count of occurences of the matching letter. Luckily, in
> ##  only a single case was there more than 9 occurences of any
> ##  given letter, which turned not to be a word but a series of
> ##  words concatenated so I just deleted it from the database
> ##  (lots of crap in the original word list I used).
> ##
> ##  Example:
> ##
> ##  CONS     signature
> ##  aah      20000001000000000000000000 # 'a' occurs twice & 'h' once
> ##  aahed    20011001000000000000000000
> ##  aahing   20000011100001000000000000
> ##  aahs     20000001000000000010000000
> ##  aaii     20000000200000000000000000
> ##  aaker    20001000001000000100000000
> ##  aal      20000000000100000000000000
> ##  aalborg  21000010000100100100000000
> ##  aalesund
> 20011000000101000010100000
> ##
> ##  Any words with identical signatures must be anagrams.
> ##
> ##  Once this was been set up, I wrote a whole bunch of queries
> ##  to use this table. I use the normal Access drag and drop
> ##  design, but the SQL can be extracted from each, so I can
> ##  simply open the query from Python or I can grab the SQL
> ##  and build it inside the program. The example
> ##
> ##    signatures_anagrams_select_signature
> ##
> ##  is hard coded for criteria 9 & 10 and should be cast inside
> ##  Python so the criteria can be changed dynamically.
> ##
> ##
> ##  QUERY signatures_anagrams_longest
> ##  ---------------------------------
> ##  SELECT   Len([CONS]) AS Expr1,
> ##           Count(Cons_alpha_only_signature_unique.CONS) AS
> CountOfCONS,
> ##           Cons_alpha_only_signature_unique.signature
> ##  FROM     Cons_alpha_only_signature_unique
> ##  GROUP BY Len([CONS]),
> ##           Cons_alpha_only_signature_unique.signature
> ##  HAVING   (((Count(Cons_alpha_only_signature_unique.CONS))>1))
> ##  ORDER BY Len([CONS]) DESC ,
> ##           Count(Cons_alpha_only_signature_unique.CONS) DESC;
> ##
> ##  This is why I don't use SQLite3, must have crosstab queries.
> ##
> ##  QUERY signatures_anagram_summary
> ##  --------------------------------
> ##  TRANSFORM Count(signatures_anagrams_longest.signature) AS
> CountOfsignature
> ##  SELECT    signatures_anagrams_longest.Expr1 AS [length of word]
> ##  FROM      signatures_anagrams_longest
> ##  GROUP BY  signatures_anagrams_longest.Expr1
> ##  PIVOT     signatures_anagrams_longest.CountOfCONS;
> ##
> ##
> ##  QUERY signatures_anagrams_select_signature
> ##  ------------------------------------------
> ##  SELECT   Len([CONS]) AS Expr1,
> ##           Count(Cons_alpha_only_signature_unique.CONS) AS
> CountOfCONS,
> ##           Cons_alpha_only_signature_unique.signature
> ##  FROM     Cons_alpha_only_signature_unique
> ##  GROUP BY Len([CONS]),
> ##           Cons_alpha_only_signature_unique.signature
> ##  HAVING   (((Len([CONS]))=9) AND
> ##            ((Count(Cons_alpha_only_signature_unique.CONS))=10))
> ##  ORDER BY Len([CONS]) DESC ,
> ##           Count(Cons_alpha_only_signature_unique.CONS) DESC;
> ##
> ##  QUERY signatures_lookup_by_anagram_select_signature
> ##  ---------------------------------------------------
> ##  SELECT     signatures_anagrams_select_signature.Expr1,
> ##             signatures_anagrams_select_signature.CountOfCONS,
> ##             Cons_alpha_only_signature_unique.CONS,
> ##             Cons_alpha_only_signature_unique.signature
> ##  FROM       signatures_anagrams_select_signature
> ##  INNER JOIN Cons_alpha_only_signature_unique
> ##  ON         signatures_anagrams_select_signature.signature
> ##             = Cons_alpha_only_signature_unique.signature;
> ##
> ##
> ##  Now it's a simple matter to use the ODBC from Win32 to extract
> ##  the query output into Python.
>
> import dbi
> import odbc
>
> con = odbc.odbc("words")
> cursor = con.cursor()
>
> ##  This first section grabs the anagram summary. Note that
> ##  queries act just like tables (as long as they don't have
> ##  internal dependencies. I read somewhere you can get the
> ##  field names, but here I put them in by hand.
>
> ##cursor.execute("SELECT * FROM signature_anagram_summary")
> ##
> ##results = cursor.fetchall()
> ##
> ##for i in results:
> ##  for j in i:
> ##    print '%4s' % (str(j)),
> ##  print
>
> ##  (if this wraps, each line is 116 characters)
> ##        2    3    4    5    6    7    8    9   10   11   12   13
> 14   15   16   17   18   23
> ##   2  259 None None None None None None None None None None None
> None None None None None None
> ##   3  487  348  218  150  102 None None None None None None None
> None None None None None None
> ##   4 1343  718  398  236  142  101   51   26   25    9    8    3
> 2 None None None None None
> ##   5 3182 1424  777  419  274  163  106   83   53   23   20   10
> 6    4    5    1    3    1
> ##   6 5887 2314 1051  545  302  170  114   54   43   21   15    6
> 5    4    4    2 None None
> ##   7 7321 2251  886  390  151   76   49   37   14    7    5    1
> 1    1 None None None None
> ##   8 6993 1505  452  166   47   23    8    6    4    2    2 None
> None None None None None None
> ##   9 5127  830  197   47   17    6 None None    1 None None None
> None None None None None None
> ##  10 2975  328   66    8    2 None None None None None None None
> None None None None None None
> ##  11 1579  100    5    4    2 None None None None None None None
> None None None None None None
> ##  12  781   39    2    1 None None None None None None None None
> None None None None None None
> ##  13  326   11    2 None None None None None None None None None
> None None None None None None
> ##  14  166    2 None None None None None None None None None None
> None None None None None None
> ##  15   91 None    1 None None None None None None None None None
> None None None None None None
> ##  16   60 None None None None None None None None None None None
> None None None None None None
> ##  17   35 None None None None None None None None None None None
> None None None None None None
> ##  18   24 None None None None None None None None None None None
> None None None None None None
> ##  19   11 None None None None None None None None None None None
> None None None None None None
> ##  20    6 None None None None None None None None None None None
> None None None None None None
> ##  21    6 None None None None None None None None None None None
> None None None None None None
> ##  22    4 None None None None None None None None None None None
> None None None None None None
>
> ##  From the query we have the word size as row header and size of
> ##  anagram set as column header. The data value is the count of
> ##  how many different anagram sets match the row/column header.
> ##
> ##  For example, there are 7321 different 7-letter signatures that
> ##  have 2 anagram sets. There is 1 5-letter signature having a
> ##  23 member anagram set.
> ##
> ##  We can then pick any of these, say the single 10 member anagram
> ##  set of 9-letter words, and query out out the anagrams:
>
> cursor.execute("SELECT * FROM
> signatures_lookup_by_anagram_select_signature")
> results = cursor.fetchall()
> for i in results:
>   for j in i:
>     print j,
>   print
>
> ##  9 10 anoretics 10101000100001100111000000
> ##  9 10 atroscine 10101000100001100111000000
> ##  9 10 certosina 10101000100001100111000000
> ##  9 10 creations 10101000100001100111000000
> ##  9 10 narcotise 10101000100001100111000000
> ##  9 10 ostracine 10101000100001100111000000
> ##  9 10 reactions 10101000100001100111000000
> ##  9 10 secration 10101000100001100111000000
> ##  9 10 tinoceras 10101000100001100111000000
> ##  9 10 tricosane 10101000100001100111000000
>
> ## Nifty, eh?
>
>
>
> > DG

Yes, nifty.  Thanks for all the help, all!

DG


From inq1ltd at inqvista.com  Wed Jan  9 12:30:00 2008
From: inq1ltd at inqvista.com (jim-on-linux)
Date: Wed, 09 Jan 2008 12:30:00 -0500
Subject: user friendly datetime features
In-Reply-To: 
References: 
Message-ID: <200801091230.00894.inq1ltd@inqvista.com>



Why not build your own module?  You can use it where and when you need 
it.

jim-on-linux
http://www.inqvista.com



On Tuesday 08 January 2008 20:19, Daniel Fetchinson wrote:
> Many times a more user friendly date format is convenient than the
> pure date and time.
> For example for a date that is yesterday I would like to see
> "yesterday" instead of the date itself. And for a date that was 2
> days ago I would like to see "2 days ago" but for something that
> was 4 days ago I would like to see the actual date. This is often
> seen in web applications, I'm sure you all know what I'm talking
> about.
>
> I'm guessing this feature is needed so often in so many projects
> that it has been implemented already by several people. Does anyone
> know of such a stand alone module?


From mwm-keyword-python.b4bdba at mired.org  Sat Jan 12 15:25:53 2008
From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer)
Date: Sat, 12 Jan 2008 15:25:53 -0500
Subject: where do my python files go in linux?
In-Reply-To: <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com>
References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com>
	<20080112113759.GJ75977@nexus.in-nomine.org>
	<11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com>
Message-ID: <20080112152553.638cfa3d@bhuda.mired.org>

On Sat, 12 Jan 2008 16:13:08 +0100 "Jorgen Bodde"  wrote:
> > Normally you'd split up the bulk of the code into a module which gets
> > installed into site-packages and a piece of stand-alone front-end code which
> > imports the module and executes whatever you need to do and gets installed
> > into a typical PATH directory.
> I would agree but it is not a site package I am trying to distribute,
> but a wxPython application. I would not think my app belongs in the
> python site packages dir.

I suspect that's because your app is "simple", in that it only has one
command. Many apps have multiple commands that share the same set of
libraries. So putting a package for that app in site-packages makes a
lot of sense. If your app-specific library is properly designed and
documented, users may be able to build further commands for the system
as well.

On the issue of .pyc files - don't distribute them. Instead, arrange
for the install package to run the compileall.py script (in the
standard library) on your libraries. .pyc files are *not* guaranteed
to be platform independent (even though the latest rpm tools seem to
claim otherwise), so if you build them for your platform, they may
well be unusable after being installed.

     		http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.


From bignose+hates-spam at benfinney.id.au  Mon Jan 28 03:21:48 2008
From: bignose+hates-spam at benfinney.id.au (Ben Finney)
Date: Mon, 28 Jan 2008 19:21:48 +1100
Subject: py3k feature proposal: field auto-assignment in constructors
References: 
	<0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com>
	<87d4rm93l1.fsf@benfinney.id.au>
	<479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net>
	
	<8763xe8vzd.fsf@benfinney.id.au>
	
Message-ID: <87y7aa742r.fsf@benfinney.id.au>

"Russ P."  writes:

> OK, then how about a special function that could be called from
> inside the constructor (or anywhere else for that matter) to
> initialize a list of data members. For example,
> 
> self.__set__(host, port, protocol, bufsize,
>     timeout)
> 
> This would be equivalent to
> 
> self.host = host
> self.port = port
> # etc.
> 
> I'm not sure if that is technically feasible, but it would cut down
> on repetition of names.

It's much more attractive, because it doesn't change the function
signature. In fact, here's a variation that doesn't even need a
language change::

    >>> class Foo(object):
    ...     def __init__(self, spam, eggs, beans):
    ...         self.__dict__.update(dict(
    ...             (name, value) for (name, value) in vars().items()
    ...             if name in ['spam', 'beans']))
    ... 
    >>> foo = Foo("some spam", "more eggs", "other beans")
    >>> foo.spam
    'some spam'
    >>> foo.eggs
    Traceback (most recent call last):
      File "", line 1, in ?
    AttributeError: 'Foo' object has no attribute 'eggs'
    >>> foo.beans
    'other beans'

-- 
 \       "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 bret.wortman at gmail.com  Tue Jan 22 14:52:30 2008
From: bret.wortman at gmail.com (Bret)
Date: Tue, 22 Jan 2008 11:52:30 -0800 (PST)
Subject: A global or module-level variable?
Message-ID: <7637fd0b-961e-4730-abd8-96e85c907082@i72g2000hsd.googlegroups.com>

This has to be easier than I'm making it....

I've got a module, remote.py, which contains a number of classes, all
of whom open a port for communication.  I'd like to have a way to
coordinate these port numbers akin to this:

So I have this in the __init__.py file for a package called cstore:

nextport=42000

def getNextPort():
    nextport += 1
    return nextport

:
Then, in the class where I wish to use this (in cstore.remote.py):
:


class Spam():

    def __init__(self, **kwargs):
        self._port = cstore.getNextPort()

I can't seem to make this work, though.  As given here, I get an
"UnboundLocalError:local variable 'nextport' referenced before
assignment".  When I try prefixing the names inside __init__.py with
"cstore.", I get an error that the global name "cstore" is not
defined.

I've been looking at this long enough that my eyes are blurring.  Any
ideas?

BTW, the driving force here is that I'm going to need to wrap this in
some thread synchronization.  For now, though, I'm just trying to get
the basics working.

Thanks!


Bret


From http  Sun Jan 27 20:56:46 2008
From: http (Paul Rubin)
Date: 27 Jan 2008 17:56:46 -0800
Subject: optional static typing for Python
References: 
	<0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com>
Message-ID: <7xbq76pva9.fsf@ruckus.brouhaha.com>

Paddy  writes:
> I would rather advocate such random test generation methods as being
> more appropriate for testing software in safety critical systems when
> the programming language is dynamic.

That method totally failed to find the Pentium FDIV bug, and they use
static proof checkers like ACL2 now.


From george.sakkis at gmail.com  Thu Jan 17 01:25:38 2008
From: george.sakkis at gmail.com (George Sakkis)
Date: Wed, 16 Jan 2008 22:25:38 -0800 (PST)
Subject: assigning values in python and perl
References:  
	<2d37f441-c01f-439b-9897-35b7e4dfa77b@h11g2000prf.googlegroups.com> 
	
Message-ID: <34e2dc93-9819-479f-a8d5-79d11350f0b3@s8g2000prg.googlegroups.com>

On Jan 17, 1:03 am, Christian Heimes  wrote:

> George Sakkis wrote:
> > Python's parameter passing is like passing a pointer in C/C++.
>
> [snip]
>
> It's not (I repeat NOT) like passing a pointer in C. Please readhttp://effbot.org/zone/call-by-object.htm
>
> Christian

Posting a counter-example where the difference is clearly shown would
be more vastly useful than referring to a list of long obscure usenet
posts with practically no examples. C/C++ are not even mentioned in
that page. I am not claiming you are wrong, I just don't find
particularly this page particularly enlightening.

George


From David.Reksten at sweco.no  Thu Jan 10 07:39:52 2008
From: David.Reksten at sweco.no (David.Reksten at sweco.no)
Date: Thu, 10 Jan 2008 13:39:52 +0100
Subject: SV: Conventions for dummy name
In-Reply-To: <87odbt27ph.fsf@physik.rwth-aachen.de>
References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de><873at6k2qt.fsf_-_@benfinney.id.au><87sl1613c8.fsf@physik.rwth-aachen.de>
	<87odbt27ph.fsf@physik.rwth-aachen.de>
Message-ID: <6A539E6F80E48B40A81F5169256139D301D982B8@srvmail02.nettverk.int>

Torsten Bronger writes:
>David.Reksten at sweco.no writes:
>
>> Torsten Bronger wrote:
>>
>>> [...]
>>>
>>> Right, that's because I've used "__" where not all returning
>>> values are interesing to me such as
>>>
>>> a, b, __ = function_that_returns_three_values(x, y)
>>
>> Variable name "dummy" serves the same purpose, such as:
>>
>>     a, b, dummy = function_that_returns_three_values(x, y)
>
>Granted, but my rationale is that "__" is less visible in the source
>code, so there is more emphasis on the actually interesting
>variables.

I guess it's a matter of preference. Personally, I find "dummy" to be more
explicit, and hence more readable for those that that will read my code
later. YMMV.

Regards,
.david


From jpeng at block.duxieweb.com  Mon Jan 21 04:32:42 2008
From: jpeng at block.duxieweb.com (J. Peng)
Date: Mon, 21 Jan 2008 17:32:42 +0800
Subject: Sorting a list depending of the indexes of another sorted list
In-Reply-To: 
References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com>	<479451D9.3060207@block.duxieweb.com>	
	
Message-ID: <479466BA.7080206@block.duxieweb.com>

Steven D'Aprano ??:
> On Mon, 21 Jan 2008 16:23:50 +0800, J. Peng wrote:
> 
>> J. Peng ??:
>>
>>>    k = (i.split())[3]
>>>    y = (i.split())[1]
>> btw, why can't I write the above two into one statement?
>>
>> (k,y) = (i.split())[3,1]
> 
> I don't know. What's "i"?
> 
> I'm guessing "i" is a string (and what a horrible choice of a name for a 
> string!) So i.split() will return a list. List indexing with multiple 
> arguments isn't defined, which is why you can't write 
> 
> k, y = (i.split())[3,1]
> 

Thanks.
Then one have to split the list twice.Given the list is large,it's maybe 
not good for performance.Is it a more effective split way?


From mnordhoff at mattnordhoff.com  Sun Jan 13 05:26:49 2008
From: mnordhoff at mattnordhoff.com (Matt Nordhoff)
Date: Sun, 13 Jan 2008 05:26:49 -0500
Subject: Elementary string-formatting
In-Reply-To: 
References: 
Message-ID: <4789E769.4020404@mattnordhoff.com>

Odysseus wrote:
> Hello, group: I've just begun some introductory tutorials in Python. 
> Taking off from the "word play" exercise at
> 
> 
> 
> I've written a mini-program to tabulate the number of characters in each 
> word in a file. Once the data have been collected in a list, the output 
> is produced by a while loop that steps through it by incrementing an 
> index "i", saying
> 
> print '%2u %6u %4.2f' % \
> (i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0])

This isn't very important, but instead of keeping track of the index
yourself, you can use enumerate():

>>> mylist = ['a', 'b', 'c']
>>> for i, item in enumerate(mylist):
...     print i, item
...
0 a
1 b
2 c
>>>

Err, it doesn't look like you can make it start at 1 though.


-- 


From fredrik at pythonware.com  Sun Jan 13 07:31:05 2008
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Sun, 13 Jan 2008 13:31:05 +0100
Subject: __init__  explanation please
In-Reply-To: <20080113104641.GN75977@nexus.in-nomine.org>
References: <47895d25$0$30708$4c368faf@roadrunner.com>
	<20080113104641.GN75977@nexus.in-nomine.org>
Message-ID: 

Jeroen Ruigrok van der Werven wrote:

> I personally tend to see __init__ or __new__ as equivalent to what other
> languages call a constructor.
> 
> (And I am sure some people might disagree with that. ;))

given that they do different things, I'm not sure it's that helpful to 
describe them *both* as constructors.





From george.sakkis at gmail.com  Mon Jan 14 15:17:40 2008
From: george.sakkis at gmail.com (George Sakkis)
Date: Mon, 14 Jan 2008 12:17:40 -0800 (PST)
Subject: Dynamical scoping
Message-ID: <1a3243ef-13f6-40d6-97eb-198b8742ac3d@d4g2000prg.googlegroups.com>

What's the best way to simulate dynamically scoped variables ala
Lisp ? The use case is an open-ended set of objects that need to
access the same piece of information (e.g. a  dict, a ConfigParser
object, a logger etc.). I know that the "proper" OO and functional way
is to pass the information explicitly but that's less maintenable in
the long run. Also this is in a web environment so the information
can't be really global (though within-thread global should be fine).
Is there some standard pattern for this scenario ?

George


From levilista at gmail.com  Thu Jan 10 13:36:48 2008
From: levilista at gmail.com (zslevi@gmail.com)
Date: Thu, 10 Jan 2008 10:36:48 -0800 (PST)
Subject: What is "lambda x=x : ... " ?
References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com>
Message-ID: <9d596a40-6cf3-4139-b1f9-5e5d766c4462@s12g2000prg.googlegroups.com>

I've figured it out, it is default argument.
print  y()
gives 13 as result.

It's a bit evil though.
I hope this post will be useful some newbie like i'm now someday :)

On Jan 10, 7:25 pm, "zsl... at gmail.com"  wrote:
> I'm reading this page:http://www.ps.uni-sb.de/~duchier/python/continuations.html
> and I've found a strange usage of lambda:
>
> ####################
> Now, CPS would transform the baz function above into:
>
> def baz(x,y,c):
>         mul(2,x,lambda v,y=y,c=c: add(v,y,c))
>
> ###################
>
> What does "y=y" and "c=c" mean in the lambda function?
> I thought it bounds the outer variables, so I experimented a little
> bit:
>
> #################
> x = 3
> y = lambda x=x : x+10
>
> print y(2)
> ##################
>
> It prints 12, so it doesn't bind the variable in the outer scope.



From qgallet at gmail.com  Thu Jan 17 09:05:56 2008
From: qgallet at gmail.com (Quentin Gallet-Gilles)
Date: Thu, 17 Jan 2008 15:05:56 +0100
Subject: Loop in a loop?
In-Reply-To: 
References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com>
	
	
Message-ID: <8b943f2b0801170605x548d4678r3cf9e6129c1188e5@mail.gmail.com>

On Jan 17, 2008 2:38 PM, Sacred Heart  wrote:

> On Jan 17, 1:35 pm, cokofree... at gmail.com wrote:
> > for i in zip(array1, array2):
> >     print i
> >
> > Although I take it you meant four d, the issue with this method is
> > that once you hit the end of one array the rest of the other one is
> > ignored.
>
> Yes, small typo there.
>
> Okey, so if my array1 is has 4 elements, and array2 has 6, it won't
> loop trough the last 2 in array2? How do I make it do that?
>
>
In that case, you can use map(). It pads the shortest list with None.

>>> array1 = ['one','two','three','four', 'five', 'six']
>>> array2 = ['a','b','c','d']
>>> map(None, array1, array2)
[('one', 'a'), ('two', 'b'), ('three', 'c'), ('four', 'd'), ('five', None),
('six', None)]

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

From deets at nospam.web.de  Thu Jan 24 18:48:53 2008
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 25 Jan 2008 00:48:53 +0100
Subject: global/local variables
In-Reply-To: 
References: 
Message-ID: <5vsmf9F1nnebqU1@mid.uni-berlin.de>

Tim Rau schrieb:
> What makes python decide whether a particular variable is global or
> local? I've got a list and a integer, both defined at top level, no
> indentation, right next to each other:
> 
> allThings = []
> nextID = 0
> 
> and yet, in the middle of a function, python sees one and doesn't see
> the other:
> 
> class ship(thing):
> ###snip###
>     def step(self):
> ###snip###
>         if keys[K_up]
>             for n in range(0,2):  #sparks/newton second is
> proportional to framerate
>                 divergence = 5.0
>                 p = self.body.getRelPointPos((-0.15,0,0))
>                 v = self.body.vectorToWorld((-100+ random.uniform(-
> divergence,divergence) ,random.uniform(-divergence,divergence),0))
>                 allThings.append(particle(p,v))
>                 allThings[len(allThings)-1].id = nextID
>                 nextID += 1
> 
> 
> I don't think it's important, but the function is defined before the
> two globals. What gives?

The difference is that you assign to nextID in your function. Statements 
of the form


foo = expression

will make foo a function-local variable.

If you want it to be a module-global, you need to do

global foo

foo = expression

If you do this:


bar = 10

def f():
    print bar

you don't assign to a variable, but only read. So if it's not found 
locally, it will be looked up globally.

Diez


From boblatest at yahoo.com  Tue Jan 22 04:12:19 2008
From: boblatest at yahoo.com (Robert Latest)
Date: 22 Jan 2008 09:12:19 GMT
Subject: Question on sort() key function
References: <5vlopgF1mv4ekU1@mid.dfncis.de>
	<7xve5mfdmr.fsf@ruckus.brouhaha.com>
Message-ID: <5vlqbjF1kl9cjU1@mid.dfncis.de>

Paul Rubin wrote:
> The attribute is on instances of File, not on the class itself.  See
> if this works:
>
>    flist.sort(key=lambda f: f.mod_date.toordinal)

It doesn't throw an error any more, but neither does it sort the list. This, 
however, works:

----------------------
def by_date(f1, f2):
	return f1.mod_date.toordinal() - f2.mod_date.toordinal()

flist.sort(by_date)
----------------------

So I'm sticking with it, although I sort of liked the key approach.

robert


From k.shaposhnikov at gmail.com  Tue Jan 22 09:10:40 2008
From: k.shaposhnikov at gmail.com (Konstantin Shaposhnikov)
Date: Tue, 22 Jan 2008 06:10:40 -0800 (PST)
Subject: stdin, stdout, redmon
References: <4794a5e3$0$9014$426a74cc@news.free.fr>
	 
	<4794ab22$0$19179$426a74cc@news.free.fr>
	 
	<4795ba80$0$17176$426a74cc@news.free.fr>
	
	
	<372ff091-2739-4178-bc36-4f8aaffe2972@e23g2000prf.googlegroups.com>
Message-ID: 

Sorry, I meant:

Alternatively you can use following command

  cat file | python script.py

instead of

  cat file | script.py




On Jan 22, 1:54 pm, Konstantin Shaposhnikov 
wrote:
> Hi,
>
> This is Windows bug that is described here:http://support.microsoft.com/default.aspx?kbid=321788
>
> This article also contains solution: you need to add registry value:
>
> HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies
> \Explorer
> InheritConsoleHandles = 1 (REG_DWORD type)
>
> Do not forget to launch new console (cmd.exe) after editing registry.
>
> Alternatively you can use following command
>
>   cat file | python script.py
>
> instead of
>
>   cat file | python script.py
>
> Regards,
> Konstantin
>
> On Jan 22, 1:02 pm, Rolf van de Krol  wrote:
>
> > Well, that's at least weird. I did test my code with Python 2.5 on Win
> > XP, using the command prompt. But testing it with IDLE gives exactly the
> > same error Bernard has. So apparently STDIN can't be accessed with IDLE.
>
> > Rolf
>
> > John Machin wrote:
>
> > > Excuse me, gentlemen, may I be your referee *before* you resort to
> > > pistols at dawn?
>
> > > ===== IDLE =====
> > > IDLE 1.2.1
>
> > >>>> import sys
> > >>>> sys.stdin.readlines
>
> > > Traceback (most recent call last):
> > >   File "", line 1, in 
> > >     sys.stdin.readlines
> > > AttributeError: readlines
>
> > > ===== Command Prompt =====
> > > C:\junk>python
> > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
> > > (Intel)] on win32
> > > Type "help", "copyright", "credits" or "license" for more information.
>
> > >>>> import sys
> > >>>> sys.stdin.readlines
>
> > > 
>
> > > HTH,
> > > John



From kyosohma at gmail.com  Mon Jan  7 14:13:29 2008
From: kyosohma at gmail.com (kyosohma at gmail.com)
Date: Mon, 7 Jan 2008 11:13:29 -0800 (PST)
Subject: Does Python cache the startup module?
References: 
Message-ID: 

On Jan 7, 12:30 pm, Baz Walter  wrote:
> Hello
>
> I remember reading somewhere (probably this list) that python may cache the
> module that starts a program (e.g. 'main.py'). I'm asking because I have found
> that this can sometimes cause problems when making small edits to the module.
> For instance, in my current module I changed the name of the main gui widget.
> When I ran the program, the program started to leak memory like a sieve. I then
> changed the name back again, and the problem went away. This looks very much
> like some sort of weird caching behaviour to me.
>
> I've tried deleting the .pyc file and even re-booting, but I can't make the
> problem go away!
>
> Can anyone confirm that this caching happens? And if so, is it documented
> anywhere?
>
> TIA

You can run a dir() in the GUI IDLE or the command line IDLE and see
what's currently "cached", so to speak. In the GUI IDLE, you can
"flush" it out by going to the Shell menu and choosing Restart Shell.

It should only display the following after a restart:

>>> dir()
['__builtins__', '__doc__', '__name__']


HTH

Mike



From gagsl-py2 at yahoo.com.ar  Wed Jan 30 09:01:13 2008
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 30 Jan 2008 06:01:13 -0800 (PST)
Subject: comparing two lists, ndiff performance
References: 
Message-ID: <4382b56f-76e7-4779-a3fc-43eafef365a6@i72g2000hsd.googlegroups.com>

On 29 ene, 22:47, Zbigniew Braniecki 
wrote:

> The new one is of course much better and cleaner (the old one is
> bloated), but I'm wondering if there is a faster way to compare two
> lists and find out what was added, what was removed, what was changed.
> I can simply iterate through two lists because I need to keep an order
> (so it's important that the removed line is after the 3 line which was
> not changed etc.)
>
> ndiff plays well here, but it seems to be extremely slow (1000
> iterations of diffToObject takes 10 sec, 7sec of this is in ndiff).

ndiff does a quadratic process: first determines matching lines using
a SequenceMatcher, then looks for near-matching lines and for each
pair, compares them using another SequenceMatcher.
You don't appear to be interested in what changed inside a line, just
that it changed, so a simple SequenceMatcher would be enough.
Output from SequenceMatcher is quite different than ndiff, but you'd
have to reimplement the _compareLists method only.

--
Gabriel Genellina


From jimgardener at gmail.com  Sun Jan  6 02:55:04 2008
From: jimgardener at gmail.com (jimgardener at gmail.com)
Date: Sat, 5 Jan 2008 23:55:04 -0800 (PST)
Subject: how to use bool
References: 
	<05c5df8b-15c4-47e6-8c14-72c57a84a0ea@y5g2000hsf.googlegroups.com> 
	<2c516040-0193-4de3-bf7d-b61e739cdc2d@l57g2000hsa.googlegroups.com>
Message-ID: <8bdb4424-0265-4393-8cf3-fe6a84e62458@v4g2000hsf.googlegroups.com>

hi bukzor & everyone who replied

thanks for the detailed replies
will try to write that way
thanx a lot
jim



bukzor wrote:
> On Jan 4, 8:51 am, bukzor  wrote:
>
> #exercise of the class and error handling
> m = myclass()
> try:
>     m.mymethod()
>     print "Completed successfully!"
> except SthingError, ste:
>     print "STHINGERROR:"
>     print ste
> except Exception, e: print e
>
> print
> print "This time no error handling:"
> m.mymethod()


From jzgoda at o2.usun.pl  Thu Jan 31 04:40:09 2008
From: jzgoda at o2.usun.pl (Jarek Zgoda)
Date: Thu, 31 Jan 2008 10:40:09 +0100
Subject: Updating documents in PyLucene
In-Reply-To: 
References: 
Message-ID: <47A19779.40001@o2.usun.pl>

gefafwisp at gmail.com napisa?(a):

> The way that Lucene (and by extension, PyLucene) seems to work is that
> updates to documents are implemented by the user as a document
> addition (of the new version) and subsequent deletion (of the old
> version).

I'd switch the operations, first delete then add. Solr does this that
way and I decided to follow.

> My problem is that I'd like to update a number of documents which have
> their Store flag set to NO - they're indexed, but not stored. I don't
> have the original text content of these documents available anywhere
> else - is there any way for me to get this un-stored indexed data from
> the old document into the new?

I think the answer is "no", there has to be some way of identifying
records that have to be deleted. If you do not store any document UID,
you are out of luck.

Anyway, you may get some hints on lucene mailing list.

-- 
Jarek Zgoda
Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101

"We read Knuth so you don't have to." (Tim Peters)


From mail at timgolden.me.uk  Wed Jan 23 09:53:40 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 23 Jan 2008 14:53:40 +0000
Subject: csv to xls using python 2.1.3
In-Reply-To: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com>
References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com>
Message-ID: <479754F4.2050205@timgolden.me.uk>

LizzyLiz wrote:
> Hi
> 
> I need to convert a .csv file to .xls file using python 2.1.3 which
> means I can't use pyExcelerator!  Does anyone know how I can do this?
> 
> Many thanks
> LizzyLiz

Use win32com.client to start Excel, tell it to .Open the .csv
file and then tell it to .SaveAs an Excel workbook.

TJG


From sjmachin at lexicon.net  Sun Jan 27 17:20:03 2008
From: sjmachin at lexicon.net (John Machin)
Date: Sun, 27 Jan 2008 14:20:03 -0800 (PST)
Subject: translating Python to Assembler
References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com>
	<13pdiaqsdicf9eb@corp.supernews.com> 
	<5vosafF1nn9odU2@mid.individual.net>
	 
	
	
	<92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> 
	
	
	
Message-ID: <6a087729-fd47-4344-ba58-208c3e8f5f05@t1g2000pra.googlegroups.com>

On Jan 27, 10:23 pm, o... at thepond.com wrote:
> >> >ajaksu at Belkar:~$ ndisasm error.txt
> >> >00000000  54                push sp
> >> >00000001  686973            push word 0x7369
> >> >00000004  206973            and [bx+di+0x73],ch
> >> >00000007  206E6F            and [bp+0x6f],ch
> >> >0000000A  7420              jz 0x2c
> >> >0000000C  61                popa
> >> >0000000D  7373              jnc 0x82
> >> >0000000F  656D              gs insw
> >> >00000011  626C65            bound bp,[si+0x65]
> >> >00000014  722E              jc 0x44
> >> >00000016  2E                db 0x2E
> >> >00000017  2E                db 0x2E
> >> >00000018  0A                db 0x0A
>
> >> >:/
>
> >> not sure what you're saying. Sure looks like assembler to me. Take the
> >> '54   push sp'. The 54 is an assembler opcode for push and the sp is
> >> the stack pointer, on which it is operating.
>
> >go troll somewhere else (you obviously don't know anything about
> >assembler and don't want to learn anything about Python).
>
> >-- bjorn
>
> before you start mouthing off, maybe you should learn assembler. If
> you're really serious, go to the Intel site and get it from the horses
> mouth. The Intel manual on assembler lists the mneumonics as well as
> the opcodes for each instruction. It's not called the Intel Machine
> Code and Assembler Language Manual. It's the bible on assembly
> language, written by Intel.
>
> If you're not so serious, here's a URL explaining it, along with an
> excerpt from the article:
>
> http://en.wikipedia.org/wiki/X86_assembly_language
>
> Each x86 assembly instruction is represented by a mnemonic, which in
> turn directly translates to a series of bytes which represent that
> instruction, called an opcode. For example, the NOP instruction
> translates to 0x90 and the HLT instruction translates to 0xF4. Some
> opcodes have no mnemonics named after them and are undocumented.
> However processors in the x86-family may interpret undocumented
> opcodes differently and hence might render a program useless. In some
> cases, invalid opcodes also generate processor exceptions.
>
> As far as this line from your code above:
>
> 00000001  686973            push word 0x7369
>
> 68 of 686973 is the opcode for PUSH. Go on, look it up. The 6973 is
> obviously the word address, 0x7369. Or, do you think that's
> coincidence?
>
> Don't fucking tell me about assembler, you asshole. I can read
> disassembled code in my sleep.

What was originally posted was:
"""
ajaksu at Belkar:~$ cat error.txt
This is not assembler...

ajaksu at Belkar:~$ ndisasm error.txt
00000000  54                push sp
00000001  686973            push word 0x7369
00000004  206973            and [bx+di+0x73],ch
[snip]
"""

Read it again -- he's "disassembled" the text "This is not
assembler..."

54 -> "T"
686973 -> "his"
206973 -> " is"

but you say "68 of 686973 is the opcode for PUSH. Go on, look it up.
The 6973 is obviously the word address, 0x7369. Or, do you think
that's coincidence?"

You are a genius of a kind encountered only very rarely. Care to share
with us your decryption of the Voynich manuscript?


From bj_666 at gmx.net  Wed Jan 23 05:55:03 2008
From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch)
Date: 23 Jan 2008 10:55:03 GMT
Subject: Module/package hierarchy and its separation from file structure
References: 
Message-ID: <5voko7F1ni1rjU1@mid.uni-berlin.de>

On Wed, 23 Jan 2008 03:49:56 -0600, Peter Schuller wrote:

> Let me just shoot down one possible suggestion right away, to show you
> what I am trying to accomplish:
> 
> I do *not* want to simply break out X into org.lib.animal.x, and have
> org.lib.animal import org.lib.animal.x.X as X.

Then you shoot down the idiomatic answer I guess.  That's what most people
do.

Ciao,
	Marc 'BlackJack' Rintsch


From jazle at localhost.com  Tue Jan 15 20:17:32 2008
From: jazle at localhost.com (Jaimy Azle)
Date: Wed, 16 Jan 2008 08:17:32 +0700
Subject: Python too slow?
References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com>
	<4785d960$0$22237$426a74cc@news.free.fr>
	
	<478733a9$0$18055$426a34cc@news.free.fr>
	
	<47877a9c$0$2437$426a34cc@news.free.fr>
	<877iiga0hb.fsf@mulj.homelinux.net>
	
	
	
Message-ID: 

"Paul Boddie"  wrote:
>>
>> perhaps in the future another sillly point could be added also, Java has
>> Jython, while Python doesn't have some thing like PyJava or... perhaps 
>> Py-va
>> (Python based Java Language).
>
> You could compile Java to CPython bytecode or, in the case of a little
> experiment I did some time ago, translate Java bytecode to CPython
> bytecode: the CPython virtual machine operates at a higher level and
> can support the Java instructions fairly easily, whereas a fair amount
> of work is required to support CPython instructions on the Java
> virtual machine. I found that the biggest obstacle was probably
> treating Java packages like Python packages - something which
> admittedly isn't completely necessary, but which would make the thing
> more usable at the prompt. Ultimately, I had little need for Java-
> based software and thus wasn't motivated into continuing the work,
> although Python 2.5 and beyond do provide some conveniences which
> might make some aspects of the implementation more bearable.
>

Wow, serious... what you've done was really, really cool... :)

I was expect there are nobody willing to do to have python runs Java 
Language (such as PyPy) over CPython. Perhaps your javaclass does not work 
just like as PyPy, but really... it is damned cool to get CPython execute 
java byte-code, congratulations...

Salam,

-Jaimy. 




From ejensen at visi.com  Fri Jan 11 11:27:56 2008
From: ejensen at visi.com (Ed Jensen)
Date: Fri, 11 Jan 2008 16:27:56 -0000
Subject: Python too slow?
References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com>
	<47852dd8$0$27994$426a74cc@news.free.fr>
	<13oattm5ijqvf58@corp.supernews.com>
	<4785d960$0$22237$426a74cc@news.free.fr>
	<13od12b23hfv772@corp.supernews.com>
	
	<13od4lm3cepf0ac@corp.supernews.com>
	<47873143$0$21435$426a74cc@news.free.fr>
Message-ID: <13of68cn8hnk2f3@corp.supernews.com>

Bruno Desthuilliers  wrote:
> I don't think you're going to make you some friends here insulting 
> Fredrik. I don't know who Ed Jensen is, but we are quite a lot here to 
> know and respect Mr Lundh for his contributions to Python as both a 
> language and a community.

I'll keep in mind that some people around these parts are untouchable
and have a free pass to be insulting and childish.

Thanks for the tip.


From nagle at animats.com  Fri Jan 11 01:13:36 2008
From: nagle at animats.com (John Nagle)
Date: Thu, 10 Jan 2008 22:13:36 -0800
Subject: Analyzing Python GC output - what is a "cell", and what information
	is available about it.
Message-ID: <478707f2$0$36360$742ec2ed@news.sonic.net>

I'm printing out each entry in "gc.garbage" after a garbage collection in
DEBUG_LEAK mode, and I'm seeing many entries like



That's the output of "repr".   Are "cell" objects created only from
external C libraries, or can regular Python code generate them?  Is there
any way to find out what the 'function object' is from within Python?

(I'm looking for a possible memory leak, obviously.)

				John Nagle


From eegunnar at yahoo.com  Wed Jan  9 17:25:36 2008
From: eegunnar at yahoo.com (erik gartz)
Date: Wed, 9 Jan 2008 14:25:36 -0800 (PST)
Subject: for loop without variable
Message-ID: 

Hi. I'd like to be able to write a loop such as:
for i in range(10):
    pass
but without the i variable. The reason for this is I'm using pylint
and it complains about the unused variable i. I can achieve the above
with more lines of code like:
i = 0
while (i != 10):
    i += 1
Is there a concise way to accomplish this without adding extra lines
of codes? Thanks in advance for your help.


From goon12 at gmail.com  Tue Jan 29 21:12:46 2008
From: goon12 at gmail.com (Joe Riopel)
Date: Tue, 29 Jan 2008 18:12:46 -0800
Subject: Removal of element from list while traversing causes the next
	element to be skipped
In-Reply-To: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com>
References: 
	<1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com>
Message-ID: <6a2ccd190801291812k76e4d817o3a3390363b30a046@mail.gmail.com>

On Jan 29, 2008 9:23 AM, attn.steven.kuo at gmail.com
 wrote:
> If you're going to delete elements from
> a list while iterating over it, then do
> it in reverse order:

how about
>>> li = [1,2,3,4,5]
>>> filter(lambda x: x != 3, li)
[1, 2, 4, 5]
>>>


From nstjelja at gmail.com  Wed Jan  9 00:55:30 2008
From: nstjelja at gmail.com (Nikola Stjelja)
Date: Wed, 9 Jan 2008 06:55:30 +0100
Subject: Pet Store
In-Reply-To: <44713824-c8c9-4a4c-af7e-042260068c0c@x69g2000hsx.googlegroups.com>
References: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com>
	<5ugv69F1hqn2cU3@mid.uni-berlin.de>
	<44713824-c8c9-4a4c-af7e-042260068c0c@x69g2000hsx.googlegroups.com>
Message-ID: <2d24984a0801082155l1c6447if1f6bd90822c3a85@mail.gmail.com>

On Jan 8, 2008 7:32 PM, George Maggessy  wrote:

> Yeap. It is. I'm looking for something like that app. Smth that I
> could base my future developments on.
>
> On Jan 8, 1:47 am, Marc 'BlackJack' Rintsch  wrote:
> > On Mon, 07 Jan 2008 22:21:53 -0800, George Maggessy wrote:
> > > I'm an experience Java developer trying to learn Python. I just
> > > finished the Python tutorial on python.org and I'm currently reading
> > > the "Learning Python" book. However, if I could find something like a
> > > simple web app with some best practices, such as those famous "Java
> > > Pet Store" apps, I think that would help me to fill up some gaps in my
> > > learning process. Does anybody know any app like that?
> >
> > Isn't that a web application using Java web frameworks?  So you are
> > looking for a Python web framework with a "Pet Store" tutorial?
> >
> > Ciao,
> >         Marc 'BlackJack' Rintsch
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

If you are looking for a good , well documented , easy to use but powerfull
web framework you deffinitely need to use Django.

-- 
Please visit this site and play my RPG!

http://www.1km1kt.net/rpg/Marinci.php
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From kyosohma at gmail.com  Wed Jan 23 11:15:55 2008
From: kyosohma at gmail.com (Mike Driscoll)
Date: Wed, 23 Jan 2008 08:15:55 -0800 (PST)
Subject: Processing XML that's embedded in HTML
References: 
	 
	<6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> 
	<47972624.2050002@web.de>
Message-ID: 

Stefan,

> I would really encourage you to use the normal parser here instead of iterparse().
>
>   from lxml import etree
>   parser = etree.HTMLParser()
>
>   # parse the HTML/XML melange
>   tree = etree.parse(filename, parser)
>
>   # if you want, you can construct a pure XML document
>   row_root = etree.Element("newroot")
>   for row in tree.iterfind("//Row"):
>       row_root.append(row)
>
> In your specific case, I'd encourage using lxml.objectify:
>
> http://codespeak.net/lxml/dev/objectify.html
>
> It will allow you to do this (untested):
>
>   from lxml import etree, objectify
>   parser = etree.HTMLParser()
>   lookup = objectify.ObjectifyElementClassLookup()
>   parser.setElementClassLookup(lookup)
>
>   tree = etree.parse(filename, parser)
>
>   for row in tree.iterfind("//Row"):
>       print row.relationship, row.StartDate, row.Priority * 2.7
>
> Stefan

Both the normal parser example and the objectify example you gave me
give a traceback as follows:

Traceback (most recent call last):
  File "\\clippy\xml_parser2.py", line 70, in -toplevel-
    for row in tree.iterfind("//Row"):
AttributeError: 'etree._ElementTree' object has no attribute
'iterfind'


Is there some kind of newer version of lxml?

Mike


From gslindstrom at gmail.com  Mon Jan  7 15:51:07 2008
From: gslindstrom at gmail.com (Greg Lindstrom)
Date: Mon, 7 Jan 2008 14:51:07 -0600
Subject: Tutorials at PyCon 2008 (US)
Message-ID: 

Hello Everyone-

I'd like to announce the tutorials sessions for PyCon 2008 (US).  As you may
know, this year PyCon is being held in Chicago, Illinois March 14-16 with
the Thursday before (the 13th) being "Tutorial Thursday".  We are expecting
nearly 600 Python enthusiasts to meet up for the conference and have 29
tutorial sessions scheduled on Thursday in three sessions; morning,
afternoon, and evening.  There is an extra fee to attend a tutorial, but the
sessions are 3 hours long (with a break) and are taught by some of the
smartest cookies in the Python community.  Pop on over to
http://us.pycon.org/2008/about/ for more information

Here's a list of the sessions currently offered (we may cancel a session if
there are fewer than 10 people registered, but that doesn't happen very
often). In particular, note that there are 4 different introduction to
Python tutorials aimed at different audiences.

*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 and Michael Baye)
   - Python plotting with matplotlib and
pylab(John Hunter)
   - SWIG Master Class
(David Beazley)
   - Secrets of the Framework
Creators(Feihong
Hsu)
   - 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 and Michael Baye)
   - 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 martin at v.loewis.de  Sun Jan 27 15:32:09 2008
From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=)
Date: Sun, 27 Jan 2008 21:32:09 +0100
Subject: Some questions about decode/encode
In-Reply-To: <6035alF1oh17aU3@mid.uni-berlin.de>
References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com>	<5vr1ekF1njt09U2@mid.uni-berlin.de>	<84f39f37-4d18-47c1-9349-bf3f471b2bf5@s19g2000prg.googlegroups.com>
	<6035alF1oh17aU3@mid.uni-berlin.de>
Message-ID: <479CEA49.6010007@v.loewis.de>

>> Is there any way to solve this better?
>> I mean if I shouldn't convert the GBK string to unicode string, what
>> should I do to make SAX work?
> 
> Decode it and then encode it to utf-8 before feeding it to the parser.

The tricky part is that you also need to change the encoding declaration
in doing so, but in this case, it should be fairly simple:

unicode_doc = original_doc.decode("gbk")
unicode_doc = unicode_doc.replace('gbk','utf-8',1)
utf8_doc = unicode_doc.encode("utf-8")

This assumes that the string "gbk" occurs in the encoding declaration
as



If the encoding name has a different spelling (e.g. GBK), you need to
cater for that as well. You might want to try replacing the entire
XML declaration (i.e. everything between ), or just the
encoding= parameter. Notice that the encoding declaration may include
' instead of ", and may have additional spaces, e.g.



HTH,
Martin


From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Mon Jan 28 11:03:28 2008
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Mon, 28 Jan 2008 17:03:28 +0100
Subject: [OT] "just like Java" (was :Re: translating Python to Assembler)
In-Reply-To: 
References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com>			<4799de28$0$12358$426a74cc@news.free.fr>
	
Message-ID: <479dfccf$0$19716$426a74cc@news.free.fr>

Jeroen Ruigrok van der Werven a ?crit :
> -On [20080125 14:07], Bruno Desthuilliers (bruno.42.desthuilliers at wtf.websiteburo.oops.com) wrote:
>> I'm surprised you've not been flamed to death by now - last time I 
>> happened to write a pretty similar thing, I got a couple nut case 
>> accusing me of being a liar trying to spread FUD about Java vs Python 
>> respective VMs inner working, and even some usually sensible regulars 
>> jumping in to label my saying as "misleading"...
> 
> I think your attitude in responding did not help much Bruno, if you want a
> honest answer.

Possibly, yes. Note that being personnally insulted for stating 
something both technically correct *and* (as is the case here) commonly 
stated here doesn't help either.


From paddy3118 at googlemail.com  Sat Jan 26 03:04:10 2008
From: paddy3118 at googlemail.com (Paddy)
Date: Sat, 26 Jan 2008 00:04:10 -0800 (PST)
Subject: Generational Interfaces
References: <1b7b3b47-72f0-4a5d-9185-4903e75dba47@d70g2000hsb.googlegroups.com>
Message-ID: 

On Jan 26, 5:03 am, Carl Banks  wrote:
> While thinking about generational garbage collection, the thought of
> generational interfaces occurred to me.  I'd thought I'd run it by you
> guys.  I'm curious if there are any examples of this out there.
>
> I've opined on this chat room before that interfaces are more often
> cumbersome than helpful, especially in the early stages of a project
> where lots of refactoring is (or ought to be) happening.  But as
> projects mature, interfaces do too, and that made me think interfaces
> could be generated automatically by monitoring the software over time.
>
> As an example, say I'm writing a flight simulator, and I have a
> abstract base class Airplane, that I want to have an interface
> someday, but I don't know what it is yet.  So I define an
>
> AirplaneInterface = InterfaceTracker("Airplane")
>
> What this does is to open a sort of persistent database called
> Airplane (details aren't important now).  The database tracks all
> objects that claim to implement the interface.
>
> So say the first airplane is a Piper Cherokee.  I'd write a class like
> this:
>
> class PiperCherokeeX1(object):
>     wingspan = 52.2
>     wingchord = 7.9
>     ...
>     def __init__(self):
>         self.x = 0.0
>         self.y = 0.0
>         self.z = 0.0
>         ...
>         set_up_initial_state()
>         ...
>         AirplaneInterface.report(self)
>     def move_stick(self,dx,dy):
>         ...
>     def move_thottle(self,ds):
>         ...
>     def move_rudder_pedals(self,ddr):
>         ...
>     def camera_matrix(self):
>         return self._quat_to_matrix(self.q0,self.q1,self.q2,self.q3)
>     def step(self,dt):
>         ...
>
> The key here is the call to AirplaneInterface.report() at the end of
> __init__; this tells the interface tracker that, as of this call, this
> object is implementing the Aircraft interface.
>
> At this point, the interface tracker notes that PiperCherokeeX1 object
> has certain methods (move_stick, move_throttle, etc), certain class
> attributes, and certain instance attributes.  And that's all it does--
> at first.  It just writes information into the database.
>
> As time passes, and development continues, methods and data are added,
> changed, reconfigured.  For instance, I might split up move_stick()
> into move_stick_x() and move_stick_y() for some reason.  Then I might
> get rid of these functions altogether in favor of a
> move_control(self,n,dx).  And so on.  I add more classes that
> implement the Aircraft interface, too.  They look almost nothing like
> the original interface.
>
> However, through all that, the class attribute "wingspan" remains
> there.  Until one day when the project is quite mature I add a new
> class, say Airbus380, that fails to define "wingspan".  When this
> class calls AirplaneInterface.report(), it raises an
> InterfaceException.
>
> Basically, the InterfaceTracker decides, after some threshold of
> nearly universal usage of a certain method or attribute, that it has
> become a required part of the interface and starts raising exceptions
> when it's not there.
>
> Make sense?  Details can vary, but that's the basic idea.  In this
> way, you can combine some of the openness that helps in early
> development, but also have some of the benefits of stricter typing
> when things mature and turn out to be pretty strictly useful, without
> much effort.
>
> Thoughts?  (Surely someone's thought to do this before.)
>
> Carl Banks

I thought a major use of an interface is to allow separate development
that comes together at the interface. If so then such fluid interface
changing would scupper separate development.

- Paddy.


From mario at ruggier.org  Wed Jan  2 07:16:16 2008
From: mario at ruggier.org (mario)
Date: Wed, 2 Jan 2008 04:16:16 -0800 (PST)
Subject: different encodings for unicode() and u''.encode(), bug?
References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com>
	<477B4B88.6070207@v.loewis.de>
	<391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com>
	 
	<323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> 
	<4af890f4-acbc-467c-995d-0593b0ef08ee@e6g2000prf.googlegroups.com>
Message-ID: <593794bb-370d-44af-9c3a-706222fa1140@i29g2000prf.googlegroups.com>

On Jan 2, 12:28 pm, John Machin  wrote:
> On Jan 2, 9:57 pm, mario  wrote:
>
> > Do not know what the implications of encoding according to "ANSI
> > codepage (CP_ACP)" are.
>
> Neither do I. YAGNI (especially on darwin) so don't lose any sleep
> over it.
>
> > Windows only seems clear, but why does it only
> > complain when decoding a non-empty string (or when encoding the empty
> > unicode string) ?
>
> My presumption: because it doesn't need a codec to decode '' into u'';
> no failed codec look-up, so no complaint. Any realistic app will try
> to decode a non-empty string sooner or later.

Yes, I suspect I will never need it ;)

Incidentally, the situation is that in a script that tries to guess a
file's encoding, it bombed on the file ".svn/empty-file" -- but why it
was going so far with an empty string was really due to a bug
elsewhere in the script, trivially fixed. Still, I was curious about
this non-symmetric behaviour for the empty string by some encodings.

Anyhow, thanks a lot to both of you for the great feedback!

mario


From http  Sun Jan 27 21:57:53 2008
From: http (Paul Rubin)
Date: 27 Jan 2008 18:57:53 -0800
Subject: py3k feature proposal: field auto-assignment in constructors
References: 
	<0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com>
	<87d4rm93l1.fsf@benfinney.id.au>
	<479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net>
Message-ID: <7xhcgyodvy.fsf@ruckus.brouhaha.com>

Wildemar Wildenburger  writes:
> class Server(object):
>      def __init__(self, self.host, self.port,
>                   self.protocol, self.bufsize, self.timeout):
>          pass
> ?

That could temporarily bind those attributes but it shouldn't
persistently mutate the object.

How about:

    class Server(object):
         def __init__(self, host, port, protocol, bufsize, timeout):
            self.(host, port, protocol, bufsize, timeout) = \
                  host, port, protocol, bufsize, timeout

That's fairly explicit yet cuts down the total amount of boilerplate.


From eproust at gmail.com  Sun Jan 20 11:50:19 2008
From: eproust at gmail.com (pythonewbie)
Date: Sun, 20 Jan 2008 08:50:19 -0800 (PST)
Subject: Linux/Win32 func. to get Python instdir (not exedir) + 
	site-packages => extensions mgmt
References:  
	
Message-ID: 

On 20 jan, 12:20, Christian Heimes  wrote:
> pythonewbie wrote:
> > I am stucked on creating a function to get the Python install
> > directory (and site-packages directory) with a 100% reliable method...
>
> Only one method is 100% reliable:
>
> try:
>     import yourextension
> except ImportError:
>     available = False
> else:
>     available = True
>
> Christian

Hi Christian,

OK thanks, interesting to detect if an extension is available or not.

But for different reasons I also want to get the absolute path of
Python install directory (not only the executable under Linux) and
site-packages directory.

How could I proceed ?


From mnordhoff at mattnordhoff.com  Mon Jan 14 09:06:04 2008
From: mnordhoff at mattnordhoff.com (Matt Nordhoff)
Date: Mon, 14 Jan 2008 09:06:04 -0500
Subject: ucs2 or ucs4?
In-Reply-To: 
References: 
Message-ID: <478B6C4C.3030809@mattnordhoff.com>

Neal Becker wrote:
> How do I tell if my python-2.5 is build with ucs2 or ucs4?

You can also check sys.maxunicode.

>>> import sys
>>> sys.maxunicode

If it's 1114111, you're UCS-4. If it's something much lower, you're UCS-2.
-- 


From deets at nospam.web.de  Fri Jan  4 12:41:02 2008
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 04 Jan 2008 18:41:02 +0100
Subject: Details about pythons set implementation
In-Reply-To: 
References: 
	<87bq818wbt.fsf@mulj.homelinux.net>
	
	
Message-ID: <5u79deF1gf91rU1@mid.uni-berlin.de>

bukzor schrieb:
> On Jan 4, 9:08 am, Sion Arrowsmith 
> wrote:
>> Hrvoje Niksic   wrote:
>>
>>> BTW if you're using C++, why not simply use std::set?
>> Because ... how to be polite about this? No, I can't. std::set is
>> crap. The implementation is a sorted sequence -- if you're lucky,
>> this is a heap or a C array, and you've got O(log n) performance.
>> But the real killer is that requirement for a std::set is that
>> T::operator< exists. Which means, for instance, that you can't
>> have a set of complex numbers....
>>
>> --
>> \S -- si... 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
> 
> Why cant you implement < for complex numbers? Maybe I'm being naive,
> but isn't this the normal definition?
>     a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2)
> 
> How do you implement a set without sorting?
> 
> Are you expecting better than O(log n)?

Of course, hashing does O(1) (most of the time, with a sane hash of course.)

Diez


From suyashjape at gmail.com  Sat Jan 12 03:21:56 2008
From: suyashjape at gmail.com (suyash jape)
Date: Sat, 12 Jan 2008 13:51:56 +0530
Subject: How to POST call and retrieve result page
In-Reply-To: <20080111115703.16dbabd7@mbook.mired.org>
References: <16314edc0801110114t346bca6ek71660132de60b91e@mail.gmail.com>
	<20080111115703.16dbabd7@mbook.mired.org>
Message-ID: <16314edc0801120021l913a100l2a514998d8856627@mail.gmail.com>

Hi

/search.php fills the text box values. But /search.php has two form action
elements

1) 
AND 2) I did GET and POST to both results.php page , which gives *'String could not be parsed as XML'* exception. Should data passed be in some XML format or normal query ? POST on blast_results.php also does not work. I guess i am not able to identify the variable names to be passed.For/search.php i found the variables.But couldnt in the other forms. Thanks for your help.. Suyash On Jan 11, 2008 10:27 PM, Mike Meyer wrote: > On Fri, 11 Jan 2008 14:44:19 +0530 "suyash jape" > wrote: > > > Hi all > > i want to access a web page through python script, fillup the necessary > > fields, > > and press submit button (which does POST call) and retrieve the result > page > > and retrieve some values from it. > > > > Here is the script i have written till now. > > > > >import urllib2 > > > # create array of name/value pairs > > > self.params = urllib.urlencode({'seqname': 'BioSequence', 'sequence': > > 'ATACATTATCCAAACATAAAAAGCATGGCTT'}) > > > > > > # send http-post > > > request = urllib.urlopen("http://www.hydrazome.metazome.net/search.php > ", > > params) > > > > > > # read back each line of reply > > > line = request.read() > > >print line > > > > This script fills up the correct values in the search.php page.But i am > not > > sure if it is doing the POST (submit call). > > Beacause in 'line' varialble, i am getting the search.php page.Not the > > result page which is blast_results.php. > > > > How to retrieve the result page? > > Sounds like you're not POSTing to the right page. > > The form on .../search.php lets you fill in values, but those values > are not necessarily POSTed to search.php. In particular, the form element > has an action attribute that has a URL to which the values on the page > should be posted. If that points to .../blast_results.php, then that's > the page you need to pass to urlopen with your data. > > -- > Mike Meyer < mwm at mired.org> > http://www.mired.org/consulting.html > Independent Network/Unix/Perforce consultant, email for more information. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From azam.farooq3 at gmail.com Wed Jan 30 01:04:05 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Tue, 29 Jan 2008 22:04:05 -0800 (PST) Subject: Do You Want a GSM Mobile with Amazing Features? Please click here Message-ID: <5f454014-6362-45f3-a940-a3ca04dc2178@c23g2000hsa.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 nytrokiss at gmail.com Tue Jan 22 19:31:51 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 23 Jan 2008 01:31:51 +0100 Subject: translating Python to Assembler In-Reply-To: References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: <8a6b8e350801221631n409fe89ci9b4a7113b6d8bd88@mail.gmail.com> The reason you were finding a Python Debugger when looking for the PDB files is because PDB is Python DeBugger! Also why would you be looking for a PDB file if you can read the C source! On Jan 22, 2008 11:55 PM, Wim Vander Schelden wrote: > Python modules and scripts are normally not even compiled, if they have > been, > its probably just the Python interpreter packaged with the scripts and > resources. > > My advice is that if you want to learn Python, is that you just read a book > about > it or read only resources. Learning Python from assembler is kind of... > strange. > > Not only are you skipping several generations of programming languages, > spanned > over a period of 40 years, but the approach to programming in Python is so > fundamentally different from assembler programming that there is simply no > reason > to start looking at if from this perspective. > > I truly hope you enjoy the world of high end programming languages, but > treat them > as such. Looking at them in a low-level representation or for a low-level > perspective > doesn't bear much fruits. > > Kind regards, > > Wim > > > > On 1/22/08, over at thepond.com wrote: > > My expertise, if any, is in assembler. I'm trying to understand Python > > scripts and modules by examining them after they have been > > disassembled in a Windows environment. > > > > I'm wondering if a Python symbols file is available. In the Windows > > environment, a symbol file normally has a PDB extension. It's a little > > unfortunate that Python also uses PDB for its debugger. Google, for > > whatever reason, wont accept queries with dots, hyphens, etc., in the > > query line. For example a Google for "python.pdb" returns +python > > +pdb, so I get a ridiculous number of returns referring to the python > > debugger. I have mentioned this to Google several times, but I guess > > logic isn't one of their strong points. :-) > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com From donn.ingle at gmail.com Sun Jan 13 15:57:53 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 22:57:53 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A77F0.4000502@v.loewis.de> References: <200801132048.08966.donn.ingle@gmail.com> <478A77F0.4000502@v.loewis.de> Message-ID: <200801132257.53214.donn.ingle@gmail.com> > Now you are mixing two important concepts - the *contents* > of the file with the *name* of the file. Then I suspect the error may be due to the contents having been written in utf8 from previous runs. Phew! It's bedtime on my end, so I'll try it again when I get a chance during the week. Thanks muchly. \d -- snappy repartee: What you'd say if you had another chance. Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From donn.ingle at gmail.com Thu Jan 24 14:44:15 2008 From: donn.ingle at gmail.com (Donn) Date: Thu, 24 Jan 2008 21:44:15 +0200 Subject: piping into a python script In-Reply-To: References: <200801241903.20082.donn.ingle@gmail.com> Message-ID: <200801242144.15722.donn.ingle@gmail.com> Thanks for the tips, I'll decode and try 'em all out. > Ah yes, Groo. Ever wonder who would win if Groo and Forrest Gump fought > each other? Heh ;) I reckon they'd both die laughing. Be fun to watch -- if anyone else survived! \d -- "A computer without Windows is like chocolate cake without mustard." -- Anonymous Coward /. Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From paul at boddie.org.uk Wed Jan 23 09:07:43 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 23 Jan 2008 06:07:43 -0800 (PST) Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? References: Message-ID: On 23 Jan, 14:20, kliu wrote: > > Thank u for your reply. but what I really need is the mapping between > each DOM nodes and the corresponding original source segment. At the risk of promoting unfashionable DOM technologies, you can at least serialise fragments of the DOM in libxml2dom [1]: import libxml2dom d = libxml2dom.parseURI("http://www.diveintopython.org/", html=1) print d.xpath("//p")[7].toString() Storage and retrieval of the original line and offset information may be supported by libxml2, but such information isn't exposed by libxml2dom. Paul [1] http://www.python.org/pypi/libxml2dom From monkeydance at mailinator.com Mon Jan 7 05:55:25 2008 From: monkeydance at mailinator.com (monkeydance at mailinator.com) Date: Mon, 7 Jan 2008 02:55:25 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! Message-ID: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> See http://www.tiobe.com/index.htm?tiobe_index. Marc From python.list at tim.thechases.com Tue Jan 29 11:38:15 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 29 Jan 2008 10:38:15 -0600 Subject: MySQLdb In-Reply-To: <1fac15ec-26e5-4fbb-bb01-252ed8561d3b@d70g2000hsb.googlegroups.com> References: <1fac15ec-26e5-4fbb-bb01-252ed8561d3b@d70g2000hsb.googlegroups.com> Message-ID: <479F5677.8040909@tim.thechases.com> > i have problem manipulating mySQL data. When i add values in a Table, > i can recieve them instantly but when i check the table from another > script, the new values dont exist. Depending on your transaction settings (both on your mysql connection object in code, and the engine used for the table(s) in mysql's DB), you may have to commit your transaction to make it visible in other connections. This helps prevent partial transactions from being visible when they're in inconsistent states. -tkc From ryszard.szopa at gmail.com Sun Jan 13 07:51:20 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Sun, 13 Jan 2008 04:51:20 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> Message-ID: <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> On Jan 13, 8:59 am, Marc 'BlackJack' Rintsch wrote: > On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: > > However, I am very surprised to learn that > > > super_object.__getattr__(name)(*args, **kwargs) > > > getattr(super_object, name)(*args, **kwargs) > > > are not equivalent. This is quite odd, at least when with len() > > and .__len__, str() and .__str__. Do you maybe know what's the > > rationale behind not following that convention by getattr? > > I think you are confusing `__getattr__` and `__getattribute__` here! > `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's > different. Well, in my code calling super_object.__getattr__(name)(*args, **kwargs) and getattr(super_object, name)(*args, **kwargs) gives *different* effects (namely, the latter works, while the former doesn't). That kinda suggests that they don't map to each other :-). And that makes me feel confused. Cheers, -- Richard From lists at cheimes.de Thu Jan 17 15:55:52 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 17 Jan 2008 21:55:52 +0100 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. In-Reply-To: <478FAC5A.50206@animats.com> References: <478FAC5A.50206@animats.com> Message-ID: John Nagle wrote: > It's possible to use "pickle" for interprocess communication over > pipes, but it's not straightforward. IIRC the processing module uses pickle for IPC. Maybe you can get some idea by reading its code? http://pypi.python.org/pypi/processing/0.40 Christian From bj_666 at gmx.net Mon Jan 28 05:05:42 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Jan 2008 10:05:42 GMT Subject: read and readline hanging References: <5vuv9iF1o6ambU2@mid.uni-berlin.de> Message-ID: <605nnmF1oc8dvU2@mid.uni-berlin.de> On Sun, 27 Jan 2008 19:58:27 +0100, Olivier Lefevre wrote: >>> But how can I find out *programmatically* that there is no more >>> input? >> >> You can't. > > How do people handle this, then? Reading from a process that will > block if you ask too much yet won't let you know how much there is > to read right now has to be some kind of FAQ. It's impossible to handle if the external process does not tell you somehow if there's still data ahead or if it is finished. Then there's only the closing of the file on the process' side that tells you the definitive end of the data. >> This doesn't answer if the interpreter doesn't flush its output buffer >> after every line. > > I think it must otherwise you might get incomplete answers or no > answers at the interactive prompt and that never happens. It may > not flush its buffer after every line but it must flush them at > the end of an answer. The buffering behavior at the interactive prompt is very often different from connections via pipes. If stdout of a process is connected to a terminal the standard C library chooses line buffering but if it is connected to a pipe or redirected to a file it chooses block buffering instead. In such cases the `pexpect` module might be a solution. Ciao, Marc 'BlackJack' Rintsch From quentel.pierre at wanadoo.fr Mon Jan 14 16:05:28 2008 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Mon, 14 Jan 2008 13:05:28 -0800 (PST) Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> Message-ID: <413a62d1-6487-485b-ba15-4cf72bad164a@s12g2000prg.googlegroups.com> On 12 jan, 19:37, marcstuart wrote: > How do I divide a list into a set group of sublist's- if the list is > not evenly dividable ? > consider this example: > > x = [1,2,3,4,5,6,7,8,9,10] > y = 3 # number of lists I want to break x into > z = y/x > > what I would like to get is 3 sublists > > print z[0] = [1,2,3] > print z[2] = [4,5,6] > print z[3] = [7,8,9,10] > > obviously not even, one list will have 4 elements, the other 2 will > have 3., > the overriding logic, is that I will get 3 lists and find a way for > python to try to break it evenly, if not one list can have a greater > amount of elements > > Would I use itertools ? How would I do this ? > > Thanks Hi, If you want to split the list in 4, do you want [1,2],[3,4],[5,6],[7,8,9,10] : all extra items in the last sublist or [1,2],[3,4],[5,6,7],[8,9,10] : one extra item in each of the last sublists ? Assuming you want the second version : ======================= def split_list(lst,nb): # ln = length of smaller sublists # extra = number of longer sublists (they have ln+1 items) ln,extra = divmod(len(lst),nb) pos = ln*(nb-extra) # position where larger sublists begin return [ lst[i*ln:(i+1)*ln] for i in xrange(nb-extra) ] \ + [lst[pos+i*(ln+1):pos+(i+1)*(ln+1)] for i in xrange(extra)] ====================== x = range(1,11) print split_list(x,1) >>>[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] print split_list(x,2) >>>[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] print split_list(x,3) >>>[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] print split_list(x,4) >>>[[1, 2], [3, 4], [5, 6, 7], [8, 9, 10]] print split_list(x,5) >>>[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] print split_list(x,10) >>>[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] From bernhard.merkle at googlemail.com Thu Jan 3 08:04:22 2008 From: bernhard.merkle at googlemail.com (Bernhard Merkle) Date: Thu, 3 Jan 2008 05:04:22 -0800 (PST) Subject: reassign to builtin possible !? Message-ID: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> Hi there, I am reading Learning Python 3e from Mark Lutz and just found out that reassigning to builtins is possible. What is the reason, why Python allows this ? IMO this is very risky and can lead to hard to find errors. (see also Learning Python 3e, Chapter 16, Page 315) >>> True True >>> False False >>> True = 1 >>> True 1 >>> True = 0 >>> True 0 TIA, Berni From jwwest at gmail.com Thu Jan 3 00:35:17 2008 From: jwwest at gmail.com (jwwest) Date: Wed, 2 Jan 2008 21:35:17 -0800 (PST) Subject: Python CGI - Presenting a zip file to user References: Message-ID: <475074c1-ef0d-4551-834c-5a16781de3f8@m34g2000hsf.googlegroups.com> On Jan 2, 8:56 pm, Justin Ezequiel wrote: > On Jan 3, 7:50 am, jwwest wrote: > > > > > Hi all, > > > I'm working on a cgi script that zips up files and presents the zip > > file to the user for download. It works fine except for the fact that > > I have to overwrite the file using the same filename because I'm > > unable to delete it after it's downloaded. The reason for this is > > because after sending "Location: urlofzipfile" the script stops > > processing and I can't call a file operation to delete the file. Thus > > I constantly have a tmp.zip file which contains the previously > > requested files. > > > Can anyone think of a way around this? Is there a better way to create > > the zip file and present it for download "on-the-fly" than editing the > > Location header? I thought about using Content-Type, but was unable to > > think of a way to stream the file out. > > > Any help is appreciated, much thanks! > > > - James > > import sys, cgi, zipfile, os > from StringIO import StringIO > > try: # Windows only > import msvcrt > msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) > except ImportError: pass > > HEADERS = '\r\n'.join( > [ > "Content-type: %s;", > "Content-Disposition: attachment; filename=%s", > "Content-Title: %s", > "Content-Length: %i", > "\r\n", # empty line to end headers > ] > ) > > if __name__ == '__main__': > os.chdir(r'C:\Documents and Settings\Justin Ezequiel\Desktop') > files = [ > '4412_ADS_or_SQL_Server.pdf', > 'Script1.py', > 'html_files.zip', > 'New2.html', > ] > b = StringIO() > z = zipfile.ZipFile(b, 'w', zipfile.ZIP_DEFLATED) > for n in files: > z.write(n, n) > > z.close() > > length = b.tell() > b.seek(0) > sys.stdout.write( > HEADERS % ('application/zip', 'test.zip', 'test.zip', length) > ) > sys.stdout.write(b.read()) > b.close() Thanks! That worked like an absolute charm. Just a question though. I'm curious as to why you have to use the msvcrt bit on Windows. If I were to port my app to *NIX, would I need to do anything similar? - James From matthias.blaesing at rwth-aachen.de Sat Jan 19 17:20:47 2008 From: matthias.blaesing at rwth-aachen.de (Matthias =?iso-8859-1?q?Bl=E4sing?=) Date: 19 Jan 2008 22:20:47 GMT Subject: Naming a file References: <89bb0095-429f-404c-b7f6-ff0a554b07cc@i72g2000hsd.googlegroups.com> Message-ID: Am Sat, 19 Jan 2008 14:14:30 -0800 schrieb snoylr: > For example if the variable is 105Markum > > What statement do I need to create a file name 105Markum.txt? filename_base = '105Markum' filename = '%s.txt' % filename_base f = open(filename, 'w') f.write( References: <489729.25110.qm@web57603.mail.re1.yahoo.com> Message-ID: <14660373.post@talk.nabble.com> Francesco Pietra wrote: > > Please, how to adapt the following script (to delete blank lines) to > delete > lines containing a specific word, or words? > > f=open("output.pdb", "r") > for line in f: > line=line.rstrip() > if line: > print line > f.close() > > If python in Linux accepts lines beginning with # as comment lines, please > also > a script to comment lines containing a specific word, or words, and back, > to > remove #. > Well the simplest way in python using the stream for data or configuration or something IMHO would be to use a filter, list comprehension or generator expression: # filter (puts it all in memory) lines = filter(lambda line: not line.lstrip().startswith('#'), open("output.pdb", "r")) # list comprehension (puts it all in memory) lines = [line for line in open("output.pdb", "r") if not line.lstrip().startswith('#')] # generator expression (iterable, has .next(), not kept in memory) lines = (line for line in open("output.pdb", "r") if not line.lstrip().startswith('#')) Check out http://rgruet.free.fr/PQR25/PQR2.5.html http://rgruet.free.fr/PQR25/PQR2.5.html for some quick hints. -- View this message in context: http://www.nabble.com/Delete-lines-containing-a-specific-word-tp14651102p14660373.html Sent from the Python - python-list mailing list archive at Nabble.com. -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jan 15 17:23:17 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 15 Jan 2008 23:23:17 +0100 Subject: "env" parameter to "popen" won't accept Unicode on Windows -minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net><5v2cudF1k5a1oU1@mid.individual.net><478c551a$0$36354$742ec2ed@news.sonic.net> <5v3dq9F1k2577U1@mid.uni-berlin.de> <5v3qtsF1khn11U1@mid.uni-berlin.de> <478d2569$0$36379$742ec2ed@news.sonic.net> Message-ID: <5v4q2lF1kkdliU1@mid.individual.net> John Nagle wrote: > The problem is that only the NT-derived Microsoft systems > talk Unicode. The DOS/Win16/Win9x family did not. But they did > have CreateProcess. So the current code will handle Win9x, but not > Unicode. Please explain, I don't understand. If you try using Windows system functions in older Windows versions, u"mystring" will fail, too. Those functions need byte strings, not Unicode string instances. The latter have to be encoded to byte strings to pass them. Regards, Bj?rn -- BOFH excuse #70: nesting roaches shorted out the ether cable From arnodel at googlemail.com Mon Jan 28 07:09:48 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 28 Jan 2008 04:09:48 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> Message-ID: <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> On Jan 28, 4:47 am, "Gabriel Genellina" wrote: > En Sun, 27 Jan 2008 23:51:28 -0200, Arnaud Delobelle > escribi?: > > > Nice! I've got a slight variation without magic argument names: > > > class Test(object): > > @autoassign('foo', 'bar') > > def __init__(self, baz): > > print 'baz =', baz [...] > I would like a signature-preserving version. The help system, pydoc, the > inspect module, and likely any other introspection tool see those > decorated methods with a different signature than the original one. > Even if one writes a signature-preserving decorator (maybe along the lines > of this article by M. Simionato [1]), names like "self_foo", "self_bar" > are ugly. Furthermore, argument names are part of the public interfase, > but here they're tied to the implementation: what if later I want to keep > a reference to baz? I must change the argument name to self_baz, breaking > all users of the code. Sligthly improved (not for performance! but signature-preserving and looks for default values) from functools import wraps from inspect import getargspec from itertools import izip, chain def autoassign(*names): def decorator(f): fargnames, _, _, fdefaults = getargspec(f) defaults = [(n,v) for (n,v) in izip(reversed(fargnames), reversed(fdefaults)) if n in names] @wraps(f) def decorated(self, *args, **kwargs): self.__dict__.update(defaults) for name, arg in chain(izip(fargnames, args), kwargs.iteritems()): if name in names: setattr(self, name, arg) return f(self, *args, **kwargs) return decorated return decorator class Test(object): @autoassign('foo', 'bar') def __init__(self, foo, bar=3, baz=6): print 'baz =', baz t = Test(1, 2, 6) u = Test(foo=8) print t.foo # 1 print t.bar # 2 print u.foo # 8 print u.bar # 3 (default) -- Arnaud print t.baz # AttributeError From jpcc at nowhere.org Tue Jan 22 14:45:51 2008 From: jpcc at nowhere.org (John Carlyle-Clarke) Date: Tue, 22 Jan 2008 19:45:51 +0000 Subject: Problem with processing XML In-Reply-To: <1839ec4e-045e-4ce2-a3ea-78ed83a8c288@u10g2000prn.googlegroups.com> References: <13pbudgks88rcf3@corp.supernews.com> <1839ec4e-045e-4ce2-a3ea-78ed83a8c288@u10g2000prn.googlegroups.com> Message-ID: <13pchvlg6d59q3b@corp.supernews.com> Paul McGuire wrote: > > Here is a pyparsing hack for your problem. Thanks Paul! This looks like an interesting approach, and once I get my head around the syntax, I'll give it a proper whirl. From __peter__ at web.de Wed Jan 23 08:09:38 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Jan 2008 14:09:38 +0100 Subject: Removing objects References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> Message-ID: bladedpenguin wrote: > So, in general, is it more efficient to use a dictionary or to override > the __eq__ function? Rule of thumb: If you want to add/remove arbitrary objects from a collection a dictionary (or set) is always faster than a list. You may still have to override the __eq__() and __hash__() methods whenever you have distinct objects that can be equal. Caveat: don't use dictionaries if the result of obj1 == obj2 # items in the dict can change during the lifetime of the collection. Peter From vedrandekovic at gmail.com Tue Jan 22 09:27:00 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Tue, 22 Jan 2008 06:27:00 -0800 (PST) Subject: make exe from application with py2exe Message-ID: <6d553403-1275-459e-b2e0-9463cab39250@e10g2000prf.googlegroups.com> Hello, Is there any idea how can i create (.exe) from application (.exe ) with py2exe? Regards, Vedran From sjmachin at lexicon.net Sat Jan 26 02:52:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 23:52:54 -0800 (PST) Subject: Doesn't know what it wants References: <13plo358k5rf059@corp.supernews.com> Message-ID: On Jan 26, 6:25 pm, Steven D'Aprano wrote: > On Fri, 25 Jan 2008 22:53:16 -0800, John Machin wrote: > > On Jan 26, 5:32 pm, Jeroen Ruigrok van der Werven > nomine.org> wrote: > >> -On [20080126 06:26], Tim Rau (bladedpeng... at gmail.com) wrote: > > >> >Line 147 reads: > >> > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) > > >> I think it expects something like: > > >> # badly named variable, pick something better depending on context > >> temp = vec2d(0, 0) > >> cp.cpMomentForCircle(self.mass, .2, 0, temp) > > > That *cannot* give a different result in Python. The called function > > will be presented with *exactly* the same object as the OP's code does. > > Not quite. Look carefully at the difference. > > The OP's code calls vec2d with a single tuple argument (0,0). Jeroen's > version calls vec2d with two int arguments, 0 and 0. > > We don't know whether vec2d will treat those two things the same or not. That was Jeroen's 2nd problem; I was addressing his first problem (thinking that introducing a temp variable would work some magic). Google is your friend: """ class vec2d(ctypes.Structure): """2d vector class, supports vector and scalar operators, and also provides a bunch of high level functions """ __slots__ = ['x', 'y'] def __init__(self, x_or_pair, y = None): if y == None: self.x = x_or_pair[0] self.y = x_or_pair[1] else: self.x = x_or_pair self.y = y """ From stanc at al.com.au Sun Jan 20 21:14:41 2008 From: stanc at al.com.au (Astan Chee) Date: Mon, 21 Jan 2008 13:14:41 +1100 Subject: Bittorent client with google talk interface In-Reply-To: <4793FA6D.7090507@al.com.au> References: <4793FA6D.7090507@al.com.au> Message-ID: <47940011.9090401@al.com.au> Hi, I dont know where to send this but I'll try here. I recently took the newest version of ABCTorrent and its code and added some features to it that I find very useful. Basically it is like a webUI except it connect to google's google talk and you can issue commands from it. Kinda like a command line bittorrent client. So when you start up the client, you can enter your google talk account information and using another google talk account (from somewhere else) send commands (system and torrent related). I've also added some proxy support for it since Im constantly behind proxies (but not at work or school). I use windows XP and wxPython 2.6.3.3 and python 2.5 so I dont know how it will behave in newer versions of things. There are also new modules that it requires (win32api) for file operations that you might need before compiling this. The main script to run this all is the abc.py script. Also I havent done much brushing up with the GUI so it wont look like the fastest ship around. Any suggestions or changes for further improvement? Also for anyone who is developing or has used this before and tinkered with it Im pretty sure Im doing something wrong calling the interface from the code because it (wx) sporadically crashes; Im not sure what to do since I dont know how to call it properly. Does anyone have any idea? Cheers Astan The file can be downloaded here: http://gtalktorrent.googlecode.com/files/3.1.0.zip -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Wed Jan 2 23:35:37 2008 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2008 20:35:37 -0800 Subject: cloud computing (and python)? References: <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <13nn9k48n7ohr95@corp.supernews.com> <69337707-ff18-4b39-af0a-78cf0a14b667@1g2000hsl.googlegroups.com> Message-ID: In article <69337707-ff18-4b39-af0a-78cf0a14b667 at 1g2000hsl.googlegroups.com>, Aaron Watters wrote: > >Ok, so if we include yahoo mail and gmail in "cloud computing" then I >guess usenet is also cloud computing. Usenet actually is a good example of cloud computing, but only at the article distribution level. Netnews clients are *not* examples of cloud computing (except maybe Google Groups). The question is whether there exists an API and infrastructure that supports distributed computing and storage. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From bronger at physik.rwth-aachen.de Tue Jan 1 20:31:06 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 02 Jan 2008 02:31:06 +0100 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au> Message-ID: <87bq85rp2d.fsf@physik.rwth-aachen.de> Hall?chen! Ben Finney writes: > Steven D'Aprano writes: > >> [...] >> >> There's a very good reason to buck the trend whenever practical: >> tabs have the considerable benefit that they decouple the >> presentation of the code from the structure of the code. > > Huh? I can only interpret this to mean that you think it's a good > thing for a text file one is *directly editing* to be rendered in > such a way that one cannot tell quite what one is really editing. No. It's more like the old battle visual vs. semantic markup in markup languages. Both markup is unambiguous. After all, the width of a tab is nowhere defined. It really is a matter of the editor's settings. I, for example, dislike too wide indenting. I use four columns in Python and two in Delphi. However, there are Python projects using eight spaces for each indentation level. If all Python code used tabs, eveybody could use their own preferences, for both reading and writing code, and interoperability would be maintained nevertheless. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From sakradevanamindra at gmail.com Thu Jan 24 15:14:06 2008 From: sakradevanamindra at gmail.com (Shoryuken) Date: Thu, 24 Jan 2008 12:14:06 -0800 (PST) Subject: a newbie regex question Message-ID: Given a regular expression pattern, for example, \([A-Z].+[a-z]\), print out all strings that match the pattern in a file Anyone tell me a way to do it? I know it's easy, but i'm completely new to python thanks alot From half.italian at gmail.com Wed Jan 16 17:53:30 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 16 Jan 2008 14:53:30 -0800 (PST) Subject: read_nonblocking error in pxssh References: <12fda1ac-192b-4dcf-9ff0-249d5e260a2e@f10g2000hsf.googlegroups.com> Message-ID: <0ae8654f-737b-4934-9915-c0c3d018b83c@s19g2000prg.googlegroups.com> Just glanced at the docs, but it might be worth a shot... try: > >>> import pxssh > >>> s=pxssh.pxssh() > >>> s.login("myhost","root","mypass", auto_prompt_reset=False) Maybe??? Otherwise, I have used and modified this script with great success: (ssh_session.py) http://www.koders.com/python/fidA430838E5789710E4DCF34C414AD75EB4EEE63CF.aspx Good luck. ~Sean On Jan 16, 9:24?am, jrpfinch wrote: > I'm attempting to use the pxssh to execute commands on a remote > machine and do stuff with the output. ?Both machines are running SSH > Version Sun_SSH_1.0, protocol versions 1.5/2.0 and Intel Solaris 9. > > I am hitting a problem with read_nonblocking in the pexpect module as > follows: > > >>> import pxssh > >>> s=pxssh.pxssh() > >>> s.login("myhost","root","mypass") > > Trying command: ssh -q -l root gerard > Expect returned i=2 > Expect returned i=1 > Traceback (most recent call last): > ? File "", line 1, in > ? File "pxssh.py", line 244, in login > ? ? if not self.synch_original_prompt(): > ? File "pxssh.py", line 134, in synch_original_prompt > ? ? self.read_nonblocking(size=10000,timeout=10) # GAS: Clear out the > cache before getting the prompt > ? File "/opt/python2.5.1/lib/python2.5/site-packages/pexpect.py", line > 824, in read_nonblocking > ? ? raise TIMEOUT ('Timeout exceeded in read_nonblocking().') > pexpect.TIMEOUT: Timeout exceeded in read_nonblocking(). > > Running the ssh command from the shell yields: > > bash-2.05# ssh -q -l root myhost > root at myhost's password: > Last login: Wed Jan 16 17:10:32 2008 from x.x.x.x > Sun Microsystems Inc. ? SunOS 5.9 ? ? ? Generic January 2003 > Sun Microsystems Inc. ? SunOS 5.9 ? ? ? Generic January 2003 > root at myhost:/ # > > I would be grateful if anyone could make a suggestion as to where I go > next? ?Is read_nonblocking(), the correct method to be using here? > Are there any options in pxssh I need to explore (I've tried ssh -t, > but this means the password entry fails with raise ExceptionPxssh > ('password refused')). > > Many thanks > > Jon From jamon.ben at gmail.com Tue Jan 15 05:44:33 2008 From: jamon.ben at gmail.com (Ben Fisher) Date: Tue, 15 Jan 2008 05:44:33 -0500 Subject: print >> to a derived file In-Reply-To: References: Message-ID: <741fd030801150244q79a211fbh430590ccc2590c68@mail.gmail.com> This might have something to do with the class being derived from file. I've written it so that it doesn't derive from file, and it works. class File_and_console(): def __init__(self, *args): self.fileobj = open(*args) def write(self, s): self.fileobj.write(s) print s, f = File_and_console('testout.tmp','w') f.write('hello') print >>f,'hello', On 1/15/08, iu2 wrote: > Hi, > > I'm trying to write data to both a file and the console, so I did: > > class File_and_console(file): > def write(self, s): > file.write(self, s) > print s, > > >>> f = File_and_console('1.txt', 'w') > >>> f.write('hello') > hello > >>> print >>f, 'world' > >>> > > the 'write' method works, but 'print >>' doesn't, it writes only to > the file. It doesn't actually call File_and_console.write > > Why? How can I fix it? > Thanks > iu2 > -- > http://mail.python.org/mailman/listinfo/python-list > From paul.sijben at xs4all.nl Fri Jan 11 04:44:36 2008 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Fri, 11 Jan 2008 10:44:36 +0100 Subject: encrypting python modules Message-ID: <47873a78$0$85785$e4fe514c@news.xs4all.nl> Hello, this question has come by repeatedly in several guises over the past years but has never been solved in this forum as far as I have been able to Google. However since so many people are asking the question, I hope someone has made a solution and is willing to share it. The problem: I have a client-server app written in python. I want to make sure that the client is not: 1) destabilized by users accidentally or on purpose dropping python files in the path (after which calling the helpdesk will not be useful) 2) extended with "new features" without me knowing about it (again resulting in calls to my helpdesk...) 3) trivially decompiled. Added issue, I want the client to be able to update itself when I have fixed bugs or created new functionality. I know that I can not stop a dedicated hacker deconstructing my code. Since all clients need to go through the server I am not afraid of "freeloaders". I am now considering overriding import with some code that will only import modules signed and crypted by me. However I can not imagine that I would be the first one planning to do this. So is there a solution like this available somewhere? Paul Sijben From hvora at usc.edu Fri Jan 4 23:10:11 2008 From: hvora at usc.edu (Hita Vora) Date: Fri, 04 Jan 2008 20:10:11 -0800 Subject: do - loop Message-ID: I have a dataset which has about 3000 subjects in it. I take each subject and perform 3 to 4 geoprocessing tasks on it. Currently I have a model where I manually feed in each subject's ID and then the rest of the process is automated. I would like to automate the process such that it would automatically select another subject after the process has been completed on a specfic subject. ie to repeat the same process on each of the IDs. Any help such as a dummy code would be greatly appreciated. Thanks. Hita From gherzig at fmed.uba.ar Wed Jan 30 09:16:40 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Wed, 30 Jan 2008 11:16:40 -0300 Subject: Removing Pubic Hair Methods In-Reply-To: References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> Message-ID: <47A086C8.6010509@fmed.uba.ar> Sion Arrowsmith wrote: >Marc 'BlackJack' Rintsch wrote: > > >>On Tue, 29 Jan 2008 11:48:38 -0800, Tobiah wrote: >> >> >>>class genital: >>> def pubic_hair(self): >>> pass >>> def remove(self): >>> del(self.pubic_hair) >>> >>> >>I think `pubic_hair` is an attribute instead of a method. >> >>Oh, and ``del`` is a statement and not a function. So the way you wrote >>it with parentheses is a bit misleading. >> >> > >And who's going to want to call genital().remove() anyway? > > > I will use genital().extend(), thats for shure ^^ From ganeshborse at gmail.com Thu Jan 3 23:23:41 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 3 Jan 2008 20:23:41 -0800 (PST) Subject: PyObject_CallObject code dump after calling 4 times References: <938001bf-33d2-4071-9b08-f7bb041505b1@s19g2000prg.googlegroups.com> Message-ID: <0d763f52-6845-4822-807a-130c9c46c327@i12g2000prf.googlegroups.com> On Jan 3, 8:49?pm, grbgooglefan wrote: > On Jan 3, 8:02?pm, Phil Thompson > wrote: > > > > > > > On Thursday 03 January 2008, grbgooglefan wrote: > > > > I have a following C++ code which uses PyObject_CallObject to evaluate > > > expressions dynamically. This code sets the input parameters for the > > > function also dynamically. After calling this function 4 times (with > > > these shown values), PyObject_CallObject ?causes application to crash > > > in frame_dealloc. > > > 1) Can some one please help me understand why is this crash happening > > > in frame_dealloc & how to solve it? > > > 2) Is there anything wrong I am doing about incrementing or > > > decrementing the reference counts of the object passed to > > > PyObject_CallObject? > > > Yes. > > > > 3) Is it because of the big value (2299265.500000) I am trying to > > > convert from double to float using PyFloat_FromDouble? > > > > //========================= code reduced for readability > > > =============== > > > switch(ndtyp){ > > > ? ? ?case(INT_T): > > > ? ? ? ? ?{ > > > ? ? ? ? ?printf("PyInt_FromLong val %d, var %s > > > \n",inputVar.nionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > > ? ? ? ? ?val = PyInt_FromLong(inputVar.nionum); > > > ? ? ? ? ?break; > > > ? ? ? ? ?} > > > ? ? ? case(LONG_T): > > > ? ? ? ? ?{ > > > ? ? ? ? ?printf("PyLong_FromLong val %ld, var %s > > > \n",inputVar.lionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > > ? ? ? ? ?val = PyLong_FromLong(inputVar.lionum); > > > ? ? ? ? ?break; > > > ? ? ? ? ?} > > > ? ? ? case(FLOAT_T): > > > ? ? ? ? ?{ > > > ? ? ? ? ?printf("PyFloat_FromDouble val %f, var %s > > > \n",inputVar.fionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > > ? ? ? ? ?val = PyFloat_FromDouble(inputVar.fionum); > > > ? ? ? ? ?break; > > > ? ? ? ? ?} > > > ? ? ? case(DOUBLE_T): > > > ? ? ? ? ?{ > > > ? ? ? ? ?printf("PyFloat_FromDouble val %f, var %s > > > \n",inputVar.dionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > > ? ? ? ? ?val = PyFloat_FromDouble(inputVar.dionum); > > > ? ? ? ? ?break; > > > ? ? ? ? ?} > > > ? ? ? ?case(STRING_T): > > > ? ? ? ? ?{ > > > ? ? ? ? ?printf("PyString_FromString val %s, var %s > > > \n",inputVar.ioString,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > > ? ? ? ? ?val = PyString_FromString(inputVar.ioString); > > > ? ? ? ? ?break; > > > ? ? ? ? ?} > > > ? ? ? ?default: > > > ? ? ? ? ?printf("Unknown data type [%d] for %s\n",ndtyp,pEvalFunc- > > > > >pExprVarsArray[nCtr].szVarName); > > > > } > > > if(!val){ > > > ? ?ret = -1; > > > ? ?printf("Failed to convert %d %s to PyObject\n",ndtyp,pEvalFunc- > > > > >pExprVarsArray[nCtr].szVarName); fflush(stdout); > > > > ? ?Py_XDECREF(pTuple); > > > ? ?break; > > > } > > > ? PyTuple_SetItem(pTuple, nCtr, val); > > > ? Py_XDECREF(val); > > > Don't do this - PyTuple_SetItem() steals a reference to val. > > > > } > > > // all variables are set, call Python function > > > Py_XINCREF(pTuple); > > > Why do this? > > > > ? PyObject *pResult = PyObject_CallObject(pEvalFunc- > > > > >pPyEvalFunction,pTuple); > > > > Py_XDECREF(pTuple); > > > Why do this? > > > > if(PyErr_Occurred()){ > > > ?PyErr_Print(); > > > } else { > > > ? ? ? char* plevel = NULL; > > > ? ? ? if(NULL != (plevel = PyString_AsString(pResult))){ > > > ? ? ? ? ret = 0; > > > ? ? ? ? sprintf(szEvalResult,"%s",plevel); > > > ? ? ? } > > > } > > > Py_XDECREF(pResult); > > > pTuple will now have the same number of references as when you started the > > above code, so you may want to Py_DECREF() it. > > > Phil- Hide quoted text - > > > - Show quoted text - > > Thanks for all the responses. > These help me. > I could simulate this crash in my small test program & I think (I > could be wrong also) it is because of extraneous Py_XDECREF of > "PyObject *val" which I am using to convert variables to tuple. > When I change the code to simple do like this, it works fine. > ? ? ? ? ? ? PyTuple_SetItem(pytuple,0,PyLong_FromLong(size)); > ? ? ? ? ? ? PyTuple_SetItem(pytuple,1,PyLong_FromLong(maxvol)); > ? ? ? ? ? ? PyTuple_SetItem(pytuple,2,PyFloat_FromDouble(adv));- Hide quoted text - > > - Show quoted text - Now my new code looks like this. Do you think this is correct way to handle ref counts? Do you forsee any issues of memory leaks, etc. here? // ================================================================================ switch(ndtyp){ case(INT_T): //printf("PyInt_FromLong val %d, var %s \n",inputVar.nionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); PyTuple_SetItem(pTuple,nCtr,PyInt_FromLong(inputVar.nionum)); break; case(LONG_T): //printf("PyLong_FromLong val %ld, var %s \n",inputVar.lionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); PyTuple_SetItem(pTuple,nCtr,PyLong_FromLong(inputVar.lionum)); break; case(FLOAT_T): //printf("PyFloat_FromDouble val %f, var %s \n",inputVar.fionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); PyTuple_SetItem(pTuple,nCtr,PyFloat_FromDouble(inputVar.fionum)); break; case(DOUBLE_T): //printf("PyFloat_FromDouble val %f, var %s \n",inputVar.dionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); PyTuple_SetItem(pTuple,nCtr,PyFloat_FromDouble(inputVar.dionum)); break; case(STRING_T): //printf("PyString_FromString val %s, var %s \n",inputVar.ioString,pEvalFunc->pExprVarsArray[nCtr].szVarName); PyTuple_SetItem(pTuple,nCtr,PyString_FromString(inputVar.ioString)); break; default: printf("Unknown data type [%d] for %s \n",ndtyp,pEvalFunc->pExprVarsArray[nCtr].szVarName); bUnknownDataType = true; break; } if(bUnknownDataType){ // got an unknown data type for a variable ret = -1; break; } } // all variables are set, call Python function if(ret == 0){ PyObject *pResult = PyObject_CallObject(pEvalFunc- >pPyEvalFunction,pTuple); if(PyErr_Occurred()){ ret = -1; printf("error occured in PyObject_CallObject\n"); PyErr_Print(); } else { char* plevel = NULL; if(NULL != (plevel = PyString_AsString(pResult))){ ret = 0; strncpy(szEvalResult,plevel,strlen(plevel)); printf("Final result %s\n",szEvalResult); } else { printf("PyObject_CallObject returned NULL\n"); ret = -1; } } Py_XDECREF(pResult); Py_XDECREF(pTuple); // ================================================================================ From arkanes at gmail.com Thu Jan 31 14:36:59 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 31 Jan 2008 13:36:59 -0600 Subject: Python for mobiles In-Reply-To: <1201807007.31585.20.camel@smilochik-lin> References: <03e0ad28-e72c-4582-8518-b5cb07d408df@e10g2000prf.googlegroups.com> <1201807007.31585.20.camel@smilochik-lin> Message-ID: <4866bea60801311136y3bff85fbwaef52c4ee9f6762b@mail.gmail.com> On Jan 31, 2008 1:16 PM, Shawn Milochik wrote: > > A better solution would surely be to get a Nokia S60 'phone, for which > there is a native Python implementation. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > > > Steve: > > Do you know if the Nokia E60i phone has this capability? Also, is wxPython supported? > Or are you just knowledgeable about the S60? > wxPython is not, but there are bindings for the S60s native gui provided. You can find out it your phone is supported a pys60.sf.net. From fredrik at pythonware.com Wed Jan 9 14:05:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 20:05:39 +0100 Subject: problem of converting a list to dict In-Reply-To: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> Message-ID: Louis.Soninhu at gmail.com wrote: > I have a list like this > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] > > I'd like to remove the first and the last item as they are irrevalent, > and convert it to the dict: > {'tom':'boss','mike':'manager','paul':'employee'} > > I tried this but it didn't work: > > mydict={} > for i in mylist[1:-1]: > a=i.split('=') > mydict[a[0]]=a[1] > > and I got this: > File "srch", line 19, in > grab("a/tags1") > File "srch", line 15, in grab > mydict[mylist[0]]=mylist[1] > IndexError: list index out of range > > Anyone could shed me a light on this? works for me, with the mylist example you provided. to see what's going on on your machine, try printing "a" after the split, but before you use it to populate the dictionary. From tarundevnani at gmail.com Thu Jan 24 22:31:47 2008 From: tarundevnani at gmail.com (tarun) Date: Fri, 25 Jan 2008 09:01:47 +0530 Subject: [wxPython-users] Issue with docking wx.listctrl window In-Reply-To: <4798D1B1.7020908@alldunn.com> References: <4798D1B1.7020908@alldunn.com> Message-ID: Thanks a lot Robin. I tried using self.log and instead of self.log.list. *Code is attached.* But this gives me a panel and listctrl in it. The extra blank space around the listctrl in window1 is something that I don't need. Please help. Regards, Tarun Devnani On Jan 24, 2008 11:28 PM, Robin Dunn wrote: > tarun wrote: > > Hello All, > > > > I'm trying to create a Frame with AuiManager. The code is attached. > > > > *Problem:* > > - I want 2 windows to be docked in the frame. One is a text control and > > other is a list control. > > - The text control gets docked, but on trying to dock the list control, > > all the tabs dis-appear. > > The tabs appear only when the list control window is kept floating. > > > > In the attached code the list control window is kept floating. This can > > be docked > > To see the issue with docking, comment line 33 and un-comment line 35 in > > the attached file and then try to execute, the issue would be clearly > > visible. On un-docking the window1, the tabs again appear.. > > > > *Please let me the solution to this ASAP* > > > The main problem is that you are putting the listctrl on a panel, but > you are telling AUI to manage the listctrl, not the panel. If I > understand correctly then your other problems stem from that as well. > Try passing self.log to AddPane, instead of self.log.list. > > > -- > Robin Dunn > Software Craftsman > http://wxPython.org Java give you jitters? Relax > with wxPython! > > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Docking.py URL: From steve at REMOVE-THIS-cybersource.com.au Mon Jan 21 17:17:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 22:17:11 -0000 Subject: When is min(a, b) != min(b, a)? References: <13p9h86e9aoa43e@corp.supernews.com> Message-ID: <13pa6f7q3ftckc9@corp.supernews.com> On Mon, 21 Jan 2008 18:00:05 +0000, Pete Forman wrote: > If NaNs in your data are important then you must take care in explicit > and implicit comparisons to consider unordered results. And even if they're not important, beware of bugs from failing to consider unordered results due to unexpected NaNs. -- Steven From steven at REMOVE.THIS.cybersource.com.au Mon Jan 14 22:14:19 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 15 Jan 2008 03:14:19 -0000 Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> <7xsl105fvv.fsf@ruckus.brouhaha.com> <13onli9dk7mu926@corp.supernews.com> <7xhchgatin.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 14 Jan 2008 15:15:28 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> map = {'a': Aclass, 'b': Bclass, 'c': Cclass} class_ = map.get(astring, >> default=Zclass) >> >> The result I want is the class, not the result of calling the class >> (which would be an instance). If I wanted the other semantics, I'd be >> using defaultdict instead. > > I used default as a keyward arg name indicating the presence of a > callable. I probably should have called it defaultfunc or something. > > x = d.get('a', f) # --> default value is f x = d.get('a', > defaultfunc=f) # --> default value is result of f() . So you're talking about proposed *added* behaviour, rather than *replacing* the current behaviour? Sorry if I misunderstood you in the first place. -- Steven From mikez302 at gmail.com Mon Jan 14 12:06:18 2008 From: mikez302 at gmail.com (mikez302) Date: Mon, 14 Jan 2008 09:06:18 -0800 (PST) Subject: IDLE won't start in Python 2.5 for Windows References: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> <13ogqhlds0tbsac@corp.supernews.com> <57a7e4a2-0acc-4439-9bd6-d96862ffc22e@j78g2000hsd.googlegroups.com> <13oi9lg6onn6s72@corp.supernews.com> <13ojc0i3ii1etcb@corp.supernews.com> Message-ID: I was able to start IDLE from the command line, and reset my keyboard shortcuts. It works fine now. In case this happens again, where would I find the config file? From musiccomposition at gmail.com Tue Jan 22 22:54:42 2008 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 22 Jan 2008 19:54:42 -0800 (PST) Subject: Cleanup when a object dies Message-ID: <601f19ce-ac60-4145-9e99-6eacb8ea74e2@e6g2000prf.googlegroups.com> I writing writing a class to allow settings (options, preferences) to written file in a cross platform manner. I'm unsure how to go a about syncing the data to disk. Of course, it's horribly inefficient to write the data every time something changes a value, however I don't see how I can do it on deletion. I've read that __del__ methods should be avoided. So am I just going to have to force the client of my object to call sync when they're done? From siona at chiark.greenend.org.uk Wed Jan 30 08:24:26 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Jan 2008 13:24:26 +0000 (GMT) Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: >On Tue, 29 Jan 2008 11:48:38 -0800, Tobiah wrote: >> class genital: >> def pubic_hair(self): >> pass >> def remove(self): >> del(self.pubic_hair) >I think `pubic_hair` is an attribute instead of a method. > >Oh, and ``del`` is a statement and not a function. So the way you wrote >it with parentheses is a bit misleading. And who's going to want to call genital().remove() anyway? -- \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 tenax.raccoon at gmail.com Wed Jan 23 12:11:58 2008 From: tenax.raccoon at gmail.com (Jason) Date: Wed, 23 Jan 2008 09:11:58 -0800 (PST) Subject: application error in python References: <75de8afc-4295-40b5-b9b7-af19ef5264e6@t1g2000pra.googlegroups.com> Message-ID: <70c55d41-1feb-49bf-8f3e-4cb538c2f0de@e6g2000prf.googlegroups.com> On Jan 23, 4:29 am, abhishek wrote: > hello group i am working on a project where most of the code has been > written in c++ but the web component is written in python. Initially > we have been using python2.4 and vs.net2003 but recently we decided to > move ahead with python2.5 and vs.net2005. > > the problem that has been haunting me for while now is when i am > trying to access a few functions in c++ through python by > building .pyd extension, python.exe crashes saying an application > error has occured > > any clues why this happened as everythiing was working well > in .net2003 and python2.4 > > thanks abhishek It could be that Python 2.5 is still built and linked against version 7.1 of the Microsoft C run-time. VS 2005 links against version 8.0 of the Microsoft C run-time. The two versions of the DLL are incompatible, and will cause crashes if memory is allocated from one DLL and then freed with the other. File handles also opened with one C run-time DLL cannot be used with the other version either. Unfortunately, there's no really good fix for this. Microsoft made their libraries and C run-time incompatible between versions of Visual Studio. Rather than force all Python developers to switch to VS 2005, the Python core developers stayed with the previous compiler. If you absolutely must be able to pass file handles and memory with VS 2005 DLLs, you must recompile Python with VS 2005. You will also need to recompile all DLL libraries, such as wxPython, LXML, and the PIL. Pure Python modules and libraries will be unaffected. The easiest solution, however, is to use Python 2.5 and Visual Studio 2003. --Jason From HoustonJuliet at yahoo.com Sat Jan 26 19:52:39 2008 From: HoustonJuliet at yahoo.com (HoustonJuliet) Date: Sat, 26 Jan 2008 16:52:39 -0800 (PST) Subject: do design patterns still apply with Python? In-Reply-To: <120eok46fkf0j2b@corp.supernews.com> References: <8SINf.1718$No6.40137@news.tufts.edu> <120eok46fkf0j2b@corp.supernews.com> Message-ID: <15114746.post@talk.nabble.com> I am a fan of these people: Goldie Hawn Kate Hudson Oliver Reed Robert Conrad Vic Morrow Bill Bixby Grant Edwards wrote: > > On 2006-03-02, John Salerno wrote: > >> Since Python does so many things different, especially compared to >> compiled and statically typed languages, do most of the basic design >> patterns still apply when writing Python code? > > Definitely. Especially plaid, paisley, and a nice medium > houndstooth check. But please, not all at the same time. > > -- > Grant Edwards grante Yow! Maybe we could > paint > at GOLDIE HAWN a rich > PRUSSIAN > visi.com BLUE -- > -- > http://mail.python.org/mailman/listinfo/python-list > > :drunk: -- View this message in context: http://www.nabble.com/do-design-patterns-still-apply-with-Python--tp3210321p15114746.html Sent from the Python - python-list mailing list archive at Nabble.com. From ricaraoz at gmail.com Thu Jan 31 18:55:54 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 31 Jan 2008 20:55:54 -0300 Subject: REALLY simple xml reader In-Reply-To: <60dsbrF1qj28sU1@mid.uni-berlin.de> References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> Message-ID: <47A2600A.2090707@bigfoot.com> Diez B. Roggisch wrote: > Ricardo Ar?oz schrieb: >> Diez B. Roggisch wrote: >>> Ricardo Ar?oz schrieb: >>>> Thanks Ivan, it seems a elegant API, and easy to use. >>>> I tried to play a little with it but unfortunately could not get it off >>>> the ground. I kept getting >>>>>>> root = et.fromstring(doc) >>>> Traceback (most recent call last): >>>> File "", line 1, in >>>> File "E:\Python25\lib\xml\etree\ElementTree.py", line 963, in XML >>>> parser.feed(text) >>>> File "E:\Python25\lib\xml\etree\ElementTree.py", line 1245, in feed >>>> self._parser.Parse(data, 0) >>>> ExpatError: XML or text declaration not at start of entity: line 2, column 0 >>> That's a problem in your XML not being XML. Has nothing to do with >>> element-tree - as one sees from the error-message "ExpatError". If you >>> show it to us, we might see why. >>> >> Sure, >> >> doc = """ >> > > It's not allowed to have a newline before the > > Put it on the line above, and things will work. > > Diez Worked ok. Thanks a lot to you all, I'm not using it right now but I've had a taste and now know where to look and how to start. Cheers From cokofreedom at gmail.com Fri Jan 11 04:25:13 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 11 Jan 2008 01:25:13 -0800 (PST) Subject: python recursive function References: Message-ID: <9633edcf-b9e6-42d3-9444-1b26b6e46d63@v29g2000hsf.googlegroups.com> > Stylistically I prefer 'if not n % 5', looks neater. > As for your assignment, the hardest task will be creating an effective > method of ensuring you recurse through all possibilities. I was chatting to a friend about the 'if not n % 5' and while I am happy to use it saying that when 5 % 5 is False because it returns 0...for this case just feels wrong to me. I understand the reason to keep it this way...but still...having to use not all the time is just annoying. From misterwang at gmail.com Tue Jan 15 11:22:23 2008 From: misterwang at gmail.com (Peter Wang) Date: Tue, 15 Jan 2008 08:22:23 -0800 (PST) Subject: jpype with JFreeChart, anyone interested to help? References: Message-ID: <51378fac-791b-4ccc-97c8-7e911304b54f@v4g2000hsf.googlegroups.com> On Jan 14, 8:25 pm, oyster wrote: > Thanx > However I knew Chaco and matplotlib, and I use matplotlib during my > school days. And as I have pointed out, they are for "plot", but not > "chart". If you don't know the difference between plot and chart, you > can have a look at athttp://www.jfree.org/jfreechart,http://www.rmchart.com > Yes, it is true we can use plot lib to draw chart, but that is tedious. What are the chart types that are missing? Or do you find that the handling of categorical data is generally lacking? Charting and plotting are quite related, and I think you might get better traction trying to add the exact chart and axis types that you need to an existing package rather than starting yet another plotting package for Python. :) -Peter From boblatest at yahoo.com Wed Jan 9 15:07:10 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 20:07:10 GMT Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <5ujp0tF1ehvg2U1@mid.dfncis.de> Message-ID: <5uknreF1il028U3@mid.uni-berlin.de> Sion Arrowsmith wrote: > Robert Latest wrote: >> BTW, where can I find all methods of the built-in types? >>Section 3.6 only talks about strings and mentions the list append() method >>only in an example. Am I too stupid to read the manual, or is this an >>omission? > > 3.6 talks about features common to all "sequence" types. Strings > are discussed specifically in 3.6.1 ("String Methods"). Lists are > similarly discussed in 3.6.4 ("Mutable Sequence Types"). OK, the latter then. Too stupid. Thanks ;-) robert From subopt at gmail.com Tue Jan 29 10:00:31 2008 From: subopt at gmail.com (subopt inTheVicinityOf geemail.com) Date: Tue, 29 Jan 2008 07:00:31 -0800 (PST) Subject: Trouble loading dll via ctypes Message-ID: <68615d61-3e71-4a39-8783-52ff0db97b48@i12g2000prf.googlegroups.com> I'm trying to load a dll via ctypes by doing this: cdll.LoadLibrary('/path/to/mylib.so') But i'm getting this: /path/to/mylib.so: cannot open shared object file: No such file or directory What am i doing wrong? The dll in question is in a directory mounted via NSF, but no part of the path/filename is a symlink. When i try code from the docs: cdll.LoadLibrary('libc.so.6') ,then all is fine. I've also tried to set my LD_LIBRARY_PATH before starting Python, checking it via os.environ, then doing the cdll.LoadLibrary(...), but that fails with the same complaint. What am i doing wrong? tia, Eric From paul at boddie.org.uk Tue Jan 15 06:40:54 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 15 Jan 2008 03:40:54 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> Message-ID: On 15 Jan, 08:33, "Jaimy Azle" wrote: > > perhaps in the future another sillly point could be added also, Java has > Jython, while Python doesn't have some thing like PyJava or... perhaps Py-va > (Python based Java Language). You could compile Java to CPython bytecode or, in the case of a little experiment I did some time ago, translate Java bytecode to CPython bytecode: the CPython virtual machine operates at a higher level and can support the Java instructions fairly easily, whereas a fair amount of work is required to support CPython instructions on the Java virtual machine. I found that the biggest obstacle was probably treating Java packages like Python packages - something which admittedly isn't completely necessary, but which would make the thing more usable at the prompt. Ultimately, I had little need for Java- based software and thus wasn't motivated into continuing the work, although Python 2.5 and beyond do provide some conveniences which might make some aspects of the implementation more bearable. Given that other languages (eg. Logix [2], various Lisp dialects) have been implemented for CPython, I think your point could be better formulated. Paul [1] http://www.boddie.org.uk/python/javaclass.html [2] http://www.livelogix.net/logix/ From sjmachin at lexicon.net Wed Jan 9 14:45:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 9 Jan 2008 11:45:43 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> Message-ID: <3a9ff586-007e-40c6-9568-d83bc7ce6f7d@d4g2000prg.googlegroups.com> On Jan 10, 5:56 am, Louis.Soni... at gmail.com wrote: > Hi pals > > I have a list like this > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] > > I'd like to remove the first and the last item as they are irrevalent, > and convert it to the dict: > {'tom':'boss','mike':'manager','paul':'employee'} > > I tried this but it didn't work: > > mydict={} > for i in mylist[1:-1]: > a=i.split('=') # this will disect each item of mylist into a 2-item No it doesn't; it dissects i into a 2-item list if i is a string containing exactly one '='. DON'T rely on "knowing" that the first and last entries are the only irrelevant ones. Do some checking. Conditions to check for: (1) len(a) == 2 (2) a[0] is empty or not what you expect (a person's name) (3) a[1] is empty or not what you expect (a job title) (consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = ' boss') (4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...] From kyosohma at gmail.com Fri Jan 4 16:57:26 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 4 Jan 2008 13:57:26 -0800 (PST) Subject: Skill Resume Achievements, What Good Goes Here? References: <724e4836-d895-4210-972d-dd8f861902df@l1g2000hsa.googlegroups.com> Message-ID: On Jan 4, 3:06 pm, apatheticagnostic wrote: > On Jan 2, 11:31 am, kyoso... at gmail.com wrote: > > > > > On Jan 2, 9:59 am, vbgunz wrote: > > > > I spent some time working on a skill resume, the kind of resume > > > college students put together and realized, I am not in college and > > > everything I learned was self-taught. Of course I would like some real > > > world achievements but don't consider throw-away code an achievement > > > and am failing to really see any. I don't even wish to entertain the > > > thought of lying about anything. > > > > What are some achievements an employer may be looking for in someone > > > willing to start at ground level, entry level, intern, etc? What are > > > some real world achievements every n00b will need under his/her belt > > > in order to be taken seriously? > > > Internships are always a good thing to have. If you've contributed to > > open source projects, I'd put that on there. If you're applying for > > some kind of programming job, they'll probably want to see some of > > your code, know what home-brewed projects you've done and how long > > they took to complete, issues you ran into, etc. > > > That might get you started anyway. > > > Mike > > As someone else who's self-educated and curious about this, would > listing canonical comp-sci books that you've gone through on your own > and understood be a reasonable thing to mention? For example, SICP, > PLAI, etc? I'm not sure...I went through a ton of interviews and was never asked about what books I'd read. I did get questions about group projects / assignments and a couple companies wanted to know what I programs I created on my own. Mike From DustanGroups at gmail.com Sun Jan 6 07:51:32 2008 From: DustanGroups at gmail.com (Dustan) Date: Sun, 6 Jan 2008 04:51:32 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <33417662-8246-4950-9b86-265aa1c63c69@c23g2000hsa.googlegroups.com> Message-ID: <24f46b58-330b-435c-8e57-8e18f1ce471e@d70g2000hsb.googlegroups.com> On Jan 5, 4:16 am, c... at mailinator.com wrote: > The warning "The group you are posting to is a Usenet group. Messages > posted to this group will make your email address visible to anyone on > the Internet." means a person, but not a bot, may see my email > address, so it is safe to use my real address next time... Wrong. A bot may be able to read and scan all messages sent through Usenet. From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 20:47:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 28 Jan 2008 01:47:18 -0000 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> Message-ID: <13pqd16n4o3rufe@corp.supernews.com> On Sun, 27 Jan 2008 19:13:27 -0500, Terry Reedy wrote: [snip] > class Test(object): > @autoassign > def __init__(self, _foo, _bar, baz): > print 'baz =', baz [snip] > I think this version, with this name convention, is nice enough to > possibly go in the stdlib if there were an appropriate place for it. > Not sure where though. If there were a classtools module.... -1/2 I don't like the name convention. _name already has a perfectly good convention: it's a private name, don't mess with it. That includes in function/method signatures. With your convention, _foo is public. I suppose you could write __foo for a private name, and ___foo for a *really* private name, relying on the decorator to strip one of the underscores. But counting all those underscores is a PITA, and what happens if you don't actually want that private name set as an instance attribute? As nice as this feature would be, and I vote +2 on the functionality, I wonder whether the amount of line noise in method definitions now will be approaching Perlish levels? We've got default values, type annotations (in Python3), *args and **kwargs, _ private names, and now we want to add auto-assignment. If we do get syntax support, I vote +1 on &foo, +1/2 on @foo, -1 on .foo and -1 on self.foo. (It's explicit, but it's long...). -- Steven From john.m.roach at gmail.com Wed Jan 9 14:30:45 2008 From: john.m.roach at gmail.com (John) Date: Wed, 9 Jan 2008 11:30:45 -0800 (PST) Subject: printing dots in simple program while waiting References: Message-ID: On Jan 9, 12:14 pm, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of Martin Marcher > > Sent: Wednesday, January 09, 2008 11:57 AM > > To: python-l... at python.org > > Subject: Re: printing dots in simple program while waiting > > > John wrote: > > > > import time > > > s = '.' > > > print 'working', # Note the "," at the end of the line > > > while True: > > > print s > > > time.sleep(1) > > > see my comment in the code above... > > > if that's what you mean > > Bah. The trailing command may prevent the newline, but it appends a > space whether you want it or not.[1] Use sys.stdout.write('.') instead. > > import sys > > print "wussy nanny state, tax 'n spend my spaces, liberal comma:" > for i in range(1, 10): > print '.', > print > print "manly neo-con I know what's Right so keep your government out of > my strings! print:" > for i in range(1, 10): > sys.stdout.write('.') > > [1] Which has to be _the_ most annoying feature of Python. *grrr* > > ***** > > 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 Thanks for all of the help. This is what ended up working: import time import sys s = '.' sys.stdout.write( 'working' ) while True: sys.stdout.write( s ) sys.stdout.flush() time.sleep(0.5) From suyashjape at gmail.com Fri Jan 11 01:25:06 2008 From: suyashjape at gmail.com (suyash jape) Date: Fri, 11 Jan 2008 11:55:06 +0530 Subject: How to POSTcall and retrieve result page Message-ID: <16314edc0801102225s502b8929oc802c66d4f0bedb1@mail.gmail.com> Hi all i want to access a web page through python script, fillup the necessary fields, and press submit button (which does POST call) and retrieve the result page and retrieve some values from it. Here is the script i have written till now. >import urllib2 > # create array of name/value pairs > self.params = urllib.urlencode({'seqname': 'BioSequence', 'sequence': 'ATACATTATCCAAACATAAAAAGCATGGCTT'}) > > # send http-post > request = urllib.urlopen("http://www.hydrazome.metazome.net/search.php", params) > > # read back each line of reply > line = request.read() >print line This script fills up the correct values in the search.php page.But i am not sure if it is doing the POST (submit call). Beacause in 'line' varialble, i am getting the search.php page.Not the result page which is blast_results.php. How to retrieve the result page? Thanks Suyash -------------- next part -------------- An HTML attachment was scrubbed... URL: From aisaac at american.edu Wed Jan 23 11:57:05 2008 From: aisaac at american.edu (Alan G Isaac) Date: Wed, 23 Jan 2008 11:57:05 -0500 Subject: pairs from a list In-Reply-To: References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> Message-ID: <24SdnaCXzLZC7AranZ2dnUVZ_v2pnZ2d@rcn.net> Steven D'Aprano wrote: > In fact, "fastest" isn't even a meaningful attribute. Does it mean: > > * the worst-case is fastest > * the best-case is fastest > * the average-case is fastest > * fastest on typical data > * all of the above I confess that it did not occur to me that there might be an interesting distinction among these cases for the question of how to get sequential pairs from a list. How would one draw these distinctions in this case? Thanks, Alan Isaac PS Just for context, the sequential pairs were needed in a simulation, but my question was primarily prompted by my surprise that the approaches I looked at differed as much as they did. From lists at cheimes.de Sat Jan 26 12:39:45 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 26 Jan 2008 18:39:45 +0100 Subject: Portably killing/signalling another process not supported? In-Reply-To: <479b6c58$0$36354$742ec2ed@news.sonic.net> References: <479b6c58$0$36354$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > There doesn't seem to be any way to portably kill another process > in Python. "os.kill" is Mac/Unix only. The "signal" module only lets > you send signals to the current process. And the "subprocess" module > doesn't have a "kill" function. > > Subprocess objects really should have a portable "interrupt" or > "kill" function. They already have "poll" and "wait", which have > to be implemented differently for different systems; that's the > logical place for "kill". > > Yes, there are nonportable workarounds > (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462) > but no portable solution. We are looking for somebody to implement a portable and cross platform implementation of kill() and send_signal() for the subprocess module. Are you interested in working on a patch for Python 2.6 and 3.0? From hardcoded.software at gmail.com Thu Jan 24 10:20:23 2008 From: hardcoded.software at gmail.com (Virgil Dupras) Date: Thu, 24 Jan 2008 07:20:23 -0800 (PST) Subject: Test driven development References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> Message-ID: <53bae618-0a57-470e-b698-3f936ef7c0e7@s12g2000prg.googlegroups.com> On Jan 24, 7:37?am, ajcpp... at gmail.com wrote: > Hi > > Sorry if this is a bit off topic but as unit testing is such a > cornerstone of python development I thought a few of you may be able > to share your knowledge/experiences. > > I like the concept of TDD but find it difficult to put into practice > most of the time. I think this primarily because I tend to like top- > down development and functional/object decomposition and TDD feels > more like a bottom-up approach. > > So my question is when approaching a project that you want to employ > test driven development on how and where do you start? And also if > anyone uses top-down design with TDD I would be interested in how you > do it (does it involve lots of mock objects/ is the first test you > write the last one to pass)? > > Thanks > > Andy I know what you mean by top-down vs. bottom-up and I used to have the same dilemma, but now I would tend to agree with Albert. Your issue with top-down or bottom-up is not relevant in TDD. The only thing that is relevant is to reach your current milestone as soon as possible, without caring about what you're going to do in the milestone after that. Not so long ago, I took the "bottom-up" approach to TDD, which was a mistake because it leads to over-engineering (the end result is not so bad since it's over-engineering that has good test coverage :) ) Roy: While mocking is good to have tests well organized (instead of having a huge pile of tests at the highest level), "over- mocking" (mocking everything, early) leads to, I think, a design that is too rigid. What if a new spec reveals that the current design of a large subset of your classes has to be re-done? All your mocking and the test below them, they all have to be "brought up" to the highest level of tests so you can re-organize your code. Since doing this is a lot of work, and usually messing with tests is a lot more dangerous than messing with the code itself, you would tend to stay with your old design, even if it's not the optimal design for the task you need to do. Virgil From jared.grubb at gmail.com Thu Jan 31 22:10:02 2008 From: jared.grubb at gmail.com (Jared Grubb) Date: Thu, 31 Jan 2008 19:10:02 -0800 Subject: char string 2 hex string Message-ID: <925822270801311910q2450c19ayd347e696cc040cc4@mail.gmail.com> You could also do: "".join(['%02x' % ord(c) for c in 'AAA']) On 31 Jan 2008, at 14:09, Paul Rubin wrote: Antonio Chay writes: "AAA" should be "414141" 'AAA'.encode('hex') -- http://mail.python.org/mailman/listinfo/python-list On 31 Jan 2008, at 14:05, Antonio Chay wrote: Hello! I need to transform a string from a file into a hexadecimal representation, for example: "AAA" should be "414141" With perl I do this with: unpack("H*","AAA") And with python I got this: "".join([str(hex(ord(x)))[2:] for x in "AAA"]) But seems a little "weird" for me. Is there another way? Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From digisatori at gmail.com Thu Jan 31 02:49:46 2008 From: digisatori at gmail.com (digisatori at gmail.com) Date: Wed, 30 Jan 2008 23:49:46 -0800 (PST) Subject: list traversal and remove Message-ID: I supposed the below code will print seven 2 and generate the list li without 2. Strangely it only print four 2. If you change the number of 2 in the list, the results are all beyond expectation. I know the other way to achieve the expected goal, but why this is happening? Could somebody enlight me? li= [2,2,2,2,2,2,2,3,4,5,6,7,8,9] for x in li: if x == 2: print x li.remove(x) From arnodel at googlemail.com Mon Jan 21 02:21:04 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 20 Jan 2008 23:21:04 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> Message-ID: On Jan 21, 3:19?am, Terry Jones wrote: > Here's a solution that doesn't use any copying of lists in for recursion. > It also eliminates a bunch of trivially equivalent solutions. The countdown > function is 37 lines of non-comment code. ?Sample (RPN) output below. > > Terry [snip code] > This produces: [...] > Target 234, numbers = (100, 9, 7, 6, 3, 1) > ? ? ? ? (6, 1, 'add', 100, 'mul', 7, 'sub', 9, 'add', 3, 'div') > ? ? ? ? (100, 1, 'sub', 3, 'div', 7, 'mul', 6, 'sub', 9, 'add') > ? ? ? ? (7, 6, 'mul', 3, 'mul', 100, 'sub', 9, 'mul', 1, 'mul') > ? ? ? ? (100, 7, 'sub', 3, 'div', 6, 'sub', 1, 'add', 9, 'mul') > ? ? ? ? (7, 6, 'mul', 3, 'mul', 1, 'sub', 100, 'add', 9, 'add') > ? ? ? ? (6, 9, 'sub', 7, 'mul', 1, 'sub', 100, 'add', 3, 'mul') > ? ? ? ? (100, 9, 'sub', 7, 'sub', 6, 'sub', 3, 'mul', 1, 'mul') > ? ? ? ? (100, 7, 'mul', 3, 'mul', 6, 'add', 9, 'div', 1, 'mul') > ? ? ? ? (100, 1, 'sub', 7, 'mul', 9, 'sub', 3, 'div', 6, 'add') > ? ? ? ? (100, 7, 'sub', 3, 'div', 1, 'sub', 9, 'add', 6, 'mul') > ? ? ? ? (7, 3, 'mul', 6, 'sub', 9, 'mul', 1, 'sub', 100, 'add') > ? ? ? ? (100, 7, 'mul', 6, 'sub', 1, 'sub', 9, 'add', 3, 'div') > ? ? ? ? (100, 9, 'add', 7, 'add', 1, 'add', 3, 'div', 6, 'mul') > ? ? ? ? (100, 9, 'sub', 7, 'div', 6, 'mul', 3, 'mul', 1, 'mul') In countdown you are not required to use all numbers to reach the target. This means you are missing solutions, e.g. (1, 3, 6, 'mul', 'add', 7 , 'add', 9, 'mul') After a quick glance at your code it seems to me that you can only have solutions of the type: (num, num, op, num, op, num, op, num, op, num, op) this omits many possible solutions (see the one above). -- Arnaud From fredrik at pythonware.com Wed Jan 9 12:19:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 18:19:57 +0100 Subject: asynchronous timer events - how to? In-Reply-To: <4784fd96$0$22305$ba620e4c@news.skynet.be> References: <4784fd96$0$22305$ba620e4c@news.skynet.be> Message-ID: Helmut Jarausch wrote: > I'm using a web server (Karrigell) which is based on the asyncore module. > I'd like to be able to checkpoint some data (e.g. pickled dictionaries) to disk > from time to time. > For that I would need to setup a timer which calls a Python object/function when > its time interval has expired. While this function is running I need access to > the variables of the server. the usual way to do that with asyncore is to add an outer control loop that calls asyncore.loop with a count argument (or poll directly), and checks a "task queue" at regular intervals. but in your case, it's probably easier to set up a cron job that does a "wget" against your server with a "secret" URL, and have the server do the checkpointing whenever that URL is fetched. From David.Reksten at sweco.no Wed Jan 30 09:47:42 2008 From: David.Reksten at sweco.no (David.Reksten at sweco.no) Date: Wed, 30 Jan 2008 15:47:42 +0100 Subject: SV: Unicode literals to latin-1 In-Reply-To: <2f3cbea4-861d-4076-913e-61ef5d81d738@b2g2000hsg.googlegroups.com> References: <60avf7F1ps52dU3@mid.uni-berlin.de> <2f3cbea4-861d-4076-913e-61ef5d81d738@b2g2000hsg.googlegroups.com> Message-ID: <7C90895B4B6EE44AAF5F16CB1F48427162C41CE48B@srv-mail-02.nettverk.int> On 30. januar 2008 14:31, Gabriel Genellina wrote: >On 30 ene, 07:54, wrote: >> On 30. januar 2008 10:48, Marc 'BlackJack' Rintsch wrote: >> >> >On Wed, 30 Jan 2008 09:57:55 +0100, David.Reksten wrote: >> >> >> How can I convert a string read from a database containing unicode >> >> literals, such as "Fr\u00f8ya" to the latin-1 equivalent, "Fr?ya"? > >> >In [388]: 'Fr\u00f8ya'.decode('unicode-escape') >> >Out[388]: u'Fr\xf8ya' >> >> 'unicode-escape' did the trick! Thank you! > >A unicode-escaped string looks very strange in a database... I'd >revise the way things are stored and retrieved. I agree. I'm currently using the trick above to fix it. .david From __peter__ at web.de Wed Jan 9 05:56:46 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 9 Jan 2008 11:56:46 +0100 Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: cesco wrote: > say I have a string like the following: s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' so > that I get a new string like the following: s2 = 'hi:cat,bye:dog' >>> import re >>> from itertools import cycle >>> re.sub("_", lambda m, c=cycle(":,").next: c(), "hi_cat_bye_dog") 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... There are many. If you want to learn Python don't be afraid to write it in a long-winded way (with loops and helper functions) first. Peter From lists at cheimes.de Thu Jan 17 01:03:03 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 17 Jan 2008 07:03:03 +0100 Subject: assigning values in python and perl In-Reply-To: <2d37f441-c01f-439b-9897-35b7e4dfa77b@h11g2000prf.googlegroups.com> References: <2d37f441-c01f-439b-9897-35b7e4dfa77b@h11g2000prf.googlegroups.com> Message-ID: <478EEF97.2070807@cheimes.de> George Sakkis wrote: > Python's parameter passing is like passing a pointer in C/C++. [snip] It's not (I repeat NOT) like passing a pointer in C. Please read http://effbot.org/zone/call-by-object.htm Christian From dannox at gmail.com Fri Jan 25 19:13:19 2008 From: dannox at gmail.com (whatazor) Date: Fri, 25 Jan 2008 16:13:19 -0800 (PST) Subject: python and multithreading problem Message-ID: <3a1379f5-f5f5-4af1-903c-8b1f52eb9ed7@k2g2000hse.googlegroups.com> Hi all, I made an application that use multithreading (indifferently importing thread or threading module) , but when I call some wrapped modules (with swig) from my application they run like there is only a single thread (and my application gui ,made with wxPython, freezes). If I use other modules not wrapped, but created for test that multithread works, and gui is not freezing are ok. Modules that wrap DLL are not my product but are created by another developer with VS.NET, and the only thing I can think is that they're builded without multithreaded compiler option. Can it be another cause for this behaviour, can this explanation be correct? maybe also swig have a multithreading option. thank you in advance w From sjmachin at lexicon.net Wed Jan 23 14:03:14 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 11:03:14 -0800 (PST) Subject: csv to xls using python 2.1.3 References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> Message-ID: On Jan 24, 1:58 am, LizzyLiz wrote: > Perfect! Thanks :-) > > LizzyLiz You have an interesting notion of perfection, which may change after some experience with the proposed solution. Note that sticking with Python 2.1 precludes your using the Python csv module as you first proposed, and is shutting you out of an enormous lot of new functionality. Are you inextricably bound to 2.1? From bperry.volatile at gmail.com Tue Jan 15 16:17:28 2008 From: bperry.volatile at gmail.com (Brandon Perry) Date: Tue, 15 Jan 2008 15:17:28 -0600 Subject: Compile with GLib-1.2 instead of 2.4 In-Reply-To: <1200430429.6386.2.camel@bperry-laptop> References: <1200430429.6386.2.camel@bperry-laptop> Message-ID: <1200431848.6386.4.camel@bperry-laptop> Sorry, I know what arg to use with ./configure. With --with-libc=STRING, do I put the version I want, or the path to my GLib 1.2 files? On Tue, 2008-01-15 at 14:53 -0600, Brandon Perry wrote: > Hi, I am having to compile a standalone python because the webserver I > use doesn't allow access to /usr/lib/python. I tried compiling on my > lappy and uploading it, but the webserver does not have GLib-2.4. What > arguments would I have to include in order for it to compile with > GLib-1.2 instead of/and GLib2.4? > > Thanks, Brandon From David.Reksten at sweco.no Wed Jan 30 04:40:36 2008 From: David.Reksten at sweco.no (David.Reksten at sweco.no) Date: Wed, 30 Jan 2008 10:40:36 +0100 Subject: SV: Unicode literals to latin-1 In-Reply-To: References: Message-ID: <7C90895B4B6EE44AAF5F16CB1F48427162C41CE46B@srv-mail-02.nettverk.int> On 30. januar 2008 10:21, Berteun Damman wrote: >On Wed, 30 Jan 2008 09:57:55 +0100, > wrote: >> How can I convert a string read from a database containing unicode >> literals, such as "Fr\u00f8ya" to the latin-1 equivalent, "Fr????ya"? >> >> I have tried variations around >> "Fr\u00f8ya".decode('latin-1') >> but to no avail. > >Assuming you use Unicode-strings, the following should work: > u"Fr\u00f8ya".encode('latin-1') I'm afraid that the string read from the database is a non-unicode string, thus me not using u"..." above. But it may contain unicode literals from the (Python-based) system that populated the table, and I'd like to get them back to proper unicode strings again, so that I can display them correctly to the user. >That is, for some string s, s.decode('encoding') converts the >non-unicode string s with encoding to a unicode string u. Whereas >for some unicode string u, u.encode('encoding') converts the unicode >string u into a non-unicode string with the specified encoding. > >You can use s.encode() on a non-unicode string, but it will first try to >decode it (which might give an DecodeError if there are non-ASCII >characters present) and it will then encode it. Any suggestions on how that would look, given the example above? .david From ryan at ryankaskel.com Wed Jan 23 13:50:02 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 10:50:02 -0800 (PST) Subject: Stripping whitespace Message-ID: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> Hello. I have a string like 'LNAME PASTA ZONE'. I want to create a list of those words and basically replace all the whitespace between them with one space so i could just do lala.split(). Thank you! Ryan Kaskel From fredrik at pythonware.com Fri Jan 4 04:25:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 10:25:54 +0100 Subject: linecache and glob In-Reply-To: <3682a1dd-a3a6-436f-87a0-37feaef65ccc@h11g2000prf.googlegroups.com> References: <0e16ca26-9e34-4f97-83de-9ddc3693d085@i12g2000prf.googlegroups.com> <0a62d553-7fe9-41c0-84dc-a1f3749b46f8@e23g2000prf.googlegroups.com> <3682a1dd-a3a6-436f-87a0-37feaef65ccc@h11g2000prf.googlegroups.com> Message-ID: jo3c wrote: > i have a 2000 files with header and data > i need to get the date information from the header > then insert it into my database > i am doing it in batch so i use glob.glob('/mydata/*/*/*.txt') > to get the date on line 4 in the txt file i use > linecache.getline('/mydata/myfile.txt/, 4) > > but if i use > linecache.getline('glob.glob('/mydata/*/*/*.txt', 4) won't work glob.glob returns a list of filenames, so you need to call getline once for each file in the list. but using linecache is absolutely the wrong tool for this; it's designed for *repeated* access to arbitrary lines in a file, so it keeps all the data in memory. that is, all the lines, for all 2000 files. if the files are small, and you want to keep the code short, it's easier to just grab the file's content and using indexing on the resulting list: for filename in glob.glob('/mydata/*/*/*.txt'): line = list(open(filename))[4-1] ... do something with line ... (note that line numbers usually start with 1, but Python's list indexing starts at 0). if the files might be large, use something like this instead: for filename in glob.glob('/mydata/*/*/*.txt'): f = open(filename) # skip first three lines f.readline(); f.readline(); f.readline() # grab the line we want line = f.readline() ... do something with line ... From bkasterm at gmail.com Tue Jan 29 21:23:56 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Tue, 29 Jan 2008 18:23:56 -0800 (PST) Subject: Gmail imap search does not get all messages. Message-ID: <60cd1edc-761c-4e68-b110-65df54f3c6b3@l32g2000hse.googlegroups.com> 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 Scott.Daniels at Acm.Org Sun Jan 6 13:52:35 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 06 Jan 2008 10:52:35 -0800 Subject: how to use bool In-Reply-To: References: <05c5df8b-15c4-47e6-8c14-72c57a84a0ea@y5g2000hsf.googlegroups.com> <2c516040-0193-4de3-bf7d-b61e739cdc2d@l57g2000hsa.googlegroups.com> Message-ID: <13o28j16l831pbe@corp.supernews.com> jimgardener at gmail.com wrote: > ...if another method in the same class calls this method but wants to > pass the error to a gui code which calls it,,can i do like this > > def callingmethode(self): > try: > mymethod() > except MyError,myerr: > raise myerr > > so that I can handle the error in a gui code that calls > callingmethode() > > class MyGUI: > def guimethode(self): > someinst=SomeClass() > try: > someinst.callingmethode() > except MyError,myer: > self.dealwithMyError(myer) > > is this kind of raising exception the correct way?I am getting syntax > error at > except MyError,myerr: > raise myerr > Almost. The callingmethode code above behaves like: def callingmethode(self): mymethod() except that your code hides the traceback information. If you need to do something locally (other than passing along the exception), use either: def callingmethode(self): try: mymethod() finally: cleanup_stuff() or (if you have some exception-specific code to do): def callingmethode(self): try: mymethod() except MyError,myerr: stuff_only_for_exceptional_cases() raise # Note that this keeps the original traceback. --Scott David Daniels Scott.Daniels at Acm.Org From martin at marcher.name Sat Jan 12 15:34:32 2008 From: martin at marcher.name (Martin Marcher) Date: Sat, 12 Jan 2008 21:34:32 +0100 Subject: sqlite3 is it in the python default distro? Message-ID: Hello, I can see that sqlite is in the standard lib documentation: http://docs.python.org/lib/module-sqlite3.html however debian and ubuntu (and gentoo according to the packages info) seem _not_ to include it. Now 2 question arise: a) Is sqlite included in the python default distribution b) In real life can I consider (on linux) that an installation of python includes the sqlite stuff? thanks martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 22 06:48:02 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 22 Jan 2008 12:48:02 +0100 Subject: what's this instance? In-Reply-To: References: <4795b32d$0$16941$426a74cc@news.free.fr> Message-ID: <4795d7a5$0$25895$426a74cc@news.free.fr> J. Peng a ?crit : > Bruno Desthuilliers ??: >> J. Peng a ?crit : >>> def safe_float(object): >>> try: >>> retval = float(object) >>> except (ValueError, TypeError), oops: >>> retval = str(oops) >>> return retval >>> The code above works well. >> For which definition of "works well" ? >> > > I got it from Core Python Programming book I bought.You may ask it to > Westley Chun.:) Ok: Mr Chun, if you here us ?-) From stanc at al.com.au Thu Jan 31 19:01:40 2008 From: stanc at al.com.au (Astan Chee) Date: Fri, 01 Feb 2008 11:01:40 +1100 Subject: wxEVT_SCROLL_ENDSCROLL In-Reply-To: <151424.10138.qm@web35309.mail.mud.yahoo.com> References: <151424.10138.qm@web35309.mail.mud.yahoo.com> Message-ID: <47A26164.30109@al.com.au> try wx.EVT_SCROLL_ENDSCROLL ? Jack Holt wrote: > Hello, > > I got the following error: > > Traceback (most recent call last): > File "vplayer.py", line 15, in ? > File "config.pyo", line 3, in ? > File "wx\__init__.pyo", line 44, in ? > File "wx\_core.pyo", line 3592, in ? > AttributeError: 'module' object has no attribute > 'wxEVT_SCROLL_ENDSCROLL' > > > I never had that error before... until I messed up > with the python package > (I had to reinstall Active Python + py2exe + > wxpython). I can run my app > from the SVN with no problem. I get the error from the > compiled version - > made with py2exe. > > Line 3 in config.py points to: Import wx > > > > Help!! > > Thanks, > -Dan > > > > ____________________________________________________________________________________ > Looking for last minute shopping deals? > Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping > Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. From petr.jakes.tpc at gmail.com Tue Jan 1 23:11:12 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Tue, 1 Jan 2008 20:11:12 -0800 (PST) Subject: Newbie: Why doesn't this work References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> <13nldkj6ecl4j31@corp.supernews.com> Message-ID: Steven, thanks for a nice explanation. I am trying to experiment a little bit with new-style class and I am confused why following example always returns 0 (zero). I was expecting will return values from 0 to 9 and finaly an Exception. class GenExample(object): def getInfo(self): for no in range(10): yield no myNo=property(getInfo) gen=GenExample() print gen.myNo.next() print gen.myNo.next() . . print gen.myNo.next() -- Petr Jakes From arnodel at googlemail.com Tue Jan 22 13:55:55 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 10:55:55 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Jan 22, 6:34?pm, Paddy wrote: [...] > Hi George, > You need to 'get it right' first. Micro optimizations for speed > without thought of the wider context is a bad habit to form and a time > waster. > If the routine is all that needs to be delivered and it does not > perform at an acceptable speed then find out what is acceptable and > optimise towards that goal. My questions were set to get posters to > think more about the need for speed optimizations and where they > should be applied, (if at all). > > A bit of forethought might justify leaving the routine alone, or > optimising for readability instead. But it's fun! Some-of-us-can't-help-it'ly yours -- Arnaud From hniksic at xemacs.org Fri Jan 4 10:05:58 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 04 Jan 2008 16:05:58 +0100 Subject: Details about pythons set implementation References: Message-ID: <87bq818wbt.fsf@mulj.homelinux.net> Achim Domma writes: > I'm interested in details about how sets are implemented in python. > They seem to be quite fast and I found some remarks who state, that > the implementation is highly optimized. I need to implemented sets > in C/C++ and need a starting point on how to do it right. Could > somebody give me a starting point? You can simply look at the implementation, Objects/setobject.c in the Python source code. Most that it's mostly copy-paste from the dict implementation (dictobject.c) and that both are quite involved and optimized for the use by Python. They're not general implementation of sets from use in C. The "highly optimized" remarks should be understood in the context of Python, not in the context of other C and C++ set libraries. I don't know how well Python sets compare to other set libraries, but I doubt that it's much faster than the median (which "highly optimized" could be understood to imply). BTW if you're using C++, why not simply use std::set? If you need it called from C, you can wrap the needed methods in a C-accessible API. From nick at craig-wood.com Fri Jan 4 09:30:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 04 Jan 2008 08:30:05 -0600 Subject: Why python says "unexpected parameter 'mini.py'" for my code? References: Message-ID: oyster wrote: > The following is my pure-python wxwidgets test. It is hardly pure python since it depends on wxWindows and ctypes... > It runs and give a frame, but soon python comes up to say > "unexpected parameter > 'mini.py'" and I have to close it. > I cannot find the reason. Can somebody give me a hint to let it work > well? Thanks I tried it but it doesn't work at all on linux. I suggest you use wxPython and stop re-inventing the wheel! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ajaksu at gmail.com Sun Jan 27 17:58:23 2008 From: ajaksu at gmail.com (ajaksu) Date: Sun, 27 Jan 2008 14:58:23 -0800 (PST) Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> Message-ID: <7d1d4b80-3d54-4bf7-8393-3fb2cf97f674@v67g2000hse.googlegroups.com> This message got huge :/ Sorry for being so cryptic and unhelpful. I now believe that you're incurring in a (quite deep) misunderstanding and wish to make things clear for both of us :) On Jan 27, 6:58 am, o... at thepond.com wrote: > On Fri, 25 Jan 2008 17:44:07 -0800 (PST), ajaksu > wrote: > > > > >On Jan 25, 11:36 pm, ajaksu wrote: > >> On Jan 25, 11:10 pm, o... at thepond.com wrote: > >[...] > > >Gaah, is this what's going on? > > >ajaksu at Belkar:~$ cat error.txt > >This is not assembler... > > >ajaksu at Belkar:~$ ndisasm error.txt > >00000000 54 push sp > >00000001 686973 push word 0x7369 > >00000004 206973 and [bx+di+0x73],ch > >00000007 206E6F and [bp+0x6f],ch > >0000000A 7420 jz 0x2c > >0000000C 61 popa > >0000000D 7373 jnc 0x82 > >0000000F 656D gs insw > >00000011 626C65 bound bp,[si+0x65] > >00000014 722E jc 0x44 > >00000016 2E db 0x2E > >00000017 2E db 0x2E > >00000018 0A db 0x0A > > >:/ > > not sure what you're saying. Sure looks like assembler to me. Take the > '54 push sp'. The 54 is an assembler opcode for push and the sp is > the stack pointer, on which it is operating. What I did above was: 1- create a file called "error.txt" that contains the string "This is not assembler..." 2- show the contents of the file ("cat" being the relevant command) 3- run the NetWideDisassembler (ndisasm) on error.txt 4- watch as it "disassembled" the text file (in fact, "assembling" the code above reconstructs part of the string!) 5- conclude that you were misguided by this behavior of disassemblers, for AFAIK .pyc files contain Python "opcodes" (bytecode), that in no way I can think of could be parsed by a generic disassembler 6- form a belief that you were trying to understand meaningless "assembler" like the above (that would have no bearing on what Python does!) Now, it seems that we're in flaming mode and that is unfortunate, because I do believe in your expertise. In part, because my father was a systems analyst for IBM mainframes and knows (a huge) lot about informatics. However, I've seen him, due to simple misunderstandings like this, building a complex scenario to explain his troubles with MSWord. I believe this is what's happening here, so I suggest that we take a step back and stop calling names. Given that you're in the uncomfortable place of the "troll assigned by votes" outsider in this issue, let me expose some relevant data. The people you're pissed off with (and vice-versa) are very competent and knowledgeable Python (and other languages) programmers, very kind to newcomers and notably helpful (as you might find out lurking in this newsgroup or reading the archives). They spend time and energy helping people to solve problems and understand the language. Seriously, they know about assembler (a lot more than I do) and how Python works. And they know and respect each other. Now, your attitude and faith in your own assumptions (of which, "the .pyc contains assembler" in special) was both rude and upsetting. This doesn't mean that you're not an assembler expert (I believe you are). But it seemed like you were trying to teach us how Python works, and that was considered offensive, specially due to your words. OTOH, my responses were cryptic, unhelpful and smell of "mob thinking". While Steven D'Aprano and others showed a lot more of patience and willingness to help. So please forgive me and please PAY ATTENTION to those trying to HELP and make things clearer to you. As a simple example of my own e Dunning-Kruger effect, I was sure I'd get errors on trying to "assemble" the output of the disassembling, but it does roundtrip part of the string and I was baffled. I'd guess you know why, I have no idea. The 0x74 finding was also curious, you are indeed getting part of the binary format of bytecode, but (AFAICT) you won't find real assembler there. In summary, you can show us what you know and put your knowledge (instead of what you got wrong and how you upset people) in focus. Try to set things right. Believe me, this here community packs an uncommon amount of greatness and openness. HTH, Daniel From sour.craig at gmail.com Fri Jan 11 11:31:24 2008 From: sour.craig at gmail.com (Craig Ward) Date: Fri, 11 Jan 2008 11:31:24 -0500 Subject: Fwd: newbie question regarding int(input(:)) - sorry for the spam Message-ID: <275866c0801110831sbe97615ic96af03c3473f2d1@mail.gmail.com> sorry for the spam Here is the complete message! I am trying to write a menu script that will execute bash scripts. Everything is fine until the script executes and I want to see if there are any more options to run before quitting. Example: ================================================= def menu(opt1 = "something", opt2 = "something else"): print "1)", opt1 "" print "2)", opt2"" def anythingelse(opt 3 = "final check"): menu() print "3)", opt3"" menu() choice = int(input(":")) if choice == 1 command anythingelse() elif choice == 2 command 2 anythingelse() else choice ==3 command 3 quit ======================================= My newbie problem is that although the menu repeats there is no chance to have a second input and I can't put the int(input(":") in the function because I get the error 'int' is not callable plus my choice variable is not defined. can someone please enlighten me? :-) ---------- Forwarded message ---------- From: Craig Ward Date: Jan 11, 2008 11:21 AM Subject: newbie question regarding int(input(:)) To: python-list at python.org Hi experts! I am trying to write a menu script that will execute bash scripts. Everything is fine until the script executes and I want to see if there are any more options to run before quitting. Example: def menu(opt1 = "something", opt2 = "something else"): -- Computers are like air conditioners. They stop working when you open Windows. -- Computers are like air conditioners. They stop working when you open Windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Jan 8 10:45:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 Jan 2008 16:45:01 +0100 Subject: stupid/style/list question In-Reply-To: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> References: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> Message-ID: Giampaolo Rodola' wrote: > To flush a list it is better doing "del mylist[:]" or "mylist = []"? > Is there a preferred way? If yes, why? The latter creates a new list object, the former modifies an existing list in place. The latter is shorter, reads better, and is probably a bit faster in most cases. The former should be used when it's important to clear a specific list object (e.g. if there are multiple references to the list). From emin.shopper at gmail.com Thu Jan 3 17:09:03 2008 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Thu, 3 Jan 2008 17:09:03 -0500 Subject: choosing random dynamic port number Message-ID: <32e43bb70801031409o5d1dcd2at5a159339cd43ae52@mail.gmail.com> Dear Experts, Is there a good way to choose/assign random dynamic port numbers in python? I had in mind something like the following, but if multiple programs are generating random port numbers, is there a way to check if a given port number is already taken? def GenerateDynamicPortNumber(): "Generate a random dynamic port number and return it." # port numbers between 49152 to 65535 are dynamic port numbers return 49152 + random.randrange(15000) -------------- next part -------------- An HTML attachment was scrubbed... URL: From cokofreedom at gmail.com Fri Jan 11 04:06:16 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 11 Jan 2008 01:06:16 -0800 (PST) Subject: python recursive function References: Message-ID: <33eeba3f-701c-40a3-bb71-fb3fd94b877e@e6g2000prf.googlegroups.com> On Jan 11, 9:46 am, Gary Herron wrote: > Tom_chicollegeboy wrote: > > here is what I have to do: > > > This question involves a game with teddy bears. The game starts when I > > give you some bears. You then start giving me back some bears, but you > > must follow these rules (where n is the number of bears that you > > have): > > This sounds very much like a homework assignment, and so should probably > not be answered here. (Neither should it have been asked here.) If, > in your attempt to write this program, you have some questions about > Python, then I encourage to ask those questions here. > > Gary Herron > > > If n is even, then you may give back exactly n/2 bears. (Hint: To test > > whether n is even, use the expression ((n % 2) == 0).) > > If n is divisible by 3 or 4, then you may multiply the last two digits > > of n and give back this many bears. (By the way, the last digit of n > > is n%10, and the next-to-last digit is (n%100)/10; this rule may not > > be used if either of the last two digits is 0.) > > > If n is divisible by 5, then you may give back exactly 42 bears. > > The goal of the game for you is to end up with EXACTLY 42 bears. > > > For example, suppose that you start with 250 bears. Then you could > > make these moves: > > > Start with 250 bears. > > Since 250 is divisible by 5, you may return 42 of the bears, leaving > > you with 208 bears. > > Since 208 is even, you may return half of the bears, leaving you with > > 104 bears. > > Since 104 is even, you may return half of the bears, leaving you with > > 52 bears. > > Since 52 is divisible by 4, you may multiply the last two digits > > (resulting in 10) and return these 10 bears. This leaves you with 42 > > bears. > > You have reached the goal! > > Now, you are to write a program that, if I give you n bears, returns > > true if it is at all possible for you to win the game. Your program > > must use recursion to check all possible ways in which you can apply > > the rules. > > > Usage: > > >>>> bears(42) > > > True > > >>>> bears(250) > > > True > > >>>> bears(50) > > > False > > >>>> bears(84) > > > True > > >>>> bears(41) > > > False > > > As you see my program must use recursion. > > > I came up with this idea but I am not sure if its right or are there > > any minor errors that I can easily fix: > > > def bears (n): > > if n==42: > > return True > > if n%5==0: > > bears(n-42) > > if n%2==0: > > bears(n/2) > > if n%3==0 or n%4==0: > > one = (n%10) > > two = ((n%100)/10) > > if one!=0 and two!=0: > > bears(n-(one*two)) > > return False > > > If a game hits 42 it should return True, otherwise False. If program > > never hits 42 and return True, then it returns False. I figured out > > base case, but I still get False when I enter bears(250). Any help > > would be very appreciated! Note that for ; if one!=0 and two!=0: you can use if one and two: which is my pythonic. Also in your example with 52, shouldn't it divide by even first? Obviously this must not happen, thus maybe you should run a check that when you are returning a new value it does not go below 42? Frankly this looks like a terrible way to use recursion. From fredrik at pythonware.com Sat Jan 12 14:35:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Jan 2008 20:35:58 +0100 Subject: IDLE won't start in Python 2.5 for Windows In-Reply-To: <57a7e4a2-0acc-4439-9bd6-d96862ffc22e@j78g2000hsd.googlegroups.com> References: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> <13ogqhlds0tbsac@corp.supernews.com> <57a7e4a2-0acc-4439-9bd6-d96862ffc22e@j78g2000hsd.googlegroups.com> Message-ID: mikez302 wrote: > I opened a command window in my Python25 folder and tried typing > pythonw. I just got another command prompt as if the program ran but > didn't do anything. It looked like this: > > C:\Python25>pythonw > > C:\Python25> "pythonw" is the console-less version of the Python runtime, so that's expected. Try using "python" instead. From sjmachin at lexicon.net Sun Jan 27 16:50:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 27 Jan 2008 13:50:15 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> Message-ID: On Jan 28, 7:47 am, "Mark Tolonen" wrote: > >"John Machin" wrote in message > >news:eeb3a05f-c122-4b8c-95d8-d13741263374 at h11g2000prf.googlegroups.com... > >On Jan 27, 9:17 pm, glacier wrote: > >> On 1?24?, ??3?29?, "Gabriel Genellina" > >> wrote: > > >*IF* the file is well-formed GBK, then the codec will not mess up when > >decoding it to Unicode. The usual cause of mess is a combination of a > >human and a text editor :-) > > SAX uses the expat parser. From the pyexpat module docs: > > Expat doesn't support as many encodings as Python does, and its repertoire > of encodings can't be extended; it supports UTF-8, UTF-16, ISO-8859-1 > (Latin1), and ASCII. If encoding is given it will override the implicit or > explicit encoding of the document. > > --Mark Thank you for pointing out where that list of encodings had been cunningly concealed. However the relevance of dropping it in as an apparent response to my answer to the OP's question about decoding possibly butchered GBK strings is .... what? In any case, it seems to support other 8-bit encodings e.g. iso-8859-2 and koi8-r ... C:\junk>type gbksax.py import xml.sax, xml.sax.saxutils import cStringIO unistr = u''.join(unichr(0x4E00+i) + unichr(ord('W')+i) for i in range(4)) print 'unistr=%r' % unistr gbkstr = unistr.encode('gbk') print 'gbkstr=%r' % gbkstr unistr2 = gbkstr.decode('gbk') assert unistr2 == unistr print "latin1 FF -> utf8 = %r" % '\xff'.decode('iso-8859-1').encode('utf8') print "latin2 FF -> utf8 = %r" % '\xff'.decode('iso-8859-2').encode('utf8') print "koi8r FF -> utf8 = %r" % '\xff'.decode('koi8-r').encode('utf8') xml_template = """%s""" asciidoc = xml_template % ('ascii', 'The quick brown fox etc') utf8doc = xml_template % ('utf-8', unistr.encode('utf8')) latin1doc = xml_template % ('iso-8859-1', 'nil illegitimati carborundum' + '\xff') latin2doc = xml_template % ('iso-8859-2', 'duo secundus' + '\xff') koi8rdoc = xml_template % ('koi8-r', 'Moskva' + '\xff') gbkdoc = xml_template % ('gbk', gbkstr) for doc in (asciidoc, utf8doc, latin1doc, latin2doc, koi8rdoc, gbkdoc): f = cStringIO.StringIO() handler = xml.sax.saxutils.XMLGenerator(f, encoding='utf8') xml.sax.parseString(doc, handler) result = f.getvalue() f.close print repr(result[result.find(''):]) C:\junk>gbksax.py unistr=u'\u4e00W\u4e01X\u4e02Y\u4e03Z' gbkstr='\xd2\xbbW\xb6\xa1X\x81 at Y\xc6\xdfZ' latin1 FF -> utf8 = '\xc3\xbf' latin2 FF -> utf8 = '\xcb\x99' koi8r FF -> utf8 = '\xd0\xaa' 'The quick brown fox etc' '\xe4\xb8\x80W\xe4\xb8\x81X\xe4\xb8\x82Y\xe4\xb8\x83Z' 'nil illegitimati carborundum\xc3\xbf' 'duo secundus\xcb\x99' 'Moskva\xd0\xaa' Traceback (most recent call last): File "C:\junk\gbksax.py", line 27, in xml.sax.parseString(doc, handler) File "C:\Python25\lib\xml\sax\__init__.py", line 49, in parseString parser.parse(inpsrc) 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 xml.sax._exceptions.SAXParseException: :1:30: unknown encoding C:\junk> From kay.schluehr at gmx.net Mon Jan 28 10:02:25 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 28 Jan 2008 07:02:25 -0800 (PST) Subject: optional static typing for Python References: Message-ID: <6ddadeeb-6ca6-4456-a0d8-ba80fd8d1d17@v46g2000hsv.googlegroups.com> On 27 Jan., 23:19, "Russ P." wrote: > A while back I came across a tentative proposal from way back in 2000 > for optional static typing in Python: > > http://www.python.org/~guido/static-typing > > Two motivations were given: > > -- faster code > -- better compile-time error detection > > I'd like to suggest a third, which could help extend Python into the > safety-critical domain: > > -- facilitates automated source-code analysis > > There has been much heated debate in the past about whether Python is > appropriate for safety-critical software. Some argue that, with > thorough testing, Python code can be as reliable as code in any > language. Well, maybe. But then, a famous computer scientist once > remarked that, > > "Program testing can be used to show the presence of bugs, but never > to show their absence!" --Edsger Dijkstra > > The next step beyond extensive testing is automated, "static" analysis > of source-code ("static" in the sense of analyzing it without actually > running it). For example, Spark Ada is a subset of Ada with > programming by contract, and in some cases it can formally prove the > correctness of a program by static analysis. > > Then there is Java Pathfinder (http://javapathfinder.sourceforge.net), > an "explicit state software model checker." The developers of JPF > wanted > to use it on a prototype safety-critical application that I wrote in > Python, but JPF only works on Java code. We considered somehow using > Jython and Jythonc, but neither did the trick. So they ended up having > someone manually convert my Python code to Java! (The problem is that > my code was still in flux, and the Java and Python versions have now > diverged.) > > In any case, optional static typing in Python would help tremendously > here. The hardest part of automated conversion of Python to a > statically typed language is the problem of type inference. If the > types are explicitly declared, that problem obviously goes away. > Explicit typing would also greatly facilitate the development of a > "Python Pathfinder," so the conversion would perhaps not even be > necessary in the first place. > > Note also that, while "static" type checking would be ideal, > "explicit" typing would be a major step in the right direction and > would probably be much easier to implement. That is, provide a syntax > to explicitly declare types, then just check them at run time. A > relatively simple pre-processor could be implemented to convert the > explicit type declarations into "isinstance" checks or some such > thing. (A pre-processor command-line argument could be provided to > disable the type checks for more efficient production runs if > desired.) > > I noticed that Guido has expressed further interest in static typing > three or four years ago on his blog. Does anyone know the current > status of this project? Thanks. It has been withdrawn in its original version. What's left is annotation syntax and the __annotation__ dict ( I don't know what the latter is good for but maybe some purpose emerges once a complete signature object is provided? ). So there has not been much work spent on hybrid type systems, static analysis and type directed native compilation. I did some work on type feedback and created a Python dialect called TPython a while ago based on Python 3.0 but supporting more syntax to add also local type annotations and an 'A of T' construct for type parametricity. The main purpose of TPython was to provide an interface for 3rd party tools used for refactoring, type checking, compilation, documentation etc. without separating annotations from Python code but build them in place. This project is unpublished and on hold because it is part of EasyExtend 2.0 and I reworked EE to incorporate a brand new parser generator called Trail that involved quite some research from my side. EasyExtend 3 is intended to be released in Q2. Regards From bignose+hates-spam at benfinney.id.au Tue Jan 1 23:17:54 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 02 Jan 2008 15:17:54 +1100 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au> <87bq85rp2d.fsf@physik.rwth-aachen.de> Message-ID: <87abnoc13h.fsf@benfinney.id.au> Torsten Bronger writes: > [...] the width of a tab is nowhere defined. It really is a matter > of the editor's settings. RFC 678 "Standard File Formats" : Horizontal Tab Moves the printer to the next horizontal tab stop. The conventional stops for horizontal tabs are every eight characters, that is character positions 9, 17, 25, ... within the logical page. Note that it is difficult to enforce these conventions and it is therefore recommended that horizontal tabs not be used in document files. > I, for example, dislike too wide indenting. I use four columns in > Python and two in Delphi. However, there are Python projects using > eight spaces for each indentation level. How many columns to indent source code is an orthogonal question to how wide an ASCII TAB (U+0009) should be rendered. The former question is open to matters of style; the latter at least is standardised, even given the caveats about enforcement. > If all Python code used tabs, eveybody could use their own > preferences, for both reading and writing code, and interoperability > would be maintained nevertheless. Interoperability isn't the only criterion though. On the contrary, source code is primarily for reading by programmers, and only incidentally for reading by the compiler. -- \ "I hate it when my foot falls asleep during the day, because | `\ that means it's gonna be up all night." -- Steven Wright | _o__) | Ben Finney From msj at infoserv.dk Tue Jan 29 09:21:46 2008 From: msj at infoserv.dk (Martin Skou) Date: Tue, 29 Jan 2008 15:21:46 +0100 Subject: Executing other python code In-Reply-To: References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: <479f3618$0$2088$edfadb0f@dtext02.news.tele.dk> Over-simplified yes, but it will work! Python is beautiful :-) From steveo at syslang.net Mon Jan 28 13:06:16 2008 From: steveo at syslang.net (Steven W. Orr) Date: Mon, 28 Jan 2008 13:06:16 -0500 (EST) Subject: Question on importing wxPython Message-ID: python-2.3.5 wx-2.6 I just bought the wxPython In Action book and I see that all the examples say to import wx All of our pre-existing code was horribly doing a from wxPython import * I changed all the code so that it was doing an import wx and found that everything was broken. In particular, references to wxNewId would fail. 634 > python Python 2.3.5 (#2, May 4 2005, 08:51:39) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import wx >>> wx.wxNewId Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'wxNewId' >>> In fact, the *only* way to get it was to go back to import wxPython and then refer to it as wxPython.wx.wxNewId Is my system broken or am I missing something? i.e., should I be able to say import wx? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From lists at cheimes.de Wed Jan 23 02:51:13 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 23 Jan 2008 08:51:13 +0100 Subject: bags? 2.5.x? In-Reply-To: References: Message-ID: Dan Stromberg wrote: > Is there a particular reason why bags didn't go into 2.5.x or 3000? > > I keep wanting something like them - especially bags with something akin > to set union, intersection and difference. Ask yourself the following questions: * Is the feature useful for the broad mass? * Has the feature been implemented and contributed for Python? * Is the code well written, tested and documented? * Is the code mature and used by lots of people? Can you answer every question with yes? Christian From yuxi at ece.gatech.edu Sat Jan 19 08:57:24 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Sat, 19 Jan 2008 08:57:24 -0500 Subject: Core Python Programming . . . In-Reply-To: <0005f532-409b-4c4e-8483-b2e32bbc724a@q77g2000hsh.googlegroups.com> References: <7xir1q29j5.fsf@ruckus.brouhaha.com> <0005f532-409b-4c4e-8483-b2e32bbc724a@q77g2000hsh.googlegroups.com> Message-ID: FireNWater wrote: > I guess I'm not fully up to speed on what constitutes an IP address. > Does the term 'octet' refer to an 8-bit (xFF) number? Yes, it somewhat archaic though. It's used when "byte" is ambiguous. On some ancient (by computing standards) computers, the size of a byte may be as small as 6 bits or as big as 9. For the purposes of this question, I think it's safe to assume an IP address is just a 32-bit number. And you need to extract each group of 8-bits and print those out with dots between them. From ckimyt at gmail.com Fri Jan 4 08:45:22 2008 From: ckimyt at gmail.com (Mike) Date: Fri, 4 Jan 2008 05:45:22 -0800 (PST) Subject: Strange varargs issue Message-ID: I'm not sure if this is a bug or if I'm just not understanding something correctly. I'm running the following (broken.py) on ActivePython 2.5.1.1, based on Python 2.5.1 (r251:54863 5/1/2007) as "python broken.py foo" (on Windows, of course): #!/bin/env python import sys class foobar(object): def func(arg): print 'foobar.func: %r' % arg __f = foobar() def caller(a): print 'caller: %r' % a __f.func(a) def main(): rest = sys.argv[1:] print 'main: %r' % rest caller(*rest) if __name__ == '__main__': main() ...and the result of running this ("python broken.py foo") is: main: ['foo'] caller: 'foo' Traceback (most recent call last): File "broken.py", line 21, in main() File "broken.py", line 18, in main caller(*rest) File "broken.py", line 13, in caller __f.func(a) TypeError: func() takes exactly 1 argument (2 given) How can this possibly be? The "caller" print statement obviously shows "a" is singular. Thanks in advance for any and all insight... Mike From ajaksu at gmail.com Sat Jan 5 11:57:35 2008 From: ajaksu at gmail.com (ajaksu) Date: Sat, 5 Jan 2008 08:57:35 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> Message-ID: <2ab22f95-d132-4e3c-8b68-bcbcee64e2ef@j78g2000hsd.googlegroups.com> Hi there :) On Jan 5, 2:14 pm, c... at mailinator.com wrote: > On Jan 5, 5:07 pm, c... at mailinator.com wrote: > > > Hello, Paul and Arnaud. > > While I think about your answers: do you think there is any way to > > avoid shuffle? > > It may take unnecessary long on a long list most of whose elements > > have the property. I've been thinking about this one before you asked and only got a bad solution: you don't need to shuffle the list if you can construct a random list of indexes to loop through, but my timings show that I can't do that faster than "shuffle(range(x))" for worst cases (i.e., iterate thru the whole list) :) The rather good news is that shuffling a list of arbitrary objects is pretty fast (as compared to a list of integers). OTOH, if you do know that the chances are high enough, you can try choosing items randomly without substitution (adapted from random.py's sample): from random import random def randpickuntil(lst, prop=bool): selected = set() for i in xrange(len(lst)): j = int(random() * n) while j in selected: j = int(random() * n) if prop(lst[j]): return lst[j] selected_add(j) > Umm... > You provide nice answers in the case many elements are picked from the > same list. > Any ideas for the case when the picker is called many times on a > program, but never twice with the same list? If the lists share items, a cache could help a lot. Otherwise, you'd benefit more from finding a good way to test the property (could you give a hint on what it is?). How do objects acquire that property, is it a sum of independent factors? HTH, Daniel From devraj at gmail.com Thu Jan 10 21:44:34 2008 From: devraj at gmail.com (Devraj) Date: Thu, 10 Jan 2008 18:44:34 -0800 (PST) Subject: open excel file while it is being used. References: Message-ID: <3305cad1-a17b-4b95-98ce-04ac2e420dfb@s19g2000prg.googlegroups.com> Hi Barry, Obviously what you are trying to do is detect file locks. I am not exactly sure how to do this in Python but from previous system administration jobs here are some scenarios that you might want to watch out for. - I know for one that if you are accessing the file on a Samba share, file locking with OpenOffice or Excel have strange things happen to them - I am also aware that the same thing works different if the files are shared from a Windows server and accessed on a Linux machine, and depends on the version of Samba/Linux kernel you are running On Jan 11, 7:38 am, barry.z... at gmail.com wrote: > Hi, > > I have a python program that constantly updates an excel spreadsheet. > I would like to be able to view its updates while using excel to edit > other excel files. Below are the test codes I have: > > -------------------------------------------------------------------------------------- > from time import sleep > import win32com.client as w32c > > def test(): > w32c.pythoncom.CoInitialize() > print w32c.pythoncom._GetInterfaceCount() > app1 = w32c.Dispatch("Excel.Application") > #app1.Visible=False > #app1.Interactive = False > wb=app1.Workbooks.Open("c:\\temp\\Book1.xls") > > sleep(3) > sh=wb.Sheets("Sheet1") > sh.Cells(2,1).Value = "Hello, world!" > sh = None > > wb.Save() > wb = None > app1 = None > w32c.pythoncom.CoUninitialize() > print w32c.pythoncom._GetInterfaceCount() > ------------------------------------------------------------------------------------- > > If the user just looks at the file then it's fine, but if the user > double clicks one cell, which will have a cursor flashing in the cell, > then it will lead to a crash of the program with error: "Call was > rejected by callee." I can make the program keep trying to access the > file, but if the user doesn't make the flashing cursor disappear, the > program will wait forever! > > I know excel has the fuction such that when a user is accessing a file > and other users open that file, it will prompt for options of opening > it as read-only or sending notification. I have been trying to > implement that in the program, but don't know how. > > So, any suggestion will be greatly appreciated! > > - Barry From mobiledreamers at gmail.com Mon Jan 14 01:49:39 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Sun, 13 Jan 2008 22:49:39 -0800 Subject: Recieving emails in python In-Reply-To: References: Message-ID: ok i dont want to write an mta i want to use another mta to recieve emails on say - python at mygrouplist.com so can i start reading the emails to python from that mta How to set this up to read messages from the mta sending out email we are using sendmail so we ll continue using that for now thanks It depends. If you're trying to write a MTA, think about looking at and stealing parts of mailmain and smtpd.py Mailman: http://www.gnu.org/software/mailman/index.html Smtpd:http://barry.warsaw.us/software/Code/smtpd.py If you're going to use someone else as a MTA then just use IMAP or POP to get the mail out, there are IMAP and POP libraries imap: http://docs.python.org/lib/module-imaplib.html pop: http://docs.python.org/lib/module-poplib.html Else, if you're writing this all from scratch, whip out the RFC and start hacking: http://info.internet.isi.edu/in-notes/rfc/files/rfc821.txt --Michael On 1/13/08, mobiledreamers at gmail.com wrote: > > I m trying to create something simple a mailing list similar to yahoo > groups > I m stumbling at the part where the python recieves messages via say > python at yahoogroups.com > > how to make python recieve emails and process it > after that it is straight forward processing in python inserting in db etc > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Sun Jan 6 22:55:44 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 Jan 2008 03:55:44 -0000 Subject: Should HTML entity translation accept "&"? References: <47817BDC.7020707@animats.com> <87tzlqo2a4.fsf@benfinney.id.au> Message-ID: On Mon, 07 Jan 2008 12:25:07 +1100, Ben Finney wrote: > John Nagle writes: > >> For our own purposes, I rewrote "htmldecode" to require a sequence >> ending in ";", which means some bogus HTML escapes won't be recognized, >> but correct HTML will be processed correctly. What's general opinion of >> this behavior? Too strict, or OK? > > I think it's fine. In the face of ambiguity (and deviation from the > published standards), refuse the temptation to guess. That's good advice for a library function. But... > More specifically, I don't see any reason to contort your code to > understand some non-entity sequence that would be flagged as invalid by > HTML validator tools. ... it is questionable advice for a program which is designed to make sense of invalid HTML. Like it or not, real-world applications sometimes have to work with bad data. I think we can all agree that the world would have been better off if the major browsers had followed your advice, but given that they do not, and thus leave open the opportunity for websites to exist with invalid HTML, John is left in the painful position of having to write code that has to make sense of invalid HTML. I think only John can really answer his own question. What are the consequences of false positives versus false negatives? If it raises an exception, can he shunt the code to another function and use some heuristics to make sense of it, or is it "game over, another site can't be analyzed"? -- Steven From sjmachin at lexicon.net Wed Jan 9 14:53:32 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 9 Jan 2008 11:53:32 -0800 (PST) Subject: printing dots in simple program while waiting References: Message-ID: On Jan 10, 6:30 am, John wrote: > On Jan 9, 12:14 pm, "Reedick, Andrew" wrote: > > > > > > -----Original Message----- > > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > > list-bounces+jr9445=att.... at python.org] On Behalf Of Martin Marcher > > > Sent: Wednesday, January 09, 2008 11:57 AM > > > To: python-l... at python.org > > > Subject: Re: printing dots in simple program while waiting > > > > John wrote: > > > > > import time > > > > s = '.' > > > > print 'working', # Note the "," at the end of the line > > > > while True: > > > > print s > > > > time.sleep(1) > > > > see my comment in the code above... > > > > if that's what you mean > > > Bah. The trailing command may prevent the newline, but it appends a > > space whether you want it or not.[1] Use sys.stdout.write('.') instead. > > > import sys > > > print "wussy nanny state, tax 'n spend my spaces, liberal comma:" > > for i in range(1, 10): > > print '.', > > print > > print "manly neo-con I know what's Right so keep your government out of > > my strings! print:" > > for i in range(1, 10): > > sys.stdout.write('.') > > > [1] Which has to be _the_ most annoying feature of Python. *grrr* > > > ***** > > > 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 > > Thanks for all of the help. This is what ended up working: > > import time > import sys > > s = '.' > sys.stdout.write( 'working' ) > while True: > sys.stdout.write( s ) > sys.stdout.flush() > time.sleep(0.5) For your next trick, write a "spinner" using |/-\ in succession :-) From leon at pasde.spam.fr Tue Jan 1 10:21:51 2008 From: leon at pasde.spam.fr (Leon) Date: Tue, 01 Jan 2008 16:21:51 +0100 Subject: TK 8.5 References: Message-ID: > We are planing to use Tcl/Tk 8.5 for Python 2.6 and 3.0. The topic is > currently being discussed but nothing has been decided yet. Great news! I hope you'll decide to use Tcl/Tk 8.5 ! I'm sure I'm not the only one !!! On this page : http://www.python.org/dev/peps/pep-0361/ We can read : "the initial 2.6 target is for April 2008" Great ! But I found nothing about Tk 8.5 ? Leon From joejacob21 at gmail.com Thu Jan 24 06:25:06 2008 From: joejacob21 at gmail.com (joe jacob) Date: Thu, 24 Jan 2008 03:25:06 -0800 (PST) Subject: Designing website Message-ID: <248758f0-6d8b-4e91-9c3c-a6a0314bebcb@q77g2000hsh.googlegroups.com> Hi All, I am planning to design a website using windows, apache, mysql, python. But I came to know that python cgi is very slow. I came across mod_python also but no good documentation are available for learning mod_python. Suggest me a good solution for this as I don't know other languages like PHP; I prefer python. From mitko at qlogic.com Fri Jan 11 18:54:16 2008 From: mitko at qlogic.com (Mitko Haralanov) Date: Fri, 11 Jan 2008 15:54:16 -0800 Subject: Import and execfile() In-Reply-To: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> References: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> Message-ID: <20080111155416.7a008755@opal.mv.qlogic.com> On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis wrote: > # trying to set the configuration: > CFG = {} > execfile('path/to/some_config.py', CFG) > > Traceback (most recent call last): > ... > ImportError: No module named master_config > > > I understand why this fails but I'm not sure how to tell execfile() to > set the path accordingly. Any ideas ? This might be overly simplistic but you could have a load_config function which takes the path to the config file and the variable where to load the config as arguments. In the load_config function, you could get the directory part of the config file path, appending it to sys.path, load the config, and then remove the newly added directory from sys.path. -- Mitko Haralanov From hinds.ja at gmail.com Wed Jan 2 16:01:23 2008 From: hinds.ja at gmail.com (hinds.ja at gmail.com) Date: Wed, 2 Jan 2008 13:01:23 -0800 (PST) Subject: Insert to a clob field using cx_Oracle via a stored procedure Message-ID: <87860f02-9c78-4248-8d30-c13c91a59f00@i29g2000prf.googlegroups.com> Hello, Does anyone have experience using cx_Oracle to call a stored procedure that inserts to a clob field? We have done this successfully via straight SQL, but we are at a loss on how to do the same insert using a stored procedure call. Any assistance would be much appreciated. Thanks. Jason From steve at REMOVE-THIS-cybersource.com.au Mon Jan 28 03:09:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 28 Jan 2008 08:09:45 -0000 Subject: Using a dict as if it were a module namespace References: <13podkpqqvef674@corp.supernews.com> Message-ID: <13pr3e9bqgt3t81@corp.supernews.com> On Sun, 27 Jan 2008 10:04:06 -0500, Ross Ridge wrote: > I think this is the way to go as it follows the principle of "say what > you mean." You can however simplify it, and repeat yourself less, by > using the extended call syntax: > > expr = "myfunc(**test)" > setup = """from __main__ import myfunc, test""" Ah, also good thinking! I'd have to modify it, because the tests carry other information which shouldn't be passed to the test function, but that's a simple modification. Thanks to all who replied. -- Steven From bronger at physik.rwth-aachen.de Mon Jan 28 06:54:12 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 28 Jan 2008 12:54:12 +0100 Subject: optional static typing for Python References: <479da584$0$25625$426a74cc@news.free.fr> <69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com> Message-ID: <87d4rm88t7.fsf@physik.rwth-aachen.de> Hall?chen! Russ P. writes: > On Jan 28, 1:51 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Russ P. a ?crit :> A while back I came across a tentative proposal from way > back in 2000 >> > for optional static typing in Python: >> >> (snip) >> >>> In any case, optional static typing in Python would help >>> tremendously here. The hardest part of automated conversion of >>> Python to a statically typed language is the problem of type >>> inference. If the types are explicitly declared, that problem >>> obviously goes away. >> >> (snip) >> >>> Note also that, while "static" type checking would be ideal, >>> "explicit" typing would be a major step in the right direction >> >> Lord have mercy(tm). > > What is that supposed to mean? So you haven't understood him. Then why is this rant following? Anyway, I can only speak for myself: I have the concern that any (albeit optional) declaring of types in Python leads to people thinking that their code is more valuable with such declarations. Mostly you know which type is to be expected after all. As a result, you see such declarations everywhere, whether helpful or not. Maybe eventually tools such as pylint will even give a percentage how many parameters are annotated, and people try to maximize this value. Ugh. Then, Python is not as useful anymore because readability falls drastically. Moreover, there is a Fortran saying: "One person's constant is another person's variable." The same applies to types in Python. Pythons is one way, Ada another way; there is no silver bullet. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From jitender001001 at gmail.com Thu Jan 17 23:12:00 2008 From: jitender001001 at gmail.com (jitender001001 at gmail.com) Date: Thu, 17 Jan 2008 20:12:00 -0800 (PST) Subject: plz help how to print python variable using os.system() References: <78444c3a-17dc-4912-aac7-39253648d86f@u10g2000prn.googlegroups.com> Message-ID: <0d32c730-9fa6-492f-ac92-af4f83f55331@e23g2000prf.googlegroups.com> Thanks Lutz....... From gagsl-py2 at yahoo.com.ar Wed Jan 23 17:06:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 20:06:51 -0200 Subject: get the size of a dynamically changing file fast ? References: <198fd91f-912b-4f56-a840-af96225125a7@c23g2000hsa.googlegroups.com> <197576d1-ab36-45f2-9648-3cfab6d3a814@j20g2000hsi.googlegroups.com> <4797849A.3040002@gmail.com> Message-ID: En Wed, 23 Jan 2008 16:16:58 -0200, Stef Mientki escribi?: >>> Yes, that's a small disadavantage of using a "high-level" language, >>> where there's no flush available, and you assume it'll done >>> automatically ;-) >> >> Uhm, there is a flush method for Python's files. From "http:// >> > I was talking about a "high-level" language, in which the sending > program was written, > (Delphi, not about Python ;-) In Delphi, flush(filevar) does work. Or are you using a TFileStream or similar? -- Gabriel Genellina From alex.holkner at gmail.com Thu Jan 17 08:42:20 2008 From: alex.holkner at gmail.com (Alex Holkner) Date: Fri, 18 Jan 2008 00:42:20 +1100 Subject: ANN: pyglet 1.0 Message-ID: The first stable/production version of pyglet has been released. http://www.pyglet.org --- pyglet provides an object-oriented programming interface for developing games and other visually-rich applications for Windows, Mac OS X and Linux. Some of the features of pyglet are: * No external dependencies or installation requirements. For most application and game requirements, pyglet needs nothing else besides Python, simplifying distribution and installation. * Take advantage of multiple windows and multi-monitor desktops. pyglet allows you to use as many windows as you need, and is fully aware of multi-monitor setups for use with fullscreen games. * Load images, sound, music and video in almost any format. pyglet can optionally use AVbin to play back audio formats such as MP3, OGG/Vorbis and WMA, and video formats such as DivX, MPEG-2, H.264, WMV and Xvid. pyglet is provided under the BSD open-source license, allowing you to use it for both commercial and other open-source projects with very little restriction. Cheers Alex. From deets at nospam.web.de Mon Jan 28 13:48:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jan 2008 19:48:04 +0100 Subject: post variable In-Reply-To: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> References: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> Message-ID: <606mbbF1p1kafU1@mid.uni-berlin.de> pavloutefkros at gmail.com schrieb: > sorry for creating a new post but this is totally different from the > previous one. > > Here is the problem (which is very hard to explain, so i will use a > paradigm): i submit a form and the post variable is being sent to the > page test.py. then the test.py retrieves the POST and print it to the > page. now everything is great except one thing. > > lets say i submitted the form and went to test.py and the output was > correct, then, while i'm on test.py if i reload the page, the POST > variable IS STILL THERE. > > so the output is always the POST retrieven at first. So the page keeps > on printing the POST variable retrieven at first even thought i might > have reloaded the page 1000 times. Is there any way to "empty" the > POST variable, so that at reload nothing would be the same? > > ps: so many "so" and wacky explanation, noone would understand :(. If you are reloading a page, the variables that were sent to it are re-send by the browser. I fail to see where the problem is. Reloading means reloading. Diez From spaceoutlet at gmail.com Sat Jan 26 05:26:37 2008 From: spaceoutlet at gmail.com (Alex K) Date: Sat, 26 Jan 2008 11:26:37 +0100 Subject: paging in python shell In-Reply-To: <857659.95304.qm@web32813.mail.mud.yahoo.com> References: <857659.95304.qm@web32813.mail.mud.yahoo.com> Message-ID: That seems interesting but it's not quite what I want to do. To take an example I would like to be able to do something similar to the mysql shell when its pager is set to less. Displayhook is called whenever an expression is being evaluated. I'd like to call 'less' on the ouput of a statement. Alex On 26/01/2008, gagsl-py2 at yahoo.com.ar wrote: > > --- Alex K escribi?: > > > Thank you for this interesting tip. However I'm not > > sure to know how > > to use it. It seems pydoc.pager('text') just pages > > the text passed in. > > How do I actually make the python shell use a > > different pager? > > I'm unsure of what you want. Do you want the print > statement, inside the Python interpreter, to page its > output? Write a function to page the output the way > you like, and assign it to sys.displayhook (see > http://docs.python.org/lib/module-sys.html#l2h-5124 ) > > -- > Gabriel Genellina > > > Tarjeta de cr?dito Yahoo! de Banco Supervielle. > Solicit? tu nueva Tarjeta de cr?dito. De tu PC directo a tu casa. www.tuprimeratarjeta.com.ar > -- > http://mail.python.org/mailman/listinfo/python-list > From namesagame-usenet at yahoo.com Wed Jan 2 22:12:47 2008 From: namesagame-usenet at yahoo.com (gamename) Date: Wed, 2 Jan 2008 19:12:47 -0800 (PST) Subject: Cloning Environments Message-ID: Hi, I have several machines running Linux (mostly fedora6) and Windows (mostly XP). I'm thinking of using easy_install to create as uniform an environment as possible for all of them. Cloning the environment, to put it another way. Is there a good example somewhere showing how to do this? I'm new to easy_install and relatively new to python. TIA, -T From inFocus at sl.com Tue Jan 22 20:45:22 2008 From: inFocus at sl.com (inFocus at sl.com) Date: Tue, 22 Jan 2008 20:45:22 -0500 Subject: Extract value from a attribute in a string Message-ID: Hello, I am looking for some help in reading a large text tile and extracting a value from an attribute? so I would need to find name=foo and extract just the value foo which can be at any location in the string. The attribute name will be in almost each line. Thank you for any suggestions. From doug.farrell at gmail.com Thu Jan 17 15:25:43 2008 From: doug.farrell at gmail.com (writeson) Date: Thu, 17 Jan 2008 12:25:43 -0800 (PST) Subject: handlers.SocketHandler and exceptions References: <02de2e9c-331d-45c0-afaa-578ddad55664@j78g2000hsd.googlegroups.com> Message-ID: On Jan 17, 2:45 pm, Vinay Sajip wrote: Vinay, Again, thanks for your very timely help! I was just editing the handlers.py code, and didn't really understand how that was going to work, and of course it didn't. I was just about to write to you again, and voila, you'd already responded with what I needed to know. I would have been floundering around for quite awhile before I'd have found (if ever) the change you mentioned to __init__.py. I made the changes and my logging server is working as I expected! Exceptions are being placed in the log file, complete with their tracebacks. Again, thanks very much for your help, greatly appreciated! Doug From paul at boddie.org.uk Fri Jan 18 17:54:05 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 18 Jan 2008 14:54:05 -0800 (PST) Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. References: <478FAC5A.50206@animats.com> <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> <479046a5$0$36403$742ec2ed@news.sonic.net> Message-ID: <3b14e57b-9461-4e1c-9bde-fdde99f87617@z17g2000hsg.googlegroups.com> On 18 Jan, 07:32, John Nagle wrote: > > "Processing" is useful, but it uses named pipes and sockets, > not ordinary pipes. Also, it has C code, so all the usual build > and version problems apply. The pprocess module uses pickles over sockets, mostly because the asynchronous aspects of the communication only appear to work reliably with sockets. See here for the code: http://www.python.org/pypi/pprocess Unlike your approach, pprocess employs the fork system call. In another project of mine - jailtools - I use some of the pprocess functionality with the subprocess module: http://www.python.org/pypi/jailtools I seem to recall that a few things are necessary when dealing with subprocesses, especially those which employ the python executable: running in unbuffered mode is one of those things. Paul From bignose+hates-spam at benfinney.id.au Wed Jan 16 03:11:53 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jan 2008 19:11:53 +1100 Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> <873asyclo0.fsf@benfinney.id.au> Message-ID: <87y7aqb35i.fsf@benfinney.id.au> Christian Heimes writes: > Ben Finney wrote: > > The term "reference" is fine, since that's exactly how it works. > > One gets at an object via some reference, be it a name or some > > access into a container object. When an object has no more > > references to itself, it becomes a candidate for garbage > > collection. And so on. > > Thanks you, but I know exactly how Python works. I'm actually > developing CPython and PythonDotNET. Uh, okay. I didn't ask for you to flash your credentials, but if that is significant to you, be my guest. > Anyway your message doesn't help a newbie and it gives most > certainly the wrong impression. You are using words that have a > different meaning in other languages. If you explain Python w/o the > words variable, pointer, reference or call-by-value you have a much > better chance to explain it right. Trust me :) I've done my share of explaining of Python to people, and found "reference" to be exactly the right term to help the newbie understand what's happening and what they should expect. I agree with you on "variable", "pointer", and "call-by-value". Those don't describe how Python works, and thus only confuse the matter. Thus I avoid them, and correct newbies who appear to be getting confused because of those existing concepts. -- \ "I don't accept the currently fashionable assertion that any | `\ view is automatically as worthy of respect as any equal and | _o__) opposite view." -- Douglas Adams | Ben Finney From asmodai at in-nomine.org Sat Jan 12 06:37:59 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 12 Jan 2008 12:37:59 +0100 Subject: where do my python files go in linux? In-Reply-To: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> Message-ID: <20080112113759.GJ75977@nexus.in-nomine.org> -On [20080112 12:03], Jorgen Bodde (jorgen.maillist at gmail.com) wrote: >app.py calls a lot of modules in {dir}/app. Horst says the python file >goes in /usr/bin/app.py which is ok with me, but I have multiple >python files, and I decided to use an app.sh script to call my python >files. In the /usr/bin I do not see subdirs so I assume that is not >really desirable. Personally I'd be loathe to put app.py in /usr/bin. This directory is normally reserved for OS-specific binaries. For personal/system-extended stuff I'd use /usr/local/bin or whatever your system mandates. (But hey, that's the typical mentality difference between the BSD and Linux world it seems, so do with it what you want.) >Question 2. Should I use *.pyc rather then *.py files to speed up >executing as the user cannot write to /usr/bin or any other dir in the >system and everytime my app runs it will recompile it .pyc will help execution time so it might be nice to have those in place. Normally you'd split up the bulk of the code into a module which gets installed into site-packages and a piece of stand-alone front-end code which imports the module and executes whatever you need to do and gets installed into a typical PATH directory. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ ...fools rush in where Angels fear to tread. From lists at cheimes.de Wed Jan 23 14:44:26 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 23 Jan 2008 20:44:26 +0100 Subject: When is min(a, b) != min(b, a)? In-Reply-To: <13p9hdmh7c08abe@corp.supernews.com> References: <13p9hdmh7c08abe@corp.supernews.com> Message-ID: Grant Edwards wrote: > In many applications (e.g. process control) propogating NaN > values are way too useful to avoid. Avoiding NaN would make a > lot of code far more complicated than would using them. NaNs are very useful for experienced power users but they are very confusing for newbies or developers without a numerical background. It's very easy to create an inf or nan in Python: inf = 1E+5000 ninf = -inf nan = inf * 0. 1E5000 creates a nan because it is *much* bigger than DBL_MAX (around 1E+308). In fact it is even larger than LDBL_MAX (around 1E+4932). Christian From martin at v.loewis.de Thu Jan 17 15:26:59 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 Jan 2008 21:26:59 +0100 Subject: -fno-strict-aliasing turned off when cross compiling In-Reply-To: <8d3d3114-0e23-4506-be43-e980613a0e93@q39g2000hsf.googlegroups.com> References: <66c2d5b4-c84f-47d9-aa4a-1cca3ae594b2@q39g2000hsf.googlegroups.com> <478ee01b$0$4589$9b622d9e@news.freenet.de> <8d3d3114-0e23-4506-be43-e980613a0e93@q39g2000hsf.googlegroups.com> Message-ID: <478FBA13.20806@v.loewis.de> > This makes some sense. Thank you. As for this: > > def detect_modules(self): > # Ensure that /usr/local is always used > add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') > add_dir_to_list(self.compiler.include_dirs, '/usr/local/ > include') > > it looks like a recipe for a disaster when cross compiling: > cc1: warning: include location "/usr/local/include" is unsafe for > cross-compilation Yes, Python doesn't really support cross-compilation. So you are on your own. Of course, in true cross-compilation, you won't get a chance to run setup.py, since python will only run on the target system, not on the host system, therefore setup.py won't even start, and it doesn't matter that it won't support cross-compilation. Regards, Martin From kyosohma at gmail.com Wed Jan 30 13:33:41 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 30 Jan 2008 10:33:41 -0800 (PST) Subject: event handling References: Message-ID: <3fb69345-56e7-43e7-927b-82c7312e86f5@n20g2000hsh.googlegroups.com> On Jan 30, 11:16 am, Peter Nemeth wrote: > Hi , > > I am working on a stellar spectral analysis pipeline in Python. My OS is > Suse 10.0, and i use Python 2.5 . I have found difficulties with keyboard > event handling. My code communicates with the user through an xterm window > and shows graphs in a Gnuplot window. At a certain point i start an > infinite loop in order to select multiple spectral regions by mouse-clicks > over the Gnuplot graph. I would like to terminate this loop by a single > keystroke, but i can not get it done. I use 'thread' to run this process > in the background waiting for a keystroke. I don't want to use tkinter, > widgets or pygame because those require a popup surface to work in and i > already have the gnuplot window. > > I tried a C like getch() function, but that pauses the code waiting for > key press instead of scanning the event queue. > > Is there any other means for general event handling in Python? > > Any help would be greatly appreciated. > > Sincerely, > Peter I would use wxPython, but since you seem against that, here's what I found using Google-fu: http://www.freenetpages.co.uk/hp/alan.gauld/tutevent.htm It sounds very similar to what you are doing and it shows how to do it in both Windows and Linux. Threads are annoying buggers. You'll probably want to have one thread catching key-presses and storing them in a file or "file-like" object and have your other thread read from it periodically. I'm not sure that the link above mentions that. Hope that helps! Mike From antroy at gmail.com Fri Jan 4 03:50:25 2008 From: antroy at gmail.com (Ant) Date: Fri, 4 Jan 2008 00:50:25 -0800 (PST) Subject: Jython: Honourable mention on Charles Nutter's blog. Message-ID: <284737ca-7626-4f65-a780-638377d3b3d6@e25g2000prg.googlegroups.com> Hi all, The Jython team got an honourable mention on the Headius blog this morning. Apparently they have got Django working with the latest builds of Jython: http://headius.blogspot.com/2008/01/jythons-back-baby.html So congratulations! -- Ant. From paddy3118 at googlemail.com Wed Jan 9 16:40:44 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 13:40:44 -0800 (PST) Subject: alternating string replace: Extended input (Long). References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <3dc4aed2-ae92-418f-b86d-2b7f0d2abd73@y5g2000hsf.googlegroups.com> On Jan 9, 9:29 pm, Paddy wrote: > On Jan 9, 8:56 pm, Fredrik Lundh wrote: > > > Donald 'Paddy' McCarthy wrote: > > > I created some more test strings and ran posters solutions against them. > > > the point being? > > > > > To see how they act against 'corner cases' and > an exercise for me in trying to create corner cases. (I'm in to > functional testing at the mo'). > > - Paddy. ... Then there is seeing how multiple interpretations of a real world (i.e. limited), spec. act on an extended dataset. The limited spec comes up all the time in the design and verification of digital circuits. Then again, I was also waiting on someone and it passed the time amiably :-) - Paddy. From aaron.watters at gmail.com Tue Jan 1 19:19:30 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 1 Jan 2008 16:19:30 -0800 (PST) Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> Message-ID: <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> On Jan 1, 5:05 pm, Steven D'Aprano wrote: > On Tue, 01 Jan 2008 13:55:10 -0800, PatrickMinnesota wrote: > > The idea is that your data and applications are on the net, rather than > > your local hard drive. > > Or, to put it another way, your data and applications are controlled by > another company rather than you. > > Not that I wish to be cynical or anything like that. > > -- > Steven I see. So cloud computing is java dickless^H^H^H^H^H^Hskless workstations warmed over but less flexible? I'm having trouble understanding why people would want to buy in to this. For example at the amazon site I see things like "it might take a couple minutes to load your image..." Are they joking? hmmm. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=try+not+to+allocate+too+many+objects+okay From sjmachin at lexicon.net Sun Jan 13 04:54:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 13 Jan 2008 01:54:33 -0800 (PST) Subject: Elementary string-formatting References: Message-ID: <7d17fa05-67c5-4acb-91b6-c53fdf70ae27@q77g2000hsh.googlegroups.com> On Jan 13, 8:43 pm, Odysseus wrote: > In article > , > Roberto Bonvallet wrote: > > > Put this at the beginning of your program: > > > from __future__ import division > > > This forces all divisions to yield floating points values: > > Thanks for the tip. May I assume the div operator will still behave as > usual? div operator? The integer division operator is // >>> from __future__ import division >>> 1 / 3 0.33333333333333331 >>> 1 // 3 0 >>> 22 / 7 3.1428571428571428 >>> 22 // 7 3 >>> 22 div 7 File "", line 1 22 div 7 ^ SyntaxError: invalid syntax >>> From spaceoutlet at gmail.com Mon Jan 7 09:46:32 2008 From: spaceoutlet at gmail.com (Alex K) Date: Mon, 7 Jan 2008 15:46:32 +0100 Subject: introspection question In-Reply-To: References: Message-ID: Nice thank you. But anyway to make it look pretty? On 07/01/2008, Peter Otten <__peter__ at web.de> wrote: > Alex K wrote: > > > What would be the simplest way of enumerating all methods and members > > (including inherited) of a given object? Thank you. > > inspect.getmembers() > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From jzgoda at o2.usun.pl Sat Jan 5 06:41:54 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sat, 05 Jan 2008 12:41:54 +0100 Subject: Question on os.tempnam() vulnerability In-Reply-To: <13nt81gftkfa32d@corp.supernews.com> References: <13nt81gftkfa32d@corp.supernews.com> Message-ID: Grant Edwards pisze: >> you get a name instead of a file, so someone else can create that file >> after you've called tempnam/tmpnam, but before you've actually gotten >> around to create the file yourself. which means that anyone on the >> machine might be able to mess with your application's data. >> >> use the functions marked as "safe" in the tempfile module instead. > > Under Windows, is there a "safe" way to create a temp file that > has a name that can be passed to a program which will then open > it? I never figured out a way to do that and had to fall back > on the "unsafe" tmpnam method. I think it's all impossible to get only file name and feel safe. You have to have both file name and a file object opened exclusively for you. Any other way you'll get a possible race condition. -- Jarek Zgoda http://zgodowie.org/ From george.sakkis at gmail.com Mon Jan 14 14:37:15 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 14 Jan 2008 11:37:15 -0800 (PST) Subject: SyntaxError: 'import *' not allowed with 'from .' Message-ID: <9ac37212-7521-454d-a35f-afd6f7ec24f6@m34g2000hsf.googlegroups.com> Unless I missed it, PEP 328 doesn't mention anything about this. What's the reason for not allowing "from .relative.module import *' ? George From bruno.desthuilliers at gmail.com Tue Jan 15 14:14:31 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 15 Jan 2008 11:14:31 -0800 (PST) Subject: Benchmark [was Re: common problem - elegant solution sought] References: <5v3gg1F1kkla5U1@mid.dfncis.de> <478ccc9e$0$29264$ba620e4c@news.skynet.be> <7xbq7ngdge.fsf@ruckus.brouhaha.com> Message-ID: <2007a710-3a9c-40f2-aab2-24d60432454c@e23g2000prf.googlegroups.com> On Jan 15, 6:18 pm, Paul Rubin wrote: > Helmut Jarausch writes: > > def del_by_key(L,key) : > > for pos, (k,d) in enumerate(L): > > if k == key : > > del L[pos] > > break > > This looks very dangerous, mutating L while iterating over it. This would indeed be dangerous *without* the break statement !-) From papilonv at gmail.com Mon Jan 21 04:38:15 2008 From: papilonv at gmail.com (Vikas Jadhav) Date: Mon, 21 Jan 2008 15:08:15 +0530 Subject: Fwd: Help! - Invoke setup.py file In-Reply-To: <7856b4e60801190232j3b1a18b5n3630ddf77aed9ee0@mail.gmail.com> References: <7856b4e60801190232j3b1a18b5n3630ddf77aed9ee0@mail.gmail.com> Message-ID: <7856b4e60801210138w5e71a977w473db4bea0cba43c@mail.gmail.com> Hi, Please look into the query mentioned in below email. Cheers, Vikas ---------- Forwarded message ---------- From: Vikas Jadhav Date: Jan 19, 2008 4:02 PM Subject: Help! - Invoke setup.py file To: python-list at python.org Hi, We have setup of SVGMath* 0.3.2 (Converter- Mathml 2.0 coding to SVG). The setup folder contains setup.py file but we are not able to initiate this file. Kindly help us, resolution to this query will be appreciated. Python version: Installed on PC- 2.5.1 and OS- Windows 2000. * *SVGMath* is a *command*-line utility to convert MathML expressions to SVG, written entirely in Python. Note: Attached file contains SVGMath installation components. Cheers, Vikas -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: SVGMath-0.3.2.zip Type: application/zip Size: 77473 bytes Desc: not available URL: From terry at jon.es Thu Jan 17 21:45:23 2008 From: terry at jon.es (Terry Jones) Date: Fri, 18 Jan 2008 03:45:23 +0100 Subject: Some Berkeley DB questions (being maintained? queries?) In-Reply-To: Your message at 04:29:05 on Thursday, 17 January 2008 References: <0ba30836-8e2d-4061-94ea-ccddb24bc290@s19g2000prg.googlegroups.com> <003601c85904$904150c0$0401a8c0@T60> Message-ID: <18320.4803.331705.315917@terry.local> >>>>> "Brian" == Brian Smith writes: Brian> HerbAsher at googlemail.com wrote: >> 2. Are there good python libraries for bdb available, that >> are being maintained? Brian> I would like to know the answer to this question too--if you have Brian> used the pybsddb/bsddb.db module, please share your experience. I used it a little in mid-2006. I ran into one issue that I resolved by looking at the C source and fiddling with the Python interface. I sent mail to the people mentioned in the bsddb README file. One (Barry Warsaw) answered to say he hadn't looked at the code in a couple of years and was probably not the person to contact. >> 4. What are good, stable alternatives? >From memory, the Chandler project also has an interface to BSD DB, but I don't remember any details at all. I'm also interested in any ongoing or planned work on the Python interface. Terry From paddy3118 at googlemail.com Mon Jan 7 22:16:10 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 7 Jan 2008 19:16:10 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> Message-ID: <325e6baa-db24-4636-83e2-f66b2c7c00a5@e10g2000prf.googlegroups.com> On Jan 7, 10:55 am, monkeyda... at mailinator.com wrote: > Seehttp://www.tiobe.com/index.htm?tiobe_index. > > Marc ohloh "Monthly Commits by Language" also shows Python open-source work being healthy: http://tinyurl.com/2wcadu If you remove C/C++ the other languages can be more easily compared. (C/C++ I see as the bedrock language of open-source): http://tinyurl.com/2u76d9 - Paddy. From aekidens at yahoo.es Fri Jan 11 16:31:05 2008 From: aekidens at yahoo.es (Gabriel) Date: Fri, 11 Jan 2008 22:31:05 +0100 Subject: Graphics Module Message-ID: Hi all ! I'm developing a math program that shows graphics of functions. I would hear suggestions about the way of drawing 2D . Thanks a lot for your answers. - Gabriel - From Matthew_WARREN at bnpparibas.com Mon Jan 28 10:10:54 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Mon, 28 Jan 2008 15:10:54 +0000 Subject: validate string is valid maths Message-ID: Hi pythoners. I am generating strings of length n, randomly from the symbols +-/*0123456789 What would be the 'sensible' way of transforming the string, for example changing '3++++++8' into 3+8 or '3++--*-9' into '3+-9' such that eval(string) will always return a number? in cases where multiple symbols conflict in meaning (as '3++--*-9' the earliest valid symbols in the sequence should be preserved so for example, '3++*/-9' = 3+-9 '45--/**/+7' = 45-+7 '55/-**+-6**' = 55/-6 ...that is, unless there is a canonical method for doing this that does something else instead.. this sounds like homework. It's not. I like making problems up and it's a slow work day. So, as an aside, there is no real reason I want to do this, nor other problem to solve, nor other background to what I'm trying to achieve ;) other than twiddling with python. 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 mail at timgolden.me.uk Mon Jan 28 05:36:42 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 28 Jan 2008 10:36:42 +0000 Subject: starting programs from python script on windows In-Reply-To: References: Message-ID: <479DB03A.9060801@timgolden.me.uk> Benedict Verheyen wrote: > i want to automate starting programs on my windows machine and i want > to do it with windows. > This is a sample script: > > from subprocess import Popen, PIPE > import time > > print " Starting app 1" > time.sleep(1) > try: > p1 = Popen(["C:\Program Files\Microsoft > Office\OFFICE11\OUTLOOK.EXE"], stdout=PIPE) > except Exception, e: > print "Error on startup app 1 %s " % str(e) > > print " Starting app 2" > time.sleep(1) > > try: > p2 = Popen(["C:\Windows\system32\cmd.exe"], stdout=PIPE) > except Exception, e: > print "Error on startup app 2 %s " % str(e) > > It start it from a batch file: > SET PYTHONPATH=C:\Python25 > > rem - path to script to execute > %PYTHONPATH%\python.exe C:\login.py > > This is the result: > > C:\>C:\Python25\python.exe C:\login.py > Starting app 1 > Starting app 2 > Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. > Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. > Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. > > 1. I get an error message saying the process has tried to write to a non > existing pipe. > > 2. Order of execution isn't respected: it prints the 2 messages and then > it tries to start the programs. Outlook is started but the command > prompt not. > > Anyway, if it works, i would like to start using python to drive the > startup scripts of the users on the system. > > How can i use python to start several programs as i would otherwise do > manually and keep the order i want? [Takes a big, deep breath] OK. You've got a few misunderstandings in there. Nothing too major, but it's worth sorting them out. 1) If you just want to kick off a program and that's it, say as part of some kind of startup process, then you can just use the subprocess.call convenience function. The business with stdout=PIPE is for communicating with (usually console-based) programs which read and write to the console. 2) The optional PYTHONPATH env var is used *internally* to Python as one way of determining the path to search for Python modules *after you've got Python running*. To run Python itself, you either need to ensure the python.exe is already in the standard PATH env var, or look for it in its conventional place: c:\python25\python.exe. (Or make some other arrangement according to local convention etc.) There was a thread here recently about using Python as part of a login script -- which is what I think you're doing here. I think, because of the uncertain interaction between the Workstation in effect when you're logging in as opposed to the Workstation which owns the user's desktop, you might do better to have some technique for adding to the [Startup] entry on the Start Menu if all you want to do is to start programs. All that said, here's some sample code which just kicks off a batch of programs. Note that I'm use os.startfile because that will use ShellExecute which honours app path shortcuts, making common things like MS Office apps much easier. You could equivalently use subprocess.call but then you either have to hardcode application paths or use FindExectable against an arbitrary associated doc to find the right place. import os programs = [ "outlook.exe", "cmd.exe", "winword.exe", "c:/temp/helpfile.pdf" ] for program in programs: os.startfile (program) The last entry -- helpfile.pdf -- is to illustrate that os.startfile can "start" documents as well as executable programs. TJG From steven at REMOVE.THIS.cybersource.com.au Thu Jan 10 04:03:46 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 10 Jan 2008 09:03:46 -0000 Subject: How to get memory size/usage of python object References: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> <257fa40e-5a6d-4e1d-aefd-9439a182391c@f47g2000hsd.googlegroups.com> Message-ID: On Thu, 10 Jan 2008 00:14:42 -0800, Santiago Romero wrote: >> Would you care to precisely define "REAL size" first? Consider: >> >> >>> atuple = (1, 2) >> >>> mylist = [(0, 0), atuple] >> >> Should sizeof(mylist) include sizeof(atuple) ? > > No, I'm talking about "simple" lists, without REFERENCES to another > objects into it. > > I mean: > > lists = [ 0, 1, 2, 3, 4, (1,2), 3] That list has 7 references to other objects. One of those objects has 2 references to objects. In total, depending on implementation, there could be as many as 9 objects referenced by that list, or as few as 6 objects (both references to 3 could be to the same object). In the current CPython implementation, that list will have 7 references to 6 objects. Including indirect references, there will be 9 references to 6 objects. (Or so I understand.) > or > > array = [ [0,0,0,0,0,0,0], [1,1,1,1,2,1,2], ... ] Ignoring the '...', there will be a total of 16 references to 5 objects in the current CPython implementation. Other Pythons (Jython, IronPython, PyPy, ...) may be different. > Maybe I can "pickle" the object to disk and see the filesize ... :-? That would measure something very different. Possibly you want something like this heuristic: def sizeof(obj): """APPROXIMATE memory taken by some Python objects in the current 32-bit CPython implementation. Excludes the space used by items in containers; does not take into account overhead of memory allocation from the operating system, or over-allocation by lists and dicts. """ T = type(obj) if T is int: kind = "fixed" container = False size = 4 elif T is list or T is tuple: kind = "variable" container = True size = 4*len(obj) elif T is dict: kind = "variable" container = True size = 144 if len(obj) > 8: size += 12*(len(obj)-8) elif T is str: kind = "variable" container = False size = len(obj) + 1 else: raise TypeError("don't know about this kind of object") if kind == "fixed": overhead = 8 else: # "variable" overhead = 12 if container: garbage_collector = 8 else: garbage_collector = 0 malloc = 8 # in most cases size = size + overhead + garbage_collector + malloc # Round to nearest multiple of 8 bytes x = size % 8 if x != 0: size += 8-x size = (size + 8) return size See: http://mail.python.org/pipermail/python-list/2002-March/135223.html to get you started. -- Steven. From attn.steven.kuo at gmail.com Thu Jan 31 18:24:15 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 31 Jan 2008 15:24:15 -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> <7xzlula8z4.fsf@ruckus.brouhaha.com> Message-ID: On Jan 31, 3:09 pm, Paul Rubin wrote: > "attn.steven.... at gmail.com" writes: > > mysets = [set(range(x[2],x[1])) for x in mylist] > > This is pretty horrible, each set can be arbitrarily large, > i.e. if x[2] and x[1] are 0 and 1000000, you get a set with > a million elements. True... Any lighter-weight implementation of sets out there? That is, one that would defer use of resources until actually needed -- somewhat akin to the distinction between range and xrange, and so on. xset? -- Regards, Steven From asmodai at in-nomine.org Tue Jan 8 03:18:18 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 09:18:18 +0100 Subject: web service between python and c# In-Reply-To: <12f6e713-392e-4fda-8354-51a8337d77dc@l6g2000prm.googlegroups.com> References: <12f6e713-392e-4fda-8354-51a8337d77dc@l6g2000prm.googlegroups.com> Message-ID: <20080108081818.GC75977@nexus.in-nomine.org> -On [20080108 07:24], abhishek (guptaabhishek1983 at gmail.com) wrote: >but have no idea on how to interface it with c# client. Totally depends on what exactly you need to accomplish. Some solutions can just use SOAP or REST. Others need full-fledged XML-RPC or other similar solutions. Some just use a serialization format like JSON. So what exactly are you trying to do? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ And every word upon your spiralling cross is but a misled sun, a bitter loss... From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Jan 12 04:22:43 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 12 Jan 2008 10:22:43 +0100 Subject: [Kamaelia] TCPClient: How to sense connection failure? References: <5uq49vF1jkgcoU1@mid.individual.net> Message-ID: <5urf73F1j3iqgU1@mid.individual.net> Hendrik van Rooyen wrote: > Not sure about Kamelia, but I have found that when a FIN comes > along, a socket.recv() gives back an empty string, just like EOF > on a file. That Python socket interface can detect it I'm absolutely sure -- Twisted handles it. I even pdb'ed Kamaelia and control flow ended at a different point in case of connection closing -- but yielded control to the scheduler immediately and never continued. > Below is what I use - a sort of netstring, synced on a tilde, with > human readable length implementation and escaping of tildes and > the escape character. Thank you (though I hope I won't have to mess with socket functions ;) ). > I hope the tabs survive the journey Looks like they morphed to spaces. Regards, Bj?rn -- BOFH excuse #77: Typo in the code From PatrickMinnesota at gmail.com Tue Jan 1 17:04:10 2008 From: PatrickMinnesota at gmail.com (PatrickMinnesota) Date: Tue, 1 Jan 2008 14:04:10 -0800 (PST) Subject: cloud computing (and python)? References: Message-ID: <2d4cea90-a09a-422d-ac26-cce8bbbc9a60@x69g2000hsx.googlegroups.com> On Jan 1, 3:26 pm, Aaron Watters wrote: > So, in between skiing runs I noticed > a Business Week cover story on > "cloud computing". The article had > lots of interesting information in it like > about how somebody's mom used to > be an airline stewardess and the > interior decor of various office spaces. > It was a truly excellent piece of > journalism. > > However it gave me no idea what > "cloud computing" is and how it > could be used to solve a computational > problem. > > Could anyone on this list > which usually has highly informed > readers give me a clue at some > level of technical detail what cloud > computing is about and how it could > be used. Bonus points if you mention > Python in the response! > > An actual example would be great, > if it's not web scraping and searching. > > - Aaron Watters > > ==http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=snow Oh, and I forgot to mention Python for points. Python combined with a framework like Django is used with Amazon's cloud services in various applications. www.Pownce.com is an example. From gherron at islandtraining.com Sat Jan 12 23:32:57 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 12 Jan 2008 20:32:57 -0800 Subject: Elementary string-formatting In-Reply-To: References: Message-ID: <47899479.7010404@islandtraining.com> Odysseus wrote: > Hello, group: I've just begun some introductory tutorials in Python. > Taking off from the "word play" exercise at > > > > I've written a mini-program to tabulate the number of characters in each > word in a file. Once the data have been collected in a list, the output > is produced by a while loop that steps through it by incrementing an > index "i", saying > > print '%2u %6u %4.2f' % \ > (i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0]) > Using 4.2 is the problem. The first digit (your 4) give the total number of characters to use for the number. Your numbers require at least 5 characters, two digits, one decimal point, and two more digits. So try 5.2, or 6.2 or 7.2 or higher if your numbers can grow into the hundreds or thousands or higher. If you want to try one of the floating point formats, then your first number must be large enough to account for digits (before and after) the decimal point, the 'E', and any digits in the exponent, as well as signs for both the number and the exponent. Gary Herron > My problem is with the last entry in each line, which isn't getting > padded: > > 1 0 0.00 > 2 85 0.07 > 3 908 0.80 > 4 3686 3.24 > 5 8258 7.26 > 6 14374 12.63 > 7 21727 19.09 > 8 26447 23.24 > 9 16658 14.64 > 10 9199 8.08 > 11 5296 4.65 > 12 3166 2.78 > 13 1960 1.72 > 14 1023 0.90 > 15 557 0.49 > 16 261 0.23 > 17 132 0.12 > 18 48 0.04 > 19 16 0.01 > 20 5 0.00 > 21 3 0.00 > > I've tried varying the number before the decimal in the formatting > string; "F", "g", and "G" conversions instead of "f"; and a couple of > other permutations (including replacing the arithmetical expression in > the tuple with a variable, defined on the previous line), but I can't > seem to get the decimal points to line up. I'm sure I'm missing > something obvious, but I'd appreciate a tip -- thanks in advance! > > FWIW I'm running > > Python 2.3.5 (#1, Oct 5 2005, 11:07:27) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin > > from the Terminal on Mac OS X v10.4.11. > > P.S. Is there a preferable technique for forcing floating-point division > of two integers to that used above, multiplying by "100.0" first? What > about if I just wanted a ratio: is "float(n / m)" better than "1.0 * n / > m"? > > From lasses_weil at klapptsowieso.net Mon Jan 14 09:37:20 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 14 Jan 2008 15:37:20 +0100 Subject: __init__ explanation please In-Reply-To: References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> Message-ID: <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> Jeroen Ruigrok van der Werven wrote: > To restate it more correctly: __init__ is akin to a constructor. > No. See Hrvoje Niksic's reply (and Ben Finney's to which it was a reply). __init__() /initializes/ an instance (automatically after creation). It is called, /after/ the instance has been constructed via the __new__() method. __new__() actually /constructs/ a new instance. > I am not entirely sure I fully understand __new__'s semantics though. Create a new (blank) instance of a class and return it. That's all there is to it. > I must not be understanding something and __new__'s documentation there is not > that clear to me, to be honest. > It is somewhat confusing at first. But just bear in mind: 99 out of 100 times, you don't need to override __new__(). When you need it, you'll know. /W From bignose+hates-spam at benfinney.id.au Tue Jan 1 19:53:37 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 02 Jan 2008 11:53:37 +1100 Subject: Catching external program exceptions References: <25qdnZuc2dn0WOfanZ2dnUVZ_gWdnZ2d@wideopenwest.com> Message-ID: <87ejd1avzi.fsf@benfinney.id.au> Marty writes: > I need to catch exceptions thrown by programs started by the os.system > function, as indicated by a non-zero return code (e.g. the mount > utility). That's not an exception. It's referred to as an "exit status" or (often) some short form or variation of that term. Python can make available the exit status value of an external process, but isn't going to interpret them to the point of raising exceptions that you can catch. The exit status is always available to the parent process, but the *meaning* of any given value of that status is highly dependent on the program that was running. If you want to respond to particular values, you'll have to do so by explicitly testing the exit status against values to which you've assigned meaning -- hopefully meanings documented in the manual page for the program which generates the exit status. > For example, if I get the following results in a bash > shell: > > $mount test > mount: can't find /home/marty/test in /etc/fstab or /etc/mtab > > then I want to catch the same exception What's happening isn't an exception. It's a message being emitted to an output stream (likely the stderr stream of the mount process, though some programs will put error messages on stdout), followed by an exit of that process. The parent of that process will receive an exit status from the process when it terminates; it will also (on Unix-like systems) receive a separate value indicating the OS signal that caused the process to exit. Python's 'os.system' function makes both these values available as the return value of the function. > from the corresponding os.system() call, i.e. "os.system('mount > test')", but it doesn't work as expected: > > > >>> import os, sys > >>> try: os.system('mount test') > ... except: print 'error' > ... > mount: can't find /home/marty/test in /etc/fstab or /etc/mtab > 256 > >>> The statement within the 'try' block executes the 'os.system()' call; since you're running inside the interpreter, the return value from that function is displayed. The return value, as documented in the 'os.system' documentation, encodes both the signal number (the low 8 bits, in this case (256 & 0x0F) == 0) and, since the signal number is zero ("no signal received") the exit status value (the high 8 bits, in this case (256 >> 8) == 1). No exception is being raised, so the 'try' block completes successfully and the 'except' block is not invoked. So, instead of testing for an exception, you should instead be testing the exit status code returned by the 'os.system' call. First, read the documentation for the command you're running:: $ man mount [...] Unfortunately the 'mount(8)' manual page doesn't (on my system) mention possible values for the exit status. So, you'll just have to deduce it, or go with the common convention of "zero status == success, non-zero status == error". MountFailedError = OSError import os return_value = os.system('mount test') signal_number = (return_value & 0x0F) if not signal_number: exit_status = (return_value >> 8) if exit_status: raise MountFailedError("Oh no!") Why isn't this standardised? Because the process-call interface is inconsistent between operating systems, and there's even less consistency in the implementations of the programs that return these values. The Zen of Python says: "In the face of ambiguity, refuse the temptation to guess." Thus, Python can do little more than present the values it received from the process call; anything further would be guessing. -- \ "I bought some batteries, but they weren't included; so I had | `\ to buy them again." -- Steven Wright | _o__) | Ben Finney From deets at nospam.web.de Fri Jan 11 13:36:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jan 2008 19:36:19 +0100 Subject: Converting a bidimensional list in a bidimensional array In-Reply-To: <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> <005679e9-c355-4e0a-872c-e0dae3181fd0@x69g2000hsx.googlegroups.com> <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> Message-ID: <5upr93F1j6u7aU1@mid.uni-berlin.de> Santiago Romero schrieb: >>> - Speed Performance: Do you think that changing from list to Array() >>> would improve speed? I'm going to do lots of tilemap[y][x] checks (I >>> mean, player jumping around the screen, checking if it's falling over >>> a non-zero tile, and so). > >> First of all: if you have enough memory to use a python list, then I >> suggest you to use a list. >> >> Often python lists are faster than array.array (maybe because python >> lists actually contain pyobjects). > > > My problem is that, in my game, each screen is 30x20, and I have > about 100 screens, so my tilemap contains 32*20*100 = 60000 python > objects (integers). > > If each integer-python-object takes 16 bytes, this makes 60000 * 16 = > almost 1MB of memory just for the tilemaps... > > Using array of type H (16 bits per item = 2 bytes), my maps take just > 60000*2 = 120KB of memory. > > After that, I just will access tilemap data for reading (i.e. value > = tilemap.GetTile(x,y)) ... > > Do you think I should still go with lists instead of an H-type array? With these requirements, there is no need to jump through hoops to try and save memeroy. You even can load levels from disk while the player moves through the world. Seriously - even a decade old machine would have had enough ram for this. And nowadays .5GB to 2GB are the minimum. Don't waste time you could spend designing a nice game on saving memory.... Diez From deets at nospam.web.de Mon Jan 7 08:12:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 Jan 2008 14:12:24 +0100 Subject: TIOBE declares Python as programming language of 2007! In-Reply-To: <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Message-ID: <5uempsF1gt5cbU1@mid.uni-berlin.de> Berco Beute schrieb: > Cool! We knew it would happen one day :) > What could be the reason? Python 3? Jython 2.2? Java's loss of > sexiness? I'd say Java was never sexy, but dressed up in expensive lingerie by marketing maniacs... Diez From jpeng at block.duxieweb.com Tue Jan 22 04:25:52 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Tue, 22 Jan 2008 17:25:52 +0800 Subject: what's this instance? In-Reply-To: <4795b32d$0$16941$426a74cc@news.free.fr> References: <4795b32d$0$16941$426a74cc@news.free.fr> Message-ID: <4795B6A0.9010809@block.duxieweb.com> Bruno Desthuilliers ??: > J. Peng a ?crit : >> def safe_float(object): >> try: >> retval = float(object) >> except (ValueError, TypeError), oops: >> retval = str(oops) >> return retval > >> The code above works well. > > For which definition of "works well" ? > I got it from Core Python Programming book I bought.You may ask it to Westley Chun.:) From kay.schluehr at gmx.net Tue Jan 29 16:33:08 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 29 Jan 2008 13:33:08 -0800 (PST) Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> <479e0225$0$36389$742ec2ed@news.sonic.net> Message-ID: <70c4064a-a65d-4fd5-b39c-38e6a3fb567b@i7g2000prf.googlegroups.com> On 29 Jan., 17:00, "Chris Mellon" wrote: > Given the difficulty of statically analyzing Python, and the > limitations you need to add for either static typing or type inference > to be practical, I think that the real future for faster Python code > is JIT, not static optimizations. Python has a JIT right now - so why do you think it's Pythons "real future"? From detlev at die-offenbachs.de Sat Jan 12 08:34:35 2008 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 12 Jan 2008 14:34:35 +0100 Subject: eric4 request for contribution Message-ID: Hi, I am in the progress of writing a refactoring plugin for eric4 using the rope refactoring library. Unfortunately, this library does not contain a nice icon to be shown in an About Rope dialog. Is there anybody around, who could contribute such an icon. Maybe it could look like the Python snake but instead of the snake a rope is shown. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From jimis at gmx.net Thu Jan 10 12:17:47 2008 From: jimis at gmx.net (Dimitrios Apostolou) Date: Thu, 10 Jan 2008 19:17:47 +0200 (EET) Subject: urllib2 rate limiting Message-ID: Hello list, I want to limit the download speed when using urllib2. In particular, having several parallel downloads, I want to make sure that their total speed doesn't exceed a maximum value. I can't find a simple way to achieve this. After researching a can try some things but I'm stuck on the details: 1) Can I overload some method in _socket.py to achieve this, and perhaps make this generic enough to work even with other libraries than urllib2? 2) There is the urllib.urlretrieve() function which accepts a reporthook parameter. Perhaps I can have reporthook to increment a global counter and sleep as necessary when a threshold is reached. However there is not something similar in urllib2. Isn't urllib2 supposed to be a superset of urllib in functionality? Why there is no reporthook parameter in any of urllib2's functions? Moreover, even the existing way reporthook can be used doesn't seem so right: reporthook(blocknum, bs, size) is always called with bs=8K even for the last block, and sometimes (blocknum*bs > size) is possible, if the server sends wrong Content-Lentgth HTTP headers. 3) Perhaps I can use filehandle.read(1024) and manually read as many chunks of data as I need. However I think this would generally be inefficient and I'm not sure how it would work because of internal buffering of urllib2. So how do you think I can achieve rate limiting in urllib2? Thanks in advance, Dimitris P.S. And something simpler: How can I disallow urllib2 to follow redirections to foreign hosts? From arnodel at googlemail.com Mon Jan 21 06:33:28 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 21 Jan 2008 03:33:28 -0800 (PST) Subject: Default attribute values pattern References: <4794697f$0$16980$426a74cc@news.free.fr> <41f8394c-342c-42dc-9bf2-a737b572aff9@c4g2000hsg.googlegroups.com> Message-ID: <2b478c87-238d-43b7-a414-8dc609395752@e25g2000prg.googlegroups.com> On Jan 21, 10:09?am, cokofree... at gmail.com wrote: > > Grab(argdict, key, default) is argdict.pop(key, default) > > "pop() raises a KeyError when no default value is given and the key is > not found." And it doesn't if a default is provided, which is always the case in the uses of Grab(...), so it seems the right tool for the job. > > def grab(kw, key, default=None): > > ? ?try: > > ? ? ?return kw.pop(key) > > ? ?except KeyError: > > ? ? ?return default > > So Bruno's technique seems to me to be the correct one as it catches > the KeyError. If you really really want to write a grab function (IMHO pop is good enough): def grab(kw, key, default=None): return kw.pop(key, default) -- Arnaud From tjreedy at udel.edu Sat Jan 26 02:32:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jan 2008 02:32:48 -0500 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com><8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com><479A58F9.4090805@gmx.net> <8d04436f0801251519g482a697dn625223b6d46e8f2c@mail.gmail.com> Message-ID: "Henry Baxter" wrote in message news:8d04436f0801251519g482a697dn625223b6d46e8f2c at mail.gmail.com... | Thanks Hexamorph and Neal. Somehow I didn't make the connection with using | 'index', but I'm all sorted out now :) | | On Jan 25, 2008 1:47 PM, Hexamorph wrote: | | > Henry Baxter wrote: | > > Oops, gmail has keyboard shortcuts apparently, to continue: | > > | > > def maxi(l): | > > m = max(l) | > > for i, v in enumerate(l): | > > if m == v: | > > return i | > > | > | > What's about l.index(max(l)) ? Both of these methods scan the list twice. The two given by RH and SDD do so just once. Both of those will give the index of the of the last maximum value. If you want the index of the first max value (you did not specify ;-), write an explicit loop. From travis.jensen at gmail.com Fri Jan 18 13:53:23 2008 From: travis.jensen at gmail.com (Travis Jensen) Date: Fri, 18 Jan 2008 11:53:23 -0700 Subject: array and list In-Reply-To: <010888f2-7755-4ec1-9f56-be8a43097a1f@i12g2000prf.googlegroups.com> References: <24f854eb-93a8-414d-a518-842bb2d185fb@s13g2000prd.googlegroups.com> <010888f2-7755-4ec1-9f56-be8a43097a1f@i12g2000prf.googlegroups.com> Message-ID: <4C920483-DD98-4DB2-9E6B-21879D82E2B8@gmail.com> On Jan 18, 2008, at 2:48 AM, bearophileHUGS at lycos.com wrote: > J. Peng>why perl call it array and python call it list?< > > Unfortunate naming, I'd say. Calling list a dynamic array is silly, > despite all the things you may say about abstract data types having > the correct methods, etc. I wouldn't call it unfortunate. The list semantics follow LISP's semantics far more closely than C's array semantics. I would hazard to guess that they are called lists because that is what every functional language calls them and this aspect of python was modeled after functional languages. tj Travis Jensen travis.jensen at gmail.com http://softwaremaven.innerbrane.com/ You should read my blog; it is more interesting than my signiature. From donn.ingle at gmail.com Fri Jan 25 09:33:47 2008 From: donn.ingle at gmail.com (Donn) Date: Fri, 25 Jan 2008 16:33:47 +0200 Subject: piping into a python script In-Reply-To: References: <200801241903.20082.donn.ingle@gmail.com> Message-ID: <200801251633.47201.donn.ingle@gmail.com> Andrew, Thanks for your tips. I managed to get a working script going. I am sure there will be stdin 'issues' to come, but I hope not. If anyone wants to have a look, it's on the cheese shop at: http://pypi.python.org/pypi/fui \d -- "You know, I've gone to a lot of psychics, and they've told me a lot of different things, but not one of them has ever told me 'You are an undercover policewoman here to arrest me.'" -- New York City undercover policewoman Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From stefan.behnel-n05pAM at web.de Wed Jan 23 09:12:23 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 15:12:23 +0100 Subject: Problem with processing XML In-Reply-To: <6c291c78-7a11-4d6f-be15-c916017ccf60@s13g2000prd.googlegroups.com> References: <13pbudgks88rcf3@corp.supernews.com> <47971EFF.8070701@web.de> <6c291c78-7a11-4d6f-be15-c916017ccf60@s13g2000prd.googlegroups.com> Message-ID: <47974B47.5000509@web.de> Hi, Paul Boddie wrote: > I'm not disputing the benefits of the ElementTree approach, but one > has to recall that the DOM is probably the most widely used XML API > out there (being the one most client-side developers are using) and > together with the other standards (XPath and so on) isn't as bad as > most people like to make out. I didn't deny that it works in general. However, it does not fit into the standard ways things work in Python. > Furthermore, I don't think it does > Python much good to have people "acting all Ruby on Rails" and telling > people to throw out everything they ever did in order to suck up the > benefits, regardless of the magnitude of those benefits; it comes > across as saying that "your experience counts for nothing compared to > our superior skills". Not exactly the best way to keep people around. I would have formulated it a bit different from my experience, which usually is: people complain on the list that they can't manage to get X to work for them. Others tell them: "don't use X, use Y", implicitly suggesting that you may have to learn it, but it will help you get your problem done in a way that you can /understand/ (i.e. that will fix your code for you, by enabling you to fix it yourself). >From my experience, this works in most (although admittedly not all) cases. But in any case, this reduction of complexity is an important step towards making people ask less questions. > As I noted in my chronology, the kind of attitude projected by various > people in the Python community at various times (and probably still > perpetuated in the Ruby community) is that stuff originating from the > W3C is bad The W3C is good in defining standards for portability and interoperability. APIs rarely fall into that bag. They should be language specific as they are made for use in a programming language, and therefore must match the way this language works. However, programming languages themselves are sometimes made for interoperability, and this is definitely true for XSLT and XQuery. I am a big fan of domain specific languages, because they (usually) are great in what they are designed for, and nothing more. > like the DOM stuff, if the support for standardised/ > recognised technologies is perceived as deficient, and given the point > above about glossing over what people themselves bring with them to > solve a particular problem, then people are quite likely to gloss over > Python than hear anyone's sermon about how great Python's other XML > technologies are. It's not about "other XML technologies", it's only about making the standard XML technologies accessible and usable. It's about designing interfaces in a way that matches the tool people are using anyway, which in this case is Python. Stefan From paddy3118 at googlemail.com Tue Jan 29 13:00:33 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 29 Jan 2008 10:00:33 -0800 (PST) Subject: Python noob SOS (any [former?] Perlheads out there?) References: Message-ID: <4786a797-dedf-45bc-960a-9d1a20b0de5d@l1g2000hsa.googlegroups.com> On Jan 29, 4:39 pm, kj wrote: > It's not the Python syntax that I'm having problems with, but rather > with larger scale issues such as the structuring of packages, > techniques for code reuse, test suites, the structure of > distributions,... Python and Perl seem to come from different > galaxies altogether... Maybe if someone could point Kynn at a suitable project where he could look at the complete repository and see how its successfully done? It would need I guess to employ: * Setuptools * modules/package(s) * Doctest/unit tests And not be too large I guess. Anyone wish to put forward their project? - Paddy. - Paddy. From mensanator at aol.com Mon Jan 21 19:02:34 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 21 Jan 2008 16:02:34 -0800 (PST) Subject: Max Long References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> Message-ID: On Jan 21, 5:36?pm, Gary Herron wrote: > tjhn... at gmail.com wrote: > > How can I figure out the largest long available? ?I was hoping for > > something like sys.maxint, but I didn't see it. ?Also, can someone > > point me to where I can (concisely) read about size of such types > > (int, float, long). > > There is no explicit (defined) limit. ?The amount of available address > space forms a practical limit. But not the only limitation: >>> import collatz_functions as cf >>> for k in xrange(1,20): a = cf.Type12MH(k,1) print 'number of digits in generation %2d:' % (k),cf.gmpy.numdigits(a) number of digits in generation 1: 2 number of digits in generation 2: 9 number of digits in generation 3: 74 number of digits in generation 4: 659 number of digits in generation 5: 5926 number of digits in generation 6: 53328 number of digits in generation 7: 479940 number of digits in generation 8: 4319453 number of digits in generation 9: 38875064 number of digits in generation 10: 349875565 Traceback (most recent call last): File "", line 2, in a = cf.Type12MH(k,1) File "C:\Program Files\PyGTK\Python\lib\collatz_functions.py", line 745, in Type12MH return TWO**(SIX*a - ONE) - ONE ValueError: mpz.pow outrageous exponent The power function can't do exponents that have 32 or more bits even if the memory can hold the resulting number. > > Gary Herron From lists at cheimes.de Tue Jan 29 06:46:15 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 29 Jan 2008 12:46:15 +0100 Subject: refcount In-Reply-To: References: Message-ID: Simon Pickles wrote: > Hi, > > Is is possible to access the refcount for an object? > > Ideally, I am looking to see if I have a refcount of 1 before calling del Help on built-in function getrefcount in module sys: getrefcount(...) getrefcount(object) -> integer Return the reference count of object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount(). Christian From cjw at sympatico.ca Tue Jan 8 13:01:02 2008 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 08 Jan 2008 13:01:02 -0500 Subject: I'm searching for Python style guidelines In-Reply-To: References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: Martin Vilcans wrote: > On 1/7/08, Guilherme Polo wrote: >> 2008/1/7, MartinRinehart at gmail.com : >>> Anything written somewhere that's thorough? Any code body that should >>> serve as a reference? >> PEP 8 >> http://www.python.org/dev/peps/pep-0008/ > > The problem with PEP 8 is that even code in the standard libraries > doesn't follow the recommendations regarding the naming of functions > for example. The recommendation is to_separate_words_with_underscore, > but some code uses lowerCamelCase instead. > > I tended to dislike the underscore convention, but after forcing > myself to use it for a while I'm starting to appreciate its beauty. I've come to like lowerCamelCase and a tab of 2. A tab of 4 wastes more space than is needed for the occasional heavy indenting. Colin W. From gregcorradini at gmail.com Tue Jan 29 11:27:13 2008 From: gregcorradini at gmail.com (Greg Corradini) Date: Tue, 29 Jan 2008 08:27:13 -0800 (PST) Subject: Mx.ODBC insert error Message-ID: <15163149.post@talk.nabble.com> Hello, I've never gotten this traceback error before using mx.ODBC. Any ideas about resolving this issue? The statement and the error it generates are listed below. curse.execute("Insert into FHWA_StandSamp_2008(LRS_ID_NEW) values('0402000010') where LRS_ID = '0403700010'") Traceback (most recent call last): File "", line 1, in ? curse.execute("Insert into FHWA_StandSamp_2008(LRS_ID_NEW) values ('0402000010') where LRS_ID = '0403700010'") ProgrammingError: ('37000', -3516, '[Microsoft][ODBC Microsoft Access Driver] Missing semicolon (;) at end of SQL statement.', 4612) Thanks Greg -- View this message in context: http://www.nabble.com/Mx.ODBC-insert-error-tp15163149p15163149.html Sent from the Python - python-list mailing list archive at Nabble.com. From rong.xian at gmail.com Sun Jan 27 08:50:53 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 05:50:53 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> Message-ID: On 1?27?, ??7?20?, John Machin wrote: > On Jan 27, 9:17 pm, glacier wrote: > > > > > > > On 1?24?, ??3?29?, "Gabriel Genellina" wrote: > > > > En Thu, 24 Jan 2008 04:52:22 -0200, glacier escribi?: > > > > > According to your reply, what will happen if I try to decode a long > > > > string seperately. > > > > I mean: > > > > ###################################### > > > > a='???'*100000 > > > > s1 = u'' > > > > cur = 0 > > > > while cur < len(a): > > > > d = min(len(a)-i,1023) > > > > s1 += a[cur:cur+d].decode('mbcs') > > > > cur += d > > > > ###################################### > > > > > May the code above produce any bogus characters in s1? > > > > Don't do that. You might be splitting the input string at a point that is > > > not a character boundary. You won't get bogus output, decode will raise a > > > UnicodeDecodeError instead. > > > You can control how errors are handled, see http://docs.python.org/lib/string-methods.html#l2h-237 > > > > -- > > > Gabriel Genellina > > > Thanks Gabriel, > > > I guess I understand what will happen if I didn't split the string at > > the character's boundry. > > I'm not sure if the decode method will miss split the boundry. > > Can you tell me then ? > > > Thanks a lot. > > *IF* the file is well-formed GBK, then the codec will not mess up when > decoding it to Unicode. The usual cause of mess is a combination of a > human and a text editor :-)- ??????? - > > - ??????? - I guess firstly, I should check if the file I used to test is well- formed GBK..:) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 23 08:12:50 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 23 Jan 2008 14:12:50 +0100 Subject: Max Long References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> <5vkog7F1m4dhvU1@mid.individual.net> Message-ID: <5vosqiF1nc20jU1@mid.individual.net> tjhnson at gmail.com wrote: > Indeed, as the docs pointed out. I guess I was confused by > > "If pylong is greater than ULONG_MAX, an OverflowError is raised." > > at http://docs.python.org/api/longObjects.html. Take care -- this is about "unsigned long" data type of C, not a Python "long" instance. Regards, Bj?rn -- BOFH excuse #75: There isn't any problem From gagsl-py2 at yahoo.com.ar Tue Jan 22 00:34:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 Jan 2008 03:34:30 -0200 Subject: newbie question: On installation of additional packages to Python References: Message-ID: En Tue, 22 Jan 2008 00:36:34 -0200, Nasser Abbasi escribi?: > I am running on windowz. I have downloaded and installed 2.5.1 Python. > > my question is on installing additional packages. > > What is the easiest way to do that? I read about python 'eggs' (like jar > files for Java), and easyInstall script, and such. Once you have setuptools installed, it's as easy as executing: easy_install packagename The alternative is to find and download the package yourself, unzip in a temporary directory, and execute: setup.py install For most packages that's all that is required. > Is there some automated way to install Python packages? a > manual/document I > could read that describes step by step how to do that? Browsing the > documentation, there does not seem to be something specific there (other > than saying download this tar file and install it). > > I like how one can install additional packages in 'R' . In 'R' one can do > all that from the user interface for R by a pull-down menu, then one > selects > a mirror site, then one can see all the packages available, then select > the > package to download, and the rest is done automatically. (The package is > downloaded, installed, etc...) That's mainly what easy_install does, plus dependency checking. -- Gabriel Genellina From petr.jakes.tpc at gmail.com Fri Jan 4 12:50:16 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Fri, 4 Jan 2008 09:50:16 -0800 (PST) Subject: Pivot Table/Groupby/Sum question References: <148c3214-77b9-47b0-a680-ffb85dd3efcd@e6g2000prf.googlegroups.com> <63a5a87e-3385-4ef0-80a3-cd1a01eeeac3@w38g2000hsf.googlegroups.com> <276d150b-6b2a-4973-8569-bd8cad6df948@s19g2000prg.googlegroups.com> <018c37d5-67c0-4995-88e3-86f701580c26@e23g2000prf.googlegroups.com> <5d6721cc-1912-4adc-9e47-0afa21c51c89@21g2000hsj.googlegroups.com> <17de023b-8dfd-4478-8271-96e21968d489@s8g2000prg.googlegroups.com> <39fd9ee5-d874-4cea-a7bb-64ab62594332@m34g2000hsf.googlegroups.com> <14a5ef8d-41c8-4164-8a5b-f992c7d12990@u10g2000prn.googlegroups.com> <84ab8796-cef2-4e02-bd91-c5226e2b283b@u10g2000prn.googlegroups.com> Message-ID: <55d47b0b-3655-45f9-9e19-088d67157758@d21g2000prf.googlegroups.com> On Jan 4, 4:55 pm, patrick.wa... at gmail.com wrote: > Petr thanks so much for your input. I'll try to learnSQL, especially > if I'll do a lot of database work. > > I tried to do it John's way as en exercise and I'm happy to say I > understand a lot more. Basically I didn't realize I could nest > dictionaries like db = {country:{genre:{sub_genre:3}}} and call them > like db[country][genre][sub_genre]. The Python Cookbook was quite > helpful to figure out why items needed to be added the way they did. > Also using the structure of the dictionary was a conceptually easier > solution than what I found onhttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334695. > > So, now I need to work on writing it to Excel. I'll update with the > final code. > Hi, good to know you have succeded. I think it is matter of taste which way to go (dictionary or database). My feelig is: for data use database! If you are trying to work with data, you will need it sooner or later anyway. Again: database is made for data! :-) Writing your data to excel? Just save your numbers separated by commas in the file with the extension csv (my_data.csv) and you can open it directly in Excel. Good luck :-) Petr From 42flicks at gmail.com Thu Jan 31 00:07:40 2008 From: 42flicks at gmail.com (Mike D) Date: Thu, 31 Jan 2008 18:07:40 +1300 Subject: Design question - Sharing of single object by multiple processes Message-ID: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> Hello, I've just picked up the Python language and am really enjoying it. I've just signed up to this mailing list and I'm looking forward to taking part in some discussions. My first post is a question I've been pondering for the last couple of days: For relatively static data (such as a list), is it possible to load a single instance and have many python processes access it? I want to have an object in memory. This object will be loaded on application start up and will contain a list of objects. These will be obtained from (most likely) the file system. My reasoning is: I want to prevent a file system or database fetch each time as it seems unnecessary. Is this possible? In Java I'm pretty sure this could implemented with an object factory and static methods. My understanding is that python invokes a separate process for each request however. If possible, what would be a good way of providing a new structure as it is updated. If anyone could give me some advice or point me in the correct direction I'd really appreciate it. Thanks in advance, Mike. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Tue Jan 15 05:06:18 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 15 Jan 2008 02:06:18 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <13od12b23hfv772@corp.supernews.com> <5b035c91-72eb-4d88-b19b-e89470865c5b@i7g2000prf.googlegroups.com> <13ogbfasbcici1c@corp.supernews.com> <389f20bb-ccbf-43bd-b38b-e359a3f62c3a@f47g2000hsd.googlegroups.com> Message-ID: Paul Boddie: > what is everyone with any degree of > concern about Python's performance doing to improve the situation? They are probably developing systems like Cython and ShedSkin, and hoping to see Psyco improved again to manage itertools better (and maybe 64 bit CPUs too). > Sure, C (or actually C++) seems to win the shootout [1], Beside C++ being the faster (not C anymore), there are other ways to "win" the Shootout, like using less RAM, writing shorter code, etc. If you change the way you measure you can see that FreePascal, Ruby and D too "win" the Shootout :-) (the first as the one using less memory, the second one as the one with shorter programs, and the third one as "faster && with shorter programs"). > but there are > plenty of language implementations between g++ and CPython to suggest > that the old choice of extension modules written in C vs. other code > written in Python doesn't provide a complete map of the opportunities. I think in few years it may become feasible to use Pyd to write extensions in D for CPython :-) Bye, bearophile From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 12:04:34 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 18:04:34 +0100 Subject: Unknown cause to error (new to python) In-Reply-To: References: <478e10bd$0$27280$426a34cc@news.free.fr> Message-ID: <478e38f7$0$27530$426a34cc@news.free.fr> Brandon Perry a ?crit : (top-post corrected) >> >> On Wed, 2008-01-16 at 15:12 +0100, Bruno Desthuilliers wrote: >>> Brandon Perry a ?crit : (snip context) >>>> but I am getting some weird errors. >>>> >>>> File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", >>>> line 41, in ? >>>> File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", line 71, in ? >>>> File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", line 4, in ? >>>> File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", line 4, in ? >>>> File "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", line 15, in ? >>> >>> Sorry but my crystal ball is broken. Please post the *whole* traceback. >>> > Sorry, this is all I can get. :-( > > This isn't my webserver, so the only error logs I get are what they give > me. I guess I will just have to keep working at it. Then looks like you're in for hard time. Trying to solve a problem without any relevant information is not rationaly possible. Perhaps you should try voodoo ? > Thanks for looking at it though, Brandon Sorry, can't help much here. From hniksic at xemacs.org Fri Jan 11 12:11:51 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 11 Jan 2008 18:11:51 +0100 Subject: Learning Python via a little word frequency program References: <205c99df-2550-47b0-9c82-020b99ed3122@l1g2000hsa.googlegroups.com> <7x63y0ins2.fsf@ruckus.brouhaha.com> Message-ID: <87abncs2w8.fsf@mulj.homelinux.net> Mike Meyer writes: > On 11 Jan 2008 03:50:53 -0800 Paul Rubin <"http://phr.cx"@NOSPAM.invalid> wrote: > >> rent writes: >> > keys = freq.keys() >> > keys.sort(key = freq.get, reverse = True) >> > for k in keys: >> > print "%-10s: %d" % (k, freq[k]) >> >> I prefer (untested): >> >> def snd((x,y)): return y # I wish this was built-in > > What's wrong with operator.itemgetter? > >> sorted_freq = sorted(freq.iteritems(), key=snd, reverse=True) > > (still untested) > > from operator import itemgetter > sorted_freq = sorted(freq.iteritems(), key=itemgetter(2), reverse=True) It should be itemgetter(1). See how easy it is to get it wrong? :-) (Okay, this was too easy a shot to miss out on; I actually like itemgetter.) From bj_666 at gmx.net Wed Jan 9 14:08:15 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Jan 2008 19:08:15 GMT Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> Message-ID: <5ukkcvF1hs5vpU1@mid.uni-berlin.de> On Wed, 09 Jan 2008 10:56:36 -0800, Louis.Soninhu wrote: > Hi pals > > I have a list like this > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] > > I'd like to remove the first and the last item as they are irrevalent, > and convert it to the dict: > {'tom':'boss','mike':'manager','paul':'employee'} > > I tried this but it didn't work: > > mydict={} > for i in mylist[1:-1]: > a=i.split('=') # this will disect each item of mylist into a 2-item > list > mydict[a[0]]=a[1] > > and I got this: > File "srch", line 19, in > grab("a/tags1") > File "srch", line 15, in grab > mydict[mylist[0]]=mylist[1] > IndexError: list index out of range > > Anyone could shed me a light on this? The real list you used had at least one string without a '=' in it. The list given above doesn't raise that exception: In [102]: mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] In [103]: mydict={} In [104]: for i in mylist[1:-1]: .....: a=i.split('=') .....: mydict[a[0]]=a[1] .....: In [105]: mydict Out[105]: {'mike': 'manager', 'paul': 'employee', 'tom': 'boss'} Ciao, Marc 'BlackJack' Rintsch From http Tue Jan 22 08:24:34 2008 From: http (Paul Rubin) Date: 22 Jan 2008 05:24:34 -0800 Subject: Question on sort() key function References: <5vlopgF1mv4ekU1@mid.dfncis.de> <7xve5mfdmr.fsf@ruckus.brouhaha.com> <5vlqbjF1kl9cjU1@mid.dfncis.de> Message-ID: <7xy7airo19.fsf@ruckus.brouhaha.com> Robert Latest writes: > > flist.sort(key=lambda f: f.mod_date.toordinal) > > It doesn't throw an error any more, but neither does it sort the list. This, > however, works: Oh, I didn't realize that toordinal was a callable, given your earlier sample. You want: flist.sort(key=lambda f: f.mod_date.toordinal() ) From http Sun Jan 20 18:24:27 2008 From: http (Paul Rubin) Date: 20 Jan 2008 15:24:27 -0800 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> Message-ID: <7xhch8cc7o.fsf@ruckus.brouhaha.com> dg.google.groups at thesamovar.net writes: > Unfortunately I realise I stated the problem imprecisely. You're only > allowed to use each number once (otherwise there's a trivial solution > for every problem, i.e. x/x + x/x + x/x + ... + x/x repeated y times > for target y given any source number x). Trying your program on 234 > from [100,9,7,6,3,1] gives you 9*9*3-9 using the 9 three times. Here's an inefficient solution, that doesn't find 234 but finds 253. If you see a double post, it's because I posted something similar a little while ago but cancelled it since it had a bug. I'm not sure this one is correct either ;-). from operator import * def countdown(nums, trace='', ops=[add,mul,sub,div]): n0,n1s = nums[0], nums[1:] if not n1s: yield n0, str(n0) return for f in ops: for r,t in countdown(n1s, trace, [add, mul, sub]): if f != div or r != 0 and n0 % r == 0: yield f(n0, r), '%s(%s,%s)'% (f.__name__, n0, t) def find_repr(target, nums): # print all representations of target from nums for x,t in countdown(nums): if x == target: print x,t find_repr(253, [100,9,7,6,3,1]) From bignose+hates-spam at benfinney.id.au Thu Jan 24 00:41:02 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 24 Jan 2008 16:41:02 +1100 Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> Message-ID: <87abmv7pch.fsf@benfinney.id.au> Ben Finney writes: > glacier writes: > > > I use chinese charactors as an example here. > > > > >>>s1='???' > > >>>repr(s1) > > "'\\xc4\\xe3\\xba\\xc3\\xc2\\xf0'" > > >>>b1=s1.decode('GBK') > > > > My first question is : what strategy does 'decode' use to tell the > > way to seperate the words. I mean since s1 is an multi-bytes-char > > string, how did it determine to seperate the string every 2bytes > > or 1byte? > > The codec you specified ("GBK") is, like any character-encoding > codec, a precise mapping between characters and bytes. It's almost > certainly not aware of "words", only character-to-byte mappings. To be clear, I should point out that I didn't mean to imply static tabular mappings only. The mappings in a character encoding are often more complex and algorithmic. That doesn't make them any less precise, of course; and the core point is that a character-mapping codec is *only* about getting between characters and bytes, nothing else. -- \ "He who laughs last, thinks slowest." -- Anonymous | `\ | _o__) | Ben Finney From christopher.saunter at durham.ac.uk Fri Jan 25 09:24:56 2008 From: christopher.saunter at durham.ac.uk (c d saunter) Date: Fri, 25 Jan 2008 14:24:56 +0000 (UTC) Subject: Windows AVIFile problems References: Message-ID: Thomas Heller (theller at ctypes.org) wrote: : c d saunter schrieb: : > Hi All, : > : The dll is not corrupt. It is the 16-bit dll, possibly present for legacy : 16-bit support. Thomas, Thanks, that explains a lot. Regards, Chris Saunter From huayang.xia at gmail.com Thu Jan 24 17:17:09 2008 From: huayang.xia at gmail.com (Huayang Xia) Date: Thu, 24 Jan 2008 14:17:09 -0800 (PST) Subject: PyPerforce: How to open file for editing Message-ID: I'm completely new to pyperforce. I want to open a file (check out a file) for editing. How can I do it from PyPerforce? Another thing is how can I add files to my created label? Thanks in advance. From sjmachin at lexicon.net Thu Jan 31 14:48:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 31 Jan 2008 11:48:36 -0800 (PST) Subject: PIL linux err References: Message-ID: On Feb 1, 5:41 am, dzizes wrote: > Hi, > > I'm trying to run simple .py on linux, which is using PIL. Below error > message which I receive: > > File "/usr/lib/python2.4/site-packages/PIL/Image.py", line 960, in > histogram > self.load() > File "/usr/lib/python2.4/site-packages/PIL/ImageFile.py", line 180, in > load > d = Image._getdecoder(self.mode, d, a, self.decoderconfig) > File "/usr/lib/python2.4/site-packages/PIL/Image.py", line 375, in > _getdecoder > raise IOError("decoder %s not available" % decoder_name) > IOError: decoder jpeg not available > > Do you know what might be the problem? Is your googler broken? See: http://effbot.org/zone/pil-decoder-jpeg-not-available.htm From paddy3118 at googlemail.com Mon Jan 7 02:33:06 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 6 Jan 2008 23:33:06 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> Message-ID: <91f8a1dd-248c-40c3-a70a-6f0caefb6c4a@s8g2000prg.googlegroups.com> On Jan 5, 11:07 pm, bearophileH... at lycos.com wrote: > Paddy: > > > Not really, it seems to me to be going the exact opposite way with > > languages with automatic type conversions being seen as not suited for > > larger programs. > > In Java you can add the number 1 to a string, and have it > automatically converted to string before the string join... What do > you think of that feature? > > Bye, > bearophile Hi Bearophile, Unfortunately, (fortunately?), I don't know enough Java. I can just get by reading correct Java programs so could not really comment. If Java is flexible enough to allow the '+' operator to be defined between strings and integers and left it to the programmer to define the result then that would be a good thing, but having the language automatically define conversions between unrelated types would break strong typing which I have read that Java enjoys. http://en.wikipedia.org/wiki/Type_system#Strong_and_weak_typing - Paddy. From peng.kyo at gmail.com Thu Jan 17 01:11:57 2008 From: peng.kyo at gmail.com (J. Peng) Date: Thu, 17 Jan 2008 14:11:57 +0800 Subject: assigning values in python and perl In-Reply-To: References: <18c1e5f20801161934m69ff44edo1e35f5381f7d2928@mail.gmail.com> Message-ID: <18c1e5f20801162211u661efa36u582eea623449c5d4@mail.gmail.com> On Jan 17, 2008 1:54 PM, Mel wrote: > > test(a) (along with def test(x)) takes the object named 'a' in the > current namespace and binds it with the name 'x' in function test's > local namespace. So, inside test, the name 'x' starts by referring to > the list that contains [1,2,3]. But the only use test makes of the > name 'x' is to re-bind it to a new list [4,5,6]. Exiting test, the > local namespace is thrown away. > Hi, Yes I know it pretty well now, but thanks for the pointer. What I asked is that, if we re-write that code with perl or C, we'll get different results. From fredrik at pythonware.com Thu Jan 10 16:54:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 22:54:16 +0100 Subject: Newbie question on Classes In-Reply-To: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> References: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> Message-ID: Adrian Wood wrote: > I can call man.state() and then woman.state() or Person.state(man) and > Person.state(woman) to print the status of each. This takes time and > space however, and becomes unmanageable if we start talking about a > large number of objects, and unworkable if there is an unknown number. > What I'm after is a way to call the status of every instance of Man, > without knowing their exact names or number. > > I've gone through the relevant parts of the online docs, tried to find > information elsewhere online, and looked for code samples, but the > ionformation either isn't there, or just isn't clicking with me. I've > tried tracking the names of each object in a list, and even creating > each object within a list, but don't seem to be able to find the right > syntax to make it all work. For a start, how about: class Person: ... your class ... persons = [] man = Person() persons.add(man) woman = Person() persons.add(woman) for p in persons: print p, p.state() Once you've gotten this to work, you can, if you want, look into moving the list maintenance into the class itself (i.e. let the __init__ function add the person to the list, and provide a destroy method that removes it from the list). And once you've gotten that to work, you can look at the "weakref" module for more elegant ways to handle destruction. But one step at a time... From tjreedy at udel.edu Sun Jan 27 19:26:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jan 2008 19:26:46 -0500 Subject: explicit protocols and duck typing References: <5e28034f-a20f-4aa7-b299-9c9132ef2566@c4g2000hsg.googlegroups.com> Message-ID: wrote in message news:5e28034f-a20f-4aa7-b299-9c9132ef2566 at c4g2000hsg.googlegroups.com... | Hi all, | | As I understand it, the idea behind duck typing is that you just take | an object and if it has the methods you want to use you use it | assuming it to be the right type of object. I'm interested in | extending this idea a bit, but I feel the sort of thing I have in mind | has already been thought of. So for example, in the program I'm | writing a 'state variable' specifier can be either an integer or a | string (the string name is mapped to an integer by another function | getvarindex(name)). Why a function rather than a dict 'varindex'? The valid strings are then varindex.keys(). You might want a build_varindex() func though. |In this case, I can't do duck typing by seeing if | the object has a method or not, because both of the types are built in | types. builtin types have methods same as user types. It is not clear from your description why there should be any restriction on state-variable specifier other than hashable since any set of hashable objects can be easily mapped to range(len() with a dict. Whether you merely document the rules or write code to enforce them should partly depends on who suffers when they are broken. tjr From jeff at jmcneil.net Thu Jan 24 12:49:19 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 24 Jan 2008 12:49:19 -0500 Subject: Duplicating a variable In-Reply-To: References: Message-ID: <82d28c40801240949h4545636xbaa2751086939d32@mail.gmail.com> Have a look at the copy module if you have a somewhat "complex" object graph to duplicate. Remember, you're essentially just creating another reference to a singular list object with simple assignment (a = b). >>> a = [1,2,3,4, ['5a', '5b', '5c', ['6a', '6b','6c']], 7,8] >>> b = a >>> a [1, 2, 3, 4, ['5a', '5b', '5c', ['6a', '6b', '6c']], 7, 8] >>> a[4][1] = None >>> a [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> b [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> import copy >>> d = copy.deepcopy(a) >>> d [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> a [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> a[4][1] = "Something" >>> a [1, 2, 3, 4, ['5a', 'Something', '5c', ['6a', '6b', '6c']], 7, 8] >>> b [1, 2, 3, 4, ['5a', 'Something', '5c', ['6a', '6b', '6c']], 7, 8] >>> d [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> Thanks, Jeff On 1/24/08, hnessenospam at yahoo.com wrote: > > I have run into a bit of a subtle problem. How do I go about > duplicating a variable (particularly a list of lists) in python. I > was surprised when simple assignment didn't work. For example, let y = > [1,2,3] > > >>> x = y > >>> x[2] = 5 > >>> y > [1,2,5] > > It seems that simply assigning x to y allows further modification of y > via x. (I'm new to python and I'm sure this is obvious to experienced > users). So my question, how do I go about duplicating a variable > which I can then manipulate independently? > > Thanks, > > -Hans > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Fri Jan 25 11:23:40 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 25 Jan 2008 10:23:40 -0600 Subject: Automatically Writing a Dictionary In-Reply-To: <8CA2D8436C5B761-E80-5C4@FWM-D40.sysops.aol.com> References: <8CA2C0BF25FCAA6-1374-117B@WEBMAIL-DC15.sysops.aol.com> <47979785.502@tim.thechases.com> <8CA2D8436C5B761-E80-5C4@FWM-D40.sysops.aol.com> Message-ID: <479A0D0C.1040703@tim.thechases.com> >> d = dict(line.split(',').rstrip('\n')? > > Thanks. That worked except for the rstrip. So I did this: Sorry...I got the order wrong on them (that's what I get for editing after copy&pasting). They should be swapped: d = dict(line.rstrip('\n').split(',')) to strip off the newline before you split it. -tkc From news at neither-nor.net Wed Jan 23 09:43:47 2008 From: news at neither-nor.net (Kristian Domke) Date: Wed, 23 Jan 2008 15:43:47 +0100 Subject: twisted: problem with sftp-client Message-ID: Hello Folks, I don't know, if it is ok to post large portions of code, but I have really no idea where the problem lies, so I don't have much of a choice. I am programming a tool, which in the end shall connect to an sftp-server, take the list of files in a specified directory, searches for some special names and mailes them to different persons. I am only at the start at the moment. As orientation I use the cftp.py programm from twisted.conch with some alterations because of not having userinteraction. At its current state the programm should do nothing but getting the listing of files from a server. It works fine with the cfto.py, so the server is ok. But while the cftp.py script gets 'files' as an exceptions.EOFError exeption in the StdioClient._cbReadFile at the end of the listing, I just get another list and run into wall (aka Traceback): > 2008/01/23 16:14 +0200 [SSHChannel session (0) on SSHService > ssh-connection on SimpleTransport,client] Unhandled Error > Traceback (most recent call last): > File "/usr/lib/python2.5/site-packages/twisted/python/log.py", > line 48, in callWithLogger > return callWithContext({"system": lp}, func, *args, **kw) > File "/usr/lib/python2.5/site-packages/twisted/python/log.py", > line 33, in callWithContext > return context.call({ILogContext: newCtx}, func, *args, > **kw) > File > "/usr/lib/python2.5/site-packages/twisted/python/context.py", line 59, > in callWithContext > return self.currentContext().callWithContext(ctx, func, > *args, **kw) > File > "/usr/lib/python2.5/site-packages/twisted/python/context.py", line 37, > in callWithContext > return func(*args,**kw) > --- --- > File > "/usr/lib/python2.5/site-packages/twisted/conch/ssh/filetransfer.py", > line 52, in dataReceived > f(data) > File > "/usr/lib/python2.5/site-packages/twisted/conch/ssh/filetransfer.py", > line 694, in packet_STATUS > msg, data = getNS(data) > File > "/usr/lib/python2.5/site-packages/twisted/conch/ssh/common.py", line > 39, in getNS > l, = struct.unpack('!L',s[c:c+4]) > File "struct.py", line 87, in unpack > return o.unpack(s) > struct.error: unpack requires a string argument of length 4 I have no Idea, and hope here is someone who can help me. Kristian ---------------------------------------- from twisted.internet import reactor, defer, protocol from twisted.conch.ssh import connection, filetransfer, keys, userauth from twisted.conch.ssh import channel, transport, common from twisted.conch.client import options, default, connect from twisted.python import log, failure import sys, time publicKey = 'some public key' privateKey ='''some private key''' USER = 'sftpuser' def run(): opts = options.ConchOptions() opts['host'] = 'localhost' opts['user'] = USER opts['port'] = 22 log.startLogging(sys.stdout) log.msg('logging started') protocol.ClientCreator(reactor, SimpleTransport).connectTCP(opts['host'], opts['port']) reactor.run() # start the event loop def doConnect(options): host = options['host'] user = options['user'] port = options['port'] conn = SSHConnection vhk = default.verifyHostKey uao = UserAuthClient(user, conn) d = connect.connect(host, port, options, vhk, uao) d.addErrback(_ebExit) return d def _ebExit(f): if hasattr(f.value, 'value'): s =f.value.value else: s = str(f) log.msg( s ) try: reactor.stop() except: pass def _cleanExit(): try: reactor.stop() except: pass class SimpleTransport(transport.SSHClientTransport): def verifyHostKey(self, hostKey, fingerprint): log.msg('host key fingerprint: %s' % fingerprint) return defer.succeed(1) def connectionSecure(self): self.requestService( UserAuthClient(USER, SSHConnection())) class UserAuthClient(userauth.SSHUserAuthClient): """Simple User Authentication Client""" def getPassword(self, prompt = None): return # this says we won't do password authentication def getPublicKey(self): return keys.getPublicKeyString(data = publicKey) def getPrivateKey(self): return defer.succeed(keys.getPrivateKeyObject(data = privateKey)) class SSHConnection(connection.SSHConnection): def serviceStarted(self): log.msg('Service started') self.openChannel(SSHSession(conn = self)) class SSHSession(channel.SSHChannel): name = 'session' def channelOpen(self, irgnoreData): log.msg('session %s is open' % self.id) request = 'subsystem' d = self.conn.sendRequest(self, request, common.NS('sftp'), wantReply=1) d.addCallback(self._cbSubsystem) d.addErrback(_ebExit) return d def _cbSubsystem(self, result): log.msg('Establishing Subsystem') self.client = SFTPClient() self.client.makeConnection(self) self.dataReceived = self.client.dataReceived def openFailed(self, reason): log.err('Opening Session failed: %s' % reason) _cleanExit() class SFTPClient(filetransfer.FileTransferClient): def __init__(self): filetransfer.FileTransferClient.__init__(self) self.currentDirectory = '' def connectionMade(self): log.msg('Connection with SFTPClient established') self.realPath('').addCallback(self._cbSetCurDir).addErrback(_cleanExit) def _cbSetCurDir(self, path): self.currentDirectory = path log.msg('currentDirectory set to %s.' % path) #self.cmd_MKDIR('test') self.cmd_LS(self.currentDirectory) def cmd_MKDIR(self, path): return self.makeDirectory(path, {}).addCallback(self._ignore) def cmd_LS(self, path): log.msg('List Stucture of %s' % path) d = self.openDirectory(path) d.addCallback(self._cbOpenList) def _cbOpenList(self, directory): files = [] log.msg('direc.:%s' % str(directory)) log.msg('direc.:%s' % type(directory)) log.msg('direc.:%s' % str(directory.parent)) log.msg('direc.:%s' % type(directory.parent)) d = directory.read() d.addCallback(self._cbReadFile, files, directory) d.addErrback(self._ebRaeadFile, files, directory) def _ebReadFile(self, files, l, directory): log.msg('**errback!**') self._cbReadFile(files, l, directory) def _cbReadFile(self, files, l, directory): log.msg('ReadFile called') log.msg('direc.:%s' % type(files)) if not isinstance(files, failure.Failure): log.msg('if not') l.extend(files) d = directory.read() #d.addCallback(self._ignore) d.addBoth(self._cbReadFile, l, directory) return d else: log.msg('else') reason = files reason.trap(EOFError) directory.close() return l def _ignore(self, *args): pass if __name__ == "__main__": run() From fredrik at pythonware.com Tue Jan 8 07:16:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 Jan 2008 13:16:42 +0100 Subject: Open a List of Files In-Reply-To: References: Message-ID: BJ Swope wrote: > the code looks ok. please define "not working". > > Yep, defining "not working" is always helpful! :) > > I want to have all 3 files open at the same time. I will write to each > of the files later in my script but just the last file is open for writing. to keep more than one file open, you need more than one variable, or a variable that can hold more than one object. if the number of files may vary, put the file objects in a list. if the number of files is constant, you might as well just use three variables and call open three times; e.g. def getfilename(name): return os.path.join(Host_Path, name) messages_file = open(getfilename("messages"), "w") recipients_file = open(getfilename("recipients"), "w") viruses_file = open(getfilename("viruses"), "w") From bearophileHUGS at lycos.com Fri Jan 11 12:50:46 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 11 Jan 2008 09:50:46 -0800 (PST) Subject: Converting a bidimensional list in a bidimensional array References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> <005679e9-c355-4e0a-872c-e0dae3181fd0@x69g2000hsx.googlegroups.com> <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> Message-ID: <054ea1c0-2b68-44cf-b7c6-f8e0d1a97a62@i72g2000hsd.googlegroups.com> Santiago Romero: > If each integer-python-object takes 16 bytes, this makes 60000 * 16 = > almost 1MB of memory just for the tilemaps... > Using array of type H (16 bits per item = 2 bytes), my maps take just > 60000*2 = 120KB of memory. > Do you think I should still go with lists instead of an H-type array? 1 MB or RAM may be small enough nowdays, so you may use lists. If not, then the array.array solution can be good. You may even store just the rows of your images as arrays, so you can use the usual syntax [][]. Another alternative is to use some external numerical lib, it's quite useful if you use pygame, to blit, process images, store and process bitmaps, etc. Bye, bearophile From bill.wws at gmail.com Thu Jan 17 10:38:57 2008 From: bill.wws at gmail.com (bill.wu) Date: Thu, 17 Jan 2008 07:38:57 -0800 (PST) Subject: the tutor list has been strangely silent for a few days. Anyone know what has happened? Message-ID: <2a3fed86-fc50-4d43-88af-38ea155fc09c@e4g2000hsg.googlegroups.com> the tutor list has been strangely silent for a few days. Anyone know what has happened? why? From princismo at gmail.com Mon Jan 21 11:15:02 2008 From: princismo at gmail.com (=?Big5?B?w0P4rw==?=) Date: Mon, 21 Jan 2008 08:15:02 -0800 (PST) Subject: How to solve "TypeError: list indices must be integers". Message-ID: <3f3ca8c6-b57c-43ff-bf80-11768e1a0f94@s8g2000prg.googlegroups.com> This is more details about my problem, which I running my py script for my project. Programming in pythoncard that we can develop a GUI based application easily. I was assigned dialog.colorDialog(self) return value to a result object, but I suspect that result.color is the attribute of the result object that can assign to a string variable. There is a error prompt from python console "TypeError: list indices must be integers". Have any suggestion to solve this problem? When I print result.color, it is print out something like (255,0,0). How to covert result.color into a string? How to convert a string to result.color type? adrian From yuxi at gatech.edu Thu Jan 17 11:31:50 2008 From: yuxi at gatech.edu (Yu-Xi Lim) Date: Thu, 17 Jan 2008 11:31:50 -0500 Subject: How to create graphs an embed them in GUI? In-Reply-To: References: Message-ID: Heiko Niedermeyer wrote: > Sorry for the fuzzy subject... > > Currently I'm writing a little programm to extract some chemical > information out of a text file, and then present it in a pleasant way. > The Extraction works so far, so now the presentation will be next. > If the GUI is only for the graph, try matplotlib. It should do the graphs/charts you require. If necessary, you can combine matplotlib with another GUI toolkit for a full GUI. This might be useful if you want to display menus and dialogs to load the text files, etc. 3D is a different matter. I'd personally go with Python bindings for VTK, but be warned that the learning curve is very steep and the online docs are quite sparse (you're encouraged to buy the book, which is probably the main source of income for the VTK devs). From devraj at gmail.com Thu Jan 10 21:37:59 2008 From: devraj at gmail.com (Devraj) Date: Thu, 10 Jan 2008 18:37:59 -0800 (PST) Subject: Detecting OS platform in Python Message-ID: Hi everyone, My Python program needs reliably detect which Operating System its being run on, infact it even needs to know which distribution of say Linux its running on. The reason being its a GTK application that needs to adapt itself to be a Hildon application if run on devices like the N800. I have been searching around for an answer to this, and did find some messages on a lists that suggested the use of sys.platform to detect platform, with counter posts saying that it didn't work on Windows etc. Can anyone please shed some light on this? Thanks a lot. From fuzzyman at gmail.com Wed Jan 23 16:47:37 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Wed, 23 Jan 2008 13:47:37 -0800 (PST) Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? References: Message-ID: ios... at gmail.com wrote: > Hi, I am looking for a HTML parser who can parse a given page into > a DOM tree, and can reconstruct the exact original html sources. > Strictly speaking, I should be allowed to retrieve the original > sources at each internal nodes of the DOM tree. > I have tried Beautiful Soup who is really nice when dealing with > those god damned ill-formed documents, but it's a pity for me to find > that this guy cannot retrieve original sources due to its great tidy > job. > Since Beautiful Soup, like most of the other HTML parsers in > python, is a subclass of sgmllib.SGMLParser to some extent, I have > investigated the source code of sgmllib.SGMLParser, see if there is > anything I can do to tell Beautiful Soup where he can find every tag > segment from HTML source, but this will be a time-consuming job. > so... any ideas? > A while ago I had a similar need, but my solution may not solve your problem. I wanted to rewrite URLs contained in links and images etc, but not modify any of the rest of the HTML. I created an HTML parser (based on sgmllib) with callbacks as it encounters tags and attributes etc. It is easy to process a stream without 'damaging' the beautiful orginal structure of crap HTML - but it doesn't provide a DOM. http://www.voidspace.org.uk/python/recipebook.shtml#scraper All the best, Michael Foord http://www.manning.com/foord > > cheers > kai liu From ptmcg at austin.rr.com Wed Jan 30 20:01:42 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 30 Jan 2008 17:01:42 -0800 (PST) Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! References: Message-ID: <8713cbea-7e82-4713-b411-b62f49b40f79@b2g2000hsg.googlegroups.com> On Jan 30, 6:40?pm, "Blubaugh, David A." wrote: > I do not understand why no one has answered the following question: > > Has anybody worked with Gene Expression Programming???? ? > > David Blubaugh > Sorry, I was too busy reading the posts about the pubic hair. And did you really wait only 1/2 an hour before going ballistic that NOBODY ANSWERED YOUR QUESTION????!!!!!!!!!!!!!! Take a pill. -- Paul From lists at cheimes.de Mon Jan 28 12:08:50 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 28 Jan 2008 18:08:50 +0100 Subject: Get Available Functions In-Reply-To: <479E0A7A.9080305@tim.thechases.com> References: <020501c861ca$d604dc70$820e9550$@rawlins@thinkbluemedia.co.uk> <479E0A7A.9080305@tim.thechases.com> Message-ID: Tim Chase wrote: > I've had a couple cases where the underlying module was written > in C (mod_python in particular...don't know if it still has this > problem) where dir() wouldn't actually tell you about the object, > but for most cases, dir() will get you pointed in the right > dir-ection. :) dir(), inspect and help() can't retrieve the method signature from a C function (builtin_function_or_method type). Christian From apatheticagnostic at gmail.com Fri Jan 4 16:06:02 2008 From: apatheticagnostic at gmail.com (apatheticagnostic) Date: Fri, 4 Jan 2008 13:06:02 -0800 (PST) Subject: Skill Resume Achievements, What Good Goes Here? References: Message-ID: <724e4836-d895-4210-972d-dd8f861902df@l1g2000hsa.googlegroups.com> On Jan 2, 11:31 am, kyoso... at gmail.com wrote: > On Jan 2, 9:59 am, vbgunz wrote: > > > I spent some time working on a skill resume, the kind of resume > > college students put together and realized, I am not in college and > > everything I learned was self-taught. Of course I would like some real > > world achievements but don't consider throw-away code an achievement > > and am failing to really see any. I don't even wish to entertain the > > thought of lying about anything. > > > What are some achievements an employer may be looking for in someone > > willing to start at ground level, entry level, intern, etc? What are > > some real world achievements every n00b will need under his/her belt > > in order to be taken seriously? > > Internships are always a good thing to have. If you've contributed to > open source projects, I'd put that on there. If you're applying for > some kind of programming job, they'll probably want to see some of > your code, know what home-brewed projects you've done and how long > they took to complete, issues you ran into, etc. > > That might get you started anyway. > > Mike As someone else who's self-educated and curious about this, would listing canonical comp-sci books that you've gone through on your own and understood be a reasonable thing to mention? For example, SICP, PLAI, etc? From jarausch at skynet.be Thu Jan 31 14:51:23 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Thu, 31 Jan 2008 20:51:23 +0100 Subject: helper function in a class' namespace Message-ID: <47a226bb$0$2982$ba620e4c@news.skynet.be> Hi, the following code works fine def Helper(M) : return 'H>'+M class A(object): def __init__(self,Msg) : print Helper(Msg) B=A('ZZ') but the Helper function is in the module's namespace. I'd like to put it into class A's namespace. Note, the Helper function doesn't need access to any instance attributes. The first variant class A(object): def Helper(M) : return 'H>'+M def __init__(self,Msg) : print Helper(Msg) doesn't work since Python is looking for a global function Helper (why?) The alternative class A(object): def Helper(M) : return 'H>'+M def __init__(self,Msg) : print A.Helper(Msg) doesn't work either since now the first argument to A.Helper must be 'A'. So, isn't it possible to have a helper function in the namespace of a class without (the overhead of) passing a 'self' or a 'cls' parameter? Probably I'm hurt by my C++ history. Many thanks for your help, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From lists.gnarlodious at gmail.com Tue Jan 8 00:27:40 2008 From: lists.gnarlodious at gmail.com (Gnarlodious) Date: Mon, 7 Jan 2008 22:27:40 -0700 Subject: mod-python on Mac OSX 10.5 Message-ID: <4782fe18$0$26015$88260bb3@free.teranews.com> I am trying to install mod_python on OSX 10.5, Intel version. sudo apachectl configtest tells me this: httpd: Syntax error on line 114 of /private/etc/apache2/httpd.conf: Cannot load /usr/libexec/apache2/mod_python.so into server: dlopen(/usr/libexec/apache2/mod_python.so, 10): no suitable image found. Did find:\n\t/usr/libexec/apache2/mod_python.so: mach-o, but wrong architecture I attempted to follow instructions found on these pages but it didn't work: Can anyone tell me what is causing this error? -- Gnarlie http://Gnarlodious.com/ -- Posted via a free Usenet account from http://www.teranews.com From mccredie at gmail.com Thu Jan 10 23:58:51 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 10 Jan 2008 20:58:51 -0800 (PST) Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <71343659-f8df-475b-813c-973fa82948e8@m77g2000hsc.googlegroups.com> On Jan 10, 10:36 pm, Marty wrote: > Hrvoje Niksic wrote: > > Mike Meyer writes: > > >> It sounds to me like your counter variable actually has meaning, > > > It depends how the code is written. In the example such as: > > > for meaningless_variable in xrange(number_of_attempts): > > ... > > > the loop variable really has no meaning. Rewriting this code only to > > appease pylint is exactly that, it has nothing with making the code > > more readable. > > >> you've hidden that meaning by giving it the meaningless name "i". If > >> you give it a meaningful name, then there's an obvious way to do it > >> (which you listed yourself): > > >> while retries_left: > > [...] > > > This loop contains more code and hence more opportunities for > > introducing bugs. For example, if you use "continue" anywhere in the > > loop, you will do one retry too much. > > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) > > This caused me to wonder why Python does not have a "foreach" statement (and > also why has it not come up in this thread)? I realize the topic has probably > been beaten to death in earlier thread(s), but does anyone have the short answer? Pythons `for' essentially is foreach. The code below does the same thing as what you have posted does. Actually, I've found that if you find yourself ever doing range(len(data_in)) in python, it is time to take a second look. data_out = [] for x in data_in: data_out.append([]) `range' is just a function that returns a list. Matt From ajaksu at gmail.com Sat Jan 5 12:23:13 2008 From: ajaksu at gmail.com (ajaksu) Date: Sat, 5 Jan 2008 09:23:13 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> <2ab22f95-d132-4e3c-8b68-bcbcee64e2ef@j78g2000hsd.googlegroups.com> Message-ID: <52aaba7c-6c39-49e3-a3a6-9c346fe9a8d8@e10g2000prf.googlegroups.com> > OTOH, if you do know that the chances are high enough, you can try > choosing items randomly without substitution (adapted from random.py's > sample): Sorry, this works: def randpickuntil(lst, prop=bool): selected = set() n = len(lst) for i in xrange(n): j = int(random() * n) while j in selected: j = int(random() * n) if prop(lst[j]): return lst[j] selected.add(j) Gotta say it's much faster on average than shuffle for moderately to highly probable tests, but might become pathological (i.e. run for minutes) for very large lists in which prop(x) is False for all. From ganeshborse at gmail.com Thu Jan 31 05:44:25 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 31 Jan 2008 02:44:25 -0800 (PST) Subject: Import of cStringIO failing with "undefined symbol: PyObject_SelfIter" on python-2.3.3-88.9 References: <13cb45c0-5b5d-4151-9797-d851ed3ad544@i7g2000prf.googlegroups.com> Message-ID: <8a39673c-528a-4512-a3ca-89ece8b7cf5f@l32g2000hse.googlegroups.com> On Jan 10, 6:07?pm, grbgooglefan wrote: > I am importing cStringIO module in my PythonC++ embedded program. > > The import is failing with the following error: > ImportError: /usr/lib/python2.3/lib-dynload/cStringIO.so: undefined > symbol:PyObject_SelfIter > > I have python-2.3.3-88.9.x86 installed on my machine. > Why is this error coming? how can I resolve this undefined symbol? > Do I need to import anything before this? Workaround to avoid this problem is in another post named "PyImport_ImportModule("cStringIO") failure with undefined symbol Options". From nytrokiss at gmail.com Wed Jan 23 14:10:46 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 23 Jan 2008 20:10:46 +0100 Subject: Stripping whitespace In-Reply-To: <5vphe6F1njt09U1@mid.uni-berlin.de> References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> Message-ID: <8a6b8e350801231110n55dfcdaft5ff670c09b0155ef@mail.gmail.com> Using the split method is the easiest! On 23 Jan 2008 19:04:38 GMT, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jan 2008 10:50:02 -0800, ryan k wrote: > > > Hello. I have a string like 'LNAME > > PASTA ZONE'. I want to create a list of those words and > > basically replace all the whitespace between them with one space so i > > could just do lala.split(). Thank you! > > You *can* just do ``lala.split()``: > > In [97]: lala = 'LNAME PASTA ZONE' > > In [98]: lala.split() > Out[98]: ['LNAME', 'PASTA', 'ZONE'] > > Ciao, > Marc 'BlackJack' Rintsch > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com From pavlovevidence at gmail.com Fri Jan 18 14:59:56 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 18 Jan 2008 11:59:56 -0800 (PST) Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. References: <478FAC5A.50206@animats.com> Message-ID: <008e67da-7ad7-4cc5-a9d0-405d89297217@v29g2000hsf.googlegroups.com> On Jan 17, 2:28 pm, John Nagle wrote: > It's possible to use "pickle" for interprocess communication over > pipes, but it's not straightforward. > > First, "pickle" output is self-delimiting. > Each dump ends with ".", and, importantly, "load" doesn't read > any characters after the "." So "pickle" can be used repeatedly > on the same pipe, and one can do repeated message-passing this way. This > is a useful, but undocumented, feature. > > It almost works. > > Pickle's "dump" function doesn't flush output after dumping, so > there's still some data left to be written. The sender has to > flush the underlying output stream after each call to "dump", > or the receiver will stall. The "dump" function probably ought to flush > its output file. But... you can also write multiple pickles to the same file. Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import cPickle >>> f = open('xxx.pkl','wb') >>> cPickle.dump(1,f) >>> cPickle.dump('hello, world',f) >>> cPickle.dump([1,2,3,4],f) >>> f.close() >>> f = open('xxx.pkl','rb') >>> cPickle.load(f) 1 >>> cPickle.load(f) 'hello, world' >>> cPickle.load(f) [1, 2, 3, 4] An automatic flush would be very undesirable there. Best to let those worrying about IPC to flush the output file themselves: which they ought to be doing regardless (either by explicitly flushing or using an unbuffered stream). > It's also necessary to call Pickle's "clear_memo" before each "dump" > call, since objects might change between successive "dump" calls. > "Unpickle" doesn't have a "clear_memo" function. It should, because > if you keep reusing the "Unpickle" object, the memo dictionary > fills up with old objects which can't be garbage collected. > This creates a memory leak in long-running programs. This is all good to know. I agree that this is a good use case for a clear_memo on a pickle unloader. > Then, on Windows, there's a CR LF problem. This can be fixed by > launching the subprocess with > > proc = subprocess.Popen(launchargs, > stdin=subprocess.PIPE, stdout=subprocess.PIPE, > universal_newlines=True) > > Failure to do this produces the useful error message "Insecure string pickle". > Binary "pickle" protocol modes won't work at all in this situation; "universal > newline" translation is compatible, not transparent. On Unix/Linux, this > just works, but the code isn't portable. I would think a better solution would be to use the -u switch to launch the subprocess, or the PYTHONUNBUFFERED environment variable if you want to invoke the Python script directly. It opens up stdin and stdout in binary, unbuffered mode. Using "univeral newlines" in a non-text format seems like it's not a good idea. For text-format pickles it'd be the right thing, of course. > Incidentally, in the subprocess, it's useful to do > > sys.stdout = sys.stderr > > after setting up the Pickle objects. This prevents any stray print statements > from interfering with the structured Pickle output. Nice idea. > Then there's end of file detection. When "load" reaches an end of > file, it properly raises EOFError. So it's OK to do "load" after > "load" until EOFerror is raised. > > "pickle" and "cPickle" seem to be interchangeable in this application, > so that works. > > It's a useful way to talk to a subprocess, but you need to know all the > issues above to make it work. Thanks: this was an informative post Carl Banks From steve at REMOVE-THIS-cybersource.com.au Fri Jan 4 17:15:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 04 Jan 2008 22:15:01 -0000 Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: <13ntbv51tqcm7c@corp.supernews.com> On Fri, 04 Jan 2008 09:29:50 -0800, bukzor wrote: > Why cant you implement < for complex numbers? Maybe I'm being naive, but > isn't this the normal definition? > a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) No, it is not. Ordered comparisons are not defined for complex numbers. Which is bigger, 4+2j or 2+4j? > How do you implement a set without sorting? With a hash table. Or if you are willing to limit yourself to sets of small integers, you can implement it using bit flipping. E.g. 5 is an element of the set if bit 5 is on. > Are you expecting better than O(log n)? Sure. -- Steven From gherron at islandtraining.com Mon Jan 14 03:44:35 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 14 Jan 2008 00:44:35 -0800 Subject: NotImplimentedError In-Reply-To: <882739.52486.qm@web63705.mail.re1.yahoo.com> References: <882739.52486.qm@web63705.mail.re1.yahoo.com> Message-ID: <478B20F3.7010208@islandtraining.com> hakim ouaras wrote: > Hi, > > I am begining with python, I want to know what is the utility and how > to use the expression "NotImplementedError". > > Thak you for your answers > Hakim > > ------------------------------------------------------------------------ > Never miss a thing. Make Yahoo your homepage. > It's meant to be used to mark a procedure that you intend to write, but have not yet done so. The procedure you have not yet written "raises" that exception to indicate that it is not yet implemented and should not be called: def DoSomething(some, args): """ This procedure will do ... great things someday. """ raise NotImplementedError Then *if* the writer of the application that will call it forgets that's it not yet implemented, and mistakenly tries to call it, an error will be raised. It's not so useful in a small application, or a single person project, but it does become useful if several people are writing different parts (say a library and an application) at the same time. Gary Herron From mlindo at gmail.com Tue Jan 15 16:48:32 2008 From: mlindo at gmail.com (Moises Alberto Lindo Gutarra) Date: Tue, 15 Jan 2008 16:48:32 -0500 Subject: Running Multiple Versions In-Reply-To: <795bedbb-e21e-49b8-856d-bce83a5fced3@f10g2000hsf.googlegroups.com> References: <795bedbb-e21e-49b8-856d-bce83a5fced3@f10g2000hsf.googlegroups.com> Message-ID: <5db591c00801151348g7a100796u7f75bb50ef640aae@mail.gmail.com> that is correct, you can work several version of python in same machine. When you execute some script you only need redirect %PATH% and %PYTHONPATH% 2008/1/15, noel at webeok.org : > Hi, > > We are windows shop with some unix servers as well. We run 2.4.1 and > want to begin migrating to 2.5.1. I am looking for information > dealing with having more than one version of python on a server at one > time. I believe this is called side-by-side and all that is needed to > select a version on a windows box is to set the path to the desired > version of python prior to launching the script. > > Does this sound correct? > > Is there doc online that describes this? > > For windows, has anyone come up with a way to have the script launch > the correct version at load time - similar to the she-bang method used > in unix? > > Thanks > > Noel > -- > http://mail.python.org/mailman/listinfo/python-list > -- Atentamente, Mois?s Alberto Lindo Gutarra Asesor - Desarrollador Java / Open Source From tjreedy at udel.edu Sun Jan 27 19:13:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jan 2008 19:13:27 -0500 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net><60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> Message-ID: "Andr?" wrote in message news:7dcc86da-6ed7-48ec-9a9e-ada5574ae06e at v17g2000hsa.googlegroups.com... If one goes back to the original idea instead, the decision of using automatic assignment should depend on the signature of the __init__ function. Here's an implementation (using "_" instead of "." as it would lead to a syntax error): from functools import * from inspect import * def autoassign(_init_): @wraps(_init_) def _autoassign(self, *args, **kwargs): argnames, _, _, _ = getargspec(_init_) for name, value in zip(argnames[1:], args): if name.startswith("_"): setattr(self, name[1:], value) _init_(self, *args, **kwargs) return _autoassign class Test(object): @autoassign def __init__(self, _foo, _bar, baz): print 'baz =', baz t = Test(1, 2, 3) print t.foo print t.bar print t.baz #== the output is baz = 3 1 2 Traceback (most recent call last): File "/Users/andre/CrunchySVN/branches/andre/src/tools_2k.py", line 24, in exec_code exec code in local_dict File "User's code", line 23, in AttributeError: 'Test' object has no attribute 'baz' ================================= I think this version, with this name convention, is nice enough to possibly go in the stdlib if there were an appropriate place for it. Not sure where though. If there were a classtools module.... tjr From S.Mientki-nospam at mailbox.kun.nl Wed Jan 23 10:12:32 2008 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 23 Jan 2008 16:12:32 +0100 Subject: A GUI framework for running simulations In-Reply-To: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com> References: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com> Message-ID: <657f0$47975960$83aef404$1819@news1.tudelft.nl> ram.rachum at gmail.com wrote: > Hello! I am currently working on writing a simulation engine for > special relativity physics. I'm writing it in Python, of course. I'm > doing fine with the engine, but I want a GUI framework in which I > could use it conveniently, and test different setups on it. I'm not so > strong with GUI programming. I looked at Tkinter, I looked at > WxPython, I looked at PythonCard. It all looks pretty daunting. > > My question is, does there exist a GUI package that is intended > specifically for simulations? I saw a program called Golly, which is a > simulation for Conway's Game of Life. Its GUI had most of the features > I needed. For example, you can load a setup, there are "play" and > "stop" buttons, you can change a setup and save it, etc. > > So does anyone know of a general GUI framework for running > simulations? although quit premature, PyLab_Works might be of interest, see some demos here (watch the demo at the bottom first): http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_animations_screenshots.html (you can contact me offline if PyLab_Works looks interesting to you). cheers, Stef Mientki From sjmachin at lexicon.net Sat Jan 12 20:46:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 12 Jan 2008 17:46:02 -0800 (PST) Subject: Is unicode.lower() locale-independent? References: <871w8ni60t.fsf@physik.rwth-aachen.de> <8b781e43-c3c0-4113-a9a1-7351fb377d0d@i3g2000hsf.googlegroups.com> Message-ID: On Jan 13, 9:49 am, Carl Banks wrote: > On Sat, 12 Jan 2008 13:51:18 -0800, John Machin wrote: > > On Jan 12, 11:26 pm, Torsten Bronger > > wrote: > >> Hall?chen! > > >> Fredrik Lundh writes: > >> > Robert Kern wrote: > > >> >>> However it appears from your bug ticket that you have a much > >> >>> narrower problem (case-shifting a small known list of English words > >> >>> like VOID) and can work around it by writing your own > >> >>> locale-independent casing functions. Do you still need to find out > >> >>> whether Python unicode casings are locale-dependent? > > >> >> I would still like to know. There are other places where .lower() is > >> >> used in numpy, not to mention the rest of my code. > > >> > "lower" uses the informative case mappings provided by the Unicode > >> > character database; see > > >> > http://www.unicode.org/Public/4.1.0/ucd/UCD.html > > >> > afaik, changing the locale has no influence whatsoever on Python's > >> > Unicode subsystem. > > >> Slightly off-topic because it's not part of the Unicode subsystem, but > >> I was once irritated that the none-breaking space (codepoint xa0 I > >> think) was included into string.whitespace. I cannot reproduce it on > >> my current system anymore, but I was pretty sure it occured with a > >> fr_FR.UTF-8 locale. Is this possible? And who is to blame, or must my > >> program cope with such things? > > > The NO-BREAK SPACE is treated as whitespace in the Python unicode > > subsystem. As for str objects, the default "C" locale doesn't know it > > exists; otherwise AFAIK if the character set for the locale has it, it > > will be treated as whitespace. > > > You were irritated because non-break SPACE was included in > > string.whiteSPACE? Surely not! It seems eminently logical to me. > > To me it seems the point of a non-breaking space is to have something > that's printed as whitespace but not treated as it. To me it seems the point of a no-break space is that it's treated as a space in all respects except that it doesn't "break". > > > Perhaps > > you were irritated because str.split() ignored the "no-break"? If like > > me you had been faced with removing trailing spaces from text columns in > > databases, you surely would have been delighted that str.rstrip() > > removed the trailing-padding-for-nicer-layout no-break spaces that the > > users had copy/pasted from some clown's website :-) > > > What was the *real* cause of your irritation? > > If you want to use str.split() to split words, you will foil the user who > wants to not break at a certain point. Which was exactly my point -- but this would happen only rarely or not at all in my universe (names, addresses, product descriptions, etc in databases). > > Your use of rstrip() is a lot more specialized, if you ask me. Not very specialised at all in my universe -- a standard transformation that one normally applies to database text is to remove all leading and trailing whitespace, and compress runs of 1 or more whitespace characters to a single normal space. Your comment seems to imply that trailing non-break spaces are significant and should be preserved ... From mani.sabri at gmail.com Mon Jan 28 13:29:35 2008 From: mani.sabri at gmail.com (mani) Date: Mon, 28 Jan 2008 10:29:35 -0800 (PST) Subject: Embeding python with mingw on win32 and python 2.4.4 Message-ID: <563a8060-8d79-4bc8-8306-9a5d77bfae5e@i72g2000hsd.googlegroups.com> Hi I'm bringing up an old story once more! I'm on win32 (winxp sp2) python 2.4.4. mingw gcc version is 3.4.5. msys is in c:\msys. mingw is in c:\mingw and python is in c:\pyton24. there are also python24.lib and libpython24.a in c:\python24\libs. when I try to compile this sample code [1] from msys prompt with command [2] in msys shell I get the results [3]. this subject was discussed a few times over these years and I tried everything in the posts and forums that I found and google could translate with no success. I realy need your suggestion! Regards, Mani [1] Sample code: #include int main(int argc, char *argv[]) { Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } [2] Command: $ g++ -I/c/python24/include -I/c/MinGW/include -L/c/python24/libs -L/ c/ mingw/lib -lpython24 -shared -mwin32 -o p1 p1.o [3] Results: p1.o:p1.cpp:(.text+0x2b): undefined reference to `_imp__Py_Initialize' p1.o:p1.cpp:(.text+0x39): undefined reference to `_imp__PyRun_SimpleString' p1.o:p1.cpp:(.text+0x40): undefined reference to `_imp__Py_Finalize' collect2: ld returned 1 exit status From smriti.sebastuan at gmail.com Wed Jan 9 12:13:09 2008 From: smriti.sebastuan at gmail.com (smriti Sebastian) Date: Wed, 9 Jan 2008 22:43:09 +0530 Subject: centre of mass of protein Message-ID: <22c5c6390801090913w6667560cv809a2e5fc8ad7e5b@mail.gmail.com> hi all, Is there any script or module in python where we can find the centre of mass of protein? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Jan 7 16:32:22 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jan 2008 08:32:22 +1100 Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <87ve65mie1.fsf@benfinney.id.au> MartinRinehart at gmail.com writes: > The best thing about Python is _______. The best thing about Python is its elegance. -- \ "Like the creators of sitcoms or junk food or package tours, | `\ Java's designers were consciously designing a product for | _o__) people not as smart as them." -- Paul Graham | Ben Finney From piet at cs.uu.nl Tue Jan 8 03:48:39 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 08 Jan 2008 09:48:39 +0100 Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> <5uen3rF1f2vjrU1@mid.uni-berlin.de> Message-ID: >>>>> "Diez B. Roggisch" (DBR) wrote: >DBR> So you can also do >DBR> "" + some_object >DBR> However, >DBR> some_object + "" >DBR> or >DBR> 1 + "" >DBR> don't work - the operator is only overloaded on the left argument. There is no problem with 1+"" neither with new Integer(1)+"" in Java. Nor any other object on the left hand side. The + operator is not tied to the left hand side as in C++. if either side is a string and the other side has a toString method it is OK. This is special-cased in the compiler. It is defined in the language definition, not in the library definition. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From oweston at earthlink.net Mon Jan 28 08:42:26 2008 From: oweston at earthlink.net (wes) Date: Mon, 28 Jan 2008 05:42:26 -0800 Subject: Python Genetic Algorithm In-Reply-To: References: Message-ID: <13prmt7khp1gg42@corp.supernews.com> Max, def GeneticNextGen(self): numsets = len(self.WtSets) numwts = len(self.WtSets[0].Lis) self.WtSets.sort(CompByCurrentFitness) index_lis = [] K = 100.0 N = float(numwts) #if RISE(slope) is too high, concentration occurs too fast and #you lose many quickly RISE = -0.01*K RUN = N - 1.0 m = RISE/RUN for i in range( numsets ): x = float(i) numin = int(m * x + K) for k in range(numin): index_lis.append( i ) new_wtset_list = WtSetListClass() while len(new_wtset_list.WtSets) < numsets: #split in a number of placeses splitPoints = [] #empty list of places where dna's are crossed numSplitPoints = random.randint( 2, 4 ) #number of places to cross at(not to hot & not to cold) while len(splitPoints) < numSplitPoints: #get required num of points at random split_pt = random.randint( 0, numwts - 1 ) if split_pt not in splitPoints: splitPoints.append(split_pt) i1 = random.choice( index_lis ) #get two old weight sets at random from a biased list while( 1 ): i2 = random.choice( index_lis ) if i2 <> i1: break wts1 = self.WtSets[ i1 ] wts2 = self.WtSets[ i2 ] list1 = wts1.Lis[0:] #just size new weight sets list2 = wts1.Lis[0:] flip = False #copy into new weight sets from old alternating the for k in range(len(wts1.Lis)): # the source on 2 to 4 flip points if k in splitPoints: flip = not flip if flip: list1[k] = wts2.Lis[k] list2[k] = wts1.Lis[k] else: list1[k] = wts1.Lis[k] list2[k] = wts2.Lis[k] split_pt1 = random.choice(splitPoints) #capture a place to mutate at low probabilty x = random.randint( 0, 1000 ) #.1 % of time mutate at boundry if x == 5: list1[ split_pt1 ] = RandomFloat(LOWWT,HIGHWT) list2[ split_pt1 ] = RandomFloat(LOWWT,HIGHWT) wt = WtSetClass( list1 ) wt.FoldParentFitnesses( wts1,wts2 ) new_wtset_list.WtSets.append( wt ) if len(new_wtset_list.WtSets) < numsets: wt = WtSetClass( list2 ) wt.FoldParentFitnesses( wts1,wts2 ) new_wtset_list.WtSets.append( wt ) x = random.randint(0,10000) if x == 5: new_wtset_list.RandomizeRandomWt() #0.01% of time made an entire new random wt self.WtSets = new_wtset_list.WtSets From roy at panix.com Mon Jan 28 23:01:51 2008 From: roy at panix.com (Roy Smith) Date: Mon, 28 Jan 2008 23:01:51 -0500 Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: In article , "Terry Reedy" wrote: > "Paddy" wrote in message > news:4dc87a25-1d90-4b66-8fa4-d0d41f48344e at i29g2000prf.googlegroups.com... > |I would value the opinion of fellow Pythoneers who have also > | contributed to Wikipedia, on the issue of "Is Python Standardized". > > Depends entirely on the operative meaning of standardized. Formal > standards body? Obviously no. > > Specified in a standard-setting document? Yes. In fact, in someways, > Python is better standardized that C, for instance, in that the Python > standard usefully standardizes some things that the C standard leaved > unstandardized as 'implementation defined'. > > Example 1. Order of evaluation of function arguments. Python: left to > right. C: undefined (and unstandardized), I believe. > > Example 2: Strings for Infinity and Not-A-Number. Python: will standardize > in 2.6 to hide the variation in C implementations (or is Microsoft just > non-compliant here?). But, surely Python has plenty of "implementation defined" aspects. Especially in the libraries. Especially those parts of the libraries which are thin layers on top of operating system services (os and socket come to mind as two highly variable areas). From python.list at tim.thechases.com Mon Jan 28 11:55:38 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 28 Jan 2008 10:55:38 -0600 Subject: referer url In-Reply-To: <0e7fb40e-809c-4979-bbb8-0cd9a7e816c2@t1g2000pra.googlegroups.com> References: <0e7fb40e-809c-4979-bbb8-0cd9a7e816c2@t1g2000pra.googlegroups.com> Message-ID: <479E090A.9020907@tim.thechases.com> > I was wondering, if there is a way to retrieve the referer url with > python (web-based). > I tried this: > > import os > print os.getenv('HTTP_REFERER') > > but it's not working, even thought other http variables do function, > this one is always a None. This could be for any number of reasons, inter alia: 1) you don't specify the environment in which your python code is running. this may not get stashed in the os.getenv(). In Django, it's stashed in request.META.HTTP_REFERER; in CGI, it should be in your os.getenv(); in WebStack, the trans parameter has get_headers()/get_header_values() methods you can use to extract the referer; and in other frameworks, they may toss them elsewhere. 2) the browser is configured to protect the privacy of the browser, and not send a Referer header 3) your server may not be configured to include the HTTP_REFERER environment variable (improbable, but possible) 4) your user(s) are coming from a book-marked link where there is no Referer to be sent -tkc From python.list at tim.thechases.com Thu Jan 3 09:05:07 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 03 Jan 2008 08:05:07 -0600 Subject: reassign to builtin possible !? In-Reply-To: References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> Message-ID: <477CEB93.8000706@tim.thechases.com> >> But you can't alter the values for True/False globally with this. > > Are you sure ? what about the following example ? > Is this also shadowing ? > >>>> import __builtin__ >>>> __builtin__.True = False >>>> __builtin__.True > False It doesn't seem to screw things up globally >>> import __builtin__ >>> t = __builtin__.True >>> __builtin__.True = False >>> __builtin__.False = t >>> True False >>> False True >>> 1 == 1 True >>> import os >>> os.path.isdir('.') True >>> #if they were globally redefined, this would be False >>> #you'd have to actually reference __builtin__.True My thought would be if you do something as daft as redefining/shadowing True and False, you get the headaches that ensue. Fortunately, since Python is explicit, you can trace back through the code and see where the inanity occurred. Additionally, any scoping rules mean that programmer stupidity can't leak too badly outside the scope of the block containing the stupidity. It's the old "DIHWIDT! WDDT!" ("Doctor, it hurts when I do this!", "well don't do that!") syndrome. -tkc From python.list at tim.thechases.com Wed Jan 2 16:42:47 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 02 Jan 2008 15:42:47 -0600 Subject: database query - logic question In-Reply-To: <6A85AD3923D6C348AF108B4A8F459EA201BEFD3B@CIXMX1.compxnet.com> References: <6A85AD3923D6C348AF108B4A8F459EA201BEFD3B@CIXMX1.compxnet.com> Message-ID: <477C0557.6070808@tim.thechases.com> Israel Carr wrote: > Thanks for anyone who takes the time to read this. If I posted to the > wrong list, I apologize and you can disregard. > > I need help with a script to pull data from a postgres database. I'm ok > with the database connection just not sure how to parse the data to get > the results I need. > > I'm running Python 2.4.4. For what it's worth, once I can get my logic > correct I'll be publishing the reports mentioned below via zope for web > clients. > > Here is a small sample of the records in the table: > > name date time status > machine1 01/01/2008 13:00:00 system ok > machine1 01/01/2008 13:05:00 system ok > machine1 01/01/2008 13:10:00 status1 > machine1 01/01/2008 13:10:30 status1 > machine1 01/01/2008 13:11:00 system ok > machine1 01/01/2008 13:16:30 status2 > machine1 01/01/2008 13:17:00 status2 > machine1 01/01/2008 13:17:30 status2 > machine1 01/01/2008 13:18:00 status2 > machine1 01/01/2008 13:18:30 status2 > machine1 01/01/2008 13:19:00 system ok > machine1 01/01/2008 13:24:00 status2 > machine1 01/01/2008 13:24:30 status2 > machine1 01/01/2008 13:25:00 system ok > > I need to report from this data. > The detail report needs to be something like: > machine1 01/01/2008 13:10:00 status1 00:01:30 > machine1 01/01/2008 13:16:30 status2 00:02:30 > machine1 01/01/2008 13:24:00 status2 00:01:00 Well, just for fun of the SQL challenge, I tossed together the following (using sqlite3) SELECT name, Min(ts) as ts, next_ts, status FROM ( SELECT *, ( SELECT ts FROM test WHERE test.name = t.name AND test.ts > t.ts AND test.status = 'system ok' ORDER BY test.ts ASC LIMIT 1) AS next_ts FROM test t WHERE status <> 'system ok' ) with_next GROUP BY name, status, next_ts where my table has "name", "ts" (a timestamp field combo of your "date" and "time" fields, and for sqlite, formatting in "YYYY-MM-DD mm:ss" format) which yields rows with the machine name, the non "system ok" status, the timestamp of the initial event, and the timestamp of the subsequent "system ok" stamp. There's a bit of an underdefined case where you have more than one non-OK status before OK gets reset: 00:10 status1 00:20 status1 00:30 status2 00:40 status ok If this can't happen, it should work fine. If the above can happen, you'll get odd overlaps in your reporting. Since I couldn't find an Interval data type in sqlite, you'd just have to take the "ts" and "next_ts" columns and subtract them to get the interval you want. > and the summary needs to be > machine1 01/01/2008 total 'status1' time = 00:01:30 > machine1 01/01/2008 total 'status2' time = 00:03:30 > _____ > machine1 01/01/2008 total 'non-OK' time = 00:05:00 #this is the > sum of status1 and status2 times While the below doesn't track the changing of the machine, you can follow the basic framework given here. I threw in a couple helper functions to normalize whatever data types ("normalize_status()" and "make_timestamp()") NO_TIME = datetime.datetime(datetime.MINYEAR, 1, 1) OK = 'system ok' normalize_status = lambda s: s.lower() def log(s): print s print '=' * len(s) def make_timestamp(date, time): d = datetime.datetime(*(int(s) for s in date.split('-') + time.split(':'))) return d status_tally = {} last_status = OK last_ts = NO_TIME log('Intervals (your first request)') for i, (machine, date, time, status) in enumerate(fetchall()): ts = make_timestamp(date, time) status = normalize_status(status) if status == OK and last_status <> OK: interval = ts - last_ts print machine, last_status, last_ts, interval if last_status in status_tally: status_tally[last_status] += interval else: status_tally[last_status] = interval last_status = status elif status <> OK and last_status == OK: last_ts = ts last_status = status log('Summary (your 2nd request)') for k,v in status_tally.iteritems(): print k, v log('Grand Total (your 3rd request)') print sum(status_tally.values(), datetime.timedelta(0)) Thanks for the mental exercise. :) -tkc From qgallet at gmail.com Thu Jan 17 07:32:53 2008 From: qgallet at gmail.com (Quentin Gallet-Gilles) Date: Thu, 17 Jan 2008 13:32:53 +0100 Subject: Loop in a loop? In-Reply-To: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <8b943f2b0801170432o5016ef9i20eedf80a50e3479@mail.gmail.com> Hi, I'd consider using zip : >>> array1 = ['one','two','three','four'] >>> array2 = ['a','b','c','d'] >>> zip(array1, array2) [('one', 'a'), ('two', 'b'), ('three', 'c'), ('four', 'd')] >>> for one, two in zip(array1, array2): ... print one, two ... one a two b three c four d >>> HTH, Quentin On Jan 17, 2008 1:21 PM, Sacred Heart wrote: > Hi, > I'm new to Python and have come across a problem I don't know how to > solve, enter com.lang.python :) > > I'm writing some small apps to learn the language, and I like it a lot > so far. > > My problem I've stumbled upon is that I don't know how to do what I > want. I want to do a loop in a loop. I think. > > I've got two arrays with some random stuff in, like this. > > array1 = ['one','two','three','four'] > array2 = ['a','b','c','d'] > > I want to loop through array1 and add elements from array2 at the end, > so it looks like this: > > one a > two b > three c > four c > > I'm stuck. I know how to loop through the arrays separatly and print > them, but both at the same time? Hmmm. > > A push in the right direction, anyone? > > R, > SH > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vlastimil.brom at gmail.com Tue Jan 1 12:14:22 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 1 Jan 2008 18:14:22 +0100 Subject: WXPython - Using inline images In-Reply-To: <2adc542f0712310615na782e58vc9710c4bfab1edf4@mail.gmail.com> References: <2adc542f0712310615na782e58vc9710c4bfab1edf4@mail.gmail.com> Message-ID: <9fdb569a0801010914s6a3abf97xcfd3416d056f2c33@mail.gmail.com> 2007/12/31, Sick Monkey : ... Is there anyway WXPython can just use the inline image without having to create a physical copy? I know this can be done in TKinter using inline gifs, but was wondering if anyone knew of a clever way to do this in WXPython? ... I think, you can use a stream and wx.ImageFromStream for that see the wxPython Demo ...\demo\images.py for some examples. Greetings, Vlasta -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Jan 8 08:44:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 Jan 2008 14:44:52 +0100 Subject: use fileinput to read a specific line In-Reply-To: <13o6tldft8suj83@corp.supernews.com> References: <6f2db44c-2641-47cb-ab24-4177ccc96d6e@m77g2000hsc.googlegroups.com> <13o637afk4mql0c@corp.supernews.com> <36e49a53-8e56-4847-a792-5032ea204a8e@l6g2000prm.googlegroups.com> <13o6tldft8suj83@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > Python guarantees[1] that files will be closed, but doesn't specify when > they will be closed. I understand that Jython doesn't automatically close > files until the program terminates, so even if you could rely on the ref > counter to close the files in CPython, it won't be safe to do so in > Jython. From what I can tell, Java's GC automatically closes file streams, so Jython will behave pretty much like CPython in most cases. I sure haven't been able to make Jython run out by file handles by opening tons of files and discarding the file objects without closing them. Has anyone? From ncoghlan at gmail.com Tue Jan 1 00:06:53 2008 From: ncoghlan at gmail.com (NickC) Date: Mon, 31 Dec 2007 21:06:53 -0800 (PST) Subject: getting n items at a time from a generator References: <5657aa68-cbc4-4285-86e8-91ddd317260d@q77g2000hsh.googlegroups.com> <05e5f3ef-9930-4ad5-af88-2f08594568aa@j20g2000hsi.googlegroups.com> Message-ID: On Dec 27 2007, 11:31 pm, Kugutsumen wrote: > On Dec 27, 7:24 pm, Terry Jones wrote: > > > > > >>>>> "Kugutsumen" == Kugutsumen writes: > > > Kugutsumen> On Dec 27, 7:07 pm, Paul Hankin wrote: > > > >> On Dec 27, 11:34 am, Kugutsumen wrote: > > > >> > I am relatively new the python language and I am afraid to be missing > > >> > some clever construct or built-in way equivalent to my 'chunk' > > >> > generator below. > > > Kugutsumen> Thanks, I am going to take a look at itertools. I prefer the > > Kugutsumen> list version since I need to buffer that chunk in memory at > > Kugutsumen> this point. > > > Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.) p705 > > > def chop(iterable, length=2): > > return izip(*(iter(iterable),) * length) > > > Terry > > [snip code] > > > Try this instead: > > > import itertools > > > def chunk(iterator, size): > > # I prefer the argument order to be the reverse of yours. > > while True: > > chunk = list(itertools.islice(iterator, size)) > > if chunk: yield chunk > > else: break > > Steven, I really like your version since I've managed to understand it > in one pass. > Paul's version works but is too obscure to read for me :) > > Thanks a lot again. To work with an arbitrary iterable, it needs an extra line at the start to ensure the iterator items are consumed correctly each time around the loop. It may also be better to ensure the final item is the same length as the other items - if that isn't the case (you want to know where the data really ends) then leave out the parts relating to adding the padding object. import itertools def chunk(iterable, size, pad=None): iterator = iter(iterable) padding = [pad] while True: chunk = list(itertools.islice(iterator, size)) if chunk: yield chunk + (padding*(size-len(chunk))) else: break Cheers, Nick. From S.Mientki-nospam at mailbox.kun.nl Thu Jan 17 11:19:56 2008 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 17 Jan 2008 17:19:56 +0100 Subject: How to create graphs an embed them in GUI? In-Reply-To: References: Message-ID: <5967b$478f802b$83aef404$8664@news1.tudelft.nl> Heiko Niedermeyer wrote: > Sorry for the fuzzy subject... > > Currently I'm writing a little programm to extract some chemical > information out of a text file, and then present it in a pleasant way. > The Extraction works so far, so now the presentation will be next. > > As I'm learning Python from scratch, I don't care wether to use (=learn) > TKinter or PyQt or whatever, I just need some advice, which suits my > needs best. > It would be nice to have the programm working under win and linux > (shouldn't be a big Problem) and my requirements concerning the standard > elements should be met by almost every framework. > My problem is, that I want to add graph (simple, line connected X,Y- > scatter plots) and if possible the 3D representation of atoms in a > molecule (-> coloured spheres in space). > I think it would take me years to program those by myself, so I would ne > ready to use packages, if available. > Long story short: Are there packages that could do this, and does it > matter which GUI I want to embed them in? I think "Vision" (formerly Viper)is exactly what you are looking for. If not look at VTK. cheers, Stef > > best wishes From deets at nospam.web.de Wed Jan 16 14:28:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jan 2008 20:28:47 +0100 Subject: Interesting Thread Gotcha In-Reply-To: References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> <5v70v9F1kmtinU1@mid.uni-berlin.de> Message-ID: <5v747jF1lc8buU1@mid.uni-berlin.de> Dan schrieb: > On Jan 16, 1:33 pm, "Diez B. Roggisch" wrote: >> Dan schrieb: >> >> >> >>> On Jan 16, 11:06 am, "Diez B. Roggisch" wrote: >>>> Hendrik van Rooyen wrote: >>>>> "Dan" wrote: >>>>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) >>>>>> Needs to be >>>>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) >>>>>> Commas are important! >>>>>> -Dan >>>>> Absolutely! - well spotted! >>>>> As the first correct respondent, you win the freedom to spend a week in >>>>> Naboomspruit at your own expense. >>>>> It would have been nice, however, to have gotten something like: >>>>> TypeError - This routine needs a tuple. >>>>> instead of the silent in line calling of the routine in question, >>>>> while failing actually to start a new thread. >>>> You can't prevent the silent inline-calling - otherwise, how would you do >>>> this: >>>> def compute_thread_target(): >>>> def target(): >>>> pass >>>> return target >>>> thread.start_new_thread(compute_thread_target()) >>>> Of course start_new_thread could throw an error if it got nothing callable >>>> as first argument. No idea why it doesn't. >>>> Diez >>> Of course, in his case, having start_new_thread throw an error >>> wouldn't have helped, since he went into an infinite loop while >>> evaluating the parameters for start_new_thread. >>> Would it be possible to have pychecker (or some such) warn that there >>> is an insufficient parameter count to start_new_thread? I guess that >>> would require knowing the type of thread. . . >> What has this to do with the second argument? It's perfectly legal to >> have a function as thread-target that takes no arguments at all, so >> enforcing a second argument wouldn't be helpful - all it would do is to >> force all developers that don't need an argument tuple to pass the empty >> tuple. So there was no insufficient argument count. >> >> And none of these would solve the underlying problem that in python >> expressions are evaluated eagerly. Changing that would mean that you end >> up with a totally new language. >> >> the only thing that could help to a certain extend would be static >> types. Which we don't want here :) >> >> Diez > > It doesn't seem to be legal in my version of python (or the doc): > >>>> import thread >>>> def bat(): > print "hello" > > >>>> thread.start_new_thread(bat) > > Traceback (most recent call last): > File "", line 1, in > thread.start_new_thread(bat) > TypeError: start_new_thread expected at least 2 arguments, got 1 >>>> thread.start_new_thread(bat, ()) > 2256hello Ah, I thought it was optional, as in the threading.Thread(target=..., args=....)-version. Sorry for not looking that up. Then you'd might stand a chance that pychecker can find such a situation - but of course not on a general level, as in the above - that would only work with type-annotations. Diez From software at ginstrom.com Thu Jan 31 01:45:42 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Thu, 31 Jan 2008 15:45:42 +0900 Subject: Has Anyone Worked with Gene Expression Programming??????????????????????????? In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F38021A5D9F@AWMAIL04.belcan.com> Message-ID: <003d01c863d4$e6631990$0203a8c0@MOUSE> > On Behalf Of Daniel Fetchinson > Actually, it turns out I might say I'm a world known expert > of Gene Expression Programming. > The only thing is that some higher powers are preventing me > from telling you about it. > I'm really sorry, I hope you understand. Please don't ask > questions. It's not safe to know too much about this stuff. > One day, my son, you'll understand. You'll understand. The first rule of Gene Expression Programming is - you do not talk about Gene Expression Programming. Regards, Ryan Ginstrom From cokofreedom at gmail.com Mon Jan 21 02:59:38 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Sun, 20 Jan 2008 23:59:38 -0800 (PST) Subject: Bug in __init__? References: <88580064-3590-471e-8036-a631dd5a38b4@i3g2000hsf.googlegroups.com> Message-ID: <50ed76e4-f865-4821-935f-310c96b0ecb9@e23g2000prf.googlegroups.com> Is there no way of adding a possible warning message (that obviously could be turned off) to warn users of possible problems linked to using mutable types as parameters? Seems to me this could save users a few minutes/hours of headaches and headscratching. (The biggest issue affecting new programmers these days!) From nytrokiss at gmail.com Fri Jan 11 08:37:05 2008 From: nytrokiss at gmail.com (James Matthews) Date: Fri, 11 Jan 2008 14:37:05 +0100 Subject: HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? In-Reply-To: <47872936.9070603@islandtraining.com> References: <7243c2ac-fa22-4b5b-bd8c-34235123ab69@t1g2000pra.googlegroups.com> <47872936.9070603@islandtraining.com> Message-ID: <8a6b8e350801110537j6ba0fddew8571aa71b0b7e5af@mail.gmail.com> Ahh it's good to know that you "love" pointers like everyone else! On Jan 11, 2008 9:30 AM, Gary Herron wrote: > abhishek wrote: > > Hi group any idea on HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? > > > > > > Thank you > > > POINTERS? Heaps? Huh? Ummm, let me think -- those terms *do* sound > vaguely familiar -- from sometime in the deep dark primitive past. > Perhaps from back in my (shudder) C/C++ days -- ya, that's it. > Thankfully, this is Python and the modern era -- we don't use no > stinking POINTERS here. > > Seriously, this group deals with Python. There are no pointers in > Python. Now please, what did you *really* mean to ask? > > Gary Herron > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com From hat at se-162.se.wtb.tue.nl Fri Jan 11 07:18:29 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 11 Jan 2008 13:18:29 +0100 Subject: reading a specific column from file References: Message-ID: On 2008-01-11, cesco wrote: > Hi, > > I have a file containing four columns of data separated by tabs (\t) > and I'd like to read a specific column from it (say the third). Is > there any simple way to do this in Python? > > I've found quite interesting the linecache module but unfortunately > that is (to my knowledge) only working on lines, not columns. > > Any suggestion? the csv module may do what you want. From nikbaer at gmail.com Tue Jan 29 13:56:18 2008 From: nikbaer at gmail.com (nik) Date: Tue, 29 Jan 2008 10:56:18 -0800 (PST) Subject: ISO with timezone References: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Message-ID: Thanks, that does help and now I have: >>> from datetime import datetime, tzinfo, timedelta >>> import time >>> class TZ(tzinfo): ... def utcoffset(self,dt): return timedelta(seconds=time.timezone) ... >>> print datetime(2008,2,29,15,30,11,tzinfo=TZ()).isoformat() 2008-02-29T15:30:11+8:00 But what I want to know now it how to get the actual time into the expression instead of typing the 2008,2,29,15.... So something like: >>> print datetime(time.gmtime(),tzinfo=TZ()).isoformat(), but that doesn't work. I realize that I could do: >>> t = time.gmtime() >>> print datetime(t[0],t[1],t[2],t[3],t[4],t[5],tzinfo=TZ()).isoformat() but I imagine there might be a cleaner way of doing this. Thanks, Nik On Jan 28, 9:10 pm, "Nicholas F. Fabry" wrote: > Hello, nik. > > On Jan 28, 2008, at 21:03, nik wrote: > > > > > Hi, > > > How does one express the time in ISO format with the timezone > > designator? > > > what I want is YYYY-MM-DDThh:mm:ss.sTZD > > >> From the documentation I see: > >>>> from datetime import tzinfo, timedelta, datetime > >>>> class TZ(tzinfo): > > ... def utcoffset(self, dt): return timedelta(minutes=-399) > > ... > >>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') > > '2002-12-25 00:00:00-06:39' > > > and I've also figured out: > >>>> datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3] > > '2008-01-23T11:22:54.130' > > > But can't figure out how to fit them together. > > There is nothing there to 'fit together' - in the first example given, > the datetime object has no time component specified, so it fills in > default vaules of zero. The following should make this clear: > > >>> your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ()) > >>> print your_time > 2008-02-29 15:30:11-05:00 > >>> print your_time.isoformat('T') > 2008-02-29T15:30:11-05:00 > > If you wish to append the NAME of the tzinfo object instead of its > offset, that requires a bit more playing around (along with a properly > defined tzinfo object - check out dateutil or pytz for a concrete > implementation of tzinfo subclasses (i.e. timezones)), but the > following would work: > > >>> print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z') > 2008-02-29T15:30:11 EST > > For details on how the .strftime method works, see Python Standard > Library, Section 14.2. > > I hope this helps! > > Nick Fabry > > > Thank you, > > Nik > > -- > >http://mail.python.org/mailman/listinfo/python-list > From jd1987 at borozo.com Wed Jan 30 02:54:53 2008 From: jd1987 at borozo.com (Joe Demeny) Date: Wed, 30 Jan 2008 02:54:53 -0500 Subject: Form to mail script Message-ID: <200801300254.55107.jd1987@borozo.com> I am looking for a python web form to mail script for a public web site - could you recommend one? -- Joe Demeny From tezzspaceman at gmail.com Wed Jan 23 01:41:33 2008 From: tezzspaceman at gmail.com (TezZ Da Sp@cE MaN) Date: Wed, 23 Jan 2008 12:11:33 +0530 Subject: UNSUBSCRIBE In-Reply-To: <5vme8iF1mqjl6U1@mid.uni-berlin.de> References: <5vme8iF1mqjl6U1@mid.uni-berlin.de> Message-ID: <006801c85d8b$020776a0$061663e0$@com> -----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 Diez B. Roggisch Sent: 22 January 2008 20:22 To: python-list at python.org Subject: Re: isgenerator(...) - anywhere to be found? Jean-Paul Calderone wrote: > On Tue, 22 Jan 2008 15:15:43 +0100, "Diez B. Roggisch" > wrote: >>Jean-Paul Calderone wrote: >> >>> On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" >>> wrote: >>>>For a simple greenlet/tasklet/microthreading experiment I found myself >>>>in the need to ask the question >>>> >>>> [snip] >>> >>> Why do you need a special case for generators? If you just pass the >>> object in question to iter(), instead, then you'll either get back >>> something that you can iterate over, or you'll get an exception for >>> things that aren't iterable. >> >>Because - as I said - I'm working on a micro-thread thingy, where the >>scheduler needs to push returned generators to a stack and execute them. >>Using send(), which rules out iter() anyway. > > Sorry, I still don't understand. Why is a generator different from any > other iterator? Because you can use send(value) on it for example. Which you can't with every other iterator. And that you can utizilize to create a little framework of co-routines or however you like to call it that will yield values when they want, or generators if they have nested co-routines the scheduler needs to keep track of and invoke after another. I'm currently at work and can't show you the code - I don't claim that my current approach is the shizzle, but so far it serves my purposes - and I need a isgenerator() Diez -- http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Thu Jan 3 10:56:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 16:56:45 +0100 Subject: how to use bool In-Reply-To: References: Message-ID: jimgardener at gmail.com wrote: > hi, i have some code where i set a bool type variable and if the value > is false i would like to return from the method with an error msg.. > being a beginner I wd like some help here > > class myclass: > ......... > def mymethod(self): > success=True > msg="all validation OK" > success=validateSthing() > if(success==False): > msg="sthing failed" > return (success,msg) > > dosomeprocessing() > ..... > success=validateSthingelse() > if(success==False): > msg="sthingelse failed" > return (success,msg) > domoreprocessing() > .... > return(success,msg) > > i would like to know if this way of doing this is OK..I have need of > many kinds of validations in this ..is there a better way of doing > this ? to test boolean values, it's usually better to use plain "if" or "if not" statements: if success: ... handle success here ... if not success: ... handle failure here ... to report failures, use exceptions (the raise and try/except statements). see the tutorial for more on this topic. From alainpoint at yahoo.fr Mon Jan 7 08:41:12 2008 From: alainpoint at yahoo.fr (alain) Date: Mon, 7 Jan 2008 05:41:12 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <08f0c528-0619-432a-80a1-569cd9183e09@s12g2000prg.googlegroups.com> On Jan 7, 2:09?pm, MartinRineh... at gmail.com wrote: > I'm a Java guy who's been doing Python for a month now and I'm > convinced that > > 1) a multi-paradigm language is inherently better than a mono-paradigm > language > > 2) Python writes like a talented figure skater skates. > > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is _______. > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > "grace" but I'm not sure I've done enough to choose. Paraphrasing Steve Jobs but in this context: PYTHON = a bycycle for the mind Best regards Alain From duncan.booth at invalid.invalid Mon Jan 21 05:36:45 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jan 2008 10:36:45 GMT Subject: problem with 'global' References: Message-ID: Mel wrote: > oyster wrote: >> why the following 2 prg give different results? a.py is ok, but b.py >> is 'undefiend a' >> I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC >> v.1310 32 bit (Intel)] on win32 >> #a.py >> def run(): >> if 1==2: # note, it always False >> global a >> a=1 >> >> run() >> a >> >> #b.py >> def run(): >> a=1 >> >> run() >> a > > The docs seem to be in > but don't look all that helpful. Why are you reading Python 2.4 docs? Try http://docs.python.org/ref/global.html The first sentence (which hasn't changed since 2.4) describing the global statement seems clear enough to me: "The global statement is a declaration which holds for the entire current code block." From mario at ruggier.org Wed Jan 2 13:28:36 2008 From: mario at ruggier.org (mario) Date: Wed, 2 Jan 2008 10:28:36 -0800 (PST) Subject: unicode(s, enc).encode(enc) == s ? References: <5e49e7e6-f2b3-4c9f-9dec-e5f01f12d59a@e4g2000hsg.googlegroups.com> <4773f0de$0$15825$9b622d9e@news.freenet.de> <7cb20641-ab33-4818-a911-80c684cb9792@q77g2000hsh.googlegroups.com> <4775AC6B.8070109@v.loewis.de> Message-ID: <1310677e-51ec-49f2-9709-196dcc4e1ac9@e4g2000hsg.googlegroups.com> Thanks a lot Martin and Marc for the really great explanations! I was wondering if it would be reasonable to imagine a utility that will determine whether, for a given encoding, two byte strings would be equivalent. But I think such a utility will require *extensive* knowledge about many bizarrities of many encodings -- and has little chance of being pretty! In any case, it goes well beyond the situation that triggered my original question in the first place, that basically was to provide a reasonable check on whether round-tripping a string is successful -- this is in the context of a small utility to guess an encoding and to use it to decode a byte string. This utility module was triggered by one that Skip Montanaro had written some time ago, but I wanted to add and combine several ideas and techniques (and support for my usage scenarios) for guessing a string's encoding in one convenient place. I provide a write-up and the code for it here: http://gizmojo.org/code/decodeh/ I will be very interested in any remarks any of you may have! Best regards, mario From maxerickson at gmail.com Fri Jan 25 18:57:30 2008 From: maxerickson at gmail.com (Max Erickson) Date: Fri, 25 Jan 2008 23:57:30 +0000 (UTC) Subject: a newbie regex question References: <4227b8d4-c2c7-4395-97a3-5aadcec94b7d@p69g2000hsa.googlegroups.com> <880dece00801250545t124745cck6f9be1b887ec57b5@mail.gmail.com> Message-ID: "Dotan Cohen" wrote: > Maybe you mean: > for match in re.finditer(r'\([A-Z].+[a-z])\', contents): > Note the last backslash was in the wrong place. The location of the backslash in the orignal reply is correct, it is there to escape the closing paren, which is a special character: >>> import re >>> s='Abcd\nabc (Ab), (ab)' >>> re.findall(r'\([A-Z].+[a-z]\)', s) ['(Ab), (ab)'] Putting the backslash at the end of the string like you indicated results in a syntax error, as it escapes the closing single quote of the raw string literal: >>> re.findall(r'\([A-Z].+[a-z])\', s) SyntaxError: EOL while scanning single-quoted string >>> max From danielatdaveschool at gmail.com Wed Jan 16 00:19:03 2008 From: danielatdaveschool at gmail.com (danielatdaveschool at gmail.com) Date: Tue, 15 Jan 2008 21:19:03 -0800 (PST) Subject: Image to browser References: <8c014bd1-7040-4ba3-9206-e1567c4a391a@n20g2000hsh.googlegroups.com> Message-ID: On Jan 16, 12:16 am, danielatdavesch... at gmail.com wrote: > Hi, noob here > > Im using mod_python and apache2 using psp for output of page, i open a > file and resize it with the following code > > <% > import Image, util > > fields = util.FieldStorage(req) > filename = fields.getlist('src')[0] > > path = '/var/www/content/' + filename > size = 128, 128 > > im = Image.open(path) > print im.resize(size, Image.ANTIALIAS) > %> > > so for one, I dont think print does much with psp as far as i can > tell, i cant even do a print 'hello world', it has to be a > req.write('hello world'), but i cant req.write the im.resize. The > manual for im.resize states that its return can go ahead and be > streamed via http but I get a blank page when im expecting to see > image characters dumped to my screen. Python doesn't throw up any > errors. Im not sure where else to look or what to do. > > Thanks for any help, > Daniel its worth noting that ive tried using print "Content-Type: image/jpeg\n" before the print im.resize and still no luck From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 30 04:08:04 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 30 Jan 2008 10:08:04 +0100 Subject: Web Interface Recommendations In-Reply-To: References: <45040839-8b1f-40af-9ef5-1be274c6e95f@z17g2000hsg.googlegroups.com> <80d6ce9f-6c8b-412d-a261-cfe480bd0c3b@e10g2000prf.googlegroups.com> Message-ID: <47a03e68$0$5443$426a34cc@news.free.fr> PurpleServerMonkey a ?crit : (snip) > Out of the major frameworks is there one that stands out as being > particularly well suited for what I'm trying to do? > > Django and CherryPy are on the short list so I'll give them a detailed > look although Pylons does sound rather interesting as well. I guess you'll have to try them out to find the one that best match your needs and personal preferences. Mostly: - CherryPy is more of a web application server than a framework per-se: it's it's own HTTP server - which might or not be a good thing -, and only deals with the "controler" part of the MVC triad. - Django is by now a mostly mature MVC framework, with more than a couple years of production use on quite a lot of sites and applications, good documentation and a somewhat large and active community. OTHO, it's a very opiniated (and somewhat monolithic) framework, with most parts of the stack (ORM, forms validation, template system etc) built specifically for this framework (which was probably the sensible thing to do by the time), so it's perhaps the less flexible of the three. - Pylons is IMHO very promising: wsgi from bottom to top, very flexible, good default components choice (paste / Routes / SQLAlchemy / Mako / FormEncode) but let you swap what you want in and out, and FWIW I've seen so far a very sound architecture. FWIW, next Turbogears major version will switch from CherryPy to Pylons. OTHO, it's still far from being as mature and documented as Django. My 2 cents... From kyosohma at gmail.com Fri Jan 4 16:58:49 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 4 Jan 2008 13:58:49 -0800 (PST) Subject: Skill Resume Achievements, What Good Goes Here? References: <724e4836-d895-4210-972d-dd8f861902df@l1g2000hsa.googlegroups.com> Message-ID: <7c505881-f8ff-4ef9-8b08-7160791233c4@k39g2000hsf.googlegroups.com> On Jan 4, 3:06 pm, apatheticagnostic wrote: > On Jan 2, 11:31 am, kyoso... at gmail.com wrote: > > > > > On Jan 2, 9:59 am, vbgunz wrote: > > > > I spent some time working on a skill resume, the kind of resume > > > college students put together and realized, I am not in college and > > > everything I learned was self-taught. Of course I would like some real > > > world achievements but don't consider throw-away code an achievement > > > and am failing to really see any. I don't even wish to entertain the > > > thought of lying about anything. > > > > What are some achievements an employer may be looking for in someone > > > willing to start at ground level, entry level, intern, etc? What are > > > some real world achievements every n00b will need under his/her belt > > > in order to be taken seriously? > > > Internships are always a good thing to have. If you've contributed to > > open source projects, I'd put that on there. If you're applying for > > some kind of programming job, they'll probably want to see some of > > your code, know what home-brewed projects you've done and how long > > they took to complete, issues you ran into, etc. > > > That might get you started anyway. > > > Mike > > As someone else who's self-educated and curious about this, would > listing canonical comp-sci books that you've gone through on your own > and understood be a reasonable thing to mention? For example, SICP, > PLAI, etc? I should mention that it's certainly not hopeless. My boss is self- taught and so is our webmaster...you'll probably just have to start somewhere low on the ladder. Such as small businesses like computer repair shops or local ISPs where you can show your stuff. Mike From george.sakkis at gmail.com Tue Jan 22 21:32:22 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 22 Jan 2008 18:32:22 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Jan 22, 1:34 pm, Paddy wrote: > On Jan 22, 5:34 am, George Sakkis wrote: > > > > > On Jan 22, 12:15 am, Paddy wrote: > > > > On Jan 22, 3:20 am, Alan Isaac wrote:> I want to generate sequential pairs from a list. > > > <> > > > > What is the fastest way? (Ignore the import time.) > > > > 1) How fast is the method you have? > > > 2) How much faster does it need to be for your application? > > > 3) Are their any other bottlenecks in your application? > > > 4) Is this the routine whose smallest % speed-up would give the > > > largest overall speed up of your application? > > > I believe the "what is the fastest way" question for such small well- > > defined tasks is worth asking on its own, regardless of whether it > > makes a difference in the application (or even if there is no > > application to begin with). > > Hi George, > You need to 'get it right' first. For such trivial problems, getting it right alone isn't a particularly high expectation. > Micro optimizations for speed > without thought of the wider context is a bad habit to form and a time > waster. The OP didn't mention anything about the context; for all we know, this might be a homework problem or the body of a tight inner loop. There is this tendency on c.l.py to assume that every optimization question is about a tiny subproblem of a 100 KLOC application. Without further context, we just don't know. > If the routine is all that needs to be delivered and it does not > perform at an acceptable speed then find out what is acceptable > and optimise towards that goal. My questions were set to get > posters to think more about the need for speed optimizations and > where they should be applied, (if at all). I don't agree with this logic in general. Just because one can solve a problem by throwing a quick and dirty hack with quadratic complexity that happens to do well enough on current typical input, it doesn't mean he shouldn't spend ten or thirty minutes more to write a proper linear time solution, all else being equal or at least comparable (elegance, conciseness, readability, etc.). Of course it's a tradeoff; spending a week to save a few milliseconds on average is usually a waste for most applications, but being a lazy keyboard banger writing the first thing that pops into mind is not that good either. George From paul at boddie.org.uk Tue Jan 22 11:48:40 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 22 Jan 2008 08:48:40 -0800 (PST) Subject: Problem with processing XML References: <13pbudgks88rcf3@corp.supernews.com> Message-ID: On 22 Jan, 15:11, John Carlyle-Clarke wrote: > > I wrote some code that works on my Linux box using xml.dom.minidom, but > it will not run on the windows box that I really need it on. Python > 2.5.1 on both. > > On the windows machine, it's a clean install of the Python .msi from > python.org. The linux box is Ubuntu 7.10, which has some Python XML > packages installed which can't easily be removed (namely python-libxml2 > and python-xml). I don't think you're straying into libxml2 or PyXML territory here... > I have boiled the code down to its simplest form which shows the problem:- > > import xml.dom.minidom > import sys > > input_file = sys.argv[1]; > output_file = sys.argv[2]; > > doc = xml.dom.minidom.parse(input_file) > file = open(output_file, "w") On Windows, shouldn't this be the following...? file = open(output_file, "wb") > doc.writexml(file) > > The error is:- > > $ python test2.py input2.xml output.xml > Traceback (most recent call last): > File "test2.py", line 9, in > doc.writexml(file) > File "c:\Python25\lib\xml\dom\minidom.py", line 1744, in writexml > node.writexml(writer, indent, addindent, newl) > File "c:\Python25\lib\xml\dom\minidom.py", line 814, in writexml > node.writexml(writer,indent+addindent,addindent,newl) > File "c:\Python25\lib\xml\dom\minidom.py", line 809, in writexml > _write_data(writer, attrs[a_name].value) > File "c:\Python25\lib\xml\dom\minidom.py", line 299, in _write_data > data = data.replace("&", "&").replace("<", "<") > AttributeError: 'NoneType' object has no attribute 'replace' > > As I said, this code runs fine on the Ubuntu box. If I could work out > why the code runs on this box, that would help because then I call set > up the windows box the same way. If I encountered the same issue, I'd have to inspect the goings-on inside minidom, possibly using judicious trace statements in the minidom.py file. Either way, the above looks like an attribute node produces a value of None rather than any kind of character string. > The input file contains an block which is what actually > causes the problem. If you remove that node and subnodes, it works > fine. For a while at least, you can view the input file at > http://rafb.net/p/5R1JlW12.html The horror! ;-) > Someone suggested that I should try xml.etree.ElementTree, however > writing the same type of simple code to import and then write the file > mangles the xsd:schema stuff because ElementTree does not understand > namespaces. I'll leave this to others: I don't use ElementTree. > By the way, is pyxml a live project or not? Should it still be used? > It's odd that if you go to http://www.python.org/and click the link > "Using python for..." XML, it leads you to http://pyxml.sourceforge.net/topics/ > > If you then follow the download links to > http://sourceforge.net/project/showfiles.php?group_id=6473 you see that > the latest file is 2004, and there are no versions for newer pythons. > It also says "PyXML is no longer maintained". Shouldn't the link be > removed from python.org? The XML situation in Python's standard library is controversial and can be probably inaccurately summarised by the following chronology: 1. XML is born, various efforts start up (see the qp_xml and xmllib modules). 2. Various people organise themselves, contributing software to the PyXML project (4Suite, xmlproc). 3. The XML backlash begins: we should all apparently be using stuff like YAML (but don't worry if you haven't heard of it). 4. ElementTree is released, people tell you that you shouldn't be using SAX or DOM any more, "pull" parsers are all the rage (although proponents overlook the presence of xml.dom.pulldom in the Python standard library). 5. ElementTree enters the standard library as xml.etree; PyXML falls into apparent disuse (see remarks about SAX and DOM above). I think I looked seriously at wrapping libxml2 (with libxml2dom [1]) when I experienced issues with both PyXML and 4Suite when used together with mod_python, since each project used its own Expat libraries and the resulting mis-linked software produced very bizarre results. Moreover, only cDomlette from 4Suite seemed remotely fast, and yet did not seem to be an adequate replacement for the usual PyXML functionality. People will, of course, tell you that you shouldn't use a DOM for anything and that the "consensus" is to use ElementTree or lxml (see above), but I can't help feeling that this has a damaging effect on the XML situation for Python: some newcomers would actually benefit from the traditional APIs, may already be familiar with them from other contexts, and may consider Python lacking if the support for them is in apparent decay. It requires a degree of motivation to actually attempt to maintain software providing such APIs (which was my solution to the problem), but if someone isn't totally bound to Python then they might easily start looking at other languages and tools in order to get the job done. Meanwhile, here are some resources: http://wiki.python.org/moin/PythonXml Paul [1] http://www.python.org/pypi/libxml2dom From paddy3118 at googlemail.com Mon Jan 28 01:40:27 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 27 Jan 2008 22:40:27 -0800 (PST) Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <7xbq76pva9.fsf@ruckus.brouhaha.com> <7x1w82xymd.fsf@ruckus.brouhaha.com> Message-ID: On Jan 28, 6:17 am, Paul Rubin wrote: > Paddy writes: > > Given the complexity of current microprocessors i'm guessing that > > their previous testing methods would be too good to just junk in > > totality because the FDIV bug was not found. Similarly if they were > > not using formal methods then it makes sense to add it too your > > arsenal; and unfortunately it takes a mistake like that to allow > > different methods to be explored and incorporated. > > Fair enough. My main issue was against the notion that random testing > is the only thing necessary. Sorry Paul if I may have given that impression, its just that when you bring in random testing to a design that until then had only directed tests you can see the bug rate jump up! Think of a hysteresis curve that has gone flat with current testing methods as not many new bugs are being found; add a new test methodology - random testing and you get a new hysteresis curve added as bugs found jump up again. We eventually ship the chip and get awarded by one of our large customers for quality - which happened - so thats why I put it forward. - Paddy. From max at alcyone.com Tue Jan 1 23:40:16 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 Jan 2008 20:40:16 -0800 Subject: os.tmpfile() In-Reply-To: References: Message-ID: jyoung79 at kc.rr.com wrote: > Can anyone elaborate on how 'os.tmpfile()' works? I was thinking it would create some sort of temporary file I could quickly add text too and then when I was finished would automatically get rid of it. Here's my questions: ... > Can you actually 'write' to this file? And if so, do you have to 'close()' it when you're done with it? Thanks for your help with this... I'm still learning Python and haven't been able to find out much about this in the documentation or on-line. It's a file. You read strings from it and write strings to it. It isn't a string itself. Given that what you're trying to do doesn't make any sense, it's hard to know where to begin to identify what's confusing you. -- 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 And though the odds say improbable / What do they know -- Stevie Wonder From gherzig at fmed.uba.ar Mon Jan 28 10:26:32 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Mon, 28 Jan 2008 12:26:32 -0300 Subject: sharing objects between classes Message-ID: <479DF428.4070902@fmed.uba.ar> Hi all. Im wondering the way to share a database connection between some classes: So far, i came up with a simple class schema, where each class means each different relation, i mean i have the follow classes class Database(object): ## make the connection self.conn = make_conn(....) class Table(object): def get_fields: .... And at this point i dont know how to use the Database.conn attribute, since the get_fields method will perform a query over the given database. At first, i just define the Table class as a inner class of Database, but if i try a class Database(object): ## make the connection def __init__(self): self.conn = sql_connect(....) self.table = Table('foo') class Table(object): ## inner class def get_fields(self, name): .... I get a "NameError: global name 'Table' is not defined". So, which would the right pattern to use here? Using a global module? I dont know why, but i dont like that idea too much. Any comments will be appreciated! Thanks! Gerardo From gagsl-py2 at yahoo.com.ar Tue Jan 22 22:13:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 01:13:31 -0200 Subject: Extract value from a attribute in a string References: Message-ID: En Tue, 22 Jan 2008 23:45:22 -0200, escribi?: > I am looking for some help in reading a large text tile and extracting > a value from an attribute? so I would need to find name=foo and > extract just the value foo which can be at any location in the string. > The attribute name will be in almost each line. In this case a regular expression may be the right tool. See http://docs.python.org/lib/module-re.html py> import re py> text = """ok name=foo ... in this line name=bar but ... here you get name = another thing ... is this what you want?""" py> for match in re.finditer(r"name\s*=\s*(\S+)", text): ... print match.group(1) ... foo bar another -- Gabriel Genellina From greg.johnston at gmail.com Wed Jan 23 10:41:47 2008 From: greg.johnston at gmail.com (Greg Johnston) Date: Wed, 23 Jan 2008 07:41:47 -0800 (PST) Subject: PyGTK, Glade, and ComboBoxEntry.append_text() References: <4066a33f-6293-48e3-a48c-66af699d0eb9@i29g2000prf.googlegroups.com> Message-ID: <03d13e0b-9cf4-47e1-95c4-082ffd6dc76d@e4g2000hsg.googlegroups.com> On Jan 21, 5:44?pm, Greg Johnston wrote: > Hey all, > > I'm a relative newbie to Python (switched over from Scheme fairly > recently) but I've been usingPyGTKand Glade to create an interface, > which is a combo I'm very impressed with. > > There is, however, one thing I've been wondering about. It doesn't > seem possible to modifyComboBoxEntrychoice options on the fly--at > least with append_text(), etc--because they were not created with > gtk.combo_box_entry_new_text(). Basically, I'm wondering if there's > any way around this. > > Thank you, > Greg Johnston P.S. If anyone reads this later wondering how to do it, all you need to do is "prime" the ComboBoxEntry with a blank entry in Glade. You can then use append_text(), insert_text(), etc. on the object, as well as remove_text(0) to get rid of your blank entry. From rtw at freenet.co.uk Thu Jan 3 11:48:24 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Thu, 03 Jan 2008 10:48:24 -0600 Subject: Who's to blame? References: <92dfc2fc-0677-43c0-b34f-4f240fa40205@e4g2000hsg.googlegroups.com> Message-ID: Nicola Musatti wrote in news:92dfc2fc-0677-43c0-b34f-4f240fa40205 @e4g2000hsg.googlegroups.com in comp.lang.python: Note there is a wxpython mailinglist/newsgroup: news:gmane.comp.python.wxpython [snip] > problem lies in the fact that apparently ShowModal() does not return > when either the Yes or the No buttons are pressed. Curiously, if you > change the Yes and No buttons with the OK and Cancel ones that are > currently commented everything works as expected. This is because the wx.Dialog class has handlers for the wxID_OK and wxID_CANCEL button identifiers, IIRC in windows the MS supplied dialog procedure behaves this way. > > As the sbs_test_xrc.py file below is automatically generated by > wxPython 2.8.6.1's XRCed tool from a XRC file which in turn is > generated by wxFormBuilder (http://wxformbuilder.org/), I really cant > figure out to whom I should report this problem, assuming I'm not > missing some obvious mistake of mine, that is. > class MainFrame(sbs_test_xrc.xrcMainFrame): > def __init__(self, parent): > sbs_test_xrc.xrcMainFrame.__init__(self, parent) > self.button.Bind(wx.EVT_BUTTON, self.OnButton) First you can make the dialog a member, you are showing and hiding it so there is no need to create a new one every time OnButton is fired. self.dialog = sbs_test_xrc.xrcDialog(self) # now replace the defaults of ID_OK and ID_CANCEL # self.dialog.SetAffirmativeId( wxID_YES ) self.dialog.SetEscapeId( wxID_NO ) Alternativly you could derive from xrcDialog as you are with xrcMainFrame and do the above in the derived classes __init__. > def OnButton(self, event=None): > d = sbs_test_xrc.xrcDialog(self) > ## if d.ShowModal() == wx.ID_OK: > if d.ShowModal() == wx.ID_YES: > self.Close() > http://www.wxpython.org/docs/api/wx.Dialog-class.html Rob. -- http://www.victim-prime.dsl.pipex.com/ From anne.nospam01 at wangnick.de Mon Jan 7 17:29:51 2008 From: anne.nospam01 at wangnick.de (anne.nospam01 at wangnick.de) Date: Mon, 7 Jan 2008 14:29:51 -0800 (PST) Subject: What is the encoding of __file__? References: <736ae822-54a9-4ee6-91fe-92c2c6eb43db@21g2000hsj.googlegroups.com> <4782A255.8070604@v.loewis.de> Message-ID: On 7 Jan., 23:06, "Martin v. L?wis" wrote: > > can someone quickly tell me what the encoding of __file__ is? I can't > > find it in the documentation. > > > BTW, I'm using Python 2.5.1 on WIndows XP and Vista. > > It's platform-specific - the same encoding that is used for file names > (i.e. sys.getfilesystemencoding()). On Windows, it will be "mbcs", which > in turn is installation-specific - on Western European/US installations, > it's "windows-1252". Thanks, I'll then use sys.getfilesystemencoding() to decode _file__ and re-encode into utf-8, which is the default encoding of all strings in our software, as we deal a bit with Chinese terms. Windows-1252 on my box. I just created a directory containing Chinese characters (on Vista), and whoa, files opened with IDLE are empty, import doesn't find modules in that directory. Of course Windows-1252 can't encode these ... But I understand that Python 3 will clean this up? Kind regards, Sebastian From bladedpenguin at gmail.com Sat Jan 26 00:17:01 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 21:17:01 -0800 (PST) Subject: How can I use the up and down, left and right arrow keys to control a Python Pgm References: Message-ID: On Jan 25, 10:48 pm, "jitrowia" wrote: > I was wondering what kind of python code I would need to enable me to > use the up and down, left and right arrow keys to control software > programming decisions within a Python Program. > > Any direction and advice would be greatly appreciated, > > Thank You, > Rodney "software programming decisions" is awfully vague. COuld oyu narrow down exactly what you want to do? From brkict at gmail.com Thu Jan 31 10:16:47 2008 From: brkict at gmail.com (glomde) Date: Thu, 31 Jan 2008 07:16:47 -0800 (PST) Subject: Bug/Patch: Problem with xml/__init__.py when using freeze.py Message-ID: <36e7c2d1-27f0-47c6-9527-14eb3353b0db@f47g2000hsd.googlegroups.com> Hi, I tried to do freeze.py for my script that uses ElementTree. But got the this error: File "/usr/lib/python2.5/xml/__init__.py", line 45, in _xmlplus.__path__.extend(__path__) AttributeError: 'str' object has no attribute 'extend' The reason seems that _xmlplus.__path__ is a string after freeze.py. I fixed it by changing the import to: try: _xmlplus.__path__.extend(__path__) sys.modules[__name__] = _xmlplus except AttributeError: pass This might not be the correct solution but it works for me. I do not really now how the __path__ variable works in a freezed environment. Best regards /T From konrad at isg.cs.uni-magdeburg.de Wed Jan 30 03:21:28 2008 From: konrad at isg.cs.uni-magdeburg.de (=?ISO-8859-1?Q?Konrad_M=FChler?=) Date: Wed, 30 Jan 2008 09:21:28 +0100 Subject: Removing hidden files and folders with python ... Message-ID: Hi, I try to delete a whole directory-tree using shutil.rmtree(...) But there are always the hidden files and folders (e.g. from the svn .svn) left. How can I delete -all- files and folders (also the hidden) with python? Many Thanks Konrad From nikolaskaralis at gmail.com Wed Jan 2 09:22:21 2008 From: nikolaskaralis at gmail.com (Nikolas Karalis) Date: Wed, 2 Jan 2008 16:22:21 +0200 Subject: cloud computing (and python)? In-Reply-To: <3693eb2d-9034-4f30-8d8f-84376bc6d521@e25g2000prg.googlegroups.com> References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <7yBej.30029$CN4.18224@news-server.bigpond.net.au> <3693eb2d-9034-4f30-8d8f-84376bc6d521@e25g2000prg.googlegroups.com> Message-ID: <85b2e0230801020622x244ea444h2273572dd336e1ee@mail.gmail.com> I read a few things about this on the web, and i still don't get the difference between cloud computing and grid computing... It looks like the same. Nikolas On Jan 2, 2008 3:46 AM, PatrickMinnesota wrote: > On Jan 1, 7:12 pm, Neil Hodgson wrote: > > Cloud computing is mostly about scalability. You do not need to be > > concerned so much about low level infrastructure details such as > > purchasing servers, configuring and maintaining them, hiring space in > > data centres, linking up data centres, etc. It converts a lot of fixed > > costs into lower recurring costs so makes it easier for a start up with > > limited capital to start operating. > > > > There are Python libraries for accessing some of the cloud computing > > services and you can also host Python application code on some services > > that allow code execution. This includes services that can run arbitrary > > code on virtual machines such as EC2 and more restricted computational > > services like Hadoop which can run Jython. > > > > Neil > > I would say that cloud computing to an implementor or company > providing cloud > computing is all about scalability and stuff like S3 and EC3. There > are > other options for this BTW. > > But to the end user, it's about having your data and applications on a > disk > served by a network and server that is somewhere out there on the net > and > accessible from anywhere that you have connectivity. You might travel > with > a laptop, but generally, when in Hong Kong, you'll be screwed if a > chunk of > data is sitting on a disk inside a desktop in your home office and > isn't on > your laptop. With the 'cloud' concept, it wouldn't matter where you > are, > as long as you have a connection to the internet, you can run the apps > and > access the data. > > Issues: and yes, they are big, who has control over the data, is it > being > backed up and protected, and is your private data being mined without > your approval. Oh, > and what happens if you use Zoho's system and they go out of > business? > -- > http://mail.python.org/mailman/listinfo/python-list > -- Nikolas Karalis Applied Mathematics and Physics Undergraduate National Technical University of Athens, Greece http://users.ntua.gr/ge04042 -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at marcher.name Mon Jan 7 15:54:55 2008 From: martin at marcher.name (Martin Marcher) Date: Mon, 07 Jan 2008 21:54:55 +0100 Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: On Monday 07 January 2008 21:25 Dustan wrote: > On Jan 7, 11:40 am, Martin Marcher wrote: >> it's pythonicness. > > "it is pythonicness"??? not all here are native english speakers, but thanks for the correction. I'll try to keep it in mind. -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From fredrik at pythonware.com Wed Jan 9 05:12:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 11:12:31 +0100 Subject: "Canonical" way of deleting elements from lists In-Reply-To: <5ujkbaF1e11ksU1@mid.dfncis.de> References: <5ujkbaF1e11ksU1@mid.dfncis.de> Message-ID: Robert Latest wrote: >>From a list of strings I want to delete all empty ones. This works: > > while '' in keywords: keywords.remove('') > > However, to a long-term C programmer this looks like an awkward way of > accomplishing a simple goal, because the list will have to be re-evaluated > in each iteration. you're using a quadratic algorihm ("in" is a linear search, and remove has to move everything around for each call), and you're worried about the time it takes Python to fetch a variable? > Is there a way to just walk the list once and throw out unwanted > elements as one goes along? creating a new list is always almost the right way to do things like this. in this specific case, filter() or list comprehensions are good choices: keywords = filter(None, keywords) # get "true" items only keywords = [k for k in keywords if k] also see: http://effbot.org/zone/python-list.htm#modifying From gowricp at gmail.com Sun Jan 13 18:44:12 2008 From: gowricp at gmail.com (Gowri) Date: Sun, 13 Jan 2008 15:44:12 -0800 (PST) Subject: converting JSON to string References: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> <13og5g06rvrtefa@corp.supernews.com> Message-ID: <4f5b1f7a-923a-4d68-ab6d-5e019590f02d@k2g2000hse.googlegroups.com> On Jan 12, 2:58 am, Jeroen Ruigrok van der Werven wrote: > -On [20080112 08:38], Gowri (gowr... at gmail.com) wrote: > > >Actually, I have one other problem after all this. I see that if I try > >to construct JSON output as above, it is of the form > >[{'isbn': u'1-56592-724-9', 'title': u'The Cathedral & the Bazaar'}, > >{'isbn': u'1-56592-051-1', 'title': u'Making TeX Work'}] > >The extra 'u' seems to causing syntax error in JavaScript which is not > >able to parse this response string. Any idea how I can fix this? > > JSON does not support Unicode in the sense of allowing raw Unicode codepoints. > Instead JSON uses a \uNNNN scheme to encode Unicode characters (a bit flawed > to limit it to four hexadecimal digits though, it leaves the whole CJK Unified > Ideographs Extension B out of scope.). > > I use simplejson along with lxml/ElementTree for my JSON<>XML needs. > > -- > Jeroen Ruigrok van der Werven / asmodai > ????? ?????? ??? ?? ??????http://www.in-nomine.org/|http://www.rangaku.org/ > Any road leads to the end of the world... Thanks Jeroen. That helped a lot :) From sevengeon at gmail.com Wed Jan 2 07:39:43 2008 From: sevengeon at gmail.com (Geon.) Date: Wed, 2 Jan 2008 04:39:43 -0800 (PST) Subject: how to get playtime ( playback time ) of movie files? Message-ID: <7ab948ea-0ea9-47ab-80ff-73a95a4d958d@d21g2000prf.googlegroups.com> hi.. i want get playtime of movie files ( avi , mpeg , wav , mov etc... ) how to get ?? please help me .. From rasky at develer.com Sun Jan 27 15:15:55 2008 From: rasky at develer.com (Giovanni Bajo) Date: Sun, 27 Jan 2008 20:15:55 GMT Subject: strftime return value encoding (mbcs, locale, etc.) Message-ID: <%D5nj.2630$Xg7.935@tornado.fastwebnet.it> Hello, I am trying to find a good way to portably get the output of strftime() and put it onto a dialog (I'm using PyQt, but it doesn't really matter). The problem is that I need to decode the byte stream returned by strftime () into Unicode. This old bug: http://mail.python.org/pipermail/python-bugs-list/2003- November/020983.html (last comment) mentions that it is "byte string in the locale's encoding". The comment also suggests to use "mbcs" in Windows (which, AFAIK, it's sort of an "alias" encoding for the current Windows codepage), and to find out the exact encoding using locale.getpreferredencoding(). Thus, I was hoping that something like: strftime("%#c", localtime()).decode(locale.getpreferredencoding()) would work... but alas I was reported this exception: LookupError: unknown encoding: cp932 So: what is the correct code to achieve this? Will something like this work: data = strftime("%#c", localtime()) if os.name == "nt": data = data.decode("mbcs") else: data = dada.decode(locale.getpreferredencoding()) Is this the correct way of doing it? (Yes, it sucks). Shouldn't Python automatically alias whatever is returned by locale.getpreferredencoding() to "mbcs", so that my original code works portably? Thanks in advance! -- Giovanni Bajo From stanc at al.com.au Thu Jan 3 02:18:50 2008 From: stanc at al.com.au (Astan Chee) Date: Thu, 03 Jan 2008 18:18:50 +1100 Subject: sending commands in body of HTTP with urllib2 Message-ID: <477C8C5A.7000901@al.com.au> Hi, Im trying to implement the logic from http://www.hypothetic.org/docs/msn/general/http_connections.php to a simple python code using urllib2 and some parts of urllib. Im behind a http proxy that requires authentication that is why Im using urllib2. Im asking for help on how to send commands in a body of a HTTP before requesting for response. What am I doing wrong? I only get the response from the server but my commands never seem to be acknowledged or properly handled. Below is my code: import urllib2 import base64 import urllib USER='user' PASS='pass' proxy_info = {'host' : "proxy.com.au",'port' : 8080} # build a new opener that uses a proxy requiring authorization proxy_support = urllib2.ProxyHandler({"http" : \ "http://%(host)s:%(port)d" % proxy_info}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) user_pass = base64.encodestring('%s:%s' % (urllib.unquote(USER),urllib.unquote(PASS))) authheader = "Basic %s" % user_pass opener.addheaders = [('Accept-Language','en-us'), ('Accept-Encoding','gzip, deflate'), ('Host','gateway.messenger.hotmail.com'), ('Proxy-Connection','Keep-Alive'), ('Connection','Keep-Alive'), ('Pragma','no-cache'), ('Content-Type','application/x-msn-messenger'), ('User-agent','MSMSGS'), ('Accept','*/*'), ('Proxy-authorization',authheader)] # install it urllib2.install_opener(opener) # use it url = 'http://gateway.messenger.hotmail.com/gateway/gateway.dll?Action=open&Server=NS&IP=messenger.hotmail.com' values = 'VER 5 MSNP8 CVR0' f = urllib2.urlopen(url,values) print f.headers print f.read() Thanks for any help! From ioscas at gmail.com Wed Jan 23 08:20:32 2008 From: ioscas at gmail.com (kliu) Date: Wed, 23 Jan 2008 05:20:32 -0800 (PST) Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? References: Message-ID: On Jan 23, 7:39 pm, "A.T.Hofkamp" wrote: > On 2008-01-23, ios... at gmail.com wrote: > > > Hi, I am looking for a HTML parser who can parse a given page into > > a DOM tree, and can reconstruct the exact original html sources. > > Why not keep a copy of the original data instead? > > That would be VERY MUCH SIMPLER than trying to reconstruct a parsed tree back > to original source text. > > sincerely, > Albert Thank u for your reply. but what I really need is the mapping between each DOM nodes and the corresponding original source segment. From meesters at uni-mainz.de Mon Jan 28 13:30:01 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Mon, 28 Jan 2008 19:30:01 +0100 Subject: extending Python - passing nested lists References: <8d3fbe29-f188-4a5b-b249-ba01a3d00320@1g2000hsl.googlegroups.com> Message-ID: Mark Dickinson wrote: > Well, it's pretty clear: you misspelt "length" as "lenght". :) Well, that's not it ;-). (Damn copy & paste plague ...) > > PySequence_Fast doesn't return an array: it returns a PyObject---in > this case, a PyObject corresponding to a Python tuple. That's it. Thanks. Think I just need a different approach. I got completely on the wrong track here. Thanks Christian From dickinsm at gmail.com Mon Jan 28 13:20:33 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 28 Jan 2008 10:20:33 -0800 (PST) Subject: extending Python - passing nested lists References: Message-ID: <8d3fbe29-f188-4a5b-b249-ba01a3d00320@1g2000hsl.googlegroups.com> On Jan 28, 10:10 am, Christian Meesters wrote: > Hi, > > I would like to write a C-extension function for an application of mine. For > this I need to pass a nested list (like: [[a, b, c], [d, e, f], ...], where > all letters are floats) to the C-function. Now, with the code I have the > compiler is complaining: "subscripted value is neither array nor pointer". > Can somebody tell me what's wrong? Well, it's pretty clear: you misspelt "length" as "lenght". :) PySequence_Fast doesn't return an array: it returns a PyObject---in this case, a PyObject corresponding to a Python tuple. As the compiler says, a PyObject is neither an array nor a pointer, so when you write dummy_list[i] the compiler doesn't know what you mean. You probably want to use PySequence_Fast_GET_ITEM. See the documentation at http://docs.python.org/api/sequence.html#l2h-333 Mark From tjreedy at udel.edu Sun Jan 27 20:01:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jan 2008 20:01:17 -0500 Subject: Python Genetic Algorithm References: Message-ID: "Max" wrote in message news:caf75b0d-7ed3-421a-93f8-6f7d90a98923 at p69g2000hsa.googlegroups.com... | In GAs, you operate on a Population of solutions. Each Individual from | the Population is a potential solution to the problem you're | optimizing, and Individuals have what's called a chromosome - a | specification of what it contains. For example, common chromosomes are | bit strings, lists of ints/floats, permutations...etc. I'm stuck on | how to implement the different chromosomes. I have a Population class, | which is going to contain a list of Individuals. Each individual will | be of a certain chromosome. I envision the chromosomes as subclasses | of an abstract Individual class, perhaps all in the same module. I'm | just having trouble envisioning how this would be coded at the | population level. Presumably, when a population is created, a | parameter to its __init__ would be the chromosome type, but I don't | know how to take that in Python and use it to specify a certain class. | | I'm doing something similar with my crossover methods, by specifying | them as functions in a module called Crossover, importing that, and | defining | | crossover_function = getattr(Crossover, "%s_crossover" % xover) | | Where xover is a parameter defining the type of crossover to be used. | I'm hoping there's some similar trick to accomplish what I want to do | with chromosomes - or maybe I'm going about this completely the wrong | way, trying to get Python to do something it's not made for. Any help/ | feedback would be wonderful. 'Python genetic algorithm' returns 25000 hits with Google. But here is what I would do without looking at them. Start with the Individual base class and common methods, some virtual (not implemented). An example of a virtual method would be the crossover(self,other) method, since its implementation depends on the concrete chromosome implementation. Make subclasses with concrete chromosome types (initialized in .__init__). For each, implement the methods that depend on that type. In particular, the mutate(self, args) and crossover(self,other, args) methods. For the Population class, give __init__ an 'individual' parameter and store it as an attribute. If you want, check that it 'issubclass(Individual)'. To add members to the population, call the stored subclass. To operate on the population, write Population methods. There should not depend on the particular chromosome implementations. To operate on the members within the Population methods, call their Individual methods. b = a.mutate(args); c = a.crossover(b, args). I see two ways to deal with scoring the fitness of individuals within a Population instance. Once is to write a particular fitness function, pass it to the Population init to save as an attribute, and then call as needed. The other is to subclass an Individual subclass, give it that funtion fitness method, and pass that subsubclass to Population. The difference is between having Population methods calling self.fitness(some_member) versus some_member.fitness(). I hope this is helpful for getting started. Terry Jan Reedy From JAMoore84 at gmail.com Thu Jan 24 11:44:31 2008 From: JAMoore84 at gmail.com (JAMoore84 at gmail.com) Date: Thu, 24 Jan 2008 08:44:31 -0800 (PST) Subject: Beginner Pyserial Question Message-ID: <93223c7c-c891-424c-bc4f-00d61592663a@l32g2000hse.googlegroups.com> Hi Guys, I have a project where I'd like to save GPS data that is streamed to a Sony Vaio over bluetooth. I can monitor the data stream over Hyper Terminal, but I'd like to use python to capture it as well. I've installed Python 2.5, pyserial 2.2 and the appropriate pywin program (pywin32-210.win32-py2.5.exe). My problem comes when I try to open a serial port. After importing "serial", I issue the following statement: >>> GPS = serial.Serial(0) Traceback (most recent call last): File "", line 1, in GPS = serial.Serial(0) File "C:\Python25\lib\site-packages\serial\serialutil.py", line 156, in __init__ self.open() File "C:\Python25\lib\site-packages\serial\serialwin32.py", line 55, in open raise SerialException("could not open port: %s" % msg) SerialException: could not open port: (2, 'CreateFile', 'The system cannot find the file specified.') I'm not sure where the source of the problem is. I was wondering if someone could recognize what might be be. the Vaio is running XP SP2. Thanks! From george.maggessy at gmail.com Tue Jan 8 01:21:53 2008 From: george.maggessy at gmail.com (George Maggessy) Date: Mon, 7 Jan 2008 22:21:53 -0800 (PST) Subject: Pet Store Message-ID: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com> Hi there, I'm an experience Java developer trying to learn Python. I just finished the Python tutorial on python.org and I'm currently reading the "Learning Python" book. However, if I could find something like a simple web app with some best practices, such as those famous "Java Pet Store" apps, I think that would help me to fill up some gaps in my learning process. Does anybody know any app like that? Cheers, George From matiassurdi at gmail.com Thu Jan 3 11:43:46 2008 From: matiassurdi at gmail.com (Matias Surdi) Date: Thu, 03 Jan 2008 17:43:46 +0100 Subject: Adding a HTTP header to a SOAPpy request Message-ID: Hi, Could anybody tell me which is the easier way to do a SOAP call to a web service wich requires an http header to be present? I can't figure it out. Thanks a lot Some code I'm using: import SOAPpy s = SOAPpy.SOAPProxy("http://10.3.5.128:10560/SERVICES",namespace="http://ws.mysite.com") s.some_method() Thanks a lot. From stanc at al.com.au Thu Jan 3 03:42:51 2008 From: stanc at al.com.au (Astan Chee) Date: Thu, 03 Jan 2008 19:42:51 +1100 Subject: sending commands in body of HTTP with urllib2 In-Reply-To: <477C8C5A.7000901@al.com.au> References: <477C8C5A.7000901@al.com.au> Message-ID: <477CA00B.6010001@al.com.au> Astan Chee wrote: > Hi, > Im trying to implement the logic from > http://www.hypothetic.org/docs/msn/general/http_connections.php to a > simple python code using urllib2 and some parts of urllib. Im behind a > http proxy that requires authentication that is why Im using urllib2. Im > asking for help on how to send commands in a body of a HTTP before > requesting for response. What am I doing wrong? I only get the response > from the server but my commands never seem to be acknowledged or > properly handled. > I've tried a httplib implementation for it, and now it keeps giving me an Error 400 (bad request) / Invalid header name as a response. What am I doing wrong? is the server depreciated? or not working like the document describes it? Thanks again for any help. Below is my code import httplib import base64 import urllib USER='user' PASS='pass' url = 'http://gateway.messenger.hotmail.com/gateway/gateway.dll?Action=open&Server=NS&IP=messenger.hotmail.com' values = 'VER 5 MSNP8 CVR0\r\n' user_pass = base64.encodestring('%s:%s' % (urllib.unquote(USER),urllib.unquote(PASS))) authheader = "Basic %s" % user_pass proxy_authorization='Proxy-authorization: Basic '+user_pass+'\r\n' conn = httplib.HTTPConnection("proxy.com.au", 8080) conn.connect() conn.putrequest("POST", url) conn.putheader('Accept','*/*') conn.putheader('Accept-Language','en-us') conn.putheader('Accept-Encoding','gzip, deflate') conn.putheader('User-agent','MSMSGS') conn.putheader('Host','gateway.messenger.hotmail.com') conn.putheader('Proxy-Connection','Keep-Alive') conn.putheader('Pragma','no-cache') conn.putheader('Content-Type','application/x-msn-messenger') conn.putheader('content-length',str(len(values))) conn.putheader('Proxy-authorization',authheader) conn.endheaders() conn.send(values) r = conn.getresponse() print r.status, r.reason print r.msg print r.read() From steve at holdenweb.com Wed Jan 30 21:51:53 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Jan 2008 21:51:53 -0500 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <13q2960err4db28@corp.supernews.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> <13q2960err4db28@corp.supernews.com> Message-ID: <47A137C9.507@holdenweb.com> Grant Edwards wrote: > On 2008-01-31, Daniel Fetchinson wrote: >>> I do not understand why no one has answered the following question: >>> >>> Has anybody worked with Gene Expression Programming???? >> Hmmmmm, maybe because nobody did? Just a thought. It can also be that >> everyone worked with it but everyone is part of a big conspiracy not >> to answer any of your emails just to make you act weird. > > That's it then, now we're going to have to kill you... > Look guys, I thought we'd agreed that the PSU was no longer to be From python.list at tim.thechases.com Tue Jan 8 21:41:20 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 08 Jan 2008 20:41:20 -0600 Subject: Open a List of Files In-Reply-To: References: <874pdomrrd.fsf@mulj.homelinux.net> Message-ID: <47843450.8070508@tim.thechases.com> > I decided that I was just trying to be "too smooth by 1/2" so I fell back to > > messages = open(os.path.join(host_path,'messages.txt'), 'wb') > deliveries = open(os.path.join(host_path,'deliveries.txt'), 'wb') > actions = open(os.path.join(host_path,'actions.txt'), 'wb') > parts = open(os.path.join(host_path,'parts.txt'), 'wb') > recipients = open(os.path.join(host_path,'recipients.txt'), 'wb') > viruses = open(os.path.join(host_path,'viruses.txt'), 'wb') > esp_scores = open(os.path.join(host_path,'esp_scores.txt'), 'wb') Another way to write this which reduces some of the code would be filenames = ['messages', 'deliveries', 'actions', 'parts', 'recipients', 'viruses', 'esp_scores'] (messages, deliveries, actions, parts, recipients, viruses, esp_scores) = [ open(os.path.join(host_path, '%s.txt' % fn), 'wb') for fn in filenames ] It becomes even more clear if you make an intermediate "opener" function such as binwriter = lambda fname: open( os.path.join(host_path, '%s.txt' % fname), 'wb') (messages, deliveries, actions, parts, recipients, viruses, esp_scores) = [ binwriter(fn) for fn in filenames] This makes it easier to change intended functionality in one place, rather than updating each line. Additionally, it's easy to add a new entry (just add the filename in the filename list, and the variable-name in the assignment tuple). It also makes it clear that each one is getting the same treatment (that there's not some outlier making you study matters carefully to figure out that there isn't). -tkc From joe at incomps.com Tue Jan 8 15:02:40 2008 From: joe at incomps.com (Joseph Bernhardt) Date: Tue, 8 Jan 2008 13:02:40 -0700 Subject: ZSI and .NET Message-ID: <000c01c85231$6cd3bcb0$467b3610$@com> I am successfully using ZSI to create a web service for our internal use. A request containing a username and password will respond with user information. Sample Request: Jough joughspassword Response for Sample Request: my at email.com 28 my at otheremail.com Unfortunately, when I try to complete the request via C#, an exception will be thrown when the response is deserialized: {"The specified type was not recognized: name='string', namespace='http://www.w3.org/2001/XMLSchema', at ."} I realize that my problem is mainly .NET based, but since it has to do with datatypes I thought someone from here may be able to help me. The python code is a simple CGI dispatched function. Let me know if you need to see it, or the wsdl. Thanks! Jough -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Jan 14 18:34:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 10:34:45 +1100 Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> <874pdgf2wo.fsf@benfinney.id.au> Message-ID: <87ejckdlre.fsf@benfinney.id.au> Ben Finney writes: > I think of NotImplemented as equivalent to None Not "equivalent"; rather "comparable in usage". -- \ "[W]e are still the first generation of users, and for all that | `\ we may have invented the net, we still don't really get it." | _o__) -- Douglas Adams | Ben Finney From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 29 10:35:52 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 29 Jan 2008 16:35:52 +0100 Subject: Terse Syntax through External Methods In-Reply-To: References: <5vu9gaF1no9i1U1@mid.uni-berlin.de> Message-ID: <479f47d1$0$13485$426a74cc@news.free.fr> Jens a ?crit : > On Jan 25, 3:19 pm, "Diez B. Roggisch" wrote: >> Jens schrieb: >> >> >> >>> Hello Everyone >>> I'm newbie to Zope and i have a few questions regarding external >>> methods. (snip) >>> This doesn't work because because the method doesn't have access to >>> the environment. >> If it has to be an External method, you can't access such a context >> AFAIK. IIRC, that's what the 'self' argument is for. Now I don't know if it will solve the OP's problem with dtml (which I avoid like pest). >> But then you can create a python script that _has_ this context, >> and passese it to the external method. Not the nicest solution, but >> should work. >> > > Like I said i'm a newbie. I though the deal with Zope was that i > couldn't really do inline scripting (for security reasons) > like in php but had to use these external methods. how does one go > about creating a "normal" python script exactly and > how do I invoke it's functionality? Zope (well... Zope2.x) has an object type named "Script (Python)". What you can do with them is restricted (for security reasons) but is obviously enough for what you want here. And really, you should *not* use dtml unless you have no other choice at all. Anyway: Zope is a world in itself, and most pythoneers don't use it. The Zope experts are mostly on the Zope's mailing list, so that's where you should post such questions. HTH From steven at REMOVE.THIS.cybersource.com.au Mon Jan 21 22:50:50 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 22 Jan 2008 03:50:50 -0000 Subject: read files References: Message-ID: On Tue, 22 Jan 2008 11:00:53 +0800, J. Peng wrote: > first I know this is the correct method to read and print a file: > > fd = open("/etc/sysctl.conf") > done=0 > while not done: > line = fd.readline() > if line == '': > done = 1 > else: > print line, > > fd.close() The evolution of a Python program. # Solution 2: fd = open("/etc/sysctl.conf") done = False while not done: line = fd.readline() if line: print line, else: done = True fd.close() # Solution 3: fd = open("/etc/sysctl.conf") while True: line = fd.readline() if line: print line, else: break fd.close() # Solution 4: fd = open("/etc/sysctl.conf") lines = fd.readlines() for line in lines: print line, fd.close() # Solution 5: fd = open("/etc/sysctl.conf", "r") for line in fd.readlines(): print line, fd.close() # Solution 6: for line in open("/etc/sysctl.conf").readlines(): print line, # garbage collector will close the file (eventually) # Solution 7: fd = open("/etc/sysctl.conf", "r") line = fd.readline() while line: print line, line = fd.readline() fd.close() # Solution 8: fd = open("/etc/sysctl.conf", "r") for line in fd: print line, fd.close() # Solution 9: for line in open("/etc/sysctl.conf"): print line, # Solution 10: # (the paranoid developer) try: fd = open("/etc/sysctl.conf", "r") except IOError, e: log_error(e) # defined elsewhere print "Can't open file, please try another." else: try: for line in fd: print line, except Exception, e: log_error(e) print "Reading file was interrupted by an unexpected error." try: fd.close() except IOError, e: # Can't close a file??? That's BAD news. log_error(e) raise e -- Steven From Louis.Soninhu at gmail.com Wed Jan 9 14:16:35 2008 From: Louis.Soninhu at gmail.com (Louis.Soninhu at gmail.com) Date: Wed, 9 Jan 2008 11:16:35 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> <5ukkcvF1hs5vpU1@mid.uni-berlin.de> Message-ID: <83555c97-bdc1-45e0-a2b2-d8a68e3b0df8@s19g2000prg.googlegroups.com> that's very strange... the list I give here is almost same as the real list, except for the length. Thanks Marc, I'll go check what's wrong elsewhere From Scott.Daniels at Acm.Org Thu Jan 10 00:55:46 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 09 Jan 2008 21:55:46 -0800 Subject: Collecting Rich Data Structures for students In-Reply-To: References: Message-ID: <13obci92687ms70@corp.supernews.com> kirby.urner at gmail.com wrote: > Some of us over on edu-sig, one of the community actives, > have been brainstorming around this Rich Data Structures > idea, by which we mean Python data structures already > populated with non-trivial data about various topics such > as: periodic table (proton, neutron counts); Monty Python > skit titles; some set of cities (lat, long coordinates); types > of sushi. Look into the "Stanford GraphBase" at: http://www-cs-faculty.stanford.edu/~knuth/sgb.html A great source of some data with some interesting related exercises. Also, a few screen-scraping programs that suck _current_ information from some sources should also delight; the students have a shot at getting ahead of the teacher. --Scott David Daniels Scott.Daniels at Acm.Org From bronger at physik.rwth-aachen.de Tue Jan 1 10:27:08 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 01 Jan 2008 16:27:08 +0100 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> Message-ID: <87r6h1sh0z.fsf@physik.rwth-aachen.de> Hall?chen! Steven D'Aprano writes: > [...] > > Ah, and now we're getting somewhere! It's not so much that tabs > are intrinsically harmful (as people like Thorsten keep > insisting), but that in a world supposedly dominated by people who > indent with spaces, using tabs might lead to inconsiderate > programmers ignoring your project's coding standards and inserting > spaces into your code base. > > Yes, I can see that is a problem. I believe it is best solved by > refusing contributions from such inconsiderate programmers. After > all, if they're going to ignore your project's code standards in > one aspect, they're invariably going to ignore others as well. No, you cannot have both tabs and spaces. The whole community must settle on a single method. I cannot adjust my editor's settings to the respective SVN tree I'm looking at, nor can I incorporate other project's code into mine if the indentation method is not the same. Of course, there is no intrinsic benefit from spaces but it is the method that has won. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From userprogoogle-139 at yahoo.co.uk Wed Jan 9 04:59:43 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Wed, 9 Jan 2008 01:59:43 -0800 (PST) Subject: Multi form CGI examples? Message-ID: <9443f999-ab6f-4ba6-aba9-bddf6ffb82d3@q77g2000hsh.googlegroups.com> Hi, I have been looking online for some examples of how to create multi form CGI scripts using Python. I have come across a few but am still a little confused - being new to CGI on Python. Can anyone provide me with some pointers to useful tutorials or advice on the best way to go about it? I think I have mastered the basic elements of parsing and processing single forms so it is really a matter of architecture and examples more than anything else. For example should I write everything in one file or split it up over several, also should I use HTML files or hard code the HTML in the script? As for the actual forms, there will probably be three of them. Each will have some elements which are required. Other aspects include the ability to upload files and check whether the person is logged in (probably via cookies although the people who operate the site have yet to get back to me). These are all kind of newbie questions when it comes to CGI, but not being a web developer tips and advice are appreciated. I would rather avoid costly mistakes! Thanks in advance. Kind regards, rod From mail at timgolden.me.uk Sun Jan 13 10:28:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 13 Jan 2008 15:28:39 +0000 Subject: How to get user home directory on Windows In-Reply-To: References: <0bb27916-5416-47b2-b58c-1eb82ccb6d3e@k2g2000hse.googlegroups.com> Message-ID: <478A2E27.8060109@timgolden.me.uk> thebjorn wrote: > On Jan 12, 6:50 pm, "Giampaolo Rodola'" wrote: >> Update. >> I found a way for getting the home directory of the user but it >> requires to validate the user by providing username+password: >> >> def get_homedir(username, password): >> token = win32security.LogonUser( >> username, >> None, >> password, >> win32security.LOGON32_LOGON_NETWORK, >> win32security.LOGON32_PROVIDER_DEFAULT >> ) >> return win32profile.GetUserProfileDirectory(token) >> >> What I'd like to do is avoiding the requirement of the password, the >> same way as if I would on UNIX where it would be enough just using the >> pwd module: >> >> >>> import pwd >> >>> pwd.getpwnam('user').pw_dir >> '/home/user' > > Check out http://msdn2.microsoft.com/en-us/library/bb762181(VS.85).aspx > for some of the complexities of special directories on Windows. Part of the problem here is that is the OP is asking for the "home dir" of a user, but there is no such thing under Windows. Or, rather, there are several such things. The code he posts above will get the path to what will be the user's %USERPROFILE% env var when he logs on. (Which is certainly one of the definitions of "home dir"). But he wants that path *without* having to log them in. The page you refer to (and other similar suggestions of using the os.expanduser function which essentially does the same thing for you) assume you're already logged in as the user in question. I've posted a (WMI-based) solution [1] on the python-win32 list where the OP copied his question. You could do the same just with win32security and _winreg. (Left as an exercise... etc.) Haven't yet heard back from the OP as to whether that's given him what he wants or not. TJG [1] http://mail.python.org/pipermail/python-win32/2008-January/006656.html From bg_ie at yahoo.com Thu Jan 24 10:44:42 2008 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Thu, 24 Jan 2008 07:44:42 -0800 (PST) Subject: Connecting to Sql Server from Python Message-ID: <56f14ea0-defb-445b-b957-7f379a000add@x69g2000hsx.googlegroups.com> Hi, I have an sql server from which I'd like to read and write to. The connection string is as follows - "Data Source=localhost\SQLExpress;Initial Catalog=Test;Integrated Security=True;Pooling=False" Other properties as they appear in Visual Studio 2005 include - Data Provider: .NET Framework Data Provider for SQL Server State: Open Type: Microsoft SQL Server So my question is, how might I connect to my Test Catalog and update data within its tables via perl, Thanks, Barry. From brkict at gmail.com Tue Jan 22 07:14:01 2008 From: brkict at gmail.com (glomde) Date: Tue, 22 Jan 2008 04:14:01 -0800 (PST) Subject: possible to overide setattr in local scope? Message-ID: <9dac9675-992e-4dc5-b085-06f0811939ca@1g2000hsl.googlegroups.com> In a class it is poosible to override setattr, so that you can decide how you should handle setting of variables. Is this possible to do outside of an class on module level. mysetattr(obj, var, value): print "Hello" So that test = 5 would print Hello From Scott.Daniels at Acm.Org Thu Jan 24 22:30:50 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 24 Jan 2008 19:30:50 -0800 Subject: Ignore exceptions In-Reply-To: <244a3456-84d3-4328-b30a-59fae999bada@u10g2000prn.googlegroups.com> References: <8448fdcb-3ee5-4173-a841-0e844e54d9ba@e4g2000hsg.googlegroups.com> <244a3456-84d3-4328-b30a-59fae999bada@u10g2000prn.googlegroups.com> Message-ID: <13pillknr66de4d@corp.supernews.com> Roger Miller wrote: > On Jan 24, 11:30 am, Jonathan Gardner > wrote: >> .... > >> A few sample good uses of try/except blocks: >> (1) Do something else if an expected exception occurs. >> (2) Show a friendly error message when an exception occurs over ... > I'd add (3) Clean-up handlers. These don't actually handle the > problem, they just free resources, close files, etc. before re- > raising the exception for someone else to worry about. Ah, but typically these are try/finally blocks. Many can be dealt with by context mangers in 2.5 or later -- see with_statement. --Scott David Daniels Scott.Daniels at Acm.Org From sevenbark at gmail.com Mon Jan 28 00:12:47 2008 From: sevenbark at gmail.com (sevenbark) Date: Sun, 27 Jan 2008 23:12:47 -0600 Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> Message-ID: On Sat, 26 Jan 2008 04:23:36 -0800 (PST), Dox33 wrote: >WHERE IS THE SECOND LINE? >It is in the file stderr_catch.txt!!! > >**** See the problem? >Please Tell me? Why is the prompt produced by raw_input() printed to >the error channel? It should be stdout, just as the print statement >does. Isn't this the norm in Unix shells also? In bash the "read" command prints the prompt on stderr and the "select" command prints both the menu and prompt on stderr. sb From parvini_navid at yahoo.com Tue Jan 1 03:58:17 2008 From: parvini_navid at yahoo.com (Navid Parvini) Date: Tue, 1 Jan 2008 00:58:17 -0800 (PST) Subject: File Info Message-ID: <692822.86973.qm@web54501.mail.re2.yahoo.com> Dear All, Would you please tell me if there is another function instead of stat that gives the same information ( such as the size of the file) but faster? Thank you in advance. Navid --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Thu Jan 24 10:07:47 2008 From: roy at panix.com (Roy Smith) Date: Thu, 24 Jan 2008 10:07:47 -0500 Subject: Test driven development References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> Message-ID: In article <7b0188a3-f6f6-483c-8f41-2dd9b9522268 at v67g2000hse.googlegroups.com>, ajcppmod at gmail.com wrote: > So my question is when approaching a project that you want to employ > test driven development on how and where do you start? And also if > anyone uses top-down design with TDD I would be interested in how you > do it (does it involve lots of mock objects/ is the first test you > write the last one to pass)? I've been a big fan of TDD for a few years. I don't always use it. When working with legacy code, sometimes the pain of getting things into a test harness exceeds the effort I'm able or willing to put into it right now. The other times I don't use it is when I'm "just doing some simple little thing" (which inevitably grows into something bigger than originally anticipated). In all cases, I often find that code I ended up writing is less well documented, less well tested, and more buggy. You've hit the nail on the head with the top-down, bottom-up issue. TDD (at least in my mind) encourages bottom-up design, because it forces you to have working code on day one. This is not always good. So, the key (as you pointed out) to mixing TDD with top-down, is to use mock objects a lot. But, this is a good thing; it forces you to write classes which can be tested in isolation. This no only makes for better tested code, but often leads to cleaner design. Now, to drag this thread back to something apropos to Python, the good news is that Python makes it easy to work with mock objects. Often, all you need to do is "import myTestingFoo as Foo" and it all just works. Since functions and classes are first-class objects, it's easy to pass them around. Since Python uses duck typing, you don't have to make sure your test class inherets from anything in particular. It all just works. From __peter__ at web.de Thu Jan 17 12:40:30 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jan 2008 18:40:30 +0100 Subject: Interesting Thread Gotcha References: <5v6hj5F1k6gi5U1@mid.individual.net> Message-ID: Hendrik van Rooyen wrote: > "Bjoern Schliessmann" wrote: > > Hendrik van Rooyen wrote: >> Absolutely! - well spotted! > > This is no threading problem at all; not even a syntax problem. If > you don't know exactly what start_new_thread and kbd_driver > functions do it's impossible to tell if your code does what is > intended. > >> It would have been nice, however, to have gotten something like: >> >> TypeError - This routine needs a tuple. >> >> instead of the silent in line calling of the routine in question, >> while failing actually to start a new thread. > > Exactly which part of the code should give you this warning? > > I am obviously missing something. > > My understanding is that, to start a new thread, one does: > > NewThreadID = thread.start_new_thread(NameOfRoutineToStart, > (ArgumentToCall_it_with,secondArg,Etc)) > > This calls start_new_thread with the name and the arguments to pass. > > If one omits the comma, then start_new_thread is surely stilled called, > but with an argument that is now a call to the routine in question, which > somehow causes the problem. > > So start_new_thread is the code that that is executed, with a bad set of > arguments - one thing, (a call to a routine) instead of two things - > a routine and a tuple of arguments. > > Everywhere else in Python if you give a routine the incorrect number of > arguments, you get an exception. Why not here? Python always evaluates the function's arguments first. The check for the correct number of arguments is part of the call and therefore done afterwards: >>> def f(x): print x ... >>> f(f(1), f(2), f(3)) 1 2 3 Traceback (most recent call last): File "", line 1, in TypeError: f() takes exactly 1 argument (3 given) So if one of the arguments takes forever to calculate you will never see the TypeError: >>> def g(x): ... print x ... import time ... while 1: time.sleep(1) ... >>> f(f(1), g(2), f(3)) 1 2 Traceback (most recent call last): File "", line 1, in File "", line 4, in g KeyboardInterrupt # I hit Ctrl-C Peter From ggpolo at gmail.com Wed Jan 16 12:38:49 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 16 Jan 2008 15:38:49 -0200 Subject: paramiko In-Reply-To: <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> Message-ID: 2008/1/16, Tarun Kapoor : > # now, connect and use paramiko Transport to negotiate SSH2 across > the connection > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((hostname, port)) > > t = paramiko.Transport(sock) > t.start_client() > key = t.get_remote_server_key() > > event = threading.Event() > t.auth_password(username=username, password=password, event=event) > event.wait() > > if not t.is_authenticated(): > print "not authenticated" > > output: > not authenticated > This is a different problem I guess, now you are usin get_remote_server_key. And why are you creating event after calling start_client without specifying it ? > > > > On Jan 16, 11:11 am, "Guilherme Polo" wrote: > > 2008/1/16, Tarun Kapoor : > > > > > > > > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > > > the remote server using an SFTP client I have just to make sure that > > > username and password are working.. This is the code. > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > > > connection > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > > sock.connect((hostname, port)) > > > > > t = paramiko.Transport(sock) > > > > > event = threading.Event() > > > > > t.start_client(event) > > > > > event.wait(15) > > > > > if not t.is_active(): > > > > > print 'SSH negotiation failed.' > > > > > sys.exit(1) > > > > > else: > > > > > print "SSH negotiation sucessful" > > > > > event.clear() > > > > > t.auth_password(username=username, password=password,event=event) > > > > > if not t.is_authenticated(): > > > > > print "not authenticated" > > > > > output: > > > > > SSH negotiation successful > > > > > not authenticated > > > > > Tarun > > > > > Waterstone Capital Management > > > > > 2 Carlson Parkway, Suite 260 > > > > > Plymouth, MN 55447 > > > > > Direct: 952-697-4123 > > > > > Cell: 612-205-2587 > > > Disclaimer This e-mail and any attachments is confidential and intended > > > solely for the use of the individual(s) to whom it is addressed. Any views > > > or opinions presented are solely those of the author and do not necessarily > > > represent those of Waterstone Capital Management, L.P and affiliates. If you > > > are not the intended recipient, be advised that you have received this > > > e-mail in error and that any use, dissemination, printing, forwarding or > > > copying of this email is strictly prohibited. Please contact the sender if > > > you have received this e-mail in error. You should also be aware that > > > e-mails are susceptible to interference and you should not assume that the > > > contents of this e-mail originated from the sender above or that they have > > > been accurately reproduced in their original form. Waterstone Capital > > > Management, L.P. and affiliates accepts no responsibility for information, > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > > > please verify the authenticity with the sender. > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > > You are missing an event.wait() after t.auth_password. > > Also, why are you passing this magic value "15" to event.wait() ? That > > parameter is passed to class _Verbose to indicate if debug messages > > should be displayed or not, so typical values would be 0/1 or > > False/True. > > > > -- > > -- Guilherme H. Polo Goncalves > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From asmodai at in-nomine.org Tue Jan 8 07:25:00 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 13:25:00 +0100 Subject: Look for a string on a file and get its line number In-Reply-To: <47836440$0$27202$9b4e6d93@newsspool1.arcor-online.net> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <47836440$0$27202$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <20080108122500.GK75977@nexus.in-nomine.org> -On [20080108 12:59], Wildemar Wildenburger (lasses_weil at klapptsowieso.net) wrote: >Style note: >May I suggest enumerate (I find the explicit counting somewhat clunky) >and maybe turning it into a generator (I like generators): Sure, I still have a lot to discover myself with Python. I'll study your examples, thanks. :) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ A conclusion is simply the place where you got tired of thinking... From gagsl-py2 at yahoo.com.ar Mon Jan 21 14:08:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 17:08:46 -0200 Subject: problem with 'global' References: Message-ID: En Mon, 21 Jan 2008 11:44:54 -0200, Mel escribi?: > Duncan Booth wrote: >> >> The first sentence (which hasn't changed since 2.4) describing the >> global >> statement seems clear enough to me: "The global statement is a >> declaration >> which holds for the entire current code block." > > I don't think that would stop the OP from thinking the global > statement had to be executed. In the code example, it seems to have > been stuck in a > > if 1==2: global a > > and it still worked. The future statement is another example, even worse: if 0: from __future__ import with_statement with open("xxx") as f: print f All import statements are executable, only this special form is not. That "global" and "__future__" are directives and not executable statements, is confusing. -- Gabriel Genellina From sickcodemonkey at gmail.com Thu Jan 31 21:00:44 2008 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 31 Jan 2008 21:00:44 -0500 Subject: CDA conversion Message-ID: <2adc542f0801311800q3251acebta0494befa2be2470@mail.gmail.com> Good evening. I am trying to write an application in Python that will allow a person to insert a CD into their computer and this python script will convert the music to mp3. NOTE: I have already google'd this, and nothing really pops out at me. I found tons of applications that does this, but I am trying to write this myself (as a little project). Does anyone know a good site that I can find some pointers on getting started? The machine that this will run on is running Linux and has Python 2.5. Any help is greatly appreciated. ~~~~~~~~~~~~~~~~~ .dave Filize.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Jan 7 08:33:04 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 7 Jan 2008 14:33:04 +0100 Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: MartinRinehart wrote: > Anything written somewhere that's thorough? Any code body that should > serve as a reference? http://www.python.org/dev/peps/pep-0008/ From asmodai at in-nomine.org Mon Jan 7 04:00:35 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 7 Jan 2008 10:00:35 +0100 Subject: do - loop In-Reply-To: References: Message-ID: <20080107090035.GA82115@nexus.in-nomine.org> -On [20080107 09:51], Hita Vora (hvora at usc.edu) wrote: >I have a dataset which has about 3000 subjects in it. I take each subject >and perform 3 to 4 geoprocessing tasks on it. Currently I have a model where >I manually feed in each subject's ID and then the rest of the process is >automated. I would like to automate the process such that it would >automatically select another subject after the process has been completed on >a specfic subject. ie to repeat the same process on each of the IDs. Well, hopefully I understood you correctly, but if we assume that the dataset is a simple list you can iterate over it as thus: for subject in dataset: do_geoprocessing(subject) Dictionaries and other datatypes have similar means to construct an iterator. Is this a bit what you want to achieve? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Vae victis! From MartinRinehart at gmail.com Sat Jan 5 05:40:48 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Sat, 5 Jan 2008 02:40:48 -0800 (PST) Subject: Basic inheritance question References: Message-ID: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> Jeroen Ruigrok van der Werven wrote: > Shouldn't this be: > > self.startLoc = start > self.stopLoc = stop Thanks! Of course it should. Old Java habits die slowly. From cwitts at gmail.com Fri Jan 18 06:21:16 2008 From: cwitts at gmail.com (Chris) Date: Fri, 18 Jan 2008 03:21:16 -0800 (PST) Subject: Filtering two files with uncommon column References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> <5084371c-dba0-4d11-be95-a01d1b439de6@s12g2000prg.googlegroups.com> Message-ID: <90f75e10-1f30-4c2b-8424-8e621366723f@e10g2000prf.googlegroups.com> On Jan 18, 12:08 pm, Madhur wrote: > On Jan 18, 2:37 pm, Chris wrote: > > > > > On Jan 18, 11:23 am, Madhur wrote: > > > > I would like to know the best way of generating filter of two files > > > based upon the following condition > > > > I have two files. Contents of the first file is > > > > File 1 > > > abc def hij > > > asd sss lmn > > > hig pqr mno > > > > File 2 > > > > jih def asd > > > poi iuu wer > > > wer pqr jjj > > > > I would like have the output as > > > Output > > > > File1 > > > asd sss lmn > > > File2 > > > poi iuu wer > > > > Basically I want to compare the two files based on second column. If > > > the second > > > column matches on both the files do not print anything, else if there > > > is no matc > > > h in for the second column for first file in second file then print it > > > under Fil > > > e1 header, else if there is no match for the second column for second > > > file in fi > > > rst file print it under File2 header. > > > > Thankyou > > > Madhur > > > file1 = open('file1.txt','rb') > > file2 = open('file2.txt','rb') > > > file1_line = file1.next() > > file2_line = file2.next() > > > while file1_line and file2_line: > > try: > > f1_col2 = file1_line.split(' ')[1] > > except IndexError: > > print 'Not enough delimiters in line.' > > try: > > f2_col2 = file2_line.split(' ')[2] > > except IndexError: > > print 'Not enough delimiters in line.' > > > if f1_col2 != f2_col2: > > outfile_data_to_relevant_files() > > > file1_line = file1.next() > > file2_line = file2.next() > > > HTH > > Chris > > If the files2 is unordered, then the above logic does not work. How to > takle it? Take a look at *nix's sort command, it can also sort based on a key From ajaksu at gmail.com Fri Jan 25 20:36:06 2008 From: ajaksu at gmail.com (ajaksu) Date: Fri, 25 Jan 2008 17:36:06 -0800 (PST) Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: On Jan 25, 11:10 pm, o... at thepond.com wrote: > Once a python py file is compiled into a pyc file, I can disassemble > it into assembler. Assembler is nothing but codes, which are > combinations of 1's and 0's. You can't read a pyc file in a hex > editor, but you can read it in a disassembler. It doesn't make a lot > of sense to me right now, but if I was trying to trace through it with > a debugger, the debugger would disassemble it into assembler, not > python. Please, tell me you're kidding... From aahz at pythoncraft.com Thu Jan 31 11:18:21 2008 From: aahz at pythoncraft.com (Aahz) Date: Thu, 31 Jan 2008 08:18:21 -0800 Subject: DEADLINE Feb 4: OSCON 2008 Call for Proposals Message-ID: <20080131161821.GA4232@panix.com> The O'Reilly Open Source Convention (OSCON) is accepting proposals for tutorials and presentations. The submission period ends Feb 4. OSCON 2008 will be in Portland, Oregon July 21-25. For more information and to submit a proposal, see http://conferences.oreilly.com/oscon/ -- 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 workitharder at gmail.com Tue Jan 1 11:47:11 2008 From: workitharder at gmail.com (bukzor) Date: Tue, 1 Jan 2008 08:47:11 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <601e4a81-a69a-4576-a276-41d82a256482@e50g2000hsh.googlegroups.com> <13nganfbu52dnff@corp.supernews.com> <13nh4uvkq9cmo81@corp.supernews.com> Message-ID: <5db44c52-7900-463d-9e9d-053c439cb85a@d21g2000prf.googlegroups.com> On Dec 30 2007, 11:01 pm, Steven D'Aprano wrote: > On Sun, 30 Dec 2007 20:00:14 -0800, bukzor wrote: > > I think you struck at the heart of the matter earlier when you noted > > that this is the simplest way to declare a static variable in python. > > Using the 'global' keyword is the other way, and is much more explicit, > > and much more widely used. I also see this as the main use of the > > 'notlocal' keyword to be introduced in py3k (it also fixes the example > > given by Istvan above). > > There doesn't appear to be any reference to a "notlocal" keyword in > Python 3 that I can find. Have I missed something? It sounds like an > April Fool's gag to me. Do you have a reference to a PEP or other > official announcement? > > -- > Steven I got it slightly wrong. It's 'nonlocal': http://www.python.org/dev/peps/pep-3104/ --Buck From bj_666 at gmx.net Mon Jan 28 12:38:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Jan 2008 17:38:34 GMT Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> <479e0225$0$36389$742ec2ed@news.sonic.net> Message-ID: <606i8qF1p0rptU2@mid.uni-berlin.de> On Mon, 28 Jan 2008 08:31:43 -0800, John Nagle wrote: > Unenforced static typing is somewhat pointless. If that > goes in, it should be enforced by implementations. Luckily we don't get static typing. We get annotations which *can* be used for type hints, checked by additional code. Can be used for other things as well. Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Fri Jan 25 11:26:49 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Jan 2008 16:26:49 GMT Subject: is possible to get order of keyword parameters ? References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> Message-ID: <5vugu9F1oe0goU4@mid.uni-berlin.de> On Fri, 25 Jan 2008 05:49:40 -0800, rndblnch wrote: > def f(**kwargs): > > return result > > such as : > f(x=12, y=24) == ['x', 'y'] > f(y=24, x=12) == ['y', 'x'] > > what i need is to get the order of the keyword parameters inside the > function. > any hints ? Impossible. Dictionaries are unordered. Ciao, Marc 'BlackJack' Rintsch From rocco.rossi at gmail.com Sun Jan 6 17:59:57 2008 From: rocco.rossi at gmail.com (rocco.rossi at gmail.com) Date: Sun, 6 Jan 2008 14:59:57 -0800 (PST) Subject: Noob question Message-ID: <17e045f1-7891-4afc-a98b-42dffdc45dd4@41g2000hsy.googlegroups.com> Tinkering with Python I find myself often writing scripts and then experimenting with the interactive interpreter, which is really a cool way to learn a language. However, when, after loading a module with import or from module import * and using it, I make a change to the module file, the changes are not effective after re-importing that same module, and I have to exit the interpreter and restart all over. Isn't there some way to avoid this annoying process? Thank you. From dickinsm at gmail.com Mon Jan 21 11:14:31 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 21 Jan 2008 08:14:31 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: On Jan 21, 9:55?am, Jason wrote: > display. ?On windows, "float('nan')" will cause an exception, as there > are no valid string representations of NAN that can be converted to > the special floating point value. ?Also, if you manage to create a nan > under Windows, it displays as "1.#QNAN". I believe this will be fixed in Python 2.6 :) Mark From steve at holdenweb.com Thu Jan 31 19:38:29 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 19:38:29 -0500 Subject: psycopg2 In-Reply-To: References: Message-ID: Andre' John wrote: > Hi > > I am trying to do this for a Postgresql database: > > conn = psycopg2.connect('host=localhost') > cur = conn.cursor() > cur.execute("SELECT * FROM names WHERE name=%s", ['S']) > > , which doesn't work, and neither does > > cur.execute("SELECT * FROM names WHERE name='%s'", ['S']) > > or > > cur.execute("SELECT * FROM names WHERE name='S'") > > work. I'm more inclined to believe the first two than the third, but I suppose if you are telling the truth (House: "Patients always lie") then I am guessing you have defined your table's "names" columns to be an array type. I haven't worked with those (since they don't confirm to the strict relational model I prefer to work with), but I am guessing you might try cur.execute("SELECT * FROM names WHERE name='%s'", (['S'], )) as this provides the necessary tuple as the second argument to execute, and the on;y element of the tuple is a list of a single element. > It always returns: > > Traceback (most recent call last): > > File "", line 1, in > > psycopg2.ProgrammingError: array value must start with ?{? or > dimension information > > > Though, when doing > > cur.execute("SELECT * FROM names") > > it works. > I am totally helpless here. Does anyone have an idea? > If my suggestion doesn't work, you should probably let us know more about the structure of your table. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bruno.desthuilliers at gmail.com Wed Jan 9 18:02:57 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 9 Jan 2008 15:02:57 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: <76bc64cc-541c-434f-aac5-96d1a2d231ee@c23g2000hsa.googlegroups.com> On 9 jan, 21:46, "dongie.ag... at gmail.com" wrote: > Thanks for the clarification. > > Though I was hoping someone could give me a definitive answer. Sorry - but I'm definitively not the right person on this... > I was > quite excited about this project initially, but seeing the actual > execute times was a big downer. Seeing that the original laser marker > by GRL Vienna is done in Processing which from what I know is built on > Java, I was hoping that Python would be up to a similar task. Java's declarative static typing allow agressive just-in-time optimizations - which is not the case in Python due to it's higly dynamic nature[1]. You may want to have a look at psyco (a JIT compiler) or to look for other angles (if there's any - IIRC the example you're talking about already uses at least PIL for image processing and something like scipy or numpy for intensive math ops). If none of the two above answers fits your needs, and no Python Guru comes with a better answer, then I'm afraid you'll have to go for a language with a faster implementation. Python is quite faster nowadays than it used to be, and is usually fast enough for most day-to-day programming tasks (a, but it's still not as highly optimized as some Lisp implementations (to compare to another highly [1] you can read more on this on the pypy website, and specially here IIRC: http://codespeak.net/pypy/dist/pypy/doc/dynamic-language-translation.html) From mgi820 at motorola.com Wed Jan 16 12:12:56 2008 From: mgi820 at motorola.com (Gary Duzan) Date: Wed, 16 Jan 2008 17:12:56 +0000 (UTC) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <60b75f24-d33a-476e-932d-11dfb9880562@v4g2000hsf.googlegroups.com> Message-ID: In article <60b75f24-d33a-476e-932d-11dfb9880562 at v4g2000hsf.googlegroups.com>, Paul Boddie wrote: > >I think the benefits of running Java on CPython are significantly less >than those had by running Python on the Java VM (or another VM). >Firstly, who wants to write statically typed code which then runs on a >virtual machine that can't take advantage of the type declarations? I know it was a rhetorical question, but I wanted to point out that this is exactly what happens with Java Generics. They didn't want to update the type system in the JVM, so all the generic types get thrown out by the compiler in favor of non-generic types, and casts are inserted as necessary. Practicality wins over Purity again. Gary Duzan Motorola HNM From gherron at islandtraining.com Mon Jan 21 18:36:19 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 21 Jan 2008 15:36:19 -0800 Subject: Max Long In-Reply-To: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> Message-ID: <47952C73.6080907@islandtraining.com> tjhnson at gmail.com wrote: > How can I figure out the largest long available? I was hoping for > something like sys.maxint, but I didn't see it. Also, can someone > point me to where I can (concisely) read about size of such types > (int, float, long). > There is no explicit (defined) limit. The amount of available address space forms a practical limit. Gary Herron From workitharder at gmail.com Sun Jan 6 18:38:49 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 6 Jan 2008 15:38:49 -0800 (PST) Subject: how to use bool References: <05c5df8b-15c4-47e6-8c14-72c57a84a0ea@y5g2000hsf.googlegroups.com> <2c516040-0193-4de3-bf7d-b61e739cdc2d@l57g2000hsa.googlegroups.com> Message-ID: <5b9f8f01-8e3b-413b-827b-122f86ff8962@i29g2000prf.googlegroups.com> On Jan 6, 8:56 am, jimgarde... at gmail.com wrote: > some more doubts in this area,,forgive the ignorance of a beginner > > i have > > class MyError(Exception): > def __init__(self,msg) > self.msg=msg > > now my method that can raise this is > > class SomeClass: > ........... > def mymethod(self): > if (somecondition): > raise MyError("somecondn failed") > > if another method in the same class calls this method but wants to > pass the error to a gui code which calls it,,can i do like this > > def callingmethode(self): > try: > mymethod() > except MyError,myerr: > raise myerr > > so that I can handle the error in a gui code that calls > callingmethode() > > class MyGUI: > def guimethode(self): > someinst=SomeClass() > try: > someinst.callingmethode() > except MyError,myer: > self.dealwithMyError(myer) > > is this kind of raising exception the correct way?I am getting syntax > error at > except MyError,myerr: > raise myerr It's unnecessary to catch the exception and raise it again. The default action for an uncaught exception it to raise it higher. Also this class doesn't make much sense: > class MyError(Exception): > def __init__(self,msg) > self.msg=msg This doesn't call the super class's init function. You'd want to do something like this: > class MyError(Exception): > def __init__(self,msg) > self.msg=msg > Exception.___init__(self) Also, the first argument to the Exception constructor is a text message, so you could just do this: > class MyError(Exception): > def __init__(self,msg) > Exception.___init__(self, msg) This is exactly the default constructor, so you could write it this way: > class MyError(Exception): > pass or as a one-liner: > class MyError(Exception): pass When you want to access the message out of the exception, you can use 'e.message' or 'str(e)'. If you want to print the exception's message, just do 'print e'. Besides that, your code looks good. Might want to read the exceptions chapter of the documentation: http://docs.python.org/tut/node10.html --Bukzor From hniksic at xemacs.org Wed Jan 9 05:52:13 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 09 Jan 2008 11:52:13 +0100 Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <87ejcri96v.fsf@mulj.homelinux.net> Message-ID: <87abnfi84i.fsf@mulj.homelinux.net> Hrvoje Niksic writes: > If you're looking for a quick (no quadratic behavior) and convenient > way to do it, you can do it like this: > > keywords = [s for s in keywords if s != ''] It now occurred to me that a good compromise between convenience and efficiency that retains the same list is: keywords[:] = (s for s in keywords if s) From jd at commandprompt.com Mon Jan 7 14:21:01 2008 From: jd at commandprompt.com (jd at commandprompt.com) Date: Mon, 7 Jan 2008 11:21:01 -0800 (PST) Subject: PostgreSQL Conference East: Call for Papers Message-ID: <407c0907-4584-42d0-a717-843860120083@d70g2000hsb.googlegroups.com> PostgreSQL Conference East is being held on the weekend of March 29th and 30th, 2008 in College Park, Maryland. The conference will have a series of talks, mini-tutorials and tutorials and we are now accepting submissions! If you are a third pary vendor, PostgreSQL developer, PostgreSQL consultant, DBA, or just a user who really does cool stuff, you need to submit a talk, or tutorial. Do you know how to get that last 20 transactions per second out of an array using adaptive readahead? Maybe you know more about Autovacuum than you ever care to admit? Perhaps, you have recently deployed PostgreSQL and saved a company 300k over the next closest competitor... Now is your time to share, learn and participate in the community! Submit your talk at: http://www.postgresqlconference.org/talk_submission/ . PostgreSQL Conference East is part of the PostgreSQL Community Conference series. All proceeds from the conferences are donations to PostgreSQL via the non-profit Software in the Public Interest a U.S. 501c3. Sincerely, Joshua D. Drake From brad at 16systems.com Sat Jan 19 16:54:07 2008 From: brad at 16systems.com (Brad) Date: Sat, 19 Jan 2008 16:54:07 -0500 Subject: Python 3000 and import __hello__ Message-ID: Just playing around with Python3000 a2 release on Windows XP 32-bit x86. import __hello__ doesn't print 'hello world...' as it does on 2.5 The import doesn't fail or generate errors... just no output. Perhaps this is by design? Brad From donn.ingle at gmail.com Fri Jan 25 09:42:21 2008 From: donn.ingle at gmail.com (Donn Ingle) Date: Fri, 25 Jan 2008 16:42:21 +0200 Subject: piping into a python script References: <5vrovvF1njt09U6@mid.uni-berlin.de> Message-ID: Nick Craig-Wood wrote: > This iterates over the lines of all files listed in sys.argv[1:], > defaulting to sys.stdin if the list is empty. If a filename is '-', it > is also replaced by sys.stdin. To specify an alternative list of > filenames, pass it as the first argument to input(). A single file > name is also allowed. Yeah it has been discussed. It seems the one problem with it is that it opens each file. I only want the filenames. Anyway, this has more-or-less been solved now. Thanks, \d From hat at se-162.se.wtb.tue.nl Thu Jan 24 09:51:55 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 24 Jan 2008 15:51:55 +0100 Subject: Test driven development References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> Message-ID: On 2008-01-24, ajcppmod at gmail.com wrote: > I like the concept of TDD but find it difficult to put into practice > most of the time. I think this primarily because I tend to like top- > down development and functional/object decomposition and TDD feels > more like a bottom-up approach. It is not bottom-up imho. The main difference imho is in abstract, far-away goals versus running code for a small concrete sub-set of functionality in the short-term. How you provide that "running code for a small concrete sub-set of functionality in the short-term" is not defined by the approach. > So my question is when approaching a project that you want to employ > test driven development on how and where do you start? And also if 1. Define a small step of extended functionality that you can finish by the end of the week. 2. Write tests that should run after implementing the functionality. 3. Write code that make the tests work. 4. goto 1. > anyone uses top-down design with TDD I would be interested in how you > do it (does it involve lots of mock objects/ is the first test you > write the last one to pass)? No, with TTD there is only one goal, namely increasing the percentage of passed tests to 100%. (which you then break again by doing steps 1 and 2, and fix again in step 3) TTD is about DESIGNing for WHAT YOU NEED TODAY, not for what you might need tomorrow. You may want to do a small top-down design (and next week another slightly larger one, and another slightly larger one in 2 weeks, etc), but you should NOT DESIGN FOR MORE FUNCTIONALITY THAN WHAT YOU NEED for all tests to pass. Sincerely, Albert PS The above is purely from a TTD perspective. I personally do not really think you can SOLVE ALL PROBLEMS in the most efficient way using TTD. On the other hand, the concrete, short-term approach does produce running code fast for the implemented sub-set of functionality, which may be nice in a project. From gagsl-py2 at yahoo.com.ar Tue Jan 29 15:07:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jan 2008 18:07:01 -0200 Subject: runscript module, where are the docs... References: <1fbdde0d-ae09-4b6a-8f08-0713de94cc0b@j78g2000hsd.googlegroups.com> Message-ID: En Tue, 29 Jan 2008 13:48:58 -0200, glomde escribi?: > I am going through some code and found > import runscript > > BUT I cant find and information about this module. I searched Google > did a grep in > the /usr/lib/python directory. > > What is the purpose of this module and where can I find information > about it. Or the source. It doesn't appear to be a standard module, look around the place where you found it. -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jan 31 17:09:55 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 31 Jan 2008 23:09:55 +0100 Subject: Naive idiom questions References: Message-ID: <60ev9jF1qdpctU1@mid.individual.net> Terran Melconian wrote: > * Why are there no real mutable strings available? > > I found MutableString in UserString, but further research > indicates that it is horribly inefficient and actually just > wraps immutable strings for the implementation. Did you measure such impact on your application? Also see http://www.skymind.com/~ocrow/python_string/ > I want to be able to accumulate a string with +=, not by going > through an intermediate list and then doing ''.join(), because > I think the latter is ugly. >>> yummy = "ham" >>> yummy += "eggs" >>> yummy 'hameggs' > There are also times when I'd like to use the string as a > modifiable buffer. Use a list instead. When done with modifications you may concatenate its contents to a string using "".join(my_list). > * What's the best way to initialize a list of lists? > [...] > l=[[None]*5 for i in range(5)] > > I don't particularly like it, though. It bothers me to have > to explain list comprehensions, which are a moderately > advanced feature conceptually, just to initialize an array. Look at "lower level" HLLs. In C++, you'd have to use int my_array[5][5]; for (int i=0; i<5; ++i) for (int j=0; j<5; j++) my_array[i][j] = -1; Personally, I like list comprehensions much better. Regards, Bj?rn -- BOFH excuse #254: Interference from lunar radiation From bj_666 at gmx.net Wed Jan 30 17:03:52 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jan 2008 22:03:52 GMT Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <60cai8F1qgh3aU1@mid.uni-berlin.de> On Wed, 30 Jan 2008 15:29:45 +0100, Wildemar Wildenburger wrote: > Gerardo Herzig wrote: >> I will use genital().extend(), thats for shure ^^ > > Well, you never go wrong with apply(genital(), females), do you? `apply()` is deprecated. And ``genital(*females)`` looks a bit odd. :-) Ciao, Marc 'BlackJack' Rintsch From yantao at telus.com Sun Jan 27 00:37:48 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 05:37:48 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: References: <13po55nc0q0s06@corp.supernews.com> Message-ID: I just sorted posts by from, and figured out that you are kind of PSF guy... However that does not make you qualified, I care whether you are capable not whether you have the time to spend for PSF. Adios! ========================================== "Peter Pei" wrote in message news:YHUmj.43649$fj2.28192 at edtnps82... > You didn't understand my question, but thanks any way. > > Yes, it is true that %s already support unicode, and I did not contradict > that. But it counts the number of bytes instead of characters, and makes > things like %-20s out of alignment. If you don't understand my assertion, > please don't argue back and I am only interested in answers from those who > are qualified. > ============================================================== > > "Steven D'Aprano" wrote in message > news:13po55nc0q0s06 at corp.supernews.com... >> On Sun, 27 Jan 2008 04:06:45 +0000, Peter Pei wrote: >> >>> I probably should mention that what I want is to make all parts of the >>> string aligned, and look like table. I am not looking for other ways to >>> make it table-alike, but only interested in making % work with unicode >>> -counting characters not bytes... >> >> % already works with unicode. Just give it unicode arguments: >> >> >>>>> print u"x y z %s 1 2 3" % u"Les mis?rables" >> x y z Les mis?rables 1 2 3 >> >> >> -- >> Steven > From deets at nospam.web.de Mon Jan 28 16:35:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jan 2008 22:35:52 +0100 Subject: PYS file In-Reply-To: References: Message-ID: <60705vF1pl66cU1@mid.uni-berlin.de> Gabriel Genellina schrieb: > On 28 ene, 13:05, azrael wrote: > >> A I Understood correctly, pyc files are compiled py scripts. Is it >> possible to decomplite them. >> I guess it's possible, but how hard is it. > > You want to get back the Python source? Look for the "decompyle" > package. The last published release works for version 2.3; there is a > paid service for newer versions (you send the .pyc, they give back > the .py) > > At least you may use the dis module to disassemble the compiled .pyc > into the correspoding VM instructions - if you are happy reading > that... From other posts of the OP I'd rather think that he's after copy/IP-protection. So the answer is: if your code contains algorithms worth stealing (which in 99.99% isn't the case, objectively) or the program as whole is worth being hacked because of public interest combined with high prices (SPSS, photoshop), IT WILL BE. Even if it has been under-water-mouth-coded in assembler. Diez From bj_666 at gmx.net Wed Jan 23 14:04:38 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Jan 2008 19:04:38 GMT Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> Message-ID: <5vphe6F1njt09U1@mid.uni-berlin.de> On Wed, 23 Jan 2008 10:50:02 -0800, ryan k wrote: > Hello. I have a string like 'LNAME > PASTA ZONE'. I want to create a list of those words and > basically replace all the whitespace between them with one space so i > could just do lala.split(). Thank you! You *can* just do ``lala.split()``: In [97]: lala = 'LNAME PASTA ZONE' In [98]: lala.split() Out[98]: ['LNAME', 'PASTA', 'ZONE'] Ciao, Marc 'BlackJack' Rintsch From attn.steven.kuo at gmail.com Thu Jan 31 17:58:42 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 31 Jan 2008 14:58:42 -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> Message-ID: On Jan 31, 2:48 pm, "attn.steven.... at gmail.com" wrote: > On Jan 31, 8:12 am, erikcw wrote: > > One way would be to use sets and check for intersection: > > for idx, s in enumerate(mysets): > for next_idx, next_s in enumerate(mysets[idx+1:]): > if s.intersection(next_s): > print "mylist[%d] and mylist[%d] intersect" % ( > idx, idx + next_idx + 1 ) > Um, that would have been more helpful if I hadn't forgotten to preface that with: mylist = [(55, 58, 52), (20, 22, 18), (17, 21, 13), (60, 63, 57),] mysets = [set(range(x[2],x[1])) for x in mylist] -- Cheers, Steven From cokofreedom at gmail.com Tue Jan 15 05:50:17 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 15 Jan 2008 02:50:17 -0800 (PST) Subject: common problem - elegant solution sought References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <5fcec3dc-f223-4617-acad-69d33e225c23@f47g2000hsd.googlegroups.com> > I have a list of tuples (Unique_ID,Date) both of which are strings. > I want to delete the tuple (element) with a given Unique_ID, but > I don't known the corresponding Date. > > My straight forward solution is a bit lengthy, e.g. > > L=[("a","070501"),("b","080115"),("c","071231")] Do they have to be tuples? Seems to me if you are using a Unique_ID that a dictionary would be perfect. Indeed when you are looking to delete an entry you can simply look for the Unique_ID in the dictionary and it will be a very fast look up. if key in "my_dictionary": However, if you must use a list of tuples, your current method is very inefficient. Why not use the del within the if Key == "b":? I cannot provide extremely elegant solutions with your current system, but I can tell you with a large enough list your way is going to take a very long time since you will iterate over the whole list sequentially to find an entry... From mikez302 at gmail.com Sat Jan 12 14:21:39 2008 From: mikez302 at gmail.com (mikez302) Date: Sat, 12 Jan 2008 11:21:39 -0800 (PST) Subject: IDLE won't start in Python 2.5 for Windows References: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> <13ogqhlds0tbsac@corp.supernews.com> Message-ID: <57a7e4a2-0acc-4439-9bd6-d96862ffc22e@j78g2000hsd.googlegroups.com> I opened a command window in my Python25 folder and tried typing pythonw. I just got another command prompt as if the program ran but didn't do anything. It looked like this: C:\Python25>pythonw C:\Python25> From arnodel at googlemail.com Sat Jan 19 07:07:58 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 19 Jan 2008 04:07:58 -0800 (PST) Subject: Is this a bug, or is it me? References: Message-ID: <150b3c8f-56cb-4759-b674-ed07abeda450@e6g2000prf.googlegroups.com> On Jan 17, 3:55?pm, Peter Otten <__pete... at web.de> wrote: > Here is a simpler example: > > >>> class A: > > ... ? ? a = 42 > ... ? ? list(a for _ in "a") > ... > Traceback (most recent call last): > ? File "", line 1, in > ? File "", line 3, in A > ? File "", line 3, in > NameError: global name 'a' is not defined [...] > So it seems that Python gets puzzled by the extra scope introduced by the > genexp, i. e. you are seeing an obscure variant of the following > (expected) behaviour: > > >>> class B: > > ... ? ? a = 42 > ... ? ? def f(): a > ... ? ? f() > ... > Traceback (most recent call last): > ? File "", line 1, in > ? File "", line 4, in B > ? File "", line 3, in f > NameError: global name 'a' is not defined This is exactly the problem: class A: a = 42 list(a for _ in "a") is in fact compiled as: class A: a = 42 def _genexpr(): for _ in "a": yield a list(_genexpr()) Except that the _genexpr function is not bound to any name, just left on the stack for list to pick up next. This can be checked using the dis module. Trying it yields exactly the same error: >>> class A(object): ... a = 42 ... def _genexpr(): ... for _ in "a": ... yield a ... list(_genexpr()) ... Traceback (most recent call last): File "", line 1, in File "", line 6, in A File "", line 5, in _genexpr NameError: global name 'a' is not defined > I think you should file a bug report, though making the genexp recognizing > the class scope probably isn't worth the effort. It isn't necessary to do that to fix the problem. I think that the semantics of genexprs concerning free variables are confusing (and this is a good example!). I suggested a change on python-ideas a while ago that would solve this particular issue. In short, all free variables inside a generator expression could be bound at the creation of the expression, not when it is evaluated. So for example ((c, f(x)) for x in L) would be the equivalent of what one could currently write as. (lambda _c, _f: ((c, f(x) for x in L))(c, f) so your example would compile to: class A: a = 42 def _genexpr(_a): for _ in "a": yield _a list(_genexpr(a)) Which would behave as the OP expected (and I think as it is reasonable to expect if one doesn't know about how genexprs are implemented). Other reasons why I think this is desirable are exposed (maybe not very convincingly) in this post to python-ideas. http://mail.python.org/pipermail/python-ideas/2007-December/001260.html -- Arnaud From morse at edoug.org Wed Jan 9 15:48:13 2008 From: morse at edoug.org (Doug Morse) Date: Wed, 9 Jan 2008 20:48:13 +0000 (UTC) Subject: ISO books of official Python docs References: Message-ID: Several of the O'Reilly & Assoc. books -- such as Python in a Nutshell, The Python Standard Library, etc -- are in large part reproductions of the official docs and references. So, while not exactly what you asked for, the ORA books might be a viable alternative if what you want isn't available. On Wed, 9 Jan 2008 19:55:10 +0000 (UTC), kj wrote: > > > > Is it possible to buy the official Python docs in book form? If > so, I'd very much appreciate the name(s) and author(s) of the > book(s). > > TIA! > > kynnjo From aahz at pythoncraft.com Sat Jan 12 23:58:21 2008 From: aahz at pythoncraft.com (Aahz) Date: Sat, 12 Jan 2008 20:58:21 -0800 Subject: OSCON 2008 Call for Proposals Message-ID: <20080113045821.GA4328@panix.com> The O'Reilly Open Source Convention (OSCON) is accepting proposals for tutorials and presentations. The submission period ends Feb 4. OSCON 2008 will be in Portland, Oregon July 21-25. For more information and to submit a proposal, see http://conferences.oreilly.com/oscon/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 22 04:30:59 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 22 Jan 2008 10:30:59 +0100 Subject: Bug in __init__? In-Reply-To: References: Message-ID: <4795b788$0$11545$426a34cc@news.free.fr> Bart Ogryczak a ?crit : > On 2008-01-18, citizen Zbigniew Braniecki testified: (snip usual default mutable list arg problem) >> class A(): >> >> def add (self, el): >> self.lst.extend(el) >> >> def __init__ (self, val=[]): >> print val >> self.lst = val > > What you want probably is: > def __init__ (self, val=None): > if(val == None): Better to use an identity test here - there's only one instance of the None object, and identity test is faster than equality test (one function call faster IIRC !-). Also, the parens are totallu useless. if val is None: > self.lst = [] > else: > from copy import copy > ### see also deepcopy > self.lst = copy(val) What makes you think the OP wants a copy ? From steven at REMOVE.THIS.cybersource.com.au Sun Jan 6 22:57:52 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 Jan 2008 03:57:52 -0000 Subject: Delete lines containing a specific word References: <13o2tapcc2d066e@corp.supernews.com> Message-ID: On Mon, 07 Jan 2008 00:42:01 +0000, Grant Edwards wrote: >> If you want to delete them, you still have to do the rest of the job >> yourself. > > Nonsense. > > How is this not doing what the OP asks? > > grep -v pattern infile >outfile; mv outfile infile It isn't deleting lines. As abstractions go, it comes pretty close, but just try it on a disk with insufficient free space for the temporary outfile and watch it break. -- Steven From barry.zhao at gmail.com Thu Jan 10 15:38:50 2008 From: barry.zhao at gmail.com (barry.zhao at gmail.com) Date: Thu, 10 Jan 2008 12:38:50 -0800 (PST) Subject: open excel file while it is being used. Message-ID: Hi, I have a python program that constantly updates an excel spreadsheet. I would like to be able to view its updates while using excel to edit other excel files. Below are the test codes I have: -------------------------------------------------------------------------------------- from time import sleep import win32com.client as w32c def test(): w32c.pythoncom.CoInitialize() print w32c.pythoncom._GetInterfaceCount() app1 = w32c.Dispatch("Excel.Application") #app1.Visible=False #app1.Interactive = False wb=app1.Workbooks.Open("c:\\temp\\Book1.xls") sleep(3) sh=wb.Sheets("Sheet1") sh.Cells(2,1).Value = "Hello, world!" sh = None wb.Save() wb = None app1 = None w32c.pythoncom.CoUninitialize() print w32c.pythoncom._GetInterfaceCount() ------------------------------------------------------------------------------------- If the user just looks at the file then it's fine, but if the user double clicks one cell, which will have a cursor flashing in the cell, then it will lead to a crash of the program with error: "Call was rejected by callee." I can make the program keep trying to access the file, but if the user doesn't make the flashing cursor disappear, the program will wait forever! I know excel has the fuction such that when a user is accessing a file and other users open that file, it will prompt for options of opening it as read-only or sending notification. I have been trying to implement that in the program, but don't know how. So, any suggestion will be greatly appreciated! - Barry From magicalnepal at gmail.com Thu Jan 17 00:07:45 2008 From: magicalnepal at gmail.com (magicalnepal at gmail.com) Date: Wed, 16 Jan 2008 21:07:45 -0800 (PST) Subject: Thinking of your next holiday Message-ID: <52a96c2d-6d99-4635-8d3f-781ed1ef6445@s12g2000prg.googlegroups.com> Are you planning for vacation, holiday? We would like you to spare your valuable time! Visit our website www.magical-nepal.com for information on Nepal, Tibet and Bhutan. Thanking you in advance visiting and look forward to assist you. Regards, Rath Nepal Tours and Travels P O Box 10691, 2nd Floor Mountain Plaza Tel: 977-1-4268948, 4258141, 4264512 Fax: 977-1-4264512 E-mail: sales at magical-nepal.com website: www.magical-nepal.com From bdesth.quelquechose at free.quelquepart.fr Sun Jan 6 14:46:21 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 06 Jan 2008 20:46:21 +0100 Subject: Basic inheritance question In-Reply-To: <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> Message-ID: <4781300a$0$17701$426a74cc@news.free.fr> Lie a ?crit : > On Jan 5, 5:40 pm, MartinRineh... at gmail.com wrote: > >>Jeroen Ruigrok van der Werven wrote: >> >> >>>Shouldn't this be: >> >>>self.startLoc = start >>>self.stopLoc = stop >> >>Thanks! Of course it should. Old Java habits die slowly. > > > No, seriously it isn't Java habits only, most other languages wouldn't > need explicit calling of class name. Where is the "explicit calling of class name" exactly ? From steven at REMOVE.THIS.cybersource.com.au Thu Jan 3 21:47:06 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 04 Jan 2008 02:47:06 -0000 Subject: dictionary/hash and '1' versus 1 References: Message-ID: On Thu, 03 Jan 2008 16:56:00 -0600, Reedick, Andrew wrote: > The problem occurred because a method used to generate keys was > returning a string instead of a number without an explicit conversion > taking place. And since I was using hash.get(i, default_value) to avoid > having to pair every key lookup with a hash.has_key(), no exception was > thrown when the key wasn't found. # How to fix this broken function without modifying the source? def foo(arg): """Returns a string instead of a number.""" return "1" # oops I meant 1 _foo = foo # save a reference to original broken function foo = lambda *args, **kwargs: int(_foo(*args, **kwargs)) # and patch it And now you can use foo(arg) confident that it will always return an int like you expect. Modifications of this technique should be obvious. -- Steven From caca at mailinator.com Sat Jan 5 05:16:19 2008 From: caca at mailinator.com (caca at mailinator.com) Date: Sat, 5 Jan 2008 02:16:19 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <33417662-8246-4950-9b86-265aa1c63c69@c23g2000hsa.googlegroups.com> Message-ID: > Caching might help. > > If random_pick is called several times with the same list(s) then > cache the result of > [property(i) for i in a_list] against a_list. > > If random_pick is called several times with list(s) with multiple > instances of list items then cache > property(i) against i for i in a_list . > > You could do both. > > You might investigate wether property(i) could be implemented using a > faster algorithm, maybe table lookup, or interpolation from initial > table lookup. > > - Paddy. Thanks, Paddy. Those are interesting general comments for the general problem. By the way, I noticed two things: I forgot to write randint in the third approach: > > a=globalRNG.randint(1,len(a_list)) The warning "The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet." means a person, but not a bot, may see my email address, so it is safe to use my real address next time... From henry.baxter at gmail.com Sat Jan 12 03:49:40 2008 From: henry.baxter at gmail.com (Henry Baxter) Date: Sat, 12 Jan 2008 00:49:40 -0800 Subject: ctypes, GetWindowLongPtr In-Reply-To: References: <8d04436f0801111814p31b3a98brd9fb5eed48860505@mail.gmail.com> Message-ID: <8d04436f0801120049q2f19536cpddbeabb1cfd15d8f@mail.gmail.com> David, Quick reply :) That pointed me in the right direction. The documentation I was reading indicated the use of GetWindowLongPtr, but at compile time (if one were writing C/C++ code) which particular version (Long/64, or 32 bit) is chosen. That's where I was getting mixed up - thanks! Henry On Jan 11, 2008 9:33 PM, David Wahler wrote: > On Jan 11, 2008 9:14 PM, Henry Baxter wrote: > > Hello, > > > > I have been happily using ctypes for a while to do win32 programming. I > use the Microsoft documentation to understand the function, then call it > with the help of ctypes. > > > > The problem is that the docs says user32.dll has GetWindowLongPtr, but > ctypes can't find it using windll.user32.GetWindowLongPtrA or > windll.user32.GetWindowLongPtrW or windll.user32.GetWindowLongPtr. Errors > look like this: > > > > Traceback (most recent call last): > > File "Z:\experiments\windowsapp3.py", line 106, in > > GetWindowLongPtr = windll.user32.GetWindowLongPtrA > > File "C:\Python25\lib\ctypes\__init__.py", line 353, in __getattr__ > > func = self.__getitem__(name) > > File "C:\Python25\lib\ctypes\__init__.py", line 358, in __getitem__ > > func = self._FuncPtr((name_or_ordinal, self)) > > AttributeError: function 'GetWindowLongPtrA' not found > > > > I have the same problem with the SetWindowLongPtr function. > > > > I can use plenty of other functions (GetParent, CreateWindowExA, > DefWindowProcA, and etc) but not these ones. > > > > > > I don't understand what goes on with ctypes under the hood really, so my > troubleshooting abilities at this point are quite lacking! I would > appreciate any help you could offer. > > > > > > Thanks! > > I don't have a copy of the official Win32 headers handy, but the MinGW > version of winuser.h contains this section of code: > > WINUSERAPI LONG WINAPI GetWindowLongA(HWND,int); > WINUSERAPI LONG WINAPI GetWindowLongW(HWND,int); > #ifdef _WIN64 > WINUSERAPI LONG_PTR WINAPI GetWindowLongPtrA(HWND,int); > WINUSERAPI LONG_PTR WINAPI GetWindowLongPtrW(HWND,int); > #else > #define GetWindowLongPtrA GetWindowLongA > #define GetWindowLongPtrW GetWindowLongW > #endif > > which I would take to mean you need to use GetWindowLong on 32-bit > windows, and GetWindowLongPtr on 64-bit windows. > > -- David > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Mon Jan 28 09:36:15 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 28 Jan 2008 06:36:15 -0800 (PST) Subject: wx.EVT_RIGHT_UP strangeness? References: Message-ID: <03340347-329f-493c-8027-1736b38e589a@s12g2000prg.googlegroups.com> On Jan 26, 1:30 pm, sigpo... at hotmail.com wrote: > I am playing with wxPython 2.8.7.1 on OS X 10.4.11 with MacPython 2.5 > > When running the demo program, the ShapeWindow demo does not close the > window > on right click. It turns out that the wx.EVT_RIGHT_UP does not fire. > > I discovered that one way to get it to fire is to bind the > wx.EVT_RIGHT_DOWN event also. > > Thus adding the following two lines solves the problem: > > in __init__ add: self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) > > secondly add: def OnRightDown(self, evt): pass > > Everything then works ok. > > My question is: Is this how it is supposed to work, and if not, am I > the only one with > this problem? It works for me without any changes. I right-click the snake image and it disappears. I'm on Windows XP, Python 2.4/2.5 with wxPython 2.8.7.1 What OS and wxPython version are you using? You may want to post to the wxPython user's group too. They can tell you if it is an OS dependent bug or not: http://wxpython.org/maillist.php Mike From boblatest at yahoo.com Tue Jan 22 04:56:55 2008 From: boblatest at yahoo.com (Robert Latest) Date: 22 Jan 2008 09:56:55 GMT Subject: Question on sort() key function References: <5vlopgF1mv4ekU1@mid.dfncis.de> <7xve5mfdmr.fsf@ruckus.brouhaha.com> <5vlqbjF1kl9cjU1@mid.dfncis.de> Message-ID: <5vlsv7F1n3d1bU1@mid.dfncis.de> Peter Otten wrote: > Robert Latest wrote: > >> Paul Rubin wrote: >>> The attribute is on instances of File, not on the class itself. See >>> if this works: >>> >>> flist.sort(key=lambda f: f.mod_date.toordinal) >> >> It doesn't throw an error any more, but neither does it sort the list. This, >> however, works: >> >> ---------------------- >> def by_date(f1, f2): >> return f1.mod_date.toordinal() - f2.mod_date.toordinal() >> >> flist.sort(by_date) >> ---------------------- >> >> So I'm sticking with it, although I sort of liked the key approach. >> >> robert > > This should work then: > > def date_key(f): > return f.mod_date.toordinal() > flist.sort(key=date_key) > > This can also be written as > > flist.sort(key=lambda f: f.mod_date.toordinal()) Well, that's almost Paul's (non-working) suggestion above, but it works because of the parentheses after toordinal. Beats me how both versions can be valid, anyway. To me it's all greek. I grew up with C function pointers, and they always work. robert From jeffober at gmail.com Thu Jan 17 14:26:53 2008 From: jeffober at gmail.com (Jeff) Date: Thu, 17 Jan 2008 11:26:53 -0800 (PST) Subject: how django discovers changed sources References: <18udndZmKMfMNhLanZ2dnUVZ_rzinZ2d@comcast.com> Message-ID: That is the behavior of the development server. When you are writing your application, you don't want to have to manually restart the server every time you change a file. On apache it obviously doesn't do that. From bperry.volatile at gmail.com Wed Jan 16 08:37:27 2008 From: bperry.volatile at gmail.com (Brandon Perry) Date: Wed, 16 Jan 2008 07:37:27 -0600 Subject: Unknown cause to error (new to python) Message-ID: <1200490647.5903.3.camel@bperry-laptop> Hi, I am having to compile a standalone version of python for the web server I use (they don't allow access to /usr/bin/python). I posted earlier about a GLib error, but I have fixed that now. I am very close to getting this to work, but I am getting some weird errors. File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", line 41, in ? File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", line 71, in ? File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", line 4, in ? File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", line 4, in ? File "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", line 15, in ? I am using 2.2 for compatibility purposes. Thanks, Brandon From jr9445 at ATT.COM Fri Jan 11 16:28:50 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 11 Jan 2008 15:28:50 -0600 Subject: Newbie question on Classes In-Reply-To: <2a7ff558-a688-4b6f-ba05-126d7b533cac@e10g2000prf.googlegroups.com> References: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> <2a7ff558-a688-4b6f-ba05-126d7b533cac@e10g2000prf.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 John Machin > Sent: Friday, January 11, 2008 4:08 PM > To: python-list at python.org > Subject: Re: Newbie question on Classes > > On Jan 11, 9:27 am, "Reedick, Andrew" wrote: > > > -----Original Message----- > > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > > list-bounces+jr9445=att.... at python.org] On Behalf Of Adrian Wood > > > Sent: Thursday, January 10, 2008 4:47 PM > > > To: python-l... at python.org > > > Subject: Newbie question on Classes > > > > > > How about searching the garbage collector? > > Not a good idea, because gc is an implementation artifact and in fact > is specific to the C Python implementation; you won't find it in e.g. > Iron Python or Jython. > a) I forgot the ';-)' and/or tag. b) It was junk code. A cleaner loop would be (which I figured out 5 minutes after posting =P ): for i in gc.get_objects(): if isinstance(i, Person): print i.__class__, "%x" % id(i), i.SomeMethod() c) It's good to know about GC being CPython only. d) You forgot to mention the problem that some of the objects could be 'deleted' but not garbage collected yet. e) Most importantly, anyone who is using the garbage collector as their object manager isn't into proper coding practices in the first place. From mark.e.tolonen at mailinator.com Sun Jan 13 13:51:59 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Sun, 13 Jan 2008 10:51:59 -0800 Subject: Exceptions - How do you make it work like built-in exceptions? References: <7888e20f-0775-46c4-a6e2-3fc3825c5145@e23g2000prf.googlegroups.com> Message-ID: "Lie" wrote in message news:7888e20f-0775-46c4-a6e2-3fc3825c5145 at e23g2000prf.googlegroups.com... >A built-in exceptions, when raised, would print traceback that points > out the offending code, like this: > > Traceback (most recent call last): > File "F:\dir\code.py", line 43, in > a = 1/0 <<<--- > ZeroDivisionError: integer division or modulo by zero > > a user-made exception, when raised, would print traceback that points > out the code that raises the exception > > Traceback (most recent call last): > File "F:\dir\code.py", line 48, in > raise SomeException('Some Exception Message') <<<--- > SomeException: Some Exception Message > > which is generally of little use (yeah, it's possible to trace the > code from the line number, but sometimes it might not be that easy, > cause the line number is (again) the line number for the raising code > instead of the offending code) > > The sample exception was generated from this code: > #### > class SomeException(Exception): > pass > > try: > a = 1/0 > except: > raise SomeException('Some Exception Message') > #### > > Is it possible to make the user-made exception points out the > offending code? The raise statement *was* the offending (unhandled exception) code. The ZeroDivisionError was handled by your except clause. You can override the traceback your exception will use with the three-expression form of the raise statement (See Section 6.9 "The raise statement" in the Python Reference Manual) by passing the traceback of the original exception: ###### CODE ##### import sys class SomeException(Exception): pass try: a=1/0 except: org_type,org_value,org_traceback = sys.exc_info() raise SomeException,'had some problems with this code',org_traceback ###### OUTPUT ###### Traceback (most recent call last): File "exc.py", line 7, in a=1/0 SomeException: had some problems with this code --Mark From sgeiger at ncee.net Thu Jan 10 22:36:31 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Thu, 10 Jan 2008 21:36:31 -0600 Subject: getting n items at a time from a generator In-Reply-To: <7x7iihcbsg.fsf@ruckus.brouhaha.com> References: <7x7iihcbsg.fsf@ruckus.brouhaha.com> Message-ID: <4786E43F.2000402@ncee.net> Paul Rubin wrote: > Tim Roberts writes: > >> I have to say that I have found this to be a surprisingly common need as >> well. Would this be an appropriate construct to add to itertools? >> > > I'm in favor. > I am ecstatic about the idea of getting n items at a time from a generator! This would eliminate the use of less elegant functions to do this sort of thing which I would do even more frequently if it were easier. Is it possible that this syntax for generator expressions could be adopted? >>> sentence = 'this is a senTence WiTH' >>> generator = (word.capitalize() for word in sentence.split()) >>> print generator.next(3,'PadValue') ('This','Is','A') >>> print generator.next(3,'PadValue') ('Sentence','With','PadValue') >>> generator.next(3,'PadValue') Traceback (most recent call last): File "", line 1, in StopIteration >>> While on the topic of generators: Something else I have longed for is assignment within a while loop. (I realize this might be more controversial and might have been avoided on purpose, but I wasn't around for that discussion.) >>> sentence = 'this is a senTence WiTH' >>> generator = (word.capitalize() for word in sentence.split()) >>> while a,b,c = generator.next(3,'PadValue'): ... print a,b,c ... This Is A Sentence With PadValue >>> -- 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 tjreedy at udel.edu Wed Jan 16 15:16:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Jan 2008 15:16:40 -0500 Subject: module naming conventions References: <7f39199a-3334-4bcc-a424-5102f042ed01@1g2000hsl.googlegroups.com><87zlv8dnya.fsf@benfinney.id.au><6a53a14a-8f7c-4b6b-986f-48c7698f679f@v29g2000hsf.googlegroups.com><8763xwdj9c.fsf@benfinney.id.au> <478d113a$0$26041$88260bb3@free.teranews.com> Message-ID: "Tobiah" wrote in message news:478d113a$0$26041$88260bb3 at free.teranews.com... | | > Release your package as free software on the Cheeseshop | > . If the name you want is already | > taken, pick one that will help users distinguish yours from the | > existing one. | > | | I like this idea. I developed a library with a name that got | a couple of obscure software related hits on Google. I checked | sourceforge, and found that the name was available, so I stuck | my flag in the dirt. | | It was a python module, so I suppose I will have to look into | the cheeseshop. Is that as open as sourceforge, or is it only | for mature, sophisticated modules? Look at the cheeseshop page, but I would say that 'mature' and 'sophisticated' are too high a bar. 'Potentially useful and not-known-to-be-buggy' should be more like it. From albert at spenarnc.xs4all.nl Tue Jan 22 12:49:51 2008 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 22 Jan 2008 17:49:51 GMT Subject: Beginners question about debugging (import) Message-ID: I'm starting with Python. First with some interactive things, working through the tutorial, then with definitions in a file called sudoku.py. Of course I make lots of mistakes, so I have to include that file time and again. I discovered (the hard way) that the second time you invoke from sudoku.py import * nothing happens. There is reload. But it only seems to work with import sudoku Now I find myself typing ``sudoku.'' all the time: x=sudoku.sudoku() y=sudoku.create_set_of_sets() sudoku.symbols Is there a more convenient way? (This is a howto question, rather difficult to get answered from the documentation.) Groetjes Albert ~ -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- like all pyramid schemes -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From pavloutefkros at gmail.com Mon Jan 28 12:06:58 2008 From: pavloutefkros at gmail.com (pavloutefkros at gmail.com) Date: Mon, 28 Jan 2008 09:06:58 -0800 (PST) Subject: referer url References: <0e7fb40e-809c-4979-bbb8-0cd9a7e816c2@t1g2000pra.googlegroups.com> Message-ID: Thanks for the reply. 1) CGI so i'm doing it right. 2) this is impossible as i'm doing the exact same thing with another language and it utterly works. 3) the same as above 4) no.. this gets nerve breaking! From sjmachin at lexicon.net Mon Jan 21 04:23:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jan 2008 01:23:34 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <13p8803epubo92b@corp.supernews.com> <14dc1431-909b-4702-a695-846a683ef345@q77g2000hsh.googlegroups.com> Message-ID: <2a12db76-70c3-4ffe-94dc-b5595201f05f@f47g2000hsd.googlegroups.com> On Jan 21, 8:12 pm, pythonewbie wrote: > On 21 jan, 09:53, pythonewbie wrote: > > > > > On 21 jan, 05:31, Dennis Lee Bieber wrote: > > > > On Sun, 20 Jan 2008 13:58:13 -0800 (PST), pythonewbie > > > declaimed the following in comp.lang.python: > > > > > I just would like to know if I would ALWAYS find the install directory > > > > in sys.path[6] and site-packages directory in sys.path[7] on any Win32 > > > > platform and sys.path[2] and site-packages directory in sys.path[6] on > > > > any Linux platform. > > > > Unlikely... > > > > >>> sys.path[6] > > > > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg'>>> sys.path[2] > > > > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg'>>> sys.path > > > > ['', 'E:\\Python24\\lib\\site-packages\\pyopengl-3.0.0a5-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg', > > > 'E:\\Python24\\lib\\site-packages\\sqlobject-0.7.6-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\celementtree-1.0.5_20051216-py2.4-win32.egg', > > > 'E:\\Python24\\lib\\site-packages\\configobj-4.4.0-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\ruledispatch-0.5a0.dev_r2306-py2.4-win32.egg', > > > 'E:\\Python24\\lib\\site-packages\\formencode-0.7.1-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\pastescript-1.3.4-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\elementtree-1.2.6_20050316-py2.4-win32.egg', > > > 'E:\\Python24\\lib\\site-packages\\simplejson-1.7.1-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\cherrypy-2.2.1-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\turbocheetah-0.9.5-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\turbojson-1.0-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\pyprotocols-1.0a0dev_r2302-py2.4-win32.egg', > > > 'E:\\Python24\\lib\\site-packages\\pastedeploy-1.3-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\paste-1.3-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\cheetah-2.0rc8-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\setuptools-0.6c6-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\turbogears-1.0.3.2-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\turbokid-1.0.2-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\kid-0.9.6-py2.4.egg', > > > 'e:\\python24\\lib\\site-packages\\scipy', > > > 'C:\\WINDOWS\\system32\\python24.zip', 'e:\\UserData\\Dennis Lee > > > Bieber\\My Documents', 'E:\\Python24\\DLLs', 'E:\\Python24\\lib', > > > 'E:\\Python24\\lib\\plat-win', 'E:\\Python24\\lib\\lib-tk', > > > 'E:\\Python24\\Lib\\site-packages\\pythonwin', 'E:\\Python24', > > > 'E:\\Python24\\lib\\site-packages', > > > 'E:\\Python24\\lib\\site-packages\\Numeric', > > > 'E:\\Python24\\lib\\site-packages\\PIL', > > > 'E:\\Python24\\lib\\site-packages\\win32', > > > 'E:\\Python24\\lib\\site-packages\\win32\\lib', > > > 'E:\\Python24\\lib\\site-packages\\wx-2.8-msw-unicode'] > > > > >>> os.environ["PATH"] > > > > 'E:\\Python24\\;C:\\GNAT\\bin;C:\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\PROGRA~1\\MySQL\\MySQL > > > Server 5.0\\bin;C:\\Program Files\\SciTE;C:\\Program > > > Files\\Java\\jre1.6.0_03\\bin;C:\\Program > > > Files\\Java\\jdk1.6.0_03\\bin;C:\\Program Files\\Common > > > Files\\Adobe\\AGL;C:\\MSSQL7\\BINN;c:\\PROGRA~1\\sdb\\programs\\bin;c:\\PROGRA~1\\sdb\\programs\\pgm;C:\\Tcl\\bin;C:\\Program > > > Files\\Common Files\\Roxio Shared\\DLLShared\\;C:\\Program Files\\Common > > > Files\\Roxio Shared\\9.0\\DLLShared\\;e:\\Python24\\Scripts;c:\\Regina' > > > > -- > > > 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/ > > > OK Denis Lee, I see now. I appreciate your clear and simple to > > understand reply. > > > All posts on this topic, have been appreciated a lot... Thanks to all > > helpers. > > > Cheers > > Hi John Machin, > > Your code : > > >>> import sys, re > >>> for p in sys.path: > > ... m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p) > ... if m: > ... print m.group(1, 0) > ... break > ... else: > ... raise Exception('Huh?') > ... > > Does not work on my PC : Traceback (most recent call last): > File "/home/eproust/john-machin_recup_rep_site-packages.py", line 9, > in > raise Exception('Huh?') > Exception: Huh? My palantir is in the workshop, so you'll have to tell me what's in sys.path on your machine. > > Even if I remove all code below the else: part of the script... Uh-huh. From sjmachin at lexicon.net Sun Jan 27 02:56:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 26 Jan 2008 23:56:31 -0800 (PST) Subject: how to make format operator % work with unicode as expected References: Message-ID: On Jan 27, 3:06 pm, "Peter Pei" wrote: > I probably should mention that what I want is to make all parts of the > string aligned, and look like table. I am not looking for other ways to make > it table-alike, but only interested in making % work with unicode -counting > characters not bytes... Can you show some *code* that demonstrates the alleged problem? E.g. len("" % some_unicode) != expected_len Reading this may help: http://www.chiark.greenend.org.uk/~sgtatham/bugs.html From Russ.Paielli at gmail.com Sun Jan 27 21:50:56 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 18:50:56 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Jan 27, 5:13 pm, Wildemar Wildenburger wrote: > Ben Finney wrote: > > "Andr?" writes: > > >> Personally, I like the idea you suggest, with the modification that I > >> would use "." instead of "@", as in > > >> class Server(object): > >> def __init__(self, .host, .port, .protocol, .bufsize, .timeout): > >> pass > > > -1. > > > That leading dot is too easy to miss when looking over the code. > > class Server(object): > def __init__(self, self.host, self.port, > self.protocol, self.bufsize, self.timeout): > pass > > ? > > /W That makes sense to me. Come to think of it, why restrict this convention to the constructor? Or am I just opening a can of worms? From robert.kern at gmail.com Sun Jan 13 22:15:16 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 13 Jan 2008 21:15:16 -0600 Subject: Slicing wrapped numpy arrays In-Reply-To: References: Message-ID: Martin Manns wrote: > On Sun, 13 Jan 2008 16:03:16 -0600 > Robert Kern wrote: > >> Martin Manns wrote: >>> Hi, >>> >>> I have created a class that wraps a numpy array of custom objects. I >>> would like to be able to slice respective objects (without copying >>> the array if possible). >>> >>> I have browsed the doc and found some hints at __getitem__. >>> However, I still do not grasp how to do it. How do I implement >>> __getitem__ correctly? >>> mymap[10:20,15:20,:] # This line should work afterwards >> The first thing you should do is simply implement a very basic, >> nonfunctional version just to see what objects come in: >> >> In [1]: class Sliceable(object): >> ...: def __getitem__(self, arg): >> ...: print arg >> ...: > > I did that and got here: > >> (slice(None, None, 2), slice(10, None, 10)) > > However, I still do not see how I get a Map object that employs a > slice of the array without creating a new Map object. That's because creating a new Map object is the right thing to do. Instead of making Map.__init__() generate the map array from the dimensions, it should just take a preconstructed map array. You can use a @classmethod or just a factory function to provide an alternate constructor which builds a Map from the dimensions. When designing classes, I usually try to do as little computation as possible in an __init__(). Doing a lot of stuff there limits the ways you can build the object later. For some classes, this doesn't matter a whole lot, but for data structures that can be sliced and concatenated or otherwise transformed, you really want that flexibility. -- 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 paddy3118 at googlemail.com Sat Jan 26 02:59:57 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 25 Jan 2008 23:59:57 -0800 (PST) Subject: finding child cpu usage of a running child References: Message-ID: On Jan 26, 5:43 am, Karthik Gurusamy wrote: > Hi, > > Wondering if there is a way to measure a child process's cpu usage > (sys and user) when the child is still running. I see os.times() > working fine in my system (Linux 2.6.9-42.7.ELsmp), but it gives valid > data only after the child has exited. When the child is alive, > os.times() data for child is zero for both child-sys and child-user > cpu. > > My script (process P1) launches child process P2 (using > popen2.Popen3). P2 is a long running process (big compilation). Every > minute or so, from P1, I want to measure how much cpu P2 has consumed > and based on that I can make some estimate on the completion time of > P2 (I have a rough idea how much total cpu P2 needs to complete). > > I understand it may be too expensive to update this information to the > parent process when any of the child/grand-child completes; but > wondering if any there is any way to get this info; the expensive > operations is on-demand only when the request is made. > > Thanks, > Karthik I had a similar requirement in December and found: http://lilypond.org/~janneke/software/ proc-time.c and proc-time.py poll /proc/.... files whilst command is running to get stats. Enjoy, - Paddy. From bj_666 at gmx.net Tue Jan 22 03:08:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Jan 2008 08:08:19 GMT Subject: what's this instance? References: Message-ID: <5vlmjjF1n19plU2@mid.uni-berlin.de> On Tue, 22 Jan 2008 15:36:49 +0800, J. Peng wrote: > def safe_float(object): > try: > retval = float(object) > except (ValueError, TypeError), oops: > retval = str(oops) > return retval > > x=safe_float([1,2,3,4]) > print x > > > The code above works well.But what's the instance of "oops"? where is it > coming from? I'm totally confused on it.thanks. `oops` is bound to the `ValueError` or `TypError` object if `float()` raises such an exception. Ciao, Marc 'BlackJack' Rintsch From gefafwisp at gmail.com Wed Jan 30 13:19:13 2008 From: gefafwisp at gmail.com (gefafwisp at gmail.com) Date: Wed, 30 Jan 2008 10:19:13 -0800 (PST) Subject: Updating documents in PyLucene Message-ID: Hi all, The way that Lucene (and by extension, PyLucene) seems to work is that updates to documents are implemented by the user as a document addition (of the new version) and subsequent deletion (of the old version). My problem is that I'd like to update a number of documents which have their Store flag set to NO - they're indexed, but not stored. I don't have the original text content of these documents available anywhere else - is there any way for me to get this un-stored indexed data from the old document into the new? Also posting to comp.lang.java.programmer. Thanks, James From ndbecker2 at gmail.com Fri Jan 25 16:47:22 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 25 Jan 2008 16:47:22 -0500 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> Message-ID: Henry Baxter wrote: > Oops, gmail has keyboard shortcuts apparently, to continue: > > def maxi(l): > m = max(l) > for i, v in enumerate(l): > if m == v: > return i > > But it seems like something that should be built in - or at least I should > be able to write a lambda function for it, but I'm not sure how to do that > either...Suggestions are very much welcome! > I really think this is a good candidate for a builtin. I suggest: max2 (x): """ return (minvalue,minindex)""" This allows efficient usage in all cases, including iterators (not just sequences). From steven.bethard at gmail.com Fri Jan 25 15:05:06 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 25 Jan 2008 13:05:06 -0700 Subject: is possible to get order of keyword parameters ? In-Reply-To: <5b6e2bc6-8136-4e3a-8bf2-bb6d689d6110@s8g2000prg.googlegroups.com> References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> <5b6e2bc6-8136-4e3a-8bf2-bb6d689d6110@s8g2000prg.googlegroups.com> Message-ID: rndblnch wrote: > my goal is to implement a kind of named tuple. > idealy, it should behave like this: > p = Point(x=12, y=13) > print p.x, p.y > but what requires to keep track of the order is the unpacking: > x, y = p > i can't figure out how to produce an iterable that returns the values > in the right order. > relying on a "natural" order of the key names is not possible: x, and > y are alphabetically sorted but the following example should also > work: > size = Point(width=23, height=45) > w, h = size There are a couple of recipes for named tuples: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261 The latter of these will be in Python 2.6. Using that recipe, and your example, you would write:: Point = namedtuple('Point', 'x y') p = Point(x=12, y=13) x, y = p Point = namedtuple('Point', 'width', 'height') size = Point(width=23, height=45) w, h = size STeVe From dickinsm at gmail.com Sat Jan 12 11:34:02 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 12 Jan 2008 08:34:02 -0800 (PST) Subject: Compiling fails on Mac OS X 10.5 References: <352080fd-ace1-46d4-82b1-94937b851a38@k2g2000hse.googlegroups.com> Message-ID: On Jan 12, 9:41?am, mc wrote: > Hi! > I'm trying to compile on my Macbook with OS X 10.5. I have all updates > and Xcode 3.0 installed. > > I checked python out with: svn checkouthttp://svn.python.org/projects/python/branches/py3k > After that I did "./configure" in the ?created "py3k" dir. Everything > went fine. But make fails with the following error message: > ranlib libpython3.0.a > gcc ?-u _PyMac_Error -o python.exe \ > ? ? ? ? ? ? ? ? ? ? ? ? Modules/python.o \ > ? ? ? ? ? ? ? ? ? ? ? ? libpython3.0.a -ldl > make: *** [sharedmods] Error 1 > > I tried checking out many times. I also tried de 3.0a2 release,gives > me the same error. I've heard others have compiled it successfully on > Leopard so I wonder what causes the problems on my system. Could you post the rest of the ./configure and compilation output? make might be rereporting an error that occurred further up. I don't see anything related on the Python bug tracker. It might be worth posting a bug report at bugs.python.org Mark From sjmachin at lexicon.net Thu Jan 24 16:53:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 24 Jan 2008 13:53:53 -0800 (PST) Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> Message-ID: On Jan 25, 8:26 am, Ira.Ko... at gmail.com wrote: > I need to isolate all lines that start with two characters (zz to be > particular) What does "isolate" mean to you? What does this have to do with sorting? What do you actually want to do with (a) the lines starting with "zz" (b) the other lines? What percentage of the lines start with "zz"? When looking at the GnuWin32 collection: (a) "Unicode" is not relevant to your sort problem. (b) grab yourself a wc and a grep while you're there -- they will help with "how many lines" and "what percentage of lines" questions. From svenn.bjerkem at googlemail.com Wed Jan 9 08:56:31 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Wed, 9 Jan 2008 05:56:31 -0800 (PST) Subject: executing newgrp from python in current shell possible? Message-ID: Hi, as a user on a linux system I am member of the groups "users" and "design" with users as my default group. To controll the accessibility of some parts of the file system, creation of files and directories in those parts must be done with group "design". This is currently done manually with "newgrp design" on the command line before doing anything else. I have been looking for a way to execute this command as a part of a script, but it seems that the changes are only valid in the context of the script and when the script exits, the current shell still have the original "users" group setting. It looks like the command spawns a new command line in the context of the current xterm as I get back to my old command line when exiting (instead of the xterm dissapearing) A possible alternative could be to have the python script launch a new shell, but I still have the problem to set the group id for that new shell (lack of python knowledge). I am happy for any advice. Maybe it is simply not possible to do this kind of operation from a script in python on linux. -- kind regards, Svenn From arnodel at googlemail.com Tue Jan 22 02:11:23 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 21 Jan 2008 23:11:23 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> Message-ID: On Jan 22, 3:20?am, Alan Isaac wrote: > I want to generate sequential pairs from a list. > Here is a way:: > > ? ? from itertools import izip, islice > ? ? for x12 in izip(islice(x,0,None,2),islice(x,1,None,2)): > ? ? ? ? print x12 > > (Of course the print statement is just illustrative.) > What is the fastest way? (Ignore the import time.) > > Thanks, > Alan Isaac Don't know the fastest, but here's a very concise way: from itertools import izip def ipairs(seq): it = iter(seq) return izip(it, it) >>> list(pairs(xrange(10))) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] >>> list(pairs('hello')) [('h', 'e'), ('l', 'l')] -- Arnaud From rphenry at home.com Sat Jan 12 13:09:50 2008 From: rphenry at home.com (Richard Henry) Date: Sat, 12 Jan 2008 10:09:50 -0800 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> <4788de48$0$26887$ecde5a14@news.coretel.net> Message-ID: "radiosrfun" wrote in message news:4788de48$0$26887$ecde5a14 at news.coretel.net... > "default" wrote in message > news:91hho3tr56dpsfqsav4lnr8sl944bbrviv at 4ax.com... > > On Sat, 12 Jan 2008 02:01:09 -0500, "radiosrfun" > > wrote: > > > >>I WISH - that the President and Congress of this country would shut off > >>ALL > >>foreign aid. > > > > Ditto that. > > > > Israel is the chief beneficiary of our foreign aid largesse. Some 8 > > billion dollars annually. What doesn't find its way into politicians > > pockets goes to pay for a military that is winning us a lot of new > > friends in the Arab world. > > > > We pay Egypt ~ 2 billion a year in extortion to keep them from > > attacking Israel. > > > > The actually amount Israel receives is not really known to the public. > > The official numbers read something like 3 billion in aid, and another > > 5 billion in guaranteed loans - which are turned into grants year > > after year. This is money we borrow so there's an additional interest > > burden. > > > > Actually when you talk about shutting off "foreign aid" you may be > > making thermate's point for him. > > -- > > Well - the first cup of coffee hasn't exactly kicked in yet - but I believe > I know what you're saying and if correct - you may have a point there. According to the US Govt for 2006: Israel: $2.6B Egypt $1.8B Iraq: $9.8B Afghanistan $3.7B http://qesdb.usaid.gov/gbk/ From dickinsm at gmail.com Mon Jan 28 09:40:23 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 28 Jan 2008 06:40:23 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: <13pi8fiiqgljdb5@corp.supernews.com> <13pjgrj540qt98a@corp.supernews.com> Message-ID: <15b62428-a10f-46bb-bf4c-3f37474adc6f@c23g2000hsa.googlegroups.com> On Jan 28, 6:50 am, Antoon Pardon wrote: > My personal preference would be that python would allow people the > choice, with the default being that any operation that resulted > in a non numeric result would throw an exception. > > People who somehow made it clear they know how to work with inf, and > NaN results, would get silent NaN where no exceptions would be thrown. I also think this would be the ideal situation. Getting there would require a lot of thought, planning, a PEP or two, and some hard work and tricky coding to deal with all the different ways that the C compiler, libm and hardware might try to mess things up. Right now I don't have time for this :-( Anyone else? > > Putting aside sorting and max/min, what is the use-case for having > > comparisons with NaN succeed? What benefit will it give you? > > I guess the same benefit it gives to those that have operations with > NaN succeed. If 3 * NaN should succeed and all sort of other stuff, > why suddenly make an exception for 3 < NaN. Right. This is especially true when the result of the comparison is treated as number (i.e. 0 or 1) rather than as a boolean, and goes back into the calculation in some way. On the other hand, there are certainly situations where you want a comparison with a NaN to raise an exception. I guess this is why IEEE-754r provides two sets of comparison operators: signaling and non-signaling. Mark From jayabarathi2007 at gmail.com Fri Jan 25 01:18:23 2008 From: jayabarathi2007 at gmail.com (Barathi) Date: Thu, 24 Jan 2008 22:18:23 -0800 (PST) Subject: Method for intracardiac therapy using sensor for heart wall thickness Message-ID: Method for intracardiac therapy using sensor for heart wall thickness Localization of muscle gene ..... rotating and reciprocating piston metering pumps, peristaltic pumps or any ... http://www.freewebs.com/boreqwe/ http://indianfriendfinder.com/go/g931378-pmem http://bigchurch.com/go/g931377-pmem From fredrik at pythonware.com Thu Jan 3 10:16:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 16:16:42 +0100 Subject: problem with global var In-Reply-To: <3448388f0801030638sd285c7dh78b9ea9f7b911139@mail.gmail.com> References: <3448388f0801030638sd285c7dh78b9ea9f7b911139@mail.gmail.com> Message-ID: Bruno Ferreira wrote: > When I execute the program _without_ the lines 10 and 11: > > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > > it runs perfectly. > > But if I execute the program _with_ those lines, this exception is thrown: > > bruno at ts:~$ python topsquid.py > Traceback (most recent call last): > File "topsquid.py", line 20, in > add_sorted (linefields) > File "topsquid.py", line 6, in add_sorted > if int(list[4]) > int(topsquid[i][4]): > UnboundLocalError: local variable 'topsquid' referenced before assignment Python uses static analysis to determine if a variable is local to a function; somewhat simplified, if you assign to the variable inside the function, *all* uses of that variable inside the function will be considered local. for the full story, see: http://docs.python.org/ref/naming.html to fix this, you can insert a "global" declaration at the top of the def add_sorted (list): global topsquid # mark topsquid as global in this function ... in this case, you can also avoid the local assignment by modifying the list in place; if len(topsquid) > 50: topsquid[:] = topsquid[0:50] or, as a one-liner: del topsquid[50:] From meesters at uni-mainz.de Tue Jan 29 08:22:36 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Tue, 29 Jan 2008 14:22:36 +0100 Subject: extending Python - passing nested lists References: <3ddeaf07-3f4b-4d68-a176-9205fa4d234b@k39g2000hsf.googlegroups.com> Message-ID: Thanks. Point is that all such approaches would require lots(!) of calls to the Python API - a way by which I won't gain the desired speed. I've tried pyrex and the corresponding C-file is so convoluted with dummy variables, incrementing & decrementing references, and other stuff, that I want to try to write a C-function myself. My goal is not to avoid PyObjects* and the corresponding reference handling - apart from the head and end of the function. (I could use ctypes instead, but that again would obfuscate the API of my package a bit.) Christian From jarausch at skynet.be Wed Jan 30 11:21:56 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 30 Jan 2008 17:21:56 +0100 Subject: Trouble loading dll via ctypes In-Reply-To: <68615d61-3e71-4a39-8783-52ff0db97b48@i12g2000prf.googlegroups.com> References: <68615d61-3e71-4a39-8783-52ff0db97b48@i12g2000prf.googlegroups.com> Message-ID: <47a0a425$0$2941$ba620e4c@news.skynet.be> subopt inTheVicinityOf geemail.com wrote: > I'm trying to load a dll via ctypes by doing this: > > cdll.LoadLibrary('/path/to/mylib.so') > > But i'm getting this: > > /path/to/mylib.so: cannot open shared object file: No such file or > directory What am i doing wrong? > > The dll in question is in a directory mounted via NSF, but no part of > the path/filename is a symlink. When i try code from the docs: > > cdll.LoadLibrary('libc.so.6') > > ,then all is fine. > > I've also tried to set my LD_LIBRARY_PATH before starting Python, > checking it via os.environ, then doing the cdll.LoadLibrary(...), but > that fails with the same complaint. What am i doing wrong? > I vaguely remember you need execute permissions for a dynamic library to load. Permissions on an NFS mounted directory are different, especial for user 'root'. Check if can execute some executable in that NFS path. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From kyosohma at gmail.com Tue Jan 22 15:48:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 22 Jan 2008 12:48:03 -0800 (PST) Subject: Processing XML that's embedded in HTML References: Message-ID: <6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> On Jan 22, 11:32 am, Paul Boddie wrote: > > The rest of the document is html, javascript div tags, etc. I need the > > information only from the row where the Relationship tag = Owner and > > the Priority tag = 1. The rest I can ignore. When I tried parsing it > > with minidom, I get an ExpatError: mismatched tag: line 1, column 357 > > so I think the HTML is probably malformed. > > Or that it isn't well-formed XML, at least. I probably should have posted that I got the error on the first line of the file, which is why I think it's the HTML. But I wouldn't be surprised if it was the XML that's behaving badly. > > > I looked at BeautifulSoup, but it seems to separate its HTML > > processing from its XML processing. Can someone give me some pointers? > > With libxml2dom [1] I'd do something like this: > > import libxml2dom > d = libxml2dom.parse(filename, html=1) > # or: d = parseURI(uri, html=1) > rows = d.xpath("//XML/BoundData/Row") > # or: rows = d.xpath("//XML[@id="grdRegistrationInquiryCustomers"]/ > BoundData/Row") > > Even though the document is interpreted as HTML, you should get a DOM > containing the elements as libxml2 interprets them. > > > I am currently using Python 2.5 on Windows XP. I will be using > > Internet Explorer 6 since the document will not display correctly in > > Firefox. > > That shouldn't be much of a surprise, it must be said: it isn't XHTML, > where you might be able to extend the document via XML, so the whole > document has to be "proper" HTML. > > Paul > > [1]http://www.python.org/pypi/libxml2dom I must have tried this module quite a while ago since I already have it installed. I see you're the author of the module, so you can probably tell me what's what. When I do the above, I get an empty list either way. See my code below: import libxml2dom d = libxml2dom.parse(filename, html=1) rows = d.xpath('//XML[@id="grdRegistrationInquiryCustomers"]/BoundData/ Row') # rows = d.xpath("//XML/BoundData/Row") print rows I'm not sure what is wrong here...but I got lxml to create a tree from by doing the following: from lxml import etree from StringIO import StringIO parser = etree.HTMLParser() tree = etree.parse(filename, parser) xml_string = etree.tostring(tree) context = etree.iterparse(StringIO(xml_string)) However, when I iterate over the contents of "context", I can't figure out how to nab the row's contents: for action, elem in context: if action == 'end' and elem.tag == 'relationship': # do something...but what!? # this if statement probably isn't even right Thanks for the quick response, though! Any other ideas? Mike From mail at timgolden.me.uk Thu Jan 17 06:18:26 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 17 Jan 2008 11:18:26 +0000 Subject: Opening/Running files through python In-Reply-To: <239efd0e-5ac8-485c-b316-aa52b0a2c316@i72g2000hsd.googlegroups.com> References: <239efd0e-5ac8-485c-b316-aa52b0a2c316@i72g2000hsd.googlegroups.com> Message-ID: <478F3982.7040602@timgolden.me.uk> Ionis wrote: > Hey guys, hope you can help me here. > > I am running in windows and I am trying to open a file via python. I > want the file (a text file) to open up in the users default text > editor. I'm not wanting to read a file, I just want to open it. Is > there a way? import os os.startfile ("blah.txt") From jzgoda at o2.usun.pl Sun Jan 27 18:08:32 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 28 Jan 2008 00:08:32 +0100 Subject: optional static typing for Python In-Reply-To: References: Message-ID: Russ P. pisze: >>> I noticed that Guido has expressed further interest in static typing >>> three or four years ago on his blog. Does anyone know the current >>> status of this project? Thanks. >> I thought it was april fools joke? > > On January 21, 2000? Which calendar do you use? Static typing in Python is usual theme of april fools jokes. -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From mwm-keyword-python.b4bdba at mired.org Fri Jan 11 18:29:56 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 18:29:56 -0500 Subject: Newbie Q: modifying SQL statements In-Reply-To: <20080111231141.GA24213@neptune.faber.nom> References: <20080111013206.GA18259@neptune.faber.nom> <20080110225352.2c112555@bhuda.mired.org> <20080111231141.GA24213@neptune.faber.nom> Message-ID: <20080111182956.64466688@bhuda.mired.org> On Fri, 11 Jan 2008 18:11:41 -0500 "Faber J. Fedor" wrote: > On 10/01/08 22:53 -0500, Mike Meyer wrote: > > Personally, I think it would be more pythonic to not try and use two > > different APIs to walk the list of jobs (... One Way To Do it): > > > > def __call__(self, where=None): > > q = "select * from %s" % (self.name,) + ("" if not where else (" where %s" % where)) > > Does this '("" if not where...' syntax actually work? I couldn't get it to > compile and I couldn't find any examples of such syntax (but you can't > expect googling for 'if not' to be too successful). Yes. >>> def test(name, where): ... return "select * from %s" % (name,) + ("" if not where else (" where %s" % where)) ... >>> test('mine', 'x = 3') 'select * from mine where x = 3' >>> test('mine', None) 'select * from mine' >>> test('yours', 'barfle is not NULL') 'select * from yours where barfle is not NULL' It is a 2.5 feature, though. I converted all my clients to 2.5.1, shortly after it was available, and haven't used anything older since. Sorry 'bout that. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From steve at REMOVE-THIS-cybersource.com.au Mon Jan 14 16:27:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 14 Jan 2008 21:27:21 -0000 Subject: encrypting python modules References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <13og1dbe4qcfs2b@corp.supernews.com> <478b220e$0$85788$e4fe514c@news.xs4all.nl> <13omgn69naf1se8@corp.supernews.com> <5v13toF1kbqonU1@mid.dfncis.de> Message-ID: <13onktp123l2c0e@corp.supernews.com> On Mon, 14 Jan 2008 12:46:48 +0000, Robert Latest wrote: > And, contrary to the advice I gave elsethread, unfortunately it's > impossible to just drop uncooperative customers when you develop GPL > software ;-) Just because you are writing GPLed code doesn't mean you are permanently linked to anyone you have supplied code to. You can send their emails straight to /dev/null. You don't have to give them any support, only the source code. And if you do give them support, the GPL doesn't limit what your hourly rates are: you are free to charge them one million dollars per hour, payable in advance in blocks of fifteen hours. If they don't like it, they can always fork the code, or find another person to support it, or simply stop being dicks. -- Steven From bbtestingbb at gmail.com Thu Jan 24 00:49:15 2008 From: bbtestingbb at gmail.com (bbtestingbb at gmail.com) Date: Wed, 23 Jan 2008 21:49:15 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> Message-ID: <54c22550-a2fc-4eac-b80d-20936b209b99@y5g2000hsf.googlegroups.com> On Jan 23, 8:49 pm, glacier wrote: > I use chinese charactors as an example here. > > >>>s1='???' > >>>repr(s1) > > "'\\xc4\\xe3\\xba\\xc3\\xc2\\xf0'" > > >>>b1=s1.decode('GBK') > > My first question is : what strategy does 'decode' use to tell the way > to seperate the words. decode() uses the GBK strategy you specified to determine what constitutes a character in your string. > My second question is: is there any one who has tested very long mbcs > decode? I tried to decode a long(20+MB) xml yesterday, which turns out > to be very strange and cause SAX fail to parse the decoded string. > However, I use another text editor to convert the file to utf-8 and > SAX will parse the content successfully. > > I'm not sure if some special byte array or too long text caused this > problem. Or maybe thats a BUG of python 2.5? That's probably to vague of a description to determine why SAX isn't doing what you expect it to. From aarfaee at cs.ucsd.edu Sat Jan 19 23:35:33 2008 From: aarfaee at cs.ucsd.edu (Arash Arfaee) Date: Sat, 19 Jan 2008 20:35:33 -0800 Subject: psyco problem on mac wingide Message-ID: <266557d0801192035i2fcb8a8dk268209f1d63ffbc7@mail.gmail.com> Hello All, I have no problem using psyco on python shell on my new Mac, however I cannot import it from WingIDE. I copied psyco directory into mac python folder. Does wingide installs another python shell? Thanks, Arash From rw at smsnet.pl Thu Jan 10 15:42:44 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 10 Jan 2008 21:42:44 +0100 Subject: urllib2 rate limiting References: <87ejcpo7r8.fsf@merkury.smsnet.pl> Message-ID: <87abndo1iz.fsf@merkury.smsnet.pl> Dimitrios Apostolou writes: > On Thu, 10 Jan 2008, Rob Wolfe wrote: > >> Dimitrios Apostolou writes: >> >>> P.S. And something simpler: How can I disallow urllib2 to follow >>> redirections to foreign hosts? >> >> You need to subclass `urllib2.HTTPRedirectHandler`, override >> `http_error_301` and `http_error_302` methods and throw >> `urllib2.HTTPError` exception. > > Thanks! I think for my case it's better to override redirect_request > method, and return a Request only in case the redirection goes to the > same site. Just another question, because I can't find in the docs the > meaning of (req, fp, code, msg, hdrs) parameters. To read the URL I > get redirected to (the 'Location:' HTTP header?), should I check the > hdrs parameter or there is a better way? Well, according to the documentation there is no better way. But I looked into the source code of `urllib2` and it seems that `redirect_request` method takes one more parameter `newurl`, what is probably what you're looking for. ;) Regards, Rob From tjreedy at udel.edu Tue Jan 22 22:40:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jan 2008 22:40:43 -0500 Subject: possible to overide setattr in local scope? References: <9dac9675-992e-4dc5-b085-06f0811939ca@1g2000hsl.googlegroups.com> Message-ID: "glomde" wrote in message news:9dac9675-992e-4dc5-b085-06f0811939ca at 1g2000hsl.googlegroups.com... | In a class it is poosible to override setattr, so that you can decide | how you should | handle setting of variables. | | Is this possible to do outside of an class on module level. | | mysetattr(obj, var, value): | print "Hello" | | So that | | test = 5 | | | would print | Hello An assignment at module level amounts to setting an attribute of an instance of the builtin (C coded) module type, which you cannot change. Even if you can subclass that type (I don't know), there is no way to get the (stock) interpreter to use instances of your module subclass instead. From george.sakkis at gmail.com Mon Jan 21 23:54:28 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 21 Jan 2008 20:54:28 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> Message-ID: On Jan 21, 10:20 pm, Alan Isaac wrote: > I want to generate sequential pairs from a list. > Here is a way:: > > from itertools import izip, islice > for x12 in izip(islice(x,0,None,2),islice(x,1,None,2)): > print x12 > > (Of course the print statement is just illustrative.) > What is the fastest way? (Ignore the import time.) Look up the timeit module and test yourself the various alternatives; that's the most reliable way to tell for sure. George From jarausch at igpm.rwth-aachen.de Wed Jan 23 06:21:23 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 23 Jan 2008 12:21:23 +0100 Subject: Removing objects In-Reply-To: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> Message-ID: <5vom9lF1mlfisU1@mid.dfncis.de> bladedpenguin at gmail.com wrote: > I am writing a game, and it must keep a list of objects. I've been > representing this as a list, but I need an object to be able to remove > itself. It doesn't know it's own index. If I tried to make each object > keep track of it's own index, it would be invalidated when any object > with a lower index was deleted. The error was that when I called > list.remove(self), it just removed the first thing in hte list with > the same type as what I wanted, rather than the object I wanted. The > objects have no identifying charachteristics, other than thier > location in memory > > So my question: How do I look something up in a list by it's location > in memory? does python even support pointers? > > Is there a better way? You could use a doubly linked list. The class 'deque' from collections is such a list but I don't known how to delete a specific element without this ugly (expensive?) rotate method. Here is my solution in pure Python #!/usr/bin/python import re class Queue(object): __slots__= 'Head', 'Tail', '__iter__','NNd' def __init__(self): self.Head= None self.Tail= None self.NNd= None def append(self,N): if self.Head == None: self.Head= N self.Tail= self N._enqueue_after(self.Tail) self.Tail= N def dequeue(self,N): Father, Son= N._dequeue() if self.Tail == N: self.Tail= Father if self.Head == N: self.Head= Son if self.Head == None: self.Tail= None def enqueue_after(self,N,Father): N._enqueue_after(Father) if self.Tail == Father: self.Tail= N def enqueue_before(self,N,Son): N._enqueue_before(Son) if self.Head == Son: self.Head= N def __iter__(self): next= self.Head # allows to dequeue the current element in a loop while True: current= next if current == None: raise StopIteration next= current._next() yield current class Node(object): # partially application specific __slots__= 'next', 'NNd','PNd','key','data' def __init__(self,Key,Data,P=None,N=None): # P = Previous N = Next if P != None: P.NNd= self if N != None: N.PNd= self self.PNd= P self.NNd= N self.key= Key self.data= Data def _enqueue_after(self,Father): self.NNd= Father.NNd self.PNd= Father Father.NNd= self def _enqueue_before(self,Son): self.NNd= Son self.PNd= Son.PNd Son.PNd= self def _dequeue(self): if self.PNd != None: self.PNd.NNd= self.NNd if self.NNd != None: self.NNd.PNd= self.PNd Father= self.PNd Son= self.NNd self.PNd= self.NNd= None return Father,Son def _next(self): return self.NNd def __str__(self): # highly application specific return '(%s:%s)' % (self.key,self.data) # some tests MyQ= Queue() MyQ.append( Node('HJ','3949') ) print MyQ.Head,MyQ.Tail,MyQ.Head.key MyQ.append( Node('CJ','10149') ) print MyQ.Head,MyQ.Tail,MyQ.Head.key N= MyQ.Head print "queue: ",N.key,"->" N= N.NNd print "next: ",N.key,"->" N= N.NNd if N != None: print "next: ",N.key,"->" else: print "no next:" for N in MyQ: print "loop->",N print N.key,N.data MyQ.dequeue(MyQ.Tail) print "--- after dequeue" print "Head: ",MyQ.Head," Tail: ",MyQ.Tail for N in MyQ: print "loop2->",N print N.key,N.data MyQ.dequeue(MyQ.Tail) print "after second dequeue" print "Head: ",MyQ.Head," Tail: ",MyQ.Tail for N in MyQ: print "loop3->",N print N.key,N.data ENJOY, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From jimgardener at gmail.com Wed Jan 9 00:35:35 2008 From: jimgardener at gmail.com (jimgardener) Date: Tue, 8 Jan 2008 21:35:35 -0800 (PST) Subject: copy a numpy array References: <0cc33c4e-bb6b-4f80-8b4d-d702dc7789ec@v29g2000hsf.googlegroups.com> Message-ID: <2af4702f-a29e-4d7b-85e8-78cd7dc9f36a@f3g2000hsg.googlegroups.com> thanx guys for the replies need a little clarification srcarray=array([1.2,2.3,3.4,4.5,5.6]) destarray=array(srcarray,copy=False) then srcarray[2]=99.9 will cause the change to be reflected in both src and dest. doesn't that mean data is shared between both arrays? but if i do destarray=array(srcarray) or destarray=srcarray.copy() then the change in one array will not affect the other,meaning no data sharing ...want to know if my understanding is right jim From http Thu Jan 31 10:59:03 2008 From: http (Paul Rubin) Date: 31 Jan 2008 07:59:03 -0800 Subject: Sine Wave Curve Fit Question References: <7eOdnXVrB-fQFD3anZ2dnUVZ8hednZ2d@giganews.com> <47a0c8b5$0$2994$ba620e4c@news.skynet.be> <47A1EE83.6050105@skynet.be> Message-ID: <7x8x26t29k.fsf@ruckus.brouhaha.com> Helmut Jarausch writes: > You're right: standard Python's math library missing the function arctan2. It's math.atan2 . From Luke.Visinoni at gmail.com Tue Jan 15 19:03:06 2008 From: Luke.Visinoni at gmail.com (Luke) Date: Tue, 15 Jan 2008 16:03:06 -0800 (PST) Subject: Data mapper - need to map an dictionary of values to a model References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com> <2d59f289-2def-43a8-93b7-f326b8f12066@z17g2000hsg.googlegroups.com> Message-ID: <88c59b87-a1e6-4e19-ba0f-402ecf0d7f7b@s19g2000prg.googlegroups.com> On Jan 15, 3:53 pm, George Sakkis wrote: > On Jan 14, 7:56 pm, Luke wrote: > > > > > I am writing an order management console. I need to create an import > > system that is easy to extend. For now, I want to accept an dictionary > > of values and map them to my data model. The thing is, I need to do > > things to certain columns: > > > - I need to filter some of the values (data comes in as YYYY-MM- > > DDTHH:MM:SS-(TIMEZONE-OFFSET) and it needs to map to Order.date as a > > YYYY-MM-DD field) > > - I need to map parts of an input column to more than one model param > > (for instance if I get a full name for input--like "John Smith"--I > > need a function to break it apart and map it to > > Order.shipping_first_name and Order.shipping_last_name) > > - Sometimes I need to do it the other way too... I need to map > > multiple input columns to one model param (If I get a shipping fee, a > > shipping tax, and a shipping discount, I need them added together and > > mapped to Order.shipping_fee) > > > I have begun this process, but I'm finding it difficult to come up > > with a good system that is extensible and easy to understand. I won't > > always be the one writing the importers, so I'd like it to be pretty > > straight-forward. Any ideas? > > > Oh, I should also mention that many times the data will map to several > > different models. For instance, the importer I'm writing first would > > map to 3 different models (Order, OrderItem, and OrderCharge) > > > I am not looking for anybody to write any code for me. I'm simply > > asking for inspiration. What design patterns would you use here? Why? > > The specific transformations you describe are simple to be coded > directly but unless you constrain the set of possible transformations > that can take place, I don't see how can this be generalized in any > useful way. It just seems too open-ended. > > The only pattern I can see here is breaking down the overall > transformation to independent steps, just like the three you > described. Given some way to specify each separate transformation, > their combination can be factored out. To illustrate, here's a trivial > example (with dicts for both input and output): > > class MultiTransformer(object): > def __init__(self, *tranformers): > self._tranformers = tranformers > > def __call__(self, input): > output = {} > for t in self._tranformers: > output.update(t(input)) > return output > > date_tranformer = lambda input: {'date' : input['date'][:10]} > name_tranformer = lambda input: dict( > zip(('first_name', 'last_name'), > input['name'])) > fee_tranformer = lambda input: {'fee' : sum([input['fee'], > input['tax'], > input['discount']])} > tranformer = MultiTransformer(date_tranformer, > name_tranformer, > fee_tranformer) > print tranformer(dict(date='2007-12-22 03:18:99-EST', > name='John Smith', > fee=30450.99, > tax=459.15, > discount=985)) > # output > #{'date': '2007-12-22', 'fee': 31895.140000000003, > 'first_name': #'J', 'last_name': 'o'} > > You can see that the MultiTransformer doesn't buy you much by itself; > it just allows dividing the overall task to smaller bits that can be > documented, tested and reused separately. For anything more > sophisticated, you have to constrain what are the possible > transformations that can happen. I did something similar for > transforming CSV input rows (http://pypi.python.org/pypi/csvutils/) so > that it's easy to specify 1-to-{0,1} transformations but not 1-to-many > or many-to-1. > > HTH, > George thank you that is very helpful. I will ponder that for a while :) From dieter at handshake.de Thu Jan 24 13:30:43 2008 From: dieter at handshake.de (Dieter Maurer) Date: 24 Jan 2008 19:30:43 +0100 Subject: pythonic backtrace with gdb In-Reply-To: References: Message-ID: Hynek Hanke writes on Wed, 23 Jan 2008 14:30:22 +0100: > ... > I've also tried to use the backtrace script here > http://mashebali.com/?Python_GDB_macros:The_Macros:Backtrace > But I get a different error: > (gdb) pbt > Invalid type combination in ordering comparison. > > I'm using GDB version 6.6.90. I expect that your GDB version is too new and has introduced some safety checks (which now break). It will probably help when you add explicite type casts to "long" around the comparisons in the definition of "pbt". Dieter From jerryji1976 at gmail.com Mon Jan 14 16:20:12 2008 From: jerryji1976 at gmail.com (jerryji) Date: Mon, 14 Jan 2008 13:20:12 -0800 (PST) Subject: hide object property from dir() function? Message-ID: Hi, Sorry for this newbie question, I was puzzled why the existing property of an object is not shown in the dir() function output. "v" is an lxml Element object variable -- In [44]: v Out[44]: In [45]: dir(v) Out[45]: ['__copy__', '__deepcopy__', '__reduce__', 'append', 'clear', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'keys', 'makeelement', 'remove', 'set'] dir() output doesn't contain the ".tag", which does exist -- In [46]: v.tag Out[46]: 'documentProperties' what is the rule governing the display of a property from dir()? Many thanks in advance! Jerry From mobiledreamers at gmail.com Tue Jan 8 22:32:33 2008 From: mobiledreamers at gmail.com (Mark) Date: Tue, 08 Jan 2008 19:32:33 -0800 Subject: Pyflakes pre-commit hook in subversion Message-ID: <47844051.7090401@gmail.com> An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Mon Jan 14 16:38:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 14 Jan 2008 21:38:17 -0000 Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> <7xsl105fvv.fsf@ruckus.brouhaha.com> Message-ID: <13onli9dk7mu926@corp.supernews.com> On Mon, 14 Jan 2008 12:08:52 -0800, Paul Rubin wrote: > aspineux writes: >> Yes, I missed 'get' and 'setdefault' are functions :-) Then why not >> some new semantic >> >> d.get('a', f()) --> d['a', f()] >> d.setdefault('a', f()) --> d['a'=f()] >> >> Is is a good idea enough to change the python semantic ? Or simply is >> it a good idea ? > > Changing python semantics for something like this is nuts. Allowing > passing a callable (sort of like re.sub allows) makes a certain amount > of sense: > > d.get('a', default=f) But how can Python determine when you want the result to be *the callable* and when you want it to be *the result of calling the callable*? Functions and other callables are first-class objects, and it is quite reasonable to have something like this: map = {'a': Aclass, 'b': Bclass, 'c': Cclass} class_ = map.get(astring, default=Zclass) The result I want is the class, not the result of calling the class (which would be an instance). If I wanted the other semantics, I'd be using defaultdict instead. -- Steven From bignose+hates-spam at benfinney.id.au Mon Jan 14 19:28:47 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 11:28:47 +1100 Subject: module naming conventions References: <7f39199a-3334-4bcc-a424-5102f042ed01@1g2000hsl.googlegroups.com> <87zlv8dnya.fsf@benfinney.id.au> <6a53a14a-8f7c-4b6b-986f-48c7698f679f@v29g2000hsf.googlegroups.com> Message-ID: <8763xwdj9c.fsf@benfinney.id.au> grackle writes: > I do use packages. I mentioned the Java naming conventions because > they were my first thought for solving the problem of name clashes, > and they work well in some non-Java languages. They don't apply well > to Python, since every top-level module has a unique identity that > can only be specified on one source path. If two libraries use the > same top-level module name, they can't be used together in the same > program without modifying their source code. What do you mean by "top-level module", and "the same top-level name"? Do you mean "the same fully-qualified name"? If two modules are in separate places in the hierarchy, they will have different fully-qualified names. ===== $ find foo/ -name '*.py' foo/__init__.py foo/spam.py foo/bar/__init__.py foo/bar/spam.py foo/baz/__init__.py foo/baz/spam.py ===== ===== eggs.py ===== import foo.spam import foo.bar.spam import foo.baz.spam # ... ===== > mycompany_mymodulename was just the first solution I thought of that > seemed practical. The mycompany_ prefix protects me from name clashes > with useful modules I might acquire from elsewhere. Ah, I see; you're referring to a worldwide package namespace, enforced by the language. AFAIK there's no such thing in Python. > Of course, the best convention is probably the predominant one, and > that's my question: What is the standard way of naming Python > packages? Release your package as free software on the Cheeseshop . If the name you want is already taken, pick one that will help users distinguish yours from the existing one. -- \ "If you do not trust the source do not use this program." | `\ ?Microsoft Vista security dialogue | _o__) | Ben Finney From Programus at gmail.com Wed Jan 23 22:01:05 2008 From: Programus at gmail.com (programus) Date: Wed, 23 Jan 2008 19:01:05 -0800 (PST) Subject: Removing objects References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> Message-ID: <92564557-f044-4117-8dc4-f88b79ff4d4a@s19g2000prg.googlegroups.com> On Jan 23, 2:59 pm, bladedpeng... at gmail.com wrote: > I am writing a game, and it must keep a list of objects. I've been > representing this as a list, but I need an object to be able to remove > itself. It doesn't know it's own index. If I tried to make each object > keep track of it's own index, it would be invalidated when any object > with a lower index was deleted. The error was that when I called > list.remove(self), it just removed the first thing in hte list with > the same type as what I wanted, rather than the object I wanted. The > objects have no identifying charachteristics, other than thier > location in memory > > So my question: How do I look something up in a list by it's location > in memory? does python even support pointers? > > Is there a better way? How about using pygame.sprite? ( http://www.pygame.org/docs/ref/sprite.html ) The class pygame.sprite.Sprite has a kill() function, which can remove itself from all groups that contains it. (A group is just like a list. Just see pygame.sprite.Group) And here is a short tutorial about this. http://www.pygame.org/docs/tut/SpriteIntro.html From bronger at physik.rwth-aachen.de Sat Jan 12 07:26:42 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 12 Jan 2008 13:26:42 +0100 Subject: Is unicode.lower() locale-independent? References: Message-ID: <871w8ni60t.fsf@physik.rwth-aachen.de> Hall?chen! Fredrik Lundh writes: > Robert Kern wrote: > >>> However it appears from your bug ticket that you have a much >>> narrower problem (case-shifting a small known list of English >>> words like VOID) and can work around it by writing your own >>> locale-independent casing functions. Do you still need to find >>> out whether Python unicode casings are locale-dependent? >> >> I would still like to know. There are other places where .lower() >> is used in numpy, not to mention the rest of my code. > > "lower" uses the informative case mappings provided by the Unicode > character database; see > > http://www.unicode.org/Public/4.1.0/ucd/UCD.html > > afaik, changing the locale has no influence whatsoever on Python's > Unicode subsystem. Slightly off-topic because it's not part of the Unicode subsystem, but I was once irritated that the none-breaking space (codepoint xa0 I think) was included into string.whitespace. I cannot reproduce it on my current system anymore, but I was pretty sure it occured with a fr_FR.UTF-8 locale. Is this possible? And who is to blame, or must my program cope with such things? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From gagsl-py2 at yahoo.com.ar Wed Jan 30 09:27:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jan 2008 06:27:29 -0800 (PST) Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> <0a285e6e-a3a9-4be9-ae59-4cb7547ffa3a@q21g2000hsa.googlegroups.com> <13q10njnbffkceb@corp.supernews.com> Message-ID: <0c1095b9-3e36-4151-93b8-24f8cd9fbee3@v17g2000hsa.googlegroups.com> On 30 ene, 12:00, Steven D'Aprano wrote: > I call that a bug in the inspect module. In fact, looking at the source > for the findsource() function, I can see no fewer than two bugs, just in > the way it handles classes: > > (1) it assumes that the only way to create a class is with a class > statement, which is wrong; and > > (2) it assumes that the first occurrence of "class " must be the > correct definition, which is also wrong. Yes, it's broken. But I'm afraid that's the only available thing to do. Python stores filename and line number information in code objects (only). If you have a reference to any code object (a method, a function, a traceback...) inspect can use it to retrieve that information. Once a class is defined, there is no code object attached to it. (The class statement is executed when the module is loaded and initialized, but that code object is discarded afterwards because it's not required anymore). If you *know* that a certain method is defined in a class, you can use it to find the real module. But in general, there is nothing to start with. I'm eagerly waiting for someone to come and say I'm wrong... -- Gabriel Genellina From larudwer at freenet.de Mon Jan 7 15:51:53 2008 From: larudwer at freenet.de (Ruediger) Date: Mon, 07 Jan 2008 21:51:53 +0100 Subject: Killing worker threads References: <8a6b8e350801060548m6f39594che1207cc5bc4b6487@mail.gmail.com> Message-ID: maybe following recipe from activestate may be usefull. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 http://sebulba.wikispaces.com/recipe+thread2 From boblatest at yahoo.com Mon Jan 14 07:46:48 2008 From: boblatest at yahoo.com (Robert Latest) Date: 14 Jan 2008 12:46:48 GMT Subject: encrypting python modules References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <13og1dbe4qcfs2b@corp.supernews.com> <478b220e$0$85788$e4fe514c@news.xs4all.nl> <13omgn69naf1se8@corp.supernews.com> Message-ID: <5v13toF1kbqonU1@mid.dfncis.de> Steven D'Aprano wrote: > No, it's a serious question. You distribute Python code, and you're > worried that your users will modify the source code and then neglect to > mention it when they report bugs which they introduced. > > Before you build an elephant-proof fence around your house, it is quite > reasonable to ask whether or not there are actually elephants in your > neighbourhood. Depending on where you are, there are probably plenty. Recently I started hacking around in a GPLed Python app (GRAMPS, if anybody cares). This program has a built-in bug report feature which makes it easy to email bugs with associated stack trace etc. to the developers. Unfortunately the bug report window also automatically popped up even when stuff went wrong within my own broken code. For such a case it would be good if a software could somehow detect modifications of itself and its associated modules. And, contrary to the advice I gave elsethread, unfortunately it's impossible to just drop uncooperative customers when you develop GPL software ;-) robert From kyosohma at gmail.com Sat Jan 5 10:07:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 5 Jan 2008 09:07:13 -0600 Subject: Tabnanny errors when Migrating Python 2.4 code to 2.5 Message-ID: >> I'm using Windows XP, using IDLE (which was mentioned already) > in the context of editing/displaying code, not executing it. Does the > problem occur before or after you edit a file with IDLE? Actually, neither. I'm not editing the code. I open it in IDLE in 2.5 and attempt to run it through the Run menu "Run Module" menu item or by pressing F5. It immediately fails with a tabnanny error. If I run it from 2.4's IDLE, it works. >> and I >> downloaded the 2.5.1 exe/msi file from python.org to install it. > What you downloaded doesn't answer the question about how you > installed it. Do you still have your 2.4 installation? Yes, I use both 2.4 and 2.5 as I migrate from one to the other. I've attached a file that causes it consistently. On two systems with both 2.4 and 2.5 installed, it fails on line 206 when run from the IDLE included with 2.5. >> I have yet to find a simple one which exhibits the issue to post. It >> seems to happen to my complex files, not the simple ones. > So chop up a complex file ... > Have you inspected the failing files using a text editor that can > display tabs and spaces (e.g. PythonWin, TextPad)? I just used Notepad++ to inspect the file and it does indeed have tabs at line 206 rather than spaces. I take it that Python 2.5 is more sensitive to that than is 2.4? I program almost exclusively in IDLE as I'd read that this can happen in some text editors, but it seemed implied that it didn't if you used IDLE. At least, that's what I got from various Python books and the website: http://www.python.org/idle/doc/idlemain.html Anyway, thanks for the help. Mike -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: scrubber.py URL: From hexamorph at gmx.net Thu Jan 24 12:53:22 2008 From: hexamorph at gmx.net (Hexamorph) Date: Thu, 24 Jan 2008 18:53:22 +0100 Subject: piping into a python script In-Reply-To: References: Message-ID: <4798D092.9000308@gmx.net> Donn Ingle wrote: > Paddy wrote: >> fileinput is set to process each file a line at a time unfortunately. > Wow. So there seems to be no solution to my OP. I'm amazed, I would have > thought a simple list of strings, one from stdin and one from the args, > would be easy to get. > > I *really* don't want to open each file, that would be insane. > > Perhaps I shall have to forgo the stdin stuff then, after all. > Hi! I'm not sure if I completely get what you want, but what's about this: #!/usr/bin/python import sys filelist = [] with_stdin=0 if len(sys.argv) > 1: for file in sys.argv[1:]: if file == "-": with_stdin=1 continue filelist.append(file) else: with_stdin=1 if with_stdin: for file in sys.stdin: filelist.append(file) for file in filelist: print "Processing file: %s" % file It's a bit clumsy, but seems to do what I guess you want. HTH From steve at REMOVE-THIS-cybersource.com.au Wed Jan 23 17:00:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 22:00:16 -0000 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> <24SdnaCXzLZC7AranZ2dnUVZ_v2pnZ2d@rcn.net> Message-ID: <13pfe7g5j8ek665@corp.supernews.com> On Wed, 23 Jan 2008 11:57:05 -0500, Alan G Isaac wrote: > Steven D'Aprano wrote: >> In fact, "fastest" isn't even a meaningful attribute. Does it mean: >> >> * the worst-case is fastest >> * the best-case is fastest >> * the average-case is fastest >> * fastest on typical data >> * all of the above > > > I confess that it did not occur to me that there might be an interesting > distinction among these cases for the question of how to get sequential > pairs from a list. How would one draw these distinctions in this case? Well, in this *specific* case I don't think they're terribly interesting because your problem is so simple. Best-case will, presumably, occur when the list is empty. Worst-case will occur if somebody passes a non- terminating iterator to your code (although that depends on the nature of your solution and how you are using it). But in the broader context of optimizing, these distinctions are very important. For example, Quicksort is very fast on randomly ordered data, but terribly slow on data which is already sorted: about as slow as Bubblesort. Mergesort's best-case isn't as fast as Quicksort's best-case, but it's worst-case behaviour is much, much better. And both Quicksort and Mergesort are complex enough that a simpler, slower algorithm like Shell Sort will be significantly faster for small data sets. But I'm sure you already know all this, I'm just mentioning it for the benefit of anybody else reading who still thinks that a generic "what's the fastest way" type question is meaningful. -- Steven From paddy3118 at googlemail.com Thu Jan 24 10:46:24 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 07:46:24 -0800 (PST) Subject: piping into a python script References: <5vrovvF1njt09U6@mid.uni-berlin.de> Message-ID: <77bf0ea2-5e7d-4cd0-8692-319b85a97d65@v17g2000hsa.googlegroups.com> On Jan 24, 3:25 pm, Marc 'BlackJack' Rintsch wrote: > On Thu, 24 Jan 2008 17:17:25 +0200, Donn Ingle wrote: > > Given these two examples: > > 1. > > ./fui.py *.py > > 2. > > ls *.py | ./fui.py > > > How can I capture a list of the arguments? > > I need to get all the strings (file or dir names) passed via the normal > > command line and any that may come from a pipe. > > > There is a third case: > > 3. > > ls *.jpg | ./fui.py *.png > > Where I would be gathering strings from two places. > > > I am trying to write a command-line friendly tool that can be used in > > traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. > > > I have tried: > > 1. pipedIn = sys.stdin.readlines() > > Works fine for example 2, but example 1 goes into a 'wait for input' mode > > and that's no good. Is there a way to tell when no input is coming from a > > pipe at all? > > Usually Linux tools that can get the data from command line or files treat > a single - as file name special with the meaning of: read from stdin. > > So the interface if `fui.py` would be: > > 1. ./fui.py *.a > 2. ls *.a | ./fui.py - > 3. ls *.a | ./fui.py *.b - > > Ciao, > Marc 'BlackJack' Rintsch If X.a X.b Y.a Y.b are all files whose contents are to be processed then To process all files: ./fui.py *.a *.b Or: ./fui.py `ls *.a *.b` To process one file from a pipe unix usually does: cat X.a | ./fui.py - To get the filenames from stdin would usually need a command line switch telling fui.py to read a file *list* from stdin. For verilog simulators for example you have the -f switch that says insert further command line arguments from the file name in the next argument, so you could do: ls *.a | ./fui.py -f - *.b For equivalent functionality to my first example. - Paddy. From jura.grozni at gmail.com Mon Jan 21 18:34:52 2008 From: jura.grozni at gmail.com (azrael) Date: Mon, 21 Jan 2008 15:34:52 -0800 (PST) Subject: constructor question References: <758a6b15-9c4d-4c14-82ed-d76be2be0192@21g2000hsj.googlegroups.com> Message-ID: <11dc48f6-74e2-44cf-946c-dfd648264e4b@v46g2000hsv.googlegroups.com> 5 days ago I looked at it and didn't take a notice. thnx, this helped On Jan 22, 12:10?am, TeroV wrote: > azrael wrote: > > lets supose i have a object > > >>>> class a: > >>>> ? __init__(self,b): > >>>> ? ? ? ?self.b=b > > >>>> object=a(2) > > > how can I bind the object with "print". I supose that this should be > > possible with a constructor. but I don't know how. > > >>>> print a > > 2 > > > Something like this > > > Thnx > > Is it that you want to print an object, and customize what is printed? > __str__ method is what you need, seehttp://docs.python.org/ref/customization.html > > -- > Tero From casey at rodarmor.com Thu Jan 17 03:58:38 2008 From: casey at rodarmor.com (Casey Rodarmor) Date: Thu, 17 Jan 2008 00:58:38 -0800 Subject: Stop tab-completing empty lines! Message-ID: Hi everybody, I have the following in my python startup file: import readline, rlcompleter readline.parse_and_bind("tab: complete") This lets me tab complete identifiers in the interpreter beautifully, but there's a tiny problem... If I'm sitting at the beginning of a blank line and just want a tab, it tries to tab complete, which kind of a pain. -=SIMULATED PYTHON PROMPT=- >>> def mega_awesome_function(cool_stuff, **some_sweet_kwargs): ... X (The X is where I press tab and get super annoyed) I could just rebind the key, but i like tab ;-) Any suggestions? Best regards, Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Mon Jan 14 10:15:19 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 14 Jan 2008 16:15:19 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <87myr8v3p4.fsf@mulj.homelinux.net> Wildemar Wildenburger writes: > Jeroen Ruigrok van der Werven wrote: >> To restate it more correctly: __init__ is akin to a constructor. >> > No. See Hrvoje Niksic's reply (and Ben Finney's to which it was a > reply). > > __init__() /initializes/ an instance (automatically after > creation). It is called, /after/ the instance has been constructed I don't understand the purpose of this "correction". After all, __init__ *is* the closest equivalent to what other languages would call a constructor. Take C++ and Java, the two most popular OO languages in existence. Their constructors also "initialize" an instance -- the actual allocation is left to the caller (new or stack in C++) or to the garbage collector. They even share with Python the convention of not returning the constructed value, they operate purely on side effect, just like Python's __init__. And yet, no one says that they are somehow not constructors because of that. Wikipedia calls the constructor "a special method used in object oriented programming which puts the object's members into a valid state." Again, exactly what __init__ does. From rw at smsnet.pl Tue Jan 29 14:27:08 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 29 Jan 2008 20:27:08 +0100 Subject: Telnet Program References: <777d417c-6016-4a44-8d5e-8de6bf604e9a@e6g2000prf.googlegroups.com> Message-ID: <87zluo77qr.fsf@merkury.smsnet.pl> "paul.zorn at gmail.com" writes: > I am having some issues writing a telnet program, using telnetlib. I > am not sure if it is the telnet on the connections end or it is my > program. > > A little background, when I log in straight from the Linux Command > prompt. The only thing I get is a blinking cursor. Then I type in my > command 'FOO' enter then screen on the very next line returns 'OK', > Then automatically puts the blinking cursor on the next line. Then > when I want to quit the telnet session I hit CTRL+Z that takes me to > telnet> then i type quit. > > My Program currently looks like it connects. Because the last string > that I get back that is not blank says: "Logged in successfully". > > So my problem is that when I issue the command through tn.write("FOO > \n"). Then do a tn.read_until('OK\n', 10). It gets returned nothing. I > have also added tn.read_until('OK\n', 10).splitlines(). That is also > returned blank. > > I have tried various different newlines \n \r \r\n. All the > documentation for telnet program that I am logging into says, use > Carriage Return after each command. Nothing seems to get back the > data. I am not sure if the Python telnet is looking for more of true > command line like telnet>. Have you tried: tn.set_debuglevel(1) ? HTH, Rob From Moshe.Ben-Eliezer at audiocodes.com Mon Jan 14 02:57:21 2008 From: Moshe.Ben-Eliezer at audiocodes.com (Moshe Ben-Eliezer) Date: Mon, 14 Jan 2008 09:57:21 +0200 Subject: Return name of caller function? Message-ID: Hello there, Did someone help you with this problem? I would like to know the solution as well. Do you know how to do in on C (CPP) environment ? Thanks anyway. BR. Moshe. ________________________________ This email and any files transmitted with it are confidential material. They are intended solely for the use of the designated individual or entity to whom they are addressed. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, use, distribution or copying of this communication is strictly prohibited and may be unlawful. If you have received this email in error please immediately notify the sender and delete or destroy any copy of this message -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.hankin at gmail.com Sat Jan 5 06:21:37 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 5 Jan 2008 03:21:37 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> Message-ID: <3aee60d1-47fe-4904-b648-0c8d5826850a@d21g2000prf.googlegroups.com> On Jan 4, 7:55?pm, c... at mailinator.com wrote: > ? Hello, > ? This is a question for the best method (in terms of performance > only) to choose a random element from a list among those that satisfy > a certain property. > > ? This is the setting: I need to pick from a list a random element > that satisfies a given property. All or none of the elements may have > the property. Most of the time, many of the elements will satisfy the > property, and the property is a bit expensive to evaluate. Chance of > having the property are uniform among elements. Here's some code that uses a cached random sorting of the list. It assumes you'll want more than one random element. It never calls 'prop' on the same element twice, and it's O(n) even when the elements that pass 'prop' are sparse. I hope this is useful to you! import random class RandomPicker(object): def __init__(self, seq, prop=lambda x:True): seq = list(seq) random.shuffle(seq) # Store with the item whether we've computed prop on it already. self.random_list = [(x, False) for x in seq] self.prop = prop def pick(self): for i, (x, p) in enumerate(self.random_list): if p or self.prop(x): if not p: # Record the fact that self.prop passed. self.random_list[i] = (x, True) # Chop off the items that prop failed on. self.random_list = self.random_list[i:] r = self.random_list # Instead of shuffling the whole list again, just insert # x back in the list randomly. Since the remaining elements # are randomly sorted already, this is ok. n = random.randint(0, len(r) - 1) r[0], r[n] = r[n], r[0] return x # Nothing in the list passes the 'prop' test. return None # Example: pick 100 odd integers from 0 to 1000. a = RandomPicker(xrange(1000), lambda x: x % 2 == 1) print [a.pick() for i in xrange(100)] -- Paul Hankin From rowen at cesmail.net Wed Jan 23 15:45:27 2008 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 23 Jan 2008 12:45:27 -0800 Subject: When is min(a, b) != min(b, a)? References: <13p9hdmh7c08abe@corp.supernews.com> Message-ID: In article , Christian Heimes wrote: > Grant Edwards wrote: > > In many applications (e.g. process control) propogating NaN > > values are way too useful to avoid. Avoiding NaN would make a > > lot of code far more complicated than would using them. > > NaNs are very useful for experienced power users but they are very > confusing for newbies or developers without a numerical background. > > It's very easy to create an inf or nan in Python: > > inf = 1E+5000 > ninf = -inf > nan = inf * 0. > > 1E5000 creates a nan because it is *much* bigger than DBL_MAX (around > 1E+308). In fact it is even larger than LDBL_MAX (around 1E+4932). Isn't it safer to use float("inf"), float("-inf") and float("nan") to create the necessary items? -- Russell From rtw at freenet.co.uk Sun Jan 6 11:07:34 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sun, 06 Jan 2008 10:07:34 -0600 Subject: Cost of "unicode(s)" where s is Unicode References: <4780fb68$0$36341$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote in news:4780fb68$0$36341$742ec2ed at news.sonic.net in comp.lang.python: > Does > > text = unicode(text) > > make a copy of a Unicode string, or is that essentially a > free operation if the input is already Unicode? > > John Nagle > http://docs.python.org/lib/built-in-funcs.html#l2h-78 ... More precisely, if object is a Unicode string or subclass it will return that Unicode string without any additional decoding applied. ... Rob. -- http://www.victim-prime.dsl.pipex.com/ From python.list at tim.thechases.com Wed Jan 23 11:15:15 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 23 Jan 2008 10:15:15 -0600 Subject: Python CGI script and CSS style sheet In-Reply-To: References: Message-ID: <47976813.5090309@tim.thechases.com> > I'm working with a Python CGI script that I am trying to use with an > external CSS (Cascading Style Sheet) and it is not reading it from the > web server. The script runs fine minus the CSS formatting. Does > anyone know if this will work within a Python CGI? It seems that line > 18 is not being read properly. One more thing. I tested this style > sheet with pure html code (no python script) and everything works > great. > > Listed below is a modified example. > > ++++++++++ > > 1 #!/usr/bin/python > 2 > 3 import cgi > 4 > 5 print "Content-type: text/html\n" The answer is "it depends". Mostly on the configuration of your web-server. Assuming you're serving out of a cgi-bin/ directory, you'd be referencing http://example.com/cgi-bin/foo.py If your webserver (apache, lighttpd, whatever) has been configured for this directory to return contents of non-executable items, your above code will reference http://example.com/cgi-bin/central.css and so you may be able to just drop the CSS file in that directory. However, I'm fairly certain that Apache can be (and often is) configured to mark folders like this as "execute only, no file-reading". If so, you'll likely get some sort of Denied message back if you fetch the CSS file via HTTP. A better way might be to reference the CSS file as "/media/central.css" 12 and then put it in a media folder which doesn't have the execute-only/no-read permission set. Another (less attractive) alternative is to have your CGI sniff the incoming request, so you can have both http://example.com/cgi-bin/foo.py http://example.com/cgi-bin/foo.py?file=css using the 'file' GET parameter to return the CSS file instead of your content. I'd consider this ugly unless deploy-anywhere is needed, in which case it's not so bad because the deployment is just the one .py file (and optionally an external CSS file that it reads and dumps). -tkc From dirk.collins at verizon.net Wed Jan 30 22:55:19 2008 From: dirk.collins at verizon.net (Dirk Collins) Date: Thu, 31 Jan 2008 03:55:19 GMT Subject: Why the HELL has nobody answered my question!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! References: Message-ID: "Blubaugh, David A." wrote: > I do not understand why no one has answered the following question: > Has anybody worked with Gene Expression Programming???? Not me, and I'm not expecting too. In addition, I'm not actually trying to figure out if anyone else is working with Gene Expression Programming because: 1) I'm busy at the moment trying to improve my python for other reasons... and... 2) I'm not sure whether Gene Expression Programming is a good idea. Re, Dirk From arnodel at googlemail.com Fri Jan 4 12:37:41 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 4 Jan 2008 09:37:41 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: <7018ca69-d20e-43eb-9c36-bda177ebe7cf@e4g2000hsg.googlegroups.com> On Jan 4, 5:08?pm, Sion Arrowsmith wrote: [...] > But the real killer is that requirement for a std::set is that > T::operator< exists. Which means, for instance, that you can't > have a set of complex numbers.... This is really OT but IIRC, std::set is actually std::set< T, std::less > So make your own less_complex() function (for example, use lexicographic order), std::set should give you a set of complex numbers (sorry if some syntax is incorrect I haven't done any C++ for a while :) -- Arnaud From arnodel at googlemail.com Sun Jan 27 11:14:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 27 Jan 2008 16:14:19 +0000 Subject: Python self-evaluating strings Message-ID: <1BEEBF03-1A38-4745-B08B-DCA3106D1CC5@gmail.com> Hi all, An earlier post today got me thinking about "quines" (programs that output themselves) in Python. I tried to find some on the web but didn't find many ([1]). In particular I didn't find any that corresponded to my instinctive (LISP-induced, probably) criterion: def self_evaluating(s): "Return True if string s evaluates to itself" return s == eval(s) Here is the result of my efforts so far: 1. Starting from the classic idea (lambda x:x%x)('lambda x:x%x') I got the following v=(lambda x:x%('"''""'+x+'"''""'))("""(lambda x:x%%('"''""'+x+'"''""')) (%s)""") 2. (Given that if s is a nonempty string, s*2 is a longer string). Starting from the idea "%s %s" % (("%s %s",)*2) I got the following u="\"%s\" %% ((r\"%s\",)*2)" % ((r"\"%s\" %% ((r\"%s\",)*2)",)*2) Most of my problems in creating these 2 was with finding a suitable way of quoting strings that propagates well. Both u and v are one- liners. I'm hoping for no funky line wrapping here. Note: I'm not quoting the string as it makes no difference since they evaluate to themselves:) I'd like to know if anyone on the list has indulged in this time- bending/mind-wasting activity before. If so, it would be nice to create a list of such expressions. Quining's-better-than-ironing'ly yours -- Arnaud [1] http://www.nyx.net/~gthompso/self_pyth.txt From deets at nospam.web.de Sat Jan 12 08:18:32 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 12 Jan 2008 14:18:32 +0100 Subject: upload file and estimation time In-Reply-To: References: Message-ID: <5urt1aF1ivnefU1@mid.uni-berlin.de> whatazor schrieb: > Hi all, > unseccsefully, I try to analyze this problem. If I can only work on > the client size, how can I create a module that calculate the upload > time of a file, so the time for finish it? i can start with ftp > protocol and after extend this logic for my requirements. All you need to to is to - count the number of bytes to transfer, U - count the bytes already transfered, u - measure the time since the upload, t Then the ETA is eta = (u / t) * (U - u) Using the ftp-lib, you best pass a file-wrapper that overload the read-method to accumulate the read bytes to yield u. Diez From berlin.brown at gmail.com Tue Jan 15 20:33:36 2008 From: berlin.brown at gmail.com (BerlinBrown) Date: Tue, 15 Jan 2008 17:33:36 -0800 (PST) Subject: Is str/unicode.encode supposed to work? with replace/ignore Message-ID: With this code, ignore/replace still generate an error # Encode to simple ascii format. field.full_content = field.full_content.encode('ascii', 'replace') Error: [0/1] 'ascii' codec can't decode byte 0xe2 in position 14317: ordinal not in ran ge(128) The document in question; is a wikipedia document. I believe they use latin-1 unicode or something similar. I thought replace and ignore were supposed to replace and ignore? From karthik3186 at gmail.com Thu Jan 17 03:41:33 2008 From: karthik3186 at gmail.com (Karthik) Date: Thu, 17 Jan 2008 14:11:33 +0530 Subject: Replace stop words (remove words from a string) In-Reply-To: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> Message-ID: <01be01c858e4$c6b8b280$542a1780$@com> How about - for s in stoplist: string.replace(mystr, s, "") Hope this should work. -----Original Message----- From: python-list-bounces+karthik3186=gmail.com at python.org [mailto:python-list-bounces+karthik3186=gmail.com at python.org] On Behalf Of BerlinBrown Sent: Thursday, January 17, 2008 1:55 PM To: python-list at python.org Subject: Replace stop words (remove words from a string) if I have an array of "stop" words, and I want to replace those values with something else; in a string, how would I go about doing this. I have this code that splits the string and then does a difference but I think there is an easier approach: E.g. mystr = kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsldf sd; if I have an array stop_list = [ "[BAD]", "[BAD2]" ] I want to replace the values in that list with a zero length string. I had this before, but I don't want to use this approach; I don't want to use the split. line_list = line.lower().split() res = list(set(keywords_list).difference(set(ENTITY_IGNORE_LIST))) -- http://mail.python.org/mailman/listinfo/python-list From ss.datics at gmail.com Fri Jan 25 17:21:07 2008 From: ss.datics at gmail.com (DATICS2008) Date: Fri, 25 Jan 2008 14:21:07 -0800 (PST) Subject: CFP: DATICS 2008 - Design, Analysis and Tools for Integrated Circuits and Systems Message-ID: <1b41b443-5d1a-466f-b904-b48ff2769adf@v46g2000hsv.googlegroups.com> Apologies for any multiple copies received. We would appreciate it if you could distribute the following call for papers to any relevant mailing lists you know of. CALL FOR PAPERS =========================================================== Special Session: Design, Analysis and Tools for Integrated Circuits and Systems DATICS 2008 July 22-24, 2008 (Crete Island, Greece) http://digilander.libero.it/systemcfl/datics =========================================================== Aims and Scope -------------------------- The main target of the Special Session: DATICS 2008 of the WSEAS CSCC multi-conference (http://www.wseas.org/conferences/2008/greece/icc/) is to bring together software/hardware engineering researchers, computer scientists, practitioners and people from industry to exchange theories, ideas, techniques and experiences related to all areas of design, analysis and tools for integrated circuits (e.g. digital, analog and mixed-signal circuits) and systems (e.g. real-time, hybrid and embedded systems). The special session also focuses on the field of formal methods and low power design methodologies for integrated circuits. Topics ---------- Topics of interest include, but are not limited to, the following: * digital, analog, mixed-signal designs and test * RF design and test * design-for-testability and built-in self test methodologies * reconfigurable system design * high-level synthesis * EDA tools for design, testing and verification * low power design methodologies * network and system on-a-chip * application-specific SoCs * specification languages: SystemC, SystemVerilog and UML * all areas of modelling, simulation and verification * formal methods and formalisms (e.g. process algebras, petri-nets, automaton theory and BDDs) * real-time, hybrid and embedded systems * software engineering (including real-time Java, real-time UML and performance metrics) Industrial Collaborators: ----------------------------------- DATICS 2008 is partnered with: * CEOL: Centre for Efficiency-Oriented Languages "Towards improved software timing", University College Cork, Ireland ( http://www.ceol.ucc.ie) * International Software and Productivity Engineering Institute, USA (http://www.intspei.com ) * Intelligent Support Ltd., United Kingdom (http://www.isupport- ltd.co.uk) * Solari, Hong Kong ( http://www.solari-hk.com) * Minteos, Italy (http://www.minteos.com) * M.O.S.T., Italy (http://www.most.it) Technical Program Committee: ---------------------------------------------- * Prof. Vladimir Hahanov, Kharkov National University of Radio Electronics, Ukraine * Prof. Paolo Prinetto, Politecnico di Torino, Italy * Prof. Alberto Macii, Politecnico di Torino, Italy * Prof. Joongho Choi, University of Seoul, South Korea * Prof. Wei Li, Fudan University, China * Prof. Michel Schellekens, University College Cork, Ireland * Prof. Franco Fummi, University of Verona, Italy * Prof. Jun-Dong Cho, Sung Kyun Kwan University, South Korea * Dr. Emanuel Popovici, University College Cork, Ireland * Dr. Jong-Kug Seon, Telemetrics Lab., LG Industrial Systems Co. Ltd., South Korea * Dr. Umberto Rossi, STMicroelectronics, Italy * Dr. Graziano Pravadelli, University of Verona, Italy * Dr. Vladimir Pavlov, International Software and Productivity Engineering Institute, USA * Dr. Jinfeng Huang, Philips & LiteOn Digital Solutions Netherlands, Advanced Research Centre, The Netherlands * Dr. Thierry Vallee, Georgia Southern University, Statesboro, Georgia, USA * Dr. Menouer Boubekeur, University College Cork, Ireland * Dr. Ana Sokolova, University of Salzburg, Austria * Dr. Sergio Almerares, STMicroelectronics, Italy * Ajay Patel (Director), Intelligent Support Ltd, United Kingdom * Monica Donno (Director), Minteos, Italy * Alessandro Carlo (Manager), Research and Development Centre of FIAT, Italy * Yui Fai Lam (Manager), Microsystems Packaging Institute, Hong Kong University of Science and Technology, Hong Kong Important Dates --------------------------- March 31, 2008: Deadline for submission of completed papers May 1, 2008: Notification of acceptance/rejection to authors Please visit our web-site for further information on the hosting conference of DATICS, submission guidelines, proceedings and publications and international technical reviewers. Best regards, General Chair of DATICS: Dr. K.L. Man (University College Cork, Ireland) and Organising Committee Chair: Miss Maria O'Keeffe (University College Cork, Ireland) From bearophileHUGS at lycos.com Wed Jan 30 08:24:18 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jan 2008 05:24:18 -0800 (PST) Subject: comparing two lists, ndiff performance References: Message-ID: <421f51b9-868d-4e6a-aaf8-2df0802e4467@y5g2000hsf.googlegroups.com> Zbigniew Braniecki: > Is there a way to speed it up? Any easier way? Faster method? This problem is a bit messy. Maybe it's better to sidestep the problem, and not use a list, and create an object that wraps the list, so it always keeps an updated record of what changes are done... but you have to notify it if you change the objects it contains. Bye, bearophile From ctrachte at gmail.com Fri Jan 4 20:30:42 2008 From: ctrachte at gmail.com (infixum) Date: Fri, 4 Jan 2008 17:30:42 -0800 (PST) Subject: vim newb - indenting python comments Message-ID: I'm just starting to use vim. It has helped me do a lot of repetitive editing of Python files. One problem I have is that the >> indent in normal mode doesn't work when a line starts with the # character. Any idea what I'm doing wrong? Thanks in advance for your help. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jan 25 17:46:19 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 25 Jan 2008 23:46:19 +0100 Subject: Puzzled by behaviour of class with empty constructor References: <99b8e2ac-1c72-430a-9172-a809e169f96a@i12g2000prf.googlegroups.com> Message-ID: <5vv75rF1nt2o7U1@mid.individual.net> dbaston at gmail.com wrote: > print x.ends,y.ends,z.ends > ############# > Running the following code outputs: >>>> [(0, 2)] [(0, 2)] [(0, 2)] > > Can anyone explain this? Yes. You bound a single list to the name "ends" inside the class. This name is shared by all instances. If you want the instances to each have separate lists, delete the "ends" definition from class declaration and insert "self.ends = []" into __init__. I also suggest you to have a look at the tutorial. Regards, Bj?rn -- BOFH excuse #49: Bogon emissions From sjmachin at lexicon.net Sun Jan 20 19:23:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jan 2008 16:23:46 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> Message-ID: <930da860-87d7-4a37-89cf-5a21aa3c1bd1@e6g2000prf.googlegroups.com> On Jan 21, 11:00 am, pythonewbie wrote: > On 21 jan, 00:09, John Machin wrote: > > > > > On Jan 21, 8:58 am, pythonewbie wrote: > > > > I just would like to know if I would ALWAYS find the install directory > > > in sys.path[6] and site-packages directory in sys.path[7] on any Win32 > > > platform and sys.path[2] and site-packages directory in sys.path[6] on > > > any Linux platform. > > > > If the reply is : "YES you can be sure of it !" > > > No, you can't be sure of any such thing. In general in computing > > assuming a fixed position in a variable-length list is a nonsense. > > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > > (Intel)] on win32 > > Type "help", "copyright", "credits" or "license" for more information.>>> import sys > > >>> from pprint import pprint as pp > > >>> pp([(x, p) for x, p in enumerate(sys.path)]) > > > [(0, ''), > > (1, 'c:\\python25\\lib\\site-packages\\setuptools-0.6c3-py2.5.egg'), > > (2, 'C:\\WINDOWS\\system32\\python25.zip'), > > (3, 'c:\\python25\\DLLs'), > > (4, 'c:\\python25\\lib'), > > (5, 'c:\\python25\\lib\\plat-win'), > > (6, 'c:\\python25\\lib\\lib-tk'), > > (7, 'c:\\python25'), > > (8, 'c:\\python25\\lib\\site-packages'), > > (9, 'c:\\python25\\lib\\site-packages\\win32'), > > (10, 'c:\\python25\\lib\\site-packages\\win32\\lib'), > > (11, 'c:\\python25\\lib\\site-packages\\Pythonwin')] > > > Something like this might be more reliable: > > > >>> import sys, re > > >>> for p in sys.path: > > > ... m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p) > > ... if m: > > ... print m.group(1, 0) > > ... break > > ... else: > > ... raise Exception('Huh?') > > ... > > ('c:\\python25', 'c:\\python25\\lib\\site-packages') > > > > All would be great for me and I would be ready to create a script to > > > detect with a reliable manner the installation dir. et site-packages > > > dir. for all my Linux/Win32 Python apps. > > > You mentioned Python versions back to 2.1 earlier. However you > > evidently haven't bothered to start up Python 2.1 and look at > > sys.path: > > > C:\junk>\python21\python > > Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on > > win32 > > Type "copyright", "credits" or "license" for more information.>>> import sys; sys.path > > > ['', 'C:\\junk', 'C:\\python21\\DLLs', 'C:\\python21\\lib', 'C:\ > > \python21\\lib\\ > > plat-win', 'C:\\python21\\lib\\lib-tk', 'C:\\python21'] > > > Before you rush out and re-invent the wheel, have a look at this: > > >http://www.python.org/community/sigs/current/distutils-sig/ > > > You may like to re-ask your questions on the distutils mailing list. > > > HTH, > > John > > Hi John, > > Thanks for your help and suggestions. > > Your code is very interesting for the newbie that I am. > > But I have not understood your two last suggestions... > > As a newbie, I have asked usenet for help in order to get a easy/ > convenient way to get the site-packages directory, and the best reply > I obtained, was to use the function > distutils.sysconfig.get_python_lib(). > > This function is a really good way to avoid to re-invent the wheel to > get what I wanted ! > I am talking about your underlying goal "My goal is to verify if an/ several extension(s) are installed and to automatically install the missing ones on Linux or Win32." ... you may well find that there is at least one wheel for "automatically install". From hat at se-162.se.wtb.tue.nl Thu Jan 31 08:56:55 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 31 Jan 2008 14:56:55 +0100 Subject: Python noob SOS (any [former?] Perlheads out there?) References: <6099ab30-390d-4b38-bc8e-81ecb52e03a6@e25g2000prg.googlegroups.com> Message-ID: On 2008-01-30, grflanagan wrote: > On Jan 29, 5:39 pm, kj wrote: > For command line options I get a long way with this: > > [code python] > def _getargs(): > allargs = sys.argv[1:] > args = [] > kwargs = {} > key = None > while allargs: > arg = allargs.pop(0) > if arg.startswith('--'): > key, arg = arg.split('=', 1) > key = key[2:] > elif arg.startswith('-'): > key = arg[1:] > if not allargs or allargs[0].startswith('-'): > allargs.insert(0, 'yes') > continue > if key is None: > args.append(arg) > else: > kwargs[key] = arg > key = None > return args, kwargs > > ARGS, KWARGS = _getargs() > [/code] Have a look at getopt (old) or optparse (newer) packages in the Python library instead. Sincerely, Albert From aisaac at american.edu Wed Jan 23 14:33:18 2008 From: aisaac at american.edu (Alan G Isaac) Date: Wed, 23 Jan 2008 14:33:18 -0500 Subject: Python printing! In-Reply-To: References: Message-ID: SMALLp wrote: > Hy. How to use printer in python. http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html From andre.roberge at gmail.com Sat Jan 12 15:50:54 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sat, 12 Jan 2008 12:50:54 -0800 (PST) Subject: Great Python books for the beginner References: <1a4d8dae-4722-4a10-a638-ac1b2d85227a@i72g2000hsd.googlegroups.com> Message-ID: <306d22c4-b578-4df4-b01b-7a4d55070823@1g2000hsl.googlegroups.com> On Jan 12, 4:04 pm, Landon wrote: > One thing I wonder about is the examples these books use to teach the > concepts. I found myself really attached to K&R because the end of > section projects were utilities that I would find be able to find > useful in day to day work such as a version of wc and a program that > would take collapse all consecutive whitespace in a document into one > space. I could just use the projects from K&R, but I imagine a Python > book would have a better selection that highlight Python's abilities. > > On another note, I would prefer to have a paper book so I don't have > to keep switching back and forth between documents on my computer. You don't need to switch back and forth ... if you use Crunchy! http://code.google.com/p/crunchy To see it in action, http://showmedo.com/videos/video?name=1430000&fromSeriesID=143 (the third video in that series shows how to quickly get started using the official Python tutorial). Andr? From http Sat Jan 12 14:28:05 2008 From: http (Paul Rubin) Date: 12 Jan 2008 11:28:05 -0800 Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> <354c74f6-6e56-4e41-a686-56239aa4cea9@f47g2000hsd.googlegroups.com> <7x8x2uj3yb.fsf@ruckus.brouhaha.com> <0ad68aa8-735d-4cf0-b17a-d1f2be6af652@f47g2000hsd.googlegroups.com> <7x1w8mj27a.fsf@ruckus.brouhaha.com> Message-ID: <7x7iie3ku2.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > Will you engage with me over e-mail to discuss the Locker > implementation I'm developing? Aaron I really can't, sorry. I'm finding it hard enough to follow over the newsgroup. If you just have a single one of these lists, it's probably simplest to do what Frederik Lundh suggested. The other stuff we've discussed is mostly about how to organize having a lot of them. From martyb1 at earthlink.net Tue Jan 1 17:57:44 2008 From: martyb1 at earthlink.net (Marty) Date: Tue, 01 Jan 2008 17:57:44 -0500 Subject: Catching external program exceptions Message-ID: <25qdnZuc2dn0WOfanZ2dnUVZ_gWdnZ2d@wideopenwest.com> I need to catch exceptions thrown by programs started by the os.system function, as indicated by a non-zero return code (e.g. the mount utility). For example, if I get the following results in a bash shell: $mount test mount: can't find /home/marty/test in /etc/fstab or /etc/mtab then I want to catch the same exception from the corresponding os.system() call, i.e. "os.system('mount test')", but it doesn't work as expected: >>> import os, sys >>> try: os.system('mount test') ... except: print 'error' ... mount: can't find /home/marty/test in /etc/fstab or /etc/mtab 256 >>> I get the same results with popon, popen2, popen3, etc. Apparently these also work only when the program does not generate an exception. Is there any way to catch the return code. or if not, a workaround? From martin at v.loewis.de Thu Jan 17 15:35:38 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 Jan 2008 21:35:38 +0100 Subject: Hebrew in idle ans eclipse (Windows) In-Reply-To: <86ea4c94-f4b3-4bc3-9b2a-bc9b5c182264@i12g2000prf.googlegroups.com> References: <478ee0c0$0$4589$9b622d9e@news.freenet.de> <86ea4c94-f4b3-4bc3-9b2a-bc9b5c182264@i12g2000prf.googlegroups.com> Message-ID: <478FBC1A.4080201@v.loewis.de> > import pymssql > > con = > pymssql.connect(host='192.168.13.122',user='sa',password='',database='tempdb') > cur = con.cursor() > cur.execute('select firstname, lastname from [users]') > lines = cur.fetchall() > > print lines > > or > > print lines[0] > > 'lines' is a list containing tuples of 2 values, for firstname and > lastname. The names are Hebrew and their code looks different when I'm > runnig it from IDLE than when running it from Windows shell or > eclipse, as I described in my first post. Ok. Please understand that there are different ways to represent characters as bytes; these different ways are called "encodings". Please also understand that you have to make a choice of encoding every time you represent characters as bytes: if you read it from a database, and if you print it to a file or to the terminal. Please further understand that interpreting bytes in an encoding different from the one they were meant for results in a phenomenon called "moji-bake" (from Japanese, "ghost characters"). You get some text, but it makes no sense (or individual characters are incorrect). So you need to find out a) what the encoding is that your data have in MySQL b) what the encoding is that is used when printing in IDLE c) what the encoding is that is used when printing into a terminal window. b) and c) are different on Windows; the b) encoding is called the "ANSI code page", and c) is called the "OEM code page". What the specific choice is depends on your specific Windows version and local system settings. As for a: that's a choice somebody made when the database was created; I don't know how to figure out what encoding MySQL uses. In principle, rather than doing print lines[0] you should do print lines[0].decode("").encode("") when printing to the console. Furtenately, you can also write this as print lines[0].decode("") as Python will figure out the console encoding by itself, but it can't figure out the MySQL encoding (or atleast doesn't, the way you use MySQL). Regards, Martin From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 22:03:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 03:03:06 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <13od12b23hfv772@corp.supernews.com> <5b035c91-72eb-4d88-b19b-e89470865c5b@i7g2000prf.googlegroups.com> Message-ID: <13ogbfasbcici1c@corp.supernews.com> On Fri, 11 Jan 2008 09:52:17 -0800, Paul Boddie wrote: > These days, I seriously doubt that anyone uses the term "interpreted" to > mean "parses the source text and works out what to do, over and over > again as the program runs". Given the way that people seem to use "interpreted" as a pejorative and a synonym for "slow", I don't doubt it one bit. Especially in management, where they might be making technical judgments on the basis of half- remembered Comp Sci 101 lessons from fifteen years earlier and vague buzzword-laden articles in trade magazines. -- Steven From MartinRinehart at gmail.com Mon Jan 7 11:06:24 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Mon, 7 Jan 2008 08:06:24 -0800 (PST) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: Thank you both. Stupid me, went to Python.org and found Style Guidelines and thought that was the last word. Oh well. PEP 8 reminds me a lot of Sun's Java conventions, in ways I wish it didn't. The overall structure seems like a random list of topics and it omits a lot. For Java I went from Sun to other conventions to try to compile a meta-convention ( http://www.MartinRinehart.com/articles/code-conventions.html ). Here's just one of my questions: foo = [ 'some item, quite long', 'more items, all demanding there own line as they are not short', ... Where would you put the closing ']'? From dongie.agnir at gmail.com Thu Jan 10 08:05:53 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Thu, 10 Jan 2008 05:05:53 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <8f99cb7e-5664-4ebb-b3fc-dd32124ea5f4@m77g2000hsc.googlegroups.com> Message-ID: On Jan 10, 3:00 am, Ant wrote: > On Jan 10, 12:04 pm, "dongie.ag... at gmail.com" > wrote: > > > For the most part, I agree with you, which is why I chose Python in > > the first place. I like quick development. Unfortunately, this is > > one of those cases where execution time is a factor. Who knows, maybe > > someone who's done camera vision with Python will come in and say it's > > just the algorithm in the example that needs work (I'm crossing my > > fingers that that's the case). > > It would probably be worth reposting your question with a different > subject line. Something along the lines of "Image/Video processing > performance in Python", and explaining what you actually want to > achieve. "Python too slow?" doesn't give enough information - clearly > Python is fast enough for many many tasks, since it is so widely used. > It also sounds like a troll - so many people who would actually be > able to assist you (such as the PIL, pygame and numpy/scipy > communities) may have ignored this thread. > > Cheers, > > -- > Ant. Thanks for the advice. I'll do that now. From gagsl-py2 at yahoo.com.ar Sun Jan 20 15:26:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 20 Jan 2008 18:26:14 -0200 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Message-ID: En Sun, 20 Jan 2008 18:06:57 -0200, escribi?: > Nice challenge! I came up with something like this: A nice solution too! -- Gabriel Genellina From jorgen.maillist at gmail.com Sat Jan 12 10:13:08 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Sat, 12 Jan 2008 16:13:08 +0100 Subject: where do my python files go in linux? In-Reply-To: <20080112113759.GJ75977@nexus.in-nomine.org> References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> <20080112113759.GJ75977@nexus.in-nomine.org> Message-ID: <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> Hi Jeroen, Thanks for the advice. > Personally I'd be loathe to put app.py in /usr/bin. This directory is normally > reserved for OS-specific binaries. For personal/system-extended stuff I'd use > /usr/local/bin or whatever your system mandates. (But hey, that's the typical > mentality difference between the BSD and Linux world it seems, so do with it > what you want.) I thought about that too. I just wonder why /usr/local/bin is always empty and every .deb I install from a source (if it's from Ubuntu or not) installs files in /usr/bin .. So I looked further and noticed that most python files do reside in /usr/share/{appname} > Normally you'd split up the bulk of the code into a module which gets > installed into site-packages and a piece of stand-alone front-end code which > imports the module and executes whatever you need to do and gets installed > into a typical PATH directory. I would agree but it is not a site package I am trying to distribute, but a wxPython application. I would not think my app belongs in the python site packages dir. Thanks a lot for the input! - Jorgen From asmodai at in-nomine.org Mon Jan 7 06:01:04 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 7 Jan 2008 12:01:04 +0100 Subject: python syntax In-Reply-To: <633886.19582.qm@web45510.mail.sp1.yahoo.com> References: <633886.19582.qm@web45510.mail.sp1.yahoo.com> Message-ID: <20080107110104.GD82115@nexus.in-nomine.org> -On [20080107 11:46], mpho raborife (mraborife at yahoo.com) wrote: >os.system("HCopy -T 1 -C" 'os.path.join(conf_dir, "/hcopy.conf")' "-S" >'os.path.join(list_dir, "hcopy_list.txt")') I would guess you would want this: os.system("HCopy -T 1 -C" + os.path.join(conf_dir, "/hcopy.conf") + "-S" + os.path.join(list_dir, "hcopy_list.txt")) But I'd personally not use such a contracted syntax, it makes detecting failure on any of the three function calls difficult. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ If I promise you the Moon and the Stars, would you believe it..? From deets at nospam.web.de Wed Jan 2 07:46:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Jan 2008 13:46:23 +0100 Subject: wxpython application ( problem ? ) References: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> <5u1asvF1fgr5bU2@mid.uni-berlin.de> <7cb975f6-e9a6-4527-bd84-2041aede197f@j20g2000hsi.googlegroups.com> Message-ID: <5u1fcvF1fqkc0U1@mid.uni-berlin.de> vedrandekovic at gmail.com wrote: > On 2 sij, 12:29, Marc 'BlackJack' Rintsch wrote: >> On Wed, 02 Jan 2008 03:24:56 -0800, vedrandekovic wrote: >> > Here is sample of my simple script with wxpython and modules: >> > subprocess,threading, directpython....... >> >> Are you accessing the GUI from threads? >> >> Ciao, >> Marc 'BlackJack' Rintsch > > > Hi again, > > yes, so what's the problem? It is the problem. It is usually not allowed to manipulate GUI-objects from any thread except the main-thread that runs the event-loop. All GUI-toolkits have guidelines how to cope with that, e.g. custom events in Qt3, or timers. This message indicates that WX has similar means: http://osdir.com/ml/python.matplotlib.general/2005-03/msg00208.html Diez From mail at timgolden.me.uk Wed Jan 23 04:55:08 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Jan 2008 09:55:08 +0000 Subject: what's wrong with the wmi.Terminate() method? In-Reply-To: References: Message-ID: <47970EFC.90206@timgolden.me.uk> thunder54007 at gmail.com wrote: [... snip same problem as reported to python-win32 ...] See my reply on python-win32. TJG From steve at REMOVE-THIS-cybersource.com.au Mon Jan 21 08:58:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 13:58:48 -0000 Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> Message-ID: <13p998o7mskm7e0@corp.supernews.com> On Mon, 21 Jan 2008 09:53:10 +0100, Peter Otten wrote: > Santiago Romero wrote: > >> I'm trying to sort both lists so that they end like this: >> >> preferences = [10, 20, 30] >> hosts = [ "mx1.domain.com", "mx2.domain.com", "anotherhost.domain.com" >> ] >> >> I want to sort hosts list depending on the numeric order of >> "preferences". > > The following relies on undocumented (I hope) behaviour: What bit are you suggesting is undocumented? >>>> preferences = [10, 30, 20] >>>> hosts = [ "mx1.domain.com", "anotherhost.domain.com", >... "mx2.domain.com"] >>>> hosts.sort(key=lambda x, p=iter(preferences).next: p()) >>>> preferences.sort() >>>> hosts > ['mx1.domain.com', 'mx2.domain.com', 'anotherhost.domain.com'] >>>> preferences > [10, 20, 30] Now if you wanted to claim it was opaque and confusing, I'd agree with you :-) Here's a function that uses the Decorate-Sort-Undecorate technique to sort one list by the contents of another: from sys import maxint _indices = xrange(maxint) def sorterDSU(alist, blist): """Return a copy of alist sorted by the contents of blist.""" assert len(alist) == len(blist) decorated = zip(blist, _indices, alist) decorated.sort() return [avalue for (bvalue, i, avalue) in decorated] Here's another version: def sorter(alist, blist): assert len(alist) == len(blist) table = sorted(range(len(alist)), key=blist.__getitem__) return [alist[i] for i in table] >>> alist = "John Eric Michael Graham Terry-J Terry-G".split() >>> blist = [5, 0, 4, 1, 3, 2] >>> sorter(alist, blist) ['Eric', 'Graham', 'Terry-G', 'Terry-J', 'Michael', 'John'] -- Steven From gavinlusby at googlemail.com Wed Jan 23 12:21:08 2008 From: gavinlusby at googlemail.com (Gavin Lusby) Date: Wed, 23 Jan 2008 17:21:08 -0000 Subject: Checking the existence of parsed variables Message-ID: <000001c85de4$59c3f400$0adea8c0@bp1.ad.bp.com> Hello all, I am regularly writing programs that parses ever changing lists of variables. The method I do it is by loading it in to a dictionary of the form: d['variable_name']=variable_value So when it comes to a method that uses a required set of variables I have to make tens of the following statements if d.has_key('swr'): swr = float(d['swr']) else: print 'ERROR: COREYTAB variable swr not specified'; iErr += 1 When I thought a pythonic way of doing it would be to use a variable variable.(sorry that sounds ridiculous) but it would work like this: _start_code_________________________________________________________________ ___ # make all input parameters equal the string of themselves type = 'type'; tabnum = 'tabnum'; coreyw = 'coreyw'; coreyow = 'coreyow' swc = 'swc'; swr = 'swr'; kro_swc = 'kro_swc'; krw_swr = 'krw_swr' coreyg = 'coreyg'; coreygo = 'coreygo'; sgi = 'sgi'; sgc = 'sgc' sgr = 'sgr'; kro_sgc = 'kro_sgc'; krg_swc = 'krg_swc' # error check parameters existence and if there, over-write their info # if there are integer values, then must remember to re-typecast them later for var in (type, tabnum, coreyw, coreyow, swc, swr, kro_swc, krw_swr, coreyg, coreygo, sgi, sgc, sgr, kro_sgc, krg_swc): if d.has_key(var): if isnumeric(d[var]): var = float(d[var]) else: var = d[var] else: print 'ERROR: getcorey() parameter '+str(var)+' not specified' iErr += 1 _end_code___________________________________________________________________ ___ Since this doesn't work, any other ideas out there? Many thanks in advance, Gavin -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Jan 17 10:55:56 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jan 2008 16:55:56 +0100 Subject: Is this a bug, or is it me? References: Message-ID: cptnwillard wrote: > Hello all, > For some reason, the following does not work : > > > class C: > TYPES = [None] > DICT = {} > for Type in TYPES: > DICT.update((E,Type) for E in [1]) > >>>> NameError: global name 'Type' is not defined > > > What do you think? Is this a bug? Here is a simpler example: >>> class A: ... a = 42 ... list(a for _ in "a") ... Traceback (most recent call last): File "", line 1, in File "", line 3, in A File "", line 3, in NameError: global name 'a' is not defined The equivalent code using a list comprehension instead of the generator expression works without complaint: >>> class A: ... a = 42 ... [a for _ in "a"] ... >>> So it seems that Python gets puzzled by the extra scope introduced by the genexp, i. e. you are seeing an obscure variant of the following (expected) behaviour: >>> class B: ... a = 42 ... def f(): a ... f() ... Traceback (most recent call last): File "", line 1, in File "", line 4, in B File "", line 3, in f NameError: global name 'a' is not defined I think you should file a bug report, though making the genexp recognizing the class scope probably isn't worth the effort. Peter From nytrokiss at gmail.com Tue Jan 22 15:05:26 2008 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 22 Jan 2008 21:05:26 +0100 Subject: question In-Reply-To: <6760762.631391201031899339.JavaMail.root@hrndva-web18-z01> References: <6760762.631391201031899339.JavaMail.root@hrndva-web18-z01> Message-ID: <8a6b8e350801221205s723a6330te59e48389957a086@mail.gmail.com> Since you aren't familyer with classes i will keep this within the scope of functions... If you have code like this def a(): def b(): a+=1 Then you can only call function b when you are within function a James On Jan 22, 2008 8:58 PM, wrote: > I'm still learning Python and was wanting to get some thoughts on this. I apologize if this sounds ridiculous... I'm mainly asking it to gain some knowledge of what works better. The main question I have is if I had a lot of lists to choose from, what's the best way to write the code so I'm not wasting a lot of memory? I've attempted to list a few examples below to hopefully be a little clearer about my question. > > Lets say I was going to be pulling different data, depending on what the user entered. I was thinking I could create a function which contained various functions inside: > > def albumInfo(theBand): > def Rush(): > return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > > def Enchant(): > return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > > ... > > The only problem with the code above though is that I don't know how to call it, especially since if the user is entering a string, how would I convert that string into a function name? For example, if the user entered 'Rush', how would I call the appropriate function --> albumInfo(Rush()) > > But if I could somehow make that code work, is it a good way to do it? I'm assuming if the user entered 'Rush' that only the list in the Rush() function would be stored, ignoring the other functions inside the albumInfo() function? > > I then thought maybe just using a simple if/else statement might work like so: > > def albumInfo(theBand): > if theBand == 'Rush': > return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > elif theBand == 'Enchant': > return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > ... > > Does anyone think this would be more efficient? > > I'm not familiar with how 'classes' work yet (still reading through my 'Core Python' book) but was curious if using a 'class' would be better suited for something like this? Since the user could possibly choose from 100 or more choices, I'd like to come up with something that's efficient as well as easy to read in the code. If anyone has time I'd love to hear your thoughts. > > Thanks. > > Jay > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com From rschroev_nospam_ml at fastmail.fm Thu Jan 17 13:14:38 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 17 Jan 2008 18:14:38 GMT Subject: Loop in a loop? In-Reply-To: References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: Sacred Heart schreef: > On Jan 17, 1:35 pm, cokofree... at gmail.com wrote: >> for i in zip(array1, array2): >> print i >> >> Although I take it you meant four d, the issue with this method is >> that once you hit the end of one array the rest of the other one is >> ignored. > > Yes, small typo there. > > Okey, so if my array1 is has 4 elements, and array2 has 6, it won't > loop trough the last 2 in array2? How do I make it do that? One solution is with map() instead if zip(). map() with None as the first argument works much like zip(), but it keeps looping if one of the lists is exhausted. When that happens, it uses None for those values: words = ['zero', 'one', 'two', 'three'] numbers = [0, 1, 2, 3, 4, 5, 6] for word, number in map(None, words, numbers): print word, number zero 0 one 1 two 2 three 3 None 4 None 5 None 6 -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From aahz at pythoncraft.com Sun Jan 6 12:53:21 2008 From: aahz at pythoncraft.com (Aahz) Date: 6 Jan 2008 09:53:21 -0800 Subject: Cost of "unicode(s)" where s is Unicode References: <4780fb68$0$36341$742ec2ed@news.sonic.net> <70b9f250-a7b5-423e-8395-d0c4215d2564@d70g2000hsb.googlegroups.com> Message-ID: In article <70b9f250-a7b5-423e-8395-d0c4215d2564 at d70g2000hsb.googlegroups.com>, JKPeck wrote: > >>>> u = u"abc" >>>> uu = unicode(u) >>>> u is uu >True >>>> s = "abc" >>>> ss = unicode(s) >>>> s is ss >False You uuencode Unicode? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Sorry, couldn't resist the alliteration From martin at marcher.name Tue Jan 8 05:04:33 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 08 Jan 2008 11:04:33 +0100 Subject: use fileinput to read a specific line References: Message-ID: jo3c wrote: > i need to read line 4 from a header file http://docs.python.org/lib/module-linecache.html ~/2delete $ cat data.txt L1 L2 L3 L4 ~/2delete $ python Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import linecache >>> linecache.getline("data.txt", 2) 'L2\n' >>> linecache.getline("data.txt", 5) '' >>> linecache.getline("data.txt", 1) 'L1\n' >>> -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From asmodai at in-nomine.org Sun Jan 13 05:46:41 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sun, 13 Jan 2008 11:46:41 +0100 Subject: __init__ explanation please In-Reply-To: <47895d25$0$30708$4c368faf@roadrunner.com> References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: <20080113104641.GN75977@nexus.in-nomine.org> -On [20080113 01:41], Erik Lind (elind at spamcop.net) wrote: >I'm new to Python, and OOP. I've read most of Mark Lutz's book and more >online and can write simple modules, but I still don't get when __init__ >needs to be used as opposed to creating a class instance by assignment. I personally tend to see __init__ or __new__ as equivalent to what other languages call a constructor. (And I am sure some people might disagree with that. ;)) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ The riddle master himself lost the key to his own riddles one day, and found it again at the bottom of his heart. From pydecker at gmail.com Thu Jan 24 18:12:28 2008 From: pydecker at gmail.com (Peter Decker) Date: Thu, 24 Jan 2008 17:12:28 -0600 Subject: Testing whether something is of type Exception In-Reply-To: <47991a8a$0$36353$742ec2ed@news.sonic.net> References: <47991a8a$0$36353$742ec2ed@news.sonic.net> Message-ID: On Jan 24, 2008 5:14 PM, John Nagle wrote: > How can I tell whether an object is of type Exception? > At least in Python 2.4, "Exception" is an old-style class, and > the "type" of Exception objects is "instance". > > Clearly "repr" knows; it returns: > isinstance(x, Exception) -- # p.d. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 09:11:31 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 15:11:31 +0100 Subject: anti-spam policy for c.l.py? In-Reply-To: References: <08ed32c4-6230-4b14-9c31-4b94e0231cf2@c4g2000hsg.googlegroups.com> <478dee4e$0$28424$426a34cc@news.free.fr> Message-ID: <478e1068$0$27280$426a34cc@news.free.fr> Jeroen Ruigrok van der Werven a ?crit : > -On [20080116 12:51], Bruno Desthuilliers (bruno.42.desthuilliers at wtf.websiteburo.oops.com) wrote: >> Apart from checking posts headers and complaining about the relevant >> ISPs, there's not much you can do AFAIK. This is usenet, not a mailing-list. > > It is both actually. python-list at python.org is linked to comp.lang.python due > to a news gateway. Yes, I know - but the OP explicitely mentionned c.l.py (re-read the title), not the ML. From petr.jakes.tpc at gmail.com Fri Jan 25 14:43:40 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Fri, 25 Jan 2008 11:43:40 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application Message-ID: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> Hi, I am working with the Python 2.5 running on the command line version of Linux Ubuntu 7.04. This means NO X-windows, NO GTK/Gnome, NO computer mouse, on my machine (AMD Geode 500MHz CPU, VGA output). I would like to write some really light weighted GU interface. My concept is to have just few user screens (about 10) controlled via 4 or 5 HW buttons connected to the GPIO pins they are available on the motherboard (the HW design and the SW concept of reading this buttons is already solved). After some googling, I have found below mentioned can be usable, but first, I would like to ask here for your opinions/experiences/advices. Best regards Petr Jakes http://www.libsdl.org/ http://pyfltk.sourceforge.net/ http://www.pygame.org/news.html http://pyui.sourceforge.net/ http://pyglet.org/ From eproust at gmail.com Mon Jan 21 05:38:14 2008 From: eproust at gmail.com (pythonewbie) Date: Mon, 21 Jan 2008 02:38:14 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <5vi1r8F1mjs0rU1@mid.uni-berlin.de> <5360e13d-215d-4d3e-9930-daa6cddd996a@f10g2000hsf.googlegroups.com> <5vj79dF1m2nmlU1@mid.uni-berlin.de> Message-ID: <677d61a1-16be-40ae-8332-a5ff45ff8905@j78g2000hsd.googlegroups.com> On 21 jan, 10:34, "Diez B. Roggisch" wrote: > pythonewbie > > > > > Because the solution using distutils.sysconfig.get_python_lib() is > > very smart ! > > Depending on your goal. You said > > """ > My goal is to verify if an/several extension(s) are installed and to > automatically install the missing ones on Linux or Win32. > """ > > This goal can't be reached with only the site-packages - because I can > install packages somewhere else (matter of factly, this happens on debian > for example, they've split the install-dirs and created a bunch of dirs > under /usr/share) > > So having a method that gives you the installation root doesn't help much > here. > > Diez Diez, I repeat I am a newbie, so please don't be angry against me, if I say something stupid or if I propose a method not efficient. An easy way to get the absolute path of site-packages seems very useful to me, in order to check anything (all extensions available and not provided by sys.path, etc.) related to the files on the filesystem, if necessary. For the automatic installation of missing extensions (using admin rights), I think that it is not difficult to do it on both platforms... From siona at chiark.greenend.org.uk Wed Jan 9 12:16:21 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Jan 2008 17:16:21 +0000 (GMT) Subject: How to get memory size/usage of python object References: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> Message-ID: Santiago Romero wrote: > Is there a way to check the REAL size in memory of a python object? > > Something like > >> print sizeof(mylist) > [ ... ] Would you care to precisely define "REAL size" first? Consider: >>> atuple = (1, 2) >>> mylist = [(0, 0), atuple] Should sizeof(mylist) include sizeof(atuple) ? >>> del atuple What about now, when mylist has the only reference to the (1, 2) object that also used to be referred to as atuple? -- \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 jarausch at igpm.rwth-aachen.de Fri Jan 25 04:12:02 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Fri, 25 Jan 2008 10:12:02 +0100 Subject: global/local variables In-Reply-To: <4d161c89-7e33-4ddc-851f-bc9beb537229@q21g2000hsa.googlegroups.com> References: <13pia51grjfo2ed@corp.supernews.com> <4d161c89-7e33-4ddc-851f-bc9beb537229@q21g2000hsa.googlegroups.com> Message-ID: <5vtnf3F1nen4hU1@mid.dfncis.de> Tim Rau wrote: > I'm sorry: I forgot to say what my problem was. Python seems to think > that nextID is a local, and complains that it can't find it. THis is > not the full text of the function, just the level that is causing > errors. the lack of : on the if is a transcription error. > Traceback (most recent call last): > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > \sandbox.py", line 248, in > thing.step() > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > \sandbox.py", line 112, in step > allThings[len(allThings)-1].id = nextID > UnboundLocalError: local variable 'nextID' referenced before > assignment But in the next line in the same function you say nextID+= 1 Since there is an assignment to nextID in the same function without a global statement, you tell Python, that nextID is a local variable. Note: Assignment (anywhere in a function) is a local definition unless there is a global statement in this function > I want to know why it says 'local variable' it never had a problem > when just allThings was in there. > > as for the objection to global variable: If I didn't make them global, > I'd make them part of a singleton class called gameVars that would get > passed everywhere. It's unlikely that they'll get mixed in with > anyhting else, as they fulfill a unique function. Also, I think it's > more convenient, and I am, after all, my own employer when it comes to > programming. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From radiosrfun at radiosrfun.com Sat Jan 12 10:35:38 2008 From: radiosrfun at radiosrfun.com (radiosrfun) Date: Sat, 12 Jan 2008 10:35:38 -0500 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> Message-ID: <4788de48$0$26887$ecde5a14@news.coretel.net> "default" wrote in message news:91hho3tr56dpsfqsav4lnr8sl944bbrviv at 4ax.com... > On Sat, 12 Jan 2008 02:01:09 -0500, "radiosrfun" > wrote: > >>I WISH - that the President and Congress of this country would shut off >>ALL >>foreign aid. > > Ditto that. > > Israel is the chief beneficiary of our foreign aid largesse. Some 8 > billion dollars annually. What doesn't find its way into politicians > pockets goes to pay for a military that is winning us a lot of new > friends in the Arab world. > > We pay Egypt ~ 2 billion a year in extortion to keep them from > attacking Israel. > > The actually amount Israel receives is not really known to the public. > The official numbers read something like 3 billion in aid, and another > 5 billion in guaranteed loans - which are turned into grants year > after year. This is money we borrow so there's an additional interest > burden. > > Actually when you talk about shutting off "foreign aid" you may be > making thermate's point for him. > -- Well - the first cup of coffee hasn't exactly kicked in yet - but I believe I know what you're saying and if correct - you may have a point there. From theller at ctypes.org Fri Jan 4 09:12:09 2008 From: theller at ctypes.org (Thomas Heller) Date: Fri, 04 Jan 2008 15:12:09 +0100 Subject: pydepend (checking dependencies like jdepend) ? In-Reply-To: <3E7E58237D756A4D85E7A36CB8C953ED01E24A@exchange2003.dspace.de> References: <1969e240-9e80-4df1-b085-7956dfa4f7ae@t1g2000pra.googlegroups.com> <71a1c5ae-2051-44ff-998e-a342fa88ffab@e25g2000prg.googlegroups.com> <3E7E58237D756A4D85E7A36CB8C953ED01E24A@exchange2003.dspace.de> Message-ID: Stefan Schukat schrieb: > No, py2exe does not display such information but has an algorithm to > collect such information. > Perhaps this is a starting point for you. If py2exe is run with the -x flag, it does display a cross-reference in a browser window. Thomas From wim at fixnum.org Wed Jan 23 03:36:33 2008 From: wim at fixnum.org (Wim Vander Schelden) Date: Wed, 23 Jan 2008 09:36:33 +0100 Subject: translating Python to Assembler In-Reply-To: References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: On 1/23/08, Christian Heimes wrote: > > Wim Vander Schelden wrote: > > Python modules and scripts are normally not even compiled, if they have > > been, > > its probably just the Python interpreter packaged with the scripts and > > resources. > > No, that is not correct. Python code is compiled to Python byte code and > execute inside a virtual machine just like Java or C#. It's even > possible to write code with Python assembly and compile the Python > assembly into byte code. > > You most certainly meant: Python code is not compiled into machine code. I didn't know that python uses a VM, I thought it still used an interpretter! You learn something new everyday :) Thanks, Wim -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Wed Jan 23 19:48:42 2008 From: aahz at pythoncraft.com (Aahz) Date: Wed, 23 Jan 2008 16:48:42 -0800 Subject: REMINDER: OSCON 2008 Call for Proposals Message-ID: <20080124004842.GA14395@panix.com> The O'Reilly Open Source Convention (OSCON) is accepting proposals for tutorials and presentations. The submission period ends Feb 4. OSCON 2008 will be in Portland, Oregon July 21-25. For more information and to submit a proposal, see http://conferences.oreilly.com/oscon/ -- 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 see.signature at no.spam Wed Jan 30 11:07:35 2008 From: see.signature at no.spam (Eric Brunel) Date: Wed, 30 Jan 2008 17:07:35 +0100 Subject: Tkinter - incremental input ? References: <60b922F1pnj4bU1@mid.dfncis.de> Message-ID: On Wed, 30 Jan 2008 13:32:00 +0100, Helmut Jarausch wrote: [snip] > While I can bind '' to a callback, I haven't figured out how > to get (and later on set) the cursor within the Entry widget. > In other words I need to know at which character position the last > character was entered. You can get the position of the insertion point with entry.index('insert'), and set it via entry.icursor(index). If you want to do this as the user types, take care to bind to KeyRelease; this way, the character corresponding to the key has already been entered in the entry. BTW, you may also want to automatically select the part that the user hasn't actually typed. This can be done with entry.selection_clear(), then entry.selection_range(start_position, end_position). HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From ckimyt at gmail.com Mon Jan 7 08:21:42 2008 From: ckimyt at gmail.com (Mike) Date: Mon, 7 Jan 2008 05:21:42 -0800 (PST) Subject: How to refer to the current module? Message-ID: I want to do something like the following (let's pretend that this is in file 'driver.py'): #!/bin/env python import sys def foo(): print 'foo' def bar(arg): print 'bar with %r' % arg def main(): getattr(driver, sys.argv[1])(*sys.argv[2:]) if __name__=='__main__': main() Essentially what I'm trying to get at here is dynamic function redirection, like a generic dispatch script. I could call this as python driver.py foo or python driver.py bar 15 and at any time later I can add new functions to driver.py without having to update a dispatch dict or what-have-you. The problem is, 'driver' doesn't exist in main() line 1. If I 'import driver' from the command line, then getattr(driver, ...) works, but it's not bound here. Is there any way around this? Can I somehow scope the 'current module' and give getattr(...) an object that will (at run time) have the appropriate bindings? Thanks in advance for all advice! Mike From ptmcg at austin.rr.com Mon Jan 7 18:15:47 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 7 Jan 2008 15:15:47 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python References: Message-ID: <43c9e776-b406-4e3e-9ef3-e6d7e574be3c@l6g2000prm.googlegroups.com> On Jan 7, 5:10?pm, dgoldsmith_89 wrote: > > Sorry for my ignorance: I can query an Access DB w/ standard SQL > queries (and this is how I would access it w/ Python)? > > DG If you are running on a Mac, just use sqlite, it's built-in to Python as of v2.5 and you will find more help, documentation, and fellow Python+sqlite users than you will Python+Access. -- Paul From bignose+hates-spam at benfinney.id.au Tue Jan 29 04:37:49 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 29 Jan 2008 20:37:49 +1100 Subject: optional static typing for Python References: <479da584$0$25625$426a74cc@news.free.fr> <69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com> Message-ID: <87lk69dlaq.fsf@benfinney.id.au> "Russ P." writes: > I would just like to thank you for reminding me about what losers > hang out perpetually on sites like this one, thinking they are in > some kind of real "community." Being reminded of that will help > prevent me from becoming such a loser myself. No, I didn't say that > all the "regulars" here are losers, but you most certainly are. We're a community largely because we don't tolerate this level of content-free insult. Please find a different forum for this stuff. -- \ "We spend the first twelve months of our children's lives | `\ teaching them to walk and talk and the next twelve years | _o__) telling them to sit down and shut up." -- Phyllis Diller | Ben Finney From mr.cerutti at gmail.com Tue Jan 1 18:54:54 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Tue, 1 Jan 2008 18:54:54 -0500 Subject: pyparsing question In-Reply-To: <8df809a0-1950-4250-a968-2d366f64cdb4@d21g2000prf.googlegroups.com> References: <8df809a0-1950-4250-a968-2d366f64cdb4@d21g2000prf.googlegroups.com> Message-ID: <51302a8c0801011554p16951e8fp1805ad6c3d65621a@mail.gmail.com> On Jan 1, 2008 6:32 PM, hubritic wrote: > I am trying to parse data that looks like this: > > IDENTIFIER TIMESTAMP T C RESOURCE_NAME DESCRIPTION > 2BFA76F6 1208230607 T S SYSPROC SYSTEM > SHUTDOWN BY USER > A6D1BD62 1215230807 I > H Firmware Event > > My problem is that sometimes there is a RESOURCE_NAME and sometimes > not, so I wind up with "Firmware" as my RESOURCE_NAME and "Event" as > my DESCRIPTION. The formating seems to use a set number of spaces. > > The data I have has a fixed number of characters per field, so I could > split it up that way, but wouldn't that defeat the purpose of using a > parser? I am determined to become proficient with pyparsing so I am > using it even when it could be considered overkill; thus, it has gone > past mere utility now, this is a matter of principle! If your data is really in fixed-size columns, then pyparsing is the wrong tool. There's no standard Python tool for reading and writing fixed-length field "flatfile" data files, but it's pretty simple to use named slices to get at the data. identifier = slice(0, 8) timestamp = slice(8, 18) t = slice(18, 21) c = slice(21, 24) resource_name = slice(24, 35) description = slice(35) for line in file: line = line.rstrip("\n") print "id:", line[identifier] print "timestamp:", line[timestamp] ...etc... -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Wed Jan 9 07:19:52 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 9 Jan 2008 04:19:52 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <2a90b41a-2e82-465a-8b97-50ead52dca5b@x69g2000hsx.googlegroups.com> My version, uses a re.sub, plus a function used as an object with a one bit state: from re import sub def repl(o): repl.n = not repl.n return ":" if repl.n else "," repl.n = False print sub("_", repl, "hi_cat_bye_dog_foo_bar_red") Bye, bearophile From ggpolo at gmail.com Wed Jan 16 15:28:07 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 16 Jan 2008 18:28:07 -0200 Subject: paramiko In-Reply-To: <3019696f-cf50-43e2-8534-2ef4ae4de5d9@y5g2000hsf.googlegroups.com> References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> <8ceaad4c-c725-4093-a204-ab09162d4629@c23g2000hsa.googlegroups.com> <685fabb3-c9e8-47ac-84f2-405b831bccad@v4g2000hsf.googlegroups.com> <3019696f-cf50-43e2-8534-2ef4ae4de5d9@y5g2000hsf.googlegroups.com> Message-ID: 2008/1/16, Tarun Kapoor : > On Jan 16, 1:56 pm, "Guilherme Polo" wrote: > > 2008/1/16, Tarun Kapoor : > > > > > > > > > On Jan 16, 12:22 pm, "Guilherme Polo" wrote: > > > > 2008/1/16, Tarun Kapoor : > > > > > > > On Jan 16, 11:38 am, "Guilherme Polo" wrote: > > > > > > 2008/1/16, Tarun Kapoor : > > > > > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across > > > > > > > the connection > > > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > > > > sock.connect((hostname, port)) > > > > > > > > > t = paramiko.Transport(sock) > > > > > > > t.start_client() > > > > > > > key = t.get_remote_server_key() > > > > > > > > > event = threading.Event() > > > > > > > t.auth_password(username=username, password=password, event=event) > > > > > > > event.wait() > > > > > > > > > if not t.is_authenticated(): > > > > > > > print "not authenticated" > > > > > > > > > output: > > > > > > > not authenticated > > > > > > > > This is a different problem I guess, now you are usin get_remote_server_key. > > > > > > And why are you creating event after calling start_client without > > > > > > specifying it ? > > > > > > > > > On Jan 16, 11:11 am, "Guilherme Polo" wrote: > > > > > > > > 2008/1/16, Tarun Kapoor : > > > > > > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > > > > > > > > > the remote server using an SFTP client I have just to make sure that > > > > > > > > > username and password are working.. This is the code. > > > > > > > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > > > > > > > > > connection > > > > > > > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > > > > > > > > sock.connect((hostname, port)) > > > > > > > > > > > t = paramiko.Transport(sock) > > > > > > > > > > > event = threading.Event() > > > > > > > > > > > t.start_client(event) > > > > > > > > > > > event.wait(15) > > > > > > > > > > > if not t.is_active(): > > > > > > > > > > > print 'SSH negotiation failed.' > > > > > > > > > > > sys.exit(1) > > > > > > > > > > > else: > > > > > > > > > > > print "SSH negotiation sucessful" > > > > > > > > > > > event.clear() > > > > > > > > > > > t.auth_password(username=username, password=password,event=event) > > > > > > > > > > > if not t.is_authenticated(): > > > > > > > > > > > print "not authenticated" > > > > > > > > > > > output: > > > > > > > > > > > SSH negotiation successful > > > > > > > > > > > not authenticated > > > > > > > > > > > Tarun > > > > > > > > > > > Waterstone Capital Management > > > > > > > > > > > 2 Carlson Parkway, Suite 260 > > > > > > > > > > > Plymouth, MN 55447 > > > > > > > > > > > Direct: 952-697-4123 > > > > > > > > > > > Cell: 612-205-2587 > > > > > > > > > Disclaimer This e-mail and any attachments is confidential and intended > > > > > > > > > solely for the use of the individual(s) to whom it is addressed. Any views > > > > > > > > > or opinions presented are solely those of the author and do not necessarily > > > > > > > > > represent those of Waterstone Capital Management, L.P and affiliates. If you > > > > > > > > > are not the intended recipient, be advised that you have received this > > > > > > > > > e-mail in error and that any use, dissemination, printing, forwarding or > > > > > > > > > copying of this email is strictly prohibited. Please contact the sender if > > > > > > > > > you have received this e-mail in error. You should also be aware that > > > > > > > > > e-mails are susceptible to interference and you should not assume that the > > > > > > > > > contents of this e-mail originated from the sender above or that they have > > > > > > > > > been accurately reproduced in their original form. Waterstone Capital > > > > > > > > > Management, L.P. and affiliates accepts no responsibility for information, > > > > > > > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > > > > > > > > > please verify the authenticity with the sender. > > > > > > > > > -- > > > > > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > You are missing an event.wait() after t.auth_password. > > > > > > > > Also, why are you passing this magic value "15" to event.wait() ? That > > > > > > > > parameter is passed to class _Verbose to indicate if debug messages > > > > > > > > should be displayed or not, so typical values would be 0/1 or > > > > > > > > False/True. > > > > > > > > > > -- > > > > > > > > -- Guilherme H. Polo Goncalves > > > > > > > > > -- > > > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > > > -- > > > > > > -- Guilherme H. Polo Goncalves > > > > > > > ok here is the problem... I don't know what is the correct way... The > > > > > only demos i have from the paramiko library use a hostkeyfile. since i > > > > > don't have that i thought i would use the get_remote_key to get the > > > > > key and then connect it using the code in the demo.. But clearly > > > > > nothing is working...I should not HAVE to use the key since i should > > > > > be able to authenticate using the password... > > > > > > > Can you please suggest the right way to go ? > > > > > > You don't need to use key to authenticate using username and password, > > > > indeed. And you don't. Your first email was almost correct, you just > > > > needed to add event.wait() after t.auth_password. It worked here after > > > > doing that change. You can check out my version: > > > > > > import sys > > > > import socket > > > > import paramiko > > > > import threading > > > > > > if len(sys.argv) != 4: > > > > print "%s hostname user password" % sys.argv[0] > > > > sys.exit(1) > > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > sock.connect((sys.argv[1], 22)) > > > > > > t = paramiko.Transport(sock) > > > > event = threading.Event() > > > > t.start_client(event) > > > > > > event.wait() > > > > > > if not t.is_active(): > > > > print 'SSH negotiation failed.' > > > > sys.exit(1) > > > > else: > > > > print "SSH negotiation sucessful" > > > > > > event.clear() > > > > t.auth_password(username=sys.argv[2], password=sys.argv[3], event=event) > > > > event.wait() > > > > if not t.is_authenticated(): > > > > print "Authentication failed." > > > > else: > > > > print "Authenticated!" > > > > > > t.close() > > > > > > > Thanks for your time ! > > > > > -- > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > > > > -- Guilherme H. Polo Goncalves > > > > > ok i tried the exact same code and here is the output > > > SSH negotiation sucessful > > > Authentication failed. > > > > > I am positive that the username and paddword are correct. ! > > > > I believe paramiko supports only ssh2, so be sure to check if your > > server is not running ssh1. > > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > > -- > > -- Guilherme H. Polo Goncalves > > > The server is running SSH2. > Can you think of any other ideas to troubleshoot ? > > -- > http://mail.python.org/mailman/listinfo/python-list > Take a look at ssh server log would be my next idea. -- -- Guilherme H. Polo Goncalves From bj_666 at gmx.net Tue Jan 22 05:04:54 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Jan 2008 10:04:54 GMT Subject: Question on sort() key function References: <5vlopgF1mv4ekU1@mid.dfncis.de> <7xve5mfdmr.fsf@ruckus.brouhaha.com> <5vlqbjF1kl9cjU1@mid.dfncis.de> <5vlsv7F1n3d1bU1@mid.dfncis.de> Message-ID: <5vlte5F1n19plU3@mid.uni-berlin.de> On Tue, 22 Jan 2008 09:56:55 +0000, Robert Latest wrote: > Peter Otten wrote: >> Robert Latest wrote: >> >> This should work then: >> >> def date_key(f): >> return f.mod_date.toordinal() >> flist.sort(key=date_key) >> >> This can also be written as >> >> flist.sort(key=lambda f: f.mod_date.toordinal()) > > Well, that's almost Paul's (non-working) suggestion above, but it works > because of the parentheses after toordinal. Beats me how both versions can > be valid, anyway. > > To me it's all greek. I grew up with C function pointers, and they > always work. > > robert Suppose `func` is a C function pointer, then foo = func; and foo = func(); have different meanings. It's just the same in Python. First is the function itself, second *calls* the function. Ciao, Marc 'BlackJack' Rintsch From cokofreedom at gmail.com Thu Jan 17 07:35:18 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 17 Jan 2008 04:35:18 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: On Jan 17, 1:21 pm, Sacred Heart wrote: > Hi, > I'm new to Python and have come across a problem I don't know how to > solve, enter com.lang.python :) > > I'm writing some small apps to learn the language, and I like it a lot > so far. > > My problem I've stumbled upon is that I don't know how to do what I > want. I want to do a loop in a loop. I think. > > I've got two arrays with some random stuff in, like this. > > array1 = ['one','two','three','four'] > array2 = ['a','b','c','d'] > > I want to loop through array1 and add elements from array2 at the end, > so it looks like this: > > one a > two b > three c > four c > > I'm stuck. I know how to loop through the arrays separatly and print > them, but both at the same time? Hmmm. > > A push in the right direction, anyone? > > R, > SH for i in zip(array1, array2): print i Although I take it you meant four d, the issue with this method is that once you hit the end of one array the rest of the other one is ignored. From ivanlan9 at gmail.com Thu Jan 24 18:58:05 2008 From: ivanlan9 at gmail.com (Ivan Van Laningham) Date: Thu, 24 Jan 2008 16:58:05 -0700 Subject: Problem with Tkinter scrollbar callback In-Reply-To: References: Message-ID: Hi All-- That helps. Doing a get() on the scrollbar before a set(0.0,0.0) returns a 4-tuple: (0.0, 0.0, 0.0, 0.0) ! I did the set(0.0,0.0) and now the callback gets the correct number of arguments. However, I'm still getting the weird behaviour when clicking the arrowheads--and the heads are all I want. They act like they've been set to a keybounce timeout of about a millisecond. ... The arrow click increments the number of cells in a table row (effectively), and it shoots up from 5 to 26 columns almost instantly (that's the internal max I set). Metta, Ivan On Jan 24, 2008 4:27 PM, Russell E. Owen wrote: > In article , > > "Ivan Van Laningham" wrote: > > > Hi All-- > > I'm having two problems with the scrollbar callback on linux systems > > (Fedora 7, Suse 10.1,2 and 3 all exhibit the issues). > > > > Problem one: on Windows, the callback is called with the arguments as > > specified in the doc: "scroll", "1" or "-1", "units". When I run the > > identical code on linux, the callback is invoked with only one > > argument, "1" or "-1". Here's a small program which demos the > > problem: > > > > ========begin============ > > #!/usr/bin/env python > > > > from Tkinter import * > > import sys > > > > def die(event): > > sys.exit(0) > > def sDoit(*args): > > for i in args: > > print "scrollbar:",i, type(i) > > root=Tk() > > f=Frame(root) > > f.pack(expand=1,fill=BOTH) > > button=Button(f,width=25) > > button["text"]="Quit" > > button.bind("
this is in a table, woo-hoo!
> > more HTML > blah blah blah... > """ > > # define pyparsing expressions for XML tags > rowStart,rowEnd = makeXMLTags("Row") > relationshipStart,relationshipEnd = makeXMLTags("Relationship") > priorityStart,priorityEnd = makeXMLTags("Priority") > startDateStart,startDateEnd = makeXMLTags("StartDate") > stopsExistStart,stopsExistEnd = makeXMLTags("StopsExist") > nameStart,nameEnd = makeXMLTags("Name") > addressStart,addressEnd = makeXMLTags("Address") > > # define some useful expressions for data of specific types > integer = Word(nums) > date = Combine(Word(nums,exact=2)+"/"+ > Word(nums,exact=2)+"/"+Word(nums,exact=4)) > yesOrNo = oneOf("Yes No") > > # conversion parse actions > integer.setParseAction(lambda t: int(t[0])) > yesOrNo.setParseAction(lambda t: t[0]=='Yes') > # could also define a conversion for date if you really wanted to > > # define format of a , plus assign results names for each data > field > rowRec = rowStart + \ > relationshipStart + SkipTo(relationshipEnd)("relationship") + > relationshipEnd + \ > priorityStart + integer("priority") + priorityEnd + \ > startDateStart + date("startdate") + startDateEnd + \ > stopsExistStart + yesOrNo("stopsexist") + stopsExistEnd + \ > nameStart + SkipTo(nameEnd)("name") + nameEnd + \ > addressStart + SkipTo(addressEnd)("address") + addressEnd + \ > rowEnd > > # set filtering parse action > rowRec.setParseAction(withAttribute(relationship="Owner",priority=1)) > > # find all matching rows, matching grammar and filtering parse action > rows = rowRec.searchString(htmlWithEmbeddedXml) > > # print the results (uncomment r.dump() statement to see full > # result for each row) > for r in rows: > # print r.dump() > print r.relationship > print r.priority > print r.startdate > print r.stopsexist > print r.name > print r.address > > This prints: > Owner > 1 > 07/16/2007 > False > Doe, John > 1905 S 3rd Ave , Hicksville IA 99999 > > In addition to parsing this data, some conversions were done at parse > time, too - "1" was converted to the value 1, and "No" was converted > to False. These were done by the conversion parse actions. The > filtering just for Row's containing Relationship="Owner" and > Priority=1 was done in a more global parse action, called > withAttribute. If you comment this line out, you will see that both > rows get retrieved. > > -- Paul > (Find out more about pyparsing athttp://pyparsing.wikispaces.com.) I've heard of this module, but never used it. Your code runs almost out of the box on my file and returns the correct result. That's pretty cool! It looks like the wiki you linked to has quite a few pieces of example code. I'll have to look this over. While I like lxml's very Object Oriented way of doing things, I tend to get overwhelmed by their tutorials for some reason. One more example of all those college OOP classes being a waste of money... Thank you for the help. Mike From mobiledreamers at gmail.com Tue Jan 8 20:02:28 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Tue, 8 Jan 2008 17:02:28 -0800 Subject: Pyflakes pre-commit hook in subversion Message-ID: http://tarekziade.wordpress.com/2006/11/01/protecting-a-python-svn-code-base-with-the-pre-commit-hook/ Is it possible to check code in python before committing to svn using pyflakes, pythontidy *Pyflakes and Subversion* Pyflakes is a nice little utility that checks your Python code for errors. The main advantage over PyChecker and PyLint is that it is much faster and gives almost no false positives. Today I wrote a little hack on top of the enforcerpre-commit script which forces the code you check in to pass pyflakes. Eg, the users of svn will see the following output if they try to check in code which has errors pyflakes can detect: $ svn ci -m "fix" completion.py Sending completion.py Transmitting file data .svn: Commit failed (details follow): svn: 'pre-commit' hook failed with error output: Pyflakes found 1 error(s)/warning(s): kiwi/trunk/examples/completion.py:1: undefined name 'test' The small "configuration" file for enforce can be found here. Can you share enforcer file? or a means to ensure safe code in python repo -------------- next part -------------- An HTML attachment was scrubbed... URL: From meesters at uni-mainz.de Tue Jan 29 07:48:31 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Tue, 29 Jan 2008 13:48:31 +0100 Subject: extending Python - passing nested lists References: Message-ID: Think, that I'm still at the wrong track. Point is that I cannot find any examples and don't know where to start here. Perhaps my problem boils down to two questions: I'd like to pass lists (in some cases nested ones) from Python to C and convert those Python-lists to C-arrays (e. g. of doubles). My second wish is to return a C-array of longs to a Python list. My approach so far: static PyObject *_foo(PyObject *self, PyObject *args) { double *v; if (!PyArg_Parse(args, "(d)", &v)) return NULL; // then I can't access v like v[1] ... // then return *v return with something like PyBuildValue (but didn't get so far) } Can somebody give me a hint here, please? Passing simple arguments to and fro (e. g. single integer values) is no problem, but lists of unknown size? TIA Christian From mwm-keyword-python.b4bdba at mired.org Fri Jan 11 17:37:30 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 17:37:30 -0500 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <20080111173730.3cd3a8b2@bhuda.mired.org> On Fri, 11 Jan 2008 22:18:22 GMT Neil Hodgson wrote: > Marty: > > I recently faced a similar issue doing something like this: > > data_out = [] > > for i in range(len(data_in)): > > data_out.append([]) > > Another way to write this is > data_out = [[]] * len(data_in) Not quite. All the other variants give you 23 empty lists. That one gives you 23 references to one list: >>> x = [[] for _ in range(23)] >>> x[1].append(23) >>> x [[], [23], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []] >>> x = [[]] * 23 >>> x[1].append(23) >>> x [[23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23]] http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From grflanagan at yahoo.co.uk Thu Jan 31 10:34:00 2008 From: grflanagan at yahoo.co.uk (grflanagan) Date: Thu, 31 Jan 2008 07:34:00 -0800 (PST) Subject: Python noob SOS (any [former?] Perlheads out there?) References: <6099ab30-390d-4b38-bc8e-81ecb52e03a6@e25g2000prg.googlegroups.com> Message-ID: <27f530a0-c955-43d7-93db-d907a1167d77@i29g2000prf.googlegroups.com> On Jan 31, 2:56 pm, "A.T.Hofkamp" wrote: > On 2008-01-30, grflanagan wrote: > > > > > On Jan 29, 5:39 pm, kj wrote: > > For command line options I get a long way with this: > > > [code python] > > def _getargs(): > > allargs = sys.argv[1:] > > args = [] > > kwargs = {} > > key = None > > while allargs: > > arg = allargs.pop(0) > > if arg.startswith('--'): > > key, arg = arg.split('=', 1) > > key = key[2:] > > elif arg.startswith('-'): > > key = arg[1:] > > if not allargs or allargs[0].startswith('-'): > > allargs.insert(0, 'yes') > > continue > > if key is None: > > args.append(arg) > > else: > > kwargs[key] = arg > > key = None > > return args, kwargs > > > ARGS, KWARGS = _getargs() > > [/code] > > Have a look at getopt (old) or optparse (newer) packages in the Python library > instead. > > Sincerely, > Albert Admittedly I haven't used either of them, but getopt and optparse have always looked like too much work to me. 90% of the time my '_getargs' does what I need, and when it's insufficient I go straight to a config file (ConfigParser or ConfigObj). Best Regards Gerard From steve at REMOVE-THIS-cybersource.com.au Fri Jan 18 17:39:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 18 Jan 2008 22:39:08 -0000 Subject: Is this a bug, or is it me? References: <87myr4o3sg.fsf@mulj.homelinux.net> <8afa3779-6803-43ed-ae4d-d0a102eda00d@x69g2000hsx.googlegroups.com> Message-ID: <13p2akcm9kmarce@corp.supernews.com> On Fri, 18 Jan 2008 11:01:29 -0800, cptnwillard wrote: > Now here is another one for your enjoyment: > > class C: > @staticmethod > def f1(): pass > F = { '1' : f1 } > > C().F['1']() > >>>> TypeError: 'staticmethod' object is not callable > > > What do you think of this one? The trick is to realise that the object stored in the dict is not the same object that you get back when you call C.f1(). >>> C().f1 is C().F['1'] False >>> C().f1 >>> C().F['1'] What you've done in inadvertently bypassed Python's method-access mechanism: >>> C.__dict__['f1'] is C().f1 False >>> C.__dict__['f1'] is C().F['1'] True Analogous results will occur without the decorator (although the error you get is different): >>> class D: ... def foo(self): pass ... F = {'oo': foo} ... >>> D().foo() >>> D.F['oo']() Traceback (most recent call last): File "", line 1, in TypeError: foo() takes exactly 1 argument (0 given) So... not a bug, a feature :) -- Steven From martin at v.loewis.de Thu Jan 3 16:47:22 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 03 Jan 2008 22:47:22 +0100 Subject: New-style objects are not instances, apparently In-Reply-To: <3c386519-8de3-4e50-8b96-e4c5f3cc8e78@d21g2000prf.googlegroups.com> References: <3c386519-8de3-4e50-8b96-e4c5f3cc8e78@d21g2000prf.googlegroups.com> Message-ID: <477D57EA.3040208@v.loewis.de> > Further experimentation showed that derivation from object was the > culprit; new-style objects are not considered "instances" in the above > sense. I wasn't able to figure out a workaround. Is there one, or is > the distinction between traditional classes and built-in types only > going to get more and more hazy? In the long run (ie. Python 3), the distinction is going to be very hazy, very dark: it will entirely disappear. There will be only one concept of type/class, not two, so there will be no point distinguishing between types and classes. Regards, Martin From max at alcyone.com Wed Jan 2 14:28:12 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 02 Jan 2008 11:28:12 -0800 Subject: os.tmpfile() In-Reply-To: References: Message-ID: jyoung79 at kc.rr.com wrote: > Erik, I am going to be displaying sections of text in the Terminal Window on OS X. > I wanted to format the text in a specific way and thought it might be quicker to > output all the text to a temporary file that I could quickly read sections from instead > of storing in memory. Not sure if this is the most efficient way to do this or not but > thought at least it'd be a good way to learn something new in Python. I was > assuming tmpfile() would automatically create some sort of temporary file that > would automatically delete itself when the code was finished. It is more likely that keeping it in a list will be more efficient, and easier to handle anyway. -- 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 When angry, count four; when very angry, swear. -- Mark Twain From Rens.Duijsens at gmail.com Sat Jan 26 07:23:36 2008 From: Rens.Duijsens at gmail.com (Dox33) Date: Sat, 26 Jan 2008 04:23:36 -0800 (PST) Subject: raw_input(), STRANGE behaviour Message-ID: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> I ran into a very strange behaviour of raw_input(). I hope somebody can tell me how to fix this. (Or is this a problem in the python source?) I will explain the problem by using 3 examples. (Sorry, long email) The first two examples are behaving normal, the thirth is strange....... I wrote the following flabbergasting code: #------------------------------------------------------------- print "1: This is the print statement." # Now halt the program until someone hits enter raw_input("2: This is the raw_input prompt.") import sys print "3: This is a possible solution. ", sys.stdout.flush() command = sys.stdin.readline() #------------------------------------------------------------- and saved it in the file 'script.py'. *** First, normal behaviour to stdout Now, I open a command line and run the following command: python script.py On screen appears, after a few 'enter' keys: 1: This is the print statement. 2: This is the raw_input prompt. 3: This is a possible solution. All works fine...... *** Second, redirected stdout to file, normal behaviour. >From the command prompt I run: python script.py > stdout_catch.txt The screen stays empty, and after a few 'enter' keys the prompt reapears. In the file 'stdout_catch.txt' are the lines: 1: This is the print statement. 2: This is the raw_input prompt. 3: This is a possible solution. And again, all works fine...... *** Thirst, redirect stderr to file, STRANGE behaviour...... >From the command prompt I run: python script.py 2> stderr_catch.txt This should redirect strerr to the file and stdout should stay on the screen. But..... What happens? After a few 'enter' keys, on screen apears: 1: This is the print statement. 3: This is a possible solution. WHERE IS THE SECOND LINE? It is in the file stderr_catch.txt!!! **** See the problem? Please Tell me? Why is the prompt produced by raw_input() printed to the error channel? It should be stdout, just as the print statement does. Looking at the python source code on http://svn.python.org/view/python/tags/r251/Python/bltinmodule.c?rev=54864&view=auto [found: 'builtin_raw_input(PyObject *self, PyObject *args)']. One thing that I notice is that the code checks whether stdin and stdout are connected to a terminal ("isatty" function), but I do not know why the prompt ends up on stderr then..... **** What is the solution? I have noticed this behaviour under DOS in Windows XP, Windows 2000, Windows 2003 Server, Windows vista, and Linux. How do I get raw_input() to send it's prompt to stdout? Friendly greetings Rens From mail at timgolden.me.uk Fri Jan 25 08:11:12 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 25 Jan 2008 13:11:12 +0000 Subject: Windows AVIFile problems In-Reply-To: References: Message-ID: <4799DFF0.1070007@timgolden.me.uk> c d saunter wrote: > I'm trying to access individual video frames of an AVI file from within > Python 2.4 or 2.5 under Windows XP. I thought that the recently-at-1.0 pyglet did that, only I can't now see it in their docs anywhere. Might be worth asking over there anyway [1] since it certainly comes close, is a much easier way of dealing with video images, and seems to have an active community. TJG [1] http://www.pyglet.org/ From lists at cheimes.de Wed Jan 16 02:11:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 16 Jan 2008 08:11:05 +0100 Subject: no pass-values calling? In-Reply-To: <873asyclo0.fsf@benfinney.id.au> References: <13or6esikdrqa33@corp.supernews.com> <873asyclo0.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > The term "reference" is fine, since that's exactly how it works. One > gets at an object via some reference, be it a name or some access into > a container object. When an object has no more references to itself, > it becomes a candidate for garbage collection. And so on. Thanks you, but I know exactly how Python works. I'm actually developing CPython and PythonDotNET. While your description of Python's memory management is technically, it's just an implementation detail of the CPython implementation. Jython and IronPython are using different approaches for GC. Anyway your message doesn't help a newbie and it gives most certainly the wrong impression. You are using words that have a different meaning in other languages. If you explain Python w/o the words variable, pointer, reference or call-by-value you have a much better chance to explain it right. Trust me :) Christian From charles_hans at yahoo.com Wed Jan 30 13:54:47 2008 From: charles_hans at yahoo.com (Charles_hans) Date: Wed, 30 Jan 2008 10:54:47 -0800 (PST) Subject: Q: paramiko/SSH/ how to get a remote host_key In-Reply-To: References: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> <9077ed27-e9b1-47ca-b30e-918e3b50d517@e4g2000hsg.googlegroups.com> Message-ID: <15189222.post@talk.nabble.com> I tried to get what host_key has been aquired after AutoPolicy is set. I added the following code just before client.close() in rosty's final code: try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print '*** Unable to open host keys file' I still got 'Unable to open host keys file'. Can you tell me how to get the remote host_key under this situation? Thanks! Charles 1/30/2008 by Guilherme Polo Jan 21, 2008; 09:08am : 2008/1/21, DHR : Very nice =) Just an advice, you dont need to import base64. Method decode of strings allows you to specify encoding as 'base64' to perform needed operations. by rosty Jan 21, 2008; 08:43am : Thank you! Now it works and the code looks like this: import paramiko import base64 from paramiko import AutoAddPolicy, SSHClient client = paramiko.SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect('hostIP', username='uname', password='pass') stdin, stdout, stderr = client.exec_command('ls') for line in stdout: print '... ' + line.strip('\n') client.close() -- View this message in context: http://www.nabble.com/Q%3A-paramiko-SSH--how-to-get-a-remote-host_key-tp14996119p15189222.html Sent from the Python - python-list mailing list archive at Nabble.com. From hniksic at xemacs.org Mon Jan 28 15:35:23 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 28 Jan 2008 21:35:23 +0100 Subject: post variable References: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> Message-ID: <87ir1dr8ms.fsf@mulj.homelinux.net> "pavloutefkros at gmail.com" writes: > so the output is always the POST retrieven at first. So the page > keeps on printing the POST variable retrieven at first even thought > i might have reloaded the page 1000 times. Is there any way to > "empty" the POST variable, so that at reload nothing would be the > same? Have test.py send a redirect to another page (or to itself, sans the params). Then reloading won't resend the POST params. From mccredie at gmail.com Fri Jan 18 16:12:49 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 18 Jan 2008 13:12:49 -0800 (PST) Subject: Bit Scan Forward and Reverse References: Message-ID: <4d0fa8e1-9fed-469d-9a70-ff07c8a88a79@t1g2000pra.googlegroups.com> On Jan 18, 12:01 pm, Thomas Dybdahl Ahle wrote: > Hi, I'm writing an app in python, and I'm storing some a lot of data in > bitmaps. > I need a way to find the first or latest set bit in a 64bit number, and > for that I've implemented a small routine. > > Thing is that this routine is not as fast as I'd wish. I know most > processors implement BSF and BSR calls to do this efficiently. > Is there anyway to access those calls from python? > > I'd still have my routine as a fallback on nonsupporting architectures. > > -- > Med venlig hilsen, > Best regards, > Thomas There isn't a simple way, but you have a couple of options: 1. put the code in a dll and call it from ctypes. 2. see extending and embedding in the documentation. Matt From socyl at 987jk.com.invalid Wed Jan 30 07:31:05 2008 From: socyl at 987jk.com.invalid (kj) Date: Wed, 30 Jan 2008 12:31:05 +0000 (UTC) Subject: Python noob SOS (any [former?] Perlheads out there?) References: Message-ID: In "Reedick, Andrew" writes: >> Be that as it may, the activation barrier to using Python for my >> scripting remains too high. >>=20 >> I'd written a Perl module to facilitate the writing of scripts. >> It contained all my boilerplate code for parsing and validating >> command-line options, generating of accessor functions for these >> options, printing of the help message and of the full documentation, >> testing, etc. >Bleh. Perl and Python have really good libraries. Why waste time >rolling your own when you can use Python's getopt or optparse, or Perl's >Getopt and Getopt::Long? No, no "bleh". My module in fact uses Getopt::Long behind the scenes, but customizes the heck out of it and adds a ton of functionality I wanted not available in Getopt::Long. kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From steven at REMOVE.THIS.cybersource.com.au Thu Jan 3 21:56:17 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 04 Jan 2008 02:56:17 -0000 Subject: problem with global var References: Message-ID: On Thu, 03 Jan 2008 11:38:48 -0300, Bruno Ferreira wrote: > Hi, > > I wrote a very simple python program to generate a sorted list of lines > from a squid access log file. > > Here is a simplified version: > > ################################## > 1 logfile = open ("squid_access.log", "r") > 2 topsquid = [["0", "0", "0", "0", "0", "0", "0"]] [snip] Others have already solved the immediate problem, but a much better design would be to avoid using a global variable in the first place. def add_sorted(alist, data): """Add figures from alist to collated data and return data.""" # do your processing here... return data topsquid=[["0", "0", "0", "0", "0", "0", "0"]] for line in logfile: linefields = logline.split() topsquid = add_sorted(linefields, topsquid) -- Steven From huisan.wang at gmail.com Wed Jan 2 20:15:06 2008 From: huisan.wang at gmail.com (huisan.wang at gmail.com) Date: Wed, 2 Jan 2008 17:15:06 -0800 (PST) Subject: A problem of twisted and dbus Message-ID: <87a3d1aa-f4e0-4cc0-a606-0cdaa172d5ef@e6g2000prf.googlegroups.com> Hello everyone, I am writing a program with twisted and dbus and got a such problem. If i run the code as $python local_proxy.py There is an error like this: Traceback (most recent call last): File "local_proxy.py", line 608, in reactor.listenTCP(143, factory) File "/usr/lib/python2.5/site-packages/twisted/internet/ posixbase.py", line 467, in listenTCP p.startListening() File "/usr/lib/python2.5/site-packages/twisted/internet/tcp.py", line 733, in startListening raise CannotListenError, (self.interface, self.port, le) twisted.internet.error.CannotListenError: Couldn't listen on any:143: (13, 'Permission denied'). So I tried to run the program as $sudo python local_proxy.py I got another error: Traceback (most recent call last): File "local_proxy.py", line 625, in session_bus = dbus.SessionBus() File "/var/lib/python-support/python2.5/dbus/_dbus.py", line 218, in __new__ mainloop=mainloop) File "/var/lib/python-support/python2.5/dbus/_dbus.py", line 107, in __new__ bus = BusConnection.__new__(subclass, bus_type, mainloop=mainloop) File "/var/lib/python-support/python2.5/dbus/bus.py", line 121, in __new__ bus = cls._new_for_bus(address_or_type, mainloop=mainloop) dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NoReply: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken. $sudo python local_porxy.py worked fine before I added the dbus into the program. And dbus has no problem for my other programs. How can I figure out this problem? Any helps will be appreciated. -Huisan From f.guerrieri at gmail.com Tue Jan 8 12:34:39 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Tue, 8 Jan 2008 18:34:39 +0100 Subject: copy a numpy array In-Reply-To: References: Message-ID: <79b79e730801080934x6f2403d2mc48ac0c1ca58680e@mail.gmail.com> On Jan 8, 2008 4:32 PM, jimgardener wrote: > hi, > (i posted this to numpy discussion grp couple of days back ..but it > fails to appear..)since it is needed for my work i would appreciate if > anyone can help me with this question > > > i have two ndarrays of 1000 elements each and want to copy all > elements from srcarray to destarray > > srcarray=numpy.array( [3973334.8381791776,........,382999.6748692277] ) > > arrsize=1000 > destarray=zeros(arrsize) > > i copied all items from src to dest by using > destarray[0:arrsize]=srcarray[0:arrsize] > > i don't know if this is the right way to do the copying. > is there a better(efficient?) way ? > jim If you want the array to share the data, just use destarray = numpy.array(srcarray) Otherwise you can set the copy flag to False: destarray = numpy.array(srcarray,copy=False) bye, Francesco From mr.cerutti at gmail.com Wed Jan 30 08:04:18 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 30 Jan 2008 08:04:18 -0500 Subject: Removal of element from list while traversing causes the next element to be skipped In-Reply-To: <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> Message-ID: <51302a8c0801300504i30c02ea3jfbf3228a62532720@mail.gmail.com> On Jan 30, 2008 6:57 AM, Arnaud Delobelle wrote: > Or one could use the trick of counting from the right (untested): > > n = len(a) > for i, x in enumerate(a): > if x == 99: del a[i-n] Or one can put on his bellbottoms, horn-rimmed glasses, and wear a mullet: i = 0 while i < len(a): if a[i] == 99: del a[i] else: i += 1 -- Neil Cerutti From sjmachin at lexicon.net Sun Jan 27 06:20:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 27 Jan 2008 03:20:36 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> Message-ID: On Jan 27, 9:17 pm, glacier wrote: > On 1?24?, ??3?29?, "Gabriel Genellina" wrote: > > > > > En Thu, 24 Jan 2008 04:52:22 -0200, glacier escribi?: > > > > According to your reply, what will happen if I try to decode a long > > > string seperately. > > > I mean: > > > ###################################### > > > a='???'*100000 > > > s1 = u'' > > > cur = 0 > > > while cur < len(a): > > > d = min(len(a)-i,1023) > > > s1 += a[cur:cur+d].decode('mbcs') > > > cur += d > > > ###################################### > > > > May the code above produce any bogus characters in s1? > > > Don't do that. You might be splitting the input string at a point that is > > not a character boundary. You won't get bogus output, decode will raise a > > UnicodeDecodeError instead. > > You can control how errors are handled, see http://docs.python.org/lib/string-methods.html#l2h-237 > > > -- > > Gabriel Genellina > > Thanks Gabriel, > > I guess I understand what will happen if I didn't split the string at > the character's boundry. > I'm not sure if the decode method will miss split the boundry. > Can you tell me then ? > > Thanks a lot. *IF* the file is well-formed GBK, then the codec will not mess up when decoding it to Unicode. The usual cause of mess is a combination of a human and a text editor :-) From peter.maas at somewhere.com Sat Jan 5 15:42:38 2008 From: peter.maas at somewhere.com (Peter Maas) Date: Sat, 05 Jan 2008 21:42:38 +0100 Subject: python interfaces In-Reply-To: References: Message-ID: Sion Arrowsmith wrote: > hyperboreean wrote: >> Why doesn't python provide interfaces trough its standard library? > > Because they're pointless. Wrong. I'm using Eclipse with the Java Development Tools (JDT) who do a wonderful job using interfaces to perform lots of checking, warning and code generation *nearly in real time while I am editing my code*. Because JDT knows interfaces it knows what to do and to suggest. > Java interfaces are a hack around the complexities of multiple > inheritence. A hack is something applied subsequently to solve a software problem while avoiding large changes. Java interfaces originate from careful language design. You are free to dislike Java interfaces but calling them a hack is just plain wrong. Once software becomes really big interfaces are very useful to handle complexity. Ever wondered why the Zope people introduced interfaces in their Python code? > Interfaces used purely with the idea of type safety provide > precious little gain for the added clutter and inconvenience. An interface is a software specification allowing you to use a software package without extensive code studies. This is a good thing. Interfaces have nothing to do with multiple inheritance and are not about type safety in the first place. They just tell you how to connect, how to plug in. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From caca at mailinator.com Sat Jan 5 11:07:35 2008 From: caca at mailinator.com (caca at mailinator.com) Date: Sat, 5 Jan 2008 08:07:35 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> Message-ID: <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> Hello, Paul and Arnaud. While I think about your answers: do you think there is any way to avoid shuffle? It may take unnecessary long on a long list most of whose elements have the property. From fredrik at pythonware.com Fri Jan 11 13:34:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jan 2008 19:34:35 +0100 Subject: Converting a bidimensional list in a bidimensional array In-Reply-To: <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> <005679e9-c355-4e0a-872c-e0dae3181fd0@x69g2000hsx.googlegroups.com> <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> Message-ID: Santiago Romero wrote: > My problem is that, in my game, each screen is 30x20, and I have > about 100 screens, so my tilemap contains 32*20*100 = 60000 python > objects (integers). > > If each integer-python-object takes 16 bytes, this makes 60000 * 16 = > almost 1MB of memory just for the tilemaps... or more likely, 240k for pointers to a few distinct integer objects, each of which occupies 16 bytes. if you're really running this on a machine with only a few megabytes free memory, maybe you could compress the screens you're not working with? zlib.compress(cPickle.dumps(screen)) should compress each 640-item list to say, 50 to 500 bytes, depending on the contents. From deets at nospam.web.de Wed Jan 16 13:33:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jan 2008 19:33:09 +0100 Subject: Interesting Thread Gotcha In-Reply-To: <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> Message-ID: <5v70v9F1kmtinU1@mid.uni-berlin.de> Dan schrieb: > On Jan 16, 11:06 am, "Diez B. Roggisch" wrote: >> Hendrik van Rooyen wrote: >>> "Dan" wrote: >>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) >>>> Needs to be >>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) >>>> Commas are important! >>>> -Dan >>> Absolutely! - well spotted! >>> As the first correct respondent, you win the freedom to spend a week in >>> Naboomspruit at your own expense. >>> It would have been nice, however, to have gotten something like: >>> TypeError - This routine needs a tuple. >>> instead of the silent in line calling of the routine in question, >>> while failing actually to start a new thread. >> You can't prevent the silent inline-calling - otherwise, how would you do >> this: >> >> def compute_thread_target(): >> def target(): >> pass >> return target >> >> thread.start_new_thread(compute_thread_target()) >> >> Of course start_new_thread could throw an error if it got nothing callable >> as first argument. No idea why it doesn't. >> >> Diez > > Of course, in his case, having start_new_thread throw an error > wouldn't have helped, since he went into an infinite loop while > evaluating the parameters for start_new_thread. > > Would it be possible to have pychecker (or some such) warn that there > is an insufficient parameter count to start_new_thread? I guess that > would require knowing the type of thread. . . What has this to do with the second argument? It's perfectly legal to have a function as thread-target that takes no arguments at all, so enforcing a second argument wouldn't be helpful - all it would do is to force all developers that don't need an argument tuple to pass the empty tuple. So there was no insufficient argument count. And none of these would solve the underlying problem that in python expressions are evaluated eagerly. Changing that would mean that you end up with a totally new language. the only thing that could help to a certain extend would be static types. Which we don't want here :) Diez From asmodai at in-nomine.org Tue Jan 8 03:55:28 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 09:55:28 +0100 Subject: Look for a string on a file and get its line number In-Reply-To: <9889cbd0-c19e-4b76-8c41-aa621a188661@e4g2000hsg.googlegroups.com> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <9889cbd0-c19e-4b76-8c41-aa621a188661@e4g2000hsg.googlegroups.com> Message-ID: <20080108085528.GF75977@nexus.in-nomine.org> -On [20080108 09:51], John Machin (sjmachin at lexicon.net) wrote: >Make that >= Right you are. Sorry, was doing it quickly from work. ;) And I guess the find will also be less precise if the word you are looking is a smaller part of a bigger word. E.g. find 'door' in a line that has 'doorway' in it. So 't is merely for inspiration. ;) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ >From morning to night I stayed out of sight / Didn't recognise I'd become No more than alive I'd barely survive / In a word, overrun... From DustanGroups at gmail.com Fri Jan 18 18:44:42 2008 From: DustanGroups at gmail.com (Dustan) Date: Fri, 18 Jan 2008 15:44:42 -0800 (PST) Subject: strange syntax rules on list comprehension conditions References: Message-ID: On Jan 18, 1:04 pm, "Chris Mellon" wrote: > On Jan 18, 2008 12:53 PM, Nicholas wrote: > > > I was quite delighted today, after extensive searches yielded nothing, to > > discover how to place an else condition in a list comprehension. > > Trivial mask example: > > >>> [True if i <5 else False for i in range(10)] # A > > [True, True, True, True, True, False, False, False, False, False] > > > I then experimented to drop the else statement which yields an error > > >>> [i if i>3 for i in range(10)] That would be: [i for i in range(10) if i>3] > > Traceback ( File "", line 1 > > this syntax works of course > > >>> [i if i>3 else i for i in range(10)] > > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] From martin at v.loewis.de Wed Jan 23 04:25:30 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Jan 2008 10:25:30 +0100 Subject: python2.4-dbg and C modules In-Reply-To: References: Message-ID: <4797080a$0$11374$9b622d9e@news.freenet.de> > please, when I try to run my code under python2.4-dbg > from Ubuntu, the interpreter complains that the Py_InitModule4 > symbol is undefined in a C module I'm using (PyOpenAL): > > ImportError: /var/lib/python-support/python2.4/_openal.so: undefined > symbol: Py_InitModule4 > > Google reveals that this problem is not specific just to PyOpenAL, > but I couldn't find out what is the essence of the problem and how > python-2.4dbg is different from python2.4 except for including > debugging symbols, because in plain python2.4 the module works > fine. The dbg version does not define Py_InitModule4, but Py_InitModule4TraceRefs. This is a safety-measure to prevent modules compiled for the nodebug version of Python to load into the debug version. There are major changes to the internal interpreter data structures in the debug version, so you have to recompile your module with the debug headers. HTH, Martin From hexamorph at gmx.net Fri Jan 25 15:52:24 2008 From: hexamorph at gmx.net (Hexamorph) Date: Fri, 25 Jan 2008 21:52:24 +0100 Subject: Operator overloading In-Reply-To: References: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com> <5vuob3F1nd2bhU1@mid.uni-berlin.de> <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> Message-ID: <479A4C08.3050400@gmx.net> MartinRinehart at gmail.com wrote: > > Hexamorph wrote: >> You mean you want the ability to change for example the + operator >> for ints to something like calculating the cosine instead of doing >> addition? > > Sure. Cosines are a monadic operation and the monadic '+' is a NOP, so > why shouldn't I define +45 to return cosine of 45, (presuming I needed > lots of cosines). I'd even let you define your own operators. Lots of > programmers really liked '++' and '--', for examples. Well, OK, the cosine example was badly chosen (it would still be very wired in terms of common syntax and semantics), but I think you got my point. Changing internal behaviour mostly causes more trouble as it's worth. In the end, you probably can access the parser to do this. From mrmakent at cox.net Sat Jan 26 10:50:15 2008 From: mrmakent at cox.net (Mike Kent) Date: Sat, 26 Jan 2008 07:50:15 -0800 (PST) Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> Message-ID: <87dd811e-3095-41d0-80fd-7312338e5254@i3g2000hsf.googlegroups.com> On Jan 26, 7:23 am, Dox33 wrote: > I ran into a very strange behaviour of raw_input(). > I hope somebody can tell me how to fix this. ===CUT=== > *** Thirst, redirect stderr to file, STRANGE behaviour...... > From the command prompt I run: > python script.py 2> stderr_catch.txt > This should redirect strerr to the file and stdout should stay on the > screen. > > But..... What happens? > After a few 'enter' keys, on screen apears: > 1: This is the print statement. > 3: This is a possible solution. > > WHERE IS THE SECOND LINE? > It is in the file stderr_catch.txt!!! > > **** See the problem? > Please Tell me? Why is the prompt produced by raw_input() printed to > the error channel? It should be stdout, just as the print statement > does. I recently ran into this behaviour myself, and reported it both here and to the python-dev mailing list. See http://groups.google.com/group/comp.lang.python/browse_thread/thread/1011238ac6b79292/6f8b7c47873a4a1e?lnk=gst&q=unexpected+behavior#6f8b7c47873a4a1e It turns out that *if* you don't have GNU readline installed, Python falls back to its own implementation of readline, which is hard-coded to send the prompt output to stderr. Guido agreed that this is wrong, and a bug for it has been entered into the Python bug tracking database. Your workaround until this bug is fixed is to install GNU readline, and rebuild your python installation to use it rather than the fall- back version. From steven at REMOVE.THIS.cybersource.com.au Wed Jan 16 23:20:14 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 17 Jan 2008 04:20:14 -0000 Subject: assigning values in python and perl References: <18c1e5f20801161934m69ff44edo1e35f5381f7d2928@mail.gmail.com> Message-ID: On Thu, 17 Jan 2008 11:40:59 +0800, J. Peng wrote: > May I ask, python's pass-by-reference is passing the object's reference > to functions, but perl, or C's pass-by-reference is passing the variable > itself's reference to functions. So althought they're all called > pass-by-reference,but will get different results.Is it? Python is not call by reference. Any book or person that says it is, is wrong to do so. Python's function call semantics are not the same as C, or Perl, or Pascal. They are, however, similar to those of Lisp, Scheme, Emerald and especially CLU. It is neither pass by reference, nor pass by value. Java also uses similar call-by-object (sometimes call-by-sharing) semantics, and just like Python, Java developers tie themselves in knots by using misleading names for it: http://codertricks.strainu.ro/java/2007/05/02/why-java-sends-parameters- by-value/ and http://codertricks.strainu.ro/java/2007/06/15/call-by-sharing/ Did you read the links I sent you yesterday, especially the second one? http://effbot.org/zone/python-objects.htm http://effbot.org/zone/call-by-object.htm -- Steven From hniksic at xemacs.org Wed Jan 30 08:52:47 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 30 Jan 2008 14:52:47 +0100 Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> <7xwsprxxe6.fsf@ruckus.brouhaha.com> Message-ID: <87ejbz774g.fsf@mulj.homelinux.net> Paul Rubin writes: > Quadratic time!! Yowch!! Back to the future: > > def rocket_science(xs): > for x in xs: > if x != 99: > yield x > > a[:] = list(rocket_science(a)) I call "useless use of list"! a[:] = rocket_science(a) :-) From alex at computronix.com Thu Jan 10 00:49:15 2008 From: alex at computronix.com (Alex VanderWoude) Date: Thu, 10 Jan 2008 05:49:15 GMT Subject: printing dots in simple program while waiting In-Reply-To: References: Message-ID: John wrote: > what i want to do is print a 'waiting' statement while a script is > working-- the multithreading aspect isn't an issue, the printing on > the same line is. i want to print something like: > > (1sec) working... > (2sec) working.... > (3sec) working..... > > > where the 'working' line isn't being printed each second, but the dots > are being added with time. When issuing output to stdout I have do something like this: print "working", # Note trailing comma while some_condition: do_something() print "\b.", # \b is backspace print # Finish the line of dots - Alex From grahn+nntp at snipabacken.dyndns.org Thu Jan 17 04:56:23 2008 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 17 Jan 2008 09:56:23 GMT Subject: module naming conventions References: <7f39199a-3334-4bcc-a424-5102f042ed01@1g2000hsl.googlegroups.com> <87zlv8dnya.fsf@benfinney.id.au> <6a53a14a-8f7c-4b6b-986f-48c7698f679f@v29g2000hsf.googlegroups.com> Message-ID: On Mon, 14 Jan 2008 15:58:49 -0800 (PST), grackle wrote: > On Jan 14, 4:47 pm, Ben Finney > wrote: >> I'm not sure, but it sounds as though you have yet to discover Python >> module packages . >> They allow a hierarchy of modules in directories. > > I do use packages. I mentioned the Java naming conventions because > they were my first thought for solving the problem of name clashes, > and they work well in some non-Java languages. They don't apply well > to Python, since every top-level module has a unique identity that can > only be specified on one source path. If two libraries use the same > top-level module name, they can't be used together in the same program > without modifying their source code. > > mycompany_mymodulename was just the first solution I thought of that > seemed practical. The mycompany_ prefix protects me from name clashes > with useful modules I might acquire from elsewhere. Seems to me that the Python community solves this as if you had released an executable program for Unix (where all executables end up in /usr/bin or /usr/local/bin, so they have to have unique names). In Linux, I am aware of very few name clashes. People tend to know what names are used and pick other ones. A suite of executables usually share a common prefix (like packages in Python). Some names are a bit far-fetched or silly, of course, but in practice it works reasonably well. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From loupgaroublond at gmail.com Mon Jan 7 08:33:23 2008 From: loupgaroublond at gmail.com (Yaakov Nemoy) Date: Mon, 7 Jan 2008 08:33:23 -0500 Subject: Memory Leaks and Heapy In-Reply-To: <47822129.4050500@egenix.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> <477E5A73.9070400@egenix.com> <7f692fec0801040823q14d16429y370ffceaf046a6f3@mail.gmail.com> <477E6525.3010805@egenix.com> <7f692fec0801041819r675e2137i293084baeae4954f@mail.gmail.com> <47822129.4050500@egenix.com> Message-ID: <7f692fec0801070533k5c7b3275i557a25c7d576c1c2@mail.gmail.com> On Jan 7, 2008 7:55 AM, M.-A. Lemburg wrote: > Fair enough. Just wanted to give some more details as to > where to look for things that look like leaks, but are in > fact just results of internal feature of the Python > interpreter. We have a hackfest coming up in the Fedora Community. I'll at least show some people a copy of this email, and see if we can peer debug things a bit, and maybe we'll come up with something. -Yaakov From george.sakkis at gmail.com Thu Jan 31 02:42:17 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 30 Jan 2008 23:42:17 -0800 (PST) Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> <60cai8F1qgh3aU1@mid.uni-berlin.de> <15d16017-3b43-45a8-86b9-93203972f813@u10g2000prn.googlegroups.com> <3c3d8f03-1a69-4fbe-8979-9aae458ab46c@u10g2000prn.googlegroups.com> Message-ID: On Jan 30, 9:27 pm, MRAB wrote: > On Jan 31, 1:09 am, George Sakkis wrote:> On Jan 30, 5:03 pm, Marc 'BlackJack' Rintsch wrote: > > > > On Wed, 30 Jan 2008 15:29:45 +0100, Wildemar Wildenburger wrote: > > > > Gerardo Herzig wrote: > > > >> I will use genital().extend(), thats for shure ^^ > > > > > Well, you never go wrong with apply(genital(), females), do you? > > > > `apply()` is deprecated. And ``genital(*females)`` looks a bit odd. :-) > > > Well, that use case alone is enough to convince anyone that apply > > should stay :-) > > The original had genital(), so that would be genital()(*females). But > what is genital() anyway? A factory? It actually implements several design patterns. Factory is just one of them; others include the Bridge and the Object Pool patterns. Some advanced instances of genital() may also implement the Visitor pattern while others less advanced implement primarily the Observer. George From arnodel at googlemail.com Wed Jan 23 16:56:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 13:56:27 -0800 (PST) Subject: Creating new types and invoking super References: Message-ID: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> On Jan 23, 8:55?pm, "Guilherme Polo" wrote: > Hello, Hi [...] > First I tried this: > > def init(func): > ? ? def _init(inst): > ? ? ? ? super(inst.__class__, inst).__init__() > ? ? ? ? func(inst) > > ? ? return _init > > class A(object): > ? ? @init > ? ? def __init__(self): pass This kind of approach can't work, you need to call super(A, obj). super(type(obj), obj) is pointless, it defeats the whole purpose of the mro! The only way I can think of would be to create a metaclass, but I don't think it's worth it. super(A, obj).__init__() isn't that bad! -- Arnaud From eproust at gmail.com Sun Jan 20 17:49:21 2008 From: eproust at gmail.com (pythonewbie) Date: Sun, 20 Jan 2008 14:49:21 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <4793C903.60201@v.loewis.de> Message-ID: On 20 jan, 23:19, "Martin v. L?wis" wrote: > > But for different reasons I also want to get the absolute path of > > Python install directory (not only the executable under Linux) and > > site-packages directory. > > The Python install directory is available as sys.prefix. The > site-packages directory is > sys.prefix+"lib/python"+x.y+"/site-packages (where x.y is from > sys.version_info). > > HTH, > Martin http://forum.ubuntu-fr.org/viewtopic.php?id=184199 >>> import distutils.sysconfig >>> distutils.sysconfig.get_python_lib() '/usr/lib/python2.5/site-packages' get_python_lib(plat_specific=0, standard_lib=0, prefix=None) Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure- Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. From rridge at caffeine.csclub.uwaterloo.ca Fri Jan 18 16:15:43 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 18 Jan 2008 16:15:43 -0500 Subject: Is this a bug, or is it me? References: <8afa3779-6803-43ed-ae4d-d0a102eda00d@x69g2000hsx.googlegroups.com> Message-ID: Neil Cerutti wrote: >The decoration is setting the class type's f1 attribute correctly, but >doing something strange in the local namespace. > >>>> class C: >... @staticmethod >... def f1(): pass >... print f1 >... > >>>> print C.f1 > It might help understand the problem if you do the something similar without using @staticmethod: class C: def f1(): pass print "f1", f1 print "C.f1", C.f1 print "C().f1", C().f1 You should see output something like: f1 C.f1 C().f1 > >The class statement's local namespace is pretty strange. I think I >mightl go back to pretending there isn't one. When class attributes are referenced, functions are turned into unbound methods and staticmethod objects get turned into functions. Something like the following should work: class C: def f1(): pass F = {'1': f1} f1 = staticmethod(f1) # if you need C.f1() to work as well If you don't need C.f1() to work you can replace the last line with "del f1". Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From berteun at NO_SPAMdds.nl Tue Jan 29 12:40:10 2008 From: berteun at NO_SPAMdds.nl (Berteun Damman) Date: Tue, 29 Jan 2008 17:40:10 +0000 (UTC) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> Message-ID: On Tue, 29 Jan 2008 09:23:16 -0800 (PST), attn.steven.kuo at gmail.com wrote: > If you're going to delete elements from > a list while iterating over it, then do > it in reverse order: Why so hard? Reversing it that way creates a copy, so you might as well do: >>> a = [ 98, 99, 100 ] >>> for i, x in enumerate(a[:]): ... if x == 99: del(a[i]) ... print x Berteun From ndbecker2 at gmail.com Tue Jan 29 14:06:05 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 29 Jan 2008 14:06:05 -0500 Subject: typename Message-ID: I want python code that given an instance of a type, prints the type name, like: typename (0) -> 'int' I know how to do this with the C-api, (o->tp_name), but how do I do it from python? type(0) prints "", not really what I wanted. From nodrogbrown at gmail.com Sat Jan 26 01:17:53 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Fri, 25 Jan 2008 22:17:53 -0800 (PST) Subject: eucledian dist calculations References: <87aff9a8-a9d8-4236-8a86-66aa58417792@i72g2000hsd.googlegroups.com> <13c59b0c-534a-4a4a-bad3-f6f51721ab78@n20g2000hsh.googlegroups.com> Message-ID: sorry..the last post didn't appear! > Are you sure? What happens if the vector with the smallest > sum(distance) is the first one? > initially i will set imgindex =0 so if the first one is of smallest sum..,the image will be reteived by imgindex 0 > (a) Can't you replace the inner loop with something like this: > distance = abs(input_weight - weights[image, :]) good suggestion ..was doing it java way! > (b) I doubt that you need the .copy() > 5. Lose the hard-wired numbers like 30 and 100 those nums were only for clarification.. > 6. Put it inside a function and *TEST* it > will do... thanx john ,your post really helped gordon From superwesman at gmail.com Wed Jan 16 01:24:28 2008 From: superwesman at gmail.com (superwesman) Date: Tue, 15 Jan 2008 22:24:28 -0800 (PST) Subject: can't find pyAntTasks.properties References: <3d1efa8c-ab6a-487d-abe6-63f227a895fc@i29g2000prf.googlegroups.com> Message-ID: <5bb081a5-f578-413f-87d2-fcfc845b7526@i7g2000prf.googlegroups.com> On Jan 15, 11:41 pm, superwesman wrote: > Hi - I'm trying to use pyAntTasks. I downloaded the jar and placed it > into ~/.ant/lib, put that directory into my CLASSPATH. I then created > a very simple build.xml and I'm getting a failure I can't explain. > > Here is my build.xml: > > > > > > Here is my CLASSPATH: > > > echo $CLASSPATH > > /home/wtorres/.ant/lib > > And here's what's in it: > > > ls -lrt $CLASSPATH > > total 24 > -rwxrwxr-x 1 wtorres staff 8563 Jan 15 18:34 pyAntTasks.jar > > When I run ant, here is the failure: > > (the 'ant' script I'm running here sets up ant 1.6.2 and runs it) > > > /vobs/jfw/ant > > ANT=/tools/ant/1.6.2 > Buildfile: build.xml > [taskdef] Could not load definitions from resource > pyAntTasks.properties. It could not be found. > > BUILD SUCCESSFUL > Total time: 1 second > > What the heck am I doing wrong? Where can I find > pyAntTasks.properties? I mean, it makes sense that "It could not be > found" because I can't find it either. Where do I get/put this? > Thanks > -w update: I downloaded a newer version on pyAntTasks and this file is included. Somebody should tell them to remove the bad build or at least mention that it won't work ;) From gagsl-py2 at yahoo.com.ar Sat Jan 26 19:20:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 26 Jan 2008 22:20:20 -0200 Subject: Text-based data inspector for Python? References: Message-ID: En Fri, 25 Jan 2008 12:28:08 -0200, kj escribi?: > The one thing I couldn't > find, and would greatly miss if not available, is the ability to > set breakpoints by inserting a particular indication right in the > code. In the Perl debugger one can insert something like the > following anywhere in the code: > > $DB::single = 1; > > When such a line executes, the debugger immediately switches to > single-step mode. It's a very flexible technique, and I like it I think that pdb.set_trace() does what you want. -- Gabriel Genellina From asmodai at in-nomine.org Mon Jan 14 06:21:09 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 14 Jan 2008 12:21:09 +0100 Subject: __init__ explanation please In-Reply-To: References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> Message-ID: <20080114112109.GV75977@nexus.in-nomine.org> -On [20080113 13:36], Fredrik Lundh (fredrik at pythonware.com) wrote: >given that they do different things, I'm not sure it's that helpful to >describe them *both* as constructors. I am still behind in my learning. ;) To restate it more correctly: __init__ is akin to a constructor. I am not entirely sure I fully understand __new__'s semantics though. The first read-through of http://docs.python.org/ref/customization.html makes it sound very similar to a call like: var = Object(arguments=...) I must not be understanding something and __new__'s documentation there is not that clear to me, to be honest. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ I think, therefore I am... From sturlamolden at yahoo.no Thu Jan 17 12:12:47 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 17 Jan 2008 09:12:47 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <3c05d0ad-3578-4976-bacb-8f5f9394c00a@i29g2000prf.googlegroups.com> On 17 Jan, 13:21, Sacred Heart wrote: > A push in the right direction, anyone? for number,letter in zip(array1,array2): print "%s %s" % (number,letter) From yantao at telus.com Sat Jan 26 23:06:45 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 04:06:45 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: References: Message-ID: I probably should mention that what I want is to make all parts of the string aligned, and look like table. I am not looking for other ways to make it table-alike, but only interested in making % work with unicode -counting characters not bytes... From kyosohma at gmail.com Mon Jan 21 09:17:45 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 21 Jan 2008 06:17:45 -0800 (PST) Subject: How to use py2exe ... References: Message-ID: On Jan 21, 1:45 am, Santiago Romero wrote: > Hi... > > I'm a Linux user, and I would like some windows-friends to test a > game I'm writing with python+pygame without they needing to install > python, pygame, and so on. > > I've heard about py2exe and pygame2exe, but I'm not sure on how to > use them to create: > > a.- standalone exe files with a single .py program. > Example: myprogram.py > > or > > b.- exe files containing all my source code + data directories (png > files, data files, and so). > Example: main.py, doc/README, src/*.py and data/* > > The problem is I'm not sure on how to use py2exe and pygame2exe to > build the executables... > > And finally, a question: if I want to provide source code > separately ... can I include .pyc files instead of .py files? You should also check out the py2exe website as it has a tutorial, a link to their mailing list, etc: http://www.py2exe.org/ Mike From pavlovevidence at gmail.com Sat Jan 12 16:10:28 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 12 Jan 2008 16:10:28 -0500 Subject: where do my python files go in linux? References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> <20080112113759.GJ75977@nexus.in-nomine.org> <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> Message-ID: <4cabmf.0g2.ln@127.0.0.1> On Sat, 12 Jan 2008 15:25:53 -0500, Mike Meyer wrote: > On Sat, 12 Jan 2008 16:13:08 +0100 "Jorgen Bodde" > wrote: >> > Normally you'd split up the bulk of the code into a module which gets >> > installed into site-packages and a piece of stand-alone front-end >> > code which imports the module and executes whatever you need to do >> > and gets installed into a typical PATH directory. >> I would agree but it is not a site package I am trying to distribute, >> but a wxPython application. I would not think my app belongs in the >> python site packages dir. > > I suspect that's because your app is "simple", in that it only has one > command. Many apps have multiple commands that share the same set of > libraries. So putting a package for that app in site-packages makes a > lot of sense. They should go into their own directory in /usr/local/lib (or whatever). > If your app-specific library is properly designed and > documented, users may be able to build further commands for the system > as well. Users can still add the /usr/local/lib/whatever to their path path and use it that way. I realize it's a fine line and a judgment call in some cases, but site- packages is really for libraries; applications should use their own directories. Carl Banks From graemeglass at gmail.com Sun Jan 13 15:15:54 2008 From: graemeglass at gmail.com (Graeme Glass) Date: Sun, 13 Jan 2008 12:15:54 -0800 (PST) Subject: Great Python books for the beginner References: Message-ID: <98cc988c-6efe-4861-a6e9-59e6764e3e89@s19g2000prg.googlegroups.com> On Jan 12, 9:03 am, Landon wrote: > Hi, I'm a freshman in college and I'm going to be taking an intro to > programming course next semester which mainly uses Python, so I > thought it might be a good time to pick up Python beyond the scope of > the class as well. The text book for this class is Python for the > Absolute Beginner or something similar to that name. > > I was wondering if anyone had any opinions on what other titles I > could look into since this one seems from a glance at reviews to be > teaching mainly through game programming (a topic I'm not too > interested in) or if this one is a quality book by itself. I found CORE PYTHON PROGRAMMING by Wesley Chun to be a great book with help on both novice and advanced topics. http://starship.python.net/crew/wesc/cpp/ The tuts and library reference on www.python.org are also really well written and layed out and you will find yourself frequenting them. From chris.monsanto at gmail.com Tue Jan 15 12:06:42 2008 From: chris.monsanto at gmail.com (Chris M) Date: Tue, 15 Jan 2008 09:06:42 -0800 (PST) Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: <5a3ace63-a8cf-4970-a95e-4243226fbac7@j20g2000hsi.googlegroups.com> On Jan 15, 11:51 am, "Neil Cerutti" wrote: > > So this is a bug in set_update or in set_ior. They can't both be > right. > It's not a bug. "Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') & 'cbs' in favor of the more readable set('abc').intersection('cbs')." From floris.bruynooghe at gmail.com Wed Jan 16 10:31:12 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Wed, 16 Jan 2008 07:31:12 -0800 (PST) Subject: MSI read support in msilib? Message-ID: <367e7e5e-6b63-4474-8704-b8af300f7bfb@e4g2000hsg.googlegroups.com> Hi The introduction from the msilib documentation in python 2.5 claims it supports reading an msi. However on the Record class there is only a GetFieldCount() method and some Set*() methods. I was expecting to see GetString() and GetInteger() methods to be able to read the values. Maybe I'm missing something? Is there an other way to read the data of a record? Regards Floris From Rens.Duijsens at gmail.com Sun Jan 27 09:51:51 2008 From: Rens.Duijsens at gmail.com (Dox33) Date: Sun, 27 Jan 2008 06:51:51 -0800 (PST) Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> <87dd811e-3095-41d0-80fd-7312338e5254@i3g2000hsf.googlegroups.com> <489b6fc5-e871-425e-b242-45be618fc9f4@n20g2000hsh.googlegroups.com> <87r6g4q7hq.fsf@mulj.homelinux.net> Message-ID: Yes, I know. There are several ways to work around the problem. (Look at the innitial code I provided in this discussion start) Fact is, every time I'm getting a script from somewhere or someone, I have to search and replace all the affected code. Not very conveniant. That's why I rather would have a correct working version. On 27 jan, 04:20, Hrvoje Niksic wrote: > Dox33 writes: > > Thanks for your reply. ?Since I momentarily do not have the ability > > to build a new python executable, I would like to ask for your help > > in this case. ?Are you able to supply me with a corrected version? > > You can simply choose not to use raw_input, and use sys.stdin.readline > instead. ?Or define your own corrected raw_input: > > def my_raw_input(msg): > ? ? print msg, > ? ? return raw_input() From princismo at gmail.com Mon Jan 21 23:34:01 2008 From: princismo at gmail.com (=?Big5?B?w0P4rw==?=) Date: Mon, 21 Jan 2008 20:34:01 -0800 (PST) Subject: How to solve "TypeError: list indices must be integers". References: <3f3ca8c6-b57c-43ff-bf80-11768e1a0f94@s8g2000prg.googlegroups.com> <13p9n6efmt4b95a@corp.supernews.com> Message-ID: <38cd97ae-dff8-4a29-9657-3db101c2f515@y5g2000hsf.googlegroups.com> On 1?22?, ??1?56?, Dennis Lee Bieber wrote: > On Mon, 21 Jan 2008 08:15:02 -0800 (PST), "?C??" > declaimed the following in comp.lang.python: > > > I was assigned dialog.colorDialog(self) return value to a result > > object, but I suspect that result.color is the attribute of the result > > object that can assign to a string variable. > > ? ? ? ? Showing the actual code would help... > > > There is a error prompt from python console "TypeError: list indices > > must be integers". > > Have any suggestion to solve this problem? > > ? ? ? ? Make sure you only have an integer when subscripting into a list? > > > When I print ?result.color, it is print out something like (255,0,0). > > ? ? ? ? Looks like a tuple -- probably > ? ? ? ? ? ? ? ? (red-level, green-level, blue-level) > where *-level is in the range 0..255 (x00..xFF); your example would be > (full red, no green, no blue) > > > How to covert result.color into a string? ?How to convert a string to > > result.color type? > > ? ? ? ? What type of string? > ? ? ? ? ? ? ? ? "0x%2.2X%2.2X%2.2X" % (r, g, b) > will produce a hex string of the form > ? ? ? ? ? ? ? ? 0xFF0000 > given your sample RGB > > ? ? ? ? If you want to get "Red", you'll need a look-up table and probably > some least-distance error function for items that don't directly match. > > (255, 0, 0) ? ? ? ? ? ? Red > (255, 255, 0) ? Yellow > (255, 0, 255) ? Magenta > (0, 255, 0) ? ? ? ? ? ? Green > (0, 255, 255) ? Cyan > (0, 0, 255) ? ? ? ? ? ? Blue > (0, 0, 0) ? ? ? ? ? ? ? Black > (255, 255, 255) White > > ? ? ? ? But where would you put: ? ? ? ?(127, 127, 63) ? ? ? ? ?[A half-black Yellow > with 1/4 blue added].. Is it closer to Yellow, or to Black: 255-127 => > 128, but 127 - 0 => 127... Shorter simplistic distance means map this to > (0, 0, 0)... But (128, 128, 64) simplistic shorter distance would map to > Yellow > > -- > ? ? ? ? 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/ Many thanks, Dennis Lee Bieber for your fast reply! Regards, Andreas From kyosohma at gmail.com Fri Jan 11 09:44:19 2008 From: kyosohma at gmail.com (Mike) Date: Fri, 11 Jan 2008 06:44:19 -0800 (PST) Subject: Help with Windows build of Yapgvb Python extension References: Message-ID: <4bfd40d3-61f5-4c88-b6b2-c8ebef1b13dc@m34g2000hsf.googlegroups.com> On Jan 11, 8:41 am, Lonnie Princehouse wrote: > I'm the author of Yapgvb, a Python binding for Graphviz. Yapgvb > enjoys modest success, but for some time it has been in dire need of a > Python 2.5 build for Windows. I'm posting this message in the hopes of > finding someone who is interested in making this build. > > This is a relatively quick task for someone who is comfortable with > building C extensions and has an operational Windows build environment > for Python 2.5 (which I don't). Alternately, it's a great way to > learn about these things, and to get involved with a small open source > project. > > Technologies used: > graphviz > distutils > boost.python > boost.graph > > See:http://yapgvb.sourceforge.net What do you need exactly? One of those executables created using bdist or are you going for the msi? I usually attempt to create these things doing python setup.py bdist_wininst ...for executable installers. If you can provide a valid setup.py, I can probably create the exe/ msi. Mike From pofuk at mzm.hr Tue Jan 1 18:55:28 2008 From: pofuk at mzm.hr (SMALLp) Date: Wed, 02 Jan 2008 00:55:28 +0100 Subject: Python events, panel with text Message-ID: Hy! I have many small panels with text and I want do bind wx.EVT_LEFT_DOWN when clicked on panel, but i need to bind that in parent class. So I have instance of that small panel and when i bind it efects only part of small panel where is no text. import wx class RequestedFilesItems(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, -1, style=wx.SUNKEN_BORDER) sizer = wx.BoxSizer(wx.HORIZONTAL) upButton = PanelButton(self, -1, "Upload") upButton.Bind(wx.EVT_LEFT_DOWN, self.upload) sizer.Add(upButton, 0, wx.LEFT, 15) self.SetSizer(sizer) def upload(self, event): print "Please print this" class PanelButton(wx.Panel): def __init__(self, parent, id, buttonName): wx.Panel.__init__(self, parent, -1, style=wx.SUNKEN_BORDER) self.SetBackgroundColour("GREY") sizer = wx.BoxSizer(wx.HORIZONTAL) self.text = wx.StaticText(self, -1, buttonName) sizer.Add(self.text, -1, wx.EXPAND | wx.ALL, 1) self.text.Bind(wx.EVT_LEFT_DOWN, self.OnClick) self.SetSizer(sizer) def OnClick(self, event): print "It only works for text, not for panel what I expected here" if __name__ == '__main__': app = wx.PySimpleApp() frm = wx.Frame(None, wx.ID_ANY, 'Mouse-click test') panel = RequestedFilesItems(frm, wx.ID_ANY) frm.Show() app.MainLoop() app.MainLoop() From yantao at telus.com Sun Jan 27 11:00:42 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 16:00:42 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: <6031q9F1oh17aU1@mid.uni-berlin.de> References: <13po55nc0q0s06@corp.supernews.com> <6031q9F1oh17aU1@mid.uni-berlin.de> Message-ID: "Marc 'BlackJack' Rintsch" wrote in message news:6031q9F1oh17aU1 at mid.uni-berlin.de... > On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: > >> You didn't understand my question, but thanks any way. >> >> Yes, it is true that %s already support unicode, and I did not contradict >> that. But it counts the number of bytes instead of characters, and makes >> things like %-20s out of alignment. If you don't understand my assertion, >> please don't argue back and I am only interested in answers from those >> who >> are qualified. > > I have the impression from your original post > > [?] because it is unicode, and one byte is not neccessary one character. > > that you confuse unicode and utf-8. Are you sure you are qualified to ask > such a question in the first place!? :-? so you are saying, with utf-8 encoding a byte is a character, shame on you. > > Ciao, > Marc 'BlackJack' Rintsch From tarun.kap at gmail.com Wed Jan 16 12:21:05 2008 From: tarun.kap at gmail.com (Tarun Kapoor) Date: Wed, 16 Jan 2008 09:21:05 -0800 (PST) Subject: paramiko References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> Message-ID: <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> # now, connect and use paramiko Transport to negotiate SSH2 across the connection sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) t = paramiko.Transport(sock) t.start_client() key = t.get_remote_server_key() event = threading.Event() t.auth_password(username=username, password=password, event=event) event.wait() if not t.is_authenticated(): print "not authenticated" output: not authenticated On Jan 16, 11:11 am, "Guilherme Polo" wrote: > 2008/1/16, Tarun Kapoor : > > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > > the remote server using an SFTP client I have just to make sure that > > username and password are working.. This is the code. > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > > connection > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > sock.connect((hostname, port)) > > > t = paramiko.Transport(sock) > > > event = threading.Event() > > > t.start_client(event) > > > event.wait(15) > > > if not t.is_active(): > > > print 'SSH negotiation failed.' > > > sys.exit(1) > > > else: > > > print "SSH negotiation sucessful" > > > event.clear() > > > t.auth_password(username=username, password=password,event=event) > > > if not t.is_authenticated(): > > > print "not authenticated" > > > output: > > > SSH negotiation successful > > > not authenticated > > > Tarun > > > Waterstone Capital Management > > > 2 Carlson Parkway, Suite 260 > > > Plymouth, MN 55447 > > > Direct: 952-697-4123 > > > Cell: 612-205-2587 > > Disclaimer This e-mail and any attachments is confidential and intended > > solely for the use of the individual(s) to whom it is addressed. Any views > > or opinions presented are solely those of the author and do not necessarily > > represent those of Waterstone Capital Management, L.P and affiliates. If you > > are not the intended recipient, be advised that you have received this > > e-mail in error and that any use, dissemination, printing, forwarding or > > copying of this email is strictly prohibited. Please contact the sender if > > you have received this e-mail in error. You should also be aware that > > e-mails are susceptible to interference and you should not assume that the > > contents of this e-mail originated from the sender above or that they have > > been accurately reproduced in their original form. Waterstone Capital > > Management, L.P. and affiliates accepts no responsibility for information, > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > > please verify the authenticity with the sender. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > You are missing an event.wait() after t.auth_password. > Also, why are you passing this magic value "15" to event.wait() ? That > parameter is passed to class _Verbose to indicate if debug messages > should be displayed or not, so typical values would be 0/1 or > False/True. > > -- > -- Guilherme H. Polo Goncalves From steven.bethard at gmail.com Tue Jan 1 14:59:44 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 01 Jan 2008 12:59:44 -0700 Subject: ElementTree should parse string and file in the same way In-Reply-To: <13nkkh6almg8o6b@corp.supernews.com> References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> <5tuqfaF1f8u9tU1@mid.uni-berlin.de> <13nkkh6almg8o6b@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Tue, 01 Jan 2008 13:36:57 +0100, Diez B. Roggisch wrote: > >> And codemonkeys know that in python >> >> doc = et.parse(StringIO(string)) >> >> is just one import away > > Yes, but to play devil's advocate for a moment, > > doc = et.parse(string_or_file) > > would be even simpler. I assume the problem with this is that it would be ambiguous. You can already use either a string or a file with ``et.parse``. A string is interpreted as a file name, while a file object is used directly. How would you differentiate between a string that's supposed to be a file name, and a string that's supposed to be XML? Steve From grflanagan at yahoo.co.uk Tue Jan 8 04:34:36 2008 From: grflanagan at yahoo.co.uk (grflanagan) Date: Tue, 8 Jan 2008 01:34:36 -0800 (PST) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> <1d895d6d-a649-439e-8223-0ae7d3a4eb40@l6g2000prm.googlegroups.com> Message-ID: On Jan 8, 3:08 am, ajaksu wrote: > On Jan 7, 11:25 am, MartinRineh... at gmail.com wrote: > > > Anything written somewhere that's thorough? Any code body that should > > serve as a reference? > > I've done this search before and it was very interesting, doing it > again gave me new results that also seem valuable. Here's most of them > (where PCG = Python Coding Guidelines). [...] > > Do you think this could be a valuable addition to the Python wiki? > +1, absolutely Here's the list in rest format: ------------------------------ FOSS Projects Style Guidelines ------------------------------ `Cogent project PCG`__ .. _Cogent PCG: http://jaynes.colorado.edu/PythonGuidelines.html __ `Cogent PCG`_ `Cogent project Python Idioms`__ .. _Cogent Idioms: http://jaynes.colorado.edu/PythonIdioms.html __ `Cogent Idioms`_ `Freevo Coding Standard`__ .. _Freevo PCG: http://doc.freevo.org/CodingStandard __ `Freevo PCG`_ `Mercurial Basic Coding Style`__ .. _Mercurial PCG: http://www.selenic.com/mercurial/wiki/index.cgi/Basic_Coding_Style __ `Mercurial PCG`_ `PyBlosxom Coding Style Guide`__ .. _PyBlosxom PCG: http://pyblosxom.sourceforge.net/blog/static/development#coding __ `PyBlosxom PCG`_ `MoinMoin Coding Style`__ .. _MoinMoin PCG: http://moinmoin.wikiwikiweb.de/CodingStyle __ `MoinMoin PCG`_ `Webware Style Guidelines`__ .. _Webware PCG: http://www.webwareforpython.org/Docs/StyleGuidelines.html __ `Webware PCG`_ `NOAA Enhanced Forecaster Tools PCG`__ .. _NOAA PCG: http://www-md.fsl.noaa.gov/eft/developer/PythonCodingStandards.html __ `NOAA PCG`_ `BioPython Coding Conventions`__ .. _BioPython PCG: http://biopython.org/wiki/Contributing#Coding_conventions __ `BioPython PCG`_ `Mnet PCG`__ .. _Mnet PCG: http://mnet.sourceforge.net/coding_standards.html __ `Mnet PCG`_ `Michael Foord's (aka Voidspace) PCG`__ .. _Michael PCG: http://www.voidspace.org.uk/python/weblog/arch_d7_2006_04_01.shtml#e296 __ `Michael PCG`_ `SQLObject Coding Style`__ .. _SQLObject PCG: http://www.sqlobject.org/DeveloperGuide.html#style-guide __ `SQLObject PCG`_ `WxPython PCG`__ .. _WxPython PCG: http://www.wxpython.org/codeguidelines.php __ `WxPython PCG`_ `Mailman PCG`__ .. _Mailman PCG: http://barry.warsaw.us/software/STYLEGUIDE.txt __ `Mailman PCG`_ `VoiceCode PCG`__ .. _VoiceCode PCG: http://voicecode.iit.nrc.ca/VoiceCode/uploads/codingGuidelines.html __ `VoiceCode PCG`_ `Bazaar Coding Style Guidelines`__ .. _Bazaar PCG: http://doc.bazaar-vcs.org/bzr.dev/en/developer-guide/HACKING.html#coding-style-guidlines __ `Bazaar PCG`_ `IPython Developer Guidelines`__ .. _IPython PCG: http://ipython.scipy.org/moin/Developer_Zone/Developer_Guidelines __ `IPython PCG`_ `OSAF Chandler PCG`__ .. _OSAF PCG: http://chandlerproject.org/Projects/ChandlerCodingStyleGuidelines __ `OSAF PCG`_ `OSAF Chandler Epydoc Style Guide`__ .. _OSAF Epydoc: http://chandlerproject.org/Projects/ChandlerEpydocStyleGuide __ `OSAF Epydoc`_ `Twisted Coding Standard`__ .. _Twisted PCG: http://twistedmatrix.com/trac/browser/trunk/doc/development/policy/coding-standard.xhtml?format=raw __ `Twisted PCG`_ `PyPy RPython and CPython Coding Guidelines`__ .. _PyPy PCG: http://codespeak.net/pypy/dist/pypy/doc/coding-guide.html __ `PyPy PCG`_ `Django PCG`__ .. _Django PCG: http://www.djangoproject.com/documentation/contributing/#coding-style __ `Django PCG`_ `Docutils PCG`__ .. _Docutils PCG: http://docutils.sourceforge.net/docs/dev/policies.html#python-coding-conventions __ `Docutils PCG`_ `Trac Coding Style`__ .. _Trac PCG: http://trac.edgewall.org/wiki/TracDev/CodingStyle __ `Trac PCG`_ `OLPC PCG`__ .. _OLPC PCG: http://wiki.laptop.org/go/Python_Style_Guide __ `OLPC PCG`_ `Skeletonz Coding and Naming Conventions`__ .. _Skeletonz PCG: http://orangoo.com/skeletonz/Developer_guide/Coding_convention/ __ `Skeletonz PCG`_ `CherryPy Code Conventions`__ .. _CherryPy PCG: http://www.cherrypy.org/wiki/CodeConventions __ `CherryPy PCG`_ `Software Carpentry on style`__ .. _Software Carpentry PCG: http://www.swc.scipy.org/lec/style.html __ `Software Carpentry PCG`_ `Zope's Coding Style`__ .. _Zope PCG: http://wiki.zope.org/zope3/CodingStyle __ `Zope PCG`_ `The docstrings PEP`__ .. _docstrings: http://www.python.org/dev/peps/pep-0257/ __ `docstrings`_ `Pyflakes`__ .. _Pyflakes: http://divmod.org/trac/wiki/DivmodPyflakes __ `Pyflakes`_ `PyChecker`__ .. _PyChecker: http://pychecker.sourceforge.net/ __ `PyChecker`_ `Pylint`__ .. _Pylint: http://www.logilab.org/857 __ `Pylint`_ From sunilkrghai at gmail.com Mon Jan 7 11:01:01 2008 From: sunilkrghai at gmail.com (Sunil Ghai) Date: Mon, 7 Jan 2008 21:31:01 +0530 Subject: PostgreSQL with Python Message-ID: <52da23100801070801o55c6ce8bva2e0a09be4ffa94e@mail.gmail.com> I am looking for an E-Book or some tutorial in which a good explanation about PostgreSQL/MySQL database, then about interacting with them using Python is explained. I want to start RDBMS, i have no idea about them. I have been doing Python, willing to do some good project in RDBMS. Thanks in advance :) Regards -- Sunil Ghai -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Tue Jan 22 16:42:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 22 Jan 2008 13:42:13 -0800 (PST) Subject: Processing XML that's embedded in HTML References: <6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> Message-ID: <25087d9b-ce63-4e9c-b83c-55e6043c49f9@v46g2000hsv.googlegroups.com> On Jan 23, 7:48 am, Mike Driscoll wrote: [snip] > I'm not sure what is wrong here...but I got lxml to create a tree from > by doing the following: > > > from lxml import etree > from StringIO import StringIO > > parser = etree.HTMLParser() > tree = etree.parse(filename, parser) > xml_string = etree.tostring(tree) > context = etree.iterparse(StringIO(xml_string)) > > > However, when I iterate over the contents of "context", I can't figure > out how to nab the row's contents: > > for action, elem in context: > if action == 'end' and elem.tag == 'relationship': > # do something...but what!? > # this if statement probably isn't even right > lxml allegedly supports the ElementTree interface so I would expect elem.text to refer to the contents. Sure enough: http://codespeak.net/lxml/tutorial.html#elements-contain-text Why do you want/need to use the iterparse technique on the 2nd pass instead of creating another tree and then using getiterator? From bertle at smoerz.org Fri Jan 25 11:46:13 2008 From: bertle at smoerz.org (Roman Bertle) Date: 25 Jan 2008 16:46:13 GMT Subject: grouping in module 'locale' Message-ID: Hello, I try to format monetary values using the locale module, python2.5: Python 2.5.2a0 (r251:54863, Jan 3 2008, 17:59:56) [GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_ALL, 'de_AT.utf8') 'de_AT.utf8' >>> locale.localeconv() {'mon_decimal_point': ',', 'int_frac_digits': 2, 'p_sep_by_space': 1, 'frac_digits': 2, 'thousands_sep': '', 'n_sign_posn': 1, 'decimal_point': ',', 'int_curr_symbol': 'EUR ', 'n_cs_precedes': 1, 'p_sign_posn': 1, 'mon_thousands_sep': ' ', 'negative_sign': '-', 'currency_symbol': '\xe2\x82\xac', 'n_sep_by_space': 1, 'mon_grouping': [3, 3, 0], 'p_cs_precedes': 1, 'positive_sign': '', 'grouping': []} >>> locale.currency(1234.5678, grouping=True, symbol=False) '1234,57' As you can see, the decimal point is correctly set to ','. But the grouping is not done, every 3 digits should be separated by space (' '). Using the 'de_DE.utf8' locale, ist works: >>> locale.setlocale(locale.LC_ALL, 'de_DE.utf8') 'de_DE.utf8' >>> locale.localeconv() {'mon_decimal_point': ',', 'int_frac_digits': 2, 'p_sep_by_space': 1, 'frac_digits': 2, 'thousands_sep': '.', 'n_sign_posn': 1, 'decimal_point': ',', 'int_curr_symbol': 'EUR ', 'n_cs_precedes': 0, 'p_sign_posn': 1, 'mon_thousands_sep': '.', 'negative_sign': '-', 'currency_symbol': '\xe2\x82\xac', 'n_sep_by_space': 1, 'mon_grouping': [3, 3, 0], 'p_cs_precedes': 0, 'positive_sign': '', 'grouping': [3, 3, 0]} >>> locale.currency(1234.5678, grouping=True, symbol=False) '1.234,57' The difference here is that thounds_sep is '.', not ' '. If we look at the code of locale.py, revision 55038, lines 157-161, the inserted spaces are later deleted again: while seps: sp = formatted.find(' ') if sp == -1: break formatted = formatted[:sp] + formatted[sp+1:] seps -= 1 This code is only called if numbers are formated as floating point, but not for integers. The following works: >>> locale.setlocale(locale.LC_ALL, 'de_AT.utf8') 'de_AT.utf8' >>> locale.format('%d',1234.5678, grouping=True, monetary=True) '1 234' The reason for the space removal is explained in an earlier version of locale.py, e.g. 42120: # If the number was formatted for a specific width, then it # might have been filled with spaces to the left or right. If # so, kill as much spaces as there where separators. # Leading zeroes as fillers are not yet dealt with, as it is # not clear how they should interact with grouping. But I don't know the why and how this code is necessary. Can anybody shed some light on this issue? Best Regards, Roman From max at alcyone.com Thu Jan 10 17:06:49 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 10 Jan 2008 14:06:49 -0800 Subject: Embedding python code into text document question. In-Reply-To: References: Message-ID: Thomas Troeger wrote: > I've written a program that parses a string or file for embedded python > commands, executes them and fills in the returned value. The input might > look like this: > > process id: $$return os.getpid()$$ > current date: $$return time.ctime()$$ > superuser: $$ > if os.geteuid(): > return "Yes" > else: > return "No"$$ > > I've tried several solutions using eval, execfile or compile, but none > of those would solve my problem. Does anyone have a solution that works? > Any suggestions? Any help will be appreciated :) What you're looking for is a templating system for Python. There are already many with varying degrees of complexity and emphasis, including one I've put together, EmPy: http://www.alcyone.com/software/empy/ For more, google around for Python templating. -- 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 If the sun comes up / And you're not home / I'll be strong -- India Arie From rong.xian at gmail.com Sun Jan 27 05:20:08 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 02:20:08 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <77a2d5cd-239f-4ce7-9fd1-3c935453180d@i29g2000prf.googlegroups.com> Message-ID: <64a9b332-c4e3-4bf3-b4f6-6c55c6161333@i12g2000prf.googlegroups.com> On 1?24?, ??5?51?, John Machin wrote: > On Jan 24, 2:49 pm, glacier wrote: > > > I use chinese charactors as an example here. > > > >>>s1='???' > > >>>repr(s1) > > > "'\\xc4\\xe3\\xba\\xc3\\xc2\\xf0'" > > > >>>b1=s1.decode('GBK') > > > My first question is : what strategy does 'decode' use to tell the way > > to seperate the words. I mean since s1 is an multi-bytes-char string, > > how did it determine to seperate the string every 2bytes or 1byte? > > The usual strategy for encodings like GBK is: > 1. If the current byte is less than 0x80, then it's a 1-byte > character. > 2. Current byte 0x81 to 0xFE inclusive: current byte and the next byte > make up a two-byte character. > 3. Current byte 0x80: undefined (or used e.g. in cp936 for the 1-byte > euro character) > 4: Current byte 0xFF: undefined > > Cheers, > John Thanks John, I will try to write a function to test if the strategy above caused the problem I described in the 1st post:) From rick.arnett at gmail.com Mon Jan 28 12:30:31 2008 From: rick.arnett at gmail.com (the_ricka) Date: Mon, 28 Jan 2008 09:30:31 -0800 (PST) Subject: SMTP Sending Mail Problem References: <9b00a5f5-277d-4d23-be82-60c2aafc4227@c23g2000hsa.googlegroups.com> Message-ID: <8d8a744f-f009-41b6-8a6a-001c6b1f0615@y5g2000hsf.googlegroups.com> I added a longer text file with vocabulary typically used in our office and the email sent successfully. The crazy thing is I had already checked all the spam filters and queues in Exchange, and the older messages seem to have disappeared. Sorry for the post, I thought I was going crazy for a bit! Thanks again for the sanity check. From khoard at gmail.com Fri Jan 18 14:50:27 2008 From: khoard at gmail.com (FireNWater) Date: Fri, 18 Jan 2008 11:50:27 -0800 (PST) Subject: Core Python Programming . . . Message-ID: I'm working my way thru the book "Core Python Programming" 2d Edition - Wesley Chun. . . Trying to figure out what he's looking for on Page 248, Exercise 6-11 (a). Is it supposed to be: 1) convert a 4-digit Integer (WXYZ) to an IP address (WWW.XXX.YYY.ZZZ) or 2) convert an 8-digit Integer (WWWXXXYYYZZZ) to (WWW.XXX.YYY.ZZZ) Thanks for anyone with the clue!!! From mwilson at the-wire.com Tue Jan 29 11:25:11 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 29 Jan 2008 11:25:11 -0500 Subject: extending Python - passing nested lists References: <3ddeaf07-3f4b-4d68-a176-9205fa4d234b@k39g2000hsf.googlegroups.com> Message-ID: Christian Meesters wrote: >> You didn't mention speed in your original post. > Sorry, perhaps I considered this self-evident - which it is, of course, not. > >> What about using >> array.array? Unless I am mistaken, these are just a thin wrapper >> around normal C arrays. > The algorithm I want to implement requires several million floating point > operations. Neither the array-modules nor numpy's thin layer seem thin > enough for me. ;-) > >> Anyway you could always convert your list >> into a c array, do lots and lots of fast calculations, then convert it >> back again to a list. > I guess I am too blind to see, but I couldn't discover a method description > like "double* PyList_toDouble". So, yes, my question is a C-API-newbie > question: What is the way to say "myCarray = SomePyMethod(InputPyList)"? Or > better, what should be here instead > static PyObject *_foo(PyObject *self, PyObject *args) { > double *v; > if (!PyArg_Parse(args, "(d)", &v)) > return NULL; > to get a list as an array of doubles into 'v' (and back to Python)? > > I did read the API-description, but still am lost at this point. I presume, > once I get to know the answer I'll bang my head on the table ... ;-) I haven't strictly tried this, but PyArg_ParseTuple and Py_BuildValue seem to be the orthodox ways to do Python->C and C->Python conversions. But if Numpy isn't fast enough, then any Python at all in the solution might be too much. Perhaps keeping your values in a file and reading them into the C programs will work. Mel. From mail at microcorp.co.za Thu Jan 17 09:22:26 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 17 Jan 2008 16:22:26 +0200 Subject: Interesting Thread Gotcha References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> Message-ID: <001301c85929$9cd82000$03000080@hendrik> "Diez B. Roggisch" wrote: > Hendrik van Rooyen wrote: > > It would have been nice, however, to have gotten something like: > > > > TypeError - This routine needs a tuple. > > > > instead of the silent in line calling of the routine in question, > > while failing actually to start a new thread. > > You can't prevent the silent inline-calling - otherwise, how would you do > this: > > def compute_thread_target(): > def target(): > pass > return target > > thread.start_new_thread(compute_thread_target()) > > > Of course start_new_thread could throw an error if it got nothing callable > as first argument. No idea why it doesn't. Thanks - got it, I think. Doesn't mean I like it, though: >>> a = 42 >>> b = 24 >>> def do_something(c,d): print c print d >>> do_something(a,b) 42 24 >>> def harmless(): return a >>> def evil(): while True: pass >>> do_something(a) Traceback (most recent call last): File "", line 1, in ? do_something(a) TypeError: do_something() takes exactly 2 arguments (1 given) >>> do_something(harmless()) Traceback (most recent call last): File "", line 1, in ? do_something(harmless()) TypeError: do_something() takes exactly 2 arguments (1 given) >>>do_something(evil()) This hangs and needs OS intervention to kill it - and there is also just one argument, not two. Looks like the arguments are handled one by one without validation till the end. Lets see: >>> do_something(a,b,harmless()) Traceback (most recent call last): File "", line 1, in ? do_something(a,b,harmless()) TypeError: do_something() takes exactly 2 arguments (3 given) So far, so good. >>>do_something(a,b,evil()) This also hangs - the third, extra argument is actually called! Are you all sure this is not a buglet? - Hendrik From mr.cerutti at gmail.com Tue Jan 15 08:24:47 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Tue, 15 Jan 2008 08:24:47 -0500 Subject: Append zip files together, just get the binary data (in memory) In-Reply-To: References: <53f66038-ccc3-4c3d-97b2-fa5deb148809@d4g2000prg.googlegroups.com> <5v27oiF1kavhlU1@mid.uni-berlin.de> Message-ID: <51302a8c0801150524u3020b402h31be2848b725fb87@mail.gmail.com> On Jan 15, 2008 4:28 AM, John Machin wrote: > On Jan 15, 9:58 am, "Diez B. Roggisch" wrote: > > > Module StringIO is your friend. > > and cStringIO is your ....? ... friend +1? -- Neil Cerutti From bignose+hates-spam at benfinney.id.au Mon Jan 14 17:20:17 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 09:20:17 +1100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> Message-ID: <87lk6sf3ry.fsf@benfinney.id.au> Hrvoje Niksic writes: > Wildemar Wildenburger writes: > > __init__() /initializes/ an instance (automatically after > > creation). It is called, /after/ the instance has been constructed > > I don't understand the purpose of this "correction". After all, > __init__ *is* the closest equivalent to what other languages would > call a constructor. No. That would be '__new__', which actually constructs the instance, and actually returns it to the caller. '__init__' does neither of those. It so happens that, in Python, one usually overrrides the initialiser and not the constructor. Thus, the confusion is understandable, but still regrettable and avoidable. -- \ "My, your, his, hers, ours, theirs, its. I'm, you're, he's, | `\ she's, we're, they're, it's." ?anonymous, | _o__) alt.sysadmin.recovery | Ben Finney From deets at nospam.web.de Thu Jan 3 10:05:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 16:05:07 +0100 Subject: problem with global var References: Message-ID: <5u4bt3F1ef265U1@mid.uni-berlin.de> Bruno Ferreira wrote: > Hi, > > I wrote a very simple python program to generate a sorted list of > lines from a squid access log file. > > Here is a simplified version: > > ################################## > 1 logfile = open ("squid_access.log", "r") > 2 topsquid = [["0", "0", "0", "0", "0", "0", "0"]] > 3 > 4 def add_sorted (list): > 5 for i in range(50): > 6 if int(list[4]) > int(topsquid[i][4]): > 7 topsquid.insert(i,list) > 8 break > 8 # Max len = 50 > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > 12 > 13 while True: > 14 logline = logfile.readline() > 15 linefields = logline.split() > 16 > 17 if logline != "": > 18 add_sorted (linefields) > 19 else: > 20 break > 21 > 22 for i in range (len(topsquid)): > 23 print topsquid[i][4] > #################################### > > When I execute the program _without_ the lines 10 and 11: > > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > > it runs perfectly. > > But if I execute the program _with_ those lines, this exception is thrown: > > bruno at ts:~$ python topsquid.py > Traceback (most recent call last): > File "topsquid.py", line 20, in > add_sorted (linefields) > File "topsquid.py", line 6, in add_sorted > if int(list[4]) > int(topsquid[i][4]): > UnboundLocalError: local variable 'topsquid' referenced before assignment > > > Note that now the error shown is not related with the lines 10 and 11, > but wiht a line prior to them. > > Any hints? Use def add_sorted(list): global topsquid ... to make topsquid a global variable to add_sorted. Otherwise python sees that it gets referred by in the if-statement before assigning to it, thus resulting in the error you see. The reason for this is that a (limited) static analysis of python-code is performed to determine which variables are local to a function and which not. The criteria essentially is the appearance on the left-hand-side of an expression makes a variable (or name) local to that function. Which makes it require the explicit global declaration. Apart from that there are quite a few things worth mentioning in your code: - don't shadow built-in names like list - it's superfluous to do for i in xrange(len(some_list)): .. some_list[i] .. as you do, unless you need the index. Instead do for element in some_list: ... element ... If you need an index, do for i, element in enumerate(some_list): ... - don't use range, use xrange if you don't need a list but rather want to enumerate indices. - the while-loop is superfluous as well, just do for line in logfile: ... or if your python is older do for line in logfile.xreadlines(): ... Diez From python.list at tim.thechases.com Mon Jan 28 12:01:46 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 28 Jan 2008 11:01:46 -0600 Subject: Get Available Functions In-Reply-To: <020501c861ca$d604dc70$820e9550$@rawlins@thinkbluemedia.co.uk> References: <020501c861ca$d604dc70$820e9550$@rawlins@thinkbluemedia.co.uk> Message-ID: <479E0A7A.9080305@tim.thechases.com> > I'm working with a python module which isn't part of the core > Python API and it also isn't very documented or supported, is > there any way that I can easily dump/view the available > classes and methods within the package from within python? Most of the time, the dir(), type() and help() functions can be your friend: >>> import somelib >>> dir(somelib) ['Foo', 'thing', 'whatever'] >>> type(somelib.Foo) >>> dir(somelib.Foo) ['method1', 'method2'] >>> type(somelib.thing) >>> print somelib.thing 'I didn't expect the Spanish Inquisition!' >>> type(somelib.whatever) >>> help(somelib.whatever) Help on function whatever in module somelib: whatever(param1, param2, *args, **kwargs) >>> I've had a couple cases where the underlying module was written in C (mod_python in particular...don't know if it still has this problem) where dir() wouldn't actually tell you about the object, but for most cases, dir() will get you pointed in the right dir-ection. :) -tkc From vriolk at gmail.com Fri Jan 18 04:20:40 2008 From: vriolk at gmail.com (coldpizza) Date: Fri, 18 Jan 2008 01:20:40 -0800 (PST) Subject: How to detect a remote webpage is accessible? (in HTTP) References: Message-ID: I suppose that if the file is really big and you don't need to read all of it then instead of f.readlines() you could use f.read(256) to read just the first 256 bytes. On Jan 18, 7:28?am, Astan Chee wrote: > How about: > > import socket, urllib2 > > timeout = 10 > socket.setdefaulttimeout(timeout) > try: > auth_handler = urllib2.HTTPBasicAuthHandler() > opener = urllib2.build_opener(auth_handler) #this used if we need > authentication > urllib2.install_opener(opener) > req = urllib2.Request('http://website.com') > f = urllib2.urlopen(req) > notes= f.readlines() > f.close() > print "Everything is ok" > except IOError, r: > p = str(r) > if re.search(r'urlopen error timed out',p): > print "Web page timed out" > > You'll need to set up the timeout to whatever duration your website > takes to load. > Cheers > Astan > > > > ?? wrote: > > Howdy, all, > > ? ? ?I want to use python to detect the accessibility of website. > > Currently, I use urllib > > to obtain the remote webpage, and see whether it fails. But the problem is that > > the webpage may be very large; it takes too long time. Certainly, it > > is no need to download > > the entire page. Could you give me a good and fast solution? > > ? ? Thank you. > > -- > > ShenLei From cyberco at gmail.com Mon Jan 7 06:53:40 2008 From: cyberco at gmail.com (Berco Beute) Date: Mon, 7 Jan 2008 03:53:40 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> Message-ID: <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Cool! We knew it would happen one day :) What could be the reason? Python 3? Jython 2.2? Java's loss of sexiness? What I would like to know is what it was that boosted Python's popularity in 2004 (see http://www.tiobe.com/tiobe_index/Python.html). Equally interesting is the question why it dropped shortly after. 2B From sjmachin at lexicon.net Sat Jan 12 20:12:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 12 Jan 2008 17:12:51 -0800 (PST) Subject: Is unicode.lower() locale-independent? References: <47894DD2.1080503@v.loewis.de> Message-ID: <99b941b9-ea25-46fd-bb9e-fd6998380c51@y5g2000hsf.googlegroups.com> On Jan 13, 10:31 am, "Martin v. L?wis" wrote: > > The Unicode standard says that case mappings are language-dependent. > > I think you are misreading it. Ummm well, it does say "normative" as opposed to Fredrik's "informative" ... > 5.18 "Implementation Guides" says > (talking about "most environments") "In such cases, the > language-specific mappings *must not* be used." (emphasis also > in the original spec). > Here is the paragraph from which you quote: """ In most environments, such as in file systems, text is not and cannot be tagged with language information. In such cases, the language- specific mappings /must not/ be used. Otherwise, data structures such as B-trees might be built based on one set of case foldings and used based on a different set of case foldings. This discrepancy would cause those data structures to become corrupt. For such environments, a constant, language-independent, default case folding is required. """ This is from the middle of a section titled "Caseless Matching"; this section starts: """ Caseless matching is implemented using case folding, which is the process of mapping strings to a canonical form where case differences are erased. Case folding allows for fast caseless matches in lookups because only binary comparison is required. It is more than just conversion to lowercase. For example, it correctly handles cases such as the Greek sigma, so that and will match. """ Python doesn't offer a foldedcase method, and the attitude of 99% of users would be YAGNI; use this: foldedcase = lambda x: x.lower() What the paragraph you quoted seems to be warning about is that people who do implement a fully-principled foldedcase using the Unicode CaseFolding.txt file should be careful about offering foldedcaseTurkic and foldedcaseLithuanianDictionary -- both dangerous and YAGNI**2. This topic seems to be quite different to the topic of whether the results of unicode.lower does/should depend on the locale or not. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 09:12:56 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 15:12:56 +0100 Subject: Unknown cause to error (new to python) In-Reply-To: References: Message-ID: <478e10bd$0$27280$426a34cc@news.free.fr> Brandon Perry a ?crit : > Hi, I am having to compile a standalone version of python for the web > server I use (they don't allow access to /usr/bin/python). I posted > earlier about a GLib error, but I have fixed that now. I am very close > to getting this to work, but I am getting some weird errors. > > File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", > line 41, in ? > File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", line 71, in ? > File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", line 4, in ? > File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", line 4, in ? > File "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", line 15, in ? Sorry but my crystal ball is broken. Please post the *whole* traceback. From tjreedy at udel.edu Mon Jan 7 20:40:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 Jan 2008 20:40:28 -0500 Subject: code doesn't reference immutables? References: <5e6d3674-fddb-402f-9e5c-19afcd7fcc22@i7g2000prf.googlegroups.com> Message-ID: wrote in message news:5e6d3674-fddb-402f-9e5c-19afcd7fcc22 at i7g2000prf.googlegroups.com... | >From the manual: | | "code objects are immutable and contain no references (directly or | indirectly) to mutable objects" (3.2) | | I thought my code worked with both mutable and immutable objects. | Whassup? Consider the following: >>> def g(): return (1,2), [1,2] >>> dis.dis(g) 1 0 LOAD_CONST 3 ((1, 2)) 3 LOAD_CONST 1 (1) 6 LOAD_CONST 2 (2) 9 BUILD_LIST 2 12 BUILD_TUPLE 2 15 RETURN_VALUE >>> g.func_code.co_consts (None, 1, 2, (1, 2)) The code object stores the immutables 1, 2, and (1,2) but not the mutable [1,2]. Rather it stores immutable code to create the mutable list. I tried to see if the addition of closures violated the stipulation, using >>> def f(): l = [] def _(x): l.append(x) return _ but the inner code object only knows the list by the (immutable) name 'l', which does not count as a reference. Such code objects cannot be directly exec'ed but only executed indirectly by calling the function that wraps it and that has the reference to the in-this-case mutable object. (The mapping from 'l' to that object appears to be hidden.) Terry Jan Reedy From ShekinaAngel at webtv.net Thu Jan 31 01:43:56 2008 From: ShekinaAngel at webtv.net (Eddie Davis) Date: Wed, 30 Jan 2008 22:43:56 -0800 Subject: Wo killed Benazir Bhutto of Pakistan = NEOCON/ZIOCON many layers of deception References: Message-ID: <47a16282$0$26005$88260bb3@free.teranews.com> A moron posting from google? How unusual! -- Posted via a free Usenet account from http://www.teranews.com From ppetrick at gmail.com Mon Jan 21 20:44:19 2008 From: ppetrick at gmail.com (p.) Date: Mon, 21 Jan 2008 17:44:19 -0800 (PST) Subject: Transforming ascii file (pseduo database) into proper database References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> <47952796$0$17606$426a74cc@news.free.fr> Message-ID: <531e2dd1-6044-4a33-8651-9fc578a73bde@q39g2000hsf.googlegroups.com> Thanks to all for the ideas. I am familiar with external sorting. Hadn't considered it though. Will definitely be giving that a go, and then merging. Again, thanks all. From cokofreedom at gmail.com Fri Jan 18 05:03:10 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 18 Jan 2008 02:03:10 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> <7xy7aong73.fsf@ruckus.brouhaha.com> <4eba552a-3f9f-4bc7-81e7-150f109013ad@c23g2000hsa.googlegroups.com> Message-ID: <27215072-005b-4979-a27c-d328a947487b@d4g2000prg.googlegroups.com> > Hehe.. I remember seeing a similar one for Java and "Hello world" > using more and more elaborate abstractions and design patterns but I > can't find the link. > > George This is not linked to Java but deals with Hello World http://www.ariel.com.au/jokes/The_Evolution_of_a_Programmer.html From paul.hankin at gmail.com Thu Jan 17 18:59:44 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 17 Jan 2008 15:59:44 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> Message-ID: <657961e1-44ce-4fef-b3b7-5662878f28d8@f47g2000hsd.googlegroups.com> On Jan 17, 7:02?pm, George Sakkis wrote: > On Jan 17, 12:25 pm, Paul Hankin wrote: > > > > > On Jan 17, 4:38 pm, Bruno Desthuilliers > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > > Now there are very certainly smart solutions using itertools, but the > > > one I cooked is way too ugly so I'll leave this to itertools masters !-) > > > Here's my effort: > > > from itertools import izip, islice, chain, repeat > > > def padzip(*xs, **kw): > > ? ? pad = kw.get('padding', None) > > ? ? maxlen = max(len(x) for x in xs) > > ? ? return islice(izip(*[chain(x, repeat(pad)) for x in xs]), maxlen) > > > -- > > Paul Hankin > > And if the iterables don't necessarily support len(), here's a more > general solution: > > from itertools import repeat > > def izippad(*iterables, **kw): > ? ? pad = kw.get('padding', None) > ? ? next_pad = repeat(pad).next > ? ? getnext = [iter(iterable).next for iterable in iterables] > ? ? pending = size = len(iterables) > ? ? while True: > ? ? ? ? slice = [None] * size > ? ? ? ? for i in xrange(size): > ? ? ? ? ? ? try: slice[i] = getnext[i]() > ? ? ? ? ? ? except StopIteration: > ? ? ? ? ? ? ? ? pending -= 1 > ? ? ? ? ? ? ? ? if not pending: return > ? ? ? ? ? ? ? ? getnext[i] = next_pad > ? ? ? ? ? ? ? ? slice[i] = pad > ? ? ? ? yield slice Instead of counting the exceptions, we can limit the padding iterables by using an iterator that returns len(iterables) - 1 padding generators, use a sort of lazy chain, and then just izip. from itertools import izip, repeat def chain_next(xs, yg): for x in xs: yield x for y in yg.next(): yield y def izippad(*xs, **kw): padder = repeat(kw.get('padding', None)) padder_gen = repeat(padder, len(xs) - 1) return izip(*[chain_next(x, padder_gen) for x in xs]) -- Paul Hankin From gnewsg at gmail.com Sat Jan 12 12:50:16 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 12 Jan 2008 09:50:16 -0800 (PST) Subject: How to get user home directory on Windows References: <0bb27916-5416-47b2-b58c-1eb82ccb6d3e@k2g2000hse.googlegroups.com> Message-ID: Update. I found a way for getting the home directory of the user but it requires to validate the user by providing username+password: def get_homedir(username, password): token = win32security.LogonUser( username, None, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT ) return win32profile.GetUserProfileDirectory(token) What I'd like to do is avoiding the requirement of the password, the same way as if I would on UNIX where it would be enough just using the pwd module: >>> import pwd >>> pwd.getpwnam('user').pw_dir '/home/user' From researchbase at gmail.com Tue Jan 22 13:57:15 2008 From: researchbase at gmail.com (krishnakant Mane) Date: Wed, 23 Jan 2008 00:27:15 +0530 Subject: difflib confusion Message-ID: hello all, I have a bit of a confusing question. firstly I wanted a library which can do an svn like diff with two files. let's say I have file1 and file2 where file2 contains some thing which file1 does not have. now if I do readlines() on both the files, I have a list of all the lines. I now want to do a diff and find out which word is added or deleted or changed. and that too on which character, if not at least want to know the word that has the change. any ideas please? kk From ajaksu at gmail.com Mon Jan 7 14:55:12 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 7 Jan 2008 11:55:12 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Message-ID: On Jan 7, 9:53 am, Berco Beute wrote: > Cool! We knew it would happen one day :) > What could be the reason? Python 3? Jython 2.2? Java's loss of > sexiness? > > What I would like to know is what it was that boosted Python's > popularity in 2004 (seehttp://www.tiobe.com/tiobe_index/Python.html). > Equally interesting is the question why it dropped shortly after. > > 2B >From http://www.tiobe.com/index.htm?tiobe_index(and http://www.tiobe.com/tiobe_index/images/tpci_trends.png ) # Q: What happened to Java in April 2004? Did you change your methodology? A: No, we did not change our methodology at that time. Google changed its methodology. They performed a general sweep action to get rid of all kinds of web sites that had been pushed up. As a consequence, there was a huge drop for languages such as Java and C++. In order to minimize such fluctuations in the future, we added two more search engines (MSN and Yahoo) a few months after this incident. From alonie at unimelb.edu.au Thu Jan 10 16:40:58 2008 From: alonie at unimelb.edu.au (Andrew Lonie) Date: Fri, 11 Jan 2008 08:40:58 +1100 Subject: Elementtree 1.3 and xpath Message-ID: Hi I noticed that the xpath functionality of elementtree has been upgraded in version 1.3. However I can't seem to get the [postion] predicate to function. All the other new functionality seems to be working. Maybe I'm getting the syntax wrong?: >>> xml = ET.XML("""texttext2""") >>> elem = xml.find("tag[@att]") #Works fine - returns first tag element >>> elem = xml.find("tag[@att]/..") #Works fine - returns entire doc >>> elem = xml.find("tag[1]") # FAILS - returns nothing. Should return first tag element. Any help appreciated! Andrew From steven at REMOVE.THIS.cybersource.com.au Wed Jan 23 00:50:44 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 05:50:44 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> Message-ID: On Wed, 23 Jan 2008 04:58:02 +0000, Grant Edwards wrote: > On 2008-01-22, over at thepond.com wrote: > >> My expertise, if any, is in assembler. I'm trying to understand Python >> scripts and modules by examining them after they have been disassembled >> in a Windows environment. > > You can't dissassemble them, since they aren't ever converted to > assembler and assembled. Python is compiled into bytecode for a virtual > machine (either the Java VM or the Python VM or the .NET VM). There is the Python disassembler, dis, which dissassembles the bytecode into something which might as well be "assembler" *cough* for the virtual machine. -- Steven From python.list at tim.thechases.com Wed Jan 16 09:55:36 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 16 Jan 2008 08:55:36 -0600 Subject: Python help for a C++ programmer In-Reply-To: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> References: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> Message-ID: <478E1AE8.9090207@tim.thechases.com> > I want something like (C++ code): > > struct Response > { > std::string name; > int age; > int iData[ 10 ]; > std::string sData; > }; > > // Prototype > void Process( const std::vector& ); > > int main() > { > std::vector responses; > > while( /* not end of file */ ) > { > Response r; > > // Fill struct from file > r.name = /* get the data from the file */; > r.age = /* ... */; > r.iData[0] = /* ... */; > // ... > r.sData = /* ... */; > responses.push_back( r ); > } > > // Do some processing on the responses > Process( responses ); > } > > What is the preferred way to do this sort of thing in Python? Without knowing more about the details involved with parsing the file, here's a first-pass whack at it: class Response(object): def __init__(self, name, age, iData, sData): self.name = name self.age = age self.iData = iData self.sData = sData def __repr__(self): return '%s (%s)' % self.name def parse_response_from_line(line): name, age, iData, sData = line.rstrip('\n').split('\t') return Response(name, age, iData, sData) def process(response): print 'Processing %r' % response responses = [parse_response_from_line(line) for line in file('input.txt')] for response in responses: process(response) That last pair might be condensed to just for line in file('input.txt'): process(parse_response_from_line(line)) Things get a bit hairier if your input is multi-line. You might have to do something like def getline(fp): return fp.readline().rstrip('\n') def response_generator(fp): name = None while name != '': name = getline(fp) age = getline(fp) iData = getline(fp) sData = getline(fp) if name and age and iData and sData: yield Response(name, age, iData, sData) fp = file('input.txt') for response in response_generator(fp): process(response) which you can modify accordingly. -tkc From dongie.agnir at gmail.com Sat Jan 12 14:52:13 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Sat, 12 Jan 2008 11:52:13 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: Oh.. it seems my naiveness has stirred quite a discussion >_<... I must admit though, I've learned a bit about Python reading through this topic. Thanks to everyone who pointed out the flaws in the code. I'll see if I can come up with my own color tracking solution in a few weeks and post back here. Thanks! From killerkiwi2005 at gmail.com Sun Jan 27 01:49:08 2008 From: killerkiwi2005 at gmail.com (Jason Taylor) Date: Sun, 27 Jan 2008 19:49:08 +1300 Subject: Klik2 Project, Python apps on linux Message-ID: <94dd8f6f0801262249v1c07cf3em2548c470a523291e@mail.gmail.com> Hi We've been working on klik2, http://code.google.com/p/klikclient/, which implements OSX like application files on linux (with applications working on all distros), In which every user desktop application is 1 file We've run into a bit of a problem with python apps, so while we can run a complicated application like openoffice.org on ubuntu, fedora and suse from a single file we cant run any python applications such as jokosher gnome-specimen angrydd gausssum pathological quodlibet webboard istanbul exaile ccsm bittornado pessulus labyrinth wammu accerciser We'd like to fix this in a clean way with out resorting to nasty hacks involving $PYTHON_PATH. If any one has any suggestions please email me or drop by #klik on freenode Issue http://code.google.com/p/klikclient/issues/detail?id=144 Cheers Jason Taylor -- "Why isn't my life like a situation comedy? Why don't I have a bunch of friends with nothing better to do but drop by and instigate wacky adventures? Why aren't my conversations peppered with spontaneous witticisms? Why don't my friends demonstrate heartfelt concern for my well being when I have problems? ...I gotta get my life some writers." - Calven -------------- next part -------------- An HTML attachment was scrubbed... URL: From Louis.Soninhu at gmail.com Wed Jan 9 14:57:07 2008 From: Louis.Soninhu at gmail.com (Louis.Soninhu at gmail.com) Date: Wed, 9 Jan 2008 11:57:07 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> <962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.googlegroups.com> Message-ID: oops, it seems there are other 'meaningless' item, which actually caused the problem Thanks for helps From steve at REMOVE-THIS-cybersource.com.au Thu Jan 31 17:39:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 31 Jan 2008 22:39:02 -0000 Subject: helper function in a class' namespace References: <47a226bb$0$2982$ba620e4c@news.skynet.be> <47a22a17$0$8306$9b622d9e@news.freenet.de> Message-ID: <13q4jg6edfvi970@corp.supernews.com> On Thu, 31 Jan 2008 20:05:44 +0000, Stargaming wrote: > String concatenation is generally considered unpythonic, better use > string interpolation:: > > 'H> %s' % (M,) String concatenation is significantly faster than string interpolation. >>> import timeit >>> timeit.Timer("'H> %s' % M", "M = 'abcdef'").repeat() [1.3407769203186035, 0.69128704071044922, 0.56362509727478027] >>> timeit.Timer("'H> ' + M", "M = 'abcdef'").repeat() [0.69647812843322754, 0.69620108604431152, 0.65643787384033203] The danger with string concatenation comes from building up a string piece by piece: even though a single + is faster than a single %, a dozen concats will likely be MUCH slower than a single &. Also, the tuple above is totally unnecessary. 'H> %s' % M will work fine. -- Steven From jimgardener at gmail.com Thu Jan 3 10:49:19 2008 From: jimgardener at gmail.com (jimgardener at gmail.com) Date: Thu, 3 Jan 2008 07:49:19 -0800 (PST) Subject: how to use bool Message-ID: hi, i have some code where i set a bool type variable and if the value is false i would like to return from the method with an error msg.. being a beginner I wd like some help here class myclass: ......... def mymethod(self): success=True msg="all validation OK" success=validateSthing() if(success==False): msg="sthing failed" return (success,msg) dosomeprocessing() ..... success=validateSthingelse() if(success==False): msg="sthingelse failed" return (success,msg) domoreprocessing() .... return(success,msg) i would like to know if this way of doing this is OK..I have need of many kinds of validations in this ..is there a better way of doing this ? thank you From mail at danielcuschieri.com Wed Jan 2 14:04:36 2008 From: mail at danielcuschieri.com (Daniel Cuschieri) Date: Wed, 2 Jan 2008 20:04:36 +0100 Subject: Pickle problem In-Reply-To: <267762840801021100j62f1c25o772a1f54625ecc43@mail.gmail.com> References: <267762840801021100j62f1c25o772a1f54625ecc43@mail.gmail.com> Message-ID: <267762840801021104v4560d4c0pd424212000ee0070@mail.gmail.com> Hi, I used code similar to the one at http://www.onlamp.com/pub/a/python/2006/02/09/ai_decision_trees.html in order to build an ID3 decision tree using python. I obviously do not want to rebuild this tree every time i need to use it! so i tried to save it using pickle, after building it: >from cPickle import dump >output = open(path, 'wb') >dump(self.tree, output, -1) >output.close() As soon as I do this, I get the following error: >dump(self.tree, output, -1) >cPickle.PicklingError: Can't pickle : attribute lookup __builtin__.function failed How on earth can I solve this!? Rebuilding the tree every time is dumb! I'm sure there is a work around somehow, but I honestly don't have a clue as to what this might be! Any ideas please!? I'm totally lost and stuck! Thanks! Daniel -------------- next part -------------- An HTML attachment was scrubbed... URL: From terry at jon.es Mon Jan 21 06:52:00 2008 From: terry at jon.es (Terry Jones) Date: Mon, 21 Jan 2008 12:52:00 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 02:52:59 on Monday, 21 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: <18324.34656.19567.943223@terry.local> >>>>> "cokofreedom" == cokofreedom writes: cokofreedom> Terry, your technique is efficient and pretty readable! All cokofreedom> that could be added now is a way to output the data in a more cokofreedom> user-friendly print. Yes, and a fix for the bug Arnaud just pointed out :-) Below is code to print things more nicely for you. Terry from operator import * from itertools import izip def countdown(target, nums, numsAvail, value, partialSolution, solutions, ops=(add, mul, sub, div)): if value == target or not any(numsAvail): # Add the solution, if we're right. if value == target: solutions.add(tuple(partialSolution)) elif value is None: # Use each distinct number as a starting value. used = set() for i, num in enumerate(nums): if num not in used: numsAvail[i] = False used.add(num) partialSolution.append(num) countdown(target, nums, numsAvail, num, partialSolution, solutions, ops) numsAvail[i] = True partialSolution.pop() else: for op in ops: for i, num in enumerate(nums): if numsAvail[i]: numsAvail[i] = False moreAvail = any(numsAvail) try: lastNum, lastOp = partialSolution[-2:] except ValueError: lastNum, lastOp = partialSolution[-1], None # Don't allow any of: if not ( # Div: after mul, by 1, by 0, producing a fraction. (op == div and (lastOp == 'mul' or num <= 1 or value % num != 0)) or # If initial mul/add, canonicalize to 2nd operator biggest. ((op == mul or op == add) and lastOp is None and num > lastNum) or # Don't allow add or sub of 0. ((op == add or op == sub) and num == 0) or # Don't allow mult by 1. (op == mul and num == 1) or # Don't allow sub after add (allow add after sub). (op == sub and lastOp == 'add') or # If same op twice in a row, canonicalize operand order. (lastOp == op.__name__ and num > lastNum) ): partialSolution.extend([num, op.__name__]) countdown(target, nums, numsAvail, op(value, num), partialSolution, solutions, ops) del partialSolution[-2:] numsAvail[i] = True op2sym = { 'add' : '+', 'sub' : '-', 'mul' : '*', 'div': '/', } def pretty(s): out = [str(s[0])] lastOp = None for value, op in izip(*(iter(s[1:]),) * 2): if (op == 'mul' or op == 'div') and (lastOp == 'add' or lastOp == 'sub'): out.insert(0, '(') out.append(')') out.append(op2sym[op]) out.append(str(value)) lastOp = op return ''.join(out) for nums, target in ( ((100, 9, 7, 6, 3, 1), 253), ((100, 9, 7, 6, 3, 1), 234), ((2, 3, 5), 21), ((7, 8, 50, 8, 1, 3), 923), ((8, 8), 16), ((8, 8, 8), 8), ((8, 0), 8), ((7,), 8), ((), 8), ((8, 8, 8, 8), 32), ((2, 4, 5, 8, 25), 758), ((2, 3, 4, 100), 406), ): solutions = set() countdown(target, nums, [True,] * len(nums), value=None, partialSolution=[], solutions=solutions) print "%d solutions to: target %d, numbers = %s" % (len(solutions), target, nums) for s in sorted(solutions, cmp=lambda a, b: cmp(len(a), len(b)) or cmp(a, b)): print '\t', pretty(s) Sample output: 8 solutions to: target 253, numbers = (100, 9, 7, 6, 3, 1) (6*3-1)*9+100 (7*6+9)*3+100 (9-3)*7*6+1 (100-9-7)*3+1 ((3+1)*6-7)*9+100 (7+1)*6*3+100+9 (7+6+3+1)*9+100 (100-7-6)*3-9+1 19 solutions to: target 234, numbers = (100, 9, 7, 6, 3, 1) (6*3+7+1)*9 ((7+1)*9+6)*3 (7*3-1+6)*9 (7*6*3-100)*9 ((100-1)/3-7)*9 ((100-1)*7+9)/3 (100*7*3+6)/9 (100-9)/7*6*3 (100-9-7-6)*3 ((6+1)*100-7+9)/3 ((6-9)*7-1+100)*3 (7*3-6)*9-1+100 7*6*3-1+100+9 (100-1)/3*7-6+9 ((100-1)*7-9)/3+6 (100*7-6-1+9)/3 ((100-7)/3-1+9)*6 ((100-7)/3-6+1)*9 (100+9+7+1)/3*6 From bearophileHUGS at lycos.com Sat Jan 26 17:12:37 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 26 Jan 2008 14:12:37 -0800 (PST) Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> <7xy7acsx2l.fsf@ruckus.brouhaha.com> <8ddebd68-43dc-4320-86e1-887aadff4af3@d70g2000hsb.googlegroups.com> <7xmyqs722t.fsf@ruckus.brouhaha.com> <13pnbp9l8lk1j8b@corp.supernews.com> Message-ID: Steven D'Aprano: > Much to my surprise, the fastest solution I've tried appears to be a pure > Python version not even using max() at all. That version is easy to translate to other languages and you can probably find that Psyco makes it much faster still. Bye, bearophile From ggpolo at gmail.com Mon Jan 21 09:08:11 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 21 Jan 2008 12:08:11 -0200 Subject: Q: paramiko/SSH/ how to get a remote host_key In-Reply-To: <9077ed27-e9b1-47ca-b30e-918e3b50d517@e4g2000hsg.googlegroups.com> References: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> <9077ed27-e9b1-47ca-b30e-918e3b50d517@e4g2000hsg.googlegroups.com> Message-ID: 2008/1/21, DHR : > Thank you! Now it works and the code looks like this: > > import paramiko > import base64 > from paramiko import AutoAddPolicy, SSHClient > > client = paramiko.SSHClient() > client.set_missing_host_key_policy(AutoAddPolicy()) > client.connect('hostIP', username='uname', password='pass') > stdin, stdout, stderr = client.exec_command('ls') > for line in stdout: > print '... ' + line.strip('\n') > > client.close() Very nice =) Just an advice, you dont need to import base64. Method decode of strings allows you to specify encoding as 'base64' to perform needed operations. > > On Jan 21, 3:10 pm, "Guilherme Polo" wrote: > > 2008/1/21, DHR : > > > > > > > > > I am connecting from a WindowsXP SP2 machine. When using Putty as an > > > SSH client, if you connect for the first time then you get somethign > > > like this: > > > > > ''' The server's host key is not cached in the registry. You > > > have no guarantee that the server is the computer you > > > think it is. > > > The server's rsa2 key fingerprint is: > > > ssh-rsa 1024 7b:e5:6f:a7:f4:f9:81:62:5c:e3:1f:bf:8b:57:6c:5a > > > If you trust this host, hit Yes to add the key to > > > PuTTY's cache and carry on connecting. > > > If you want to carry on connecting just once, without > > > adding the key to the cache, hit No. > > > If you do not trust this host, hit Cancel to abandon the > > > connection. ''' > > > > > If I get it correctly, Putty is using such a command to recieve the > > > host_key the first time it connects to a remote SSH server. Then it > > > stores it into the registry. The question is how can I do it from > > > Python? > > > > When you call method connect of SSHClient it checks if server's > > hostname is in system_hot_keys or any local host keys, if it is not, > > the missing host key policy is used. The default policy is to reject > > the key and raise an SSHException, but you can change that default > > policy to AutoAddPolicy > > > > > > > > > > > > > Guilherme Polo wrote: > > > > 2008/1/21, DHR : > > > > > I'm trying to run the simpliest example form paramiko readme(Homepage: > > > > >http://www.lag.net/paramiko/), and > > > > > cannot find out how to get the remote SSH server host_key. > > > > > > > This is the code. It is supposed to connect to a remote SSH host and > > > > > execute an 'ls' command: > > > > > > > import paramiko, base64 > > > > > > > key = paramiko.RSAKey(data=base64.decodestring('AAA...')) > > > > > client = paramiko.SSHClient() > > > > > client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key) > > > > > client.connect('227.112.168.273', username='uname', password='pass') > > > > > stdin, stdout, stderr = client.exec_command('ls') > > > > > for line in stdout: > > > > > print '... ' + line.strip('\n') > > > > > > > client.close() > > > > > > > Now, if I understand it correctly I need to get somehow the host_key > > > > > from the server and > > > > > write it insted of the 'AAA...' thing. Is there a command to get the > > > > > host_key from a remote SSH > > > > > server? > > > > > -- > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > You need a key to connect to that server, so you should want this: > > > > > > keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) > > > > > > Then keys[hostname] should contain a RSAKey object that you are looking for > > > > > > -- > > > > -- Guilherme H. Polo Goncalves > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > > -- > > -- Guilherme H. Polo Goncalves > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From lists at cheimes.de Wed Jan 23 02:54:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 23 Jan 2008 08:54:19 +0100 Subject: python24 symbol file...pyhon24.pdb In-Reply-To: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> References: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> Message-ID: over at thepond.com wrote: > I've seen a few references on the net to a python24.pdb file. I assume > it's a symbol file along the lines of the pdb files issued by > microsoft for their products. Maybe I'm wrong. .pdb files (program database) are created by MS' compiler, see http://en.wikipedia.org/wiki/Program_database. Python doesn't ship the files. You have to compile Python yourself to get the pdb files. Christian From paul.hankin at gmail.com Sun Jan 6 08:15:49 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sun, 6 Jan 2008 05:15:49 -0800 (PST) Subject: how to use bool References: Message-ID: <7db0fe1e-bbc0-4eb1-ac54-db6d0750bad7@s12g2000prg.googlegroups.com> On Jan 3, 3:49?pm, jimgarde... at gmail.com wrote: > hi, i have some code where i set a bool type variable and if the value > is false i would like to return from the method with an error msg.. > being a beginner I wd like some help here > > class myclass: > ? ? ?......... > ? ? def ?mymethod(self): > ? ? ? ? ? ? ?success=True > ? ? ? ? ? ? ?msg="all validation OK" > ? ? ? ? ? ? ?success=validateSthing() > ? ? ? ? ? ? ?if(success==False): > ? ? ? ? ? ? ? ? ? ?msg="sthing failed" > ? ? ? ? ? ? ? ? ? ?return (success,msg) > > ? ? ? ? ? ? ?dosomeprocessing() > ? ? ? ? ? ? ?..... > ? ? ? ? ? ? ?success=validateSthingelse() > ? ? ? ? ? ? ?if(success==False): > ? ? ? ? ? ? ? ? ? ?msg="sthingelse ?failed" > ? ? ? ? ? ? ? ? ? ?return (success,msg) > ? ? ? ? ? ? ?domoreprocessing() > ? ? ? ? ? ? ? .... > ? ? ? ? ? ? ? ?return(success,msg) > > i would like to know if this way of doing this is OK..I have need of > many kinds of validations in this ..is there a better way of doing > this ? As everyone's pointed out, you should use exceptions for this sort of thing. > def mymethod(self): > success=True > msg="all validation OK" > success=validateSthing() > if(success==False): > msg="sthing failed" > return (success,msg) > > dosomeprocessing() > ..... > success=validateSthingelse() > if(success==False): > msg="sthingelse failed" > return (success,msg) > domoreprocessing() > .... > return(success,msg) As everyone else has pointed out, you should use exceptions for this sort of thing. But even without exceptions, you can write your code a lot more cleanly by omitting all the temporary variables. That way, you don't have to search around to see where things are used (eg. seeing where "all validation OK" is used requires you to read every line of your method). def mymethod(self): if not validateSthing(): return (False, "sthing failed") dosomeprocessing() .... if not validateSthingelse(): return (False, "sthingelse failed") domoreprocessing() ... return (True, "all validation OK") Isn't that a lot more readable? -- Paul Hankin From steveo at syslang.net Thu Jan 10 16:04:23 2008 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 10 Jan 2008 16:04:23 -0500 (EST) Subject: Another dumb scope question for a closure. In-Reply-To: References: Message-ID: On Wednesday, Jan 9th 2008 at 14:01 -0000, quoth Fredrik Lundh: =>Steven W. Orr wrote: => =>> So sorry because I know I'm doing something wrong. =>> =>> 574 > cat c2.py =>> #! /usr/local/bin/python2.4 =>> =>> def inc(jj): =>> def dummy(): =>> jj = jj + 1 =>> return jj =>> return dummy =>> =>> h = inc(33) =>> print 'h() = ', h() =>> 575 > c2.py =>> h() = =>> Traceback (most recent call last): =>> File "./c2.py", line 10, in ? =>> print 'h() = ', h() =>> File "./c2.py", line 5, in dummy =>> jj = jj + 1 =>> UnboundLocalError: local variable 'jj' referenced before assignment => =>http://docs.python.org/ref/naming.html has the answer: => => "If a name binding operation occurs anywhere within a code block, => all uses of the name within the block are treated as references => to the current block." Thanks. This helps a little. But I still don't understand something. If it's a question of a legal reference or not, I could buy it. But what's really happening is that it works if it's a read-only ref but fails if it's a write: >>> def inc(jj): ... def dummy(): ... print jj ... return dummy ... >>> f = inc(44) >>> f() 44 >>> f() 44 >>> f() 44 >>> The problem only happens if I try to modify jj. What am I not understanding? From fetchinson at googlemail.com Sat Jan 5 22:58:39 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 5 Jan 2008 19:58:39 -0800 Subject: Python web aps - A matter of security In-Reply-To: <53318.192.168.1.35.1199558462.webmail@192.168.1.35> References: <53318.192.168.1.35.1199558462.webmail@192.168.1.35> Message-ID: On 1/5/08, lloyd at paisite.com wrote: > Hello, > > I'm developing a Python-based web ap, but don't understand how to best > organize the modules and set permissions for maximum security. > > Here's how the Python code for my ap is organized: > > 1) I have Python modules in a project directory. The path to that directory > is in a *.pth file in the .*/pythonx-y/site-packages directory. > > Question: who should own these modules; what groups should have access, and > how should permissions be set? > > 2) I have high-level modules that import the worker-bee modules in the web > root directory tree that are called by the webserver. > > Questions: who should own these modules, what groups should have access, and > how should permissions be set? > > 3) Is there a better way to organize my Python modules? Are there other > security issues I should heed? > > Many thanks, > > Lloyd Are you using any of the many available web frameworks like turbogears, django, etc? If so your best option is probably to use the authentication/authorization capabilities of these frameworks and then you won't have to worry about it too much. Cheers, Daniel From castironpi at gmail.com Sat Jan 12 17:41:14 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 14:41:14 -0800 (PST) Subject: removeall() in list References: <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> <354c74f6-6e56-4e41-a686-56239aa4cea9@f47g2000hsd.googlegroups.com> <7x8x2uj3yb.fsf@ruckus.brouhaha.com> <0ad68aa8-735d-4cf0-b17a-d1f2be6af652@f47g2000hsd.googlegroups.com> <7x1w8mj27a.fsf@ruckus.brouhaha.com> <7x7iie3ku2.fsf@ruckus.brouhaha.com> Message-ID: <94c5da6f-00df-4d9e-9ed6-d4a3b8d67eed@j78g2000hsd.googlegroups.com> On Jan 12, 1:28 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > Will you engage with me over e-mail to discuss the Locker > > implementation I'm developing? Aaron > > I really can't, sorry. I'm finding it hard enough to follow over the > newsgroup. If you just have a single one of these lists, it's > probably simplest to do what Frederik Lundh suggested. The other > stuff we've discussed is mostly about how to organize having a lot of > them. Highlight from the working solution: def onfulfill( self, func, *args, **kwargs ): '''decorator launches its function in separate thread upon completion of func. todo: cancel and reference check.''' locfunc= Ref() def honorth(): result= self.op( func, *args, **kwargs ) locfunc.val( result ) def prefulfill( func ): locfunc.val= func th= threading.Thread( target= honorth ) th.start() return prefulfill From tteststudent at gmail.com Sat Jan 5 11:04:42 2008 From: tteststudent at gmail.com (ttest) Date: Sat, 5 Jan 2008 08:04:42 -0800 (PST) Subject: Request for help with Image color space conversion References: <8586a895-f238-4a22-a1bb-31c39f22b4cc@n20g2000hsh.googlegroups.com> Message-ID: <37094242-5728-466f-a3b9-c5ae76a9f3c5@s12g2000prg.googlegroups.com> > Reimplement colorsys.rgb_to_hsv() such that it operates on arrays instead of > scalars. Only minor modifications are necessary. > > -- > Robert Kern Thanks! I'll try and see if a newcomer like me can get his head around the array-centric modifications to colorsys. From asmodai at in-nomine.org Sat Jan 5 05:36:44 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 5 Jan 2008 11:36:44 +0100 Subject: Fortran to Python In-Reply-To: <13nstth7a3km06c@corp.supernews.com> References: <13nstth7a3km06c@corp.supernews.com> Message-ID: <20080105103643.GT82115@nexus.in-nomine.org> -On [20080104 19:21], Dennis Lee Bieber (wlfraed at ix.netcom.com) wrote: > If the FORTRAN is using single precision reals, I'd expect a >slow-down in Python just on that alone, as Python uses doubles as the >only float type. There is also the overhead of object access for each. In this case it uses complex*16 and real*8. Is a real*8 a single precision real? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Everything has beauty, but not everyone sees it. - Confucius From gagsl-py2 at yahoo.com.ar Wed Jan 30 18:09:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jan 2008 21:09:36 -0200 Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> Message-ID: En Wed, 30 Jan 2008 20:47:36 -0200, FireNWater escribi?: > I'm curious why the different outputs of this code. If I make the > dictionary with letters as the keys, they are not listed in the > dictionary in alphabetical order, but if I use the integers then the > keys are in numerical order. > > I know that the order of the keys is not important in a dictionary, > but I was just curious about what causes the differences. Thanks!! > > list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] > list2 = [1,2,3,4,5,6,7,8] > > Dictionary = dict(zip(list1, list2)) > print Dictionary > > Dictionary1 = dict(zip(list2, list1)) > print Dictionary1 Dictionaries use the hash value of the keys to distribute them in "buckets". Compare these: for key in list1: print key, hash(key) for key in list2: print key, hash(key) -- Gabriel Genellina From rong.xian at gmail.com Sun Jan 27 05:17:05 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 02:17:05 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> Message-ID: <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> On 1?24?, ??3?29?, "Gabriel Genellina" wrote: > En Thu, 24 Jan 2008 04:52:22 -0200, glacier escribi?: > > > According to your reply, what will happen if I try to decode a long > > string seperately. > > I mean: > > ###################################### > > a='???'*100000 > > s1 = u'' > > cur = 0 > > while cur < len(a): > > d = min(len(a)-i,1023) > > s1 += a[cur:cur+d].decode('mbcs') > > cur += d > > ###################################### > > > May the code above produce any bogus characters in s1? > > Don't do that. You might be splitting the input string at a point that is > not a character boundary. You won't get bogus output, decode will raise a > UnicodeDecodeError instead. > You can control how errors are handled, see http://docs.python.org/lib/string-methods.html#l2h-237 > > -- > Gabriel Genellina Thanks Gabriel, I guess I understand what will happen if I didn't split the string at the character's boundry. I'm not sure if the decode method will miss split the boundry. Can you tell me then ? Thanks a lot. From asmodai at in-nomine.org Fri Jan 4 10:23:38 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jan 2008 16:23:38 +0100 Subject: Fortran to Python In-Reply-To: <477E48B4.1090809@chamonix.reportlab.co.uk> References: <20080104132119.GK82115@nexus.in-nomine.org> <20080104144712.GL82115@nexus.in-nomine.org> <477E48B4.1090809@chamonix.reportlab.co.uk> Message-ID: <20080104152338.GN82115@nexus.in-nomine.org> -On [20080104 15:56], Robin Becker (robin at reportlab.com) wrote: >you probably want to look at numpy an extension that handles lots of matrix >things with great ease. I think it now lives at http://scipy.org/ Yeah, I am aware of SciPy/NumPy, but aside from these two calls to do this inverse matrix calculation the rest is just stock mathematics, supported by Python. I am trying to avoid another external dependency if I can. :) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Time is merely a residue of Reality... From cbmeeks at gmail.com Wed Jan 16 14:51:46 2008 From: cbmeeks at gmail.com (cbmeeks) Date: Wed, 16 Jan 2008 11:51:46 -0800 (PST) Subject: Help with python shell References: <2706aa71-b072-4cbb-a7d9-abbfadd7d35a@c4g2000hsg.googlegroups.com> <5v7100F1kmtinU2@mid.uni-berlin.de> <5v74kaF1kt3a3U1@mid.uni-berlin.de> Message-ID: <93c924ff-f25a-48cf-ac1d-1b179bcaebf3@c4g2000hsg.googlegroups.com> On Jan 16, 2:35 pm, "Diez B. Roggisch" wrote: > cbmeeks schrieb: > > > > > On Jan 16, 1:33 pm, "Diez B. Roggisch" wrote: > >> cbmeeks schrieb: > > >>> I just upgraded my Python install up to version 2.5.1 (from 2.4.x) > >>> using source code and compiling. > >>> Everything went fine until I enter the command line mode and press any > >>> arrow keys. > >>> When I press UP arrow, I was getting my previous command as always but > >>> now I get: ^[[A > >>> What can I do to fix this?? > >> Compiling with readline support? I guess that's missing. > > >> Diez > > > I tried ./configure --enable-readline but that didn't do the trick. > > ARG!! This is annoying. > > You don't just need to enable it - the readline lib needs to be > installed, including the possible devel-package (If you are under linux) > for the headers. > > Diez That worked! I had to install readline-devel and rebuild with --enable-readline Thanks!!!!! cbmeeks http://codershangout.com From peng.kyo at gmail.com Thu Jan 17 02:20:36 2008 From: peng.kyo at gmail.com (J. Peng) Date: Thu, 17 Jan 2008 15:20:36 +0800 Subject: assigning values in python and perl In-Reply-To: <87tzlddjq6.fsf@mulj.homelinux.net> References: <87tzlddjq6.fsf@mulj.homelinux.net> Message-ID: <18c1e5f20801162320g6e25e4acw62fe08f451498051@mail.gmail.com> On Jan 17, 2008 2:55 PM, Hrvoje Niksic wrote: > > @$ref = (4, 5, 6) intentionally assigns to the same list pointed to by > the reference. That would be spelled as x[:] = [4, 5, 6] in Python. > What Python does in your example is assign the same as Perl's $ref = > [4, 5, 6]. So they're not so different after all. > Yup,you're so right.This test below in perl is the same as in python. So at before I may got mistaken by myself.Thanks all. $ cat t1.pl sub test { my $ref = shift; $ref = [4,5,6]; } my @a = (1,2,3); test(\@a); print "@a"; $ perl t1.pl 1 2 3 From mdfranz at gmail.com Tue Jan 1 17:31:30 2008 From: mdfranz at gmail.com (Matthew Franz) Date: Tue, 1 Jan 2008 16:31:30 -0600 Subject: Network Module In-Reply-To: <52da23100801010540s122337aci470e2ee4fa85fa1b@mail.gmail.com> References: <52da23100801010540s122337aci470e2ee4fa85fa1b@mail.gmail.com> Message-ID: <33acb3db0801011431h341e23f5mf6a1df91e3cc209f@mail.gmail.com> Why not just wrap netstat for what you need? or you might be able to get from /proc entries? Or look at http://www.psychofx.com/psi/trac/wiki/ (PSI Tools) If you want interface statistics you can process the CSV output of bwm-ng (http://www.gropp.org/?id=projects&sub=bwm-ng) - mdf On Jan 1, 2008 7:40 AM, Sunil Ghai wrote: > Hello people, > I am searching for a python module to interact with the network > connections/interfaces. For example the number of active TCP/IP connections > via eth0 interface and all that stuff. > I have done googling and search at pythonorg but couldn't find any. > > Thanks > Sunil Kumar Ghai > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matthew Franz http://www.threatmind.net/ From f.guerrieri at gmail.com Tue Jan 8 05:37:48 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Tue, 8 Jan 2008 11:37:48 +0100 Subject: Paid subscription Python magazines In-Reply-To: <13o6jthqrl90o2d@corp.supernews.com> References: <13o6jthqrl90o2d@corp.supernews.com> Message-ID: <79b79e730801080237s24235e6ap268af62bf3f255ba@mail.gmail.com> On Jan 8, 2008 11:17 AM, Jon Harrop wrote: > > Are there any Python magazines that you can pay to subscribe to? (either > paper or on-line). > Python Magazine comes to mind www.pythonmagazine.com I am subscribed and find it very good. Francesco From ganeshborse at gmail.com Thu Jan 10 05:07:34 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 10 Jan 2008 02:07:34 -0800 (PST) Subject: Import of cStringIO failing with "undefined symbol: PyObject_SelfIter" on python-2.3.3-88.9 Message-ID: <13cb45c0-5b5d-4151-9797-d851ed3ad544@i7g2000prf.googlegroups.com> I am importing cStringIO module in my PythonC++ embedded program. The import is failing with the following error: ImportError: /usr/lib/python2.3/lib-dynload/cStringIO.so: undefined symbol: PyObject_SelfIter I have python-2.3.3-88.9.x86 installed on my machine. Why is this error coming? how can I resolve this undefined symbol? Do I need to import anything before this? From azam.farooq3 at gmail.com Tue Jan 29 01:50:13 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Mon, 28 Jan 2008 22:50:13 -0800 (PST) Subject: Do You Want a GSM Mobile with Amazing Features? Please click here Message-ID: <8be6326a-f91c-431c-8c06-5a78a41ac20c@s8g2000prg.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 ganeshborse at gmail.com Tue Jan 15 06:01:49 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Tue, 15 Jan 2008 03:01:49 -0800 (PST) Subject: how to set sys.stderr to object of cStringIO type References: <45c94bc5-4bbe-491d-bcdd-3cb904cb552b@f47g2000hsd.googlegroups.com> Message-ID: <740646f5-f2e7-4b5f-a02d-aec8367e68b9@s8g2000prg.googlegroups.com> On Jan 15, 5:45?pm, grbgooglefan wrote: > I am in a perculiar situation. I want to use PyRun_SimpleString for > creating Python functions in embedded Python in C++. > But there could be cases when Python function code compilation could > fail & PyRun_SimpleString will return -1 as return status. At this > time, it prints the error message to sys.stderr. > So, we do not have any control or cannot use that message to show to > user to correct the errors in the function code. > I could assign an object of cStringIO type to sys.stderr at Python > command prompt as below: > > >>> import sys > >>> import cStringIO > >>> obj=cStringIO.StringIO() > >>> sys.stderr=obj > > And then using the obj.getvalue(), I could print exceptions printed to > sys.stderr. > > But, I am not able to figure out, how can I do this same thing in > Python/C API in my program using Py* functions? > > How do we set the "sys.stderr" to cStringIO object from Python > embedded in C++ or C? > > Should I be using PyFile_FromFile for convert the cStringIO object? > Please help. I have got a solution for this. Would like to know if this is the correct way or will it cause any problems if program runs for long time? /***************************************************/ /--1st stage is assign object of cStringIO to sys.stderr at initialization /-- once that is done, we can call getvalue() on that object on every error. /-----------------------------------------------------/ PyObject *_pPyobStringIO; PyObject *_pPyGetValFunc; _pPyobStringIO=NULL; _pPyGetValFunc=NULL; PyObject *obFuncStringIO = NULL; int ret1 = 0; // Import cStringIO module PyObject * modStringIO = PyImport_ImportModule("cStringIO"); if(PyErr_Occurred() || modStringIO == NULL){ printf("pyParserEvaluator::Init::PyImport cStringIO failed:"); PyErr_Print(); goto PY_INIT_ERR; } // get StringIO constructor obFuncStringIO = PyObject_GetAttrString(modStringIO, "StringIO"); if(PyErr_Occurred() || obFuncStringIO == NULL){ printf("pyParserEvaluator::Init: cant find cStringIO.StringIO:"); PyErr_Print(); goto PY_INIT_ERR; } // Construct cStringIO object _pPyobStringIO = PyObject_CallObject(obFuncStringIO, NULL); if(PyErr_Occurred() || _pPyobStringIO==NULL){ printf("pyParserEvaluator::Init: cStringIO.StringIO() failed:"); PyErr_Print(); goto PY_INIT_ERR; } // get the getvalue function ptr _pPyGetValFunc = PyObject_GetAttrString(_pPyobStringIO, "getvalue"); if(PyErr_Occurred() || _pPyGetValFunc==NULL){ printf("pyParserEvaluator::Init: cant find getvalue function:"); PyErr_Print(); goto PY_INIT_ERR; } // try assigning this object to sys.stderr ret1 = PySys_SetObject("stderr", _pPyobStringIO); if(ret1 != 0){ printf("failed to assign _pPyobStringIO to stderr\n"); } else printf("assigned _pPyobStringIO to stderr\n"); PY_INIT_ERR: printf("pyParseEvaluator::pyParseEvaluator failed\n"); / **********************************************************************/ int ret = PyRun_SimpleString(strFunction); if(ret != 0){ // call getvalue() method in StringIO instance PyObject *obResult=NULL; obResult = PyObject_CallObject(_pPyGetValFunc, NULL); if(PyErr_Occurred() || obResult==NULL){ printf("getvalue() failed\n"); return -1; } else printf("PyObject_CallObject on getvalue is ok\n"); // did getvalue return a string? if(!PyString_Check(obResult)){ printf("getvalue() did not return error string\n"); return -1; } else printf("getvalue returned string object\n"); // retrieve error message string from this object char *sresult = NULL; if(NULL != (sresult = PyString_AsString(obResult))){ printf("result string was [%s]\n",sresult); } } /**********************************************************/ From mattheww at chiark.greenend.org.uk Tue Jan 8 16:22:42 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 08 Jan 2008 21:22:42 +0000 (GMT) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> <0b11ce6b-3565-41b6-8e63-17cb941b8197@i7g2000prf.googlegroups.com> <105594e7-39bd-4e6a-9d21-71ba6b1fabfa@e10g2000prf.googlegroups.com> Message-ID: Paul McGuire wrote: > While not required by any means, you will also find it handy to follow > *every* entry in the list with a comma, even the last one in the list > (this is legal Python). That is, in your example: > > foo =3D [ > 'too long', > 'too long too', > 'too long too', > 'last item', > ] > > Later on when you want to reorder the items, then you can just copy/ > paste whole lines, even if moving to or from the bottom of the list. > This is also a good argument for putting the closing ']' on its own > line, instead of on the same line as the last item. The other good reason for doing these two things is that they fit better with the line-based rules that most source code management systems use for merging. -M- From timr at probo.com Thu Jan 31 02:35:50 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 31 Jan 2008 07:35:50 GMT Subject: Telnet Program References: <777d417c-6016-4a44-8d5e-8de6bf604e9a@e6g2000prf.googlegroups.com> <87zluo77qr.fsf@merkury.smsnet.pl> <13q026bb5f1i669@corp.supernews.com> Message-ID: <1fu2q3l0aeh6uj4s6duetlak6n2jovn42p@4ax.com> Dennis Lee Bieber wrote: >On Tue, 29 Jan 2008 16:23:28 -0800 (PST), "paul.zorn at gmail.com" > declaimed the following in comp.lang.python: > >> Telnet(192.168.2.75,5000): send '\n\n' > > Should that be "\r\n" (or, if two lines is intended, "\r\n\r\n") I don't think so. The RFC quote you provided talks about the physical manifestation of CR and LF on a terminal, and says that a Telnet server must be prepared to handle various combinations, but if you think about a real Telnet session, the user is going to press CR when its through with a line. Thus, I would think he needs either \r\r or \n\n. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From castironpi at gmail.com Sat Jan 12 03:37:25 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 00:37:25 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> Message-ID: <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> On Jan 11, 8:04 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > Could you: > > > lockerA= Locker( listA, listB ) > > lockerA.op( listB.reverse ) > > lockerA.op( listA.pop ) > > > Where lockerA ops acquire the locks on all its threads? > > I don't understand that question. The main thing to understand is > that multi-threaded programming is complicated (especially if you're > after high performance), and very difficult to get right without > knowing exactly what you're doing. The generally preferred approach > in Python is to keep things simple at some performance cost. > > Your Locker approach above looks sort of reasonable if you can be > absolutely sure that nothing else can mess with listA or listB > concurrently with those locker operations. Normally you would put > listA and listB into a single object along with a lock, then do > operations on that object. > > You might check the Python Cookbook for some specific recipes and > sample code for this stuff. If you've used Java, Python's general > threading mechanisms are similar, but they are in the library rather > than built into the language (i.e. there is no "synchronized" > keyword, you have to do that locking explicitly). > > What is the actual application, if you don't mind saying? Are you > sure that you really need concurrency? I'm writing an NxN observer pattern, mostly for my own personal exploration. Two threads -might- be calling 'Disconnect' at the same time, and I can't even guarantee that the function runs properly. for emelem in [ e for e in emlist if e.func is func ]: try: emlist.remove( emelem ) except ValueError: pass From stefan.behnel-n05pAM at web.de Sun Jan 27 04:05:24 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 27 Jan 2008 10:05:24 +0100 Subject: how to make format operator % work with unicode as expected In-Reply-To: References: <13po55nc0q0s06@corp.supernews.com> Message-ID: <479C4954.6030400@web.de> Ever heard the word "PLONK"? Peter Pei harshly top-posted: > You didn't understand my question, but thanks any way. > > Yes, it is true that %s already support unicode, and I did not > contradict that. But it counts the number of bytes instead of > characters, and makes things like %-20s out of alignment. If you don't > understand my assertion, please don't argue back and I am only > interested in answers from those who are qualified. > ============================================================== > > "Steven D'Aprano" wrote [pretty qualifying response stripped] From nagle at animats.com Mon Jan 21 15:36:33 2008 From: nagle at animats.com (John Nagle) Date: Mon, 21 Jan 2008 12:36:33 -0800 Subject: Is there a portable way to tell if data is available on a pipe? In-Reply-To: <13p9le6nu1u9l4d@corp.supernews.com> References: <47941112$0$36375$742ec2ed@news.sonic.net> <13p9le6nu1u9l4d@corp.supernews.com> Message-ID: <47950101$0$36322$742ec2ed@news.sonic.net> Scott David Daniels wrote: > John Nagle wrote: >> I need some way to find out if a pipe has data available for >> a read without blocking if it does not. > ... >> I'd like to avoid having a thread to manage each pipe, but if I >> have to, so be it. > > Well, without granting your wish, put a Queue.Queue "in front" of > each pipe. The per-pipe thread ... That's what I thought. Oh, well. John Nagle From fredrik at pythonware.com Wed Jan 9 15:55:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 21:55:15 +0100 Subject: Another dumb scope question for a closure. In-Reply-To: <741fd030801091246h491ffbccp4cbbb3f947aeac63@mail.gmail.com> References: <20080109152403.433b113a@bhuda.mired.org> <741fd030801091246h491ffbccp4cbbb3f947aeac63@mail.gmail.com> Message-ID: Ben Fisher wrote: > One way to get this to work is: > > def inc(jj): > def dummy(jj = jj): > jj = jj + 1 > return jj > return dummy > > h = inc(33) > print h() > > It's not very pretty though, especially when you have many variables > you want to have in the inner scope. Default argument binding allows you to bind to an outer object rather than a name, but it doesn't help if you want to update the object: >>> def inc(jj): ... def dummy(jj = jj): ... jj = jj + 1 ... return jj ... return dummy ... >>> h = inc(33) >>> print h() 34 >>> print h() 34 >>> print h() 34 >>> print h() 34 From ivanlan9 at gmail.com Tue Jan 29 10:46:09 2008 From: ivanlan9 at gmail.com (Ivan Van Laningham) Date: Tue, 29 Jan 2008 08:46:09 -0700 Subject: Problem with Tkinter scrollbar callback In-Reply-To: References: Message-ID: Nope: 'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '300'), And even after I set it, it looks funny: 'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '1000'), And when I try it with the new repeatdelay (1000), the only thing that has changed is that it waits 1000 milliseconds before exhibiting the same uncontrolled growth as before. Metta, Ivan On Jan 25, 2008 5:49 PM, Russell E. Owen wrote: > In article , > "Ivan Van Laningham" wrote: > > > Hi All-- > > That helps. Doing a get() on the scrollbar before a set(0.0,0.0) > > returns a 4-tuple: (0.0, 0.0, 0.0, 0.0) ! I did the set(0.0,0.0) > > and now the callback gets the correct number of arguments. > > > > However, I'm still getting the weird behaviour when clicking the > > arrowheads--and the heads are all I want. They act like they've been > > set to a keybounce timeout of about a millisecond. ... The arrow > > click increments the number of cells in a table row (effectively), and > > it shoots up from 5 to 26 columns almost instantly (that's the > > internal max I set). > > Is the scroll bar's repeatinterval set to a reasonable value? > > -- Russell > > -- > 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 gregturn at mindspring.com Fri Jan 11 15:44:16 2008 From: gregturn at mindspring.com (Goldfish) Date: Fri, 11 Jan 2008 12:44:16 -0800 (PST) Subject: virtualpython / workingenv / virtualenv ... shouldn't this be part of python References: <4787981c$0$90268$14726298@news.sunsite.dk> Message-ID: On Jan 11, 11:45 am, Christian Heimes wrote: > Damjan wrote: > > My question is, shoudn't it be enough to set PYTHONPATH and everything > > automagically to work then? Is there some work done on this for python 3.0 > > or 2.6 perhaps? > > I'm working on a PEP for a per user site dir for 2.6 and 3.0 > > Christian What about security holes, like a malicious version of socket getting downloaded into a user's directory, and overriding the default, safe version? Don't forget that in your PEP. From cokofreedom at gmail.com Mon Jan 21 05:52:59 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 21 Jan 2008 02:52:59 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: On Jan 21, 11:29 am, Terry Jones wrote: > >>>>> "dg" == dg google groups writes: > > dg> It's great how many different sorts of solutions (or almost solutions) > dg> this puzzle has generated. Speedwise, for reference my solution posted > dg> above takes about 40 seconds on my 1.8GHz laptop, and the less elegant > dg> version (on my webpage linked to in the original post) takes about 15 > dg> seconds. It seems to me like surely this problem can be more > dg> efficiently solved than that? > > dg> Paul: 758 = 8+(5*((2+4)*25)) > > For this I get: > > 2 solutions to: target 758, numbers = (2, 4, 5, 8, 25) > (4, 2, 'add', 25, 'mul', 5, 'mul', 8, 'add') > (25, 4, 'mul', 5, 'sub', 8, 'mul', 2, 'sub') > > real 0m0.118s > user 0m0.074s > sys 0m0.044s > > Terry Terry, your technique is efficient and pretty readable! All that could be added now is a way to output the data in a more user-friendly print. (it currently reminds me of Lisp operands done backwards :) ) Also perhaps the creation of a random generator for the 6 numbers and the target :) I do not remember if countdown enforced that it must be possible to actually get the target, you could also get close to it. (I believe you would get different points depending on this) Will have to read up on how many large numbers you can have, as well as small. Currently I think it is you can take up to 4 large numbers, and up to 6 small numbers to a total of 6. (you must always have 6 numbers to work with) From alejandro.valdez at gmail.com Fri Jan 25 17:59:41 2008 From: alejandro.valdez at gmail.com (alejandro.valdez at gmail.com) Date: Fri, 25 Jan 2008 14:59:41 -0800 (PST) Subject: How to modify the content of an email Message-ID: <3f39a8c3-7e47-4971-84db-f26f03e0abae@d70g2000hsb.googlegroups.com> Hello, I'm trying to make a python script that take an email in (raw) text format, and add a footer to the text (or html) body of the email. I'm aware of the email and email.mime modules, but I can't figure out how to identify 'the main text (or html) content' from the email, and how to be sure that I don't incorrectly identify a txt (or html) attach as the main content of the email. By 'main text (or html) content' I mean the text (or html) that is showed by a Mail User Agent when it display the email to the recipient. Thanks in advance. From mail at timgolden.me.uk Wed Jan 23 11:42:45 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Jan 2008 16:42:45 +0000 Subject: Python printing! In-Reply-To: References: Message-ID: <47976E85.9080208@timgolden.me.uk> SMALLp wrote: > Hy. How to use printer in python. I goggled little i I found only some > win32 package which doesn't look processing for cross platform > application. (I'm using USB printer and I tried to f=open("dev/...") usb > port but i couldn't fond where printer is! You perhaps want to look at something like wxPython where someone's already done the dirty work for you: http://wiki.wxpython.org/Printing I assume other x-platform toolkits like Qt have similar facilities. Python itself is a bit lower-level than that and as far as I know no-one's put together a x-platform printing module, so you could be the first. TJG From minger at gmail.com Sat Jan 5 21:59:59 2008 From: minger at gmail.com (Ming) Date: Sat, 5 Jan 2008 18:59:59 -0800 (PST) Subject: MRO Error on Multiple Inheritance? References: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> <87prwhp4l8.fsf@benfinney.id.au> Message-ID: <9b389f23-c8c4-461e-ba09-031e12397c59@l1g2000hsa.googlegroups.com> Thanks for the all the replies. CPP2e is the Second Edition of the book "Core Python Programming." On Jan 4, 6:13 pm, Ben Finney wrote: > Ming writes: > > I'm working through Wesley Chun's CPP2e and got this error on 13.11.1, > > pp 548 where his interpreter snippet shows no problems: > > I don't know what a "CPP2e" is. Is it a book? Can you give the ISBN? > > > > > ActivePython 2.5.1.1 (ActiveState Software Inc.) b > > Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [ > > win32 > > Type "help", "copyright", "credits" or "license" f > > >>> class A(object): pass > > ... > > >>> class B(A): pass > > ... > > >>> class C(B): pass > > ... > > >>> class D(A, B): pass > > ... > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: Error when calling the metaclass bases > > Cannot create a consistent method resolution > > order (MRO) for bases A, B > > > (I submitted the problem to the author but I'm not sure I'll ever hear > > back.) I'm guessing that this kind of diamond inheritance is > > prohibited by the interpreter, and that his lack of error messages > > from the interpretation is due to actually leaving out the "class > > B(A): pass" Can someone shed light? Thanks. > > That's not an example of diamond inheritance > because classes A > and B are not distinct classes with a *common* base. Instead, they're > in a direct parent-child relationship. > > So there's no sense in defining class D to inherit from both A *and* > B. To get a descendent of both those classes, inheriting from B is > sufficient. It should rather be:: > > class D(B): pass > > -- > \ "Pinky, are you pondering what I'm pondering?" "Uh, I think so, | > `\ Brain, but we'll never get a monkey to use dental floss." -- | > _o__) _Pinky and The Brain_ | > Ben Finney From steve at REMOVE-THIS-cybersource.com.au Wed Jan 30 09:06:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 30 Jan 2008 14:06:26 -0000 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> Message-ID: <13q1132200cf537@corp.supernews.com> On Tue, 29 Jan 2008 06:48:59 -0600, Peter Schuller wrote: >> You can also put, in animal/__init__.py: >> from monkey import Monkey >> and now you can refer to it as org.lib.animal.Monkey, but keep the >> implementation of Monkey class and all related stuff into >> .../animal/monkey.py > > The problem is that we are now back to the identity problem. The class > won't actually *BE* org.lib.animal.Monkey. It what sense will it not be? Why do you care so much about where the source code for Monkey is defined? If you actually want to read the source, you might need to follow the chain from "animal", see that Monkey is imported from "monkey", and go look at that. But the rest of the time, why would you care? There is a very good reason to care *in practice*: if there is code out there that assumes that the source code from Monkey is in the file it was found in. In practice, you might be stuck needing to work around that. But that's not a good reason to care *in principle*. In principle, the actual location of the source code should be an implementation detail of which we care nothing. It's possible that the source for Monkey doesn't exist *anywhere*. It is important to deal with buggy tools. But the correct way to do so is to fix the bugs, not to throw away perfectly good abstractions. -- Steven From sergio at invalid.invalid Sun Jan 20 07:00:18 2008 From: sergio at invalid.invalid (Sergio) Date: Sun, 20 Jan 2008 13:00:18 +0100 Subject: convivenza In-Reply-To: <1ib0fd9.i462gwrkkb06N%riko@despammed.com> References: <0690b38a-d587-45f5-95e9-fc1216da4b93@l1g2000hsa.googlegroups.com> <1i9np5k.uxildouuzt58N%riko@despammed.com> <477608c1$0$17940$4fafbaef@reader1.news.tin.it> <1iaktue.wi85ml1ro93ycN%riko@despammed.com> <1ib0fd9.i462gwrkkb06N%riko@despammed.com> Message-ID: crxor 666 wrote: > >> Evidentemente equivocher? sul termine "potenza di un linguaggio", ma >> dubito che io possa scrivere un device driver in Python, >> indipendentemente dalla potenza processore o dall'esistenza di un >> compilatore Python (ho preso per esempio il Python ma potevo usare molti >> altri linguaggi). > E perch?? In particolare questa ? una questione di libreria pi? che di > linguaggio. Questo oggetto per dire ti fa scrivere driver per oggetti > USB in Python: > Per prima cosa non ? scritta in Python ma in C, ma in ogni caso mi pare una libreria per l'accesso a dispositivi USB, non una libreria per scrivere driver in Python, che sono due cose ben diverse. Il fatto che le librerie Python (come quelle di altri linguaggi) siano scritte per la maggior parte in un linguaggio diverso non dipende solo da questioni prestazionali, ma anche dal fatto che certe cose sono impossibili in Python. > Come sopra, il kernel non ? in Python. Ciao. From thermostat at gmail.com Tue Jan 15 10:50:42 2008 From: thermostat at gmail.com (Dan) Date: Tue, 15 Jan 2008 07:50:42 -0800 (PST) Subject: Interesting Thread Gotcha References: Message-ID: On Jan 15, 10:07 am, "Hendrik van Rooyen" wrote: > I thought I would share this nasty little gotcha with the group. > > Consider the following code fragment: > > > print 'starting kbd thread' > keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) > print 'starting main loop' > error = Mainloop(s,port_q,active_q_list) > > > It produces, as output, the following: > > starting kbd thread > we get here - a > > It does not print 'starting main loop', the Mainloop routine > is never executed, and no exceptions are raised. > > Here is the offending routine that seems to capture the control: > > > def kbd_driver(out_q,in_q): > """ > thread to look for keyboard input and to put it on the queue out_q > also looks for replies on in_q and prints them > """ > > kbdname = '/dev/stdin' > > kbd = open(kbdname,'r+',1) # Reading, line buffered > > unblock(kbd) # Call the magic to unblock keyboard > print 'we get here - a' > while True: > > try: > d = kbd.readline() # see if any kbd input > except: > IOError > try: > msg=in_q.get(block=False) > except Queue.Empty: > time.sleep(0.1) > continue > print msg > time.sleep(0.1) > continue > d = d.rstrip() # get rid of line feed > out_q.put([d + '\r',in_q]) # add a carriage return and return q and send > to port > > > The unblock is a routine that unblocks a port using fcntl - it > is not the problem. In case you don't believe me, here it is: > > def unblock(f): > """Given file 'f', sets its unblock flag to true.""" > > fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) > > I will post the solution tomorrow when I read my mail, > if no one has spotted it by then. > > - Hendrik >>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) Needs to be >>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) Commas are important! -Dan From MartinRinehart at gmail.com Mon Jan 7 08:25:55 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Mon, 7 Jan 2008 05:25:55 -0800 (PST) Subject: I'm searching for Python style guidelines Message-ID: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> There's a lot of dumb stuff out there. "Algorithms should be coded efficiently ..." Thanks, I'll keep that in mind. van Rossum's guidelines tend toward "pick something and stick to it" which is OK if you have enough experience to pick something Pythonic. I'm a relative newbie, not qualified to pick. Anything written somewhere that's thorough? Any code body that should serve as a reference? From alnilam at gmail.com Tue Jan 22 08:44:45 2008 From: alnilam at gmail.com (Alnilam) Date: Tue, 22 Jan 2008 05:44:45 -0800 (PST) Subject: HTML parsing confusion References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> Message-ID: <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> > Pardon me, but the standard issue Python 2.n (for n in range(5, 2, > -1)) doesn't have an xml.dom.ext ... you must have the mega-monstrous > 200-modules PyXML package installed. And you don't want the 75Kb > BeautifulSoup? I wasn't aware that I had PyXML installed, and can't find a reference to having it installed in pydocs. And that highlights the problem I have at the moment with using other modules. I move from computer to computer regularly, and while all have a recent copy of Python, each has different (or no) extra modules, and I don't always have the luxury of downloading extras. That being said, if there's a simple way of doing it with BeautifulSoup, please show me an example. Maybe I can figure out a way to carry the extra modules I need around with me. From omer at no-log.org Fri Jan 11 09:48:34 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Fri, 11 Jan 2008 15:48:34 +0100 Subject: Problem with Tkinter.PhotoImage Message-ID: <200801111548.34270.omer@no-log.org> Hi, I can only load gif images with Tkinter.PhotoImage and none with BitmapImage. I tried png, jpg, bmp and xpm and always got this errors : >>> img = Tkinter.PhotoImage(file='/home/omer/fgfs/fgsync/map.xpm') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 3206, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 3162, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't recognize data in image file "/home/omer/fgfs/fgsync/map.xpm" (or _tkinter.TclError: format error in bitmap data with BitmapImage) I also tried the imageview demo with the bitmaps in Demo/tix/bitmaps and same result (only works with tix.gif). Sounds weird that tkinter only supports a non-free format... Am I lacking some packages or config ? I'm on a debian sid and have the following python packages installed : libboost-python1.34.1 python python-central python-doc python-imaging python-imaging-tk python-minimal python-mode python-newt python-selinux python-semanage python-support python-tk python2.4 python2.4-doc python2.4-minimal thanks, -- C?dric Lucantis From lists at cheimes.de Fri Jan 25 22:54:37 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 26 Jan 2008 04:54:37 +0100 Subject: "just like Java" (was :Re: translating Python to Assembler) In-Reply-To: <7f6f3a93-4301-4a75-83d3-13d9a7c57cda@h11g2000prf.googlegroups.com> References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <4799de28$0$12358$426a74cc@news.free.fr> <7f6f3a93-4301-4a75-83d3-13d9a7c57cda@h11g2000prf.googlegroups.com> Message-ID: Paul Boddie wrote: > Well, it is important to make distinctions when people are wondering, > "If Python is 'so slow' and yet everyone tells me that the way it is > executed is 'just like Java', where does the difference in performance > come from?" Your responses seemed to focus more on waving that issue > away and leaving the whole topic in the realm of mystery. The result: > "Python is just like Java apparently, but it's slower and I don't know > why." Short answer: Python doesn't have a Just In Time (JIT) compiler. While Java's JIT optimizes the code at run time Python executes the byte code without additional optimizations. Christian From google at mrabarnett.plus.com Mon Jan 7 18:29:36 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 7 Jan 2008 15:29:36 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: On Jan 7, 5:40 pm, Martin Marcher wrote: > MartinRineh... at gmail.com wrote: > > The best thing about Python is _______. > > it's pythonicness. > I think it sounds better as "its pythonicity". From david.hotham at blueyonder.co.uk Tue Jan 29 04:02:34 2008 From: david.hotham at blueyonder.co.uk (david.hotham at blueyonder.co.uk) Date: Tue, 29 Jan 2008 01:02:34 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <92b67efe-c437-40bc-89fc-bbdd85d6e718@s19g2000prg.googlegroups.com> <816442e1-be46-4543-88dc-1b328ced7231@j20g2000hsi.googlegroups.com> Message-ID: On Jan 28, 10:11 pm, Arnaud Delobelle wrote: > My strategy was to walk through each solution "only once" (for a > certain definition of "only once :), thus I was hoping not to need a > hashtable. Yes, that seems like it should be preferable (and indeed necessary for a more general problem with larger numbers of seeds). But I wasn't smart enough to figure out how to do it ;-) > Did you pick these numbers at random? Interestingly, the solution is > unique: Not at random - this particular puzzle came out of the first post in this thread. > Mine is faster on this example, but one example is not representative! If you've found an efficient way to walk through the possible solutions only once, then - I expect that yours will be faster - and well done! I guess I should try to understand your code... > -- > Arnaud From terry at jon.es Thu Jan 24 20:00:55 2008 From: terry at jon.es (Terry Jones) Date: Fri, 25 Jan 2008 02:00:55 +0100 Subject: Text-based data inspector for Python? In-Reply-To: Your message at 00:36:16 on Friday, 25 January 2008 References: Message-ID: <18329.13511.152371.434938@jon.es> >>>>> "kj" == kj writes: kj> I've only recently started programming in Python, trying to wean kj> myself from Perl. One of the things I *really* miss from Perl is kj> a 100% mouse-free data inspector, affectionally known as the Perl kj> debugger, PerlDB, or just perl -d. With it I can examine the most kj> elaborate data structures with ease: You actually liked the perl debugger... gasp! OK, I used it too, but it left a few things to be desired (the mouse was not one). kj> And, since it's text-based, I can run it within a shell in Emacs, and kj> transfer anything I want between it and an editing buffer without even kj> a THOUGHT of touching the filthy mouse! If there's a greater joy in kj> life I have yet to find it. I use M-x pydb to debug python from inside emacs. I like it more than the straight pdb as it's a bit more like gdb. In pydb (and pdb) there's p and pp to print and pretty print a python object. They work pretty well & there's no need for the mouse. kj> NOTE: In my address everything before the first period is backwards; kj> and the last period, and everything after it, should be discarded. Nice. See http://www.fluidinfo.com/terry/2007/10/31/stagnant-email-address-arms-race/ Terry From zentraders at gmail.com Wed Jan 16 15:50:17 2008 From: zentraders at gmail.com (Zentrader) Date: Wed, 16 Jan 2008 12:50:17 -0800 (PST) Subject: error/warning color customization in interactive console? References: Message-ID: <0cb7044d-4f20-4cf8-b08c-5a99543853bd@i29g2000prf.googlegroups.com> On Jan 15, 5:44?pm, yhvh wrote: > Is it possible to output error messages in a different color? > I'm using Terminal on Gnome. For the few times that I want to do this, this simple form works with xterm. for j in range(1,10): os.system("tput setaf "+str(j)) print "test for ", j From boblatest at yahoo.com Mon Jan 14 06:33:34 2008 From: boblatest at yahoo.com (Robert Latest) Date: 14 Jan 2008 11:33:34 GMT Subject: encrypting python modules References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <5v0mquF1jhm3dU7@mid.dfncis.de> <478b4043$0$85785$e4fe514c@news.xs4all.nl> Message-ID: <5v0vkeF1kgr8fU5@mid.dfncis.de> Paul Sijben wrote: >> >> You could check the MD5 hashes of your files. > > indeed but I still need to hook into import to do that reliably, right? Depends. In a job I once had I just supplied a shell script that spat out the MD5 sums of my sources. When I got a support request I had the customer run the script and email the result to me so I could check if anything had changed. (A malicious person could of course have stored the good MD5 sums, then done his changes, and then made his request, sending me the old sums.) If your customer is cooperative and trustworthy, this is a good way to find stupid mistakes. If he ain't, drop him ;-) robert From fredrik at pythonware.com Wed Jan 9 09:57:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 15:57:51 +0100 Subject: How to get memory size/usage of python object In-Reply-To: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> References: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> Message-ID: Santiago Romero wrote: > Is there a way to check the REAL size in memory of a python object? in standard Python, without reading the interpreter source code carefully, no. to get an approximate value, create a thousand (or a million) objects and check how much the interpreter grows when you do that. From arkanes at gmail.com Fri Jan 25 22:33:22 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 25 Jan 2008 21:33:22 -0600 Subject: translating Python to Assembler In-Reply-To: <13pl92h3um45rc1@corp.supernews.com> References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pl92h3um45rc1@corp.supernews.com> Message-ID: <4866bea60801251933u38b89eedte105098ca0437e62@mail.gmail.com> On Jan 25, 2008 9:09 PM, Steven D'Aprano wrote: > On Wed, 23 Jan 2008 08:49:20 +0100, Christian Heimes wrote: > > > It's even > > possible to write code with Python assembly and compile the Python > > assembly into byte code. > > Really? How do you do that? > > I thought it might be compile(), but apparently not. > There are tools for it in the undocumented compiler.pyassem module. You have to pretty much know what you're doing already to use it - I spent a fun (but unproductive) week figuring out how to use it and generated customized bytecode for certain list comps. Malformed hand-generated bytecode stuffed into code objects is one of the few ways I know of to crash the interpreter without resorting to calling C code, too. From goldspin at gmail.com Mon Jan 7 12:27:40 2008 From: goldspin at gmail.com (Henry Chang) Date: Mon, 7 Jan 2008 09:27:40 -0800 Subject: Python's great, in a word In-Reply-To: <08f0c528-0619-432a-80a1-569cd9183e09@s12g2000prg.googlegroups.com> References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <08f0c528-0619-432a-80a1-569cd9183e09@s12g2000prg.googlegroups.com> Message-ID: What exactly does it mean "a bycycle for the mind"?? (assuming s/bycycle/bicycle) On Jan 7, 2008 5:41 AM, alain wrote: > On Jan 7, 2:09pm, MartinRineh... at gmail.com wrote: > > I'm a Java guy who's been doing Python for a month now and I'm > > convinced that > > > > 1) a multi-paradigm language is inherently better than a mono-paradigm > > language > > > > 2) Python writes like a talented figure skater skates. > > > > Would you Python old-timers try to agree on a word or two that > > completes: > > > > The best thing about Python is _______. > > > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > > "grace" but I'm not sure I've done enough to choose. > > Paraphrasing Steve Jobs but in this context: > PYTHON = a bycycle for the mind > > Best regards > > Alain > > -- > http://mail.python.org/mailman/listinfo/python-list > From robert.kern at gmail.com Fri Jan 4 17:21:21 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 04 Jan 2008 16:21:21 -0600 Subject: Fortran to Python In-Reply-To: <20080104132119.GK82115@nexus.in-nomine.org> References: <20080104132119.GK82115@nexus.in-nomine.org> Message-ID: Jeroen Ruigrok van der Werven wrote: > I got someone who asked me to make changes in an old Fortran program she is > using for some calculations. > The calculations are pretty standard aside from 2 calls to DLINCG (an IMSL > numerical_libraries function to calculate an inverse matrix). > > What I wonder about, does anybody have a Fortran to Python conversion page > somewhere to map some of the basic types to Python equivalents? > What kind of speed difference should I expect? Fairly large, if you insist on avoiding numpy. However, if your inputs are small enough, it may not matter a whole lot. You may want to use Raymond Hettinger's Matfunc.py module to implement the inverse matrices (or preferably, reformulate the problem to use a solver instead of inverting matrices explicitly): http://users.rcn.com/python/download/python.htm -- 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 pataphor at gmail.com Tue Jan 29 15:55:13 2008 From: pataphor at gmail.com (pataphor) Date: Tue, 29 Jan 2008 21:55:13 +0100 Subject: breaking out of outer loops References: Message-ID: <20080129215513.3352a90d@hyperspace> On Tue, 29 Jan 2008 11:51:04 -0800 (PST) noemailplease0001 at gmail.com wrote: > Any elegant way of breaking out of the outer for loop than below, I > seem to have come across something, but it escapes me > > for i in outerLoop: > for j in innerLoop: > if condition: > break > else: > continue > break Ha! Think outside the box to begin with ... P. def cross(args): ans = [[]] for arg in args: ans = [x+[y] for x in ans for y in arg] return ans def test(): L = [[0,1,2]]*3 for a,b,c in cross(L): print a,b,c if __name__=='__main__': test() From devnew at gmail.com Sat Jan 12 11:53:30 2008 From: devnew at gmail.com (devnew at gmail.com) Date: Sat, 12 Jan 2008 08:53:30 -0800 (PST) Subject: a problem with py2exe Message-ID: <76ba6371-abb9-4e1c-9019-711d1582adb6@s12g2000prg.googlegroups.com> I wrote an app that uses some Tix widgets and wanted to make an exe using py2exe .i used the setup script as given in http://www.py2exe.org/index.cgi/TixSetup and it copies the dlls into the dist directory created by py2exe. But then the application works only if i create a directory named 'DLLs ' and copy the tix84.dll alone into that directory. it seems silly to have tix84.dll in that dir and all other dlls in the dist directory.can anyone advise me if i can run the app with all dlls in one directory. the setup script i used is below import glob,os,sys from distutils.core import setup import py2exe def files(folder): for path in glob.glob(folder+'/*'): if os.path.isfile(path): yield path data_files=[ ('.', glob.glob(sys.prefix+'/DLLs/tix84.dll')), ('tcl/tix8.4', files(sys.prefix+'/tcl/tix8.4')), ('tcl/tix8.4/bitmaps', files(sys.prefix+'/tcl/tix8.4/bitmaps')), ('tcl/tix8.4/pref', files(sys.prefix+'/tcl/tix8.4/pref')), ] setup( script_args=['py2exe'], windows=['pyfaces.py'], data_files=data_files ) thanx in adv dn From hnessenospam at yahoo.com Tue Jan 22 13:53:27 2008 From: hnessenospam at yahoo.com (hnessenospam at yahoo.com) Date: Tue, 22 Jan 2008 10:53:27 -0800 (PST) Subject: rpy registry Message-ID: <12d6367e-4e8f-4286-8ad1-dd5f02ff0803@s12g2000prg.googlegroups.com> Howdy, I've been using rpy (1.0.1) and python (2.5.1) on my office computer with great success. When I went to put rpy on my laptop, however, I get an error trying to load rpy. "Unable to determine R version from the registry. Trying another method." followed by a few lines of the usual error message style (ending with "NameError: global name 'RuntimeExecError' is not defined." I have reinstalled R (now 2.6.1), rpy, and python without any luck (being sure to check the "include in registry" on the installation of R). Everything else I have used thus far works perfectly. Any thoughts on what might be causing problems? Thanks, -Hans From timr at probo.com Tue Jan 22 01:03:54 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 22 Jan 2008 06:03:54 GMT Subject: I don't understand what is happening in this threading code References: Message-ID: Matthew Wilson wrote: >In this code, I tried to kill my thread object by setting a variable on it >to False. > >Inside the run method of my thread object, it checks a different >variable. > >I've already rewritten this code to use semaphores, but I'm just curious >what is going on. >... >The memory address of should_keep_running seems to change when I set it >from True to False, and inside the run method, I keep checking the old >location. You misunderstand what "id(a)" does. "id" doesn't tell you anything about the name "a" or the address of "a". What it tells you is the unique identifier of the object that "a" is bound to. Any time you change "a", "id(a)" will also change. Note, for example: C:\tmp>python Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> id(True) 504958236 >>> a = True >>> id(a) 504958236 >>> id(False) 504958224 >>> a = False >>> b = False >>> id(a) 504958224 >>> id(b) 504958224 >>> 504958236 is the id of "True", not of "a". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From hniksic at xemacs.org Tue Jan 15 05:15:18 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 15 Jan 2008 11:15:18 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> <87ir1wf1wi.fsf@mulj.homelinux.net> <478c8594$0$31498$426a34cc@news.free.fr> Message-ID: <87ejcjbdjd.fsf@mulj.homelinux.net> Bruno Desthuilliers writes: > So while it's true that __init__ is the closest equivalent to what > C++ and Java (and possibly a couple "other languages") call a > constructor, it doesn't imply that you should refer to it as "the > constructor". As Neil Cerutti points out, there's in fact nothing > like a 'constructor method' in Python : there are a "__new__" > method, an "__init__" method, and "constructor expressions" which > may invoke them !-) I agree with this. The poster I was responding to called __init__ "akin to a constructor", which (to me) implied connection to other languages, not aspiration to define __init__ as THE constructor. From PatrickMinnesota at gmail.com Tue Jan 1 20:46:14 2008 From: PatrickMinnesota at gmail.com (PatrickMinnesota) Date: Tue, 1 Jan 2008 17:46:14 -0800 (PST) Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <7yBej.30029$CN4.18224@news-server.bigpond.net.au> Message-ID: <3693eb2d-9034-4f30-8d8f-84376bc6d521@e25g2000prg.googlegroups.com> On Jan 1, 7:12 pm, Neil Hodgson wrote: > Cloud computing is mostly about scalability. You do not need to be > concerned so much about low level infrastructure details such as > purchasing servers, configuring and maintaining them, hiring space in > data centres, linking up data centres, etc. It converts a lot of fixed > costs into lower recurring costs so makes it easier for a start up with > limited capital to start operating. > > There are Python libraries for accessing some of the cloud computing > services and you can also host Python application code on some services > that allow code execution. This includes services that can run arbitrary > code on virtual machines such as EC2 and more restricted computational > services like Hadoop which can run Jython. > > Neil I would say that cloud computing to an implementor or company providing cloud computing is all about scalability and stuff like S3 and EC3. There are other options for this BTW. But to the end user, it's about having your data and applications on a disk served by a network and server that is somewhere out there on the net and accessible from anywhere that you have connectivity. You might travel with a laptop, but generally, when in Hong Kong, you'll be screwed if a chunk of data is sitting on a disk inside a desktop in your home office and isn't on your laptop. With the 'cloud' concept, it wouldn't matter where you are, as long as you have a connection to the internet, you can run the apps and access the data. Issues: and yes, they are big, who has control over the data, is it being backed up and protected, and is your private data being mined without your approval. Oh, and what happens if you use Zoho's system and they go out of business? From lists at cheimes.de Sat Jan 26 17:14:23 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 26 Jan 2008 23:14:23 +0100 Subject: Python and binary compatibility In-Reply-To: References: <083456aa-1ed1-4455-a8ca-4bbaaba1ce00@i29g2000prf.googlegroups.com> Message-ID: Joshua Kugler wrote: > That page has a link to the Microsoft Visual C++ Toolkit 2003 page, which > then says it's been discontinued and to use Visual C++ 2005 Express > Edition. Sigh... You can still find some copies of the free toolkit on the internet. Christian From mmazur at gmail.com Tue Jan 8 20:16:38 2008 From: mmazur at gmail.com (Mike Mazur) Date: Wed, 9 Jan 2008 10:16:38 +0900 Subject: 'Borg' and multiple threads. In-Reply-To: <47829a95$0$26035$88260bb3@free.teranews.com> References: <47829a95$0$26035$88260bb3@free.teranews.com> Message-ID: <184110a70801081716v19d4136du24a0cb3c6951ab61@mail.gmail.com> Hi, On Jan 8, 2008 7:24 AM, Tobiah wrote: > I have a class that I call Borg that starts like this: > > class Borg(dict): > > static_state = {} > def __init__(self): > self.__dict__ = self.static_state > > > so that I can access the same data from anywhere within > any module or function just by instantiating one. > > This is used in a cherrypy web app. I got to thinking > about whether there would be confusion when multiple > users are eventually hitting the site at the same time. > Everything seems ok. Each time I hit the app and examine > the Borg() at the beginning, it seems to have no attributes. > This is what I want. > > My question is why this seems to work. I had the idea that > there was a class object that is created when the file containing > the definition is read, which actually contains the static > information that is later accessed by instances. Isn't this > done when the cherrypy app first loads, rather than each time > a browser hits the app? Otherwise, where is the individual data > stored for each of two simultaneous hits of the web page? Maybe a silly question, but are you changing the values in the dict before hitting it again and getting the empty dict? Mike From no_one at here Thu Jan 31 01:54:56 2008 From: no_one at here (Iain Mackay) Date: Thu, 31 Jan 2008 06:54:56 -0000 Subject: Sine Wave Curve Fit Question References: <7eOdnXVrB-fQFD3anZ2dnUVZ8hednZ2d@giganews.com> Message-ID: Thanks folks - I'll have a think about both of these options. From elind at spamcop.net Wed Jan 16 13:45:50 2008 From: elind at spamcop.net (Erik Lind) Date: Wed, 16 Jan 2008 13:45:50 -0500 Subject: A question about event handlers with wxPython References: <478c3bb2$0$5150$4c368faf@roadrunner.com> <2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com> <478ccbc3$0$11000$4c368faf@roadrunner.com> <478d15b4$0$18437$4c368faf@roadrunner.com> <0571a7cd-f7f6-44b4-a4d5-e427de93590a@c4g2000hsg.googlegroups.com> Message-ID: <478e5251$0$22656$4c368faf@roadrunner.com> "Mike Driscoll" wrote in message news:0571a7cd-f7f6-44b4-a4d5-e427de93590a at c4g2000hsg.googlegroups.com... > On Jan 15, 2:20 pm, "Erik Lind" wrote: >> That all looks cool. I will experiment more. I'm a bit slow on this as >> only >> two weeks old so far. >> >> Thanks for the patience > > No problem. I'm pretty slow with some toolkits too...such as > SQLAlchemy. Ugh. > > Mike BTW, The wxPython group that you mentioned....is that http://wxforum.shadonet.com/ ? From bearophileHUGS at lycos.com Sun Jan 27 05:49:25 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 27 Jan 2008 02:49:25 -0800 (PST) Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> <7xy7acsx2l.fsf@ruckus.brouhaha.com> <8ddebd68-43dc-4320-86e1-887aadff4af3@d70g2000hsb.googlegroups.com> <7xmyqs722t.fsf@ruckus.brouhaha.com> <13pnbp9l8lk1j8b@corp.supernews.com> Message-ID: <8a699886-24f7-485e-a87f-90518e9ff536@l32g2000hse.googlegroups.com> bearophile: > That version is easy to translate to other languages and you can > probably find that Psyco makes it much faster still. That operation is quite common, so it deserves a bit more work: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/543271 (I can show you the D/C code if you want it. The C code is just for testing, while the D code is usable). The final sum: the Psyco version is almost 40 times faster than the Python version, and just 2.8 times slower than the D version, and 3.4 times slower than a C version (that doesn't use too many pointer tricks). I think this is good enough. Bye, bearophile From gagsl-py2 at yahoo.com.ar Sun Jan 27 12:45:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 15:45:24 -0200 Subject: Exceptions on delete in pysqlite References: <479a7b0c$0$9119$9b4e6d93@newsspool2.arcor-online.net> Message-ID: En Fri, 25 Jan 2008 22:12:57 -0200, Wildemar Wildenburger escribi?: > Using pysqlite, I'd like to check if some dataset that I removed has > been in the database at all. Ideally I'd like pysqlite to raise an > Exception if deleting does nothing. Is that possible? I don't think so. It isn't an error, like a SELECT which returns an empty set isn't an error either. > Codewise, I'd like the following, but without me checking for and > raising the exception myself: > > cur = con.execute("""DELETE FROM SomeTable WHERE id=? AND name=?""", > (ID, NAME)) > if cur.rowcount == 0: > raise Exception Write a function to do that. -- Gabriel Genellina From arnlen at mac.com Mon Jan 28 04:43:36 2008 From: arnlen at mac.com (Jumping Arne) Date: Mon, 28 Jan 2008 10:43:36 +0100 Subject: Serving images Message-ID: <0001HW.C3C3625800224F8DB04379AF@news.individual.de> I'm no web programmer so please be kind. I'm just going to start writing a small "web app", it's very small and will only do one thing so I'm not going to use some kind of web framework. The purpose of the script is to do some custom markup of markdown formatted pages, render them and send them back to the browser. This is fairly simple and I've done similar things before but this time I'm going to add support for handling images. Before I've just placed the images on a server where the script didn't need to bother about it. Now I'm considering to let the script handle the images also, that is serve them to the browser when requested. I've tried two different approaches in other scripts: + Put them somewhere outside the scope of the script and link to them. + In my own code open the images, read the data and send it back (is there a library for this?). Before deciding on how to handle this for this script I would like to ask: how is this best done? Is there a better way? From thelanguageofcities at gmail.com Sun Jan 27 19:21:34 2008 From: thelanguageofcities at gmail.com (Max) Date: Sun, 27 Jan 2008 16:21:34 -0800 (PST) Subject: Python Genetic Algorithm References: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <2a0f06c6-4fad-4c41-ac67-ce87aaae89cd@u10g2000prn.googlegroups.com> On Jan 27, 7:01 pm, "Steven Clark" wrote: > Why not make chromosome itself a class? > > class BasicChromosome(object): > def __init__(self, data): > self.data = data > > def crossover(self): > [stuff here] > > You can subclass this as needed, altering the crossover method as necessary. > > ...perhaps I didn't understand your question. > -Steven > > On Jan 27, 2008 6:35 PM, Wildemar Wildenburger > > wrote: > > Max wrote: > > > In GAs, you operate on a Population of solutions. Each Individual from > > > the Population is a potential solution to the problem you're > > > optimizing, and Individuals have what's called a chromosome - a > > > specification of what it contains. For example, common chromosomes are > > > bit strings, lists of ints/floats, permutations...etc. I'm stuck on > > > how to implement the different chromosomes. I have a Population class, > > > which is going to contain a list of Individuals. Each individual will > > > be of a certain chromosome. I envision the chromosomes as subclasses > > > of an abstract Individual class, perhaps all in the same module. I'm > > > just having trouble envisioning how this would be coded at the > > > population level. Presumably, when a population is created, a > > > parameter to its __init__ would be the chromosome type, but I don't > > > know how to take that in Python and use it to specify a certain class. > > > I'm not sure I'm following you here. So a "chromosome" is bit of > > functionality, right? So basically it is a function. So my advice would > > be to write these functions and store it to the "indivuals"-list like so: > > > class Population(object): > > def __init__(self, *individuals): > > self.individuals = list(individuals) > > > Then you can say: > > p = Population(indiv1, indiv2, indiv3) > > for individual in p.individual: > > individual(whatever_your_problem) > > > (Don't know if this is the way GA's are supposed to work) > > > You can also create callable classes (that is, classes that implement > > the __call__ method), and use instances of these as the individuals. For > > example you can create a Permutation class that returns a permutation > > (defined in it's __init__()) when it's __call__ method is called. (Am I > > making sense?) > > > This is just generic advice, maybe this helps and maybe it doesn't at > > all. :) > > > > I'm doing something similar with my crossover methods, by specifying > > > them as functions in a module called Crossover, importing that, and > > > defining > > > > crossover_function = getattr(Crossover, "%s_crossover" % xover) > > > > Where xover is a parameter defining the type of crossover to be used. > > > I'm hoping there's some similar trick to accomplish what I want to do > > > with chromosomes - or maybe I'm going about this completely the wrong > > > way, trying to get Python to do something it's not made for. Any help/ > > > feedback would be wonderful. > > > This isn't too bad, but for such things dictionaries are your Go-To > > datatype. Just have a dictionary of xover-functions handy and call the > > thusly: > > > crossover_function = Crossover.function[xover] > > > > Thanks, > > > Max Martin > > If that helps :) > > > regards > > /W > > > -- > >http://mail.python.org/mailman/listinfo/python-list This is sort of what I'm trying to do. The super class would be Individual, and subclasses would be BitStringIndividual, IntIndividual, PermutationIndividual...etc. I just am feeling lost as to how I'm going to implement my Population class, because when a Population is initially created, it's going to fill itself up with individuals by creating them, so it's going to need to know which class it's creating instances of (which will be input when creating the population somehow; I'm just not sure how to implement this). From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 30 04:15:55 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 30 Jan 2008 10:15:55 +0100 Subject: Appropriate use of Property() In-Reply-To: <72c9d910-f19a-407d-91cf-5599fa3e73b3@h11g2000prf.googlegroups.com> References: <72c9d910-f19a-407d-91cf-5599fa3e73b3@h11g2000prf.googlegroups.com> Message-ID: <47a0403f$0$15926$426a74cc@news.free.fr> noemailplease0001 at gmail.com a ?crit : > Property() can be used to rid ourselves of the extra effort of using > two different methods (getAttrib() setAttrib()) for access of an > attribute without giving direct access to the attribute, NB : properties are for computed attributes, not to "avoid giving direct acces to (an) attribute". If what you need is really a public attribute, then use a plain attribute - knowing you'll be able to switch to a property if and when the need arises. > thus making > it more elegant. So, the outsider using my module accesses the > attribute with the syntax 'Object.attrib', but since this syntax looks > as if he is accessing the attribute (rather than through a > descrtiptor), should we subscribe to this syntax only when the > attribute is both readable and writable? i.e., > if I have an attribute which I strongly believe would always be only > readable, should I go with the old style 'Object.getAttrib()'? > Would like to know different perspectives. I just can second Gabriel on this: as long as it's not computation intensive, I use a read-only attribute (ie: fset and fdel raising AttributeError('attribute XXX is read-only')). From vimfefv at gmail.com Tue Jan 1 04:19:22 2008 From: vimfefv at gmail.com (vimfefv at gmail.com) Date: Tue, 1 Jan 2008 09:19:22 +0000 (UTC) Subject: M'I-5 Persecutio n , Capita l R adio - Chri s Tarran t Message-ID: -=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-= -=. Capital Radio - Chris Tarrant -= -=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-= Capital Radio DJs have been "in on it". from the start. One of the first things I heard in the summer of 1990 was from a Capital DJ who said,. "If he listens to Capital then he. can't be all bad" (supportive, you see. We're not bastards). Much of. what came over the radio in 1990 is now so far away the precise details have. been obliterated by time. No diary was kept of the details, and although archives if they exist may give. pointers, the ambiguity of what broadcasters said would leave that. open to re-interpretation. In spring 1994,. Chris Tarrant on his Capital morning show made an aside to someone else in the studio, about a person. he didn't identify. He said, "You know this. bloke? He says we're trying to kill him. We should be done for attempted. manslaughter". That mirrored something I had said a day. or two before. What Tarrant said was understood by the staff member in the. studio he was saying it to; they said, "Oh no, don't say that" to Tarrant. If any archives. exist of the morning show (probably unlikely) then it. could be found there; what he said was so out of context that he would be very hard. put to find an explanation. A couple of days. later, someone at the site where I was working repeated the remark although in a. different way; they said there had been people in a computer room when automatic fire extinguishers. went off and those people were. "thinking of suing for attempted manslaughter". Finally, this isn't confined. to the established radio stations. In 1990 after I. had listened to a pirate radio station in South London for about half an. hour, there was an audible phone call in the background, followed by total. silence for a few moments, then shrieks of laughter. "So what are we supposed to say now? Deadly torture? He's. going to talk to us now, isn't he?", which meant that they could hear what I would say in my. room. 5203 From steve at REMOVE-THIS-cybersource.com.au Tue Jan 1 17:01:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 01 Jan 2008 22:01:55 -0000 Subject: ElementTree should parse string and file in the same way References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> <5tuqfaF1f8u9tU1@mid.uni-berlin.de> <13nkkh6almg8o6b@corp.supernews.com> Message-ID: <13nle2jp4lh1g9a@corp.supernews.com> On Tue, 01 Jan 2008 12:59:44 -0700, Steven Bethard wrote: > Steven D'Aprano wrote: >> On Tue, 01 Jan 2008 13:36:57 +0100, Diez B. Roggisch wrote: >> >>> And codemonkeys know that in python >>> >>> doc = et.parse(StringIO(string)) >>> >>> is just one import away >> >> Yes, but to play devil's advocate for a moment, >> >> doc = et.parse(string_or_file) >> >> would be even simpler. > > I assume the problem with this is that it would be ambiguous. You can > already use either a string or a file with ``et.parse``. A string is > interpreted as a file name, while a file object is used directly. Ah! I wasn't aware that parse() operated on either an open file object or a string file name. That's an excellent reason for not treating strings the same as files in ElementTree. > How would you differentiate between a string that's supposed to be a > file name, and a string that's supposed to be XML? Well, naturally I wouldn't. I *could*, if I assumed that a multi-line string that started with "<" was XML, and a single-line string with the path separator character or ending in ".xml" was a file name, but that sort of Do What I Mean coding is foolish in a library function that can't afford to occasionally Do The Wrong Thing. -- Steven From pavlovevidence at gmail.com Mon Jan 7 18:27:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 7 Jan 2008 15:27:39 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: On Jan 7, 8:09 am, MartinRineh... at gmail.com wrote: > I'm a Java guy who's been doing Python for a month now and I'm > convinced that > > 1) a multi-paradigm language is inherently better than a mono-paradigm > language > > 2) Python writes like a talented figure skater skates. > > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is _______. > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > "grace" but I'm not sure I've done enough to choose. "it doesn't suck". (Really. All programming languages have good, useful features. Even Perl. Python is unique in having no very bad ones.) Carl Banks From gagsl-py2 at yahoo.com.ar Fri Jan 25 15:00:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 Jan 2008 18:00:02 -0200 Subject: Increment Variable Name References: Message-ID: En Wed, 23 Jan 2008 23:09:36 -0200, David Brochu escribi?: > Basically what I am trying to do is pass each value from a list to > the following line of code (where XXX is where I need to pass each > value of the list > > tests = easygui.multchoicebox(message="Pick the test(s) you would > like to run from the list below." > , title="Validation Tests" > ,choices=[XXX]) > > If i were to manually pass values to this line it would appear like : > tests = easygui.multchoicebox(message="Pick the test(s) you would > like to run from the list below." > , title="Validation Tests" > ,choices=["Test 1","Test 2", "Test 3"]) > > When I actually pass the list to the line of code, it works, however > it doesn't really split the list by element. The desired output of > this line of code would be a GUi that included a list consisting of > each element from the passed list. Right now I can only get it to > consist of a single element that contains every part of the list. You should have posted this in the first place! No answer to your previous specific question would have helped you in this case. See http://catb.org/~esr/faqs/smart-questions.html#goal Ok, you have a list containing all the possible choices. It doesn't matter how did you build that list. Then, just pass *that* *list* as the choices parameter to the function. By example: all_tests = ["Test 1","Test 2", "Test 3"] tests = easygui.multchoicebox(message="Pick the test(s) you would like to run from the list below.", title="Validation Tests", choices=all_tests) (If you use [items] you are building a new list with a single element which itself is the list of choices, and that's not what multchoicebox expects). -- Gabriel Genellina From deets at nospam.web.de Wed Jan 9 17:59:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Jan 2008 23:59:10 +0100 Subject: for loop without variable In-Reply-To: References: Message-ID: <5ul1tuF1i0qr1U1@mid.uni-berlin.de> erik gartz schrieb: > Hi. I'd like to be able to write a loop such as: > for i in range(10): > pass > but without the i variable. The reason for this is I'm using pylint > and it complains about the unused variable i. I can achieve the above > with more lines of code like: > i = 0 > while (i != 10): > i += 1 > Is there a concise way to accomplish this without adding extra lines > of codes? Thanks in advance for your help. The underscore is used as "discarded" identifier. So maybe for _ in xrange(10): ... works. Diez From paul.hankin at gmail.com Wed Jan 9 04:21:25 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 9 Jan 2008 01:21:25 -0800 (PST) Subject: Open a List of Files References: <874pdomrrd.fsf@mulj.homelinux.net> Message-ID: <4f67337a-14ea-4552-8a5a-6de9703e58ff@d70g2000hsb.googlegroups.com> On Jan 9, 2:41?am, Tim Chase wrote: > > I decided that I was just trying to be "too smooth by 1/2" so I fell back to > > > messages = open(os.path.join(host_path,'messages.txt'), 'wb') > > deliveries = open(os.path.join(host_path,'deliveries.txt'), 'wb') > > actions = open(os.path.join(host_path,'actions.txt'), 'wb') > > parts = open(os.path.join(host_path,'parts.txt'), 'wb') > > recipients = open(os.path.join(host_path,'recipients.txt'), 'wb') > > viruses = open(os.path.join(host_path,'viruses.txt'), 'wb') > > esp_scores = open(os.path.join(host_path,'esp_scores.txt'), 'wb') > > Another way to write this which reduces some of the code would be > > ? filenames = ['messages', 'deliveries', 'actions', 'parts', > ? ? 'recipients', 'viruses', 'esp_scores'] > > ? (messages, deliveries, actions, parts, > ? ? recipients, viruses, esp_scores) = [ > ? ? open(os.path.join(host_path, '%s.txt' % fn), 'wb') > ? ? for fn in filenames > ? ? ] > > It becomes even more clear if you make an intermediate "opener" > function such as > > ? binwriter = lambda fname: open( > ? ? ? os.path.join(host_path, '%s.txt' % fname), 'wb') > > ? (messages, deliveries, actions, parts, > ? ? recipients, viruses, esp_scores) = [ > ? ? binwriter(fn) for fn in filenames] This can be more cleanly written using locals() for fn in filenames: locals()[fn] = open(os.path.join(host_path, fname + '.txt', 'wb') -- Paul Hankin From hyperneato at gmail.com Fri Jan 4 05:40:08 2008 From: hyperneato at gmail.com (stuntgoat) Date: Fri, 4 Jan 2008 02:40:08 -0800 (PST) Subject: import zlib in 2.5 fails References: Message-ID: <1b0cd0c2-8e13-46df-8463-ac452f170940@t1g2000pra.googlegroups.com> Modules/main.c:186: warning: function declaration isn't a prototype /home/name/Desktop/webdl/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ ffi64.c:45: warning: function declaration isn't a prototype /home/name/Desktop/webdl/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ ffi64.c:342: warning: function declaration isn't a prototype /usr/bin/ld: /usr/local/lib/libz.a(adler32.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC /usr/local/lib/libz.a: could not read symbols: Bad value collect2: ld returned 1 exit status this error occurred at one point during a compilation of Python 2.5. It seems related to my inability to import zlib now. On Jan 4, 10:19 am, stuntgoat wrote: > import zlib works in Python 2.4 (debian etch AMD64 - default python > version for that distro) > > I built python 2.5 from source; zlib is not importable. > > I am trying to compile MySQLdb. > > any clues about how to get zlib able to be imported in 2.5? > > -sg From arkanes at gmail.com Mon Jan 14 13:49:57 2008 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 14 Jan 2008 12:49:57 -0600 Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) In-Reply-To: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> Message-ID: <4866bea60801141049xcaab6d7vac5b42d75c141a6e@mail.gmail.com> On Jan 14, 2008 12:39 PM, aspineux wrote: > > This append in both case > > dict(a=1).get('a', f()) > dict(a=1).setdefault('a', f()) > > This should be nice if f() was called only if required. > Think about the change to Python semantics that would be required for this to be true, and then use collections.defaultdict instead. From peng.kyo at gmail.com Tue Jan 15 22:09:09 2008 From: peng.kyo at gmail.com (J. Peng) Date: Wed, 16 Jan 2008 11:09:09 +0800 Subject: no pass-values calling? Message-ID: <18c1e5f20801151909u4cdd227ah685741ea21734491@mail.gmail.com> Hello, I saw this statement in Core Python Programming book, All arguments of function calls are made by reference, meaning that any changes to these parameters within the function affect the original objects in the calling function. Does this mean there is not pass-values calling to a function in python? only pass-reference calling? Thanks! From asmodai at in-nomine.org Thu Jan 10 05:56:58 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 10 Jan 2008 11:56:58 +0100 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <20080110105658.GW75977@nexus.in-nomine.org> -On [20080110 11:46], A.T.Hofkamp (hat at se-162.se.wtb.tue.nl) wrote: >In my experience however, differences in CPU execution time are usually >meaningless compared to differences in development time. I have to disagree with you to a point. Yes, maintenance of code is important, no denying that. However, if I can calculate N variations of a certain material's properties in an hour and using Python will cut that in half, the number of calculated variations per hour, I will be concerned. This is especially so for people designing, say, optics. If you look at the amount of optimizing designs and calculating the resulting properties and doing this for X iterations in a day it becomes quite painfully obvious that raw CPU execution time *does* matter. 't All varies with what you want, of course... -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ When you have eliminated the impossible, whatever remains, however improbable, must be the truth... From grante at visi.com Sun Jan 20 10:16:53 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 20 Jan 2008 15:16:53 -0000 Subject: Memory errors with imaplib References: <6012daff-0fd3-4835-a9ca-c18d2a2ac53c@v29g2000hsf.googlegroups.com> Message-ID: <13p6pf5he8am89e@corp.supernews.com> On 2008-01-20, Fredrik Lundh wrote: > looks like a known bug in imaplib: > > http://bugs.python.org/issue1389051 > > "In a worst case scenario, you'll need some 13 gigabytes of > virtual memory to read a 15 megabyte message..." The problem and the one-line soulution have been known for over two years and it's still an open bug? -- Grant Edwards grante Yow! Yow! Is my fallout at shelter termite proof? visi.com From joejacob21 at gmail.com Wed Jan 23 06:31:20 2008 From: joejacob21 at gmail.com (joe jacob) Date: Wed, 23 Jan 2008 03:31:20 -0800 (PST) Subject: wxpython Message-ID: <77cc3d61-5dd0-4878-b436-b6d07e40de4d@i7g2000prf.googlegroups.com> I am trying to open a file containing non displayable characters like contents an exe file. The is is with the below mentioned code: self.text_ctrl_1.SetValue(file_content) If the file_content contains non displayable characters I am getting an error like this: Traceback (most recent call last): File "C:\Documents and Settings\joe_jacob\Desktop\notepad.py", line 102, in open_file self.text_ctrl_1.SetValue(file_content) File "D:\softwares\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx \_controls.py", line 1708, in SetValue return _controls_.TextCtrl_SetValue(*args, **kwargs) File "D:\softwares\Python25\lib\encodings\cp1252.py", line 15, in decode return codecs.charmap_decode(input,errors,decoding_table) UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to I am trying to create an encryption program so if I open any file even if it is an exe file it should display in text ctrl. What is this problem with this ? How can I rectify this? From asmodai at in-nomine.org Fri Jan 4 09:47:12 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jan 2008 15:47:12 +0100 Subject: Fortran to Python In-Reply-To: <20080104132119.GK82115@nexus.in-nomine.org> References: <20080104132119.GK82115@nexus.in-nomine.org> Message-ID: <20080104144712.GL82115@nexus.in-nomine.org> -On [20080104 14:22], Jeroen Ruigrok van der Werven (asmodai at in-nomine.org) wrote: >What I wonder about, does anybody have a Fortran to Python conversion page >somewhere to map some of the basic types to Python equivalents? Just to share my own ideas: Seems COMPLEX*16/complex*16 ~= complex REAL*8/real*8 ~= float INTEGER/integer ~= int/long -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Necessity is the mother of invention... From eproust at gmail.com Mon Jan 21 04:12:59 2008 From: eproust at gmail.com (pythonewbie) Date: Mon, 21 Jan 2008 01:12:59 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <13p8803epubo92b@corp.supernews.com> Message-ID: <14dc1431-909b-4702-a695-846a683ef345@q77g2000hsh.googlegroups.com> On 21 jan, 09:53, pythonewbie wrote: > On 21 jan, 05:31, Dennis Lee Bieber wrote: > > > > > On Sun, 20 Jan 2008 13:58:13 -0800 (PST), pythonewbie > > declaimed the following in comp.lang.python: > > > > I just would like to know if I would ALWAYS find the install directory > > > in sys.path[6] and site-packages directory in sys.path[7] on any Win32 > > > platform and sys.path[2] and site-packages directory in sys.path[6] on > > > any Linux platform. > > > Unlikely... > > > >>> sys.path[6] > > > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg'>>> sys.path[2] > > > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg'>>> sys.path > > > ['', 'E:\\Python24\\lib\\site-packages\\pyopengl-3.0.0a5-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg', > > 'E:\\Python24\\lib\\site-packages\\sqlobject-0.7.6-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\celementtree-1.0.5_20051216-py2.4-win32.egg', > > 'E:\\Python24\\lib\\site-packages\\configobj-4.4.0-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\ruledispatch-0.5a0.dev_r2306-py2.4-win32.egg', > > 'E:\\Python24\\lib\\site-packages\\formencode-0.7.1-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\pastescript-1.3.4-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\elementtree-1.2.6_20050316-py2.4-win32.egg', > > 'E:\\Python24\\lib\\site-packages\\simplejson-1.7.1-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\cherrypy-2.2.1-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\turbocheetah-0.9.5-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\turbojson-1.0-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\pyprotocols-1.0a0dev_r2302-py2.4-win32.egg', > > 'E:\\Python24\\lib\\site-packages\\pastedeploy-1.3-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\paste-1.3-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\cheetah-2.0rc8-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\setuptools-0.6c6-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\turbogears-1.0.3.2-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\turbokid-1.0.2-py2.4.egg', > > 'E:\\Python24\\lib\\site-packages\\kid-0.9.6-py2.4.egg', > > 'e:\\python24\\lib\\site-packages\\scipy', > > 'C:\\WINDOWS\\system32\\python24.zip', 'e:\\UserData\\Dennis Lee > > Bieber\\My Documents', 'E:\\Python24\\DLLs', 'E:\\Python24\\lib', > > 'E:\\Python24\\lib\\plat-win', 'E:\\Python24\\lib\\lib-tk', > > 'E:\\Python24\\Lib\\site-packages\\pythonwin', 'E:\\Python24', > > 'E:\\Python24\\lib\\site-packages', > > 'E:\\Python24\\lib\\site-packages\\Numeric', > > 'E:\\Python24\\lib\\site-packages\\PIL', > > 'E:\\Python24\\lib\\site-packages\\win32', > > 'E:\\Python24\\lib\\site-packages\\win32\\lib', > > 'E:\\Python24\\lib\\site-packages\\wx-2.8-msw-unicode'] > > > >>> os.environ["PATH"] > > > 'E:\\Python24\\;C:\\GNAT\\bin;C:\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\PROGRA~1\\MySQL\\MySQL > > Server 5.0\\bin;C:\\Program Files\\SciTE;C:\\Program > > Files\\Java\\jre1.6.0_03\\bin;C:\\Program > > Files\\Java\\jdk1.6.0_03\\bin;C:\\Program Files\\Common > > Files\\Adobe\\AGL;C:\\MSSQL7\\BINN;c:\\PROGRA~1\\sdb\\programs\\bin;c:\\PROGRA~1\\sdb\\programs\\pgm;C:\\Tcl\\bin;C:\\Program > > Files\\Common Files\\Roxio Shared\\DLLShared\\;C:\\Program Files\\Common > > Files\\Roxio Shared\\9.0\\DLLShared\\;e:\\Python24\\Scripts;c:\\Regina' > > > -- > > 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/ > > OK Denis Lee, I see now. I appreciate your clear and simple to > understand reply. > > All posts on this topic, have been appreciated a lot... Thanks to all > helpers. > > Cheers Hi John Machin, Your code : >>> import sys, re >>> for p in sys.path: ... m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p) ... if m: ... print m.group(1, 0) ... break ... else: ... raise Exception('Huh?') ... Does not work on my PC : Traceback (most recent call last): File "/home/eproust/john-machin_recup_rep_site-packages.py", line 9, in raise Exception('Huh?') Exception: Huh? Even if I remove all code below the else: part of the script... - Thanks for your advice to read : http://www.python.org/community/sigs/current/distutils-sig/ Cheers From http Wed Jan 23 14:05:01 2008 From: http (Paul Rubin) Date: 23 Jan 2008 11:05:01 -0800 Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> Message-ID: <7x8x2g8isi.fsf@ruckus.brouhaha.com> ryan k writes: > Hello. I have a string like 'LNAME > PASTA ZONE'. I want to create a list of those words and > basically replace all the whitespace between them with one space so i > could just do lala.split(). Thank you! import re s = 'LNAME PASTA ZONE' re.split('\s+', s) From nagle at animats.com Thu Jan 24 19:13:30 2008 From: nagle at animats.com (John Nagle) Date: Thu, 24 Jan 2008 16:13:30 -0800 Subject: Sorting Large File (Code/Performance) In-Reply-To: References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> Message-ID: <4799285d$0$36346$742ec2ed@news.sonic.net> Ira.Kovac at gmail.com wrote: > Thanks to all who replied. It's very appreciated. > > Yes, I had to double check line counts and the number of lines is ~16 > million (instead of stated 1.6B). OK, that's not bad at all. You have a few options: - Get enough memory to do the sort with an in-memory sort, like UNIX "sort" or Python's "sort" function. - Thrash; in-memory sorts do very badly with virtual memory, but eventually they finish. Might take many hours. - Get a serious disk-to-disk sort program. (See "http://www.ordinal.com/". There's a free 30-day trial. It can probably sort your data in about a minute.) - Load the data into a database like MySQL and let it do the work. This is slow if done wrong, but OK if done right. - Write a distribution sort yourself. Fan out the incoming file into one file for each first letter, sort each subfile, merge the results. With DRAM at $64 for 4GB, I'd suggest just getting more memory and using a standard in-memory sort. John Nagle From aspineux at gmail.com Sat Jan 5 05:01:18 2008 From: aspineux at gmail.com (aspineux) Date: Sat, 5 Jan 2008 02:01:18 -0800 (PST) Subject: How a smart editor could make "Postfix type declarations PEP3117" in Python3000 more readable References: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> Message-ID: <27358cb1-7e7d-42c2-91d3-00e003ecb6d8@z17g2000hsg.googlegroups.com> On Jan 5, 4:39 am, aspineux wrote: > Hi > > I read the PEP 3117 about the new "Postfix type declarations" in > Python3000. > THIS PEP as been REJECTED ! But ... > > The notation in the PEP is very ugly ! This make python code more > difficult to read! > > Anyway when I switched to python (from C, C++, ..), I suffered a lot > of the > untyped python variables. And I think this is a good idea to include > typing in python. > > Then I get this idea: The editor could hide the typing notation, just > displaying hint ! > It could also auto-complete the type of any variable having already a > type in > the current function, and underline untyped variable or variable > having multiple type inside the function. > > Just an idea ! And to go further the editor could do all the job of type checking, using formatted comment to specify type, like in some existing embedded documentation. But then we are losing the brevity provided by the PEP. Pydev (and certainly other) already does some interesting work to find mistyped (typed like in "I made a typo") variable name. TO ALL "NEW IDEA" RESISTANT : Hopefully, in 1990 nobody said to someone that inventing a language where bloc definition is based on indentation was a s.... Regards > > Alain Spineux > > Happy new year. From mattheww at chiark.greenend.org.uk Tue Jan 8 16:19:10 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 08 Jan 2008 21:19:10 +0000 (GMT) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> <1d895d6d-a649-439e-8223-0ae7d3a4eb40@l6g2000prm.googlegroups.com> <4fb7129f-3887-4e3b-a827-3255344047f3@c23g2000hsa.googlegroups.com> Message-ID: wrote: > A quick look (thorough analysis still required) shows that OLPC and > PyPy are, indeed, extensive standards. > one-laptop-per-child.html (olpc),74.3,,http://wiki.laptop.org/go/Python_Style_Guide I think that's mostly PEP 8, with some notes added. -M- From lasses_weil at klapptsowieso.net Tue Jan 22 15:48:01 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Tue, 22 Jan 2008 21:48:01 +0100 Subject: question In-Reply-To: References: Message-ID: <47965686$0$5955$9b4e6d93@newsspool3.arcor-online.net> Hi there :) A little tip upfront: In the future you might want to come up with a more descriptive subject line. This will help readers decide early if they can possibly help or not. jyoung79 at kc.rr.com wrote: > def albumInfo(theBand): > def Rush(): > return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > > def Enchant(): > return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > > ... > Yuck! ;) > The only problem with the code above though is that I don't know how to call it, especially since if the user is entering a string, how would I convert that string into a function name? While this is relatively easy, it is *waaayyy* too complicated an approach here, because . . . > def albumInfo(theBand): > if theBand == 'Rush': > return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > elif theBand == 'Enchant': > return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > ... > . . . this is a lot more fitting for this problem. You could also have used a dictionary here, but the above is better if you have a lot of lists, because only the one you use is created (I think . . .). You might also want to consider preparing a textfile and reading it into a list (via lines = open("somefile.txt").readlines()) and then work with that so you don't have to hardcode it into the program. This however is somewhat advanced (if you're just starting out), so don't sweat it. > I'm not familiar with how 'classes' work yet (still reading through my 'Core Python' book) but was curious if using a 'class' would be better suited for something like this? Since the user could possibly choose from 100 or more choices, I'd like to come up with something that's efficient as well as easy to read in the code. If anyone has time I'd love to hear your thoughts. > Think of classes as "models of things and their behavior" (like an animal, a car or a robot). What you want is a simple "request->answer" style functionality, hence a function. Hope that helps. Happy coding :) /W From vivfvfifi at gmail.com Tue Jan 1 06:41:56 2008 From: vivfvfifi at gmail.com (vivfvfifi at gmail.com) Date: Tue, 1 Jan 2008 11:41:56 +0000 (UTC) Subject: M,I-5,Persecu tion w ho kn ows abou t it? Message-ID: -=-=-=-=-=-=-=-=-=-=-=-=- -= who knows about it?. =- -=-=-=-=-=-=-=-=-=-=-=-=- Many people know, both in the establishment and media, and. among the general. public. Despite an absence of its target from the UK for more than two years, the echoes of paranoia can still. be heard loud and clear from across the water. When it started in 1990, the only. people who knew were those in BBC television who were. spying on my home, and a few radio broadcasters. There were a few cases of public harassment, but. very little compared to the situation that developed a couple of years. later. The list today includes BBC. TV staff (newsreaders such as Martyn Lewis, Michael Buerk, Nicholas. Witchell), people from radio stations such as Chris Tarrant of Capital and. Radio 1 DJs, people in the print media, but also many. people in the general public. All united in a conspiracy which breaks the laws which the UK does have regarding. harassment, and all completely uncaring for any semblance. of decency or elementary respect for. individual rights. The British police (obviously) do know the nature of the. harassment and in all probability the identity of those behind. it. Some time ago I made a complaint to my local police station in London, without positive. result. The UK police are failing in their. duty to see the law enforced in not checking the. abuse. 2773 From DustanGroups at gmail.com Wed Jan 30 18:08:52 2008 From: DustanGroups at gmail.com (Dustan) Date: Wed, 30 Jan 2008 15:08:52 -0800 (PST) Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> Message-ID: <6047713b-c963-404d-af92-7e31053a06c8@v46g2000hsv.googlegroups.com> On Jan 30, 4:47 pm, FireNWater wrote: > I'm curious why the different outputs of this code. If I make the > dictionary with letters as the keys, they are not listed in the > dictionary in alphabetical order, but if I use the integers then the > keys are in numerical order. > > I know that the order of the keys is not important in a dictionary, > but I was just curious about what causes the differences. Thanks!! > > list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] > list2 = [1,2,3,4,5,6,7,8] > > Dictionary = dict(zip(list1, list2)) > print Dictionary > > Dictionary1 = dict(zip(list2, list1)) > print Dictionary1 The underlying order is a result, in part, of the key's hash codes*. Integers are hash coded by their integer values, therefore, they appear in numeric order. Strings, however, use an algorithm that ensures as unique hash codes as possible. Notice the difference: >>> map(hash, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 1, 2, 3, 4, 5, 6, 7, 8]) [-468864544, -340864157, -212863774, -84863387, 43136996, 171137383, 299137766, 427138153, 1, 2, 3, 4, 5, 6, 7, 8] * emphasis on the "in part". Other factors include the amount of memory space available, order added, the current size of the underlying hash table, etc. From deets at nospam.web.de Wed Jan 16 08:54:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jan 2008 14:54:56 +0100 Subject: Unknown cause to error (new to python) References: Message-ID: <5v6glgF1kpndqU1@mid.uni-berlin.de> Brandon Perry wrote: > Hi, I am having to compile a standalone version of python for the web > server I use (they don't allow access to /usr/bin/python). I posted > earlier about a GLib error, but I have fixed that now. I am very close > to getting this to work, but I am getting some weird errors. > > File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", > line 41, in ? > File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", > line 71, in ? File > "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", > line 4, in ? File > "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", > line 4, in ? File > "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", line > 15, in ? > > I am using 2.2 for compatibility purposes. I don't see no error - is that all stacktrace you get? Diez From robert.kern at gmail.com Sat Jan 12 06:39:17 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 12 Jan 2008 05:39:17 -0600 Subject: Is unicode.lower() locale-independent? In-Reply-To: References: Message-ID: John Machin wrote: > On Jan 12, 8:25 pm, Robert Kern wrote: >> The section on "String Methods"[1] in the Python documentation states that for >> the case conversion methods like str.lower(), "For 8-bit strings, this method is >> locale-dependent." Is there a guarantee that unicode.lower() is >> locale-*in*dependent? >> >> The section on "Case Conversion" in PEP 100 suggests this, but the code itself >> looks like to may call the C function towlower() if it is available. On OS X >> Leopard, the manpage for towlower(3) states that it "uses the current locale" >> though it doesn't say exactly *how* it uses it. >> >> This is the bug I'm trying to fix: >> >> http://scipy.org/scipy/numpy/ticket/643 >> http://dev.laptop.org/ticket/5559 >> >> [1]http://docs.python.org/lib/string-methods.html >> [2]http://www.python.org/dev/peps/pep-0100/ > > The Unicode standard says that case mappings are language-dependent. > It gives the example of the Turkish dotted capital letter I and > dotless small letter i that "caused" the numpy problem. See > http://www.unicode.org/versions/Unicode4.0.0/ch05.pdf#G21180 That doesn't determine the behavior of unicode.lower(), I don't think. That specifies semantics for when one is dealing with a given language in the abstract. That doesn't specify concrete behavior with respect to a given locale setting on a real computer. For example, my strings 'VOID', 'INT', etc. are all English, and I want English case behavior. The language of the data and the transformations I want to apply to the data is English even though the user may have set the locale to something else. > Here is what the Python 2.5.1 unicode implementation does in an > English-language locale: > >>>> import unicodedata as ucd >>>> eyes = u"Ii\u0130\u0131" >>>> for eye in eyes: > ... print repr(eye), ucd.name(eye) > ... > u'I' LATIN CAPITAL LETTER I > u'i' LATIN SMALL LETTER I > u'\u0130' LATIN CAPITAL LETTER I WITH DOT ABOVE > u'\u0131' LATIN SMALL LETTER DOTLESS I >>>> for eye in eyes: > ... print "%r %r %r %r" % (eye, eye.upper(), eye.lower(), > eye.capitalize()) > ... > u'I' u'I' u'i' u'I' > u'i' u'I' u'i' u'I' > u'\u0130' u'\u0130' u'i' u'\u0130' > u'\u0131' u'I' u'\u0131' u'I' > > The conversions for I and i are not correct for a Turkish locale. > > I don't know how to repeat the above in a Turkish locale. If you have the correct locale data in your operating system, this should be sufficient, I believe: $ LANG=tr_TR python Python 2.4.3 (#1, Mar 14 2007, 19:01:42) [GCC 4.1.1 20070105 (Red Hat 4.1.1-52)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_ALL, '') 'tr_TR' >>> 'VOID'.lower() 'vo\xfdd' >>> 'VOID'.lower().decode('iso-8859-9') u'vo\u0131d' >>> u'VOID'.lower() u'void' >>> > However it appears from your bug ticket that you have a much narrower > problem (case-shifting a small known list of English words like VOID) > and can work around it by writing your own locale-independent casing > functions. Do you still need to find out whether Python unicode > casings are locale-dependent? I would still like to know. There are other places where .lower() is used in numpy, not to mention the rest of my code. -- 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 paddy3118 at googlemail.com Tue Jan 22 00:15:06 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 21 Jan 2008 21:15:06 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> Message-ID: On Jan 22, 3:20 am, Alan Isaac wrote: > I want to generate sequential pairs from a list. <> > What is the fastest way? (Ignore the import time.) 1) How fast is the method you have? 2) How much faster does it need to be for your application? 3) Are their any other bottlenecks in your application? 4) Is this the routine whose smallest % speed-up would give the largest overall speed up of your application? - Paddy. From sjmachin at lexicon.net Thu Jan 31 17:11:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 31 Jan 2008 14:11:27 -0800 (PST) Subject: pyExcelerator - Can I read and modify an existing Excel-WorkBook? References: Message-ID: On Feb 1, 4:37 am, Stephen Brown wrote: > Yes indeed, pyExcelerator does support reading data from excel > spreadsheets. I presume this is an orphaned and belated reply to the 3-message thread in July 2006 with the same subject. > An example of how to do this is included in the file > xls2csv-gerry.py under the directory ... pyExcelerator/examples/tools > Syntax is pretty straight forward. extract_all = parse_xls(filename, CP > = None) where CP is the encoding format used within tht file. The OP was aware of pyExcelerator's parse_xls, but required formatting information: """ To me it seems, that pyExcelerator does not support the reading for modification of an Excel-sheet. It allows only the "parse_xls" but I would like to keep the "formatting" in the template. """ > Uses > same codes that xlrd uses, ie 'cp437' = US English. An interesting way of describing it. It is *not* restricted to being a "codepage". The arg can be any Python-supported encoding that can be passed to str.decode to convert internal 8-bit strings to unicode. > > All you need is the "parse_xls" command and simply let it iterate > through your spreadsheet file. [snip] Current situation: I am (sporadically) maintaining xlwt, a fork of pyExcelerator which among other things fixes bugs and enables use with Python 2.3. It is available from https://secure.simplistix.co.uk/svn/xlwt/trunk xlwt.parse_xls is the same as pyExcelerator.parse_xls and thus has the same deficiencies e.g. it reports a date as a floating-point number of days since some more-or-less-fixed epoch and provides no indication that the item should be interpreted as a date. It will not be maintained, and is severely deprecated -- use xlrd instead. HTH, John From fredrik at pythonware.com Wed Jan 9 08:03:05 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 14:03:05 +0100 Subject: PIL question In-Reply-To: References: Message-ID: Alex K wrote: > Would anyone know how to generate thumbnails with rounded corners > using PIL? I'm also considering imagemagick if PIL turns out not to be > appropriate for the task. create a mask image with round corners (either with your favourite image editor or using ImageDraw/aggdraw or some such). in your program, load the mask image, and cut out the four corners using "crop". then, for each image, create a thumbnail as usual, and use the corner masks on the corners of the thumbnail. - if you want transparent corners, create an "L" image with the same size as the thumbnail, use "paste" to add the corner masks in that image, and then use "putalpha" to attach the alpha layer it to the thumbnail. - if you want solid corners, use "paste" on the thumbnail instead, using a solid color as the source. From sjmachin at lexicon.net Mon Jan 21 16:47:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jan 2008 13:47:06 -0800 (PST) Subject: index of min element of sequence References: <7xfxwrt1dx.fsf@ruckus.brouhaha.com> <6243b2e3-e2eb-41fb-bb7c-88b40ffcef60@e25g2000prg.googlegroups.com> <7xabmyyk29.fsf@ruckus.brouhaha.com> Message-ID: On Jan 22, 7:56 am, Paul Rubin wrote: > John Machin writes: > > s/[1]/[0]/ or more generally: > > Oops, got two spellings confused. Originally was going to use > > from itertools import count, izip > min(izip(seq, count()))[1] > > but did it with enumerate instead. I don't know which is actually > faster. > > > minindex, minvalue = min(enumerate(seq), key=itemgetter(1)) > > Cool, I like this best of all. Or alternatively, > > minindex, minvalue = min(izip(seq, count())) Bzzzt #2! >>> from itertools import count, izip >>> min(izip(seq, count())) (7, 3) From Russ.Paielli at gmail.com Tue Jan 8 01:08:54 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 7 Jan 2008 22:08:54 -0800 (PST) Subject: use fileinput to read a specific line References: <6f2db44c-2641-47cb-ab24-4177ccc96d6e@m77g2000hsc.googlegroups.com> <13o637afk4mql0c@corp.supernews.com> Message-ID: <44c28069-12bf-43c2-96f6-06b4c3923188@41g2000hsy.googlegroups.com> > Given that the OP is talking 2000 files to be processed, I think I'd > recommend explicit open() and close() calls to avoid having lots of I/O > structures floating around... Good point. I didn't think of that. It could also be done as follows: for fileN in files: lnum = 0 # line number input = file(fileN) for line in input: lnum += 1 if lnum >= 4: break input.close() # do something with "line" Six of one or half a dozen of the other, I suppose. From arkanes at gmail.com Thu Jan 3 14:06:07 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 3 Jan 2008 13:06:07 -0600 Subject: reassign to builtin possible !? In-Reply-To: <477CEB93.8000706@tim.thechases.com> References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> <477CEB93.8000706@tim.thechases.com> Message-ID: <4866bea60801031106j70d496caw8e1a60e6931ab4fc@mail.gmail.com> On Jan 3, 2008 8:05 AM, Tim Chase wrote: > >> But you can't alter the values for True/False globally with this. > > > > Are you sure ? what about the following example ? > > Is this also shadowing ? > > > >>>> import __builtin__ > >>>> __builtin__.True = False > >>>> __builtin__.True > > False > > It doesn't seem to screw things up globally > > >>> import __builtin__ > >>> t = __builtin__.True > >>> __builtin__.True = False > >>> __builtin__.False = t > >>> True > False > >>> False > True > >>> 1 == 1 > True > >>> import os > >>> os.path.isdir('.') > True > >>> #if they were globally redefined, this would be False > >>> #you'd have to actually reference __builtin__.True > > My thought would be if you do something as daft as > redefining/shadowing True and False, you get the headaches that > ensue. Fortunately, since Python is explicit, you can trace back > through the code and see where the inanity occurred. > Additionally, any scoping rules mean that programmer stupidity > can't leak too badly outside the scope of the block containing > the stupidity. > > It's the old "DIHWIDT! WDDT!" ("Doctor, it hurts when I do > this!", "well don't do that!") syndrome. > In Py3k this will be a syntax error, like assigning to None is now. Possibly also in 2.6. From jo at durchholz.org Thu Jan 3 10:13:55 2008 From: jo at durchholz.org (Joachim Durchholz) Date: Thu, 03 Jan 2008 16:13:55 +0100 Subject: Choosing a new language In-Reply-To: References: <20071228162351.f29a3ce4.coolzone@it.dk> Message-ID: Tim Roberts schrieb: > Joachim Durchholz wrote: > >>> Xah Lee wrote: >>>> [...] PHP and Perl are practically identical in their >>>> high-levelness or expressiveness or field of application (and >>>> syntax), >> That must have been a very, very distant point of view with narrowly >> squinted eyes. > > Do you really think so? It seems clear to me that the syntax of PHP was > heavily influenced by Perl. PHP lacks the @array and %hash weirdnesses, > but most PHP code will work just fine as Perl. Quite unlikely. It won't even parse. PHP code starts with and the next Do I have to install something extra to use the new look? Robert From steven at REMOVE.THIS.cybersource.com.au Tue Jan 15 23:36:27 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Jan 2008 04:36:27 -0000 Subject: no pass-values calling? References: Message-ID: On Wed, 16 Jan 2008 11:09:09 +0800, J. Peng wrote: > Hello, > > I saw this statement in Core Python Programming book, > > All arguments of function calls are made by reference, meaning that any > changes to these parameters within the function affect the original > objects in the calling function. > > > Does this mean there is not pass-values calling to a function in python? > only pass-reference calling? Thanks! No, Python does not use either pass by reference or pass by value. It uses pass by object. (Sometimes called "pass by object reference".) See: http://effbot.org/zone/call-by-object.htm for further details. -- Steven From grante at visi.com Sat Jan 5 09:40:06 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 05 Jan 2008 14:40:06 -0000 Subject: Question on os.tempnam() vulnerability References: <13nt81gftkfa32d@corp.supernews.com> Message-ID: <13nv5m68qeknk1f@corp.supernews.com> On 2008-01-05, Jarek Zgoda wrote: >> Under Windows, is there a "safe" way to create a temp file >> that has a name that can be passed to a program which will >> then open it? I never figured out a way to do that and had to >> fall back on the "unsafe" tmpnam method. > > I think it's all impossible to get only file name and feel > safe. You have to have both file name and a file object opened > exclusively for you. Any other way you'll get a possible race > condition. I know. That's the point of my question: how do you do that under Windows? -- Grant Edwards grante Yow! HAIR TONICS, please!! at visi.com From over at thepond.com Wed Jan 23 13:47:37 2008 From: over at thepond.com (over at thepond.com) Date: Wed, 23 Jan 2008 18:47:37 GMT Subject: python24 symbol file...pyhon24.pdb References: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> <479706a0$0$13412$9b622d9e@news.freenet.de> Message-ID: <3u2fp3ht1cr9avj68qvf26qqsh0jiqh9co@4ax.com> On Wed, 23 Jan 2008 10:19:28 +0100, "Martin v. L?wis" wrote: >> Also, is there source code available for python24 for Windoze? I have >> seen reference to source code but not in a package for Windows. > >It's available from > >http://www.python.org/ftp/python/2.4/Python-2.4.tgz > >Regards, >Martin thanks you kindly. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 30 17:09:03 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 30 Jan 2008 23:09:03 +0100 Subject: Events in Python References: <2b005569-3dbc-41c1-aebf-8b6fd8d2175e@v46g2000hsv.googlegroups.com> Message-ID: <60carvF1q0a0rU1@mid.individual.net> Ivan Illarionov wrote: > Note that all those signals/events are very slow in Python. Compared to what, did you measure something? Regards, Bj?rn -- BOFH excuse #38: secretary plugged hairdryer into UPS From ajaksu at gmail.com Sat Jan 19 18:22:01 2008 From: ajaksu at gmail.com (ajaksu) Date: Sat, 19 Jan 2008 15:22:01 -0800 (PST) Subject: Python 3000 and import __hello__ References: Message-ID: <952a1ed8-638b-4c78-abd7-1dc62fdc837d@z17g2000hsg.googlegroups.com> On Jan 19, 7:54 pm, Brad wrote: > Just playing around with Python3000 a2 release on Windows XP 32-bit x86. > > import __hello__ > > doesn't print 'hello world...' as it does on 2.5 Thanks for spoiling this easter egg for me! ;) From brkict at gmail.com Mon Jan 21 12:25:57 2008 From: brkict at gmail.com (glomde) Date: Mon, 21 Jan 2008 09:25:57 -0800 (PST) Subject: is it possible to set namespace to an object. Message-ID: <27529efd-b8d8-4a8e-b72d-379a607366b7@i7g2000prf.googlegroups.com> Hi, is it somehow possible to set the current namespace so that is in an object. Somthing like. class Test(): .... testObj = Test() set namespace testObj Name = "Test" Name would set testObj.Name to "Test". I was thinking this could be done with the with statement somehow (without using as) in the __enter__ function. Is the above possible? /T From http Thu Jan 10 21:22:35 2008 From: http (Paul Rubin) Date: 10 Jan 2008 18:22:35 -0800 Subject: Best way to merge/sort two sorted lists?... References: <1230064b-603d-4386-b68c-a913c5cf80d3@s12g2000prg.googlegroups.com> <60572417-9e83-4d0c-80da-2c99a9bd19e4@b40g2000prf.googlegroups.com> <232c569b-783a-43b8-bdb0-2d578bac037b@s8g2000prg.googlegroups.com> Message-ID: <7xfxx5cd90.fsf@ruckus.brouhaha.com> Aaron Watters writes: > The second one is! That's why it works so fast. > Tim Peters optimized this case! > Gotta hand it to Tim Peters. The first one should > win some sort of obfuscated code contest, imho. > It also seems to be 5 times slower than any of the others. The heapq method is the right way to do it when you want to merge n lists instead of two lists. Each selection takes O(log n) operations. From superwesman at gmail.com Wed Jan 16 00:41:01 2008 From: superwesman at gmail.com (superwesman) Date: Tue, 15 Jan 2008 21:41:01 -0800 (PST) Subject: can't find pyAntTasks.properties Message-ID: <3d1efa8c-ab6a-487d-abe6-63f227a895fc@i29g2000prf.googlegroups.com> Hi - I'm trying to use pyAntTasks. I downloaded the jar and placed it into ~/.ant/lib, put that directory into my CLASSPATH. I then created a very simple build.xml and I'm getting a failure I can't explain. Here is my build.xml: Here is my CLASSPATH: > echo $CLASSPATH /home/wtorres/.ant/lib And here's what's in it: > ls -lrt $CLASSPATH total 24 -rwxrwxr-x 1 wtorres staff 8563 Jan 15 18:34 pyAntTasks.jar When I run ant, here is the failure: (the 'ant' script I'm running here sets up ant 1.6.2 and runs it) > /vobs/jfw/ant ANT=/tools/ant/1.6.2 Buildfile: build.xml [taskdef] Could not load definitions from resource pyAntTasks.properties. It could not be found. BUILD SUCCESSFUL Total time: 1 second What the heck am I doing wrong? Where can I find pyAntTasks.properties? I mean, it makes sense that "It could not be found" because I can't find it either. Where do I get/put this? Thanks -w From deets at nospam.web.de Fri Jan 25 09:19:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jan 2008 15:19:50 +0100 Subject: Terse Syntax through External Methods In-Reply-To: References: Message-ID: <5vu9gaF1no9i1U1@mid.uni-berlin.de> Jens schrieb: > Hello Everyone > > I'm newbie to Zope and i have a few questions regarding external > methods. What i wan't to do > is provide a terse syntax for converting urls to special tracking > urls: > > > > turns the provided url into something like > > http://host/tracking?url=http%3A%2F%2Fmyurl%2F > > in the output. > > i've been trying to use a external procedure like this. > > ## Script (Python) "track_link" > ##bind container=container > ##bind context=context > ##bind namespace=_ > ##bind script=script > ##bind subpath=traverse_subpath > ##parameters=self,url > ##title=track link > ## > return "%s%s" % (self.tracking_prefix, url_quote(url)) > > This doesn't work because because the method doesn't have access to > the environment. Obviously I don't wan't to pass everything explicitly > into the function as this would defeat the purpose of the exercise, > namely to provide a terse syntax. > > I have a background in other languages so I might be missing something > conceptually with regard Zope and DTML.. Is there a better was of > doing this, perhaps without using external methods? Currently im doing > the following which isn't very elegant: > > in content document > tracking>">link > ... > tracking: > > > Appreciate any input you might have on this- Is it really needed to use an external method for this, or isn't a "normal" python script enough already? If it has to be an External method, you can't access such a context AFAIK. But then you can create a python script that _has_ this context, and passese it to the external method. Not the nicest solution, but should work. Diez From shriphanip at gmail.com Tue Jan 1 07:21:29 2008 From: shriphanip at gmail.com (Shriphani) Date: Tue, 1 Jan 2008 04:21:29 -0800 (PST) Subject: pdf library. References: <133097f4-de83-4e13-93f1-1404213333a4@l6g2000prm.googlegroups.com> Message-ID: <3b429178-8c07-4dcb-8034-1912c0597830@d21g2000prf.googlegroups.com> On Jan 1, 4:28 pm, Piet van Oostrum wrote: > >>>>>Shriphani (S) wrote: > >S> I tried pyPdf for this and decided to get the pagelinks. The trouble > >S> is that I don't know how to determine whether a particular page is the > >S> first page of a chapter. Can someone tell me how to do this ? > > AFAIK PDF doesn't have the concept of "Chapter". If the document has an > outline, you could try to use the first level of that hierarchy as the > chapter starting points. But you don't have a guarantee that they really > are chapters. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org How would a pdf to html conversion work ? I've seen Google's search engine do it loads of times. Just that running a 500odd page ebook through one of those scripts might not be such a good idea. From robert.kern at gmail.com Fri Jan 4 21:45:32 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 04 Jan 2008 20:45:32 -0600 Subject: vim newb - indenting python comments In-Reply-To: <477EE677.1030908@tim.thechases.com> References: <477EE677.1030908@tim.thechases.com> Message-ID: Tim Chase wrote: >> One problem I have is that the >> indent in normal mode doesn't work >> when a line starts with the # character. Any idea what I'm doing >> wrong? > > In short, ">>" *does* indent in normal mode (I presume you > accurately mean "Normal" mode, rather than "Insert" mode). The > question becomes why doesn't it work in your particular copy of Vim? > > To evidence this, start vim with > > vim -u NONE myfile.py > > (which bypasses startup files) and you'll see that >> does indeed > shift commented lines. > > To track down the problem, you'll need to provide a little more > info. Starting Vim the way you normally do, pointed at a > problematic python file, what is the output of > > :scriptnames > > What mappings do you have defined: > > :nmap > > (particularly any mappings for ">" and its kin). > > What are your filetype settings: > > :filetype > > What are your settings for 'indentkeys', 'indentexpr', > 'shiftwidth', 'tabstop', 'expandtab' and 'filetype' > > :set indentkeys? indentexpr? sw? ts? et? ft? :set cindent? Having this set (in the absence of anything else) will replicate the behavior for me (vim 7.1 OS X). :filetype plugin on :filetype indent on Fixes it. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From nospam at invalid.com Sat Jan 12 01:07:07 2008 From: nospam at invalid.com (Jack) Date: Sat, 12 Jan 2008 06:07:07 GMT Subject: Using a proxy with urllib2 References: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> <87ir21o8sj.fsf@merkury.smsnet.pl> Message-ID: >> I'm trying to use a proxy server with urllib2. >> So I have managed to get it to work by setting the environment >> variable: >> export HTTP_PROXY=127.0.0.1:8081 >> >> But I wanted to set it from the code. However, this does not set the >> proxy: >> httpproxy = '127.0.0.1:3129' >> proxy_support = urllib2.ProxyHandler({"http":"http://" + httpproxy}) >> opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) >> urllib2.install_opener(opener) I find out why it doesn't work in my code but I don't have a solution - somewhere else in the code calls these two lines: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) and they override the proxy opener. Could anyone tell me how to use both openers? From pofuk at mzm.hr Thu Jan 17 19:13:56 2008 From: pofuk at mzm.hr (SMALLp) Date: Fri, 18 Jan 2008 01:13:56 +0100 Subject: Downlod from FTP, pickle Message-ID: Hy! I have a little problem. I have to download file from FTP sp i use ftplib. And then i have to pickle.load from that file. I make callback function that saves line by line into temporary file and now i cant read from that file and when i close it i diapers. Thanks! From rw at smsnet.pl Thu Jan 10 13:28:11 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 10 Jan 2008 19:28:11 +0100 Subject: urllib2 rate limiting References: Message-ID: <87ejcpo7r8.fsf@merkury.smsnet.pl> Dimitrios Apostolou writes: > P.S. And something simpler: How can I disallow urllib2 to follow > redirections to foreign hosts? You need to subclass `urllib2.HTTPRedirectHandler`, override `http_error_301` and `http_error_302` methods and throw `urllib2.HTTPError` exception. http://diveintopython.org/http_web_services/redirects.html HTH, Rob From martin at marcher.name Mon Jan 21 08:57:31 2008 From: martin at marcher.name (Martin Marcher) Date: Mon, 21 Jan 2008 14:57:31 +0100 Subject: [OT] Valid Mail addresses modifications (WAS: Re: Looping through the gmail dot trick) References: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> Message-ID: Martin Vilcans wrote: > Try the SMTP spec. IIRC there's a passage there that says that the > server should try to make sense of addresses that don't map directly > to a user name. Specifically, it says that firstname.lastname should > be mapped to the user with those first and last names. Short story long: there aren't any! FYI: https://mail.google.com/support/bin/answer.py?answer=10313&topic=1564 that was the only reference i found, http://www.ietf.org/rfc/rfc0821.txt doesn't mention anything beside EXPN which still treats the localpart literally and checks for a mailbox (or alias) as literally found in the localpart. Personally I think google's doing wrong here. Just don't do it anywhere else, as it's unlikely your mail will reach the person you intended to send it. -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From fredrik at pythonware.com Sun Jan 6 05:01:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 06 Jan 2008 11:01:11 +0100 Subject: python interfaces In-Reply-To: <96b70141-f872-413a-a433-08b217cecb27@e4g2000hsg.googlegroups.com> References: <96b70141-f872-413a-a433-08b217cecb27@e4g2000hsg.googlegroups.com> Message-ID: r.grimm at science-computing.de wrote: > Interfaces are a extremly smart Design Principle in static typed > languages like Java and C++. that's somewhat questionable in itself, and even more questionable as an argument for interfaces in Python. I'd recommend anyone who thinks that they cannot program without formal interfaces to try using Python as Python for a while, before they try using it as something else. you might be surprised over how easy it is to build robust stuff without having to add lots of extra constraints to your code. From marduk at python.invalid Mon Jan 21 02:00:11 2008 From: marduk at python.invalid (Albert Hopkins) Date: Mon, 21 Jan 2008 01:00:11 -0600 Subject: When is min(a, b) != min(b, a)? References: Message-ID: On Sun, 20 Jan 2008 20:16:18 -0800, Paddy wrote: > I am definitely NOT a floating point expert, but I did find this: > http://en.wikipedia.org/wiki/IEEE_754r#min_and_max > > P.S. What platform /Compiler are you using for Python? Linux with GCC 4 -a From grahn+nntp at snipabacken.dyndns.org Sun Jan 20 09:59:43 2008 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 20 Jan 2008 14:59:43 GMT Subject: Core Python Programming . . . References: <7xir1q29j5.fsf@ruckus.brouhaha.com> <0005f532-409b-4c4e-8483-b2e32bbc724a@q77g2000hsh.googlegroups.com> Message-ID: On Sat, 19 Jan 2008 08:57:24 -0500, Yu-Xi Lim wrote: > FireNWater wrote: > >> I guess I'm not fully up to speed on what constitutes an IP address. >> Does the term 'octet' refer to an 8-bit (xFF) number? > > Yes, it somewhat archaic though. It's more precise than byte, like you say. I don't think its archaic though; it's a fairly common term when you are talking data communication in general and IP-based protocols in particular. > It's used when "byte" is ambiguous. On > some ancient (by computing standards) computers, the size of a byte may > be as small as 6 bits or as big as 9. On ancient computers and in some embedded processors. I have a Texas Instruments DSP in my cellphone with 16-bit words. A C "char" is 16 bits in that environment. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From http Fri Jan 11 09:00:13 2008 From: http (Paul Rubin) Date: 11 Jan 2008 06:00:13 -0800 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <7xir21lzmo.fsf@ruckus.brouhaha.com> Message-ID: <7xprw8xy1e.fsf@ruckus.brouhaha.com> Fredrik Lundh writes: > (and if you use sane naming conventions, the risk for collisions is > near zero as well). I haven't felt that way, I'm always worried about clobbering something by leaking a variable. Maybe collisions don't really happen much, but it's always seemed cleaner to me to use the most restricted scopes possible just to minimize or eliminate the possibility. This is especially attractie in a language like Python, with no declarations and no compile-time type safety. From goon12 at gmail.com Tue Jan 29 14:02:29 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 29 Jan 2008 14:02:29 -0500 Subject: noob stuck on reading double In-Reply-To: <6a2ccd190801291059q1a18c70co8e9db881c6994f63@mail.gmail.com> References: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk> <6a2ccd190801291059q1a18c70co8e9db881c6994f63@mail.gmail.com> Message-ID: <6a2ccd190801291102m457f1fb9odca04ef24fb47ac3@mail.gmail.com> On Jan 29, 2008 1:59 PM, Joe Riopel wrote: > When reading the file, try using > file = open('data.bin', 'rb') > file.seek(0) > raw = file.read() > > Do the unpack on "raw". Ignore this, sorry for the confusion. From fredrik at pythonware.com Thu Jan 10 14:52:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 20:52:07 +0100 Subject: What is "lambda x=x : ... " ? In-Reply-To: <20080110144135.20e55ec3@bhuda.mired.org> References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> <20080110134335.37cf5377@mbook.mired.org> <20080110144135.20e55ec3@bhuda.mired.org> Message-ID: Mike Meyer wrote: >>>> What does "y=y" and "c=c" mean in the lambda function? >>> >>> Older versions of python didn't make variables in an outer scope >>> visible in the inner scope. This was the standard idiom to work >>> around that. >>> >> lexically scoped free variables and object binding are two different >> things, and have different semantics. the former does not always >> replace the latter. > > And? and what? it's not the same thing. the "newer" idiom only replaces the "older" idiom under certain circumstances (such as in the OP's first example, but *not* in his second example). From arnodel at googlemail.com Tue Jan 22 09:19:24 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 06:19:24 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: On Jan 22, 1:19?pm, Alan Isaac wrote: [...] > PS My understanding is that the behavior > of the last is implementation dependent > and not guaranteed. [...] > def pairs4(x): > ? ? xiter = iter(x) > ? ? for x12 in izip(xiter,xiter): > ? ? ? ? yield x12 According to the docs [1], izip is defined to be equivalent to: def izip(*iterables): iterables = map(iter, iterables) while iterables: result = [it.next() for it in iterables] yield tuple(result) This guarantees that it.next() will be performed from left to right, so there is no risk that e.g. pairs4([1, 2, 3, 4]) returns [(2, 1), (4, 3)]. Is there anything else that I am overlooking? [1] http://docs.python.org/lib/itertools-functions.html -- Arnaud From sjmachin at lexicon.net Tue Jan 29 15:29:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 30 Jan 2008 07:29:31 +1100 Subject: noob stuck on reading double In-Reply-To: References: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk> <6a2ccd190801291059q1a18c70co8e9db881c6994f63@mail.gmail.com> <6a2ccd190801291102m457f1fb9odca04ef24fb47ac3@mail.gmail.com> Message-ID: <479F8CAB.7060203@lexicon.net> [I can't see Hannah's posting(s) with my news client (Thunderbird), nor with Google Groups] Joe Riopel wrote: > Since you're unpacking it with the 'd' format character I am assuming > a "doubleword" field is a double. Given Hannah has sensibly stated up front that she is a noob, I would assume nothing from her code. Given "doubleword" is Intel/MS-speak for "32-bit quantity", and following the strong hint of repeat-every-4-bytes from the printed gibberish (e.g. "Q???Q???Q???Q???Q?") I'd *guess* that a "doubleword" is a signed or unsigned 32-bit integer. Now let's check the guess: > You said you had 113 of them in the > binary file. There are about 170 bytes of gibberish, that I saw in Joe's second reply. Hannah, don't do: print gibberish do: print len(gibberish), repr(gibberish) What is the size of the file? 4 * 113 -> 452, 8 * 113 = 904 > You should be doing something like this: > > file = open('data.bin', 'rb') don't shadow the 'file' built-in function > file.seek(0) where else would it be positioned??? > raw = file.read() > unpacked = unpack('113d', raw) > for i in range(0,113): > print unpacked[i] > file.close() I suggest that Hannah try something like this: from struct import unpack f = open('data.bin', 'rb') raw = f.read() nbytes = len(raw) print 'nbytes', nbytes print '32-bit signed integer', unpack('<%di' % (nbytes // 4), raw) print '32-bit unsigned integer', unpack('<%dI' % (nbytes // 4), raw) print '64-bit floating point', unpack('<%dd' % (nbytes // 8), raw) and choose depending on what output best meets her expectations. Note: the "<" in the above is another guess based on "doubleword" -> Intel -> little-endian. If struct.unpack is unhappy or if all three results look like rubbish, change the "<" to a ">" and try again ... if in doubt, come back for more advice. If you do, please include the output from starting Python at the shell prompt and peeking at sys.byteorder -- this i swhat that produces on my machine: C:\junk>python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys; sys.byteorder 'little' >>> HTH, John From asmodai at in-nomine.org Thu Jan 10 03:13:37 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 10 Jan 2008 09:13:37 +0100 Subject: Conventions for dummy name (was: for loop without variable) In-Reply-To: <873at6k2qt.fsf_-_@benfinney.id.au> References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de> <873at6k2qt.fsf_-_@benfinney.id.au> Message-ID: <20080110081337.GU75977@nexus.in-nomine.org> -On [20080110 00:21], Ben Finney (bignose+hates-spam at benfinney.id.au) wrote: >The problem with the '_' name is that it is already well-known and >long-used existing convention for an entirely unrelated purpose: in >the 'gettext' i18n library, the '_' function to get the >locally-translated version of a text string. The same applies for Babel (http://babel.edgewall.org/) where we have _() in similar vein to the gettext implementation. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ With a nuclear fire of Love in our Hearts, rest easy baby, rest easy... From brian at briansmith.org Thu Jan 17 07:29:05 2008 From: brian at briansmith.org (Brian Smith) Date: Thu, 17 Jan 2008 04:29:05 -0800 Subject: Some Berkeley DB questions (being maintained? queries?) In-Reply-To: <0ba30836-8e2d-4061-94ea-ccddb24bc290@s19g2000prg.googlegroups.com> References: <0ba30836-8e2d-4061-94ea-ccddb24bc290@s19g2000prg.googlegroups.com> Message-ID: <003601c85904$904150c0$0401a8c0@T60> HerbAsher at googlemail.com wrote: > 1. Now that Berkeley DB is part of Oracle, is it still being > maintained? Is it free? Berkeley DB is owned by Oracle, but it is seperate from the Oracle RDBMS product. Yes, it is free. > 2. Are there good python libraries for bdb available, that > are being maintained? I would like to know the answer to this question too--if you have used the pybsddb/bsddb.db module, please share your experience. > 3. Is it possible to query a berkeley db database? Just > simple queries like: find me all items where key "name" = "John" That is basically the only kind of query that a Berkeley DB database can do: key [<|=|>] value. > 4. What are good, stable alternatives? That depends soley on your requirements. Berkeley DB is actually one of the most complicated persistence solutions. It is more complex than SQLite, and WAY more complex than gdbm, for example. If you don't need all its functionality, especially its multi-user capabilities, then I recommend using something simpler. However, if you DO need its multi-user cabailities or its advanced features like secondary indexes, then it is better to use Berkeley DB than to re-invent it. - Brian From rrr at ronadam.com Sun Jan 13 23:08:39 2008 From: rrr at ronadam.com (Ron Adam) Date: Sun, 13 Jan 2008 22:08:39 -0600 Subject: time.time or time.clock In-Reply-To: References: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> Message-ID: <478AE047.8070306@ronadam.com> Fredrik Lundh wrote: > John Machin wrote: > >> AFAICT that was enough indication for most people to use time.clock on >> all platforms ... > > which was unfortunate, given that time.clock() isn't even a proper clock > on most Unix systems; it's a low-resolution sample counter that can > happily assign all time to a process that uses, say, 2% CPU and zero > time to one that uses 98% CPU. > > > before the introduction of the timeit module; have you considered it? > > whether or not "timeit" suites his requirements, he can at least replace > his code with > > clock = timeit.default_timer > > which returns a good wall-time clock (which happens to be time.time() on > Unix and time.clock() on Windows). Thanks for the suggestion Fredrik, I looked at timeit and it does the following. import sys import time if sys.platform == "win32": # On Windows, the best timer is time.clock() default_timer = time.clock else: # On most other platforms the best timer is time.time() default_timer = time.time I was hoping I could determine which to use by the values returned. But maybe that isn't as easy as it seems it would be. Ron From tjreedy at udel.edu Mon Jan 28 22:48:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jan 2008 22:48:11 -0500 Subject: Python self-evaluating strings References: <1BEEBF03-1A38-4745-B08B-DCA3106D1CC5@gmail.com> Message-ID: "Arnaud Delobelle" wrote in message news:a04ca850-fe63-4b7e-abff-cdacab3bcc0f at i29g2000prf.googlegroups.com... | I found this: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a1316cb4e216eba4/0cda739385abd03c?lnk=gst&q=Self-Reproducing+Program#0cda739385abd03c Exactly the one I meant. | It contains a lambda-solution similar to mine, only more concise: | (lambda x:x%`x`)('(lambda x:x%%`x`)(%s)') Being a Lisp novice, I was rather proud of that translation | I have been using python for 7 years, and it the first time ever that | I see the `...` construct being used! It is going away in 3.0, so the above would need revision to work with repr(), if indeed it will. | Thanks You're welcome Terry From mobiledreamers at gmail.com Mon Jan 14 00:51:20 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Sun, 13 Jan 2008 21:51:20 -0800 Subject: Recieving emails in python Message-ID: I m trying to create something simple a mailing list similar to yahoo groups I m stumbling at the part where the python recieves messages via say python at yahoogroups.com how to make python recieve emails and process it after that it is straight forward processing in python inserting in db etc -------------- next part -------------- An HTML attachment was scrubbed... URL: From buzzard at urubu.freeserve.co.uk Sat Jan 19 11:30:41 2008 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Sat, 19 Jan 2008 16:30:41 +0000 Subject: TopSort in Python? In-Reply-To: <12f0f54e-5d30-40bc-9135-2c59b8a5acc2@i3g2000hsf.googlegroups.com> References: <0000161d@bossar.com.pl> <358cc5a3-300f-49ba-9857-2f0cd629a4df@i12g2000prf.googlegroups.com> <12f0f54e-5d30-40bc-9135-2c59b8a5acc2@i3g2000hsf.googlegroups.com> Message-ID: Carl Banks wrote: > On Jan 18, 7:01 pm, Paddy wrote: >> On Jan 18, 9:47 pm, startec... at gmail.com wrote:> Tim, >> >>> Thanks for the topsort code. It would be useful in a project I'm >>> working on. Can I use the code for free under public domain? Thanks! >> When I needed one I didn't know the name. I'm curious, how did you >> know to look for the topological sort algorithm by name? > > I spent quite a bit of time looking for this one myself. It was quite > a stumper. Sometimes Google gets us in the habit of just firing > random search terms when we ought to be thinking it out. > > After quite of bit of dead end searching--like a week--I stepped back, > thought about what I was looking for. I wanted a sort of dependency > system: A must happen before B. What other programs do that? make, > of course. I looked at the documents for make and found the term > "directed acyclic graph", and pretty much instantly knew I had it. Searching for "precedence diagram" might throw up some relevant results; but you've probably already discovered that. I have some basic precedence diagram code (no warranty etc.) somewhere if anyone is interested. Duncan From rw at smsnet.pl Thu Jan 10 09:09:56 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 10 Jan 2008 06:09:56 -0800 (PST) Subject: New Tk look (aka Ttk or Tile widgets) References: Message-ID: <89e08cf4-a815-412b-b575-ccd770a7f0d3@v4g2000hsf.googlegroups.com> Robert Hicks napisa?(a): > Do I have to install something extra to use the new look? I managed to use Tile with Tk 8.4 and Python 2.5. After installing Tile I followed these advices: http://tkinter.unpythonic.net/wiki/UsingTile and used this code: http://tkinter.unpythonic.net/wiki/TileWrapper Actually, I wanted to use Treeview, so I needed to tweak a little bit this code, but it's very simple to do. HTH, Rob From rw at smsnet.pl Sat Jan 12 07:16:02 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Sat, 12 Jan 2008 13:16:02 +0100 Subject: Using a proxy with urllib2 References: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> <87ir21o8sj.fsf@merkury.smsnet.pl> Message-ID: <874pdjck8t.fsf@merkury.smsnet.pl> "Jack" writes: >>> I'm trying to use a proxy server with urllib2. >>> So I have managed to get it to work by setting the environment >>> variable: >>> export HTTP_PROXY=127.0.0.1:8081 >>> >>> But I wanted to set it from the code. However, this does not set the >>> proxy: >>> httpproxy = '127.0.0.1:3129' >>> proxy_support = urllib2.ProxyHandler({"http":"http://" + httpproxy}) >>> opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) >>> urllib2.install_opener(opener) > > I find out why it doesn't work in my code but I don't have a solution - > somewhere > else in the code calls these two lines: > > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > urllib2.install_opener(opener) > > and they override the proxy opener. Could anyone tell me how to use both > openers? > You don't have to create another opener if you only want to add some handler. You can use `add_handler` method, e.g.: opener.add_handler(urllib2.HTTPCookieProcessor(cj)) HTH, Rob From wuhrrr at gmail.com Thu Jan 17 04:47:20 2008 From: wuhrrr at gmail.com (Hai Vu) Date: Thu, 17 Jan 2008 01:47:20 -0800 (PST) Subject: reading a specific column from file References: Message-ID: <3149e879-b94d-443c-b056-d6cf5bad2688@h11g2000prf.googlegroups.com> Here is another suggestion: col = 2 # third column filename = '4columns.txt' third_column = [line[:-1].split('\t')[col] for line in open(filename, 'r')] third_column now contains a list of items in the third column. This solution is great for small files (up to a couple of thousand of lines). For larger file, performance could be a problem, so you might need a different solution. From papilonv at gmail.com Sat Jan 19 05:32:28 2008 From: papilonv at gmail.com (Vikas Jadhav) Date: Sat, 19 Jan 2008 16:02:28 +0530 Subject: Help! - Invoke setup.py file Message-ID: <7856b4e60801190232j3b1a18b5n3630ddf77aed9ee0@mail.gmail.com> Hi, We have setup of SVGMath* 0.3.2 (Converter- Mathml 2.0 coding to SVG). The setup folder contains setup.py file but we are not able to initiate this file. Kindly help us, resolution to this query will be appreciated. Python version: Installed on PC- 2.5.1 and OS- Windows 2000. * *SVGMath* is a *command*-line utility to convert MathML expressions to SVG, written entirely in Python. Note: Attached file contains SVGMath installation components. Cheers, Vikas -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: SVGMath-0.3.2.zip Type: application/zip Size: 77473 bytes Desc: not available URL: From stefan.behnel-n05pAM at web.de Thu Jan 3 03:08:36 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 03 Jan 2008 09:08:36 +0100 Subject: ElementTree should parse string and file in the same way In-Reply-To: References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> Message-ID: <477C9804.40003@web.de> Hi, Chris Mellon wrote: > On that note, I really don't like APIs that take either a file name or > a file object - I can open my own files, thanks. ... and HTTP URLs, and FTP URLs. In lxml, there is a performance difference between passing an open file (which is read in Python space using the read() method) and passing a file name or URL, which is passed on to libxml2 (and thus doesn't require the GIL at parse time). That's only one reason why I like APIs that allow me to pass anything that points to a file - be it an open file object, a local file path or a URL - and they just Do The Right Thing with it. I find that totally pythonic. > open(fname) is even shorter than StringIO(somedata). It doesn't serve the same purpose, though. > My take on the API decision in question was always that a file is > inherently an XML *document*, while a string is inherently an XML > *fragment*. Not inherently, no. I know some people who do web processing with an XML document coming in as a string (from an HTTP request) and a result XML document going out as a string. I don't think that's an uncommon use case. Stefan From johnthawk at excite.com Sat Jan 12 22:14:57 2008 From: johnthawk at excite.com (johnthawk at excite.com) Date: Sat, 12 Jan 2008 22:14:57 -0500 (EST) Subject: pygtk dnd woes Message-ID: <20080113031457.1DA4C2F5E7@xprdmxin.myway.com> Hi all, DND has just about got me going bonkers. I want to process the dnd drop to main window and then process the dnd_list to ship to open_arg. Resulting in individual editor panes opening the files. The problem: TypeError: dnd_drop() takes exactly 6 arguments (8 given) or TypeError: dnd_drop() takes exactly 8 arguments (6 given) Seems I'm in a catch 22 here. The code: # read notes self.on_read_notes() # dnd # self.TARGET_TYPE_URI_LIST = 80 self.window.dnd_list = [ ( 'text/plain', 0, self.TARGET_TYPE_URI_LIST ) ] self.window.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_HIGHLIGHT, self.window.dnd_list, gtk.gdk.ACTION_COPY) self.window.connect('drag_data_received', self.dnd_drop) self.window.drag_dest_set(gtk.DEST_DEFAULT_ALL, [ ( 'text/uri-list', 0, self.TARGET_TYPE_URI_LIST ) ], gtk.gdk.ACTION_COPY) self.window.connect('drag_drop', self.dnd_drop) # # show all self.window.show_all() self.window.set_title('GEd:') self.window.show() # welcome self.set_status('Welcome to GEd-V-0.1 :-) ...') # #-------------------------------------------------------------------------- def dnd_drop(self, widget, context, x, y, times): # (self, widget, context, x, y, selection, target_type, time): # process list and and ship to open_arg print 'data received' context.finish(True, False, time) return True # #-------------------------------------------------------------------------- def on_blank(self, widget): pass Thanks john _______________________________________________ Join Excite! - http://www.excite.com The most personalized portal on the Web! From grante at visi.com Wed Jan 23 18:54:13 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 23 Jan 2008 23:54:13 -0000 Subject: Increment Variable Name References: <5vq0rjF1o724kU1@mid.uni-berlin.de> Message-ID: <13pfkt53kq7jo7c@corp.supernews.com> On 2008-01-23, Diez B. Roggisch wrote: > David Brochu schrieb: >> This is probably really trivial but I'm stumped.... :-( >> >> Does anyone know how to increment a variable name? >> >> For example: >> >> I know the length of a list and I want to pass each element of a list to >> a unique variable, thus I want to increment variable names. If the list >> length = 4, i want to have the following variables: var1, var2, var3, var4. >> > > Use a dictionary > > value_dict = {} > > for i, value in values: > value_dict["var%i" % i] = value That assumes that the OPs "list" is actually a list of tumples: [(1,firstvalue),(2,secondvalue), (3, thirdvalue), ...] I'd adjust my thinking (regarding 0/1 based counting) and just use a list or a tuple: var = list(values) or var = tuple(values) In either case, you now have var[0], var[1], var[2], var[3], ... If you insist on numbers starting at 1, then a dict would work: var = {} for i,value in itertools.enumerate(itertools.count(1), values): var[i] = value now you have var[1], var[2], var[3], var[4], ... -- Grant Edwards grante Yow! I'm continually AMAZED at at th'breathtaking effects visi.com of WIND EROSION!! From lists at cheimes.de Sat Jan 19 10:14:26 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 19 Jan 2008 16:14:26 +0100 Subject: finding memory leak in edgewall trac 0.11 In-Reply-To: References: Message-ID: <479213D2.2020701@cheimes.de> rupert.thurner wrote: > what would be a good means of finding where the 0.11 version of > edgewall trac uses excessive memory. see > http://groups.google.com/group/trac-dev/browse_thread/thread/116e519da54f16b > for some details, where jonas suggested > http://wingolog.org/archives/2007/11/27/reducing-the-footprint-of-python-applications > as reading. > > tiran already gave some hints on http://bugs.python.org/issue1871, but > also suggested to ask the general mailing list: > > Do you have classes with a __del__ method which may create reference > cycles? The GC can't break cycles when a __del__ method is involved. > > Are you keeping references to tracebacks, exception objects (except > Exception, err) or frames (sys._getframe()) I forgot one important point in my reply. The GC module contains some useful methods for debugging. Check gc.garbage. It should be empty. http://docs.python.org/lib/module-gc.html Christian From lasses_weil at klapptsowieso.net Mon Jan 28 07:23:54 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 28 Jan 2008 13:23:54 +0100 Subject: Python Genetic Algorithm In-Reply-To: <13pqbvn8ckilnfc@corp.supernews.com> References: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> <13pqbvn8ckilnfc@corp.supernews.com> Message-ID: <479dc95e$0$9103$9b4e6d93@newsspool2.arcor-online.net> Steven D'Aprano wrote: >> I'm not sure I'm following you here. So a "chromosome" is bit of >> functionality, right? So basically it is a function. So my advice would >> be to write these functions and store it to the "indivuals"-list like >> so: > > No, a chromosome is a bit of *data*: a noun, not a verb. Read these bits > again: > > "Individuals HAVE what's called a chromosome - a SPECIFICATION of what it > contains. For example, common chromosomes are BIT STRINGS, ..." > Oh, OK. I *sort of* got this. Sort of. My reasoning was that these functions would return their associated "representation" upon being called. Which makes not much sense, especially after your explanation. > Some background which may help you understand what the OP is asking for. > > [snip little GA-intro] > Thanks Steven, that sure was useful. I think I now have a new toy hammer. I'm sure I'll see myself looking for toy nails everywhere over the next few weeks. :) /W From sjmachin at lexicon.net Sat Jan 19 06:38:49 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jan 2008 03:38:49 -0800 (PST) Subject: Excess whitespace in my soup Message-ID: <48eb8853-91b3-4c43-8014-a0c624e4c6e7@t1g2000pra.googlegroups.com> I'm trying to recover the original data from some HTML written by a well-known application. Here are three original data items, in Python repr() format, with spaces changed to tildes for clarity: u'Saturday,~19~January~2008' u'Line1\nLine2\nLine3' u'foonly~frabjous\xa0farnarklingliness' Here is the HTML, with spaces changed to tildes, angle brackets changed to square brackets, omitting \r\n from the end of each line, and stripping a large number of attributes from the [td] tags. ~~[td]Saturday,~19 ~~January~2008[/td] ~~[td]Line1[br] ~~~~Line2[br] ~~~~Line3[/td] ~~[td]foonly ~~frabjous farnarklingliness[/td] Here are the results of feeding it to ElementSoup: >>> import ElementSoup as ES >>> elem = ES.parse('ws_soup1.htm') >>> from pprint import pprint as pp >>> pp([(e.tag, e.text, e.tail) for e in elem.getiterator()]) [snip] (u'td', u'Saturday, 19\n January 2008', u'\n'), (u'td', u'Line1', u'\n'), (u'br', None, u'\n Line2'), (u'br', None, u'\n Line3'), (u'td', u'foonly\n frabjous\xa0farnarklingliness', u'\n')] I'm happy enough with reassembling the second item. The problem is in reliably and correctly collapsing the whitespace in each of the above five elements. The standard Python idiom of u' '.join(text.split()) won't work because the text is Unicode and u'\xa0' is whitespace and would be converted to a space. Should whitespace collapsing be done earlier? Note that BeautifulSoup leaves it as   -- ES does the conversion to \xa0 ... Does anyone know of an html_collapse_whitespace() for Python? Am I missing something obvious? Thanks in advance, John From steve at REMOVE-THIS-cybersource.com.au Fri Jan 25 06:09:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 25 Jan 2008 11:09:39 -0000 Subject: When is min(a, b) != min(b, a)? References: <13pi8fiiqgljdb5@corp.supernews.com> Message-ID: <13pjgrj540qt98a@corp.supernews.com> On Fri, 25 Jan 2008 07:57:13 +0000, Antoon Pardon wrote: >> But if you consider that having "x is not smaller than y" be equivalent >> to "x is greater than or equal to y" is more important than forcing a >> boolean answer in the first place, then you need something to signal >> Undefined, and an exception is the right solution unless you have >> multi- valued logic system (True, False, Maybe, Undefined, ...) > > Why should we consider that? It's a value judgement. Ask the Apple and IBM engineers and mathematicians. Personally, I think it is more useful to be able to assume that if x is not less than y, it must be greater or equal to instead ("completeness"), than it is to have a guarantee that x < y will never raise an exception. Having said that, I think the opposite holds for sorting and calculating the min() and max() of floats. Sorting should push the NaNs to one end of the list (I don't care which) while min() and max() should ignore NaNs and only raise an exception if all the arguments are NaNs. > The world is full of partial orders. In > python we have sets and a partial order is perfectly mathematically > sound. Sure, we could define floats to have any sort of order we want. We could define them to be ordered by their English spelling so that "five million point three" would be less than "zero point one". But is it useful? Putting aside sorting and max/min, what is the use-case for having comparisons with NaN succeed? What benefit will it give you? -- Steven From martin at v.loewis.de Fri Jan 25 02:20:47 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 25 Jan 2008 08:20:47 +0100 Subject: Python and binary compatibility In-Reply-To: <083456aa-1ed1-4455-a8ca-4bbaaba1ce00@i29g2000prf.googlegroups.com> References: <083456aa-1ed1-4455-a8ca-4bbaaba1ce00@i29g2000prf.googlegroups.com> Message-ID: <47998dcf$0$15586$9b622d9e@news.freenet.de> > All my troubles could apparently be fixed if I > could acquire a copy of VS 2003, but Microsoft has made it incredibly > difficult to find the download for it (I don't think it exists). > > Any suggestions? You can get copies of VS 2003 from ebay fairly easily. Regards, Martin From cokofreedom at gmail.com Mon Jan 28 05:49:58 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 28 Jan 2008 02:49:58 -0800 (PST) Subject: optional static typing for Python References: <479da584$0$25625$426a74cc@news.free.fr> <69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com> Message-ID: <6d586b84-743b-475b-90be-944fddb1941e@v46g2000hsv.googlegroups.com> On Jan 28, 11:42 am, "Russ P." wrote: > On Jan 28, 1:51 am, Bruno Desthuilliers > > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > Russ P. a ?crit :> A while back I came across a tentative proposal from way back in 2000 > > > for optional static typing in Python: > > > (snip) > > > > In any case, optional static typing in Python would help tremendously > > > here. The hardest part of automated conversion of Python to a > > > statically typed language is the problem of type inference. If the > > > types are explicitly declared, that problem obviously goes away. > > > (snip) > > > > Note also that, while "static" type checking would be ideal, > > > "explicit" typing would be a major step in the right direction > > > Lord have mercy(tm). > > What is that supposed to mean? > > Oh, I almost forgot. I'm supposed to sit here and be polite while > clueless dolts make wise cracks. Sorry, but I haven't yet mastered > that level of self-control. > > I would just like to thank you for reminding me about what losers hang > out perpetually on sites like this one, thinking they are in some kind > of real "community." Being reminded of that will help prevent me from > becoming such a loser myself. No, I didn't say that all the "regulars" > here are losers, but you most certainly are. > > Do you have a job? How about a life? Have you ever been "with" a > woman? How in the world is it that every time I come to this site, I > see your sorry ass hanging around yet again? I can't even imagine how > "pointless" your life must be if you have that much time to spend > "hanging around" on comp.lang.python -- and being an a--hole to boot. > > Yeah, Lord have mercy -- on losers like you. > > And thanks for reminding me to quit wasting so much time here. I've > been doing way too much of that lately. Why is it everyone has to resort to name calling and instantly being offended by everyone. If you don't think he reply has merit, then either simply ask him what he meant or ignore the post altogether. Your reply just flames the issue. I never get the reason why people feel the need to insult someone they feel has insulted them. That somehow by the re-doing the act they will solve the issue? Just move on. From dg.google.groups at thesamovar.net Sun Jan 20 12:41:32 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Sun, 20 Jan 2008 09:41:32 -0800 (PST) Subject: Just for fun: Countdown numbers game solver Message-ID: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Ever since I learnt to program I've always loved writing solvers for the Countdown numbers game problem in different languages, and so now I'm wondering what the most elegant solution in Python is. If you don't know the game, it's simple: you're given six randomly chosen positive integers, and a target (another randomly chosen positive integer), and you have to make the target using only the numbers you're given, and +,-,* and / (and any number of brackets you like). You're not allowed fractions as intermediate values. So, given 2, 3 and 5 say, and a target of 21, you could do (2+5)*3 = 21. So what's the best algorithm? And, what's the most elegant way to code it in Python? I've posted my most elegant version below (I have a faster version which is slightly less elegant). Can anyone do better? Refs: * This academic paper describes an implementation of an algorithm to solve the problem in Haskell. I found it after I'd written mine but it uses a very similar algorithm. http://www.cs.nott.ac.uk/~gmh/countdown.pdf * My web page where I put both versions of my code: http://thesamovar.net/countdownnumbers * The web page of the TV show the problem is based on: http://www.channel4.com/entertainment/tv/microsites/C/countdown/index.html My version: class InvalidExpressionError(ValueError): pass subtract = lambda x,y: x-y def add(x,y): if x<=y: return x+y raise InvalidExpressionError def multiply(x,y): if x<=y or x==1 or y==1: return x*y raise InvalidExpressionError def divide(x,y): if not y or x%y or y==1: raise InvalidExpressionError return x/y add.display_string = '+' multiply.display_string = '*' subtract.display_string = '-' divide.display_string = '/' standard_operators = [ add, subtract, multiply, divide ] class Expression(object): pass class TerminalExpression(Expression): def __init__(self,value,remaining_sources): self.value = value self.remaining_sources = remaining_sources def __str__(self): return str(self.value) def __repr__(self): return str(self.value) class BranchedExpression(Expression): def __init__(self,operator,lhs,rhs,remaining_sources): self.operator = operator self.lhs = lhs self.rhs = rhs self.value = operator(lhs.value,rhs.value) self.remaining_sources = remaining_sources def __str__(self): return '('+str(self.lhs)+self.operator.display_string +str(self.rhs)+')' def __repr__(self): return self.__str__() def ValidExpressions(sources,operators=standard_operators,minimal_remaining_sources=0): for value, i in zip(sources,range(len(sources))): yield TerminalExpression(value=value, remaining_sources=sources[:i]+sources[i+1:]) if len(sources)>=2+minimal_remaining_sources: for lhs in ValidExpressions(sources,operators,minimal_remaining_sources+1): for rhs in ValidExpressions(lhs.remaining_sources, operators, minimal_remaining_sources): for f in operators: try: yield BranchedExpression(operator=f, lhs=lhs, rhs=rhs, remaining_sources=rhs.remaining_sources) except InvalidExpressionError: pass def TargetExpressions(target,sources,operators=standard_operators): for expression in ValidExpressions(sources,operators): if expression.value==target: yield expression def FindFirstTarget(target,sources,operators=standard_operators): for expression in ValidExpressions(sources,operators): if expression.value==target: return expression raise IndexError, "No matching expressions found" if __name__=='__main__': import time start_time = time.time() target_expressions = list(TargetExpressions(923,[7,8,50,8,1,3])) target_expressions.sort(lambda x,y:len(str(x))-len(str(y))) print "Found",len(target_expressions),"solutions, minimal string length was:" print target_expressions[0],'=',target_expressions[0].value print print "Took",time.time()-start_time,"seconds." From thomas.pani at gmail.com Thu Jan 31 06:39:50 2008 From: thomas.pani at gmail.com (Thomas Pani) Date: Thu, 31 Jan 2008 12:39:50 +0100 Subject: dl module In-Reply-To: <11ed47ab0801310303w44b173a1sacfb317bb2737b3@mail.gmail.com> References: <11ed47ab0801310303w44b173a1sacfb317bb2737b3@mail.gmail.com> Message-ID: <47A1B386.8030504@gmail.com> There's a Debian bug for python2.2 at [1]. You can't use dl on a 64bit machine anyway, because sizeof(int) != sizeof(long). Cheers Thomas Pani [1] http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=141681 Nicola Jean wrote: > Hi everyone, > I'm having a problem compiling Python2.4.4 on a 64 bits machine. It > looks like I cannot compile the dl module. > When I run test_dl.py I get the following error message: > SystemError: module dl requires sizeof(int) == sizeof(long) == sizeof(char*) > > Do I need to put any special flag when I run the configure script? > Cheers > N.Jean From steve at REMOVE-THIS-cybersource.com.au Thu Jan 24 19:09:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 25 Jan 2008 00:09:58 -0000 Subject: When is min(a, b) != min(b, a)? References: Message-ID: <13pia6m7phe2n22@corp.supernews.com> On Thu, 24 Jan 2008 16:51:16 +0000, Pete Forman wrote: > Christian Heimes writes: > > > Antoon Pardon wrote: >>> That doesn't follow. The problem is not that x < nan returns False >>> because that is correct since x isn't smaller than nan. The problem is >>> cmp(x, nan) returning 1, because that indicates that x is greater than >>> nan and that isn't true. >> > > Please report the problem. cmp(), min() and max() don't treat NaNs > > right. I don't think that x < nan == False is the correct answer, > > too. But I've to check the IEEE 754 specs. IMHO < nan and > nan > > should raise an exception. > > I disagree with your last sentence. We are dealing with quiet NaNs > which should not raise exceptions. x < nan is well defined in IEEE, it > is false. I question that. The IEEE standard states that comparisons involving NaNs are unordered and should signal INVALID. What that means at the high level of x < NAN (etc.) isn't clear. I'm having a lot of trouble finding the canonical IEEE-754 standard, so I'm forced to judge by implementations and third party accounts. For example, this is what IBM says: http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/ com.ibm.xlf101l.doc/xlfopg/fpieee.htm [quote] The IEEE standard defines several exception conditions that can occur: ... INVALID Operations are performed on values for which the results are not defined. These include: Operations on signaling NaN values ... Comparisons involving NaN values [end quote] Note that *only* sNaNs signal invalid on arithmetic operations, but *both* types of NaNs signal invalid on comparisons. The same page also lists a table showing the result of such signals. I won't reproduce the whole table, but it states that the INVALID signal results in a NaN if exceptions are disabled, and no result (naturally) if exceptions are enabled. SANE (Standard Apple Numerics Environment) and Apple's PowerPC Numerics also do the same. See for example: http://developer.apple.com/documentation/mac/PPCNumerics/ PPCNumerics-37.html [quote] ...when x or y is a NaN, x < y being false might tempt you to conclude that x >= y, so PowerPC Numerics signals invalid to help you avoid the pitfall. [end quote] Regardless of deep philosophical questions about truth, that's a great example of Practicality Beats Purity. And some of us think that raising an exception would not only be more practical, but also more pure as well. -- Steven From dickinsm at gmail.com Mon Jan 28 10:07:08 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 28 Jan 2008 07:07:08 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: <13pi8fiiqgljdb5@corp.supernews.com> <13pjgrj540qt98a@corp.supernews.com> Message-ID: <5633527c-579b-4978-acfd-20dfff7d852c@n20g2000hsh.googlegroups.com> On Jan 28, 6:50 am, Antoon Pardon wrote: > People who somehow made it clear they know how to work with inf, and > NaN results, would get silent NaN where no exceptions would be thrown. One other thing: there's an excellent starting point for considering how things should work, in the form of the Decimal type. This does exactly what you suggest: by default, users get Python exceptions instead of NaNs and/or infinities, but the user can override the defaults to switch off the various traps (Overflow, Invalid, etc.) and work directly with NaNs and infinities if (s)he prefers. Note also that decimal.py runs to over 5000 lines of (Python) code! And that's without having to deal with the vagaries of the C-compiler/ library/OS/hardware, since everything's implemented directly in Python. A surprisingly small amount of that code is actually 'real' mathematics: most of it is devoted to dealing correctly with infinities, NaNs, signed zeros, subnormals, `ideal' exponents, traps, flags, etc. Mark From cybergrind at gmail.com Mon Jan 14 06:11:41 2008 From: cybergrind at gmail.com (cybergrind at gmail.com) Date: Mon, 14 Jan 2008 03:11:41 -0800 (PST) Subject: (bit)torrent source code help References: Message-ID: Hi, Try to use ABC. it based on bittornado Thnx From musiccomposition at gmail.com Fri Jan 18 20:41:47 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 18 Jan 2008 17:41:47 -0800 (PST) Subject: Unique thread ID References: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> Message-ID: <97c1bc57-5caf-4fa5-96d7-f6847db9e18c@f10g2000hsf.googlegroups.com> On Jan 18, 2:31 am, Christian Heimes wrote: > Benjamin wrote: > > Is there a way to obtain a unique ID for the current thread? I have an > > object that I need to store local thread data in, and I don't want to > > use threading.local because each thread might have multiple instances > > of my object. > > threading.get_ident() but please use threading.local. Nobody is going to > stop you if you use a list or dict in threading.local. then, I have to figure out how to represent an instance of my object in threading.local. (The data also won't be garbage collect when my object is, will it?) I think the unique id is elegant in this case. > > Christian From Ira.Kovac at gmail.com Thu Jan 24 14:18:45 2008 From: Ira.Kovac at gmail.com (Ira.Kovac at gmail.com) Date: Thu, 24 Jan 2008 11:18:45 -0800 (PST) Subject: Sorting Large File (Code/Performance) Message-ID: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> Hello all, I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like to sort based on first two characters. I'd greatly appreciate if someone can post sample code that can help me do this. Also, any ideas on approximately how long is the sort process going to take (XP, Dual Core 2.0GHz w/2GB RAM). Cheers, Ira From pavlovevidence at gmail.com Sat Jan 26 03:19:12 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 26 Jan 2008 00:19:12 -0800 (PST) Subject: Generational Interfaces References: <1b7b3b47-72f0-4a5d-9185-4903e75dba47@d70g2000hsb.googlegroups.com> Message-ID: <87dfcd78-13ce-4c91-a6a8-8fcdb1edc07b@s8g2000prg.googlegroups.com> On Jan 26, 3:04 am, Paddy wrote: > I thought a major use of an interface is to allow separate development > that comes together at the interface. If so then such fluid interface > changing would scupper separate development. Yes, this wouldn't be appropriate for that particular use. Carl Banks From gagsl-py2 at yahoo.com.ar Mon Jan 21 16:19:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 19:19:14 -0200 Subject: problem deriving form type long References: <47950186.1040707@vtxmail.ch> Message-ID: En Mon, 21 Jan 2008 18:33:10 -0200, Frederic Rentsch escribi?: > Hi, here's something that puzzles me: > > >>> class Fix_Point (long): > def __init__ (self, l): > long.__init__ (self, l * 0x10000): > > >>> fp = Fix_Point (99) > >>> fp > 99 You have to override __new__, not __init__. Immutable types like numbers and tuples don't use __init__. See http://docs.python.org/ref/customization.html > (P.S. I am not currently a subscriber. I was and had to bail out when I > couldn't handle the volume anymore. To subscribe just to post one > question doesn't seem practical at all. So, I don't even know if this > message goes through. In case it does, I would appreciate a CC directly > to my address, as I don't think I can receive the list. Thanks a > million.) You can read this thru the Google Groups interfase: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ade1fdc42c5380b8/ or using Gmane: http://thread.gmane.org/gmane.comp.python.general/555822 -- Gabriel Genellina From greg.johnston at gmail.com Mon Jan 21 17:44:09 2008 From: greg.johnston at gmail.com (Greg Johnston) Date: Mon, 21 Jan 2008 14:44:09 -0800 (PST) Subject: PyGTK, Glade, and ComboBoxEntry.append_text() Message-ID: <4066a33f-6293-48e3-a48c-66af699d0eb9@i29g2000prf.googlegroups.com> Hey all, I'm a relative newbie to Python (switched over from Scheme fairly recently) but I've been using PyGTK and Glade to create an interface, which is a combo I'm very impressed with. There is, however, one thing I've been wondering about. It doesn't seem possible to modify ComboBoxEntry choice options on the fly--at least with append_text(), etc--because they were not created with gtk.combo_box_entry_new_text(). Basically, I'm wondering if there's any way around this. Thank you, Greg Johnston From asmodai at in-nomine.org Sat Jan 12 03:58:21 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 12 Jan 2008 09:58:21 +0100 Subject: converting JSON to string In-Reply-To: References: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> <13og5g06rvrtefa@corp.supernews.com> Message-ID: <20080112085821.GI75977@nexus.in-nomine.org> -On [20080112 08:38], Gowri (gowricp at gmail.com) wrote: >Actually, I have one other problem after all this. I see that if I try >to construct JSON output as above, it is of the form >[{'isbn': u'1-56592-724-9', 'title': u'The Cathedral & the Bazaar'}, >{'isbn': u'1-56592-051-1', 'title': u'Making TeX Work'}] >The extra 'u' seems to causing syntax error in JavaScript which is not >able to parse this response string. Any idea how I can fix this? JSON does not support Unicode in the sense of allowing raw Unicode codepoints. Instead JSON uses a \uNNNN scheme to encode Unicode characters (a bit flawed to limit it to four hexadecimal digits though, it leaves the whole CJK Unified Ideographs Extension B out of scope.). I use simplejson along with lxml/ElementTree for my JSON<>XML needs. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Any road leads to the end of the world... From guyon.moree at gmail.com Thu Jan 31 08:32:38 2008 From: guyon.moree at gmail.com (=?ISO-8859-1?Q?Guyon_Mor=E9e?=) Date: Thu, 31 Jan 2008 05:32:38 -0800 (PST) Subject: Executing other python code References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: <1451cb46-b3c0-4250-8137-62d2b39d69c0@s13g2000prd.googlegroups.com> > One simple solution would be to forbid import statements in the > scripts, to import the scripts as modules and inject whatever > functions you want them to be able to use in the module's namespace. how do you 'forbid' imports? Guyon http://gumuz.nl From donn.ingle at gmail.com Sun Jan 13 12:28:54 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 19:28:54 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A4408.2090805@v.loewis.de> References: <200801131550.50119.donn.ingle@gmail.com> <478A4408.2090805@v.loewis.de> Message-ID: <200801131928.54459.donn.ingle@gmail.com> > No. It may use replacement characters (i.e. a question mark, or an empty > square box), but if you don't see such characters, then the terminal has > successfully decoded the file names. Whether it also correctly decoded > them is something for you to check (i.e. do they look right?) Okay. So, the picture I get is: *If* my locale *happens* to be the right one then the filename will appear properly. If it does not cover that file, then that filename will appear with ? marks in the name. Because I use en_ZA.utf8 it's doing a very good job of decoding a wide variety of filenames and therefore I rarely see ? characters. What happens if there is a filename that cannot be represented in it's entirety? i.e. every character is 'replaced'. Does it simply vanish, or does it appear as "?????????" ? :) I spent an hour trying to find a single file on the web that did *not* have (what seemed like) ascii characters in it and failed. Even urls on Japanese websites use western characters ( a tcp/ip issue I suspect). I was hoping to find a filename in Kanji (?) ending in .jpg or something so that I could download it and see what my system (and Python) made of it. Thanks again, \d -- "Life results from the non-random survival of randomly varying replicators." -- Richard Dawkins Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From hniksic at xemacs.org Tue Jan 8 09:42:40 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 08 Jan 2008 15:42:40 +0100 Subject: use fileinput to read a specific line References: <6f2db44c-2641-47cb-ab24-4177ccc96d6e@m77g2000hsc.googlegroups.com> <13o637afk4mql0c@corp.supernews.com> <36e49a53-8e56-4847-a792-5032ea204a8e@l6g2000prm.googlegroups.com> <13o6tldft8suj83@corp.supernews.com> Message-ID: <87ve64l6ov.fsf@mulj.homelinux.net> Fredrik Lundh writes: > From what I can tell, Java's GC automatically closes file streams, > so Jython will behave pretty much like CPython in most cases. The finalizer does close the reclaimed streams, but since it is triggered by GC, you have to wait for GC to occur for the stream to get closed. That means that something like: open('foo', 'w').write(some_contents) may leave 'foo' empty until the next GC. Fortunately this pattern is much rarer than open('foo').read(), but both work equally well in CPython, and will continue to work, despite many people's dislike for them. (For the record, I don't use them in production code, but open(...).read() is great for throwaway scripts and one-liners.) > I sure haven't been able to make Jython run out by file handles by > opening tons of files and discarding the file objects without > closing them. Java's generational GC is supposed to be quick to reclaim recently discarded objects. That might lead to swift finalization of open files similar to what CPython's reference counting does in practice. It could also be that Jython internally allocates so many Java objects that the GC is triggered frequently, again resulting in swift reclamation of file objects. It would be interesting to monitor (at the OS level) the number of open files maintained by the process at any given time during the execution of such a loop. From Lie.1296 at gmail.com Sun Jan 13 09:14:08 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 13 Jan 2008 06:14:08 -0800 (PST) Subject: Exceptions - How do you make it work like built-in exceptions? Message-ID: <7888e20f-0775-46c4-a6e2-3fc3825c5145@e23g2000prf.googlegroups.com> A built-in exceptions, when raised, would print traceback that points out the offending code, like this: Traceback (most recent call last): File "F:\dir\code.py", line 43, in a = 1/0 <<<--- ZeroDivisionError: integer division or modulo by zero a user-made exception, when raised, would print traceback that points out the code that raises the exception Traceback (most recent call last): File "F:\dir\code.py", line 48, in raise SomeException('Some Exception Message') <<<--- SomeException: Some Exception Message which is generally of little use (yeah, it's possible to trace the code from the line number, but sometimes it might not be that easy, cause the line number is (again) the line number for the raising code instead of the offending code) The sample exception was generated from this code: #### class SomeException(Exception): pass try: a = 1/0 except: raise SomeException('Some Exception Message') #### Is it possible to make the user-made exception points out the offending code? From socyl at 987jk.com.invalid Thu Jan 10 10:22:37 2008 From: socyl at 987jk.com.invalid (kj) Date: Thu, 10 Jan 2008 15:22:37 +0000 (UTC) Subject: ISO books of official Python docs References: fm38qu$6c7$1@reader2.panix.com <966c993a-2aa6-4724-852a-49d8da686675@k2g2000hse.googlegroups.com> Message-ID: In <966c993a-2aa6-4724-852a-49d8da686675 at k2g2000hse.googlegroups.com> gordyt writes: >Howdy kynnjo, >> Is it possible to buy the official Python docs in book form? If >> so, I'd very much appreciate the name(s) and author(s) of the >> book(s). >I haven't seen them in print form, but you can download PDF's from >here: >http://docs.python.org/download.html Thanks for the link. With the name of the manual on hand I was able to find a printed version of it (ISBN: 0954161785). A mere 144 pages, and for under $15. Sweeeeet! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From danebarney at gmail.com Tue Jan 1 17:35:14 2008 From: danebarney at gmail.com (Jugdish) Date: Tue, 1 Jan 2008 14:35:14 -0800 (PST) Subject: confusion about package/module imports References: <13nlc7fecs63099@corp.supernews.com> Message-ID: Thanks very much for your helpful response! > You'll see that b is executed (making module __main__), > (1) it imports pkg.subpkg.a, > (2) which is accomplished by importing pkg (successfully), > (3) then by importing pkg.subpkg > (4) which imports pkg.subpkg.a (successfully) > (5) and then imports pkg.subpkg.b > (6) which then attempts to import pkg.subpkg.a What I'm not really understanding here is why this fails at lines (5) and (6). If pkg.subpkg.a has already been successfully imported at line (4), then (6) should be detected as a duplicate import and just be skipped, right? So the import at line (5) should succeed. From paul at boddie.org.uk Thu Jan 31 11:21:07 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 31 Jan 2008 08:21:07 -0800 (PST) Subject: Problems installing Python on server References: Message-ID: On 28 Jan, 22:28, Yansky wrote: > I asked my hosting company if they would upgrade Python on my server > to the latest version. They responded with: > > "Sorry no. We tend to stick with what comes packaged with the unix > distribution to ease maintenance issues. Which version are they running, by the way? > There is nothing stopping you from running your own version of python > from within your own account. Download the source and compile it and > install it into your own space. Adjust the fist line of your python > scripts to reflect the location of YOUR python binary: > > #! /home/youraccount/yourlibs/python > > and you should be all set." This sounds like reasonable advice, I suppose. > The build instructions for Python are: > To start building right away (on UNIX): type "./configure" in the > current directory and when it finishes, type "make". This creates an > executable "./python"; to install in usr/local, first do "su root" and > then "make install". > > The problem is, I don't have root access to the server so I can't do > the "make install". I think that the "su root" stuff is just there in anticipation of people trying to configure, build and install Python without thinking too hard about it and then finding that they get lots of errors about installing into places they don't have permissions for. If you're installing into a different location, you only need to have permissions to write to that location. > I have ubuntu on my computer, but from what I understand I can't > compile it on that and upload it because the server > runs Red Had and the ./configure would have made it incompatible > right? If you have shell access on the hosting service and they have compilers available, you can just do the build and install there. Building on your own computer and having the executable work on the server is likely to be more difficult due to the usual library versioning issues that arise between distributions - it'd be interesting to see if anyone can suggest a solution for this involving the LSB tools. > So how can I build Python without root access? Something like this: mkdir /home/youraccount/apps # optional - see below ./configure --prefix=/home/youraccount/apps make make install Here, the apps directory in your home directory will contain the usual UNIX directory structure that you would otherwise see in /usr: directories such as bin, lib, share (probably), and so on. You'll find the python executable as /home/youraccount/apps/bin/python. Some people like to mimic the full UNIX structure and have a usr directory (either underneath or instead of the apps directory employed above); others prefer to have the bin, lib (and other directories) in their home directory (thus omitting the apps directory); you get to choose. ;-) I hope this helps! Paul From donn.ingle at gmail.com Sun Jan 13 06:51:58 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 13:51:58 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <4789F559.1090703@v.loewis.de> References: <200801131224.10263.donn.ingle@gmail.com> <4789F559.1090703@v.loewis.de> Message-ID: <200801131351.59005.donn.ingle@gmail.com> Martin, > Yes. It does so when it fails to decode the byte string according to the > file system encoding (which, in turn, bases on the locale). That's at least one way I can weed-out filenames that are going to give me trouble; if Python itself can't figure out how to decode it, then I can also fail with honour. > > I will try the technique given > > on:http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html > >#guessing-the-encoding Perhaps that will help. > I would advise against such a strategy. Instead, you should first > understand what the encodings of the file names actually *are*, on > a real system, and draw conclusions from that. I don't follow you here. The encoding of file names *on* a real system are (for Linux) byte strings of potentially *any* encoding. os.listdir() may even fail to grok some of them. So, I will have a few elements in a list that are not unicode, I can't ask the O/S for any help and therefore I should be able to pass that byte string to a function as suggested in the article to at least take one last stab at identifying it. Or is that a waste of time because os.listdir() has already tried something similar (and prob. better)? > I notice that this doesn't include "to allow the user to enter file > names", so it seems there is no input of file names, only output. I forgot to mention the command-line interface... I actually had trouble with that too. The user can start the app like this: fontypython /some/folder/ or fontypython SomeFileName And that introduces input in some kind of encoding. I hope that locale.getprefferedencoding() will be the right one to handle that. Is such input (passed-in via sys.argv) in byte-strings or unicode? I can find out with type() I guess. As to the rest, no, there's no other keyboard input for filenames. There *is* a 'filter' which is used as a regex to filter 'bold', 'italic' or whatever. I fully expect that to give me a hard time too. > Then I suggest this technique of keeping bytestring/unicode string > pairs. Use the Unicode string for display, and the byte string for > accessing the disc. Thanks, that's a good idea - I think I'll implement a dictionary to keep both and work things that way. > I see no problem with that: > >>> u"M\xd6gul".encode("ascii","ignore") > 'Mgul' > >>> u"M\xd6gul".encode("ascii","replace") > 'M?gul' Well, that was what I expected to see too. I must have been doing something stupid. \d From kyosohma at gmail.com Fri Jan 11 16:51:37 2008 From: kyosohma at gmail.com (Mike) Date: Fri, 11 Jan 2008 13:51:37 -0800 (PST) Subject: Graphics Module References: Message-ID: On Jan 11, 3:31 pm, "Gabriel" wrote: > Hi all ! > > I'm developing a math program that shows graphics of functions. > I would hear suggestions about the way of drawing 2D . > > Thanks a lot for your answers. > > - Gabriel - That's not a very descriptive question, however most people talk about matplotlib for graphing and 2D drawings. Here's a few links on graphing in Python: http://matplotlib.sourceforge.net/ http://wiki.python.org/moin/PythonGraphApi http://alpha-leonis.lids.mit.edu/nlp/pygraph/ http://boost.org/libs/graph/doc/python.html http://www.python.org/doc/essays/graphs.html Some of these may have dependencies, such as numpy or scipy. Be sure to read the docs for full details either way. Mike From fredrik at pythonware.com Fri Jan 4 15:09:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 21:09:49 +0100 Subject: Question on os.tempnam() vulnerability In-Reply-To: References: Message-ID: cameronwong88 at gmail.com wrote: > Does any one know what kind of security risk these message are > suggesting? > >>>> f = os.tempnam() > __main__:1: RuntimeWarning: tempnam is a potential security risk to > your program >>>> f > '/tmp/filed4cJNX' > >>>> g = os.tmpnam() > __main__:1: RuntimeWarning: tmpnam is a potential security risk to > your program >>>> g > '/tmp/fileENAuNw' you get a name instead of a file, so someone else can create that file after you've called tempnam/tmpnam, but before you've actually gotten around to create the file yourself. which means that anyone on the machine might be able to mess with your application's data. use the functions marked as "safe" in the tempfile module instead. From wdraxinger at darkstargames.de Sun Jan 20 13:09:39 2008 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sun, 20 Jan 2008 19:09:39 +0100 Subject: HTTP POST uploading large files References: <7xwsq4zahb.fsf@ruckus.brouhaha.com> Message-ID: <3cfc65-ohe.ln1@darkstargames.dnsalias.net> Paul Rubin wrote: > Wolfgang Draxinger writes: >> Am I just blind for some urllib2/httplib feature, or some >> other library? Or do I really have to fiddle around with >> sockets myself (I hope not...). > > I did something like that by just opening a socket and writing > the > stuff with socket.sendall. It's only about 5 lines of code and > it's pretty straightforward. Well, for YouTube you've to fiddle around with cookies, form/multipart data and stuff like that. It's a bit more than just opening a socket, there's some serious HTTP going on. However I found a solution: The curl program, that comes with libcurl and can be found on most *nix systems allows to do pretty sophisticated HTTP requests, among them also sending files by POST. So instead of using urllib2 or sockets from Python, now my program just generates the appropriate calls to curl, provides the in memory storage of cookies and does the neccesary HTML parsing*. Wolfgang Draxinger *) YouTube uploads videos in a two part process: First you set the various video options, in return you get a form with some hidden input fields, some of them providing a handle to the already sent video information. That data has to be extracted from the form and be put into the POST that also transfers the video file. -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From faber at linuxnj.com Fri Jan 11 22:32:28 2008 From: faber at linuxnj.com (Faber J. Fedor) Date: Fri, 11 Jan 2008 22:32:28 -0500 Subject: Newbie Q: modifying SQL statements In-Reply-To: <20080111182956.64466688@bhuda.mired.org> References: <20080111013206.GA18259@neptune.faber.nom> <20080110225352.2c112555@bhuda.mired.org> <20080111231141.GA24213@neptune.faber.nom> <20080111182956.64466688@bhuda.mired.org> Message-ID: <20080112033228.GB24213@neptune.faber.nom> On 11/01/08 18:29 -0500, Mike Meyer wrote: > It is a 2.5 feature, though. I was beginning to wonder of that was the case. > I converted all my clients to 2.5.1, > shortly after it was available, and haven't used anything older > since. Sorry 'bout that. No prob. -- Regards, Faber Fedor -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From kyosohma at gmail.com Tue Jan 15 10:21:50 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 15 Jan 2008 07:21:50 -0800 (PST) Subject: A question about event handlers with wxPython References: <478c3bb2$0$5150$4c368faf@roadrunner.com> <2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com> <478ccbc3$0$11000$4c368faf@roadrunner.com> Message-ID: <965596ac-466b-4ff7-a6c5-53b929c56376@i29g2000prf.googlegroups.com> On Jan 15, 9:04 am, "Erik Lind" wrote: > > def HandleSomething(self, event): > > generating_control = event.GetEventObject() > > print generating_control > > > HTH, > > Thank you.That is what I was looking for, but as often seems the case, one > thing exposes another. Is there any way to listen for events without > specifically binding to a handler (it seems one cannot bind an event to two > handlers?)? One could do so with globals, but I'm trying to avoid that. > > For example, "press any button to stop" > > def HandleSomething(self, event): > ................. > while generating_control: == something: > run > else > stop There are a number of ways to handle this. You could just bind the parent to the handler. Something like this: self.Bind(wx.EVT_BUTTON, self.onStop) This will bind all button presses to the onStop handler. You could also do something like this: self.Bind(wx.EVT_BUTTON, self.onBtnStop) def onBtnStop(self, event): #do something event.Skip() By calling the Skip() method, it will propagate the event and look for another handler, which in this case would be the onStop handler. On Windows, you will most likely need to make a wx.Panel be the parent of the rest of the widgets to have this effect. My complete test code is below. import wx class Closer(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, title='Test Frame') panel = wx.Panel(self, -1) sizer = wx.BoxSizer(wx.VERTICAL) btn1 = wx.Button(panel, wx.ID_ANY, 'Button 1') btn2 = wx.Button(panel, wx.ID_ANY, 'Button 2') btn3 = wx.Button(panel, wx.ID_ANY, 'Button 3') sizer.Add(btn1) sizer.Add(btn2) sizer.Add(btn3) self.Bind(wx.EVT_BUTTON, self.onDone) self.Bind(wx.EVT_BUTTON, self.onStop, btn1) panel.SetSizer(sizer) def onStop(self, event): print 'Stop!' event.Skip() def onDone(self, event): print 'Done!' if __name__ == '__main__': app = wx.PySimpleApp() Closer().Show() app.MainLoop() FYI: There is an excellent wxPython group that you can join over on the wxPython.org website. Mike From asmodai at in-nomine.org Tue Jan 8 04:03:56 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 10:03:56 +0100 Subject: python syntax:urgent In-Reply-To: <645055.89441.qm@web45511.mail.sp1.yahoo.com> References: <645055.89441.qm@web45511.mail.sp1.yahoo.com> Message-ID: <20080108090356.GI75977@nexus.in-nomine.org> -On [20080108 09:42], mpho raborife (mraborife at yahoo.com) wrote: >subprocess.Popen(["gmmscore", "-i", Input, "-l", List, "-t", > modeltype, "-m", str(mixture), "-d", str(dimension), "-v", str(vfloor), > "-n", str(number), "-r", str(results)]) "gmmscore", "-i" seems a bit silly, why not just "gmmscore -i"? You can always do something like (assuming all arguments are strings, adjust accordingly): s = "gmmscore -i %s -l %s -t %s -m %s -d %s -v %s -n %s -r %s" % (Input, List, modeltype, str(mixture), str(dimension), str(vfloor), str(number), str(results)) subprocess.Popen([s]) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Few are those who see with their own eyes and feel with their own hearts... From george.sakkis at gmail.com Fri Jan 11 17:05:11 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 14:05:11 -0800 (PST) Subject: Import and execfile() Message-ID: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> I maintain a few configuration files in Python syntax (mainly nested dicts of ints and strings) and use execfile() to read them back to Python. This has been working great; it combines the convenience of pickle with the readability of Python. So far each configuration is contained in a single standalone file; different configurations are completely separate files. Now I'd like to factor out the commonalities of the different configurations in a master config and specify only the necessary modifications and additions in each concrete config file. I tried the simplest thing that could possibly work: ====================== # some_config.py # master_config.py is in the same directory as some_config.py from master_config import * # override non-default options foo['bar']['baz] = 1 ... ====================== # trying to set the configuration: CFG = {} execfile('path/to/some_config.py', CFG) Traceback (most recent call last): ... ImportError: No module named master_config I understand why this fails but I'm not sure how to tell execfile() to set the path accordingly. Any ideas ? George From stefan.behnel-n05pAM at web.de Thu Jan 24 16:39:57 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 24 Jan 2008 22:39:57 +0100 Subject: Sorting Large File (Code/Performance) In-Reply-To: <479904BD.9090400@web.de> References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <479904BD.9090400@web.de> Message-ID: <479905AD.6040802@web.de> Stefan Behnel wrote: > Ira.Kovac at gmail.com wrote: >>> What are you going to do with it after it's sorted? >> I need to isolate all lines that start with two characters (zz to be >> particular) > > "Isolate" as in "extract"? Remove the rest? > > Then why don't you extract the lines first, without sorting the file? (or sort > it afterwards if you still need to). That would heavily cut down your memory > footprint. Just for fun, this is what I meant: for utf8_line in open(filename, 'rb'): if utf8_line.startswith('zz'): print utf8_line Stefan From lists at cheimes.de Fri Jan 18 12:20:28 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 18 Jan 2008 18:20:28 +0100 Subject: Bug in __init__? In-Reply-To: References: Message-ID: Zbigniew Braniecki wrote: > Any clue on what's going on here, and/if where I should report it? Congratulations! You've stumbled over a well known gotcha. Most newbies fall for the trap. class A: def __init__ (self, val=[]): print val self.lst = val val is created only *once* and shared across all instaces of A. Christian From washakie at gmail.com Tue Jan 15 15:15:05 2008 From: washakie at gmail.com (washakie) Date: Tue, 15 Jan 2008 12:15:05 -0800 (PST) Subject: MySQL-python-1.2.2 install with no mysql In-Reply-To: <14837853.post@talk.nabble.com> References: <14836669.post@talk.nabble.com> <14837853.post@talk.nabble.com> Message-ID: <14845579.post@talk.nabble.com> Thank you... after: %yum install mysql* I was able to build and install mysql-python -- View this message in context: http://www.nabble.com/MySQL-python-1.2.2-install-with-no-mysql-tp14836669p14845579.html Sent from the Python - python-list mailing list archive at Nabble.com. From thudfoo at opensuse.us Wed Jan 23 19:01:59 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Wed, 23 Jan 2008 16:01:59 -0800 Subject: Trouble writing to database: RSS-reader In-Reply-To: References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> <4794e0f9$0$4429$426a74cc@news.free.fr> <739742b0-7d3d-4039-b793-ccefae4be721@1g2000hsl.googlegroups.com> Message-ID: <3d881a310801231601w4dd08b95s62b1ba6b98c128ba@mail.gmail.com> On 1/23/08, Arne wrote: > On Jan 21, 11:25pm, "Gabriel Genellina" > wrote: > > En Mon, 21 Jan 2008 18:38:48 -0200, Arne escribi?: > > [...] > > This look very interesting! But it looks like that no documents is > well-formed! I've tried several RSS-feeds, but they are eighter > "undefined entity" or "not well-formed". This is not how it should be, > right? :) > Go to http://www.feedparser.org Download feedparser.py Read the documentation, at least.: you will find out a lot about working with rss. > -- > http://mail.python.org/mailman/listinfo/python-list From tavares at fe.up.pt Sun Jan 27 10:59:18 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Sun, 27 Jan 2008 07:59:18 -0800 (PST) Subject: Workshop "Medical Imaging Systems" within EUROMEDIA 2008 - Last Call for Papers Message-ID: <70c8b903-bd4e-4122-a823-dcbd39bed34a@s13g2000prd.googlegroups.com> ----------------------------------------------------------------------------------------------------------------------------------------- (Apologies for cross-posting) Workshop "Medical Imaging Systems" within EUROSIS EUROMEDIA 2008 April 9-11, 2008, University of Porto, Porto, Portugal http://www.eurosis.org/cms/index.php?q=node/461 We would appreciate if you could distribute this information by your colleagues and co-workers. ----------------------------------------------------------------------------------------------------------------------------------------- Dear Colleague, In recent years, extensive research has been performed to develop more and more efficient and powerful medical imaging systems. Such systems are crucial for medical specialists, allowing a deeper analysis and to understand what is going inside the human body, and therefore they play an essential role for adequate medical diagnosis and treatments. To accomplish efficient and powerful medical imaging systems, many research works have being done in many domains, like the ones related with medical image devices, signal processing, image processing and analysis, biomechanical simulation and data visualization. The main goal of the Workshop "Medical Imaging Systems" is to bring together researchers involved in the related domains, in order to set the major lines of development for the near future. Therefore, the proposed Workshop will consist of researchers representing various fields related to Medical Devices, Signal Processing, Computational Vision, Computer Graphics, Computational Mechanics, Scientific Visualization, Mathematics and Medical Imaging. The Workshop endeavours to contribute to obtain better solutions for more efficient and powerful medical imaging systems, and attempts to establish a bridge between clinicians and researchers from these diverse fields. The proposed Workshop will cover topics related with medical imaging systems, such as: image acquisition, signal processing, image processing and analysis, modelling and simulation, computer aided diagnosis, surgery, therapy, and treatment, computational bioimaging and visualization, software development, virtual reality and telemedicine systems and their applications. Due to your research activities in the field, we would like to invite you to submit a contributed paper. Your contribution is mostly welcomed and we would be honoured if you could participate in EUROMEDIA 2008. DEADLINE FOR PAPERS SUBMISSION: February 5, 2008 SCIENTIFIC COMMITTEE: Alberto De Santis, Universit? degli Studi di Roma "La Sapienza", Italy Ana Mafalda Reis, Instituto de Ci?ncias Biom?dicas Abel Salazar, Portugal Arrate Mu?oz Barrutia, University of Navarra, Spain Behnam Heidari, University College Dublin, Ireland Bernard Gosselin, Faculte Polytechnique de Mons, Belgium Chandrajit Bajaj, University of Texas, USA Christos E. Constantinou, Stanford University School of Medicine, USA Daniela Iacoviello, Universit? degli Studi di Roma "La Sapienza", Italy Dinggang Shen, University of Pennsylvania, USA Djemel Ziou, University of Sherbrooke, Canada Gerald Schaefer, Aston University, UK Jo?o Krug Noronha, Dr. Krug Noronha Clinic, Portugal Jo?o Manuel R. S. Tavares, Faculty of Engineering of University of Porto, Portugal Jo?o Paulo Costeira, Instituto Superior T?cnico, Portugal Jorge M. G. Barbosa, Faculty of Engineering of University of Porto, Portugal Lyuba Alboul, Sheffield Hallam University, UK Manuel Gonz?lez Hidalgo, Balearic Islands University, Spain Maria Elizete Kunkel, Universit?t Ulm, Germany M?rio Forjaz Secca, Universidade Nova de Lisboa, Portugal Miguel Angel L?pez, Faculty University of Ciego de Avila, Cuba Miguel Velhote Correia, Faculty of Engineering of University of Porto, Portugal Patrick Dubois, Institut de Technologie M?dicale, France Reneta Barneva, State University of New York, USA Renato M. Natal Jorge, Faculty of Engineering of University of Porto, Portugal Sabina Tangaro, University of Bari, Italy Valentin Brimkov, State University of New York, USA Yongjie Zhan, Carnegie Mellon University, USA For further details please see the conference website at: http://www.eurosis.org/cms/index.php?q=node/461 We are looking forward to see you in Porto next April. Kind regards, Jo?o Manuel R. S. Tavares University of Porto tavares at fe.up.pt www.fe.up.pt/~tavares From stef.mientki at gmail.com Tue Jan 1 15:07:12 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 01 Jan 2008 21:07:12 +0100 Subject: Some specific exec behavior ? In-Reply-To: References: <477A88D9.4090708@gmail.com> Message-ID: <477A9D70.1040103@gmail.com> Gabriel Genellina wrote: > En Tue, 01 Jan 2008 16:39:21 -0200, Stef Mientki > escribi?: > > >> I find 2 strange behaviors in exec-function, >> and I can't find anything in the documentation. >> (Python 2.4.3 Enthought edition) >> >> 1. A function definition may not span more than 1 line, e.g. >> This generates an exception: >> def _func (x,y): >> return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) >> >> while this works correct: >> def _func (x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) >> >> 2. an emtpy line at the end also generates an exception >> >> Is this behavior correct ? >> where should I find information about it ? >> > > It's correct; source lines must be separated by '\n' only (NOT '\r\n' as > in a Windows text file) and the last line must end in '\n'. > It's documented, but under the compile() built-in function: > http://docs.python.org/lib/built-in-funcs.html; perhaps the docs for exec > should refer there. > > Thanks Gabriel, that explains everything ! cheers, Stef From Lie.1296 at gmail.com Wed Jan 16 07:38:10 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 16 Jan 2008 04:38:10 -0800 (PST) Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> Message-ID: <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> On Jan 15, 9:00?pm, Bruno Desthuilliers wrote: > Lie a ?crit : > > > > > On Jan 7, 2:46 am, Bruno Desthuilliers > > wrote: > >> Lie a ?crit : > > >>> On Jan 5, 5:40 pm, MartinRineh... at gmail.com wrote: > >>>> Jeroen Ruigrok van der Werven wrote: > >>>>> Shouldn't this be: > >>>>> self.startLoc = start > >>>>> self.stopLoc = stop > >>>> Thanks! Of course it should. Old Java habits die slowly. > >>> No, seriously it isn't Java habits only, most other languages wouldn't > >>> need explicit calling of class name. > >> Where is the "explicit calling of class name" exactly ? > > > Perhaps I was a bit tired when writing that (I wouldn't understand > > what I wrote if I were you)... what I meant is most other languages > > doesn't usually enforce us to explicitly state the containing class > > name, which in python is generally called "self". > > 'self' (or whatever you name it) is not the "containing class name", Current instance is what I meant, thanks for pointing out the incorrect term I used. > it's the first argument of the function - which usually happens to be > the current instance when the function is used as a method. And that's the point, self (or anything you name it) is almost always the current instance and that makes it functionally the same as Me and this in VB and Java. > > Most other languages > > 1) automatically assign the containing class' object > > s/containing class' object/current instance/ > > > in a keyword > > (Java: this, VB: Me) behind the screen, > > That's not very far from what a Python method object does - > automatically assign the current instance to something. The difference > is that Python uses functions to implement methods (instead of having > two distinct contructs), so the only reliable way to "inject" the > reference to the current instance is to pass it as an argument to the > function (instead of making it pop from pure air). It isn't very far, but Python makes it obvious about the assignment (not behind the screen). > There are some benefits to this solution. One of them is the ability to > ? dynamically assign functions as methods. So if you do have some > function taking an object as first argument, you can easily turn it into > a method. Indeed, many languages doesn't allow dynamic assignment of function which makes having an automatic assignment of current instance to Me/ this possible and with minimal harm. > > and 2) automatically searches > > variable name in both the local variable table and the containing > > class variable table ?(so to refer to a class variable named var from a > > method inside the class, we only need to write var, not self.var as in > > python). > > This - as you know - cannot work well with Python's scoping rules and > dynamicity. Anyway, implicit object reference is definitively a > BadThing(tm) wrt/ readbility, specially with multiparadigm languages > (like Python or C++). Why do you think soooo many C++ shops impose the > m_something naming scheme ? Implicit object reference for the containing class has little harm, if a class is so complex that there are more than 10 class-level variable, then it is obvious that that class needs to be fragmented to smaller classes. Remembering less than 10 variable and avoiding naming collision among just 10 variable is not hard (and 10 is really too many, most classes should only use 2-4 variables), especially if you have a good IDE that employs Intellisense-like technology (IDLE has it). And it is always a Bad Thing(tm) to use the same name for two variable in the class and in function (which is the main and only source of possible ambiguity) in ANY language, even in Python. > Anyway, I actually know 3 languages (4 if C# works the same) that has > this implicit 'this' (or whatever the name) 'feature', and at least 5 > that don't. So I'm not sure that the "most other languages" qualifier > really applies to point 2 !-) What's this 5 languages? Are they a mainstream, high-level languages or lesser known, low-level languages? C-family, Java, and Basic are the Big Three of high-level programming language. > > In VB, Me is extremely rarely used, > > I used to systematically use it - like I've always systematically used > 'this' in C++ ?and Java. And that is what reduces readability. A proficient VB/C/Java programmer would frown upon the extra, unneeded garbage as they thought it was clear already that the variable refers to a class-level variable. It is a different story if, like Python, the use of self is enforced by the language, the self wouldn't be viewed as extra unnecessary garbage. > > in Python, self is all > > over the place. Well, there is positive and negative to both sides, > > convenience in VB, and flexibility in Python. > > As far as I'm concerned, there's *no* positive point in implicit object > reference, and there has never been (and before some paranoid nutcase > around accuse me of overzealous biggotry : I already held this very same > opinion years before I discovered Python). There is one major positive point: convenience and shorter code. (isn't that two?) As I've pointed out, there is little harm in class-level variable's implicit reference. > > Compare the following codes: > > VB.NET: > > Public Class A > > ? ? Dim var > > ? ? Public Function aFunction() > > ? ? ? ? return var > > Add three levels of inheritence and a couple globals and you'll find out > that readability count !-) It's the mental model that have to be adapted here, if the current class is inheriting from another class, you've got to think it as names from parent class as it is a native names, so you don't actually need to know where the variable comes from since knowing where it comes from is breaking the encapsulation (which, in Python is very weakly implemented, which favors flexibility in many cases[1]). [1] In Python, it is impossible to create a completely private variable, which is the reason why the mental model of these other languages doesn't fit Python. > In any non-trivial piece of C++ code, and unless the author either used > the explicit 'this' reference or the 'm_xxx' naming convention, you'll > have hard time figuring out where a given name comes from when browsing > a function's code. If you're used to the implicit naming scheme it's easy to know where a variable came from, if not the current scope, it's the class' scope and searching two short variable tables (SHORT! Creating complex classes is for stupid programmers[2]) at the same time isn't an expensive operation for human-being, especially if memoization is implemented. [2] I used to create an extremely complex classes when I was still green in programming, and that hits me back many times. Small, simple class is A Good Thing(tm). Class should use less than 10 variables, although the recommended number is 2-3 variables. Function names should be as little as possible, the use of overloading and overriding should be maximized. As a final note: I don't think implicit class reference is superior to explicit class reference, neither do I think explicit class reference is superior to implicit class reference. I think both have their own +s and -s. I only pointed out that implicit do have its benefits, depending on the language used (obviously Python wouldn't benefit from using implicit behavior, due to it being extremely dynamic). From grflanagan at yahoo.co.uk Wed Jan 30 11:37:41 2008 From: grflanagan at yahoo.co.uk (grflanagan) Date: Wed, 30 Jan 2008 08:37:41 -0800 (PST) Subject: Python noob SOS (any [former?] Perlheads out there?) References: Message-ID: <6099ab30-390d-4b38-bc8e-81ecb52e03a6@e25g2000prg.googlegroups.com> On Jan 29, 5:39 pm, kj wrote: [...] > It's not the Python syntax that I'm having problems with, but rather > with larger scale issues such as the structuring of packages, > techniques for code reuse, test suites, the structure of > distributions,... Python and Perl seem to come from different > galaxies altogether... > [...] > > I'd written a Perl module to facilitate the writing of scripts. > It contained all my boilerplate code for parsing and validating > command-line options, generating of accessor functions for these > options, printing of the help message and of the full documentation, > testing, etc. > > Of course, for Python now I don't have any of this, so I must write > it all from scratch, and the thing is *I don't even know where to > begin*! And meanwhile works needs to get done, projects finished, > etc. So naturally I revert to Perl, yadda-yadda-yadda, and the > Python project gets pushed back another week... > > In a way it's the usual story with learning a new language, but > I've taught myself new languages before. (After all, there was a > time when I didn't know Perl.) It's harder this time, somehow... > The journey of a thousand miles etc. For command line options I get a long way with this: [code python] def _getargs(): allargs = sys.argv[1:] args = [] kwargs = {} key = None while allargs: arg = allargs.pop(0) if arg.startswith('--'): key, arg = arg.split('=', 1) key = key[2:] elif arg.startswith('-'): key = arg[1:] if not allargs or allargs[0].startswith('-'): allargs.insert(0, 'yes') continue if key is None: args.append(arg) else: kwargs[key] = arg key = None return args, kwargs ARGS, KWARGS = _getargs() [/code] though obviously there's no validation. For testing see doctest module. For file and directory manipulation see os and shutil modules. The following is an abuse of docstrings, but shows some OO techniques: [code python] import inspect linesep = '\n' class TemplateBase(object): factory = None template = None verb = 'substitute' @classmethod def render(cls, **kws): if cls.template is None: cls.template = cls.factory(inspect.getdoc(cls)) return getattr(cls.template, cls.verb)(**kws) @classmethod def write(cls, fd, **kws): fd.write(linesep) fd.write(cls.render(**kws)) fd.write(linesep) @classmethod def writeiter(cls, fd, seq): for context in seq: cls.write(fd, **context) class StringTemplate(TemplateBase): import string factory = string.Template class SafeStringTemplate(StringTemplate): verb = 'safe_substitute' try: class TempitaTemplate(TemplateBase): import tempita factory = tempita.Template except ImportError: pass try: class MakoTemplate(TemplateBase): from mako.template import Template factory = Template verb = 'render' except ImportError: pass class StartJythonUnix(SafeStringTemplate): r""" #!/usr/bin/ksh java \ -Dpython.home=$jythonhome \ -classpath $jythonhome/jython.jar:$CLASSPATH \ org.python.util.jython.class """ class DefineLocalQueue(StringTemplate): """ DEFINE QLOCAL($qname) + DEFPSIST(YES) + DESCR('$descr') + STGCLASS('$stgclass') + MAXDEPTH ($maxdepth) """ class DeleteLocalQueue(TempitaTemplate): """ DELETE QLOCAL({{qname}}) """ import sys StartJythonUnix.write(sys.stdout, jythonhome="/home/dev/jython/ jython-2.1") from cStringIO import StringIO s = StringIO() DefineLocalQueue.write(s, name="AAA", descr="AAA", stgclass="AAA", maxdepth=100) DeleteLocalQueue.write(s, name="BBB", descr="BBB", stgclass="BBB", maxdepth=100) print s.getvalue() [/code] HTH Gerard From f.guerrieri at gmail.com Mon Jan 14 10:01:40 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Mon, 14 Jan 2008 16:01:40 +0100 Subject: csv add lines In-Reply-To: References: Message-ID: <79b79e730801140701p4df29f20g186c6840970cb8aa@mail.gmail.com> On Jan 14, 2008 3:52 PM, Alexandru Dumitrescu wrote: > > > Hi, > I'm new to this list and to python. > > I am wondering, am I able to make my program read the *.txt files from a > directory and > > to add, at the top of the file, three new lines which are stored in a *.csv > file? Maybe you are still not able to do it :-) But if you give a look at the csv module you probably will be in a short time. Just read http://docs.python.org/lib/module-csv.html where you will learn how to parse a csv file. bye, Francesco From Arao44 at gmail.com Tue Jan 22 01:38:16 2008 From: Arao44 at gmail.com (AK444) Date: Mon, 21 Jan 2008 22:38:16 -0800 (PST) Subject: Electronic and Computer Science video courses, No login, No fee Message-ID: Hi Guys Good news is 23 Electronic and Computer Science video courses are free, No login, No fee. All you need to have is real player installed on your PC. Electronics is at http://freevideolectures.com/electronics/circuits_and_electronics.php Computer Science is at http://freevideolectures.com/ComputerScience/Computer_System_Engineering.php Keep Learning.......... Bye From pavloutefkros at gmail.com Thu Jan 31 12:46:03 2008 From: pavloutefkros at gmail.com (pavloutefkros at gmail.com) Date: Thu, 31 Jan 2008 09:46:03 -0800 (PST) Subject: Python for mobiles Message-ID: <03e0ad28-e72c-4582-8518-b5cb07d408df@e10g2000prf.googlegroups.com> Hello, Is there any chance that i could compile python programs to java (.jar [java bytecode]) so that i could run them with full support (no interpreter) in a wireless device (talking about mobiles eg. nokia, ericsson). I am aware of jython, however i am not elegible of finding a proper article claiming wheather this ability is provided or not. Thanks in advance! From steve at REMOVE-THIS-cybersource.com.au Sat Jan 12 18:56:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 23:56:21 -0000 Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> Message-ID: <13oikt5eoorace6@corp.supernews.com> On Sat, 12 Jan 2008 15:47:05 -0500, Mike Meyer wrote: > There's an apparently common bug here: you don't want to pass super > self.__class__, but the class that the method is bound to. Given an instance method, is it possible to easily determine what class it is defined in? I thought the im_class attribute might do it, but it apparently just points to self.__class__. >>> class Foo(object): ... def foo(self): ... pass ... >>> class Bar(Foo): ... def bar(self): ... pass ... >>> Bar().bar.im_class # expecting Bar >>> Bar().foo.im_class # hoping for Foo -- Steven From over at thepond.com Sun Jan 27 06:53:25 2008 From: over at thepond.com (over at thepond.com) Date: Sun, 27 Jan 2008 11:53:25 GMT Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <60357uF1perd0U1@mid.individual.net> Message-ID: > >> That's not the point, however. I'm trying to say that a processor >> cannot read a Python script, and since the Python interpreter as >> stored on disk is essentially an assembler file, > >It isn't; it's an executable. I appreciated the intelligent response I received from you earlier, now we're splitting hairs. :-) Assembler, like any other higher level language is written as a source file and is compiled to a binary. An executable is one form of a binary, as is a dll. When you view the disassembly of a binary, there is a distinct difference between C, C++, Delphi, Visual Basic, DOS, or even between the different file types like PE, NE, MZ, etc. But they all decompile to assembler. While they are in the binary format, they are exactly that...binary. Who would want to interpret a long string of 1's and 0's. Binaries are not stored in hexadecimal on disk nor are they in hexadecimal in memory. But, all the 1's and 0's are in codes when they are instructions or ASCII strings. No other high level language has the one to one relationship that assembler has to machine code, the actual language of the computer. Dissassemblers can easily convert a binary to assembler due to the one to one relationship between them. That can't be said for any other higher level language. Converting back to C or Python would be a nightmare, although it's becoming a reality. Converting a compiled binary back to hexadecimal is basically a matter of converting the binary to hexadecimal, as in a hex editor. There are exceptions to that, of course, especially with compound assembler statements that use extensions to differentiate between registers. > >> any Python script must be sooner or later be converted to >> assembler form in order to be read by its own interpreter. > >This "assembler form" is commonly referred to as "Python byte code". > thanks for pointing that out. It lead me to this page: http://docs.python.org/lib/module-dis.html where it is explained that the opcodes are in Include/opcode.h. I'll take a look at that. The light goes on. From opcode.h: #define PRINT_NEWLINE_TO 74 All the ASCIi strings end with 0x74 in the disassembly. I have noted that Python uses a newline as a line feed/carriage return. Now I'm getting it. It could all be disassembled with a hex editor, but a disassembler is better for getting things in order. OK. So the pyc files use those defs...that's cool. From http Fri Jan 25 14:56:11 2008 From: http (Paul Rubin) Date: 25 Jan 2008 11:56:11 -0800 Subject: find minimum associated values References: Message-ID: <7xd4rpznl0.fsf@ruckus.brouhaha.com> Alan Isaac writes: > print "method 2: groupby" > t=time.clock() > d = dict() > kv_sorted = sorted(kv, key=lambda x: id(x[0])) How about something like: kv_sorted = sorted(kv, key=lambda x: (id(x[0]), x[1])) Now do your groupby and the first element of each group is the minimum for that group. From asmodai at in-nomine.org Mon Jan 14 06:24:18 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 14 Jan 2008 12:24:18 +0100 Subject: __init__ explanation please In-Reply-To: <87tzlhg9vu.fsf@benfinney.id.au> References: <47895d25$0$30708$4c368faf@roadrunner.com> <87tzlhg9vu.fsf@benfinney.id.au> Message-ID: <20080114112418.GW75977@nexus.in-nomine.org> -On [20080113 14:03], Ben Finney (bignose+hates-spam at benfinney.id.au) wrote: >That's getting the two of them confused. __new__ is a constructor, >__init__ is not. And there I just sent an email stating the wrong thing. I'll dig into it again, because I am really confusing something here (and jumping between 4 languages on the same day is not helping much to be honest). -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ If slavery is not wrong, nothing is wrong... From bj_666 at gmx.net Thu Jan 24 03:44:04 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Jan 2008 08:44:04 GMT Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> Message-ID: <5vr1ekF1njt09U2@mid.uni-berlin.de> On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote: > My second question is: is there any one who has tested very long mbcs > decode? I tried to decode a long(20+MB) xml yesterday, which turns out > to be very strange and cause SAX fail to parse the decoded string. That's because SAX wants bytes, not a decoded string. Don't decode it yourself. > However, I use another text editor to convert the file to utf-8 and > SAX will parse the content successfully. Because now you feed SAX with bytes instead of a unicode string. Ciao, Marc 'BlackJack' Rintsch From bbxx789_05ss at yahoo.com Thu Jan 24 13:52:59 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 24 Jan 2008 10:52:59 -0800 (PST) Subject: Problems getting Python scripts to run on server References: <83ae0f82-e9af-433e-936d-d5b5600a315e@j20g2000hsi.googlegroups.com> Message-ID: <196f3fac-c8a4-417d-ae5d-6a8d458a99cd@v67g2000hse.googlegroups.com> On Jan 23, 11:30?pm, 7stud wrote: I just wanted to point out that the tag below would go in the httpd.conf file(a config file for apache), which you apparently do not have access to. I was suggesting that you check with your host to make sure they have the right AllowOverride line. > > 3) "What you can put in <.htaccess> files is determined by the > AllowOverride directive." > > e.g. > > > ? ? AllowOverride FileInfo > ? ? Options None > ? ? Order allow,deny > ? ? Allow from all > > > "Note: you must have "AllowOverride Options" in effect to permit the > use of the "Options" directive in .htaccess files." > > So, in the above example the line starting with AllowOverride would > need to have "Options" instead of FileInfo(or maybe in addition to?). > > More info fromhttp://httpd.apache.org/docs/2.0/howto/htaccess.html: > ------- > Finally, you may wish to use a .htaccess file to permit the execution > of CGI programs in a particular directory. This may be implemented > with the following configuration: > > Options +ExecCGI > AddHandler cgi-script cgi pl > > Alternately, if you wish to have all files in the given directory be > considered to be CGI programs, this may be done with the following > configuration: > > Options +ExecCGI > SetHandler cgi-script > > Note that AllowOverride Options and AllowOverride FileInfo must both > be in effect for these directives to have any effect. > > Please see the CGI tutorial for a more complete discussion of CGI > programming and configuration. > ----- > > According to that passage, you should have the extension 'py' not > '.py' in the AddHandler part. ?I don't know if that makes a > difference. ?Go to that web page and click the link to the CGI > tutorial, and maybe you can find some clues on how to configure your > directories with .htacesss files. From steve at REMOVE-THIS-cybersource.com.au Wed Jan 30 09:00:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 30 Jan 2008 14:00:19 -0000 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> <0a285e6e-a3a9-4be9-ae59-4cb7547ffa3a@q21g2000hsa.googlegroups.com> Message-ID: <13q10njnbffkceb@corp.supernews.com> On Tue, 29 Jan 2008 13:44:33 -0600, Robert Kern wrote: > Carl Banks wrote: >> On Jan 29, 7:48 am, Peter Schuller wrote: >>>> You can also put, in animal/__init__.py: >>>> from monkey import Monkey >>>> and now you can refer to it as org.lib.animal.Monkey, but keep the >>>> implementation of Monkey class and all related stuff into >>>> .../animal/monkey.py >>> The problem is that we are now back to the identity problem. The class >>> won't actually *BE* org.lib.animal.Monkey. >> >> The usage is the same; it works in all cases once you redefine >> __module__. Who cares what it really is? > > The inspect module. [snip example] I call that a bug in the inspect module. In fact, looking at the source for the findsource() function, I can see no fewer than two bugs, just in the way it handles classes: (1) it assumes that the only way to create a class is with a class statement, which is wrong; and (2) it assumes that the first occurrence of "class " must be the correct definition, which is also wrong. It isn't hard to break the inspect module. Here's an example: >>> import broken >>> import inspect >>> lines, lineno = inspect.findsource(broken.Parrot) >>> lines[lineno] 'class Parrot which will be defined later.\n' >>> >>> lines, lineno = inspect.findsource(broken.Wensleydale) >>> lines[lineno] 'class Wensleydale: # THIS IS GONE\n' Here's the source of broken.py: $ cat broken.py """Here is a doc string, where I happen to discuss the class Parrot which will be defined later. """ class Parrot: pass class Wensleydale: # THIS IS GONE pass del Wensleydale class Wensleydale(object): # but this exists pass It isn't often that I would come right out and say that part of the Python standard library is buggy, but this is one of those cases. -- Steven From paddy3118 at googlemail.com Thu Jan 24 20:35:16 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 17:35:16 -0800 (PST) Subject: Text-based data inspector for Python? References: Message-ID: <6398ab68-da01-408e-902b-0b488310e9b0@e10g2000prf.googlegroups.com> On 25 Jan, 00:36, kj wrote: > I've only recently started programming in Python, trying to wean > myself from Perl. One of the things I *really* miss from Perl is > a 100% mouse-free data inspector, affectionally known as the Perl > debugger, PerlDB, or just perl -d. With it I can examine the most > elaborate data structures with ease: > > DB<234> |x %one_most_elaborate_data_structure > > ...and miles of data, paged for leisurely browsing, lie at my feet. > > And, since it's text-based, I can run it within a shell in Emacs, > and transfer anything I want between it and an editing buffer > without even a THOUGHT of touching the filthy mouse! If there's > a greater joy in life I have yet to find it. > > Now, I have NO DOUBT in my mind WHATSOEVER that a plethora of simply > amazing GRAPHICAL data inspectors (or the equivalent) exist for > Python, with exquisite features, animation, sound effects, > scratch-and-sniff, massage, built-in spiritual advisor, you-name-it. > Beautiful stuff, no doubt. > > But an old geezer like me likes to keep his knobby hands on the > keyboard at all times, so that his arthritic shoulder keeps quiet... > > So. Can I hope to find a text-based data inspector for Python? > > kynn > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. I tend to do the following at the python prompt: from pprint import pprint as pp Then I can: pp(my_data) - Paddy. From paddy3118 at googlemail.com Fri Jan 18 03:06:41 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 18 Jan 2008 00:06:41 -0800 (PST) Subject: array and list References: Message-ID: <24f854eb-93a8-414d-a518-842bb2d185fb@s13g2000prd.googlegroups.com> On Jan 18, 3:23 am, "J. Peng" wrote: > what's the difference between an array and a list in python? > I see list has all features of array in C or perl. > so please tell me.thanks. If you are new to Python, then where other languages may reach for an 'array', Python programs might organise data as lists. Lists are used much more than arrays in Python. you should find that is the case in tutorials/books too. P.S. if you know Perl then try: http://wiki.python.org/moin/PerlPhrasebook?highlight=%28perl%29 - Paddy. From bret.wortman at gmail.com Thu Jan 24 10:49:40 2008 From: bret.wortman at gmail.com (Bret) Date: Thu, 24 Jan 2008 07:49:40 -0800 (PST) Subject: A global or module-level variable? References: <7637fd0b-961e-4730-abd8-96e85c907082@i72g2000hsd.googlegroups.com> <7xwsq1tyts.fsf@ruckus.brouhaha.com> <63002d69-7738-4cae-bfb5-b933f16591b8@t1g2000pra.googlegroups.com> Message-ID: On Jan 23, 2:27 pm, "Gabriel Genellina" wrote: > En Wed, 23 Jan 2008 11:58:05 -0200, Bret escribi?: > > > On Jan 22, 1:00 pm, Paul Rubin wrote: > > >> If you have to do it that way, use: > > > Is there a better way? A more Pythonic way? > > It's simple, clear and works fine, why make it more complicated? > Unless you have additional requirements, like a multithreaded program. > > -- > Gabriel Genellina Ultimately, it will be multithreaded -- and I had intended to wrap the access to the global member in a lock to ensure only one thread could get a value at any point. It might also become multiprocess (ugh!) and so might need to live in its own SocketServer some day. But for now, I agree. Simple is good. I just wanted to be sure I wasn't oversimplifying, you know? Thanks! From MartinRinehart at gmail.com Sat Jan 5 05:15:23 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Sat, 5 Jan 2008 02:15:23 -0800 (PST) Subject: Fortran to Python References: Message-ID: <95d2fc8c-d95c-4f1f-8770-cd89c1295d3c@d21g2000prf.googlegroups.com> Jeroen Ruigrok van der Werven wrote: > I got someone who asked me to make changes in an old Fortran program she is > using for some calculations. Why convert? Modern Fortran is an object oriented, structured language with the singular advantage that it can run old Fortran programs. From nagle at animats.com Fri Jan 25 00:03:06 2008 From: nagle at animats.com (John Nagle) Date: Thu, 24 Jan 2008 21:03:06 -0800 Subject: Sorting Large File (Code/Performance) In-Reply-To: <7x3asmep73.fsf@ruckus.brouhaha.com> References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <4799285d$0$36346$742ec2ed@news.sonic.net> <7x3asmep73.fsf@ruckus.brouhaha.com> Message-ID: <47996c3c$0$36337$742ec2ed@news.sonic.net> Paul Rubin wrote: > John Nagle writes: >> - Get enough memory to do the sort with an in-memory sort, like >> UNIX "sort" or Python's "sort" function. > > Unix sort does external sorting when needed. Ah, someone finally put that in. Good. I hadn't looked at "sort"'s manual page in many years. John Nagle From odysseus1479-at at yahoo-dot.ca Sun Jan 13 04:43:13 2008 From: odysseus1479-at at yahoo-dot.ca (Odysseus) Date: Sun, 13 Jan 2008 09:43:13 GMT Subject: Elementary string-formatting References: Message-ID: In article , Roberto Bonvallet wrote: > Put this at the beginning of your program: > > from __future__ import division > > This forces all divisions to yield floating points values: Thanks for the tip. May I assume the div operator will still behave as usual? -- Odysseus From stefan.behnel-n05pAM at web.de Tue Jan 29 09:17:55 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 29 Jan 2008 15:17:55 +0100 Subject: REALLY simple xml reader In-Reply-To: References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> Message-ID: <479F3593.1080005@web.de> Hi, Ricardo Ar?oz wrote: > I don't know zit about xml, but I might need to, and I am saving the > thread for when I need it. So I looked around and found some 'real' > XML document (see below). The question is, how to access s from > s (any category) but not s. > > doc = """ > > > expenses: january 2002 > > > 31.19 > 200213 > Walking Store > shoes > > > > 1549.58 > 200217 > Bob's Bolts > [...] > > """ Sure, no problem. Just use the XPath expression "//debit/amount", or maybe "/checkbook/credit/amount", if you prefer. This is basically tree traversal, so you can check the parents and the children as you see fit. Stefan From nagle at animats.com Tue Jan 15 02:43:29 2008 From: nagle at animats.com (John Nagle) Date: Mon, 14 Jan 2008 23:43:29 -0800 Subject: Is there some Python function that searches "sys.path" for a module? In-Reply-To: <6c9fb69f-04fb-460e-b78e-9b342e6f83ed@d21g2000prf.googlegroups.com> References: <478c5755$0$36354$742ec2ed@news.sonic.net> <6c9fb69f-04fb-460e-b78e-9b342e6f83ed@d21g2000prf.googlegroups.com> Message-ID: <478C6421.2030603@animats.com> Miki wrote: > http://docs.python.org/lib/module-imp.html Ah. "imp.find_module". I was looking in "sys" and path-related places. Thanks. John Nagle From steve at REMOVE-THIS-cybersource.com.au Sat Jan 5 19:00:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 06 Jan 2008 00:00:53 -0000 Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> Message-ID: <13o06hleh4dkj45@corp.supernews.com> On Sat, 05 Jan 2008 15:07:10 -0800, bearophileHUGS wrote: > Paddy: >> Not really, it seems to me to be going the exact opposite way with >> languages with automatic type conversions being seen as not suited for >> larger programs. > > In Java you can add the number 1 to a string, and have it automatically > converted to string before the string join... What do you think of that > feature? You mean special-casing the int 1 so that this works? # Faked! >>> x = "spam spam spam" >>> x = x + 1 >>> x 'spam spam spam1' but not this? >>> x = "spam spam spam" >>> x = x + 2 TypeError: automatic conversion between strings and ints only works for the int 1 How bizarre. The problem with automatic conversions between strings and integers is that it isn't clear what the user wants when they do something like this: >>> x = '1' + 1 Should x be the string '11' or the int 2? Please justify your answer. On the other hand, if the language includes separate operators for addition and concatenation (say, + and &) then that sort of auto- conversion is no longer ambiguous: >>> '2' + 3 5 >>> '2' & 3 '23' -- Steven From jura.grozni at gmail.com Sun Jan 20 14:55:19 2008 From: jura.grozni at gmail.com (azrael) Date: Sun, 20 Jan 2008 11:55:19 -0800 (PST) Subject: py2exe and modules question Message-ID: I'm working on an application and i'm having some questions. I am working with python 2.5, numpy and PIL. does anyone know if there are some problems while compiling the source because of the modules.. It has to be closed source. I didn't try Py2exe but I heard about it. Is there any other and better way to compile the source. Thnx From gagsl-py2 at yahoo.com.ar Wed Jan 30 22:49:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 31 Jan 2008 01:49:33 -0200 Subject: small problem with re.sub References: <47A13A0A.3010607@al.com.au> Message-ID: En Thu, 31 Jan 2008 01:01:30 -0200, Astan Chee escribi?: > I have a html text stored as a string. Now I want to go through this > string and find all 6 digit numbers and make links from them. > Im using re.sub and for some reason its not picking up the previously > matched condition. Am I doing something wrong? This is what my code > looks like: > htmlStr = re.sub('(?P\d{6})',' href=\"http://linky.com/(?P=id).html\">(?P=id)',htmlStr) > It seems that it replaces it alright, but it replaces it literally. Am I > not escaping certain characters? Two errors: - use raw strings r"..." to write regular expressions (or quote every backslash...) - if you want to *substitute* a named group, the syntax is "\g"; you have used the syntax to *match* a named group. re.sub(r'(?P\d{6})',r'\g',htmlStr) In simple cases like this, may be easier to just use a number: re.sub(r'(\d{6})',r'\1',htmlStr) -- Gabriel Genellina From ryan at ryankaskel.com Wed Jan 23 14:57:12 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 11:57:12 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> <12d19814-b7b9-44b0-aee3-299befac7279@i12g2000prf.googlegroups.com> Message-ID: On Jan 23, 2:53 pm, John Machin wrote: > On Jan 24, 6:17 am, ryan k wrote: > > > I am taking a database class so I'm not asking for specific answers. > > Well I have this text tile: > > >http://www.cs.tufts.edu/comp/115/projects/proj0/customer.txt > > Uh-huh, "column-aligned" output. > > > > > And this code: > > [snip] > > > > > Because the addresses contain spaces, this won't work because there > > are too many values being unpacked in row's __init__'s for loop. Any > > suggestions for a better way to parse this file? > > Tedious (and dumb) way: > field0 = line[start0:end0+1].rstrip() > field1 = line[start1:end1+1].rstrip() > etc > > Why dumb: if the column sizes change, you have to suffer the tedium > again. While your sample appears to pad out each field to some > predetermined width, some reporting software (e.g. the Query Analyzer > that comes with MS SQL Server) will tailor the widths to the maximum > size actually observed in the data in each run of the report ... so > you write your program based on some tiny test output and next day you > run it for real and there's a customer whose name is Marmaduke > Rubberduckovitch-Featherstonehaugh or somesuch and your name is mud. > > Smart way: note that the second line (the one with all the dashes) > gives you all the information you need to build lists of start and end > positions. Thank you for your detailed response Mr. Machin. The teacher *said* that the columns were supposed to be tab delimited but they aren't. So yea i will just have to count dashes. Thank you! From donn.ingle at gmail.com Thu Jan 24 11:12:39 2008 From: donn.ingle at gmail.com (Donn Ingle) Date: Thu, 24 Jan 2008 18:12:39 +0200 Subject: piping into a python script References: <5vrovvF1njt09U6@mid.uni-berlin.de> <77bf0ea2-5e7d-4cd0-8692-319b85a97d65@v17g2000hsa.googlegroups.com> Message-ID: Paddy wrote: > ls *.a | ./fui.py -f - *.b To be sure I grok this: I am seeing the single dash as a placeholder for where all the piped filenames will go, so *.b happens after *.a has been expanded and they all get fed to -f, right? I'm also guessing you mean that I should detect the single dash and then go look for stdin at that point. How do I detect a lack of stdin? Thanks, \d From cwitts at gmail.com Fri Jan 18 04:37:59 2008 From: cwitts at gmail.com (Chris) Date: Fri, 18 Jan 2008 01:37:59 -0800 (PST) Subject: Filtering two files with uncommon column References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> Message-ID: <5084371c-dba0-4d11-be95-a01d1b439de6@s12g2000prg.googlegroups.com> On Jan 18, 11:23 am, Madhur wrote: > I would like to know the best way of generating filter of two files > based upon the following condition > > I have two files. Contents of the first file is > > File 1 > abc def hij > asd sss lmn > hig pqr mno > > File 2 > > jih def asd > poi iuu wer > wer pqr jjj > > I would like have the output as > Output > > File1 > asd sss lmn > File2 > poi iuu wer > > Basically I want to compare the two files based on second column. If > the second > column matches on both the files do not print anything, else if there > is no matc > h in for the second column for first file in second file then print it > under Fil > e1 header, else if there is no match for the second column for second > file in fi > rst file print it under File2 header. > > Thankyou > Madhur file1 = open('file1.txt','rb') file2 = open('file2.txt','rb') file1_line = file1.next() file2_line = file2.next() while file1_line and file2_line: try: f1_col2 = file1_line.split(' ')[1] except IndexError: print 'Not enough delimiters in line.' try: f2_col2 = file2_line.split(' ')[2] except IndexError: print 'Not enough delimiters in line.' if f1_col2 != f2_col2: outfile_data_to_relevant_files() file1_line = file1.next() file2_line = file2.next() HTH Chris From deets at nospam.web.de Sat Jan 19 21:14:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 20 Jan 2008 03:14:25 +0100 Subject: Naming a file In-Reply-To: References: <89bb0095-429f-404c-b7f6-ff0a554b07cc@i72g2000hsd.googlegroups.com> Message-ID: <5vfp46F1meva4U1@mid.uni-berlin.de> Matthias Bl?sing schrieb: > Am Sat, 19 Jan 2008 14:14:30 -0800 schrieb snoylr: > >> For example if the variable is 105Markum >> >> What statement do I need to create a file name 105Markum.txt? > > filename_base = '105Markum' > filename = '%s.txt' % filename_base > f = open(filename, 'w') > f.write( f.close You missed the cruicial parentheses here: f.close() Diez From vladimir at greenmice.info Fri Jan 25 06:30:43 2008 From: vladimir at greenmice.info (Vladimir Rusinov) Date: Fri, 25 Jan 2008 14:30:43 +0300 Subject: problem with gethostbyaddr with intranet addresses on MAC In-Reply-To: References: Message-ID: On 1/25/08, shailesh wrote: > > apples-computer:~ apple$ ping 192.168.4.123 > PING 192.168.4.123 (192.168.4.123): 56 data bytes > 64 bytes from 192.168.4.123: icmp_seq=0 ttl=64 time=0.328 ms > 64 bytes from 192.168.4.123: icmp_seq=1 ttl=64 time=0.236 ms > 64 bytes from 192.168.4.123: icmp_seq=2 ttl=64 time= 0.255 ms > ^C > --- 192.168.4.123 ping statistics --- > 3 packets transmitted, 3 packets received, 0% packet loss > round-trip min/avg/max/stddev = 0.236/0.273/0.328/0.040 ms > apples-computer:~ apple$ python2.4 > Python 2.4.4 (#1, Oct 18 2006, 10:34:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> from socket import * > >>> x = gethostbyname('google.com') > >>> x > '64.233.167.99' > >>> gethostbyaddr(x) > ('py-in-f99.google.com', [], ['64.233.167.99']) > >>> e = '192.168.4.123' > >>> gethostbyaddr(e) > Traceback (most recent call last): > File "", line 1, in ? > socket.herror: (1, 'Unknown host') > >>> > I'm sure your dns server have no reverse records for ' 192.168.4.123'. So, it can't resolve it (123.4.168.192.in-addr.arpa). -- Vladimir Rusinov GreenMice Solutions: IT-??????? ?? ???? Linux http://greenmice.info/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.stuart.risney at gmail.com Sat Jan 12 14:13:22 2008 From: marc.stuart.risney at gmail.com (marcstuart) Date: Sat, 12 Jan 2008 11:13:22 -0800 (PST) Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> Message-ID: <3df4a0f9-6dfd-4dfd-b6bb-53ff434c65e8@s12g2000prg.googlegroups.com> I have gotten a little further, but not in the order of the original list def divide_list(lst, n): return [lst[i::n] for i in range(n)] x = [1,2,3,4,5,6,7,8,9,10] y = 3 z = divide_list(x,y) print z[0] print z[1] print z[2] this prints: [1, 4, 7, 10] [2, 5, 8] [3, 6, 9] closer, but I would like to maintain the original order of the list. From arnodel at googlemail.com Sun Jan 27 20:56:31 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 27 Jan 2008 17:56:31 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> Message-ID: On Jan 28, 1:47?am, Steven D'Aprano wrote: [...] > As nice as this feature would be, and I vote +2 on the functionality, I > wonder whether the amount of line noise in method definitions now will be > approaching Perlish levels? We've got default values, type annotations > (in Python3), *args and **kwargs, _ private names, and now we want to add > auto-assignment. Don't forget keyword only arguments! I find signatures too complicated already, please let's not clutter them even more. -- Arnaud From justinrob at gmail.com Fri Jan 25 06:50:25 2008 From: justinrob at gmail.com (justinrob at gmail.com) Date: Fri, 25 Jan 2008 03:50:25 -0800 (PST) Subject: Minimum Requirements for Python Message-ID: Can someone tell me the minimum requitements for Python as I can't find it anwhere on the site. I have 3 PC's which are only 256mb RAM, wanted to know if this was sufficenent. Thanks From musiccomposition at gmail.com Thu Jan 17 22:45:43 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 17 Jan 2008 19:45:43 -0800 (PST) Subject: Unique thread ID Message-ID: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> Is there a way to obtain a unique ID for the current thread? I have an object that I need to store local thread data in, and I don't want to use threading.local because each thread might have multiple instances of my object. From guyrutenberg at gmail.com Fri Jan 18 07:58:02 2008 From: guyrutenberg at gmail.com (Guy Rutenberg) Date: Fri, 18 Jan 2008 04:58:02 -0800 (PST) Subject: "Code Friendly" Blog? References: Message-ID: <0e3de274-1200-4268-b0ae-e3e56645ba49@s19g2000prg.googlegroups.com> On Jan 18, 8:56 am, Jeroen Ruigrok van der Werven wrote: > I personally use a Wordpress installation on my own machine with an additional > plugin for syntax highlighting.http://wordpress.org/extend/plugins/wp-syntax/ > I use the same configuration (Wordpress + wp-syntax) too. I can say I'm pretty satisfied with it. I had no problem posting python code. IIRC Wordpresss will automatically escape < and > for you (if it's no part of tag). Regards, Guy http://www.guyrutenberg.com/ From skip at pobox.com Tue Jan 15 11:05:43 2008 From: skip at pobox.com (Skip Montanaro) Date: Tue, 15 Jan 2008 16:05:43 +0000 (UTC) Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: > If the RHS is a set then it works OK: Yup, I understand that. Would be kind of bad if it didn't. ;-) > It could be modifies to handle any > iterable on the RHS. That's my question. Why does it work in one place but not everywhere? Skip From marek.rocki at wp.pl Sat Jan 26 08:20:15 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sat, 26 Jan 2008 05:20:15 -0800 (PST) Subject: Doesn't know what it wants References: <13plo358k5rf059@corp.supernews.com> Message-ID: <7909cb2e-33da-47aa-be05-38ca333d2cde@c23g2000hsa.googlegroups.com> > class vec2d(ctypes.Structure): > """2d vector class, supports vector and scalar operators, > and also provides a bunch of high level functions > """ > __slots__ = ['x', 'y'] > > def __init__(self, x_or_pair, y = None): > > if y == None: > self.x = x_or_pair[0] > self.y = x_or_pair[1] > else: > self.x = x_or_pair > self.y = y I may be way off here, but why does vec2d inherit from ctypes.Structure if it doesn't observe the protocol for Structures (they're supposed to have _fields_, not __slots__)? From rrr at ronadam.com Sun Jan 13 23:08:39 2008 From: rrr at ronadam.com (Ron Adam) Date: Sun, 13 Jan 2008 22:08:39 -0600 Subject: time.time or time.clock In-Reply-To: References: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> Message-ID: <478AE047.8070306@ronadam.com> Fredrik Lundh wrote: > John Machin wrote: > >> AFAICT that was enough indication for most people to use time.clock on >> all platforms ... > > which was unfortunate, given that time.clock() isn't even a proper clock > on most Unix systems; it's a low-resolution sample counter that can > happily assign all time to a process that uses, say, 2% CPU and zero > time to one that uses 98% CPU. > > > before the introduction of the timeit module; have you considered it? > > whether or not "timeit" suites his requirements, he can at least replace > his code with > > clock = timeit.default_timer > > which returns a good wall-time clock (which happens to be time.time() on > Unix and time.clock() on Windows). Thanks for the suggestion Fredrik, I looked at timeit and it does the following. import sys import time if sys.platform == "win32": # On Windows, the best timer is time.clock() default_timer = time.clock else: # On most other platforms the best timer is time.time() default_timer = time.time I was hoping I could determine which to use by the values returned. But maybe that isn't as easy as it seems it would be. Ron From JAMoore84 at gmail.com Sat Jan 26 15:15:59 2008 From: JAMoore84 at gmail.com (JAMoore84 at gmail.com) Date: Sat, 26 Jan 2008 12:15:59 -0800 (PST) Subject: Beginner String formatting question References: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> Message-ID: <8e13cb51-5268-419d-99d2-eba8226f4358@z17g2000hsg.googlegroups.com> I apologize for the lack of details in my last post. This time formatting program is a piece of a larger program I am trying to write to de-clutter GPS transmission. I have a GPS receiver that transmits its readings via bluetooth. I've been able to use pySerial and store X number of bytes, then write that to a file (the next step will be finding a way to write the stream to a file directly). The raw GPS data is tranmitted in the NMEA format (http://vancouver-webpages.com/ peter/nmeafaq.txt): $GPRMC,024830,V,,N,,E,,,260108,,,N*58 $GPVTG,,T,,M,,N,,K,N*2C $GPGGA,024831,LAT_GOES_HERE,N,LONG_GOES_HERE,E,0,00,,,M,,M,,*61 $GPGSA,A,1,,,,,,,,,,,,,,,*1E $GPGSV,3,1,09,09,,,37,13,,,00,18,,,00,23,,,00*75 $GPGSV,3,2,09,01,,,00,29,,,00,14,,,00,26,,,00*7A $GPGSV,3,3,09,12,,,00,,,,,,,,,,,,*73 $GPRMC,024831,V,LAT_GOES_HERE,N,LONG_GOES_HERE,E,,,260108,,,N*59 $GPVTG,,T,,M,,N,,K,N*2C the "$GPGGA" and "$GPRMC" lines are the ones that will give you your Latitude and Longitude data --or the would if I had a signal. All the entries are comma delimited, so I used the split(',') function to parse the appropriate statements. Here's the code for that: ============================= input = open('c:\sample_readout.txt','r') #location of the Raw GPS data output = open('c:\GPSout.txt', 'w') output.write("Timestamp \t Latitude \t Longitude \t Velocity") s = input.readlines() for line in s: if line.startswith('$GPGGA'): InputTuple = line.split(',') time = InputTuple[1] lat = InputTuple[2]+' '+InputTuple[3] long = InputTuple[4]+' '+InputTuple[5] out = '\n '+ time + '\t\t' + lat + '\t\t\t' + long output.writelines(out) elif line.startswith('$GPRMC'): InputTuple = line.split(',') time = InputTuple[1] lat = InputTuple[3]+' '+InputTuple[4] long = InputTuple[5]+' '+InputTuple[6] out = '\n '+ time + '\t\t' + lat + '\t\t\t' + long output.writelines(out) elif line.startswith('$GPVTG'): #this will give grounp speed in knts and [7] gives kmph InputTuple = line.split(',') out = '\n ' + '\t\t' + InputTuple[5] output.writelines(out) input.close() output.close() ======================== The time stamp for both the GPRMC and GPGGA lines will be stored in InputTuple[1]. Right now, this program will read the GPS data file and pull out the necessary information. I wanted the Format.py program to function as a module so that I could call Format.FormatTime(time) to change the HHMMSS GPS data to HH:MM:SS, for readability. The next step was to write a FormatCoord function (within the Format module) to do the same for lat/long data. Now that I've explained the structure, the argument of Format.FormatTime() will be InputTuple[1] (the timestamp). I want to be able to call that function in the GPS program to read the contents of InputTuple[1] and write the HH:MM:SS data to the file. I've incorporated some of your recommendations into my program already and it looks much better. Thanks to everyone for your suggestions. Jimmy From bill.wws at gmail.com Sun Jan 13 10:03:15 2008 From: bill.wws at gmail.com (bill.wu) Date: Sun, 13 Jan 2008 07:03:15 -0800 (PST) Subject: i am new guy for this discussion group Message-ID: i am new guy to learn python,also for this discussion group, i am chinese. nice to meet you, everyone. From cokofreedom at gmail.com Thu Jan 17 10:14:08 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 17 Jan 2008 07:14:08 -0800 (PST) Subject: Is this a bug, or is it me? References: Message-ID: <4044206c-9fd8-4dc1-8fe9-61edb314b9f5@k39g2000hsf.googlegroups.com> On Jan 17, 4:05 pm, cptnwill... at gmail.com wrote: > Hello all, > For some reason, the following does not work : > > class C: > TYPES = [None] > DICT = {} > for Type in TYPES: > DICT.update((E,Type) for E in [1]) > > >>> NameError: global name 'Type' is not defined > > What do you think? Is this a bug? Do not use those names...really poor choice... thingydingy = [None] my = {} for dingaling in thingydingy: my.update([(E,dingaling ) for E in [1]]) print my From siona at chiark.greenend.org.uk Mon Jan 28 13:02:53 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Jan 2008 18:02:53 +0000 (GMT) Subject: problem with gethostbyaddr with intranet addresses on MAC References: Message-ID: shailesh wrote: >Python 2.4.4 (#1, Oct 18 2006, 10:34:39) >[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin >Type "help", "copyright", "credits" or "license" for more information. >>>> from socket import * >>>> x = gethostbyname('google.com') >>>> x >'64.233.167.99' >>>> gethostbyaddr(x) >('py-in-f99.google.com', [], ['64.233.167.99']) >>>> e = '192.168.4.123' >>>> gethostbyaddr(e) >Traceback (most recent call last): > File "", line 1, in ? >socket.herror: (1, 'Unknown host') >>>> So what are you expecting it to return? Or, to put it another way, what would you feed to gethostbyname() to get 192.168.4.123 back? Can you get the "right" answer from host or some other command- line tool? Can you get an answer from gethostbyaddr() on one of the other machines on the network? How do they do their name resolution? -- \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 gh at ghaering.de Fri Jan 18 11:42:21 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 18 Jan 2008 17:42:21 +0100 Subject: how to resolve Windows pathnames into cygwin ones In-Reply-To: References: Message-ID: <5vc35eF1lsgcjU1@mid.uni-berlin.de> mgierdal at gmail.com wrote: > I am looking for a function to resolve 'F:/foo/bar' into '/cygdrive/f/ > foo/bar'. I get the original dirpath from tkFileDialog.askdirectory in > a Windows form and none of os.path.* functions seem to resolve it to a > cygwin form. Rather they _append_ it to the current directory, > resulting at best in a monster '/cygdrive/c/whatever/f/foo/bar'. > It's all being developed under cygwin currently (so it is a kind of > mixed environment), but I would like the fix to work correctly in any > environment. You can call the cygpath utility: >>> import commands >>> commands.getoutput("cygpath c:/windows") '/c/windows' -- Gerhard From steve at mhomer.au Thu Jan 10 05:31:18 2008 From: steve at mhomer.au (Steve Brown) Date: Thu, 10 Jan 2008 21:31:18 +1100 Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: <13obsvnqrhqvk34@corp.supernews.com> "Russ P." wrote in message news:d2a08eac-3ae7-4710-9b49-cdbe365a25ef at d21g2000prf.googlegroups.com... > On Jan 9, 11:51 pm, Fredrik Lundh wrote: >> Steve Brown wrote: >> > I've got a series of modules which look like this: >> >> > #************ >> > # >> > # Temperature Sense Test >> > # >> > #************ >> > class Test3(ar_test.AR_TEST): >> > """Temperature Sense Test""" >> >> > I don't like the duplicated information: But the comment is attractive, >> > and >> > the docstring self.__doc__ is already in use in the test log. I've read >> > that >> > all modules and classes should have docstrings, but I don't really have >> > anything else to say, and each module contains only one class. I don't >> > think >> > that >> >> > """Temperature Sense Test""" >> > class Test3(ar_test.AR_TEST): >> > """Temperature Sense Test""" >> >> > would be a real improvement. >> >> > What do you think? >> >> since you already seem to cater to your audience (clearly marked >> comments for people browsing the code, brief docstrings for the test >> log), I don't really see why you should change anything. >> >> > I've read that all modules and classes should have docstrings >> >> if nobody's going to read them, there's no reason to add them. don't >> treat generic style advice as dogma. >> >> > > Well, trivial modules certainly don't need much documentation, but he > didn't say they were trivial. I assumed there was more to them then he > showed. All of the complexity is in the test framework. I've been working on paring back the tests to make them simple to understand, create and modify, which is how I've come to this: I'm still trying to remove lines. The test itself is a now a linear script of 20-40 lines, and I'm still working on them. However, it is relatively important to make the documentation right for these simple scripts. The docstring/comment does need to show some embedded dependancies, I just chose one without any. I realise from reading Jeroen Ruigrok van der Werven's comment that I should probably also care what epydoc makes of my doc strings, -- that's an additional constraint. From steve at REMOVE-THIS-cybersource.com.au Mon Jan 14 16:21:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 14 Jan 2008 21:21:43 -0000 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <87prw4fyej.fsf@benfinney.id.au> Message-ID: <13onkj7ra3i0p75@corp.supernews.com> On Mon, 14 Jan 2008 22:18:44 +1100, Ben Finney wrote: > What one is "in reality" calling is the '__new__' method of the Person > class. That function, in turn, is creating a new Person instance, and > calling the '__init__' method of the newly-created instance. Finally, > the '__new__' method returns that instance back to the caller. But not if Person is an old-style class. -- Steven From george.sakkis at gmail.com Thu Jan 31 20:34:45 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 31 Jan 2008 17:34:45 -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> <7xzlula8z4.fsf@ruckus.brouhaha.com> <7xhcgtv8m0.fsf@ruckus.brouhaha.com> Message-ID: On Jan 31, 7:11 pm, Paul Rubin wrote: > "attn.steven.... at gmail.com" writes: > > True... Any lighter-weight implementation of > > sets out there? That is, one that would defer > > use of resources until actually needed -- > > somewhat akin to the distinction between > > range and xrange, and so on. > > Don't even think of doing it that way, that solves the space problem > but leaves a speed problem. You probably want to use something like > sort the intervals and then use the bisect module to find the > intervals intersecting a given one. I haven't actually used it but from the short description this package seems to fit the bill: http://pypi.python.org/pypi/interval/1.0.0 George From kyosohma at gmail.com Thu Jan 24 09:15:15 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 24 Jan 2008 06:15:15 -0800 (PST) Subject: wxpython References: <77cc3d61-5dd0-4878-b436-b6d07e40de4d@i7g2000prf.googlegroups.com> <0d5fbbaf-aff3-46eb-a8ff-ef0247262fcc@i29g2000prf.googlegroups.com> Message-ID: <8789c20d-4c2a-4c68-a9cb-9b68b0a3f16d@u10g2000prn.googlegroups.com> On Jan 24, 5:37 am, Tim Golden wrote: > [... snip stuff from TJG ...] > > joe jacob wrote: > > Thanks for the information. I'll try to manage it some how. > > If you haven't already, try posting to a wxPython or wxWidgets > mailing list; maybe someone's already done this kind of thing? > > TJG I'm not able to think of anything offhand that's in wxPython, but I seem to recall someone trying to display a language even if the language wasn't installed on the PC. The OP might find the internationalization techniques useful for this application. Here's some wiki entries on that topic: http://wiki.wxpython.org/RecipesI18n http://wiki.wxpython.org/Internationalization The newest version of wxPython comes with Editra, which is a fairly advanced text editor written with wxPython. It won't open exes or pictures, but most files that are in plain text it opens with no problem. Editra has its own site: http://editra.org/ The mailing list for wxPython can be found here: http://wxpython.org/maillist.php Mike From stefan.behnel-n05pAM at web.de Thu Jan 3 02:55:26 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 03 Jan 2008 08:55:26 +0100 Subject: XML-XSD Processing/Creation. In-Reply-To: References: Message-ID: <477C94EE.7080806@web.de> paul wrote: >> Can i create python classes based off the XSD files? What else can I >> do with the XSD files? > This might be worth looking at: http://www.rexx.com/~dkuhlman/#generateDS If it's really such a complex XML language, the tool above might or might not be of any help, as it doesn't support the whole XSD standard (and XML Schema is very complex). It's worth a try, but don't expect too much. The lxml way of dealing with XML languages is namespace implementation: http://codespeak.net/lxml/dev/element_classes.html#id1 However, there isn't currently a way to automatically bootstrap an implementation, especially not in XSD, so it depends on the language how much work it will be to get this to a usable state. Stefan From tteststudent at gmail.com Fri Jan 4 18:17:49 2008 From: tteststudent at gmail.com (ttest) Date: Fri, 4 Jan 2008 15:17:49 -0800 (PST) Subject: Request for help with Image color space conversion Message-ID: <8586a895-f238-4a22-a1bb-31c39f22b4cc@n20g2000hsh.googlegroups.com> Hello, I'm working on an image processing project using the Python Imaging Library along with numpy. Right now, I'm trying to build a speedy script for converting whole images between the RGB and the HSV (a.k.a. HSB) color spaces. Unfortunately, the code I've made so far runs dreadfully slow with even moderate-sized images. I'm under the impression that the crux of the problem is the fact that PIL's point method operates on only one band at a time, and to do a proper color space conversion, you need information about all three bands in a particular problem. This has forced me to do an awkward work-around where the image data is loaded into a numpy array (1600x1200x3), and a dinky for-loop run runs through the array picking up RGB values, converting to HSV, and dumping the results back into another array. How can I make this more efficient? -------- from PIL import Image from PIL import TiffImagePlugin from scipy.misc import pilutil import numpy import colorsys def myrgbtohsv(r,g,b): '''A wrapper for the colorsys function rgb_to_hsv that takes r,g,b values between 0 and 255 (standard pixel value range in most of my single-band imaging operations) and returns the corresponding 255-scaled h,s,v values''' tr = r/255.0 tg = g/255.0 tb = b/255.0 ur,ug,ub = colorsys.rgb_to_hsv(tr,tg,tb) pr = int(round(ur,0))*255 pg = int(round(ug,0))*255 pb = int(round(ub,0))*255 return pr,pg,pb def rgbarrtohsvarr(pilarray): '''Takes an 3d numpy ndarray loaded with a RGB PIL image and converts a copy of the contents to 255-scaled HSV array. Returns the converted copy of the array. ''' arrt = pilarray.copy() r,c,d = arrt.shape hsvarray = numpy.zeros((r,c,d)) print out for i in range(0,r): for j in range(0,c): localrgb = (arrt[i,j,0],arrt[i,j,1],arrt[i,j,2]) (lh,ls,lv) = rgbtohsv(localrgb) hsvarray[i,j,0],hsvarray[i,j,1],hsvarray[i,j,2]= lh,ls,lv return hsvarray im = Image.open(r'C:\test.tif') arr = pilutil.fromimage(im) out = rgbarrtohsvarr(arr) -------- From brunoacf at gmail.com Thu Jan 3 09:38:48 2008 From: brunoacf at gmail.com (Bruno Ferreira) Date: Thu, 3 Jan 2008 11:38:48 -0300 Subject: problem with global var Message-ID: <3448388f0801030638sd285c7dh78b9ea9f7b911139@mail.gmail.com> Hi, I wrote a very simple python program to generate a sorted list of lines from a squid access log file. Here is a simplified version: ################################## 1 logfile = open ("squid_access.log", "r") 2 topsquid = [["0", "0", "0", "0", "0", "0", "0"]] 3 4 def add_sorted (list): 5 for i in range(50): 6 if int(list[4]) > int(topsquid[i][4]): 7 topsquid.insert(i,list) 8 break 8 # Max len = 50 10 if len(topsquid) > 50: 11 topsquid = topsquid[0:50] 12 13 while True: 14 logline = logfile.readline() 15 linefields = logline.split() 16 17 if logline != "": 18 add_sorted (linefields) 19 else: 20 break 21 22 for i in range (len(topsquid)): 23 print topsquid[i][4] #################################### When I execute the program _without_ the lines 10 and 11: 10 if len(topsquid) > 50: 11 topsquid = topsquid[0:50] it runs perfectly. But if I execute the program _with_ those lines, this exception is thrown: bruno at ts:~$ python topsquid.py Traceback (most recent call last): File "topsquid.py", line 20, in add_sorted (linefields) File "topsquid.py", line 6, in add_sorted if int(list[4]) > int(topsquid[i][4]): UnboundLocalError: local variable 'topsquid' referenced before assignment Note that now the error shown is not related with the lines 10 and 11, but wiht a line prior to them. Any hints? -- Bruno A. C. Ferreira Linux Registered User #181386 From eduardo.padoan at gmail.com Wed Jan 23 07:32:55 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Wed, 23 Jan 2008 10:32:55 -0200 Subject: Removing objects In-Reply-To: <13peaovbkqd3202@corp.supernews.com> References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> <13peaovbkqd3202@corp.supernews.com> Message-ID: On Jan 23, 2008 9:55 AM, Steven D'Aprano wrote: > For that to work, you need to give your class an __eq__ method, and have > it match by name: > > # put this in MyClass > def __eq__(self, other): > return self.name == self.other Do you mean: # put this in MyClass def __eq__(self, other): return self.name == other.name ? -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From siona at chiark.greenend.org.uk Mon Jan 7 10:50:59 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Jan 2008 15:50:59 +0000 (GMT) Subject: dictionary/hash and '1' versus 1 References: <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> Message-ID: wrote: >In Java you can add the number 1 to a string, and have it >automatically converted to string before the string join... What do >you think of that feature? "-%s" % 1 -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From over at thepond.com Tue Jan 22 17:45:08 2008 From: over at thepond.com (over at thepond.com) Date: Tue, 22 Jan 2008 22:45:08 GMT Subject: translating Python to Assembler...sorry if this is duplicated...it's unintentional Message-ID: My expertise, if any, is in assembler. I'm trying to understand Python scripts and modules by examining them after they have been disassembled in a Windows environment. I'm wondering if a Python symbols file is available. In the Windows environment, a symbol file normally has a PDB extension. It's a little unfortunate that Python also uses PDB for its debugger. Google, for whatever reason, wont accept queries with dots, hyphens, etc., in the query line. For example a Google for "python.pdb" returns +python +pdb, so I get a ridiculous number of returns referring to the python debugger. I have mentioned this to Google several times, but I guess logic isn't one of their strong points. :-) If there's dupicates of this post it's because it wouldn't send for some reason. From python at rcn.com Tue Jan 22 15:21:54 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 22 Jan 2008 12:21:54 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: [Peter Otten] > You can be bolder here as the izip() docs explicitly state > > """ > Note, the left-to-right evaluation order of the iterables is > guaranteed. This makes possible an idiom for clustering a data series into > n-length groups using "izip(*[iter(s)]*n)". > """ . . . > is about zip(), not izip(). FWIW, I just added a similar guarantee for zip(). Raymond From http Thu Jan 24 14:41:46 2008 From: http (Paul Rubin) Date: 24 Jan 2008 11:41:46 -0800 Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> Message-ID: <7xhch380zp.fsf@ruckus.brouhaha.com> Ira.Kovac at gmail.com writes: > I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like > to sort based on first two characters. > > I'd greatly appreciate if someone can post sample code that can help > me do this. Use the unix sort command: sort inputfile -o outputfile I think there is a cygwin port. > Also, any ideas on approximately how long is the sort process going to > take (XP, Dual Core 2.0GHz w/2GB RAM). Eh, unix sort would probably take a while, somewhere between 15 minutes and an hour. If you only have to do it once it's not worth writing special purpose code. If you have to do it a lot, get some more ram for that box, suck the file into memory and do a radix sort. From mark.dufour at gmail.com Wed Jan 16 06:15:56 2008 From: mark.dufour at gmail.com (Mark Dufour) Date: Wed, 16 Jan 2008 12:15:56 +0100 Subject: Shed Skin (restricted) Python-to-C++ Compiler 0.0.26 Message-ID: <8180ef690801160315i3a2b1b30m403a02ad121f8dca@mail.gmail.com> Hi all, I have just released Shed Skin 0.0.26, with the following goodies: -Almost complete support for os.path (bootstrapped using Shed Skin) -Support for collections.defaultdict (completing collections) -Much improved support for the os module (though many methods remain) -Support for 5 of 7 last missing str methods -Added support for getopt.gnu_getopt (bootstrapped) -Improved support for locales -Optimized string addition (a+b+c..) -Much better documentation (tutorial) -Added a Debian package -Squashed many bugs -Moved to Google code hosting Please have a look at my latest blog entry for more details about the release, or visit the new Google code hosting site: http://shed-skin.blogspot.com http://shedskin.googlecode.com Thanks, Mark Dufour. -- "One of my most productive days was throwing away 1000 lines of code" - Ken Thompson From upton at virginia.edu Thu Jan 31 21:00:07 2008 From: upton at virginia.edu (Dan Upton) Date: Thu, 31 Jan 2008 21:00:07 -0500 Subject: Will Python on day replace MATLAB????????????????????????????????????????????????????? In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380239F7FC@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F7FC@AWMAIL04.belcan.com> Message-ID: <5504f9ac0801311800x6179d86ah30f8229e6d42021@mail.gmail.com> > with ImpulseC and the graphing capabilities of GNU Plot and SciPy in http://gnuplot-py.sourceforge.net/ From george.sakkis at gmail.com Mon Jan 14 21:02:36 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 14 Jan 2008 18:02:36 -0800 (PST) Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> <874pdgf2wo.fsf@benfinney.id.au> Message-ID: <44c962f1-184c-4f79-9ce8-84bd69f9ef64@f47g2000hsd.googlegroups.com> On Jan 14, 5:39 pm, Ben Finney wrote: > I think of NotImplemented as equivalent to None; it's useful as a > sentinel value to set an attribute to in (e.g.) an abstract class. My guess would be that it is more of an implementation performance decision than semantic. Checking 'if result is NotImplemented' is much faster than guarding the call with a try/except NotImplementedError block, and since the motivation for NotImplemented was AFAIK rich comparisons, the potential overhead could be substantial (e.g. a tight 'while i References: <20080109152403.433b113a@bhuda.mired.org> Message-ID: <741fd030801091246h491ffbccp4cbbb3f947aeac63@mail.gmail.com> One way to get this to work is: def inc(jj): def dummy(jj = jj): jj = jj + 1 return jj return dummy h = inc(33) print h() It's not very pretty though, especially when you have many variables you want to have in the inner scope. -Ben On 1/9/08, Mike Meyer wrote: > On Wed, 9 Jan 2008 13:47:30 -0500 (EST) "Steven W. Orr" wrote: > > > So sorry because I know I'm doing something wrong. > > > > 574 > cat c2.py > > #! /usr/local/bin/python2.4 > > > > def inc(jj): > > def dummy(): > > jj = jj + 1 > > return jj > > return dummy > > > > h = inc(33) > > print 'h() = ', h() > > 575 > c2.py > > h() = > > Traceback (most recent call last): > > File "./c2.py", line 10, in ? > > print 'h() = ', h() > > File "./c2.py", line 5, in dummy > > jj = jj + 1 > > UnboundLocalError: local variable 'jj' referenced before assignment > > > > I could have sworn I was allowed to do this. How do I fix it? > > Nope. This is one of the things that makes lisper's complain that > Python doesn't have "real closures": you can't rebind names outside > your own scope (except via global, which won't work here). > > Using a class is the canonical way to hold state. However, any of the > standard hacks for working around binding issues work. For instance: > > >>> def inc(jj): > ... def dummy(): > ... box[0] = box[0] + 1 > ... return box[0] > ... box = [jj] > ... return dummy > ... > >>> h = inc(33) > >>> h() > 34 > > > -- > Mike Meyer http://www.mired.org/consulting.html > Independent Network/Unix/Perforce consultant, email for more information. > -- > http://mail.python.org/mailman/listinfo/python-list > From http Fri Jan 18 05:56:13 2008 From: http (Paul Rubin) Date: 18 Jan 2008 02:56:13 -0800 Subject: Filtering two files with uncommon column References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> <5084371c-dba0-4d11-be95-a01d1b439de6@s12g2000prg.googlegroups.com> Message-ID: <7x1w8f2yia.fsf@ruckus.brouhaha.com> Madhur writes: > If the files2 is unordered, then the above logic does not work. How to > takle it? This sounds like a homework problem. Also, you are trying to reimplement the unix "comm" command. From gagsl-py2 at yahoo.com.ar Mon Jan 21 13:41:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 16:41:50 -0200 Subject: Trouble writing to database: RSS-reader References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> Message-ID: En Mon, 21 Jan 2008 14:12:43 -0200, Arne escribi?: > I try to make a rss-reader in python just for fun, and I'm almost > finished. I don't have any syntax-errors, but when i run my program, > nothing happends. > > This program is supposed to download a .xml-file, save the contents in > a buffer-file(buffer.txt) and parse the file looking for start-tags. > When it has found a start tag, it asumes that the content (between the > start-tag and the end-tag) is on the same line, so then it removes the > start-tag and the end-tag and saves the content and put it into a > database. That's a gratuitous assumption and may not hold on many sources; you should use a proper XML parser instead (using ElementTree, by example, is even easier than your sequence of find and replace) > The problem is that i cant find the data in the database! If i watch > my program while im running it, i can see that it sucsessfuly > downloads the .xml-file from the web and saves it in the buffer. Ok. So the problem should be either when you read the buffer again, when processing it, or when saving in the database. It's very strange to create the table each time you want to save anything, but this gives you another clue: the table is created and remains empty, else the select statement in print_rss would have failed. So you know that those lines are executed. Now, the print statement is your friend: self.buffer = file('buffer.txt') for line in self.buffer.readline(): print "line=",line # add this and see what you get Once you get your code working, it's time to analyze it. I think someone told you "in Python, you have to use self. everywhere" and you read it literally. Let's see: def update_buffer(self): self.buffer = file('buffer.txt', 'w') self.temp_buffer = urllib2.urlopen(self.rssurl).read() self.buffer.write(self.temp_buffer) self.buffer.close() All those "self." are unneeded and wrong. You *can*, and *should*, use local variables. Perhaps it's a bit hard to grasp at first, but local variables, instance attributes and global variables are different things used for different purposes. I'll try an example: you [an object] have a diary, where you record things that you have to remember [your instance attributes, or "data members" as they are called on other languages]. You also carry a tiny notepad in your pocket, where you make a few notes when you are doing something, but you always throw away the page once the job is finished [local variables]. Your brothers, sisters and parents [other objects] use the same schema, but there is a whiteboard on the kitchen where important things that all of you have to know are recorded [global variables] (anybody can read and write on the board). Now, back to the code, why "self." everywhere? Let's see, self.buffer is a file: opened, written, and closed, all inside the same function. Once it's closed, there is no need to keep a reference to the file elsewhere. It's discardable, as your notepad pages: use a local variable instead. In fact, *all* your variables should be locals, the *only* things you should keep inside your object are rssurl and the database location, and perhaps temp_buffer (with another, more meaningful name, rssdata by example). Other -more or less random- remarks: if self.titleStored == True and self.linkStored == True and descriptionStored == True: Don't compare against True/False. Just use their boolean value: if titleStored and linkStored and descriptionStored: Your code resets those flags at *every* line read, and since a line contains at most one tag, they will never be True at the same time. You should reset the flags only after you got the three items and wrote them onto the database. The rss feed, after being read, is available into self.temp_buffer; why do you read it again from the buffer file? If you want to iterate over the individual lines, use: for line in self.temp_buffer.splitlines(): -- Gabriel Genellina From fredrik at pythonware.com Wed Jan 9 16:25:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 22:25:25 +0100 Subject: ISO books of official Python docs In-Reply-To: References: Message-ID: Doug Morse wrote: > I'm terribly confused. You want me to apologize for recommending that someone > buy your books? To apologize for noting that they are a quality reference > sources for Python? for implying that the material in them is copied from the python.org handbooks. at least that's what "reproduce" means in my dictionary. From terry at jon.es Sun Jan 20 22:39:44 2008 From: terry at jon.es (Terry Jones) Date: Mon, 21 Jan 2008 04:39:44 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 04:19:51 on Monday, 21 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <18324.3927.640023.70736@terry.local> Message-ID: <18324.5120.406872.662872@terry.local> My output looks better sorted. I.e., for s in sorted(solutions)... Giving the easier to read/compare: Target 234, numbers = (100, 9, 7, 6, 3, 1) (6, 1, 'add', 100, 'mul', 7, 'sub', 9, 'add', 3, 'div') (6, 9, 'sub', 7, 'mul', 1, 'sub', 100, 'add', 3, 'mul') (7, 3, 'mul', 6, 'sub', 9, 'mul', 1, 'sub', 100, 'add') (7, 6, 'mul', 3, 'mul', 1, 'sub', 100, 'add', 9, 'add') (7, 6, 'mul', 3, 'mul', 100, 'sub', 9, 'mul', 1, 'mul') (100, 1, 'sub', 3, 'div', 7, 'mul', 6, 'sub', 9, 'add') (100, 1, 'sub', 7, 'mul', 9, 'sub', 3, 'div', 6, 'add') (100, 7, 'mul', 3, 'mul', 6, 'add', 9, 'div', 1, 'mul') * (100, 7, 'mul', 6, 'sub', 1, 'sub', 9, 'add', 3, 'div') (100, 7, 'sub', 3, 'div', 1, 'sub', 9, 'add', 6, 'mul') (100, 7, 'sub', 3, 'div', 6, 'sub', 1, 'add', 9, 'mul') (100, 9, 'add', 7, 'add', 1, 'add', 3, 'div', 6, 'mul') (100, 9, 'sub', 7, 'div', 6, 'mul', 3, 'mul', 1, 'mul') (100, 9, 'sub', 7, 'sub', 6, 'sub', 3, 'mul', 1, 'mul') Terry From mario at ruggier.org Wed Jan 2 03:24:59 2008 From: mario at ruggier.org (mario) Date: Wed, 2 Jan 2008 00:24:59 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? Message-ID: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> Hello! i stumbled on this situation, that is if I decode some string, below just the empty string, using the mcbs encoding, it succeeds, but if I try to encode it back with the same encoding it surprisingly fails with a LookupError. This seems like something to be corrected? $ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> s = '' >>> unicode(s, 'mcbs') u'' >>> unicode(s, 'mcbs').encode('mcbs') Traceback (most recent call last): File "", line 1, in LookupError: unknown encoding: mcbs Best wishes to everyone for 2008! mario From jim.hefferon at gmail.com Mon Jan 28 07:27:52 2008 From: jim.hefferon at gmail.com (Jim) Date: Mon, 28 Jan 2008 04:27:52 -0800 (PST) Subject: Can xml.sax NOT process the DTD? References: Message-ID: On Jan 28, 6:48 am, marek jedlinski wrote: > I've noticed that I can eliminate the error if I create 0-byte dtd files > and put them where the parser expects to find them, but this is a little > tedious, since there are plenty of different DTDs expected at different > locations. How about overriding the entity resolver in some way like this: class xResolver(EntityResolver): def resolveEntity(self, publicId, systemId): return "dummy.dtd" and then calling .setEntityResolver(xResolver()) ? That will always look in the same dtd file, which you say works for you. Jim From kyosohma at gmail.com Wed Jan 2 09:33:36 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 2 Jan 2008 06:33:36 -0800 (PST) Subject: Bind mouse over event for panel (or Static text) wxPython References: Message-ID: <4441d83a-9de8-4c06-902b-3dd267c3d199@s12g2000prg.googlegroups.com> On Jan 2, 6:55 am, SMALLp wrote: > How to? > > I couldn't find anything except EVT_ENTER_WINDOW that didn't work. I use wx.EVT_MOTION, which you would have found had you googled for "wxpython mouse events". The first result is: http://www.wxpython.org/docs/api/wx.MouseEvent-class.html which details all the mouse events in wxPython. As I have mentioned to you before, wxPython questions really ought to be addressed to the wxPython users group, which you can join here: http://wxpython.org/maillist.php Mike From george.sakkis at gmail.com Wed Jan 23 17:39:08 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 23 Jan 2008 14:39:08 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> <13pfdh31k2bp8eb@corp.supernews.com> Message-ID: <8f2a164c-5516-487f-802b-5651cb15b404@h11g2000prf.googlegroups.com> On Jan 23, 4:48 pm, Steven D'Aprano wrote: > As for your other points, I think we're actually very much in agreement, > except for your tolerance of random posters asking what I believe is an > incoherent question: "what's the fastest way to do ...?". It seems to me > you're willing to give them the benefit of the doubt that they've done > their profiling and considered their trade-offs, or at the very worst are > asking from purely intellectual curiosity. It depends on the specific problem and the context. For small well- defined algorithmic type problems, I just assume it's intellectual curiosity or that performance really matters. If the same question was asked in the context of, say, a typical web application fetching data from a database and rendering dynamic pages, I might have dismissed it as YAGNI. George From levilista at gmail.com Thu Jan 10 13:25:27 2008 From: levilista at gmail.com (zslevi@gmail.com) Date: Thu, 10 Jan 2008 10:25:27 -0800 (PST) Subject: What is "lambda x=x : ... " ? Message-ID: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> I'm reading this page: http://www.ps.uni-sb.de/~duchier/python/continuations.html and I've found a strange usage of lambda: #################### Now, CPS would transform the baz function above into: def baz(x,y,c): mul(2,x,lambda v,y=y,c=c: add(v,y,c)) ################### What does "y=y" and "c=c" mean in the lambda function? I thought it bounds the outer variables, so I experimented a little bit: ################# x = 3 y = lambda x=x : x+10 print y(2) ################## It prints 12, so it doesn't bind the variable in the outer scope. From ricaraoz at gmail.com Tue Jan 29 09:53:44 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 29 Jan 2008 11:53:44 -0300 Subject: REALLY simple xml reader In-Reply-To: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> Message-ID: <479F3DF8.4070308@bigfoot.com> > What about : > > doc = """ > > 99 > > > 42 > > """ That's not an XML document, so what about it? Stefan ---------------------------------------------- Ok Stefan, I will pretend it was meant in good will. I don't know zit about xml, but I might need to, and I am saving the thread for when I need it. So I looked around and found some 'real' XML document (see below). The question is, how to access s from s (any category) but not s. Probably my previous example was not properly stated, what I meant to convey is two substructures (namespaces, or whatever you call them in XML) which have the same 'properties' is not the same as as is not the same as . The examples given by Diez and Mark, though useful, don't seem to address the problem. Thanks for your help. doc = """ expenses: january 2002 31.19 200213 Walking Store shoes 1549.58 200217 Bob's Bolts 40 200218 pocket money 25 200218 188.20 200218 Boston Endodontics cavity 10.58 2002110 Exxon Saugus gasoline 909.56 2002114 Honda North car repairs 24.30 2002115 Johnny Rockets lunch """ From bill.wws at gmail.com Sun Jan 13 21:20:34 2008 From: bill.wws at gmail.com (bill.wu) Date: Sun, 13 Jan 2008 18:20:34 -0800 (PST) Subject: i am new guy for this discussion group References: <2c96a1ab-207c-4671-a529-358bdb51d4fc@f10g2000hsf.googlegroups.com> Message-ID: <9cf6638e-41ed-4c78-9d1b-aff6547f8ae3@e6g2000prf.googlegroups.com> On Jan 14, 2:03?am, "bruno.desthuilli... at gmail.com" wrote: > On Jan 13, 3:03 pm, "bill.wu" wrote: > > > i am new guy to learn python,also for this discussion group, i am > > chinese. > > nice to meet you, everyone. > > Hi and welcome onboard. > > If you're new to programming in general, you may want to join the > tutor mailing-list.http://mail.python.org/mailman/listinfo/tutor > > If you're already a programmer, you may want to follow the offficial > tutorial, then probably diveintopython:http://docs.python.org/tut/tut.htmlhttp://www.diveintopython.org/ > > HTH thank you very much. From steve at REMOVE-THIS-cybersource.com.au Thu Jan 24 19:58:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 25 Jan 2008 00:58:14 -0000 Subject: Terminology: "script" versus "program" References: <1666950d-e9a5-4b7c-a614-5bba90e5b4ca@y5g2000hsf.googlegroups.com> <87ir1j7r9k.fsf_-_@benfinney.id.au> Message-ID: <13pid16l607s065@corp.supernews.com> On Thu, 24 Jan 2008 12:22:04 +0000, samwyse wrote: >> The term "script" has the strong connotation of a limited-purpose >> program designed to solve a problem expressed almost entirely as a >> simple series of steps. Languages that are often used to write such >> scripts are usually referred to as "scripting languages", which becomes >> a denigration because such a language need not have support for much >> else. > > I strongly disagree with your interpretation. Scritping languages > provide high-level facilites for process control. Historically, they > were purely interpretive but now they tend to compile to some sort of > byte code. Examples include the various shells, Rexx, and various > languages whose names start with "P". Do you have a source for your claim that the shells (e.g. Linux/Unix shells bash, ksh, zsh, etc. or Windows shells cmd.exe, command.com) are compiled to byte code? I don't believe this is the case, I understand that they are typically "immediate interpreted" languages, that is, each line in interpreted from source code immediately before being executed, as often as it takes. Note to purists: yes, I know that being interpreted or compiled is a property of the implementation, not the language. But when all the implementations of a language (where "all" might mean "the only one"), I think it is reasonable to blur the lines. > Languages which only express a > "series of steps" are generally called batch languages. Maybe in the Windows/DOS world, but not typically in the Linux/Unix world, where they are called scripting languages. > I've never > heard anyone refer to a .BAT file as a script. Linux/Unix/Mac admins may be excused for saying that they've never come across a .BAT file at all. $ locate .bat | wc -l 14 Oh well, what do you know! I've got fourteen of the beggars. Hmmm... two are in the Python standard lib, two are in wxPython, six seem to be in the game Abuse, a couple of false positives, and a few odd files. $ locate .sh | wc -l 606 -- Steven From dongie.agnir at gmail.com Wed Jan 9 02:25:18 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Tue, 8 Jan 2008 23:25:18 -0800 (PST) Subject: Tracking colors Message-ID: I'm just getting started with Python, and I want to do a bit of color tracking using VideoCapture. However, I've never worked with video or images, so I'm a little at a loss. How would I use VideoCapture to track a specified color, and its coordinates? From ndbecker2 at gmail.com Mon Jan 14 07:56:05 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 14 Jan 2008 07:56:05 -0500 Subject: ucs2 or ucs4? Message-ID: How do I tell if my python-2.5 is build with ucs2 or ucs4? From james.pye at gmail.com Tue Jan 22 11:14:13 2008 From: james.pye at gmail.com (james.pye at gmail.com) Date: Tue, 22 Jan 2008 08:14:13 -0800 (PST) Subject: isgenerator(...) - anywhere to be found? References: <5vm8t3F1m1797U1@mid.uni-berlin.de> Message-ID: <0336d6a4-9dac-4a64-a189-2d8384046934@e10g2000prf.googlegroups.com> On Jan 22, 6:20?am, "Diez B. Roggisch" wrote: > For a simple greenlet/tasklet/microthreading experiment I found myself in > the need to ask the question > > isgenerator(v) > > but didn't find any implementation in the usual suspects - builtins or > inspect. types.GeneratorType exists in newer Pythons, but I'd suggest just checking for a send method. ;) That way, you can use something that emulates the interface without being forced to use a generator. hasattr(ob, 'send').. From stefan.behnel-n05pAM at web.de Mon Jan 7 03:43:55 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 07 Jan 2008 09:43:55 +0100 Subject: Patches to Python 2.5.1 In-Reply-To: References: Message-ID: <4781E64B.9050700@web.de> Brad wrote: > I was just looking through the 2.5.1 source code. I noticed a few > mis-spellings in the comments. No big deal really. Can patches be > submitted that correct the spelling errors or should they just be > pointed out to some mailing list? Funny you ask, if there were so few, you could already have added the patch anyway. :) However, I'd just submit it to Python's bug tracker. Broken documentation is something that should be fixed. Stefan From donn.ingle at gmail.com Mon Jan 14 17:55:07 2008 From: donn.ingle at gmail.com (Donn) Date: Tue, 15 Jan 2008 00:55:07 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478BD8AC.6050404@v.loewis.de> References: <200801141802.56353.donn.ingle@gmail.com> <478BD8AC.6050404@v.loewis.de> Message-ID: <200801150055.07699.donn.ingle@gmail.com> > You get the full locale name with locale.setlocale(category) (i.e. > without the second argument) Ah. Can one call it after the full call has been done: locale.setlocale(locale.LC_ALL,'') locale.setlocale(locale.LC_ALL) Without any issues? > > I need that two-letter code that's hidden in a > > typical locale like en_ZA.utf8 -- I want that 'en' part. Okay, I need it because I have a tree of dirs: en, it, fr and so on for the help files -- it's to help build a path to the right html file for the language being supported. > Not sure why you want that. Notice that the locale name is fairly system > specific, in particular on non-POSIX systems. It may be > "English_SouthAfrica" on some systems. Wow, another thing I had no idea about. So far all I've seen are the xx_yy.utf8 shaped ones. I will have some trouble then, with the help system. Thanks, \d -- "There may be fairies at the bottom of the garden. There is no evidence for it, but you can't prove that there aren't any, so shouldn't we be agnostic with respect to fairies?" -- Richard Dawkins Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From salgerman at gmail.com Thu Jan 3 23:44:33 2008 From: salgerman at gmail.com (gsal) Date: Thu, 3 Jan 2008 20:44:33 -0800 (PST) Subject: Problem reading csv files References: <1788604d-5fed-435a-a9f3-f7e9f652b5a3@s12g2000prg.googlegroups.com> Message-ID: <9e78ef2f-7532-41dd-935e-c1eea4b1bc58@j78g2000hsd.googlegroups.com> Well, I don't know much python, yet, but I know a csv file when I see one...and an Excel files in not a csv file. As far as I know, an Excel file is stored probably in binary and in a propriatery format...I doubt very much csv.reader would read that just like that; then again, I know nothing about cvs.reader. A csv file is a comma-separated-file and it is plain text file that humans can read with a simple editor... I think I would skip that part where you make OpenOffice store the file in Excel format and simply save it to plain text. Hope this helps. gsal From stefan.behnel-n05pAM at web.de Wed Jan 23 10:18:01 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 16:18:01 +0100 Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? In-Reply-To: References: Message-ID: <47975AA9.9010103@web.de> Hi, kliu wrote: > what I really need is the mapping between each DOM nodes and > the corresponding original source segment. I don't think that will be easy to achieve. You could get away with a parser that provides access to the position of an element in the source, and then map changes back into the document. But that won't work well in the case where the parser inserts or deletes content to fix up the structure. Anyway, the normal focus of broken HTML parsing is in fixing the source document, not in writing out a broken document. Maybe we could help you better if you explained what your actual intention is? Stefan From http Fri Jan 11 15:54:09 2008 From: http (Paul Rubin) Date: 11 Jan 2008 12:54:09 -0800 Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> Message-ID: <7xprw8w0b2.fsf@ruckus.brouhaha.com> dg.google.groups at thesamovar.net writes: > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > run() > > The idea is that the run() function inspects the stack, and looks for > object which are instances of class Obj, creates a Bigobj with those > objects and calls its run() method. > > So, any comments on that approach? Bleeearrrrrggggh!!!! Just make the object initializer remember where the instances are. Or, write something like: newobj = Bigobj() # give Bigobj a __call__ method to create and record an object obj1 = newobj(params1) obj2 = newobj(params2) ... newobj.run() From http Fri Jan 11 00:06:39 2008 From: http (Paul Rubin) Date: 10 Jan 2008 21:06:39 -0800 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> Message-ID: <7xir21lzmo.fsf@ruckus.brouhaha.com> erik gartz writes: > The loop performs some actions with web services. The particular > iteration I'm on isn't important to me. It is only important that I > attempt the web services that number of times. If I succeed I > obviously break out of the loop and the containing function (the > function which has the loop in it) returns True. If all attempts fail > the containing loop returns False. This uses an index var, but doesn't leak it outside the genexp, so I don't know what pylint would say (untested): def f(): return any(attempt_service() for i in xrange(10)) I think the above is pretty natural. If you really insist on not using any variables, the below might work (untested): from itertools import imap, repeat def f(): return any(imap(apply, repeat(attempt_service, 10))) it just seems way too obscure though. Python style seems to favor spewing extra variables around. From sjmachin at lexicon.net Wed Jan 23 17:50:21 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 14:50:21 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <7x8x2g8isi.fsf@ruckus.brouhaha.com> <13pfgdct573772d@corp.supernews.com> Message-ID: <416d70d4-35e5-457d-ad01-38725ded6ac7@s8g2000prg.googlegroups.com> On Jan 24, 9:47 am, ryan k wrote: > On Jan 23, 5:37 pm, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Wed, 23 Jan 2008 11:05:01 -0800, Paul Rubin wrote: > > > ryan k writes: > > >> Hello. I have a string like 'LNAME > > >> PASTA ZONE'. I want to create a list of those words and > > >> basically replace all the whitespace between them with one space so i > > >> could just do lala.split(). Thank you! > > > > import re > > > s = 'LNAME PASTA ZONE' > > > re.split('\s+', s) > > > Please tell me you're making fun of the poor newbie and didn't mean to > > seriously suggest using a regex merely to split on whitespace? > > > >>> import timeit > > >>> timeit.Timer("s.split()", "s = 'one two three four'").repeat() > > > [1.4074358940124512, 1.3505148887634277, 1.3469438552856445]>>> timeit.Timer("re.split('\s+', s)", "import re;s = 'one two > > > three four'").repeat() > > [7.9205508232116699, 7.8833441734313965, 7.9301259517669678] > > > -- > > Steven > > The main topic is not an issue anymore. We know that. This thread will continue with biffo and brickbats long after your assignment has been submitted :-) From gagsl-py2 at yahoo.com.ar Sat Jan 26 13:33:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 26 Jan 2008 16:33:50 -0200 Subject: Anybody has ported talib to Python via SWIG References: <6fa2a3e3-ab77-41dc-a01e-55770a764b0e@k39g2000hsf.googlegroups.com> Message-ID: En Thu, 24 Jan 2008 20:49:33 -0200, Aldo Ceccarelli escribi?: > Hi Everybody, > TaLib (technical analysis package with function indicators coded in C/C > ++, http://www.ta-lib.org ) has a complete library with source in C/C+ > +. > > I am new to SWIG (wrapper interface generator) and would really > appreciate any Python (.py) port of TaLib to be able to call and test > TaLib's functions (f.i. MACD, Parabolic SAR and so on) in some Python > (2.5) script. > > Do you have idea whether TaLib Python package has already been > generated and can be eventually downloaded anywhere? If Talib has a C API (not C++), the ctypes module can be used to call those C functions, so there is no need to write a special SWIG wrapper. In fact it may be much easier to do that way. ctypes is a standard module on Python 2.5, and is documented here: http://docs.python.org/lib/module-ctypes.html -- Gabriel Genellina From nagle at animats.com Fri Jan 18 12:54:46 2008 From: nagle at animats.com (John Nagle) Date: Fri, 18 Jan 2008 09:54:46 -0800 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. In-Reply-To: <479046a5$0$36403$742ec2ed@news.sonic.net> References: <478FAC5A.50206@animats.com> <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> <479046a5$0$36403$742ec2ed@news.sonic.net> Message-ID: <4790e693$0$36362$742ec2ed@news.sonic.net> John Nagle wrote: > Irmen de Jong wrote: >> Christian Heimes wrote: >>> John Nagle wrote: >>>> It's possible to use "pickle" for interprocess communication over >>>> pipes, but it's not straightforward. Another "gotcha". The "pickle" module seems to be OK with the translations of "universal newlines" on Windows, but the "cPickle" module is not. If I pickle Exception("Test") send it across the Windows pipe to the parent in universal newlines mode, and read it with cPickle's load() function, I get ImportError: No module named exceptions If I read it with "pickle"'s "load()", it works. And if I read the input one character at a time until I see ".", then feed that to cPickle's "loads()", that works. So cPickle doesn't read the same thing Python does in "universal newline" mode. Is there any way within Python to get the pipe from a child process to the parent to be completely transparent under Windows? John Nagle From vedrandekovic at gmail.com Wed Jan 23 11:37:15 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Wed, 23 Jan 2008 08:37:15 -0800 (PST) Subject: py2exe: python modules and applicaation Message-ID: Hello again, I'am working a simple application with wxpython, py2exe and directpython.After I write python code in my wxpython textctrl, then my application must save that code and create ( pgssetup2.py script ), and then with py2exe create (.exe) of the code. ( my application is builded with py2exe too ). Here is example of code the converts from .py to .exe: try: process2=subprocess.Popen(["python","pgssetup2.py","py2exe","- d","exe"],shell=True, stdout=subprocess.PIPE) stdout_value = process2.communicate()[0] except NameError,e: print e When I run this code before converting to exe it works fine but in .exe there is no error but It wont work. I think it's problem with modules py2exe and directpython how can I "append" that modules to my application? Regards, Vedran From wuwei23 at gmail.com Thu Jan 24 19:49:40 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jan 2008 16:49:40 -0800 (PST) Subject: Test driven development References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> <53bae618-0a57-470e-b698-3f936ef7c0e7@s12g2000prg.googlegroups.com> <98f3ca4c-a7f0-4707-b09d-8012b86de96b@x69g2000hsx.googlegroups.com> Message-ID: <273268bb-421f-4228-a16b-a64ea38869b8@m34g2000hsf.googlegroups.com> On Jan 25, 5:44 am, Roel Schroeven wrote: > I guess I just need to try somewhat harder to use TDD in my daily > coding. Apart from books, are there other resources that can help > beginners with TDD? Mailing lists, forums, newsgroups possibly? There's the Testing-in-Python mailing list. It's pretty low traffic but generally relevant: http://lists.idyll.org/listinfo/testing-in-python -alex23 From sromero at gmail.com Wed Jan 9 09:26:05 2008 From: sromero at gmail.com (Santiago Romero) Date: Wed, 9 Jan 2008 06:26:05 -0800 (PST) Subject: Converting a bidimensional list in a bidimensional array References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> Message-ID: <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> > > This is how I create the tilemap (and the clipboard, a copy of my > > tilemap): > > > def __init__( self, bw, bh, tiles ): > > self.tilemap = [] > > (...) > > for i in range(bh): > > self.tilemap.append([0] * bw) > def __init__( self, bw, bh, tiles ): > self.width, self.height = bw, bh > self.tilemap = array.array('b', [0]) * bw * bh > > Gives a pure linearization (you do the math for lines). Do you mean : tilemap[(width*y)+x] ? > def __init__( self, bw, bh, tiles ): > self.width, self.height = bw, bh > self.tilemap = [array.array('b', [0]) * bw for row in range(bh)] > > Gives a list of arrays. I punted on the type arg here; you should make > a definite decision based on your data. What do you think about: - Memory Performance: Of course, my maps will take ( 16 bytes / 2-4 bytes ) = 8 or 4 times less memory (32 / 64 bit processores) ... right? - Speed Performance: Do you think that changing from list to Array() would improve speed? I'm going to do lots of tilemap[y][x] checks (I mean, player jumping around the screen, checking if it's falling over a non-zero tile, and so). And thanks a lot for your answer :-) From sjmachin at lexicon.net Thu Jan 17 06:28:58 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 17 Jan 2008 03:28:58 -0800 (PST) Subject: reading a specific column from file References: <3149e879-b94d-443c-b056-d6cf5bad2688@h11g2000prf.googlegroups.com> Message-ID: On Jan 17, 8:47 pm, Hai Vu wrote: > Here is another suggestion: > > col = 2 # third column > filename = '4columns.txt' > third_column = [line[:-1].split('\t')[col] for line in open(filename, > 'r')] > > third_column now contains a list of items in the third column. > > This solution is great for small files (up to a couple of thousand of > lines). For larger file, performance could be a problem, so you might > need a different solution. Using the maxsplit arg could speed it up a little: line[:-1].split('\t', col+1)[col] From lars at larsjohansen.org Tue Jan 29 03:42:28 2008 From: lars at larsjohansen.org (Lars Johansen) Date: Tue, 29 Jan 2008 09:42:28 +0100 Subject: [HELP] SMTPlib not sending my mail In-Reply-To: References: Message-ID: <1201596148.7850.2.camel@lars-laptop.ez.no> have you checked your mail server logs ? tir, 29.01.2008 kl. 00.24 -0800, skrev ashok.raavi: > Hi, > > I am also facing the same problem, smtplib used to send mail a while > back but it stopped sending mails. > > when i run this in interpreter > >>> import smtplib > >>> s = smtplib.SMTP("localhost") > >>> s.sendmail(from, to, "message") > {} > >>> > > though it is not giving any error, it is not sending mail. > > Any help is appreciated. > > ornto wrote: > > Hi, I'm trying to create an application which checks a > > dynamic web site and on certain events sends an email to me. > > My problem though is with the email task. By now I made this > > simple test code: > > > > #prova invio email > > smtpserver = smtplib.SMTP(mailserver) > > messaggio= "Messaggio di prova" > > print mail > > print messaggio > > smtpresult=smtpserver.sendmail("Watcher",mail,messaggio) > > if smtpresult: > > print smtpresult > > smtpserver.quit() > > > > "mailserver" and "mail" values are loaded from a ini file > > and they're correct. > > The call to smtpserver gives back no errors (smtpresult > > remains empty). > > The running enviroment gives no error. > > So, it looks like that the program works alloright, sending > > the mail- BUT, I receive no mail! I've tried to change the > > smtp server with another one which still works with my isp, > > with no luck. If I try a smtp which doesn't give me access, > > I correctly receive an error from the program. > > What might be the problem? From pablo at decode.com.ar Wed Jan 9 09:08:31 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Wed, 09 Jan 2008 12:08:31 -0200 Subject: alternating string replace In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <4784D55F.9070004@decode.com.ar> cesco wrote: > Hi, > > say I have a string like the following: > s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... What about: >>> import re >>> s1 = 'hi_cat_bye_dog' >>> print re.sub(r'([^_]+)_([^_]+)_?', r'\1:\2;', s1) hi:cat;bye:dog; it still works for a longer string: >>> s1 = 'hi_cat_bye_dog_' + s1 >>> s1 'hi_cat_bye_dog_hi_cat_bye_dog' >>> print re.sub(r'([^_]+)_([^_]+)_?', r'\1:\2;', s1) hi:cat;bye:dog;hi:cat;bye:dog; From jgardner at jonathangardner.net Thu Jan 24 16:13:49 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 24 Jan 2008 13:13:49 -0800 (PST) Subject: object vs class oriented -- xotcl References: Message-ID: <2dc601fc-38de-4cf6-bed0-5bf8be06b29b@e6g2000prf.googlegroups.com> On Jan 24, 12:35 pm, William Pursell wrote: > I'm not sure that describes the method well. Basically, you can > instantiate an object A of class Foo, and later change A to be an > object of class Bar. Does Python support this type of flexibility? > As I stated above, I've been away from Python for awhile now, and am a > bit rusty, but it seems that slots or "new style" objects might > provide this type of behavior. The ability to have an object change > class is certainly (to me) a novel idea. Can I do it in Python? Short answer: yes, easily. Long answer: observe. >>> class Foo(object): ... def foo(self): print "Foo.foo" ... >>> class Bar(object): ... def foo(self): print "Bar.foo" ... >>> a = Foo() >>> a.__class__ = Bar >>> a.foo() Bar.foo From steve at REMOVE-THIS-cybersource.com.au Tue Jan 1 05:32:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 01 Jan 2008 10:32:06 -0000 Subject: using super References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> Message-ID: <13nk5l6oah7mh9b@corp.supernews.com> On Mon, 31 Dec 2007 22:56:41 -0800, iu2 wrote: > Indeed I might want to chain methods in all sort of ways: > @chain_call_before - call the parent's method before the derived method > @chain_call_after - call the parent's method after the derived method > @chain_call_sum - sum the result of the parent's method with the result > of the derived method > @chain_call_list - make a list from the result of the parent's method > and the result of the derived method Indeed there are all sorts of ways you might want to call the parent class' method. How about a @chain_call__multiply_by_seven_and_append_to_list decorator? [snip] >>simply remind people to call >> A.foo(self, ) within the definition of foo in B. > > Sorry, I can't agree to this (although there is nothing else I can do.. > . Reminding is not "simply" at all. Why REMIND people do stuff and not > let Python handle it automatically? But Python can't handle it automatically, not unless you do import read_my_mind_and_do_what_I_want first. (Module expected in Python 9.7, due out in 2058.) Since you have to call the superclass yourself, there's not that much difference between reminding people to call the superclass by hand, and reminding them to call some decorator. Admittedly, a decorator for the most common cases would be easier to use than super(), but I don't think it would make enough of a difference that it is worth changing Python's object model just to make it possible. As the Zen of Python says: "Special cases aren't special enough to break the rules." (or in this case, to change the rules). And as others have pointed out, if you really want this desperately enough, you can create a metaclass to handle it. -- Steven From MartinRinehart at gmail.com Mon Jan 7 08:09:15 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Mon, 7 Jan 2008 05:09:15 -0800 (PST) Subject: Python's great, in a word Message-ID: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> I'm a Java guy who's been doing Python for a month now and I'm convinced that 1) a multi-paradigm language is inherently better than a mono-paradigm language 2) Python writes like a talented figure skater skates. Would you Python old-timers try to agree on a word or two that completes: The best thing about Python is _______. Please, no laundry lists, just a word or two. I'm thinking "fluid" or "grace" but I'm not sure I've done enough to choose. From martyb1 at earthlink.net Fri Jan 11 01:48:43 2008 From: martyb1 at earthlink.net (Marty) Date: Fri, 11 Jan 2008 01:48:43 -0500 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: Mike Meyer wrote: > On Thu, 10 Jan 2008 22:36:56 -0500 Marty wrote: >> I recently faced a similar issue doing something like this: >> >> data_out = [] >> for i in range(len(data_in)): >> data_out.append([]) > > More succinctly: > > data_out = [] > for _ in data_in: > data_out.append([]) > > Or, as has already been pointed out: > > data_out = [[] for _ in data_in] That's nice. > >> This caused me to wonder why Python does not have a "foreach" statement (and >> also why has it not come up in this thread)? I realize the topic has probably >> been beaten to death in earlier thread(s), but does anyone have the short answer? > > But I'm curious - what's the difference between the "foreach" you have > in mind and the standard python "for"? > > <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> Message-ID: <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> On Jan 10, 3:37 am, Bruno Desthuilliers wrote: > I fail to see how the existence of JIT compilers in some Java VM changes > anything to the fact that both Java (by language specification) and > CPython use the byte-code/VM scheme. Because these "some Java VMs" with JIT compilers are the de facto standard used by millions; the spec is pretty much irrelevant (unless you're a compiler writer or language theorist). George From steve at REMOVE-THIS-cybersource.com.au Wed Jan 16 06:33:47 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Jan 2008 11:33:47 -0000 Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> <873asyclo0.fsf@benfinney.id.au> Message-ID: <13orqsrlp81ep71@corp.supernews.com> On Wed, 16 Jan 2008 17:46:39 +1100, Ben Finney wrote: > Christian Heimes writes: > >> Dennis Lee Bieber wrote: >> > Since all "variable" names in Python are references to objects, >> > anything accessed using a name is accessed by reference. >> >> Anybody using the terms variable, reference or call-by-value is most >> likely explaining Python the wrong way. > > The term "reference" is fine, since that's exactly how it works. One > gets at an object via some reference, be it a name or some access into a > container object. When an object has no more references to itself, it > becomes a candidate for garbage collection. And so on. The term "reference" *by itself* is fine, so long as there is no possibility of confusion with the very common concept of "call by reference" (or "pass by reference"). But since the Original Poster himself raised the question of whether Python is call by reference or call by value, that should be a great big warning flag to avoid the term "reference" until he's reset his brain. Python is not C, and if you talk about Python using C terminology without making it absolutely crystal clear that the semantics of that terminology is different in Python, then you'll just reinforce the O.P.'s misunderstandings. Python might have "references" in the generic sense, but in the specific sense that it is understood by most people with C/Pascal/Java/Perl experience, Python does not. -- Steven From jpeng at block.duxieweb.com Sun Jan 20 23:02:50 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Mon, 21 Jan 2008 12:02:50 +0800 Subject: object scope Message-ID: <4794196A.2020901@block.duxieweb.com> Please see the code below,what's the scope for object "name"? I thought it should be located in the while block, but it seems not really,it can be accessed out of while (the db[name] statement).Thanks in advance. db = {} def newuser(): prompt = 'login desired: ' while 1: name = raw_input(prompt) if db.has_key(name): prompt = 'name taken, try another: ' continue else: break pwd = raw_input('passwd: ') db[name] = pwd From stefan.behnel-n05pAM at web.de Sun Jan 27 04:30:42 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 27 Jan 2008 10:30:42 +0100 Subject: Sorting Large File (Code/Performance) In-Reply-To: References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <690cb460-fa8a-49a1-a6fa-69cdf480a918@i3g2000hsf.googlegroups.com> <7xir1hznuu.fsf@ruckus.brouhaha.com> Message-ID: <479C4F42.3010500@web.de> Gabriel Genellina wrote: > use the Windows sort command. It has been > there since MS-DOS ages, there is no need to download and install other > packages, and the documentation at > http://technet.microsoft.com/en-us/library/bb491004.aspx says: > > Limits on file size: > The sort command has no limit on file size. Sure, since no-one can ever try it with more than 640k, it's easy to state that there is no limit. :) Stefan From robert.kern at gmail.com Sat Jan 12 04:25:52 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 12 Jan 2008 03:25:52 -0600 Subject: Is unicode.lower() locale-independent? Message-ID: The section on "String Methods"[1] in the Python documentation states that for the case conversion methods like str.lower(), "For 8-bit strings, this method is locale-dependent." Is there a guarantee that unicode.lower() is locale-*in*dependent? The section on "Case Conversion" in PEP 100 suggests this, but the code itself looks like to may call the C function towlower() if it is available. On OS X Leopard, the manpage for towlower(3) states that it "uses the current locale" though it doesn't say exactly *how* it uses it. This is the bug I'm trying to fix: http://scipy.org/scipy/numpy/ticket/643 http://dev.laptop.org/ticket/5559 [1] http://docs.python.org/lib/string-methods.html [2] http://www.python.org/dev/peps/pep-0100/ Thanks. -- 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 ganeshborse at gmail.com Thu Jan 3 06:37:08 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 3 Jan 2008 03:37:08 -0800 (PST) Subject: PyObject_CallObject code dump after calling 4 times Message-ID: I have a following C++ code which uses PyObject_CallObject to evaluate expressions dynamically. This code sets the input parameters for the function also dynamically. After calling this function 4 times (with these shown values), PyObject_CallObject causes application to crash in frame_dealloc. 1) Can some one please help me understand why is this crash happening in frame_dealloc & how to solve it? 2) Is there anything wrong I am doing about incrementing or decrementing the reference counts of the object passed to PyObject_CallObject? 3) Is it because of the big value (2299265.500000) I am trying to convert from double to float using PyFloat_FromDouble? //========================= code reduced for readability =============== switch(ndtyp){ case(INT_T): { printf("PyInt_FromLong val %d, var %s \n",inputVar.nionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); val = PyInt_FromLong(inputVar.nionum); break; } case(LONG_T): { printf("PyLong_FromLong val %ld, var %s \n",inputVar.lionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); val = PyLong_FromLong(inputVar.lionum); break; } case(FLOAT_T): { printf("PyFloat_FromDouble val %f, var %s \n",inputVar.fionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); val = PyFloat_FromDouble(inputVar.fionum); break; } case(DOUBLE_T): { printf("PyFloat_FromDouble val %f, var %s \n",inputVar.dionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); val = PyFloat_FromDouble(inputVar.dionum); break; } case(STRING_T): { printf("PyString_FromString val %s, var %s \n",inputVar.ioString,pEvalFunc->pExprVarsArray[nCtr].szVarName); val = PyString_FromString(inputVar.ioString); break; } default: printf("Unknown data type [%d] for %s\n",ndtyp,pEvalFunc- >pExprVarsArray[nCtr].szVarName); } if(!val){ ret = -1; printf("Failed to convert %d %s to PyObject\n",ndtyp,pEvalFunc- >pExprVarsArray[nCtr].szVarName); fflush(stdout); Py_XDECREF(pTuple); break; } PyTuple_SetItem(pTuple, nCtr, val); Py_XDECREF(val); } // all variables are set, call Python function Py_XINCREF(pTuple); PyObject *pResult = PyObject_CallObject(pEvalFunc- >pPyEvalFunction,pTuple); Py_XDECREF(pTuple); if(PyErr_Occurred()){ PyErr_Print(); } else { char* plevel = NULL; if(NULL != (plevel = PyString_AsString(pResult))){ ret = 0; sprintf(szEvalResult,"%s",plevel); } } Py_XDECREF(pResult); ================================================ Following crash (back trace) appears when I run this in GDB. The expression that was getting evaluated at this time is: def DangerousQuantity(size,maxvol,adv): if((size<1000 and (maxvol<10000) and (size<0.001*adv))): return "Dangerous" else: return "FAIL" //--------------- Crash dump information & values of variables passed to this expression Categorizing the order pyParserEvaluator evaluating category function DangerousTactic PyString_FromString val R, var aestactic PyLong_FromLong val 1139, var endtime PyLong_FromLong val 599, var starttime PyLong_FromLong val 23, var Aggr PyObject_CallObject done, do Py_XDECREF-pTuple Final result FAIL doing Py_XDECREF(pResult pyParserEvaluator evaluating category function MediumTactic PyString_FromString val R, var aestactic PyLong_FromLong val 1139, var endtime PyLong_FromLong val 599, var starttime PyLong_FromLong val 23, var Aggr PyObject_CallObject done, do Py_XDECREF-pTuple Final result FAIL doing Py_XDECREF(pResult pyParserEvaluator evaluating category function SafeTactic PyString_FromString val R, var aestactic PyLong_FromLong val 1139, var endtime PyLong_FromLong val 599, var starttime PyLong_FromLong val 23, var Aggr PyObject_CallObject done, do Py_XDECREF-pTuple Final result FAIL doing Py_XDECREF(pResult pyParserEvaluator evaluating category function DangerousQuantity PyLong_FromLong val 1, var size PyLong_FromLong val 0, var maxvol PyFloat_FromDouble val 2299265.500000, var adv Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 82336688 (LWP 27652)] 0xc0000000 in ?? () (gdb) where #0 0xc0000000 in ?? () #1 0x0285e59e in frame_dealloc (f=0xf5a2f68c) at Objects/ frameobject.c:106 #2 0x0281a4b1 in PyEval_EvalCodeEx (co=0xf5a69990, globals=0x2884120, locals=0x0, args=0x288bca0, argcount=3, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2609 #3 0x0285f551 in function_call (func=0xf5a694c4, arg=0xf5a47c3c, kw=0x0) at Objects/funcobject.c:476 #4 0x027e1e04 in PyObject_Call (func=0xf5a2003c, arg=0xf5a47c3c, kw=0x0) at Objects/abstract.c:1688 #5 0x0281b3eb in PyEval_CallObjectWithKeywords (func=0xf5a694c4, arg=0xf5a47c3c, kw=0x0) at Python/ceval.c:3058 #6 0x027e1de3 in PyObject_CallObject (o=0xf5a694c4, a=0xf5a47c3c) at Objects/abstract.c:1679 #7 0x027dd6fd in pyParserEvaluator::EvaluateCategory (this=0xf5a08df0, nCatLevelId=1, pOrdData=0x4e84f40, szEvalResult=0x4e84b70 "Dangerous") at pyEvaluator.cpp:342 #8 0x0070da71 in ParseEvalDriver::categorizeOrder (this=0xf5a0cf20, pcatRuleCache=0xfeff4e20, pOrdData=0x4e84f40, szLevelResult=0x9876180) at IEvaluatorInterface.cpp:102 #9 0x0807e812 in HandleCheck (szTopic=0x96d0439 "CE/REQ_3_EX/NEW", szReplyTopic=0x96d0639 "CE/RES_3_EX/njl36a-7003_401", pBuff=0x9875688 "4056029121", nBuffLen=195, pUsr=0xfeff4e18) at cerule.cpp:4859 #10 0x0032130d in CMiTssSub::OnRecvMsg (this=0xf5aaf0b0, pszTopic=0x96d0439 "CE/REQ_3_EX/NEW", pszReplyTopic=0x96d0639 "CE/RES_3_EX/njl36a-7003_401", pmsg=0x98754e8) at src/mitss.cpp:1810 #11 0x0031dc01 in CMiTss::OnRecvMsg (pszTopic=0x96d0438 "/CE/REQ_3_EX/ NEW", pszReplyTopic=0x96d0638 "/CE/RES_3_EX/njl36a-7003_401", pszMsg=0x98755e8 "?T\207\t?T\207\t", nMsgLen=4, pUsr=0xf5aaf0b0) at src/mitss.cpp:466 #12 0x0032296c in CMiHelper::_worker (arg=0x96cfc44) at mihelper.cpp: 390 #13 0x00339701 in _vmt_proc (thread_arg=0x96d0250) at vmt.c:347 #14 0x002afdec in start_thread () from /lib/tls/libpthread.so.0 #15 0x00603a2a in clone () from /lib/tls/libc.so.6 =================================================================== From phd at phd.pp.ru Thu Jan 10 07:32:38 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 10 Jan 2008 15:32:38 +0300 Subject: SQLObject 0.8.7 Message-ID: <20080110123238.GF3070@phd.pp.ru> Hello! I'm pleased to announce the 0.8.7 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.8.7 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.8.6 ---------------- * With PySQLite2 do not use encode()/decode() from PySQLite1 - always use base64 for BLOBs. * MySQLConnection doesn't convert query strings to unicode (but allows to pass unicode query strings if the user build ones). DB URI parameter sqlobject_encoding is no longer used. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From duncan.booth at invalid.invalid Tue Jan 15 04:08:06 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Jan 2008 09:08:06 GMT Subject: import from question References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> Message-ID: iu2 wrote: > file a3.py: >======== > from a1 import the_number > import a2 > ... > > Why doesn't it work in the first version of a3.py? > Think of 'import a2' as being the same as: a2 = __import__('a2') and 'from a1 import the_number' as roughly the same as: the_number = __import__('a1').the_number In other words think of them as assignments and it should all make sense. From thomas.troeger.ext at siemens.com Fri Jan 11 05:11:51 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Fri, 11 Jan 2008 11:11:51 +0100 Subject: Embedding python code into text document question. References: Message-ID: Thanks guys, you've helped me very much :) Cheers & happy new year! From arnodel at googlemail.com Sun Jan 27 20:51:28 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 27 Jan 2008 17:51:28 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> Message-ID: On Jan 27, 6:32?pm, "Diez B. Roggisch" wrote: > Wildemar Wildenburger schrieb: > > > Andr? wrote: > >> Personally, I like the idea you suggest, with the modification that I > >> would use "." instead of "@", as in > > >> class Server(object): > >> ? ? def __init__(self, .host, .port, .protocol, .bufsize, .timeout): > >> ? ? ? ? pass > > > I like :) > > > However, you can probably cook up a decorator for this (not certain, I'm > > not a decorator Guru), which is not that much worse. > > > Still, I'd support that syntax (and the general idea.). > > Just for the fun of it, I implemented a decorator: > > from functools import * > from inspect import * > > def autoassign(_init_): > ? ? ?@wraps(_init_) > ? ? ?def _autoassign(self, *args, **kwargs): > ? ? ? ? ?argnames, _, _, _ = getargspec(_init_) > ? ? ? ? ?for name, value in zip(argnames[1:], args): > ? ? ? ? ? ? ?setattr(self, name, value) > ? ? ? ? ?_init_(self, *args, **kwargs) > > ? ? ?return _autoassign Nice! I've got a slight variation without magic argument names: def autoassign(*names): def decorator(f): def decorated(self, *args, **kwargs): for name in names: setattr(self, name, kwargs.pop(name)) return f(self, *args, **kwargs) return decorated return decorator class Test(object): @autoassign('foo', 'bar') def __init__(self, baz): print 'baz =', baz t = Test(foo=1, bar=2, baz=6) # or Test(6, foo=1, bar=2) print t.foo print t.bar print t.baz -- Arnaud From Russ.Paielli at gmail.com Mon Jan 28 01:31:08 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 22:31:08 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> <8763xe8vzd.fsf@benfinney.id.au> Message-ID: On Jan 27, 7:33 pm, Ben Finney wrote: > "Russ P." writes: > > On Jan 27, 5:13 pm, Wildemar Wildenburger > > wrote: > > > class Server(object): > > > def __init__(self, self.host, self.port, > > > self.protocol, self.bufsize, self.timeout): > > > pass > > > > ? > > > That makes sense to me. > > Not to me. 'self' is a name that doesn't exist until *after* that > 'def' statement is completed; in any other statement, that would mean > 'self.foo' in the same statement would raise a NameError. > > Special-casing it for a function declaration complicates the language > for little gain: the rules of what is valid when become more > complicated. Special cases aren't special enough to break the rules. > > -- > \ "I took a course in speed waiting. Now I can wait an hour in | > `\ only ten minutes." -- Steven Wright | > _o__) | > Ben Finney OK, then how about a special function that could be called from inside the constructor (or anywhere else for that matter) to initialize a list of data members. For example, self.__set__(host, port, protocol, bufsize, timeout) This would be equivalent to self.host = host self.port = port # etc. I'm not sure if that is technically feasible, but it would cut down on repetition of names. From ryan at ryankaskel.com Wed Jan 23 17:47:37 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 14:47:37 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <7x8x2g8isi.fsf@ruckus.brouhaha.com> <13pfgdct573772d@corp.supernews.com> Message-ID: On Jan 23, 5:37 pm, Steven D'Aprano wrote: > On Wed, 23 Jan 2008 11:05:01 -0800, Paul Rubin wrote: > > ryan k writes: > >> Hello. I have a string like 'LNAME > >> PASTA ZONE'. I want to create a list of those words and > >> basically replace all the whitespace between them with one space so i > >> could just do lala.split(). Thank you! > > > import re > > s = 'LNAME PASTA ZONE' > > re.split('\s+', s) > > Please tell me you're making fun of the poor newbie and didn't mean to > seriously suggest using a regex merely to split on whitespace? > > >>> import timeit > >>> timeit.Timer("s.split()", "s = 'one two three four'").repeat() > > [1.4074358940124512, 1.3505148887634277, 1.3469438552856445]>>> timeit.Timer("re.split('\s+', s)", "import re;s = 'one two > > three four'").repeat() > [7.9205508232116699, 7.8833441734313965, 7.9301259517669678] > > -- > Steven The main topic is not an issue anymore. From duncan.booth at invalid.invalid Wed Jan 9 03:59:17 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jan 2008 08:59:17 GMT Subject: stupid/style/list question References: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Giampaolo Rodola' wrote: > >> To flush a list it is better doing "del mylist[:]" or "mylist = []"? >> Is there a preferred way? If yes, why? > > The latter creates a new list object, the former modifies an existing > list in place. > > The latter is shorter, reads better, and is probably a bit faster in > most cases. > > The former should be used when it's important to clear a specific list > object (e.g. if there are multiple references to the list). I tried to measure this with timeit, and it looks like the 'del' is actually quite a bit faster (which I find suprising). C:\Python25\Lib>timeit.py -s "lista=range(10000)" "mylist=list(lista)" 10000 loops, best of 3: 81.1 usec per loop C:\Python25\Lib>timeit.py -s "lista=range(10000)" "mylist=list(lista)" "del mylist[:]" 10000 loops, best of 3: 61.7 usec per loop C:\Python25\Lib>timeit.py -s "lista=range(10000)" "mylist=list(lista)" "mylist=[]" 10000 loops, best of 3: 80.9 usec per loop In the first test the local variable 'mylist' is simply allowed to go out of scope, so the list is destroyed as its reference count drops to 0. In the third case again the list is destroyed when no longer referenced, but an empty list is also created and destroyed. Evidently the empty list takes virtually no time to process compared with the long list. The second case clears the list before destroying it, and appears to be significantly faster. Increasing the list length by a factor of 10 and it becomes clear that not only is #2 always fastest, but #3 always comes in second. Only when the lists are quite short (e.g. 10 elements) does #1 win (and even at 10 elements #2 beats #3). Unless I've missed something, it looks like there may be an avoidable bottleneck in the list code: whatever the slice delete is doing should also be done by the deletion code (at least if the list is longer than some minimum length). The most obvious thing I can see is that list_dealloc: if (op->ob_item != NULL) { /* Do it backwards, for Christian Tismer. There's a simple test case where somehow this reduces thrashing when a *very* large list is created and immediately deleted. */ i = Py_Size(op); while (--i >= 0) { Py_XDECREF(op->ob_item[i]); } PyMem_FREE(op->ob_item); } would be better written as a copy of (or even call to) list_clear which picks up op->ob_item once instead of every time through the loop. From no_one at here Wed Jan 30 09:25:54 2008 From: no_one at here (Iain Mackay) Date: Wed, 30 Jan 2008 14:25:54 -0000 Subject: Sine Wave Curve Fit Question Message-ID: <7eOdnXVrB-fQFD3anZ2dnUVZ8hednZ2d@giganews.com> Python Folks I'm a newbie to Python and am looking for a library / function that can help me fit a 1D data vector to a sine wave. I know the frequency of the wave, so its really only phase and amplitude information I need. I can't find anything in the most widely known libraries (they seem to be strong on polynomial fitting, but not, apparently, on trig functions) and I wondered if any one here had recommendations? Something that implemented IEEE 1057 , or similar, would be perfect. TIA Iain From paul.hankin at gmail.com Thu Jan 3 08:40:25 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 3 Jan 2008 05:40:25 -0800 (PST) Subject: Treating a unicode string as latin-1 References: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Message-ID: <319bb5ab-8a38-4892-9832-2b171c81c4ec@s12g2000prg.googlegroups.com> On Jan 3, 1:31 pm, Simon Willison wrote: > How can I tell Python "I know this says it's a unicode string, but I > need you to treat it like a bytestring"? u'Bob\x92s Breakfast'.encode('latin-1') -- Paul Hankin From boblatest at yahoo.com Tue Jan 22 03:45:36 2008 From: boblatest at yahoo.com (Robert Latest) Date: 22 Jan 2008 08:45:36 GMT Subject: Question on sort() key function Message-ID: <5vlopgF1mv4ekU1@mid.dfncis.de> Hello, I have this class: class File: def __init__(self): self.name = '' self.path = '' self.date = 0 self.mod_date = 0 self.keywords = [] self.url = '' ...and after creating a list of File objects called flist, I'd like to sort it like thus: flist.sort(key=File.mod_date.toordinal) However, Python says: AttributeError: class File has no attribute 'mod_date' Well if you ask me, there are many things that may be said about my File class, but the absence of the attribute 'mod_date' ain't one of them. What do you think? And yes, this loop works fine: for f in flist: print f.mod_date.isoformat() (which IMO proves that all mod_date members are properly initialized as datetime objects). robert From siona at chiark.greenend.org.uk Fri Jan 4 12:01:28 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 04 Jan 2008 17:01:28 +0000 (GMT) Subject: python interfaces References: Message-ID: hyperboreean wrote: >Why doesn't python provide interfaces trough its standard library? Because they're pointless. Java interfaces are a hack around the complexities of multiple inheritence. Python does multiple inheritence Just Fine (give or take the subtleties of super()) so does not need them. Interfaces used purely with the idea of type safety provide precious little gain for the added clutter and inconvenience. Compare them to Java's requirement for explicit declaration of exceptions thrown in a method signature, if you will. -- \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 gnewsg at gmail.com Tue Jan 8 10:34:06 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 8 Jan 2008 07:34:06 -0800 (PST) Subject: stupid/style/list question Message-ID: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> I was wondering... To flush a list it is better doing "del mylist[:]" or "mylist = []"? Is there a preferred way? If yes, why? From bruno.desthuilliers at gmail.com Tue Jan 29 18:34:23 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 29 Jan 2008 15:34:23 -0800 (PST) Subject: Decision (if, else) routine is not working as intended with CGI module References: <9dc9f5d3-2392-48d6-8cb4-8b31c1ce4af9@e6g2000prf.googlegroups.com> Message-ID: <597dcd4e-8e0d-4df7-9f2f-6fcd8d3963bc@e6g2000prf.googlegroups.com> On 29 jan, 21:23, epsilon wrote: > All: > > I'm running into trouble figuring this one out. It seems that my > decision routine is not working as intended. Does anyone know why my > output continues to utilize the "else" portion of the routine. Probably because the test expression 'tag_form["fse00"] == ""' evals to false ? Hint: try printing out tag_form["fse00"] before the test, ie: (snip) > > #!/usr/bin/python > > import cgi > > print "Content-type: text/plain\n" > tag_form = cgi.FieldStorage(keep_blank_values=True) > print "tag_form[\"fse00\"] is actually: %s" % tag_form["fse00"] print "tag_form[\"fse00\"] == '' evals to: %s" % (tag_form["fse00"] == '') > if tag_form["fse00"] == "": > fse000 = {"fse00": "0"} > tag_form.update(fse000) > print "Printing fse000: ", tag_form["fse00"] > else: > print "Printing fse00: ", tag_form["fse00"] HTH From duncan.booth at invalid.invalid Thu Jan 10 07:03:39 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Jan 2008 12:03:39 GMT Subject: for loop without variable References: Message-ID: erik gartz wrote: > Hi. I'd like to be able to write a loop such as: > for i in range(10): > pass > but without the i variable. The reason for this is I'm using pylint > and it complains about the unused variable i. I can achieve the above > with more lines of code like: > i = 0 > while (i != 10): > i += 1 > Is there a concise way to accomplish this without adding extra lines > of codes? Thanks in advance for your help. Google for: pylint unused It pointed me at: > Question: > I've a function / method which is a callback where I do not have any > control on received argument, and pylint is complaining about unused > arguments. What can I do to avoid those warnings ? > > Answer: > prefix (ui) the callback's name by cb_, as in cb_onclick(...). By doing > so arguments usage won't be checked. Another solution is to use one of > the name defined in the "dummy-variables" configuration variable for > unused argument ("_" and "dummy" by default). http://www.iaeste.or.at/doc/python2.3-pylint/html/FAQ.html So it looks like you can use 'dummy' or add any other names you want to the configuration. From jpeng at block.duxieweb.com Tue Jan 22 00:37:43 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Tue, 22 Jan 2008 13:37:43 +0800 Subject: read files In-Reply-To: References: <7xbq7e5wxt.fsf@ruckus.brouhaha.com> Message-ID: <47958127.8050208@block.duxieweb.com> Gabriel Genellina ??: > En Tue, 22 Jan 2008 02:03:10 -0200, Paul Rubin > <"http://phr.cx"@NOSPAM.invalid> escribi?: > >> "J. Peng" writes: >>> print line, >> Do you really want all the lines crunched together like that? If not, >> leave off the comma. > > Remember that Python *keeps* the end-of-line charater at the end of each > line; if you leave out the comma, you'll print them doubly spaced. > Most languages (AFAIK) keep the newline character at the end of lines when reading from a file.But python's difference is its 'print' built-in function add a newline automatically for you. So without that ',' we will get double newlines. From steve at holdenweb.com Fri Jan 25 10:33:58 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 Jan 2008 10:33:58 -0500 Subject: read and readline hanging In-Reply-To: References: Message-ID: Olivier Lefevre wrote: > I am calling subprocess.Popen with > p = Popen(args, bufsize=-1, stdin=PIPE, stdout=PIPE, stderr=PIPE) > and after sending come command to the process, I try to read > from p.stdout but after a few calls I hang. What is the correct > way to do this, i.e., to read everything w/o getting stuck? I am > not familiar with all these low-level functions and their annoying > blocking behaviour. Note that I don't want to close the process > because I want to send more commands to it after that, read the > results, and so on and on. > While I realise it isn't easy to determine what's going on in a hung program, I might ask what you have tried already? I can think of at least two reasons why your program might hang: 1. The subprocess has stopped producing output. If you are only reading its standard output, are you sure that the subprocess is flushing its buffers so you can recognize it's time to provide more input? Are you simply failing to provide more input? 2. The subprocess has blocked because it has filled its stderr buffer and is waiting for something (i.e. your program) to read it. To eliminate the second possibility use stderr=STDOUT, which will then have both streams written to standard output. In general subprocess management is much tricker and subtler than most people expect when they first dive into it, and I suspect your problem is a manifestation of that fact. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From celoserpa at gmail.com Tue Jan 29 12:52:58 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Tue, 29 Jan 2008 15:52:58 -0200 Subject: Implementation of IBuyable or Interface? Message-ID: <1e5bcefd0801290952n9e3bffdre30cff32be5b2072@mail.gmail.com> Hello! It's more a design question than anything python specific. If anyone could help me, I would be grateful. If it's not the right place for this subject, please advise. I've got a IBuyable interface. The app can sell both Products and Services (Both "Buyables"). I'm not sure if Product and Service should also be represented as interfaces (inherited from IBuyable) or if they are actually directly implementations of IBuyable. What do you think? Thanks, Marcelo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From xng at xs4all.nl Sun Jan 13 20:21:28 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Mon, 14 Jan 2008 02:21:28 +0100 Subject: How to get user home directory on Windows In-Reply-To: References: Message-ID: <478ab8a1$0$20930$e4fe514c@dreader19.news.xs4all.nl> Giampaolo Rodola' wrote: > Hi all, > I'm trying to use the pywin32 extension to find out the user's home > directory but currently I didn't find a solution yet. > What I'd need to do is not getting the home directory of the currently > logged in user but something like: > >>>> get_homedir("frank") > "C:\home\users\frank" >>>> get_homedir("josh") > "C:\home\users\josh" > > Is there a way to do that? > I tried to search through the Pywin32 documentation with no luck. > In addition I'm not practiced with the Windows API at all. Well, windows, to my knowledge, uses the same base path for all profiles (this is not true for the My Documents folder which can differ). So what you could do is get the location from the ALLUSERPROFILE environment variable, go one folder higher and iterate through that. Ignoring the folders for the 'pseudo' users: 'All Users', 'Default User', 'LocalService' and 'NetworkService'. hth -- mph From sromero at gmail.com Wed Jan 9 09:48:35 2008 From: sromero at gmail.com (Santiago Romero) Date: Wed, 9 Jan 2008 06:48:35 -0800 (PST) Subject: How to get memory size/usage of python object Message-ID: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> Is there a way to check the REAL size in memory of a python object? Something like > print sizeof(mylist) or > print sizeof(myclass_object) or something like that ... Thanks. From deets at nospam.web.de Tue Jan 22 03:42:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 09:42:48 +0100 Subject: Calculate net transfer rate without dummy file In-Reply-To: References: Message-ID: <5vlokaF1nbp4iU1@mid.uni-berlin.de> whatazor schrieb: > Hi, > how can I calulate transfer rate to a host , without using a file ? > can ping module (written by Jeremy Hylton) be useful ? You can't measure without transmitting data. It's not only the network connection between the two hosts that is important, but also the sending and receiving processes, if they can cope with the amount of data or not and so forth. Diez From jpeng at block.duxieweb.com Wed Jan 30 20:51:45 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Thu, 31 Jan 2008 09:51:45 +0800 Subject: python modules collection Message-ID: <47A129B1.6000301@block.duxieweb.com> Hello, Is there a site for python,which collects most kinds of python modules? like CPAN for Perl. Sometime I want to use a module,like the time/date modules,don't know where I should search from. Sorry if I have repeated this question on the list. Thanks! From sromero at gmail.com Mon Jan 21 05:17:37 2008 From: sromero at gmail.com (Santiago Romero) Date: Mon, 21 Jan 2008 02:17:37 -0800 (PST) Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> <479451D9.3060207@block.duxieweb.com> Message-ID: Thanks all for the answers ... I'll use a tuple as you said :) Anyway, is interesting to know how to sort 2 lists when you dont want to use tuples, so thanks also to Peter :) > Then one have to split the list twice.Given the list is large,it's maybe > not good for performance.Is it a more effective split way? Well, I just use: rows = i.split(' ') a = rows[3] b = rows[5] X-D From mr.cerutti at gmail.com Thu Jan 17 10:23:05 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 17 Jan 2008 10:23:05 -0500 Subject: Is this a bug, or is it me? In-Reply-To: References: Message-ID: <51302a8c0801170723p35097f2avcb1b19964ef28dd9@mail.gmail.com> On Jan 17, 2008 10:05 AM, wrote: > Hello all, > For some reason, the following does not work : > > > class C: > TYPES = [None] > DICT = {} > for Type in TYPES: > DICT.update((E,Type) for E in [1]) > > >>> NameError: global name 'Type' is not defined > > > What do you think? Is this a bug? You cannot access a class's class variables in it's class-statement scope, since the name of the type is not bound until after the class statement is completed. Try: class C: TYPES = [None] DICT = {} for Type in C.TYPES: C.DICT.update((E, Type) for E in [1]) -- Neil Cerutti From steve at REMOVE-THIS-cybersource.com.au Thu Jan 31 10:50:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 31 Jan 2008 15:50:26 -0000 Subject: REALLY simple xml reader References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> <87tzkujeq6.fsf@benfinney.id.au> Message-ID: <13q3ri2707niqc6@corp.supernews.com> 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. "You know Bob, XML just isn't hostile enough to anyone silly enough to believe it's 'human-readable'. What can we do to make it more hostile?" "Well Fred, how about making the XML declaration completely optional, so you can leave it out and still be vald XML, but if you include it, you're not allowed to precede it with semantically neutral whitespace?" "I take my hat off to you." This is legal XML: """ Hello, world!""" and so is this: """ Hello, world!""" but not this: """ Hello, world!""" You can't get this sort of stuff except out of a committee. -- Steven From azam.farooq3 at gmail.com Sat Jan 12 06:59:46 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Sat, 12 Jan 2008 03:59:46 -0800 (PST) Subject: Looking for GSM Mobile Phone www.enmac.com.hk Message-ID: <7da8882a-aee7-486f-a8e3-81431fb4cbfc@q77g2000hsh.googlegroups.com> ENMAC Digital Quran Mobile includes Full Quran with Text and Translation in different languages, Tafaseer books, Ahadees Books, Universal Qibla Direction, Prayer Timing and much more at good price, please contact us for best prices and visit our website http://www.enmac.com.hk for more information. From mwm-keyword-python.b4bdba at mired.org Sat Jan 12 15:47:05 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Sat, 12 Jan 2008 15:47:05 -0500 Subject: super, decorators and gettattribute In-Reply-To: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> Message-ID: <20080112154705.347fa23e@bhuda.mired.org> On Sat, 12 Jan 2008 10:45:25 -0800 (PST) Richard Szopa wrote: > Hello all, > > I am playing around w/ Python's object system and decorators and I > decided to write (as an exercise) a decorator that (if applied to a > method) would call the superclass' method of the same name before > doing anything (initially I wanted to do something like CLOS > [1] :before and :end methods, but that turned out to be too > difficult). > > However, I cannot get it right (specially, get rid of the eval). I > suspect that I may be misunderstanding something happening between > super objects and __getattribute__ methods. > > Here's my code: > > def endmethod(fun): > """Decorator to call a superclass' fun first. > > If the classes child and parent are defined as below, it should > work like: > > >>> x = child() > >>> x.foo() > I am parent's foo > I am child's foo. > """ > name = fun.__name__ > def decorated(self, *args, **kwargs): > try: > super_object = super(self.__class__, self) There's an apparently common bug here: you don't want to pass super self.__class__, but the class that the method is bound to. The two aren't the same, as an instance of a subclass will have the subclass as self.__class__, and not the current class. So super will return the current class or a subclass of it, meaning (since you invoked this method from self) you'll wind up invoking this method recursively. All of which means your decorator is probably going to have to take the class as an argument. > # now I want to achieve something equivalent to calling > # parent.foo(*args, **kwargs) > # if I wanted to limit it only to this example > > # this doesn't work: in the example, it calls child's foo, > # entering in an eternal loop (instead of calling parent's > # foo, as I would expect). > > # super_object.__getattribute__(name)(*args, **kwargs) > > # this does work, but I feel it's ugly > eval('super_object.%s(*args, **kwargs)' % name) > except AttributeError: > pass # if parent doesn't implement fun, we don't care > # about it > return fun(self, *args, **kwargs) # hopefully none > > decorated.__name__ = name > return decorated > > > class parent(object): > def foo(self): > print 'I am parent\'s foo' > > class child(parent): > @endmethod > def foo(self): > print "I am foo\'s foo." > > if __name__=='__main__': > x = child() > x.foo() > > Can anybody tell me how to call a superclass method knowing its name? The same way you call any object's methods if you know it's name": getattr(super_object, name)(*args, **kwargs) The code seems to work the way you want: >>> x.foo() I am parent's foo I am foo's foo. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From halcyon1981 at gmail.com Fri Jan 25 19:46:59 2008 From: halcyon1981 at gmail.com (David Erickson) Date: Fri, 25 Jan 2008 16:46:59 -0800 (PST) Subject: Email module, how to add header to the top of an email? References: <97c04812-3b66-4d84-9e92-21de72a3ca56@c23g2000hsa.googlegroups.com> <088eeaff-8251-49a4-9202-a9481f5e8aaa@x69g2000hsx.googlegroups.com> Message-ID: <476b67e8-ce42-4357-ba2a-90ed757e6c6a@y5g2000hsf.googlegroups.com> On Jan 25, 5:04 am, "Karlheinz Klingbeil" wrote: > Am 25.01.2008, 06:21 Uhr, schrieb David Erickson : > > > Bottom of the headers... but I am looking to insert at the top, and re- > > ordering/inserting does matter depending on what type of header you > > are, received headers for example must be inserted at the top of the > > header list so you can watch the progression of the email. I was > > unable to find a clean way to do this via the API which seems very > > strange to me.. but perhaps I am just missing something? > > I think your are really missing something. First, Email-headers are > unordered > and every relay can, and probably will, rearrange them, add or delete > headers. > You therefore most definitely should not add any headers which are > position-dependent. > If you want to track mails somehow, add headers with timestamps. > This way you can watch the progression of an email without being > dependend on "sorted" headerlines. This is incorrect, quoting directly from RFC 2822: It is important to note that the header fields are not guaranteed to be in a particular order. They may appear in any order, and they have been known to be reordered occasionally when transported over the Internet. However, for the purposes of this standard, header fields SHOULD NOT be reordered when a message is transported or transformed. More importantly, the trace header fields and resent header fields MUST NOT be reordered, and SHOULD be kept in blocks prepended to the message. See sections 3.6.6 and 3.6.7 for more information. Trace header fields are not to be ordered, and should be prepended when added to a message. Now that said I am not trying to track anything, I simply want to prepend my additional headers onto the top of the email, and seem to be unable to do that via the API, which I think ought to be possible. If for example I was writing some kind of an SMTP server with Python and needed to add said trace headers they would need to be prepended, and currently cannot be (without doing it by hand). -David From Russ.Paielli at gmail.com Thu Jan 24 13:57:15 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 24 Jan 2008 10:57:15 -0800 (PST) Subject: Linux Journal Survey References: <1666950d-e9a5-4b7c-a614-5bba90e5b4ca@y5g2000hsf.googlegroups.com> Message-ID: <56eb736f-5ba3-417a-a4c1-3a310a67c3d3@s12g2000prg.googlegroups.com> 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. From gagsl-py2 at yahoo.com.ar Wed Jan 30 00:58:35 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jan 2008 21:58:35 -0800 (PST) Subject: Replacing call to PyObject_CallObject with PyEval_CallFunction References: <5a99ab95-e225-4085-bce4-ea31da557d6d@j78g2000hsd.googlegroups.com> Message-ID: <740a5e65-64c3-45dc-95bf-691978fb4290@f47g2000hsd.googlegroups.com> On 30 ene, 01:58, grbgooglefan wrote: > How do I pass the elements populated in struct variables of this > vector dynamically to PyEval_CallFunction, in the fashion somewhat > like below? > PyEval_CallFunction(obj, "iii", vector[0].ioparam->nionum,vector[1].ioparam->nionum,vector[2].ioparam->nionum); > > PyEval_CallFunction(obj, "di", vector[0].ioparam->fionum,vector[1].ioparam->nionum); > > PyEval_CallFunction(obj, "diiisis", vector[0].ioparam->fionum,vector[1].ioparam->nionum,vector[2].ioparam- > >nionum,vector[3].ioparam->nionum,vector[4].ioparam- > >ioString,vector[5].ioparam->nionum,vector[6].ioparam->ioString); I didn't know of PyEval_CallFunction until now, but aparently the lines above are OK. Can't you use it that way? What's your problem? -- Gabriel Genellina From dima.hristov at gmail.com Mon Jan 21 06:57:12 2008 From: dima.hristov at gmail.com (DHR) Date: Mon, 21 Jan 2008 03:57:12 -0800 (PST) Subject: How to use py2exe ... References: Message-ID: Here is how I am creating my win32 exe with py2exe: 1. create a setup.py file with the following: from distutils.core import setup import py2exe #setup(console=['main_script.py']) setup(windows=['main_script.py'] ) 2. run the following command from console: 'python setup.py py2exe' Hope this helps. On Jan 21, 9:45 am, Santiago Romero wrote: > Hi... > > I'm a Linux user, and I would like some windows-friends to test a > game I'm writing with python+pygame without they needing to install > python, pygame, and so on. > > I've heard about py2exe and pygame2exe, but I'm not sure on how to > use them to create: > > a.- standalone exe files with a single .py program. > Example: myprogram.py > > or > > b.- exe files containing all my source code + data directories (png > files, data files, and so). > Example: main.py, doc/README, src/*.py and data/* > > The problem is I'm not sure on how to use py2exe and pygame2exe to > build the executables... > > And finally, a question: if I want to provide source code > separately ... can I include .pyc files instead of .py files? From yann.le_boulanger at u-paris10.fr Fri Jan 25 11:27:17 2008 From: yann.le_boulanger at u-paris10.fr (Yann Leboulanger) Date: Fri, 25 Jan 2008 17:27:17 +0100 Subject: Icon in a gtk.Entry In-Reply-To: References: Message-ID: <479a0dd4$0$1229$426a74cc@news.free.fr> johnthawk at excite.com wrote: > > Hello all, > > I have two thing I wish to accomplish, First, put an icon in a gtk.Entry as in many search boxes. Second put a gtk.Checkbox in a gtk.ComboboxEntry. On the later I thought I could get a handle to the Combobox tree and then add a column and then column span column 1 back into column 0 , thus a gtk.ToggelRender would be visible in column 0. But I had no luck getting a handle to the Combobox tree. For the first one, look at libsexy: http://www.chipx86.com/wiki/Libsexy For using a ToggleRenderer, look at pygtk tuto: http://pygtk.org/pygtk2tutorial/sec-CellRenderers.html#sec-ActivatableToggleCells -- Yann From mani.sabri at gmail.com Mon Jan 28 13:27:16 2008 From: mani.sabri at gmail.com (mani) Date: Mon, 28 Jan 2008 10:27:16 -0800 (PST) Subject: Embeding python with mingw on win32 and python 2.4.4 Message-ID: <43e347ca-1c61-4527-aa47-14f93cef3179@y5g2000hsf.googlegroups.com> Hi I'm bringing up an old story once more! I'm on win32 (winxp sp2) python 2.4.4. mingw gcc version is 3.4.5. msys is in c:\msys. mingw is in c:\mingw and python is in c:\pyton24. there is also python24.lib and libpython24.a in c:\python24\libs. when I try to compile this sample code [1] from with command [2] in msys shell I get the results [3]. this subject was discussed a few times over these years and I tried everything in the posts and forums that I found and google could translate with no success. I realy need your suggestion! Regards, Mani [1] Sample code: #include int main(int argc, char *argv[]) { Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } [2] Command: $ g++ -I/c/python24/include -I/c/MinGW/include -L/c/python24/libs -L/c/ mingw/lib -lpython24 -shared -mwin32 -o p1 p1.o [3] Results: p1.o:p1.cpp:(.text+0x2b): undefined reference to `_imp__Py_Initialize' p1.o:p1.cpp:(.text+0x39): undefined reference to `_imp__PyRun_SimpleString' p1.o:p1.cpp:(.text+0x40): undefined reference to `_imp__Py_Finalize' collect2: ld returned 1 exit status From domma at procoders.net Fri Jan 4 09:54:21 2008 From: domma at procoders.net (Achim Domma) Date: Fri, 4 Jan 2008 06:54:21 -0800 (PST) Subject: Details about pythons set implementation Message-ID: Hi, I'm interested in details about how sets are implemented in python. They seem to be quite fast and I found some remarks who state, that the implementation is highly optimized. I need to implemented sets in C/C++ and need a starting point on how to do it right. Could somebody give me a starting point? regards, Achim From mal at egenix.com Fri Jan 4 11:56:05 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 04 Jan 2008 17:56:05 +0100 Subject: Memory Leaks and Heapy In-Reply-To: <7f692fec0801040823q14d16429y370ffceaf046a6f3@mail.gmail.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> <477E5A73.9070400@egenix.com> <7f692fec0801040823q14d16429y370ffceaf046a6f3@mail.gmail.com> Message-ID: <477E6525.3010805@egenix.com> On 2008-01-04 17:23, Yaakov Nemoy wrote: > On Jan 4, 2008 11:10 AM, M.-A. Lemburg wrote: >> If you're using lots of small objects, you may be running into a >> problem with the Python memory allocation mechanism, pymalloc. It used >> to not return memory to the system. In Python 2.5 (IIRC, could be >> 2.6) this was changed to at least return completely empty blocks >> back to the OS. For details, see Objects/obmalloc.c > > The most common answer I heard was possible fragmentation, meaning > there are no or few completely empty blocks to be found. If there are > no 'leaks' in the VM, then it's probably related to how memory is > freed. You can check for this by using a special build of Python with disabled PyMalloc - Python will then use the standard OS malloc for all object allocations. It still uses free lists for a couple of object types, but those won't cause major leak problems. Alternatively, try to tune the PyMalloc implementation (see objmalloc.c), e.g. enable WITH_MEMORY_LIMITS. >> This could be caused by interned strings which are kept in a special >> pool dictionary to speed up string comparisons. > > That's quite possible, a majority of the code is a huge number of SQL > connections and code. All string based. Note that strings are normally *not* interned. However, you can write code in a way that causes Python to intern more strings than needed, e.g. if you dynamically compile code in your app, which then causes all identifiers in the compiled code to be interned. The interned dictionary is not exposed in Python, but you can access it using a debugger via Objects/stringobject.c:interned. >> However, the first thing to check is whether any of the C extension >> modules you are using is leaking memory. Python itself is usually >> well tested for memory leaks, but this is less so for C extension >> modules and it's easy to mis a few Py_DECREFs (decrementing a >> Python object's reference count), causing objects to live forever. > > I'll try to track it down, but AFAIK, most of the code is python, and > the only C code there would be is the MySQL container. How can I > debug the VM though, to determine where the leak lies? Heapy wasn't > able to tell me this, and this is the important aspect. I'm wondering > how most people go about determining the causes of leaks like these, > so I can provide some accurate bug information. Building Python in debug mode provides some help with this. You can then detect whether objects get properly freed. Doing explicit garbage collection via the gc module also helps in narrowing down the leak. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jan 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From python at rcn.com Wed Jan 9 15:56:46 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 9 Jan 2008 12:56:46 -0800 (PST) Subject: Structure of packages References: Message-ID: <49bc33e0-7980-41f1-aef6-788c54d53df6@e10g2000prf.googlegroups.com> [Ben Fisher] > I am trying to learn the best way to do intra-package references. IMO, the email package is a stellar example of best practices using packages. > I have layered the dependencies so that a depends on b, >b depends on c, and c depends on d. For the most part, I think packages tend to be over-used and can create more problems than they solve. They were added as tool for managing *very* large code bases and for helping resolve namespace collisions between tools with similiar APIs. Your layering application may also be a good use but I haven't seen packages used that way before. Raymond From rw at smsnet.pl Thu Jan 17 14:46:58 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 17 Jan 2008 20:46:58 +0100 Subject: examples of logger using smtp References: Message-ID: <87wsq85j65.fsf@merkury.smsnet.pl> DwBear75 writes: > I am hoping to find some simple examples of how to create a logger > instance using smtphandler. I don't want to create a separate ini > file. I just want to sent the smtphost, from, to right in the code > when I instantiate the logger. I can't seem to find simple code on how > to do this. Any pointers ? If you need to use smtp authentication there is a small problem with `SMTPHandler`. Actually, you need to subclass `SMTPHandler` and override `emit` method, e.g.: from logging import getLogger, Formatter, DEBUG from logging.handlers import SMTPHandler class SMTPAuthHandler(SMTPHandler): def __init__(self, mailhost, fromaddr, toaddrs, subject, user=None, password=None): SMTPHandler.__init__(self, mailhost, fromaddr, toaddrs, subject) self.user = user self.password= password def emit(self, record): import smtplib from email.Utils import formatdate smtp = smtplib.SMTP(self.mailhost, smtplib.SMTP_PORT) if self.user and self.password: smtp.login(self.user, self.password) msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, ','.join(self.toaddrs), self.getSubject(record), formatdate(), msg) smtp.sendmail(self.fromaddr, self.toaddrs, msg) smtp.quit() def smtp_logger(level, mailhost, fromaddr, toaddr, subject, user=None, password=None): logger = getLogger('AppName') logger.setLevel(level) hdlr = SMTPAuthHandler(mailhost, fromaddr, toaddr, subject, user, password) fmt = Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s', '%Y-%m-%d %H:%M:%S') hdlr.setFormatter(fmt) logger.addHandler(hdlr) hdlr.setLevel(level) return logger logger = smtp_logger(DEBUG, 'mailhost', 'fromaddr', 'toaddr', 'DEBUG: AppName', 'user', 'password') logger.debug('some message') HTH, Rob From steven.bethard at gmail.com Wed Jan 23 00:53:20 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 22 Jan 2008 22:53:20 -0700 Subject: subprocess and & (ampersand) Message-ID: I'm having trouble using the subprocess module on Windows when my command line includes special characters like "&" (ampersand):: >>> command = 'lynx.bat', '-dump', 'http://www.example.com/?x=1&y=2' >>> kwargs = dict(stdin=subprocess.PIPE, ... stdout=subprocess.PIPE, ... stderr=subprocess.PIPE) >>> proc = subprocess.Popen(command, **kwargs) >>> proc.stderr.read() "'y' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n" As you can see, Windows is interpreting that "&" as separating two commands, instead of being part of the single argument as I intend it to be above. Is there any workaround for this? How do I get "&" treated like a regular character using the subprocess module? Thanks, STeVe From deets at nospam.web.de Thu Jan 3 08:50:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 14:50:27 +0100 Subject: reassign to builtin possible !? References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> Message-ID: <5u47h3F1gbcngU1@mid.uni-berlin.de> Bernhard Merkle wrote: > On Jan 3, 2:07 pm, "Diez B. Roggisch" wrote: >> This hal always been possible. But it's not reassigning, it's shadowing - >> which is a totally different beast. Shadowing builtins is bad style, but >> lokal to your context. Which can get nasty of course, if you do the above >> on e.g. module level. >> >> But you can't alter the values for True/False globally with this. > > Are you sure ? what about the following example ? > Is this also shadowing ? > > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import __builtin__ >>>> __builtin__.True = False >>>> __builtin__.True > False >>>> True > False I'm not entirely sure what happens there, but that seems to only work in the interactive prompt. --------- test.py ------------ print True if __builtins__.True == 10: print "I'm reassigned globally" --------- test.py ------------- Then, in the interpreter do: droggisch at ganesha:/tmp$ 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. Welcome to rlcompleter2 0.96 for nice experiences hit multiple times >>> __builtins__.True = 10 >>> import test 10 Traceback (most recent call last): File "", line 1, in File "test.py", line 5, in if __builtins__.True == 10: AttributeError: 'dict' object has no attribute 'True' >>> Diez From castironpi at gmail.com Fri Jan 11 18:43:36 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 11 Jan 2008 15:43:36 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> Message-ID: <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> On Jan 11, 5:26 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > This function just wants X out of the list. It doesn't matter if this > > happens before, during, or after something else; so long as it happens. > > 2. Associate a lock with the list. Anything wanting to access the > list should acquire the lock, do its stuff, then release the lock. > This gets confusing after a while. To keep it generic, how about: listA.op( insert, x ) listA.op( remove, x ) From theCodeMaiden at gmail.com Thu Jan 3 12:50:08 2008 From: theCodeMaiden at gmail.com (Adeola Bannis) Date: Thu, 3 Jan 2008 09:50:08 -0800 (PST) Subject: PyOpenGL, wxPython weird behaviour Message-ID: <71ae5a6b-31e9-41e9-a39e-919138dc4a03@l6g2000prm.googlegroups.com> Hi everyone, I'm doing a project using wxPython and pyopengl, and I seem to have a problem rendering textures. This is code that worked before my hard drive had a meltdown, but not since I re-installed everything. I've determined the problem is in the OpenGL part of my program. I do some calculations to generate a 2D numpy array that holds the image data, and pylab.imshow() shows me the image as it is meant to be. I used the same algorithm in Octave and MATLAB, and all are giving me the right picture. However, using pyOpenGL and the numpyhandler functions (http://cours- info.iut-bm.univ-fcomte.fr/docs/python/OpenGL/ OpenGL.arrays.numpymodule.NumpyHandler-class.html) doesn't seem to work. I get a garbled screen pocked with black pixels. I am including my openGL code below. What am I doing wrong? And yes, I did make the dtype of my array 'float32'. -------code snippets------ import wx from wx.glcanvas import GLCanvas from OpenGL.GLU import * from OpenGL.GL import * from OpenGL.arrays.numpymodule import NumpyHandler PC = 1 RI = 0 class myGLCanvas(GLCanvas): def __init__(self, parent): GLCanvas.__init__(self, parent,-1) wx.EVT_PAINT(self, self.OnPaint) self.init = 0 self.mode = -1 # making a texture for the range image self.texture = glGenTextures(1) # making a spot for the point cloud points self.cloud = None return def OnPaint(self,event): dc = wx.PaintDC(self) self.SetCurrent() if not self.init: self.InitGL() self.init = 1 self.OnDraw() return def OnDraw(self): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if self.mode == RI: self.drawRange() elif self.mode == PC: self.drawCloud() def InitGL(self): glClearColor(0.0, 0.0, 0.0, 0.0); glClearDepth(1.0) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) glClear(GL_COLOR_BUFFER_BIT) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glPixelStorei(GL_PACK_ALIGNMENT, 1) #NTSC colour scales... glPixelTransferf(GL_RED_SCALE, 0.299); glPixelTransferf(GL_GREEN_SCALE, 0.587); glPixelTransferf(GL_BLUE_SCALE, 0.114); glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0,1.0,0,1.0,-1.0,1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() return def rangeImage(self, image): glBindTexture(GL_TEXTURE_2D, self.texture) glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # flatten it into a list so the OpenGL calls work n = NumpyHandler() fI = image.flatten() flatImage = n.dataPointer(n.contiguous(fI)) print n.contiguous(fI) gluBuild2DMipmaps(GL_TEXTURE_2D, 1, image.shape[0]+1, image.shape[1]+1, GL_LUMINANCE, GL_FLOAT, flatImage) self.mode = RI self.OnDraw() def drawRange(self): ''' Controls the actual drawing of the range image''' glMatrixMode(GL_MODELVIEW) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColor3f(1.0,1.0,1.0) glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.texture) glBegin(GL_TRIANGLE_FAN) glTexCoord2d(1,1); glVertex3f(0.0, 0.0, 0.0) glTexCoord2d(1,0); glVertex3f(0.0, 1.0, 0.0) glTexCoord2d(0,0); glVertex3f(1.0, 1.0, 0.0) glTexCoord2d(0,1); glVertex3f(1.0, 0.0, 0.0) glEnd() self.SwapBuffers() --------end snippet----------- From scrdhrt at gmail.com Thu Jan 17 08:38:38 2008 From: scrdhrt at gmail.com (Sacred Heart) Date: Thu, 17 Jan 2008 05:38:38 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: On Jan 17, 1:35 pm, cokofree... at gmail.com wrote: > for i in zip(array1, array2): > print i > > Although I take it you meant four d, the issue with this method is > that once you hit the end of one array the rest of the other one is > ignored. Yes, small typo there. Okey, so if my array1 is has 4 elements, and array2 has 6, it won't loop trough the last 2 in array2? How do I make it do that? R, SH From python.list at tim.thechases.com Wed Jan 9 18:00:53 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 09 Jan 2008 17:00:53 -0600 Subject: for loop without variable In-Reply-To: References: Message-ID: <47855225.90605@tim.thechases.com> >> Hi. I'd like to be able to write a loop such as: >> for i in range(10): >> pass >> but without the i variable. The reason for this is I'm using pylint >> and it complains about the unused variable i. > > if a computer tells you to do something stupid, it's often better to > find a way to tell the computer to shut up than to actually do some- > thing stupid. > > (pylint's online documentation is remarkably unreadable, so I cannot > help you with the details, but surely there's a way to disable that > test, either globally, or for a specific region of code?). That documentation on PyLint[1] is atrocious! From my reading of it, at the beginning of your file, you put a comment something like # pylint: disable-msg=W0612 which should disable that particular message. Totally untested. I don't know if PyLint is smart enough, but if you don't use "i", you might use the common "throwaway" variable of "_": for _ in xrange(10): do_something() in which case it _might_ recognize that it's a throwaway variable and not warn you about it. At least that would be nice of it. But given the abusive nature of the documenation, I'm not sure that's the case ;) -tkc [1]http://www.logilab.org/card/pylintfeatures From guptaabhishek1983 at gmail.com Fri Jan 11 03:04:00 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Fri, 11 Jan 2008 00:04:00 -0800 (PST) Subject: Why Python.exe is breaking with memory dump?? Message-ID: Hi group i have created a simple .pyd using which i m able call C function from python code. There are around 6 such functions. 4 of them work great. But when i try to run other two python's exe breaks giving memory dump. Any pros or cons on what led to such a situation.. Is it a problem in my c code?? Thank you. From lutz.horn at fastmail.fm Wed Jan 16 09:39:26 2008 From: lutz.horn at fastmail.fm (Lutz Horn) Date: Wed, 16 Jan 2008 15:39:26 +0100 Subject: Python help for a C++ programmer In-Reply-To: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> References: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> Message-ID: <1200494366.9118.1231561231@webmail.messagingengine.com> Hi, On Wed, 16 Jan 2008 06:23:10 -0800 (PST), "mlimber" said: > I'm writing a text processing program to process some survey results. > I'm familiar with C++ and could write it in that, but I thought I'd > try out Python. I've got a handle on the file I/O and regular > expression processing, but I'm wondering about building my array of > classes (I'd probably use a struct in C++ since there are no methods, > just data). You could try something like this. #!/usr/bin/env python class Response: def __init__(self, name, age, iData, sData): self.name = name self.age = age self.iData = iData self.sData = sData def sourceOfResponses(): return [["you", 42, [1, 2, 3], ["foo", "bar", "baz"]], ["me", 23, [1, 2, 3], ["ham", "spam", "eggs"]]] if __name__ == "__main__": responses = [] for input in sourceOfResponses: response = Response(input.name, input.age, input.iData, input.sData) reponses.append(response) Lutz -- GnuPG Key: 1024D/6EBDA359 1999-09-20 Key fingerprint = 438D 31FC 9300 CED0 1CDE A19D CD0F 9CA2 6EBD A359 http://dev-random.dnsalias.net/0x6EBDA35.asc http://pgp.cs.uu.nl/stats/6EBDA359.html From tim.peters at gmail.com Sun Jan 20 20:44:06 2008 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 20 Jan 2008 17:44:06 -0800 (PST) Subject: TopSort in Python? References: <0000161d@bossar.com.pl> Message-ID: <81cb9a15-4f34-4cba-9542-adaa82ca3ec6@c4g2000hsg.googlegroups.com> [startec... at gmail.com] > Thanks for the topsort code. It would be useful in a project I'm > working on. Can I use the code for free under public domain? Thanks! If I ran the world, everything I posted to a public place would be public domain. Alas, the last lawyer who typed at me about this insisted that an individual in the USA cannot meaningfully disclaim copyright, so perhaps you're required to pay me millions of dollars instead ;-) To keep him happy and you solvent, I hereby license the code under the MIT license: http://www.opensource.org/licenses/mit-license.php Copyright (c) 1999-2008 Tim Peters Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. From workitharder at gmail.com Sat Jan 5 17:09:09 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 5 Jan 2008 14:09:09 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> <13ntbv51tqcm7c@corp.supernews.com> Message-ID: <83b78deb-b7c4-4fa3-b9ad-1a40be4f9231@n22g2000prh.googlegroups.com> On Jan 4, 2:15 pm, Steven D'Aprano wrote: > On Fri, 04 Jan 2008 09:29:50 -0800, bukzor wrote: > > Why cant you implement < for complex numbers? Maybe I'm being naive, but > > isn't this the normal definition? > > a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) > > No, it is not. Ordered comparisons are not defined for complex numbers. > Which is bigger, 4+2j or 2+4j? > > > How do you implement a set without sorting? > > With a hash table. > > Or if you are willing to limit yourself to sets of small integers, you > can implement it using bit flipping. E.g. 5 is an element of the set if > bit 5 is on. > > > Are you expecting better than O(log n)? > > Sure. > > -- > Steven Good Answers! From peanut.sam at googlemail.com Sat Jan 5 18:54:55 2008 From: peanut.sam at googlemail.com (Sam Garson) Date: Sat, 5 Jan 2008 23:54:55 +0000 Subject: Taskbar/System Tray Message-ID: <4e1ac4910801051554n5927c45ejb62d77b48eedd645@mail.gmail.com> hello group, Using tkinter, is there any way to have the program not showing on the taskbar, and even better showin in the system tray? I realise tkinter does not have that much OS specific stuff but maybe there is a way? Thanks, Sam -- I intend to live forever - so far, so good. SaM -------------- next part -------------- An HTML attachment was scrubbed... URL: From jr9445 at ATT.COM Thu Jan 17 11:44:51 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 17 Jan 2008 10:44:51 -0600 Subject: Creating unique combinations from lists In-Reply-To: <478F7471.9080909@tim.thechases.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> <478E6BA7.5030509@tim.thechases.com> <478F7471.9080909@tim.thechases.com> Message-ID: > -----Original Message----- > From: Tim Chase [mailto:python.list at tim.thechases.com] > Sent: Thursday, January 17, 2008 10:30 AM > To: Reedick, Andrew > Cc: breal; python-list at python.org; martin at v.loewis.de > Subject: Re: Creating unique combinations from lists > > Yick...a nice demo of the power of eval, but definitely filed > under the "Hack" heading :) You hurt my feeling. *sniffle* Given how late python compiles/evaluates code blocks, I'm thinking that eval() is less hack and more paradigm ..err.. pythonic. ;-) > > I think Martin's solution/recommendation[1] is better > (readability-wise, and "less apt to shoot yourself in the foot > with some bogus generated code"-wise) if you don't mind building > the whole result set in memory which your eval() solution does as > well. I'm curious to see the timing results from adding that > recipe to your test-suite. Cookbook is relatively decent. 5 deep, 100 iterations: list comprehension: 11.02 nested for loop : 13.16 +19% cookbook : 18.85 +71% recursion : 69.00 +526% eval : 13.30 +20% > > The advantage to the recursive-generator solution is that it > should really only keep your initial input and the current result > in memory as the generated item, so you can reasonably iterate > over millions of rows without having gigs of RAM. I don't > believe the recursion will go deeper than the number of lists > you're iterating over, so the stack shouldn't explode. Excellent point about memory usage. However, since we're dealing with exponential algorithms, will you run out of time or memory first? Here's the test code if anyone wants to play with it. It will let you specify the levels of nested loops and display the generated code. Usage: foo.py num_nested_loops num_iterations import sys from timeit import Timer def CreateComprehension(lists): out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in range(len(lists))]) return '[ ' + out + comp + ' ]' num_loops = int(sys.argv[1]) iterations = int(sys.argv[2]) results = [] lists = '''lists = [] for i in range(%d): lists.append(range(i, i+10)) ''' % (num_loops) print "################################################" print lists print print "################################################" code = 'r = ' + CreateComprehension(range(num_loops)) t = Timer(code, lists) results.append("list comprehension: %4.2f" % t.timeit(iterations)) print results[-1:][0] print code print print "################################################" code = 'r = []\n' for i in range(num_loops): code += " " * i code += "for v%d in lists[%d]:\n" % (i, i) code += ' ' * num_loops code += 'r.append([' code += ','.join( ['v%d' % i for i in range(num_loops)]) code += '])' t = Timer(code, lists) results.append("nested for loop : %4.2f" % t.timeit(iterations)) print results[-1:][0] print code print print "################################################" code = '''r=[[]] for x in lists: t = [] for y in x: for i in r: t.append(i+[y]) r = t ''' t = Timer(code, lists) results.append("cookbook : %4.2f" % t.timeit(iterations)) print results[-1:][0] print code print print "################################################" code = ''' r = [] def iterall(*iterables): if iterables: for head in iterables[0]: for remainder in iterall(*iterables[1:]): yield [head] + remainder else: yield [] for thing in iterall(%s): r.append(thing) ''' % ( ','.join([ 'lists[%d]' % i for i in range(num_loops) ]) ) t = Timer(code, lists) results.append("recursion : %4.2f" % t.timeit(iterations)) print results[-1:][0] print code print print "################################################" code = ''' def gen(lists): out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in range(len(lists))]) return eval('[ ' + out + comp + ' ]') gen(lists) ''' t = Timer(code, lists) results.append("eval : %4.2f" % t.timeit(iterations)) print results[-1:][0] print code print print '\n'.join(results) ***** 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. GA622 From martin at v.loewis.de Sun Jan 13 15:43:28 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 13 Jan 2008 21:43:28 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801132048.08966.donn.ingle@gmail.com> References: <200801131928.54459.donn.ingle@gmail.com> <478A4F8A.5010108@v.loewis.de> <200801132048.08966.donn.ingle@gmail.com> Message-ID: <478A77F0.4000502@v.loewis.de> > Now, I want to open that file from Python, and I create a path with > os.path.join() and an os.listdir() which results in this byte string: > paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] > > I *think* that the situation is impossible because the system cannot resolve > the correct filename (due the locale being ANSI and the filename being other) > but I am not 100% sure. Not at all. The string you pass is a *byte* string, not a character string. You may think that the first letter of it is an aitch, but that's just your interpretation - it really is the byte 104. The operating system does not interpret the file names as characters at all, with the exception of treating byte 47 as the path separator (typically interpreted by people as "slash"). Your locale becomes only relevant when displaying file names, and having to chose what glyphs to use. > So, I have been trying combinations of open: > 1. f = codecs.open( paf, "r", "utf8" ) > I had hopes for this one. > 2. f = codecs.open( paf, "r", locale.getpreferredencoding()) > 3. f = open( paf, "r") Now you are mixing two important concepts - the *contents* of the file with the *name* of the file. These are entirely independent, and the file name may be in one encoding and the file contents in another, or the file contents may not represent character data at all. All these three APIs try to get to the *contents* of the file, by opening it. The name is already a byte string (as a character string, it would have started with u'...'), so there is no need to encode it. What the content of a .pog file is, I don't know, so I can't tell you what encoding it is encoded it. > But none will open it - all get a UnicodeDecodeError. This aligns with my > suspicions, but I wanted to bounce it off you to be sure. Option three should have worked if paf was a string, but above, I see it as a *list* of strings. So try f = open(paf[0], "r")# where paf[0] should be '/home/donn/.fontypython/M\xc3\x96gul.pog', as paf is ['/home/donn/.fontypython/M\xc3\x96gul.pog'] Still, I question that you *really* got a UnicodeDecodeError for three: I get TypeError: coercing to Unicode: need string or buffer, list found Can you please type paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] f = open(paf, "r") at the interactive prompt, and report the *complete* shell output? > Also, this codecs.open(filename, "r", ) function: > 1. Does it imply that the filename will be opened (with the name as it's > type : i.e. bytestring or unicode ) and written *into* as > 2. Imply that filename will be encoded via and written into as > > It's fuzzy, how is the filename handled? See above. The encoding in codecs.open has no effect at all on the file name; it only talks about the file content. Regards, Martin From fetchinson at googlemail.com Tue Jan 8 20:19:02 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 8 Jan 2008 17:19:02 -0800 Subject: user friendly datetime features Message-ID: Many times a more user friendly date format is convenient than the pure date and time. For example for a date that is yesterday I would like to see "yesterday" instead of the date itself. And for a date that was 2 days ago I would like to see "2 days ago" but for something that was 4 days ago I would like to see the actual date. This is often seen in web applications, I'm sure you all know what I'm talking about. I'm guessing this feature is needed so often in so many projects that it has been implemented already by several people. Does anyone know of such a stand alone module? From max at alcyone.com Thu Jan 10 17:10:08 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 10 Jan 2008 14:10:08 -0800 Subject: Newbie question on Classes In-Reply-To: References: Message-ID: Adrian Wood wrote: > I can call man.state() and then woman.state() or Person.state(man) and > Person.state(woman) to print the status of each. This takes time and > space however, and becomes unmanageable if we start talking about a > large number of objects, and unworkable if there is an unknown number. > What I'm after is a way to call the status of every instance of Man, > without knowing their exact names or number. > > I've gone through the relevant parts of the online docs, tried to find > information elsewhere online, and looked for code samples, but the > ionformation either isn't there, or just isn't clicking with me. I've > tried tracking the names of each object in a list, and even creating > each object within a list, but don't seem to be able to find the right > syntax to make it all work. You'll have to retain a list of all extant Person objects, and then a function which calls the relevant method on every element of that list and returns the result however you wish. You can easily encapsulate that list into a class attribute of Person, and the function into a static method of the class for elegance, but it's not required to get the proper functionality. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Life is a gamble so I should / Live life more carefully -- TLC From hannah.drayson at plymouth.ac.uk Tue Jan 29 13:35:30 2008 From: hannah.drayson at plymouth.ac.uk (Hannah Drayson) Date: Tue, 29 Jan 2008 18:35:30 +0000 Subject: noob stuck on reading double Message-ID: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk> Hi all, I have a .bin file which python just won't play ball with- Does anyone know what I'm doing wrong- is it simply incompatible? I've read it fine using a C program - its 113 doubleword fields- apparently its possible to handle these in python in a very similar way to C. I can provide the c code and have attached .bin if anyone is interested... Thank you all. It imports as a string of rubbish... i.e. >>> text = f.read() >>> print text ?F?C??y??>? @??I at g[??B8~??????Q???Q???Q???Q???Q???Q???Q???Q???Q???Q????=N@???????????????????/???8@@@@?Q at E??/??T at N#????S@?????Q???Q???Q???Q???Q???????????R[???Q??????? It won't unpack using struct... >>> unpack('d', text) Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/struct.py", line 87, in unpack return o.unpack(s) struct.error: unpack requires a string argument of length 8 Using str and repr gets me something that looks like unicode... >>> str(text) '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \xa0F\xa2C\xc0\xd2y\xf9\xf8>\xd2\n@\x00\x00\x00\xc0\xd3\x9cI@\x00\x00\x00\x 00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00g[\xa0?B8~\xd4\x00\x00\x00 \x00\x00\x00\xf8\xff\x00\x00\x00\x00\x00\x00\xf8\xff\x00\x00\x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x00\x00\x00\ etc..... Tried formatting it... >>> str(text) % ('Python', 'g') Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting Tried converting it to unicode... >>> unicode(text, 'utf8', 'strict') Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0xa0 in position 19: unexpected code byte I even tried chopping it up into 8 character pieces and then converting it into a float, but I think I'm just being stupid by this point... >>> the_list=[] >>> index = 0 >>> second_dig = 7 >>> while index < (len(bum))/8: ... new_bit = bum[index:second_dig] ... the_list.append(new_bit) ... index += 8 ... second_dig += 8 ... >>> print the_list [u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\ufffdF\ufffdC', u'y\ufffd@\x00\x00\x00\ufffd', u'I@\x00\x00\x00\x00\x00', u'\x00\x00\x00\x01\x00\x00\x00', u'\x00\x00g[\ufffd?B', u'~\ufffd\x00\x00\x00\x00\x00', u'\x00\x00\x00\ufffd\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00'] >>> the_list[1] u'\x00\x00\x00\x00\x00\x00\x00' >>> float(the_list[1]) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'decimal' codec can't encode character u'\x00' in position 0: invalid decimal Unicode string Any ideas? -------------- next part -------------- A non-text attachment was scrubbed... Name: data.bin Type: application/macbinary Size: 904 bytes Desc: data.bin URL: From stef.mientki at gmail.com Wed Jan 9 16:22:52 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 09 Jan 2008 22:22:52 +0100 Subject: getting absolute path ? Message-ID: <47853B2C.9020403@gmail.com> hello, I'm trying to convert the links in html pages to absolute links, these pages can either be webpages or files on local harddisk (winXP). Now I've struggling for a while, and this code works a lilttle: i = line.find ( 'href=' ) if i < 0 : i = line.find ( ' src=' ) if i >= 0 : ii = line.find ( '"', i+6 ) file = line [ i+6 : ii ] #print urlparse.urljoin ( p, file ) if file.find ( 'http:' ) < 0 : abspath = os.path.normpath ( os.path.join ( p, file ) ) line = line.replace ( file, abspath ) print line but it only covers files on local disk and just 1 link per line, so I guess it's a lot of trouble to catch all cases. Isn't there a convenient function for (OS independent preferable) ? Googled for it, but can't find it. thanks, Stef Mientki From bignose+hates-spam at benfinney.id.au Mon Jan 14 17:39:03 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 09:39:03 +1100 Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> Message-ID: <874pdgf2wo.fsf@benfinney.id.au> George Sakkis writes: > By the way, why do we need both NotImplementedError and the > NotImplemented singleton object ? Couldn't we have just one of them ? One of them is an exception class, the other is not. They have rather different semantics. I think of NotImplemented as equivalent to None; it's useful as a sentinel value to set an attribute to in (e.g.) an abstract class. For a function that is (or has a flow branch which is) not (yet?) implemented, I don't want to return at all. Instead, I want to raise an instance of NotImplementedError. I think it's desirable to keep them both distinct as is. -- \ "If you get invited to your first orgy, don't just show up | `\ nude. That's a common mistake. You have to let nudity | _o__) 'happen.'" -- Jack Handey | Ben Finney From kar1107 at gmail.com Sat Jan 12 19:50:23 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Sat, 12 Jan 2008 16:50:23 -0800 (PST) Subject: executing newgrp from python in current shell possible? References: <755e7fd2-5e4a-4a4b-b848-a5e4ca756087@l6g2000prm.googlegroups.com> Message-ID: <73c6fb57-caa7-4676-8e5e-31c78f882531@t1g2000pra.googlegroups.com> On Jan 12, 6:19 am, Svenn Are Bjerkem wrote: > On Jan 9, 9:18 pm, Zentrader wrote: > > > On Jan 9, 5:56 am, Svenn Are Bjerkem > > wrote: > > > >I have been looking for a way to execute this command > > > as a part of a script, but it seems that the changes are only valid in > > > the context of the script and when the script exits, the current shell > > > still have the original "users" group setting. > > > I don't think you would want it any other way. Would you want a user > > to be able to change the group and have it remain permanently? Who's > > going to remember whether they were last in "A" or "B", and it opens > > up oportunities for the practical joker when you go to the restroom > > and leave the terminal on. Put the "change the group" code into a > > separate function in a separate file (with only you as the owner) and > > call it whenever you want to change groups. > > I am trying to create a script that make it easy for users in a design > team to create files that belong to the same group, but retain the > users uid. In order to make it visible that the user is creating files > with a different gid, the script will change the prompt to indicate > so. In a tcl solution I have now, the users home is changed to the > design area as some tools are reading and writing setup files into > $HOME. I have not found a way to change the gid in tcl so I turned to > python in hope that this scripting language could do so. > > The tcl solution spawns a new tcsh after setting several environment > variables and works quite well except for not being able to change > gid. And it is also a wish from my side to port this script to python. > > Is your suggestion to put "newgrp design" into a new file and then > exec this file in my python script? What happens to the group id of > the shell that called the python script in this case? I would try to > avoid spawning a new tcsh as this make execution of tools on a remote > computer difficult as the handover of command line arguments does not > seem to be handed over to the newly spawned shell. I may be > understanding something wrongly here. When you fork a process in unix/linux, the child inherits all of parents settings; *but* any future changes that is made in child process will not get reflected in the parent. So there is no way you can fire a process and some how get its setting back to the invoking shell (which could be anything btw, say bash/tcsh/ csh). Thus what you really want is start a wrapper python script, say setup_design.py In setup_design.py, call necessary os routines like setegid(egid); this will update the process settings of the process running setup_design.py. At the end of setup_design.py, do an exec call[1] to fire the user's shell (note that even if you use popen or other ways of forking a new process, things will work just fine) Whatever changes you made to the process environment will get propagated to the new shell. User must explicitly finish the new shell (say typing 'exit' on shell prompt) Karthik [1]. e.g. import os os.execvp(cmd_run[0], cmd_run) # cmd_run is probably ['/bin/bash'] > > -- > Svenn From mwm at mired.org Thu Jan 10 13:43:35 2008 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 13:43:35 -0500 Subject: What is "lambda x=x : ... " ? In-Reply-To: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> Message-ID: <20080110134335.37cf5377@mbook.mired.org> On Thu, 10 Jan 2008 10:25:27 -0800 (PST) "zslevi at gmail.com" wrote: > I'm reading this page: http://www.ps.uni-sb.de/~duchier/python/continuations.html > and I've found a strange usage of lambda: > > #################### > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ################### > > What does "y=y" and "c=c" mean in the lambda function? Older versions of python didn't make variables in an outer scope visible in the inner scope. This was the standard idiom to work around that. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From tjreedy at udel.edu Wed Jan 30 21:26:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jan 2008 21:26:20 -0500 Subject: booleans, hash() and objects having the same value References: <9cdb261f-b81b-4eca-955a-a9b516eba9d2@s13g2000prd.googlegroups.com> Message-ID: "Ryszard Szopa" wrote in message news:9cdb261f-b81b-4eca-955a-a9b516eba9d2 at s13g2000prd.googlegroups.com... | | (Also, it is not completely clear what it means for two Python objects | to "have the same value". Objects of different types compare unequal unless provision is made otherwise. See http://docs.python.org/ref/comparisons.html for more From tjreedy at udel.edu Sat Jan 26 22:20:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jan 2008 22:20:20 -0500 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu><120eok46fkf0j2b@corp.supernews.com> <15114746.post@talk.nabble.com> Message-ID: To answer the OP's question: GOF design patterns that solve problems due to static typing (and there are some) are not needed with Python. Others do apply and can be useful. There have been various mentions in c.l.p over the years. From gherron at islandtraining.com Sun Jan 6 21:33:45 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 06 Jan 2008 18:33:45 -0800 Subject: ctypes In-Reply-To: <5bc0722e-efe7-4067-9bf4-afee3f1c9a03@f3g2000hsg.googlegroups.com> References: <5bc0722e-efe7-4067-9bf4-afee3f1c9a03@f3g2000hsg.googlegroups.com> Message-ID: <47818F89.7090001@islandtraining.com> hkimball at eti-web.com wrote: > I am having trouble with ctypes: i can load the third party dll, and > gain access to the function but the function calls do not actually > perform their intended purpose. I have tried this in both interactive > mode and from a saved script. I know that is a somewhat vague > description but any help would be greatly appreciated. > > thanks > harold kimball > It is too vague to give any help other than: Read the documentation, and search for and follow examples. That worked for me in my recent (and first) attempt a accessing a dll via ctypes. If you can be more specific about your problem and how it fails, then perhaps you'll get more specific answers. Also, please read this: http://www.catb.org/~esr/faqs/smart-questions.html Gary Herron From grante at visi.com Mon Jan 21 11:17:58 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 21 Jan 2008 16:17:58 -0000 Subject: When is min(a, b) != min(b, a)? References: Message-ID: <13p9hdmh7c08abe@corp.supernews.com> On 2008-01-21, Jason wrote: > Infinite values are also problematic. In almost all cases, it is far > better to avoid infinite and NaN values. In many applications (e.g. process control) propogating NaN values are way too useful to avoid. Avoiding NaN would make a lot of code far more complicated than would using them. -- Grant Edwards grante Yow! How's the wife? at Is she at home enjoying visi.com capitalism? From george.sakkis at gmail.com Thu Jan 17 00:42:00 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 16 Jan 2008 21:42:00 -0800 (PST) Subject: next line (data parsing) References: <13otnvakq8kc6a3@corp.supernews.com> Message-ID: On Jan 17, 12:01 am, Scott David Daniels wrote: > robleac... at gmail.com wrote: > > Hi there, > > I'm struggling to find a sensible way to process a large chuck of > > data--line by line, but also having the ability to move to subsequent > > 'next' lines within a for loop. I was hoping someone would be willing > > to share some insights to help point me in the right direction. This > > is not a file, so any file modules or methods available for files > > parsing wouldn't apply. > > > I can iterate over each line by setting a for loop on the data object; > > no problem. But basically my intension is to locate the line "Schedule > > HOST" and progressively move on to the 'next' line, parsing out the > > pieces I care about, until I then hit "Total", then I resume to the > > start of the for loop which locates the next "Schedule HOST". > > if you can do: > > for line in whatever: > ... > > then you can do: > > source = iter(whatever) > for intro in source: > if intro.startswith('Schedule '): > for line in source: > if line.startswith('Total'): > break > process(intro, line) > > --Scott David Daniels > Scott.Dani... at Acm.Org Or if you use this pattern often, you may extract it to a general grouping function such as http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877: import re for line in iterblocks(source, start = lambda line: line.startswith('Schedule HOST'), end = lambda line: re.search(r'^ \s*Total',line), skip_delim=False): process(line) George From gbacon at hiwaay.net Mon Jan 28 13:53:42 2008 From: gbacon at hiwaay.net (Greg Bacon) Date: Mon, 28 Jan 2008 18:53:42 -0000 Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> Message-ID: <13ps95mg8am3l37@corp.supernews.com> The code below at least passes your tests. Hope it helps, Greg #! /usr/bin/perl use warnings; use strict; use constant { MATCH => 1, NO_MATCH => 0, }; my @tests = ( [ "winter tire", => MATCH ], [ "tire", => MATCH ], [ "retire", => MATCH ], [ "tired", => MATCH ], [ "snowbird tire", => MATCH ], [ "tired on a snow day", => MATCH ], [ "snow tire and regular tire", => MATCH ], [ " tire" => MATCH ], [ "snow tire" => NO_MATCH ], [ "snow tire" => NO_MATCH ], [ "some snowtires" => NO_MATCH ], ); my $not_snow_tire = qr/ ^ \s* tire | ([^w\s]|[^o]w|[^n]ow|[^s]now)\s*tire /xi; my $fail; for (@tests) { my($str,$want) = @$_; my $got = $str =~ /$not_snow_tire/; my $pass = !!$want == !!$got; print "$str: ", ($pass ? "PASS" : "FAIL"), "\n"; ++$fail unless $pass; } print "\n", (!$fail ? "PASS" : "FAIL"), "\n"; __END__ -- ... all these cries of having 'abolished slavery,' of having 'preserved the union,' of establishing a 'government by consent,' and of 'maintaining the national honor' are all gross, shameless, transparent cheats -- so trans- parent that they ought to deceive no one. -- Lysander Spooner, "No Treason" From kw at codebykevin.com Thu Jan 10 17:06:27 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 10 Jan 2008 17:06:27 -0500 Subject: Wrap Tk widget using a class Message-ID: I'm trying to wrap a subset of a Tcl/Tk widget set called tclmacbag (see http://tclmacbag.autons.net/) for use in my Tkinter application, using a "macnotebook" class. I'm having some difficulty getting things configured correctly. Here is my class code: from Tkinter import * class Macnotebook: def __init__(self, master): self.master = master self.master.call('package', 'require', 'tclmacbag') def notebook(self): self.master.call('::tclmacbag::pnb', self) def add(self, child): self.master.call('::tclmacbag::pnb', 'add', child) Here is an example of how I'm calling this in my code: from Macnotebook import Macnotebook self.prefbook = Macnotebook.notebook(self.prefframe) self.prefbook.pack(fill=BOTH, expand=YES, side=TOP) This returns the following error in my console: Traceback (most recent call last): self.prefbook = Macnotebook.notebook(self.prefframe) TypeError: unbound method notebook() must be called with Macnotebook instance as first argument (got Frame instance instead) Can anyone suggest how I might better structure the class so that this works? I'm a bit of a newbie with OO, so any pointers are appreciated. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From gnewsg at gmail.com Fri Jan 4 06:25:28 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 4 Jan 2008 03:25:28 -0800 (PST) Subject: choosing random dynamic port number References: <32e43bb70801031409o5d1dcd2at5a159339cd43ae52@mail.gmail.com> Message-ID: <3e6cca84-f8cf-4947-931c-18d6af748f13@l6g2000prm.googlegroups.com> On 3 Gen, 23:21, Fredrik Lundh wrote: > Emin.shopper Martinian.shopper wrote: > > Is there a good way to choose/assign random dynamic port numbers in python? > > > I had in mind something like the following, but if multiple programs are > > generating random port numbers, is there a way to check if a given port > > number is already taken? > > > ? ? def GenerateDynamicPortNumber(): > > ? ? ? ? "Generate a random dynamic port number and return it." > > ? ? ? ? # port numbers between 49152 to 65535 are dynamic port numbers > > ? ? ? ? return 49152 + random.randrange(15000) > > ? ? def GenerateDynamicPortNumber(): > ? ? ? ? return 0 > > (to get the actual number, use getsockname() on the socket after you've > called "bind" on it) > > By using 0 as port number value you let kernel choose a free unprivileged random port: >>> import socket >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s.bind(('', 0)) >>> s.getsockname() ('0.0.0.0', 3070) From ajaksu at gmail.com Sun Jan 27 18:28:37 2008 From: ajaksu at gmail.com (ajaksu) Date: Sun, 27 Jan 2008 15:28:37 -0800 (PST) Subject: optional static typing for Python References: <23f7c55a-949f-41a4-b558-81861ede258f@f10g2000hsf.googlegroups.com> Message-ID: On Jan 27, 9:13 pm, "Russ P." wrote: > On Jan 27, 3:08 pm, Jarek Zgoda wrote: > > > Russ P. pisze: > > > >>> I noticed that Guido has expressed further interest in static typing > > >>> three or four years ago on his blog. Does anyone know the current > > >>> status of this project? Thanks. > > >> I thought it was april fools joke? > > > > On January 21, 2000? Which calendar do you use? > > > Static typing in Python is usual theme of april fools jokes. > > I hope Guido doesn't find out about that! He does know, follow http://mail.python.org/pipermail/python-dev/2007-April/072419.html and get a laugh too! :) On a more serious note, I suggest you look up ShedSkin, Pyrex and Cython, where the static typing is used for better performance. And with Psyco, you get dynamic typing with JIT specialization. In core CPython, little is being done AFAIK to support static typing per-se, but annotations can (and probably will) be used for that end. However, I don't think it'll interfere in how CPython executes the program. Daniel From mauriceling at gmail.com Tue Jan 8 06:09:26 2008 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Tue, 8 Jan 2008 03:09:26 -0800 (PST) Subject: Paid subscription Python magazines References: <13o6jthqrl90o2d@corp.supernews.com> Message-ID: On Jan 8, 6:17 pm, Jon Harrop wrote: > Are there any Python magazines that you can pay to subscribe to? (either > paper or on-line). The Python Papers (www.pythonpapers.org) is a free e-journal, including industry and academic articles. maurice From bruno.desthuilliers at gmail.com Sat Jan 12 11:42:19 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jan 2008 08:42:19 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> <478732db$0$19250$426a74cc@news.free.fr> <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> <4787762b$0$18777$426a74cc@news.free.fr> Message-ID: <2b12e762-a5ca-4e86-b95a-ef6823ed8603@j78g2000hsd.googlegroups.com> On 11 jan, 16:10, George Sakkis wrote: > On Jan 11, 8:59 am, Bruno Desthuilliers > But I *still* fail to see how it could be "misleading", and > > *you* still fail to explain in which way it could be misleading. > > > If your point is that saying that CPython uses a byte-code/VM scheme > > "just like Java" necessarily implies JIT compilation just because some > > JVM support this feature, then it would be time you pay more attention > > to what is effectively written. > > What three different people in this thread have been trying to tell > you but you seem to miss is that claiming CPython's VM "is just like > Java" George, *please*, re-read what I wrote. I *never* claimed that CPython's VM is just like a JVM, I just stated that both CPython and Java use a byte-code/VM execution model. Can't you understand that ? From ssharkey at linuxunlimited.com Thu Jan 10 13:46:47 2008 From: ssharkey at linuxunlimited.com (Scott Sharkey) Date: Thu, 10 Jan 2008 13:46:47 -0500 Subject: Persistent HTTP Connections with Python? Message-ID: <47866817.7050207@linuxunlimited.com> Hello All, I am trying to write a python script to talk to an xml-based stock feed service. They are telling me that I must connect and login, and then "issue refresh requests" to fetch the data. This sounds a lot (to me) like HTTP 1.1 persistent connections. Can I do that with the urllib functions, or do I need to use the httplib functions for this kind of work. Pointers and/or sample code would be much appreciated. Thanks! -scott From kyosohma at gmail.com Mon Jan 7 11:20:19 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 7 Jan 2008 08:20:19 -0800 (PST) Subject: Killing worker threads References: Message-ID: On Jan 6, 7:48 am, Fredrik Lundh wrote: > tarun wrote: > > Can anyone help me with a simple code through which the main thread can > > kill the worker thread it started. > > it cannot. threads cannot be killed from the "outside". > > The only way to "kill" a thread is to have the spawned thread have some kind of passed in argument which will trigger it to shut down. You could have the thread read a file or file-like object periodically (like a timer) and if it meets some condition, have the thread quit. It's kind of like a subscription process. The thread subscribes to the main program and can accept signals. I suggest that the OP read the docs on threads: http://docs.python.org/lib/module-threading.html Of special interest to this user: http://docs.python.org/lib/condition-objects.html I have messed with KillProcName, a PyWin32 script with limited success. There's also the following snippet which is Windows only and works for some processes and not others (i.e. unreliable): subprocess.Popen('taskkill /s %s /im %s' % (computer_id, proc)) Hopefully I didn't muddy the waters or write something too off the mark. Mike From ram.rachum at gmail.com Wed Jan 23 10:37:35 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Wed, 23 Jan 2008 07:37:35 -0800 (PST) Subject: A GUI framework for running simulations References: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com> <657f0$47975960$83aef404$1819@news1.tudelft.nl> Message-ID: <76254c7d-7e69-4270-a10d-bf88acdae10d@f47g2000hsd.googlegroups.com> On Jan 23, 5:12?pm, Stef Mientki wrote: > ram.rac... at gmail.com wrote: > > Hello! I am currently working on writing a simulation engine for > > special relativity physics. I'm writing it in Python, of course. I'm > > doing fine with the engine, but I want a GUI framework in which I > > could use it conveniently, and test different setups on it. I'm not so > > strong with GUI programming. I looked at Tkinter, I looked at > > WxPython, I looked at PythonCard. It all looks pretty daunting. > > > My question is, does there exist a GUI package that is intended > > specifically for simulations? I saw a program called Golly, which is a > > simulation for Conway's Game of Life. Its GUI had most of the features > > I needed. For example, you can load a setup, there are "play" and > > "stop" buttons, you can change a setup and save it, etc. > > > So does anyone know of a general GUI framework for running > > simulations? > > although quit premature, > PyLab_Works might be of interest, > see some demos here (watch the demo at the bottom first):http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_animations_sc... > > (you can contact me offline if PyLab_Works looks interesting to you). > > cheers, > Stef Mientki Thank you, Stef and Guilherme. I'll be checking those things out. If anyone else who has an idea for something that can help me, I'll be happy to hear it! Ram. From sjmachin at lexicon.net Mon Jan 28 01:31:17 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 27 Jan 2008 22:31:17 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> <72a03212-7cf3-486d-ac70-c97a002d90c7@n20g2000hsh.googlegroups.com> Message-ID: <70b77205-e870-43d2-89d0-7f0d37bd056d@s8g2000prg.googlegroups.com> On Jan 28, 2:53 pm, glacier wrote: > > Thanks,John. > It's no doubt that you proved SAX didn't support GBK encoding. > But can you give some suggestion on how to make SAX parse some GBK > string? Yes, the same suggestion as was given to you by others very early in this thread, the same as I demonstrated in the middle of proving that SAX doesn't support a GBK-encoded input file. Suggestion: Recode your input from GBK to UTF-8. Ensure that the XML declaration doesn't have an unsupported encoding. Your handler will get data encoded as UTF-8. Recode that to GBK if needed. Here's a cut down version of the previous script, focussed on demonstrating that the recoding strategy works. C:\junk>type gbksax2.py import xml.sax, xml.sax.saxutils import cStringIO unistr = u''.join(unichr(0x4E00+i) + unichr(ord('W')+i) for i in range(4)) gbkstr = unistr.encode('gbk') print 'This is a GBK-encoded string: %r' % gbkstr utf8str = gbkstr.decode('gbk').encode('utf8') print 'Now recoded as UTF-8 to be fed to a SAX parser: %r' % utf8str xml_template = """%s""" utf8doc = xml_template % ('utf-8', unistr.encode('utf8')) f = cStringIO.StringIO() handler = xml.sax.saxutils.XMLGenerator(f, encoding='utf8') xml.sax.parseString(utf8doc, handler) result = f.getvalue() f.close() start = result.find('') + 6 end = result.find('') mydata = result[start:end] print "SAX output (UTF-8): %r" % mydata print "SAX output recoded to GBK: %r" % mydata.decode('utf8').encode('gbk') C:\junk>gbksax2.py This is a GBK-encoded string: '\xd2\xbbW\xb6\xa1X\x81 at Y\xc6\xdfZ' Now recoded as UTF-8 to be fed to a SAX parser: '\xe4\xb8\x80W \xe4\xb8\x81X\xe4\xb8\x82Y\xe4\xb8\x83Z' SAX output (UTF-8): '\xe4\xb8\x80W\xe4\xb8\x81X\xe4\xb8\x82Y \xe4\xb8\x83Z' SAX output recoded to GBK: '\xd2\xbbW\xb6\xa1X\x81 at Y\xc6\xdfZ' HTH, John From duncan.booth at invalid.invalid Mon Jan 14 05:39:26 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Jan 2008 10:39:26 GMT Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> Message-ID: Gary Herron wrote: > hakim ouaras wrote: >> Hi, >> >> I am begining with python, I want to know what is the utility and how >> to use the expression "NotImplementedError". >> >> Thak you for your answers >> Hakim >> > > It's meant to be used to mark a procedure that you intend to write, > but have not yet done so. More often it is used to mark a method which is some part of a class interface but is not implemented in that specific class. Typically you do this when writing an abstract base class: whoever uses it must implement particular methods, and if they forget then you raise NotImplementedError. For examples just grep the Python lib sources. e.g. optparse has an abstract class HelpFormatter which has a couple of methods that must be implemented in subclasses: class HelpFormatter: ... def format_usage(self, usage): raise NotImplementedError, "subclasses must implement" def format_heading(self, heading): raise NotImplementedError, "subclasses must implement" ... class IndentedHelpFormatter (HelpFormatter): """Format help with indented section bodies. """ ... def format_usage(self, usage): return _("Usage: %s\n") % usage def format_heading(self, heading): return "%*s%s:\n" % (self.current_indent, "", heading) and so on. From syahreza.octadian at gmail.com Sun Jan 13 21:26:33 2008 From: syahreza.octadian at gmail.com (syahreza.octadian) Date: Sun, 13 Jan 2008 18:26:33 -0800 (PST) Subject: import gzip error (please help) References: Message-ID: <84c2aba9-19cb-4ded-8332-10cf16032127@m77g2000hsc.googlegroups.com> On Jan 11, 7:14 pm, Fredrik Lundh wrote: > the core zlib library (libz.so) isn't installed on your machine. but in my machine there is file -rwxr-xr-x 1 bin bin 48576 Sep 20 2006 /usr/local/lib/ python2.5/lib-dynload/zlib.so if i have to install zlib library core, where i can found it for solaris 10 sparcv. From ppetrick at gmail.com Mon Jan 21 17:41:18 2008 From: ppetrick at gmail.com (p.) Date: Mon, 21 Jan 2008 14:41:18 -0800 (PST) Subject: Transforming ascii file (pseduo database) into proper database References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> <051e9305-6f9a-4d95-91cb-641c04b97b79@e10g2000prf.googlegroups.com> Message-ID: So in answer to some of the questions: - There are about 15 files, each roughly representing a table. - Within the files, each line represents a record. - The formatting for the lines is like so: File1: somval1|ID|someval2|someval3|etc. File2: ID|someval1|someval2|somewal3|etc. Where ID is the one and only value linking "records" from one file to "records" in another file - moreover, as far as I can tell, the relationships are all 1:1 (or 1:0) (I don't have the full dataset yet, just a sampling, so I'm flying a bit in the dark). - I believe that individual "records" within each of the files is unique with respect to the identifier (again, not certain because I'm only working with sample data). - As the example shows, the position of the ID is not the same for all files. - I don't know how big N is since I only have a sample to work with, and probably won't get the full dataset anytime soon. (Lets just take it as a given that I won't get that information until AFTER a first implementation...politics.) - I don't know how many identifiers either, although it has to be at least as large as the number of lines in the largest file (again, I don't have the actual data yet). So as an exercise, lets assume 800MB file, each line of data taking up roughly 150B (guesstimate - based on examination of sample data)...so roughly 5.3 million unique IDs. With that size, I'll have to load them into temp db. I just can't see holding that much data in memory... From Lie.1296 at gmail.com Fri Jan 11 05:52:25 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 11 Jan 2008 02:52:25 -0800 (PST) Subject: Property with Arguments Message-ID: <3b8f3359-2889-42d5-9a5f-db2ee4268e8c@l1g2000hsa.googlegroups.com> Is there a way to create a property with arguments? Or an index value like a list? To be used in the form like: someClass.someProperty['arguments'] = 'some value' or someClass.someProperty('argument1', 'argument2') = 'some value' From gherzig at fmed.uba.ar Mon Jan 14 06:59:32 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Mon, 14 Jan 2008 08:59:32 -0300 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** In-Reply-To: <8a6b8e350801130238y1723cbcco37bdd8e7b60460ec@mail.gmail.com> References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> <4788de48$0$26887$ecde5a14@news.coretel.net> <47890e3e$0$26886$ecde5a14@news.coretel.net> <6a2ccd190801121107r7b728d09ve072909ba2863c04@mail.gmail.com> <8a6b8e350801130238y1723cbcco37bdd8e7b60460ec@mail.gmail.com> Message-ID: <478B4EA4.9070207@fmed.uba.ar> James Matthews wrote: >When did this list become a politics dialog? Please keep on topic "Python"! > >Thanks >James > >On Jan 12, 2008 8:07 PM, Joe Riopel wrote: > > >>On Jan 12, 2008 2:00 PM, radiosrfun wrote: >> >> >>>Whether we agree on "tactics" or not - if it come to a battlefield with the >>>two of us - or any Americans there - we're still going to fight the same >>>enemy - not each other. >>> >>> >>This is a good resource for starting Python >>http://diveintopython.org/ >> >>-- >>http://mail.python.org/mailman/listinfo/python-lis >> >> >> >> indian = CreeIndian() indian.setVoice("lugubrious") indian.says("When the last tree is cut down, the last fish eaten and the last stream poisoned, you will realize that you cannot eat money.") :) From deets at nospam.web.de Thu Jan 31 11:35:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jan 2008 17:35:39 +0100 Subject: REALLY simple xml reader In-Reply-To: <13q3ri2707niqc6@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> Message-ID: <60ebn3F1q0eaeU1@mid.uni-berlin.de> Steven D'Aprano schrieb: > 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. > > "You know Bob, XML just isn't hostile enough to anyone silly enough to > believe it's 'human-readable'. What can we do to make it more hostile?" > > "Well Fred, how about making the XML declaration completely optional, so > you can leave it out and still be vald XML, but if you include it, you're > not allowed to precede it with semantically neutral whitespace?" > > "I take my hat off to you." > > > This is legal XML: > > """ > Hello, world!""" > > and so is this: > > """ > Hello, world!""" > > > but not this: > > """ > Hello, world!""" > > > You can't get this sort of stuff except out of a committee. do not forget to mention that trailing whitespace is evil as well!!! And that for some reason some characters below \x20 aren't allowed in XML even if it's legal utf-8 - for what reason I'd really like to know... Diez From mr.cerutti at gmail.com Sun Jan 6 19:22:17 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Sun, 6 Jan 2008 19:22:17 -0500 Subject: Basic inheritance question In-Reply-To: <42aeef02-a0a9-4e29-9a5d-7a0785997666@v67g2000hse.googlegroups.com> References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <5u95sjF1etf0nU1@mid.individual.net> <42aeef02-a0a9-4e29-9a5d-7a0785997666@v67g2000hse.googlegroups.com> Message-ID: <51302a8c0801061622m50732b01pb948a332cfd63590@mail.gmail.com> On Jan 6, 2008 6:59 PM, Dan Bishop wrote: > > My employer has us use the "m_" convention. > > I wonder why Bjarne made "this->" optional in the first place. > -- > http://mail.python.org/mailman/listinfo/python-list > I think implicit this-> is somewhat more defensible. If 'this' were not a pointer, perhaps C++ wouldn't have chosen impliciticity.. -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sat Jan 26 02:40:28 2008 From: http (Paul Rubin) Date: 25 Jan 2008 23:40:28 -0800 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <479A58F9.4090805@gmx.net> <8d04436f0801251519g482a697dn625223b6d46e8f2c@mail.gmail.com> Message-ID: <7x8x2d11cj.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > | > What's about l.index(max(l)) ? > > Both of these methods scan the list twice. The two given by RH and SDD do > so just once. Both of those will give the index of the of the last maximum > value. If you want the index of the first max value (you did not specify > ;-), write an explicit loop. How about (corrected but still untested): -max((v,-i) for i,v in enumerate(l))[1] I may have still missed something. From jorgen.maillist at gmail.com Wed Jan 16 04:02:56 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Wed, 16 Jan 2008 10:02:56 +0100 Subject: where do my python files go in linux? In-Reply-To: References: <32650267-3c38-4eee-ac18-fbb3b7ae907f@d21g2000prf.googlegroups.com> Message-ID: <11e49df10801160102r18e86c0re6671a770ea3f9fa@mail.gmail.com> Hi All, Sorry for the late reply back, I had a busy weekend ... it seems there is no clear way to do it and maybe that is why I was / am so confused. Eventually I searched for *.py files, and like I said most apps seem to install in /usr/share/{app} I believe that location is for data only that is shared between users. But for simplicity's sake I put my whole python application in there. It saves me setting a lot of paths differently. I made a symbolic link in /usr/bin that points to /usr/share/{app}/{app}.py This all seems to work fine. When I am getting more experienced with Debian / Ubuntu and linux overall, I will re-evaluate this and see if I can improve it. Thanks all for your answer, - Jorgen On Jan 14, 2008 4:30 PM, Nick Craig-Wood wrote: > Paul Boddie wrote: > > On 14 Jan, 08:47, "A.T.Hofkamp" wrote: > > > > > > Rather than re-inventing the wheel, please have a look at distutils: > > > http://docs.python.org/lib/module-distutils.html > > > > > > It does most if not all of the things you want to do. > > > If you want something more advanced, read about eggs. > > > > Although distutils does some of the work needed by the inquirer, it > > falls far short of what is needed to make a Debian package - that's > > why you have the "new" Debian Python policy and why the authors > > specifically refer to both distutils and setuptools in that document. > > It would be nice to have an equivalent to dh-make-perl which takes a > CPAN module and makes a .deb directly. > > http://packages.debian.org/stable/devel/dh-make-perl > > What I usually do is > > python setup.py bdist_rpm > > Then use alien to convert the resulting .rpm into a .deb > > I don't think these create particularly policy compliant .debs but > they are good enough for local usage. > > > Meanwhile, even stdeb [1] doesn't appear to completely automate the > > production of Debian packages using distutils. > > Looks interesting though! > > > [1] http://stdeb.python-hosting.com/ > > -- > Nick Craig-Wood -- http://www.craig-wood.com/nick > -- > > http://mail.python.org/mailman/listinfo/python-list > From nospam at invalid.com Fri Jan 11 12:39:00 2008 From: nospam at invalid.com (Jack) Date: Fri, 11 Jan 2008 17:39:00 GMT Subject: Using a proxy with urllib2 References: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> <87ir21o8sj.fsf@merkury.smsnet.pl> Message-ID: > Works for me. > How do you know that the proxy is not set? The proxy drops some URLs and the URLs were not being dropped when I did this :) > Try this: Thank you. I'll give it a try. From andre.roberge at gmail.com Sun Jan 27 17:49:46 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 27 Jan 2008 14:49:46 -0800 (PST) Subject: optional static typing for Python References: Message-ID: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> On Jan 27, 6:19 pm, "Russ P." wrote: > A while back I came across a tentative proposal from way back in 2000 > for optional static typing in Python: > > http://www.python.org/~guido/static-typing > > Two motivations were given: > > -- faster code > -- better compile-time error detection > > I'd like to suggest a third, which could help extend Python into the > safety-critical domain: > > -- facilitates automated source-code analysis > > There has been much heated debate in the past about whether Python is > appropriate for safety-critical software. Some argue that, with > thorough testing, Python code can be as reliable as code in any > language. Well, maybe. But then, a famous computer scientist once > remarked that, > > "Program testing can be used to show the presence of bugs, but never > to show their absence!" --Edsger Dijkstra > > The next step beyond extensive testing is automated, "static" analysis > of source-code ("static" in the sense of analyzing it without actually > running it). For example, Spark Ada is a subset of Ada with > programming by contract, and in some cases it can formally prove the > correctness of a program by static analysis. > > Then there is Java Pathfinder (http://javapathfinder.sourceforge.net), > an "explicit state software model checker." The developers of JPF > wanted > to use it on a prototype safety-critical application that I wrote in > Python, but JPF only works on Java code. We considered somehow using > Jython and Jythonc, but neither did the trick. So they ended up having > someone manually convert my Python code to Java! (The problem is that > my code was still in flux, and the Java and Python versions have now > diverged.) > > In any case, optional static typing in Python would help tremendously > here. The hardest part of automated conversion of Python to a > statically typed language is the problem of type inference. If the > types are explicitly declared, that problem obviously goes away. > Explicit typing would also greatly facilitate the development of a > "Python Pathfinder," so the conversion would perhaps not even be > necessary in the first place. > > Note also that, while "static" type checking would be ideal, > "explicit" typing would be a major step in the right direction and > would probably be much easier to implement. That is, provide a syntax > to explicitly declare types, then just check them at run time. A > relatively simple pre-processor could be implemented to convert the > explicit type declarations into "isinstance" checks or some such > thing. (A pre-processor command-line argument could be provided to > disable the type checks for more efficient production runs if > desired.) > > I noticed that Guido has expressed further interest in static typing > three or four years ago on his blog. Does anyone know the current > status of this project? Thanks. Perhaps this: http://www.python.org/dev/peps/pep-3107/ might be relevant? Andr? From madhurrajn at gmail.com Fri Jan 18 05:08:27 2008 From: madhurrajn at gmail.com (Madhur) Date: Fri, 18 Jan 2008 02:08:27 -0800 (PST) Subject: Filtering two files with uncommon column References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> <5084371c-dba0-4d11-be95-a01d1b439de6@s12g2000prg.googlegroups.com> Message-ID: On Jan 18, 2:37 pm, Chris wrote: > On Jan 18, 11:23 am, Madhur wrote: > > > > > I would like to know the best way of generating filter of two files > > based upon the following condition > > > I have two files. Contents of the first file is > > > File 1 > > abc def hij > > asd sss lmn > > hig pqr mno > > > File 2 > > > jih def asd > > poi iuu wer > > wer pqr jjj > > > I would like have the output as > > Output > > > File1 > > asd sss lmn > > File2 > > poi iuu wer > > > Basically I want to compare the two files based on second column. If > > the second > > column matches on both the files do not print anything, else if there > > is no matc > > h in for the second column for first file in second file then print it > > under Fil > > e1 header, else if there is no match for the second column for second > > file in fi > > rst file print it under File2 header. > > > Thankyou > > Madhur > > file1 = open('file1.txt','rb') > file2 = open('file2.txt','rb') > > file1_line = file1.next() > file2_line = file2.next() > > while file1_line and file2_line: > try: > f1_col2 = file1_line.split(' ')[1] > except IndexError: > print 'Not enough delimiters in line.' > try: > f2_col2 = file2_line.split(' ')[2] > except IndexError: > print 'Not enough delimiters in line.' > > if f1_col2 != f2_col2: > outfile_data_to_relevant_files() > > file1_line = file1.next() > file2_line = file2.next() > > HTH > Chris If the files2 is unordered, then the above logic does not work. How to takle it? From sjmachin at lexicon.net Thu Jan 10 17:38:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 10 Jan 2008 14:38:53 -0800 (PST) Subject: Newbie question on Classes References: Message-ID: <8f91961f-4d41-48a2-b541-c0604d0fae78@21g2000hsj.googlegroups.com> On Jan 11, 8:46 am, "Adrian Wood" wrote: > Hi al! I'm new to the list, and reasonably new to Python, so be gentle. > > Long story short, I'm having a hard time finding a way to call a > function on every object of a class at once. A class is a factory that creates objects. It keeps no records of what it has created -- it will never have to recall them for remediation. The customer needs to keep track of them. [snip] >I've > tried tracking the names of each object in a list In general, objects have 0, 1, or many "names" ... "tracking the names" is not a very meaningful concept hence not a very useful concept. At your application level, a person's name is what they call themselves and can vary over time and with the purpose for which it is used, and what is actually recorded in databases is subject to a non- trivial error rate -- hence using person's name as a key is not a very good idea. > and even creating > each object within a list, but don't seem to be able to find the right > syntax to make it all work. "creating each object in a list" sounds like it's going down the right path -- you need to keep a collection of objects somehow if you want to perform some operations on all objects, and a list is a reasonable start. Here's a very basic simple skeleton toy demonstration: >>> class Person(object): ... def __init__(self, name, hair): ... self.name = name ... self.hair = hair ... def show(self): ... print 'name=%r hair=%r' % (self.name, self.hair) ... >>> plist = [] >>> obj1 = Person(name='Bluey', hair='red') >>> plist.append(obj1) >>> obj2 = Person(name='John', hair='grey') >>> plist.append(obj2) >>> >>> for obj in plist: ... obj.show() ... name='Bluey' hair='red' name='John' hair='grey' >>> Does this help? From cjw at sympatico.ca Tue Jan 15 11:25:25 2008 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 15 Jan 2008 11:25:25 -0500 Subject: Why this apparent assymetry in set operations? In-Reply-To: References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: Colin J. Williams wrote: > Neil Cerutti wrote: >> On Jan 15, 2008 10:10 AM, wrote: >>> I've noticed that I can update() a set with a list but I can't extend a set >>> with a list using the |= assignment operator. >>> >>> >>> s = set() >>> >>> s.update([1,2,3]) >>> >>> s >>> set([1, 2, 3]) >>> >>> s |= [4,5,6] >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: unsupported operand type(s) for |=: 'set' and 'list' >>> >>> s |= set([4,5,6]) >>> >>> s >>> set([1, 2, 3, 4, 5, 6]) >>> >>> Why is that? Doesn't the |= operator essentially map to an update() call? >> No, according to 3.7 Set Types, s | t maps to s.union(t). >> > If the RHS is a set then it works OK: > > *** Python 2.5.1 (r251:54863, Apr 18 > 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32. *** >>>> import sets >>>> s1= sets.Set([2, 4, 5]) > Set([2, 4, 5]) >>>> s1= sets.Set([2, 4, 5]) >>>> s2= sets.Set([4, 5, 6]) >>>> s1|s2 > Set([2, 4, 5, 6]) >>>> s1|=s2 >>>> s1 > Set([2, 4, 5, 6]) > > It could be modified to handle any > iterable on the RHS. > > Colin W. > I'm sorry, there appears to be a bug: # tSet.py import sets s1= sets.Set([1, 2, 3]) s1.union_update([3, 4,5]) print(s1) s2= sets.Set([6, 7, 8]) s1 |+ s2 # This fails: exceptions.TypeError: bad operand type for unary +: 'Set' print s1 Colin W. From dbr517 at gmail.com Tue Jan 29 08:12:46 2008 From: dbr517 at gmail.com (dbr517 at gmail.com) Date: Tue, 29 Jan 2008 05:12:46 -0800 (PST) Subject: Extending the import mechanism - what is recommended? Message-ID: I need to extend the import mechanism to support another file type. I've already written the necessary C library to read the file and return a python code object. I found one example which just sub-classed imputil.ImportManager like this: from myLib import pye_code as pye_code class MyImporter(imputil.ImportManager): def __init__(self): imputil.ImportManager.__init__(self) self.add_suffix('.pye', self.import_pye) self.install() def import_pye(self, filepath, fileinfo, filename): data = pye_code(filepath) return 0, data, {} This actually works fine if the module is just a few lines of code, but it won't chain to the "built-in" importers; if the module that I'm importing does something as simple as 'import re', it fails. It may be that my confusion here is because (even after reading the code), I'm not clear on the purposes of imputil.ImportManager vs. imputil.Importer :-( What is the "preferred" way to do this type of extension? One other note; at this time, I just need to import individual module files with this extension; I don't need to import packages. Thanks! Dan From lists at cheimes.de Wed Jan 2 03:41:00 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 02 Jan 2008 09:41:00 +0100 Subject: os.tmpfile() In-Reply-To: <32714577.240331199246555557.JavaMail.root@hrndva-web18-z01> References: <32714577.240331199246555557.JavaMail.root@hrndva-web18-z01> Message-ID: <477B4E1C.7040401@cheimes.de> jyoung79 at kc.rr.com wrote: > Can anyone elaborate on how 'os.tmpfile()' works? I was thinking it would create some sort of temporary file I could quickly add text too and then when I was finished would automatically get rid of it. Here's my questions: Please don't use os.tmpfile(). It's not safe and exists only for legacy reasons. The tempfile module contains methods to create safe temporary files and directories. Christian From PurpleServerMonkey at gmail.com Wed Jan 30 15:17:58 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Wed, 30 Jan 2008 12:17:58 -0800 (PST) Subject: Web Interface Recommendations References: <45040839-8b1f-40af-9ef5-1be274c6e95f@z17g2000hsg.googlegroups.com> <80d6ce9f-6c8b-412d-a261-cfe480bd0c3b@e10g2000prf.googlegroups.com> <47a03e68$0$5443$426a34cc@news.free.fr> Message-ID: On Jan 30, 8:08 pm, Bruno Desthuilliers wrote: > PurpleServerMonkey a ?crit : > (snip) > > > Out of the major frameworks is there one that stands out as being > > particularly well suited for what I'm trying to do? > > > Django and CherryPy are on the short list so I'll give them a detailed > > look although Pylons does sound rather interesting as well. > > I guess you'll have to try them out to find the one that best match your > needs and personal preferences. Mostly: > > - CherryPy is more of a web application server than a framework per-se: > it's it's own HTTP server - which might or not be a good thing -, and > only deals with the "controler" part of the MVC triad. > > - Django is by now a mostly mature MVC framework, with more than a > couple years of production use on quite a lot of sites and applications, > good documentation and a somewhat large and active community. OTHO, it's > a very opiniated (and somewhat monolithic) framework, with most parts of > the stack (ORM, forms validation, template system etc) built > specifically for this framework (which was probably the sensible thing > to do by the time), so it's perhaps the less flexible of the three. > > - Pylons is IMHO very promising: wsgi from bottom to top, very flexible, > good default components choice (paste / Routes / SQLAlchemy / Mako / > FormEncode) but let you swap what you want in and out, and FWIW I've > seen so far a very sound architecture. FWIW, next Turbogears major > version will switch from CherryPy to Pylons. OTHO, it's still far from > being as mature and documented as Django. > > My 2 cents... Thanks Bruno, that's just the sort of info I was after. After reading more on the subject recently I'll be installing and testing Pylons and Turbogears first, think it will be a good fit for the project and if not there's no shortage of other offerings. From steve at mhomer.au Thu Jan 10 21:02:23 2008 From: steve at mhomer.au (Steve Brown) Date: Fri, 11 Jan 2008 13:02:23 +1100 Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: <13odjhgshnchjd4@corp.supernews.com> "Neil Cerutti" wrote in message news:mailman.408.1199973821.896.python-list at python.org... > On Jan 10, 2008 12:47 AM, Steve Brown wrote: >> I've got a series of modules which look like this: >> >> #************ >> # >> # Temperature Sense Test >> # >> #************ >> class Test3(ar_test.AR_TEST): >> """Temperature Sense Test""" >> >> >> I don't like the duplicated information: But the comment is attractive, >> and >> the docstring self.__doc__ is already in use in the test log. I've read >> that >> all modules and classes should have docstrings, but I don't really have >> anything else to say, and each module contains only one class. I don't >> think >> that >> >> """Temperature Sense Test""" >> class Test3(ar_test.AR_TEST): >> """Temperature Sense Test""" >> >> would be a real improvement. >> >> What do you think? > > I recommend a careful reading of PEP 257. > > You shouldn't waste your time creating (at best) decorative comments, > like: > #************ > # > # Temperature Sense Test > # > #************ > class Test3(ar_test.AR_TEST): > """Temperature Sense Test"" > > Remember that comments have to maintained along with the rest of the > code, so unnecessary ones just create more work for you. Any time you > can replace a comment with self-explanatory code, you should. > > Here's a vast improvement: > > class TemperatureSenseTester(ar_test.AR_TEST): > > -- > Neil Cerutti Yes, I'm working in that direction. At present there is still code that parses the test sequence to get the class name, but I'm rebuilding that. However, there will still be sufficient information for some of the tests to justify one doc string or comment as well as the class name. Is it possible to get from an object to a class module doc string? Something like self.class.module.__doc__ ? I'm not able to do an assignment inside the test class, because I have to keep that clean, but I can do assignments inside the parent test class. Steve From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 16 09:10:45 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 16 Jan 2008 15:10:45 +0100 Subject: Interesting Thread Gotcha References: Message-ID: <5v6hj5F1k6gi5U1@mid.individual.net> Hendrik van Rooyen wrote: > Absolutely! - well spotted! This is no threading problem at all; not even a syntax problem. If you don't know exactly what start_new_thread and kbd_driver functions do it's impossible to tell if your code does what is intended. > It would have been nice, however, to have gotten something like: > > TypeError - This routine needs a tuple. > > instead of the silent in line calling of the routine in question, > while failing actually to start a new thread. Exactly which part of the code should give you this warning? > Is it worth the trouble of learning how to submit a bug report? For your problem not, IMHO, as a bug report for it will be closed quickly. Regards, Bj?rn -- BOFH excuse #330: quantum decoherence From fredrik at pythonware.com Thu Jan 3 07:00:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 13:00:08 +0100 Subject: PyObject_CallObject code dump after calling 4 times In-Reply-To: References: Message-ID: grbgooglefan wrote: > I have a following C++ code which uses PyObject_CallObject to evaluate > expressions dynamically. This code sets the input parameters for the > function also dynamically. After calling this function 4 times (with > these shown values), PyObject_CallObject causes application to crash > in frame_dealloc. > 1) Can some one please help me understand why is this crash happening > in frame_dealloc & how to solve it? > 2) Is there anything wrong I am doing about incrementing or > decrementing the reference counts of the object passed to > PyObject_CallObject? if something crashes after a while, it's almost always a reference count error. > default: > printf("Unknown data type [%d] for %s\n",ndtyp,pEvalFunc- >> pExprVarsArray[nCtr].szVarName); > } what's val set to if this happens? > if(!val){ > ret = -1; > printf("Failed to convert %d %s to PyObject\n",ndtyp,pEvalFunc- >> pExprVarsArray[nCtr].szVarName); fflush(stdout); > Py_XDECREF(pTuple); > break; > } > PyTuple_SetItem(pTuple, nCtr, val); > Py_XDECREF(val); > } PyTuple_SetItem "steals" a reference http://docs.python.org/api/refcountDetails.html so you shouldn't DECREF val yourself. > // all variables are set, call Python function > Py_XINCREF(pTuple); this isn't necessary, and will (most likely) result in a leak. > PyObject *pResult = PyObject_CallObject(pEvalFunc- >> pPyEvalFunction,pTuple); > Py_XDECREF(pTuple); > > if(PyErr_Occurred()){ > PyErr_Print(); > } else { > char* plevel = NULL; > if(NULL != (plevel = PyString_AsString(pResult))){ > ret = 0; > sprintf(szEvalResult,"%s",plevel); shouldn't you check the size of plevel here, before copying it to szEvalResult? (and what's wrong with using strcpy to do the copy, btw?) From ask at me Thu Jan 17 14:25:20 2008 From: ask at me (alf) Date: Thu, 17 Jan 2008 13:25:20 -0600 Subject: how django discovers changed sources Message-ID: <18udndZmKMfMNhLanZ2dnUVZ_rzinZ2d@comcast.com> hi, I started playing with django and accidentally discovered that it restarts the server once a source file is touched. does it use some python's feature or just scans for changs on its one? sources? any idea? A. From paddy3118 at googlemail.com Tue Jan 22 13:34:08 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 22 Jan 2008 10:34:08 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Jan 22, 5:34 am, George Sakkis wrote: > On Jan 22, 12:15 am, Paddy wrote: > > > On Jan 22, 3:20 am, Alan Isaac wrote:> I want to generate sequential pairs from a list. > > <> > > > What is the fastest way? (Ignore the import time.) > > > 1) How fast is the method you have? > > 2) How much faster does it need to be for your application? > > 3) Are their any other bottlenecks in your application? > > 4) Is this the routine whose smallest % speed-up would give the > > largest overall speed up of your application? > > I believe the "what is the fastest way" question for such small well- > defined tasks is worth asking on its own, regardless of whether it > makes a difference in the application (or even if there is no > application to begin with). Hi George, You need to 'get it right' first. Micro optimizations for speed without thought of the wider context is a bad habit to form and a time waster. If the routine is all that needs to be delivered and it does not perform at an acceptable speed then find out what is acceptable and optimise towards that goal. My questions were set to get posters to think more about the need for speed optimizations and where they should be applied, (if at all). A bit of forethought might justify leaving the routine alone, or optimising for readability instead. - Paddy. From jitender001001 at gmail.com Wed Jan 16 08:29:08 2008 From: jitender001001 at gmail.com (jitender001001 at gmail.com) Date: Wed, 16 Jan 2008 05:29:08 -0800 (PST) Subject: plz help how to print python variable using os.system() Message-ID: <78444c3a-17dc-4912-aac7-39253648d86f@u10g2000prn.googlegroups.com> hi all i m new to python and i have a problem of printing python variable using os.system() in bash !/usr/bin/env python var = "/home/anonymous" os.system("echo $var) it is not working.. i want to print string using os.system() ....plz help From luca.colombi.it at gmail.com Thu Jan 17 07:32:32 2008 From: luca.colombi.it at gmail.com (Luca) Date: Thu, 17 Jan 2008 04:32:32 -0800 (PST) Subject: zip function for python Message-ID: <7cec1575-12d6-458c-9507-296e7d1ff330@e6g2000prf.googlegroups.com> Hi, Ive written this easy and fast function cause there it was impossible for me to find one that zip a directory without external libraries: import zipfile import sys import os def zipdir(zipPath,directory="./"): """Store the cdontent of directory to a zipPath file, if directory is not given stores the content of the current dir ( luca.colombi.it at gmail.com )""" directory=os.path.realpath(directory) zipObject = zipfile.ZipFile(zipPath, 'w') for root, dirs, files in os.walk(directory): for file in files: arcfile=root[len(os.path.commonprefix((directory, root))) +1:]+"/"+file #retrieves the inner relative file path filepath=os.path.join(root,file) zipObject.write(filepath,arcfile) zipObject.close() return zipObject #for optional further elaborations From steven.bethard at gmail.com Tue Jan 8 17:04:15 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 08 Jan 2008 15:04:15 -0700 Subject: Modules and descriptors In-Reply-To: References: Message-ID: Chris Leary wrote: > As I understand it, the appeal of properties (and descriptors in > general) in new-style classes is that they provide a way to > "intercept" direct attribute accesses. This lets us write more clear > and concise code that accesses members directly without fear of future > API changes. > > I love this feature of the language, but find that I still have to > call getter/setter methods of module instances. Since module > attributes are accessed by way of __dict__ and the module type has a > valid __mro__, why doesn't the descriptor protocol apply to module > instances? Because it doesn't apply to class *instances*. Module-level code gets executed roughly like this:: mod = ModuleType(...) exec module_code in mod.__dict__ So consider the similar code:: >>> class C(object): ... pass ... >>> c = C() >>> exec ''' ... def foo(self, *args): ... print self, args ... ''' in c.__dict__ A function ``foo`` has been added to the ``C`` instance. But *instances* don't invoke the descriptor protocol, so we the ``self`` parameter is not bound to the ``C`` instance:: >>> c.foo() Traceback (most recent call last): File "", line 1, in TypeError: foo() takes at least 1 argument (0 given) So the straightforward answer to your question is that module instances don't invoke the descriptor protocol because instances in general don't invoke the protocol (only classes do). The follow-up question is usually something like "well, can't we make module instances special and have them invoke the descriptor protocol?" Yes, in theory it would be possible, but it would break backwards compatibility in very bad ways. For example, every pure function you define at the module level would then become a bound method whenever it was accessed. Consider a simple module ``mod`` like:: def foo(bar): return 'baz(%s)' % bar If I try to use this module, and module instances invoke the descriptor protocol, then ``bar`` will always be bound to the module instance. That means we'd have to totally change how we right module level functions, and they'd have to start looking like this:: def foo(mod, bar): return 'baz(%s)' % bar That, of course, would break *tons* of existing code. STeVe From rewonka at gmail.com Tue Jan 15 19:24:02 2008 From: rewonka at gmail.com (rewonka at gmail.com) Date: Tue, 15 Jan 2008 16:24:02 -0800 (PST) Subject: Memory problem with threading Message-ID: <55f016fb-42f9-47d6-903a-a068f846b795@e10g2000prf.googlegroups.com> Hi! I made a string parser program, it has a main function and a working thread class. When it is running in 24h non-stop, the memory run out. I dont Know why. Do anybody know somekind of debugger that can i see what is eating the memory? Maybe there is a list or value or dictionary that is growing continually but i dont know which one. Maybe there is a program for that kind of debugging, what can monitoring the memory and values size in the memory. Or it is a sience fiction :) p.s.: sorry for my english Rew From sturlamolden at yahoo.no Fri Jan 11 13:40:54 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 11 Jan 2008 10:40:54 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <64a5ee48-cc7f-4e19-be34-012b68c537ae@v67g2000hse.googlegroups.com> On 9 Jan, 20:11, "dongie.ag... at gmail.com" wrote: > Is there a better way to do color tracking, or is Python just too slow > as an interpreted language to do any effective color tracking? The slowness stems from the use of k-means clustering on each frame. SciPy's clustering module used for the purpose is written in plain C. It is not Python that is slow. From bignose+hates-spam at benfinney.id.au Mon Jan 14 23:24:52 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 15:24:52 +1100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> <87ir1wf1wi.fsf@mulj.homelinux.net> Message-ID: <87k5mbd8bv.fsf@benfinney.id.au> Hrvoje Niksic writes: > Ben Finney writes: > > > Hrvoje Niksic writes: > >> __init__ *is* the closest equivalent to what other languages > >> would call a constructor. > > > > No. That would be '__new__', which actually constructs the > > instance, > > That's not what other OO languages (C++, Java) actually call a > constructor More fool them, then. It seems that the best referent for the term "constructor" is the thing that does the constructing and returns the result. -- \ "Imagine a world without hypothetical situations." -- Anonymous | `\ | _o__) | Ben Finney From tim at rileyphotographic.com Sat Jan 26 13:48:38 2008 From: tim at rileyphotographic.com (tim at rileyphotographic.com) Date: Sat, 26 Jan 2008 10:48:38 -0800 (PST) Subject: Programmer Need Message-ID: Hi, I have a program of about 300 lines of code that I wrote in AutoHotKeys. I am looking for someone who might be interested in making a little $ to help me bring this program into a mac compatable language. I can be reached at tim at rileyphotographic dot come From B.Ogryczak at addr.in.reply-to.invalid Sat Jan 19 09:01:44 2008 From: B.Ogryczak at addr.in.reply-to.invalid (Bart Ogryczak) Date: Sat, 19 Jan 2008 14:01:44 +0000 (UTC) Subject: SPARQL server in Python? Message-ID: Hi, I'm trying to migrate some R&D I've done with PHP and RAP[1] to Python. But I've got hard time finding Python RDF/SPARQL server. Most things I find are SPARQL clients. Do you know of a Python library, that could do the job? [1] http://sites.wiwiss.fu-berlin.de/suhl/bizer/rdfapi/ bart -- Set phasers on kill, fire at will. http://candajon.azorragarse.info/ http://azorragarse.candajon.info/ From antonio.chay at gmail.com Thu Jan 31 17:05:00 2008 From: antonio.chay at gmail.com (Antonio Chay) Date: Thu, 31 Jan 2008 14:05:00 -0800 (PST) Subject: char string 2 hex string Message-ID: Hello! I need to transform a string from a file into a hexadecimal representation, for example: "AAA" should be "414141" With perl I do this with: unpack("H*","AAA") And with python I got this: "".join([str(hex(ord(x)))[2:] for x in "AAA"]) But seems a little "weird" for me. Is there another way? Thanks in advance! From fetchinson at googlemail.com Sun Jan 13 03:08:45 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 13 Jan 2008 00:08:45 -0800 Subject: __init__ explanation please In-Reply-To: <00b801c8558e$13765be0$6701a8c0@hpinm> References: <47895d25$0$30708$4c368faf@roadrunner.com> <00b801c8558e$13765be0$6701a8c0@hpinm> Message-ID: Please keep discussion on the list...... > > I'm not sure if I understand your question correctly but maybe this will > > help: > > > > If you want code to be run upon creating an instance of your class you > > would use __init__. Most common examples include setting attributes on > > the instance and doing some checks, e.g. > > > > class Person: > > def __init__( self, first, last ): > > if len( first ) > 50 or len( last ) > 50: > > raise Exception( 'The names are too long.' ) > > self.first = first > > self.last = last > > > > And you would use your class like so, > > > > p1 = Person( 'John', 'Smith' ) > > p2 = Person( "Some long fake name that you don't really want to > > except, I don't know if it's really longer than 50 but let's assume it > > is", "Smith" ) > > # This last one would raise an exception so you know that something is not > > okay > > > > HTH, > > Daniel > > Is not the code run when I create an instance by assignement somewhere else? > > I take the point that one might want to check for potential exceptions > immediately, but most examples in the literature aren't doing that and don't > seem to be doing anything that would not be done when creating an instance > by assignment later somewhere. I'm missing something basic here. What do you mean by "create an instance by asignment somewhere else"? From service at metamodul.com Fri Jan 11 09:03:30 2008 From: service at metamodul.com (HajoEhlers) Date: Fri, 11 Jan 2008 06:03:30 -0800 (PST) Subject: Define installation directory for python Message-ID: Task: build and install python 2.5.1 on AIX 5.3 to /opt/python2.5 with the subdirectories: ./lib ./bin ./include ./man ./info a.s.o The ./bin ./man are created fine but for ./lib & ./include the structure is /opt/python2.5/lib/python2.5 /opt/python2.5/include/python2.5 where i would like to have only /opt/python2.5/lib and /opt/ python2.5/include Looking at the make install output i see that setup.py is using a option called --install-platlib but how do i set this option during configure ? Or do i have to patch the setup.py ? Any hints tia Hajo From lipun4u at gmail.com Fri Jan 25 07:28:43 2008 From: lipun4u at gmail.com (asit) Date: Fri, 25 Jan 2008 04:28:43 -0800 (PST) Subject: inode number in windows XP Message-ID: <3331a284-b786-42d5-bbe8-a764d59af920@c4g2000hsg.googlegroups.com> why this program shows ambiguous behavior ?? import os import stat import time #import types file_name=raw_input("Enter file name : ") print file_name, "information" st=os.stat(file_name) print "mode", "=>", oct(stat.S_IMODE(st[stat.ST_MODE])) print "type","=>", if stat.S_ISDIR(st[stat.ST_MODE]): print "DIReCTORY" elif stat.S_ISREG(st[stat.ST_MODE]): print "REGULAR" elif stat.S_ISLINK(st[stat.ST_MODE]): print "LINK" print "file size", "=>",st[stat.ST_SIZE] print "inode number", "=>",st[stat.ST_INO] print "device inode resides on", "=>",st[stat.ST_DEV] print "number of links to this inode", "=>",st[stat.ST_NLINK] print "last accessed", "=>", time.ctime(st[stat.ST_ATIME]) print "last modified", "=>", time.ctime(st[stat.ST_MTIME]) print "inode changed", "=>", time.ctime(st[stat.ST_CTIME]) i ran this program in Winows XP SP2 in python 2.5. From bg_ie at yahoo.com Thu Jan 24 11:28:47 2008 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Thu, 24 Jan 2008 08:28:47 -0800 (PST) Subject: Connecting to Sql Server from Python References: <56f14ea0-defb-445b-b957-7f379a000add@x69g2000hsx.googlegroups.com> <00bb6a7c-7e92-4ddf-af79-4ed6827f2a6b@s13g2000prd.googlegroups.com> Message-ID: <6c436619-0898-43ea-8320-0a2f4d9f610d@v46g2000hsv.googlegroups.com> On 24 Jan, 17:16, Mike Driscoll wrote: > On Jan 24, 9:44 am, bg... at yahoo.com wrote: > > > > > > > Hi, > > > I have an sql server from which I'd like to read and write to. The > > connection string is as follows - > > > "Data Source=localhost\SQLExpress;Initial Catalog=Test;Integrated > > Security=True;Pooling=False" > > > Other properties as they appear in Visual Studio 2005 include - > > > Data Provider: .NET Framework Data Provider for SQL Server > > State: Open > > Type: Microsoft SQL Server > > > So my question is, how might I connect to my Test Catalog and update > > data within its tables via perl, > > > Thanks, > > > Barry. > > If you want to do this in Perl, then why are you asking on a Python > list? In Python, there are many ways to accomplish this task. Take a > look at SQLAlchemy, SQLObject, pymssql or the adodb package. > > http://pymssql.sourceforge.net/www.sqlalchemy.orghttp://www.sqlobject.org/http://phplens.com/lens/adodb/adodb-py-docs.htm > > Mike- D?lj citerad text - > > - Visa citerad text - Woops, I ment Python... From asmodai at in-nomine.org Fri Jan 4 10:34:41 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jan 2008 16:34:41 +0100 Subject: Memory Leaks and Heapy In-Reply-To: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> Message-ID: <20080104153441.GO82115@nexus.in-nomine.org> -On [20080104 16:11], Yaakov Nemoy (loupgaroublond at gmail.com) wrote: >I'm trying to plug some memory leaks in a TurboGears program. We (the >Fedora Project) have a few apps in Turbogears in infrastructure that >all seem to be running into the same issues in a variety of >configurations. Hopefully when I get to the cause of this in one app, >Smolt, we can fix the others too. [snip] >A couple of developers have mentioned that python might be fragmenting >its memory space, and is unable to free up those pages. How can I go >about testing for this, and are there any known problems like this? >If not, what else can I do to look for leaks? As various people pointed out to me: http://wingolog.org/archives/2007/11/27/reducing-the-footprint-of-python-applications That might help. Aside from that (rant), I seriously dislike Python's memory management and even more the fairly arcane ways people have to go about debugging/troubleshooting some 600 MB to 2-3 GB(!) of resident memory use by Python. Personally I consider this the weakest point of Python. Given the fact there is a garbage collector this sort of keeping track of memory seems a bit contradictory to the concept of garbage collection. (And yes, I am investigating this and also how to get it leaner and better.) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Speak the sweet truth... From hardcoded.software at gmail.com Thu Jan 24 13:55:35 2008 From: hardcoded.software at gmail.com (Virgil Dupras) Date: Thu, 24 Jan 2008 10:55:35 -0800 (PST) Subject: Test driven development References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> <53bae618-0a57-470e-b698-3f936ef7c0e7@s12g2000prg.googlegroups.com> Message-ID: <98f3ca4c-a7f0-4707-b09d-8012b86de96b@x69g2000hsx.googlegroups.com> On Jan 24, 1:30?pm, Roel Schroeven wrote: > Virgil Dupras schreef: > > > I know what you mean by top-down vs. bottom-up and I used to have the > > same dilemma, but now I would tend to agree with Albert. Your issue > > with top-down or bottom-up is not relevant in TDD. The only thing that > > is relevant is to reach your current milestone as soon as possible, > > without caring about what you're going to do in the milestone after > > that. > > > Not so long ago, I took the "bottom-up" approach to TDD, which was a > > mistake because it leads to over-engineering (the end result is not so > > bad since it's over-engineering that has good test coverage :) ) > > I don't regularly use TDD yet, and one of the reasons is that in many > cases I'm unsure exactly how to use it in practice. I read "Test-driven > development - A practical guide" (and I should re-read), but I feel it > doesn't help my much in everyday situations. Somehow the examples in the > book don't match very well with how I code (and I admit that perhaps the > problem is more with me than with the book). > > One of the problems I have is something like what Andy describes: I need > a function spam(), so I write tests for it. Then I start implementing > the function and see that I need to write functions ham() and eggs(). > Should I write unit tests for ham() and eggs(), or do I rely on the > tests for spam()? If I don't write them, doesn't that make it more > difficult to find out why the tests for spam() fail? > > Speaking about over-engineering, when I do TDD along the lines of the > book I mentioned, I always feel that I'm over-engineering the tests. It > all feels very unnatural though I'm convinced it shouldn't be like that. > > Can someone suggest other books to read about the subject, ideally > something more focused on Python or C++ rather than Java? > > -- > The saddest aspect of life right now is that science gathers knowledge > faster than society gathers wisdom. > ? ?-- Isaac Asimov > > Roel Schroeven I also have a book about TDD and it never was of much help either. All techniques come from the initial workflow: Red - Green - Refactor. The problem you describe is a tricky problem. The way I feel it should be solved is: - Write spam() (and its tests, of course). - Then, at some point, in the re-factor phase, you split extract the function ham() from spam(). Alright, do it and keep the tests as is (all on spam()). - Then at some other point, you extract eggs(). same thing. - After a while (I don't know, 3 or 4 milestones), when it becomes clear that ham() and eggs() are there to stay, start moving your tests away from spam() by just mocking ham() and eggs() and just make sure that spam() call them with the right arguments. The tests you had on spam() that were relevant to ham() and eggs() are just performed directly on them now. What I've been saying in my other message is: Don't do that too early, because if it turns out that ham() and eggs() is not the optimal way to do it, but foo() bar() and baz() is, it is *much* easier to do a safe re-factoring with high level tests. From george.sakkis at gmail.com Wed Jan 23 14:06:44 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 23 Jan 2008 11:06:44 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: <90cfc1f7-8792-4e28-9466-6a1bf77c87c5@q77g2000hsh.googlegroups.com> On Jan 23, 1:30 pm, Paddy wrote: > I've heard quality expressed as "meeting requirements", which I think > is apt. Falling short of requirements everyone knows doesn't give a > quality result, but equally 'exceeding' requirements also detracts > from quality (as does not knowing your requirements). > It is good to learn optimization techniques, which may be part of what > you are saying, but part of that is learning when it pays to apply > them and/or search for them; and when it does not. The OP wanted an answer to a simple question, not a lecture on good software engineering principles. This whole subthread reminds of a movie (can't remember which) where someone asks his buddy in the stadium "what do you want?". His buddy gets it wrong and embarks in a long diatribe of what he wants in life now, what he wanted as a child, what's the meaning of one's life and so on. After a couple of minutes the guy cuts him and asks again: - "Man, what do you want, burger or hot dog?" - "Oh, a hot dog". Sometimes you want to see the tree right in front of you, not the whole damn forest. George From BjornSteinarFjeldPettersen at gmail.com Mon Jan 14 17:05:21 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Mon, 14 Jan 2008 14:05:21 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> Message-ID: On Jan 14, 1:41 pm, Richard Szopa wrote: > On Jan 13, 3:31 pm, thebjorn > wrote: > > > They do, except for when it comes to what super(..) returns. It isn't > > really an object in the sense that they're presented in the tutorial, > > but rather a sort of proxy to the methods in the ancestor classes of > > the concrete object (self), relative to the current method's class. I > > can't imagine that sentence would ease any confusion however, suffice > > it to say that you have to call getattr(super(..), 'name') instead of > > super(..).__getattr__('name') and you have to call super(..).__len__() > > instead of len(super(..)) -- I can't imagine that lessens any > > confusion either :-/ > > Surprisingly, I think your first sentence *does* make something more > clear. Let me check if I understand it right: when we call a method on > super(Foo, self) it is as if we were calling call-next-method in > Common Lisp or Dylan I don't remember if CLOS was changed to use C3 Linearization also, but the concept came from Dylan (http://www.webcom.com/haahr/dylan/ linearization-oopsla96.html) and that's what is implemented in Python. [...] > However, there's one piece that doesn't completely fit to the puzzle: > why does getattr work? The help says: > > getattr(...) > getattr(object, name[, default]) -> value > > Get a named attribute from an object; getattr(x, 'y') is > equivalent to x.y. When a default argument is given, it > is returned when the attribute doesn't exist; without it, > an exception is raised in that case. > > Does it work on the basis that "getattr(x, 'y') is equivalent to x.y"? > What is then a "named attribute for an object" in Python? It seems not > to be equivalent to the value of the item whose name is 'y' in the > object's class __dict__... Conceptually, x.y is always "get the y attribute of x" and the same as getattr(x, 'y'). Depending on the type of x and y, and your familiarity with Python internals, what actually happens during a lookup might be surprising. In the vast majority of cases however, x.y is equivalent to one of x.__dict__['y'] type(x).__dict__['y'] but if you're a language geek like me, you might be excited that in some cases it is type(x).__dict__['y'].__get__(x, type(x)) which says you get the value of x.y by calling y and passing x as an argument -- if you know CLOS you'll recognize that it's a primitive multi-method call. (there are some other special cases too, although not as exciting ;-) Much more detail can be found in Raymond's paper on descriptors (http://users.rcn.com/python/download/Descriptor.htm) and Michele's paper on super (http://www.phyast.pitt.edu/~micheles/python/ super.html). -- bjorn From http Thu Jan 17 19:13:52 2008 From: http (Paul Rubin) Date: 17 Jan 2008 16:13:52 -0800 Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> Message-ID: <7xy7aong73.fsf@ruckus.brouhaha.com> George Sakkis writes: > And if the iterables don't necessarily support len(), here's a more > general solution: Not trying to pick on you personally but there's this disease when a newbie comes with a basically simple question (in this case, how to solve the problem with ordinary lists) and gets back a lot of complex, overly general "graduate level" solutions. There's a humorous set of Haskell examples that takes this to extremes: http://www.willamette.edu/~fruehr/haskell/evolution.html From nospam at invalid.com Fri Jan 11 12:57:18 2008 From: nospam at invalid.com (Jack) Date: Fri, 11 Jan 2008 17:57:18 GMT Subject: Using a proxy with urllib2 References: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> <87ir21o8sj.fsf@merkury.smsnet.pl> Message-ID: <26Ohj.3530$jJ5.1972@newssvr11.news.prodigy.net> Rob, I tried your code snippet and it worked great. I'm just wondering if getopener( ) call is lightweight so I can just call it in every call to fetchurl( )? Or I should try to share the opener object among fetchurl( ) calls? Thanks, Jack "Rob Wolfe" wrote in message news:87ir21o8sj.fsf at merkury.smsnet.pl... > Try this: > > > import urllib2 > > def getopener(proxy=None): > opener = urllib2.build_opener(urllib2.HTTPHandler) > if proxy: > proxy_support = urllib2.ProxyHandler({"http": "http://" + proxy}) > opener.add_handler(proxy_support) > return opener > > def fetchurl(url, opener): > f = opener.open(url) > data = f.read() > f.close() > return data > > print fetchurl('http://www.python.org', getopener('127.0.0.1:8081')) > > > HTH, > Rob From kyosohma at gmail.com Tue Jan 8 17:14:28 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 8 Jan 2008 14:14:28 -0800 (PST) Subject: Newbie question: Classes References: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com> Message-ID: <061b53ed-7e89-4afb-96f8-bb4d28320b47@v67g2000hse.googlegroups.com> On Jan 8, 3:31 pm, "Daniel Fetchinson" wrote: > > Basically, I have created a program using tkinter without using any class > > structure, simply creating widgets and functions (and finding ways around > > passing variables from function to function, using global variables etc). > > The program has become rather large ( lines?) I am trying to now put it into > > a class structure, because I hear it is easier to handle. > > > So basically, I put all the stuff into a class, making the widgets in the > > "def __init__(self, root)" (root being my Tk() ) and then I have had to put > > a "self." in front of any instance of any variable or widget. Is this right? > > it seems like nothing is any easier (except having variables locally). Is > > this right? Should I be creating more classes for different things or what? > > Use the method that works best for you. If you like the procedural > approach more then don't worry about being object oriented. The good > thing is that python is multi-paradigm so if custom objects don't make > your life easier then just forget about them :) One great benefit to classes is the ability to take a generic class and then subclass it. Or the ability to instantiate various objects from one class. Say you have a dog class. If you pass in the correct data, you can instantiate a dalmatian, a Labrador or a mutt. They're all dogs, but their all different too. Enough of my babbling. Check out the following links for more info: http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm http://www.diveintopython.org/object_oriented_framework/defining_classes.html http://docs.python.org/tut/node11.html Mike From yantao at telus.com Sun Jan 27 00:32:40 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 05:32:40 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: <13po55nc0q0s06@corp.supernews.com> References: <13po55nc0q0s06@corp.supernews.com> Message-ID: You didn't understand my question, but thanks any way. Yes, it is true that %s already support unicode, and I did not contradict that. But it counts the number of bytes instead of characters, and makes things like %-20s out of alignment. If you don't understand my assertion, please don't argue back and I am only interested in answers from those who are qualified. ============================================================== "Steven D'Aprano" wrote in message news:13po55nc0q0s06 at corp.supernews.com... > On Sun, 27 Jan 2008 04:06:45 +0000, Peter Pei wrote: > >> I probably should mention that what I want is to make all parts of the >> string aligned, and look like table. I am not looking for other ways to >> make it table-alike, but only interested in making % work with unicode >> -counting characters not bytes... > > % already works with unicode. Just give it unicode arguments: > > >>>> print u"x y z %s 1 2 3" % u"Les mis?rables" > x y z Les mis?rables 1 2 3 > > > -- > Steven From laurent.pointal at laposte.net Thu Jan 17 15:23:48 2008 From: laurent.pointal at laposte.net (Laurent Pointal) Date: 17 Jan 2008 20:23:48 GMT Subject: Importing java within python References: Message-ID: <478fb953$0$874$ba4acef3@news.orange.fr> Le Thu, 17 Jan 2008 08:36:59 -0800, Henry Chang a ?crit?: > www.jython.org > > On Jan 17, 2008 8:06 AM, Osthaus, Christopher (Mission Systems) > wrote: >> >> >> Hi All, >> >> This is an easy one - I'm new to Python and working on a script where I >> need to use some java swing classes. I'm running Python on Windows. >> >> I've got an import statement that looks something like: >> >> from java.lang import System >> from javax.swing import JPasswordField from javax.swing import >> JOptionPane >> >> >> How do I get Python to recognize the java module? I assume I need to >> set one of my environment variables? I realize this is probably very >> obvious but I can't seem to figure it out :) >> >> Thanks everyone... >> -- >> http://mail.python.org/mailman/listinfo/python-list >> To complement Henry Chang reply, you can also take a look at: http://jpype.sourceforge.net/ (Java To Python Integration) http://jepp.sourceforge.net/ (Java Embeded Python) See my other Python/Java links at http://www.limsi.fr/Individu/pointal/python.html#liens-intautlang-java A+ Laurent. -- Laurent POINTAL - laurent.pointal at laposte.net From davidhuebel at gmail.com Mon Jan 14 20:03:43 2008 From: davidhuebel at gmail.com (grackle) Date: Mon, 14 Jan 2008 17:03:43 -0800 (PST) Subject: module naming conventions References: <7f39199a-3334-4bcc-a424-5102f042ed01@1g2000hsl.googlegroups.com> <87zlv8dnya.fsf@benfinney.id.au> <6a53a14a-8f7c-4b6b-986f-48c7698f679f@v29g2000hsf.googlegroups.com> <8763xwdj9c.fsf@benfinney.id.au> Message-ID: <972e17b4-2d1a-43d6-8382-21585b0fe786@v29g2000hsf.googlegroups.com> On Jan 14, 6:28 pm, Ben Finney wrote: > grackle writes: > What do you mean by "top-level module", and "the same top-level name"? > Do you mean "the same fully-qualified name"? If two modules are in > separate places in the hierarchy, they will have different > fully-qualified names. I mean that if I worked at Google (which I don't) and developed google.search and google.officeapps, they would share the same top- level name "google". Because of this, if I wanted to use the two in the same program, they would have to be deployed at the same point in the source path: if I deployed one set of source at src1/google/ search/etc. and the other at src2/google/officeapps/etc. and added src1/ and src2/ to my application's Python source path, one of them would be found and the other not. (Essentially I'd be trying to create two different modules, both named "google", which is nonsense.) I would have to put them in the same source directory and merge the two google/__init__.py files together. I might as well admit that I already made the same mistake in reverse, using a single top-level module for my application, which I now want to split into a group of core application modules and one or more optional, separately-deployed packages. Since I screwed up the first time, I figured I'd get advice before attempting to rectify the situation. My next (slightly more considered, possibly just as naive) impulse is to turn google.search and google.officeapps into google_search and google_officeapps, thereby avoiding name clashes with internal or external projects. (It feels dangerous, not to mention presumptuous, to put generic names like "search" and "officeapps" in the global namespace.) > Release your package as free software on the Cheeseshop > . If the name you want is already > taken, pick one that will help users distinguish yours from the > existing one. Unfortunately, my company thinks it's their software and not mine :-) -David From elind at spamcop.net Mon Jan 14 23:50:00 2008 From: elind at spamcop.net (Erik Lind) Date: Mon, 14 Jan 2008 23:50:00 -0500 Subject: A question about event handlers with wxPython Message-ID: <478c3bb2$0$5150$4c368faf@roadrunner.com> I'd appreciate any pointer on a simple way to tell within an event handler where the event came from. I want to have "while" condition in a handler to stop or change processing if an event occurs from some other button click. Trying to bind more than one event to the same handler still doesn't tell me where the event came from in a basic bind. Is there an argument I can put in the bind so as to identify the source of the event in the event argument? . From thermostat at gmail.com Wed Jan 16 13:07:59 2008 From: thermostat at gmail.com (Dan) Date: Wed, 16 Jan 2008 10:07:59 -0800 (PST) Subject: Interesting Thread Gotcha References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> Message-ID: <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> On Jan 16, 11:06 am, "Diez B. Roggisch" wrote: > Hendrik van Rooyen wrote: > > "Dan" wrote: > > >> >>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) > > >> Needs to be > >> >>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) > > >> Commas are important! > > >> -Dan > > > Absolutely! - well spotted! > > > As the first correct respondent, you win the freedom to spend a week in > > Naboomspruit at your own expense. > > > It would have been nice, however, to have gotten something like: > > > TypeError - This routine needs a tuple. > > > instead of the silent in line calling of the routine in question, > > while failing actually to start a new thread. > > You can't prevent the silent inline-calling - otherwise, how would you do > this: > > def compute_thread_target(): > def target(): > pass > return target > > thread.start_new_thread(compute_thread_target()) > > Of course start_new_thread could throw an error if it got nothing callable > as first argument. No idea why it doesn't. > > Diez Of course, in his case, having start_new_thread throw an error wouldn't have helped, since he went into an infinite loop while evaluating the parameters for start_new_thread. Would it be possible to have pychecker (or some such) warn that there is an insufficient parameter count to start_new_thread? I guess that would require knowing the type of thread. . . -Dan From google at mrabarnett.plus.com Wed Jan 30 21:27:06 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 30 Jan 2008 18:27:06 -0800 (PST) Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> <60cai8F1qgh3aU1@mid.uni-berlin.de> <15d16017-3b43-45a8-86b9-93203972f813@u10g2000prn.googlegroups.com> Message-ID: <3c3d8f03-1a69-4fbe-8979-9aae458ab46c@u10g2000prn.googlegroups.com> On Jan 31, 1:09 am, George Sakkis wrote: > On Jan 30, 5:03 pm, Marc 'BlackJack' Rintsch wrote: > > > On Wed, 30 Jan 2008 15:29:45 +0100, Wildemar Wildenburger wrote: > > > Gerardo Herzig wrote: > > >> I will use genital().extend(), thats for shure ^^ > > > > Well, you never go wrong with apply(genital(), females), do you? > > > `apply()` is deprecated. And ``genital(*females)`` looks a bit odd. :-) > > Well, that use case alone is enough to convince anyone that apply > should stay :-) > The original had genital(), so that would be genital()(*females). But what is genital() anyway? A factory? From paddy3118 at googlemail.com Sat Jan 5 01:37:16 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 4 Jan 2008 22:37:16 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> Message-ID: <33417662-8246-4950-9b86-265aa1c63c69@c23g2000hsa.googlegroups.com> On Jan 4, 7:55 pm, c... at mailinator.com wrote: > Hello, > This is a question for the best method (in terms of performance > only) to choose a random element from a list among those that satisfy > a certain property. > > This is the setting: I need to pick from a list a random element > that satisfies a given property. All or none of the elements may have > the property. Most of the time, many of the elements will satisfy the > property, and the property is a bit expensive to evaluate. Chance of > having the property are uniform among elements. > > A simple approach is: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > > Returns None if no element has the property > ''' > random.shuffle(a_list) > for i in a_list: > if property(i): return i > > but that requires to shuffle the list every time. > > A second approach, that works if we know that at least one element of > the list has the property, is: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > > Loops forever if no element has the property > ''' > while 1: > i=random.choice(a_list) > if property(i): return i > > which is more efficient (on average) if many elements of the list have > the property and less efficient if only few elements of the list has > the property (and goes crazy if no element has the property) > > Yet another one: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > ''' > b_list=[x for x in a_list if property(x)] > try: > return random.choice(b_list) > finally: return None > > but this one checks the property on all the elements, which is no > good. > > I don't need strong random numbers, so a simple solution like: > import random > globalRNG=random.Random() > > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > > Works only if len(a_list)+1 is prime: uses Fermat's little theorem > ''' > a=globalRNG(1,len(a_list)) > ind=a > for i in xrange(len(a_list)): > x=a_list[a-1] > if property(x):return x > ind*=a > > but this works only if len(a_list)+1 is prime!!! Now this one could be > saved if there were an efficient method to find a prime number given > than a number n but not very much greater... > > Any other ideas? Thanks everybody Caching might help. If random_pick is called several times with the same list(s) then cache the result of [property(i) for i in a_list] against a_list. If random_pick is called several times with list(s) whith multiple instances of list items then cache property(i) against i for i in a_list . You could do both. You might investigate wether property(i) could be implemented using a faster algorithm, maybe table lookup, or interpolation from initial table lookup. - Paddy. From aspineux at gmail.com Fri Jan 4 22:39:13 2008 From: aspineux at gmail.com (aspineux) Date: Fri, 4 Jan 2008 19:39:13 -0800 (PST) Subject: How a smart editor could make "Postfix type declarations PEP3117" in Python3000 more readable Message-ID: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> Hi I read the PEP 3117 about the new "Postfix type declarations" in Python3000. THIS PEP as been REJECTED ! But ... The notation in the PEP is very ugly ! This make python code more difficult to read! Anyway when I switched to python (from C, C++, ..), I suffered a lot of the untyped python variables. And I think this is a good idea to include typing in python. Then I get this idea: The editor could hide the typing notation, just displaying hint ! It could also auto-complete the type of any variable having already a type in the current function, and underline untyped variable or variable having multiple type inside the function. Just an idea ! Alain Spineux Happy new year. From gagsl-py2 at yahoo.com.ar Tue Jan 1 13:58:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Jan 2008 16:58:45 -0200 Subject: Some specific exec behavior ? References: <477A88D9.4090708@gmail.com> Message-ID: En Tue, 01 Jan 2008 16:39:21 -0200, Stef Mientki escribi?: > I find 2 strange behaviors in exec-function, > and I can't find anything in the documentation. > (Python 2.4.3 Enthought edition) > > 1. A function definition may not span more than 1 line, e.g. > This generates an exception: > def _func (x,y): > return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) > > while this works correct: > def _func (x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) > > 2. an emtpy line at the end also generates an exception > > Is this behavior correct ? > where should I find information about it ? It's correct; source lines must be separated by '\n' only (NOT '\r\n' as in a Windows text file) and the last line must end in '\n'. It's documented, but under the compile() built-in function: http://docs.python.org/lib/built-in-funcs.html; perhaps the docs for exec should refer there. -- Gabriel Genellina From http Sun Jan 27 06:01:05 2008 From: http (Paul Rubin) Date: 27 Jan 2008 03:01:05 -0800 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> <7xy7acsx2l.fsf@ruckus.brouhaha.com> <8ddebd68-43dc-4320-86e1-887aadff4af3@d70g2000hsb.googlegroups.com> <7xmyqs722t.fsf@ruckus.brouhaha.com> <13pnbp9l8lk1j8b@corp.supernews.com> <8a699886-24f7-485e-a87f-90518e9ff536@l32g2000hse.googlegroups.com> Message-ID: <7xzlur353i.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > The final sum: the Psyco version is almost 40 times faster than the > Python version, and just 2.8 times slower than the D version, and 3.4 > times slower than a C version (that doesn't use too many pointer > tricks). I think this is good enough. I can't help wishing that psyco could do as good a job with the simpler expressions of that function. I'll have to see what JHC does. From bruno.desthuilliers at gmail.com Sat Jan 12 11:57:35 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jan 2008 08:57:35 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <13of60ikspqhh06@corp.supernews.com> Message-ID: <8ad434bb-4213-417c-8be1-b84faf62c7ed@q39g2000hsf.googlegroups.com> On 11 jan, 17:23, Ed Jensen wrote: > Bruno Desthuilliers wrote: > > fact 1: CPython compiles source code to byte-code. > > fact 2: CPython executes this byte-code. > > fact 3: Sun's JDK compiles source code to byte-code. > > fact 4: Sun's JDK executes this byte-code. > > > Care to prove me wrong on any of these points ? Don't bother: you can't. > > So my first assertion that "CPython is compiled to byte-code, which is > > then executed by a VM" is true, and since the same assertion also stands > > for Java (ie: sun's JDK), then the "just like" qualifier is true too. > > Period. > > #2 and #4 are wrong (or, at best, misleading). Here, I'll fix them > for you: > > Fact 2: CPython interprets the bytecode. > > Fact 4: Sun's JVM does some interpretation of the bytecode, but also > compiles some of the bytecode to native code and executes the > resulting native code. > > These distinctions can be important and it's intellectually dishonest > to gloss over them. These distinctions are important if the context is the VM implementation, which is *obviously* not the case here. FWIW, I you had spent a bit more time reading the remaining of the discussion with the OP, I do clearly mention this distinction. So please get a life and keep your comment about "intellectual dishonesty" where they belong. From arnodel at googlemail.com Tue Jan 22 11:09:01 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 08:09:01 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: On Jan 22, 1:19?pm, Alan Isaac wrote: > I suppose my question should have been, > is there an obviously faster way? > Anyway, of the four ways below, the > first is substantially fastest. ?Is > there an obvious reason why? Can you post your results? I get different ones (pairs1 and pairs2 rewritten slightly to avoid unnecessary indirection). ====== pairs.py =========== from itertools import * def pairs1(x): return izip(islice(x,0,None,2),islice(x,1,None,2)) def pairs2(x): xiter = iter(x) while True: yield xiter.next(), xiter.next() def pairs3(x): for i in range( len(x)//2 ): yield x[2*i], x[2*i+1], def pairs4(x): xiter = iter(x) return izip(xiter,xiter) def compare(): import timeit for i in '1234': t = timeit.Timer('list(pairs.pairs%s(l))' % i, 'import pairs; l=range(1000)') print 'pairs%s: %s' % (i, t.timeit(10000)) if __name__ == '__main__': compare() ===================== marigold:python arno$ python pairs.py pairs1: 0.789824962616 pairs2: 4.08462786674 pairs3: 2.90438890457 pairs4: 0.536775827408 pairs4 wins. -- Arnaud From tjreedy at udel.edu Wed Jan 16 15:12:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Jan 2008 15:12:53 -0500 Subject: import from question References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com><478d04d4$0$26042$88260bb3@free.teranews.com> <87tzleb2st.fsf@benfinney.id.au> Message-ID: "Ben Finney" wrote in message news:87tzleb2st.fsf at benfinney.id.au... | Tobiah writes: | | > This is a little surprising. So "from mod import *" really copies | > all of the scalars into new variables in the local namespace. 'Scalar' is not a Python term. Neither is 'object pointer' really, except in respect to the CPython implementation. | No. Nothing is copied. All the objects (remembering that in Python, | *everything* is an object) created by the code in module 'mod' are | given names in the current namespace. To amplify, 'from mod import *' is, I believe, more or less equivalent to import mod for name in mod.__all__ exec "%s = mod.%s" % name,name del mod except, of course, that the imported module would not actually be bound to 'mod' (and need deleting) so that there is no conflict with mod containing the name 'mod'. From beema.shafreen at gmail.com Thu Jan 3 09:09:06 2008 From: beema.shafreen at gmail.com (Beema shafreen) Date: Thu, 3 Jan 2008 19:39:06 +0530 Subject: CSV Message-ID: Hi all, I have written a script to parse a CSV file: import csv def get_lines(fname): fhandle = csv.reader(open(fname,"rb")) for line in fhandle: while fhandle.next()[0] == "prot_hit_num": continue for row in fhandle: print row result = get_lines("file.csv") print result I need to print the data from "prot_hit_num" and before the line "peptide sequence". I am able to print the whole from "prot_hit_num" to the end of the file but I need to break before line "peptide sequence........". How should i do this. -------------- next part -------------- An HTML attachment was scrubbed... URL: From neumann at wu-wien.ac.at Thu Jan 31 19:00:47 2008 From: neumann at wu-wien.ac.at (neumann at wu-wien.ac.at) Date: Thu, 31 Jan 2008 16:00:47 -0800 (PST) Subject: object vs class oriented -- xotcl References: <2dfb6cd3-921a-4692-9627-d35bda40a93e@v29g2000hsf.googlegroups.com> Message-ID: <63fecd10-4d04-40b3-9de4-139a87dcae90@q39g2000hsf.googlegroups.com> On 29 Jan., 19:22, William Pursell wrote: > I > believe "per object mixin" is the correct > term for such an animal. The first several google > hits on that phrase all reference xotcl, so I'm > not sure if that is an xotcl inspired vocabulary > that isn't really standard. well, it depends, what you mean by "standard" when it comes to mixins. We coined the term to distinguish between per object and per class mixins, where the per objects mixins have much in common with the decorator design pattern (see e.g. http://nm.wu-wien.ac.at/research/publications/xotcl-objpattern.pdf) We have as well a paper showing that the approach based on intersection classes does not scale well, especially when multiple supplemental classes should be mixed in, and some of the behavior should be as well mixed out (see e.g. section 3.3 in http://nm.wu-wien.ac.at/research/publications/xotcl-mixin.pdf) If you are interested in the matter, we have as well a recent paper http://nm.wu-wien.ac.at/research/publications/b613.pdf providing declarative semantics for mixins, and there is many more related papers in the publications section of media.wu-wien.ac.at From asmodai at in-nomine.org Tue Jan 8 03:33:02 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 09:33:02 +0100 Subject: Look for a string on a file and get its line number In-Reply-To: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> Message-ID: <20080108083302.GD75977@nexus.in-nomine.org> -On [20080108 09:21], Horacius ReX (horacius.rex at gmail.com) wrote: >I have to search for a string on a big file. Once this string is >found, I would need to get the number of the line in which the string >is located on the file. Do you know how if this is possible to do in >python ? (Assuming ASCII, otherwise check out codecs.open().) big_file = open('bigfile.txt', 'r') line_nr = 0 for line in big_file: line_nr += 1 has_match = line.find('my-string') if has_match > 0: print 'Found in line %d' % (line_nr) Something to this effect. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ If you think that you know much, you know little... From ryszard.szopa at gmail.com Mon Jan 14 18:53:48 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Mon, 14 Jan 2008 15:53:48 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> Message-ID: On Jan 14, 11:05 pm, thebjorn wrote: > I don't remember if CLOS was changed to use C3 Linearization also, but > the concept came from Dylan (http://www.webcom.com/haahr/dylan/ > linearization-oopsla96.html) and that's what is implemented in Python. The Common Lisp ANSI standard is from 1994, and the article you cite is from 1996, which strongly suggests C3 linearization wasn't included in CLOS. The most important difference between CLOS and C3 linearization AFAIK is that the latter enforces monotonicity, while the former doesn't. Of course, it shouldn't be very difficult to implement the C3 behavior in Common Lisp using the de facto standard MetaObject Protocol. (Nb. Dylan was such a nice language... It's a pity it is practically dead right now.) > but if you're a language geek like me, you might be excited that in > some cases it is > > type(x).__dict__['y'].__get__(x, type(x)) > > which says you get the value of x.y by calling y and passing x as an > argument -- if you know CLOS you'll recognize that it's a primitive > multi-method call. (there are some other special cases too, although > not as exciting ;-) Yeah, I also feel the excitement, so probably I am a language geek too ;-). However, this is still quite far away from full fledged multimethods. (OTOH trying to get something more from these primitive multimethods by abusing __get__ looks kind of tempting ;-)) Regards, -- Richard From sipickles at hotmail.com Fri Jan 18 13:51:19 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Fri, 18 Jan 2008 18:51:19 +0000 Subject: Pythonland documentation Message-ID: Hi I am new to python (fairly) but can't stop pythonning. c++ seems so far away now.... from here it looks like a horrid scribble :) Anyway.... my question is really about doc tools. I've been used to doxygen in c++ land, and although it makes a reasonable stab with a python project in java mode, the output is a bit messy. Can any one suggest a more tailored tool? or do I risk a flamewar? :) Thanks SiPi -- Linux user #458601 - http://counter.li.org. From sromero at gmail.com Thu Jan 10 03:07:35 2008 From: sromero at gmail.com (Santiago Romero) Date: Thu, 10 Jan 2008 00:07:35 -0800 (PST) Subject: Converting a bidimensional list in a bidimensional array References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> <13obak214p9h8cc@corp.supernews.com> Message-ID: > C:\> \python25\python -m -s :-) Thanks a lot :-) From paddy3118 at googlemail.com Wed Jan 23 13:30:04 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 23 Jan 2008 10:30:04 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Jan 23, 2:32 am, George Sakkis wrote: > On Jan 22, 1:34 pm, Paddy wrote: > > > > > On Jan 22, 5:34 am, George Sakkis wrote: > > > > On Jan 22, 12:15 am, Paddy wrote: > > > > > On Jan 22, 3:20 am, Alan Isaac wrote:> I want to generate sequential pairs from a list. > > > > <> > > > > > What is the fastest way? (Ignore the import time.) > > > > > 1) How fast is the method you have? > > > > 2) How much faster does it need to be for your application? > > > > 3) Are their any other bottlenecks in your application? > > > > 4) Is this the routine whose smallest % speed-up would give the > > > > largest overall speed up of your application? > > > > I believe the "what is the fastest way" question for such small well- > > > defined tasks is worth asking on its own, regardless of whether it > > > makes a difference in the application (or even if there is no > > > application to begin with). > > > Hi George, > > You need to 'get it right' first. > > For such trivial problems, getting it right alone isn't a particularly > high expectation. Hi George, not 'alone' but 'first'. And it is the ultimate expectation. Who wants to recieve wrong software? > > > Micro optimizations for speed > > without thought of the wider context is a bad habit to form and a time > > waster. > > The OP didn't mention anything about the context; for all we know, > this might be a homework problem or the body of a tight inner loop. Thats why I thought to ask about the context. > There is this tendency on c.l.py to assume that every optimization > question is about a tiny subproblem of a 100 KLOC application. Without > further context, we just don't know. Again, I did not assume; I asked about the wider context. I too don't believe your statement about c.l.p. > > > If the routine is all that needs to be delivered and it does not > > perform at an acceptable speed then find out what is acceptable > > and optimise towards that goal. My questions were set to get > > posters to think more about the need for speed optimizations and > > where they should be applied, (if at all). > > I don't agree with this logic in general. But you don't defend yourself well by such a far-fetched example. I've heard quality expressed as "meeting requirements", which I think is apt. Falling short of requirements everyone knows doesn't give a quality result, but equally 'exceeding' requirements also detracts from quality (as does not knowing your requirements). It is good to learn optimization techniques, which may be part of what you are saying, but part of that is learning when it pays to apply them and/or search for them; and when it does not. - Paddy. > Just because one can solve a > problem by throwing a quick and dirty hack with quadratic complexity > that happens to do well enough on current typical input, it doesn't > mean he shouldn't spend ten or thirty minutes more to write a proper > linear time solution, all else being equal or at least comparable > (elegance, conciseness, readability, etc.). Of course it's a tradeoff; > spending a week to save a few milliseconds on average is usually a > waste for most applications, but being a lazy keyboard banger writing > the first thing that pops into mind is not that good either. > > George From martin at v.loewis.de Sun Jan 20 17:19:47 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 20 Jan 2008 23:19:47 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt In-Reply-To: References: Message-ID: <4793C903.60201@v.loewis.de> > But for different reasons I also want to get the absolute path of > Python install directory (not only the executable under Linux) and > site-packages directory. The Python install directory is available as sys.prefix. The site-packages directory is sys.prefix+"lib/python"+x.y+"/site-packages (where x.y is from sys.version_info). HTH, Martin From hyugaricdeau at gmail.com Fri Jan 11 09:56:03 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Fri, 11 Jan 2008 06:56:03 -0800 (PST) Subject: Help with Scons References: Message-ID: <22fde803-0583-458e-a817-3087cbb21edc@f47g2000hsd.googlegroups.com> On Jan 11, 5:20 am, anush wrote: > Can anybody tell how I could go about running python scripts with > scons. Have you tried reading the SCons user guide (http://www.scons.org/doc/ production/HTML/scons-user.html)? It's actually pretty good. I'm not too clear on what you're asking though. SCons scripts are written in Python (as is SCons itself)... Hyuga From bignose+hates-spam at benfinney.id.au Sun Jan 13 07:58:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 13 Jan 2008 23:58:29 +1100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: <87tzlhg9vu.fsf@benfinney.id.au> Jeroen Ruigrok van der Werven writes: > -On [20080113 01:41], Erik Lind (elind at spamcop.net) wrote: > >I'm new to Python, and OOP. I've read most of Mark Lutz's book and > >more online and can write simple modules, but I still don't get > >when __init__ needs to be used as opposed to creating a class > >instance by assignment. > > I personally tend to see __init__ or __new__ as equivalent to what > other languages call a constructor. That's getting the two of them confused. __new__ is a constructor, __init__ is not. > (And I am sure some people might disagree with that. ;)) It isn't really a matter for much debate. __new__ is the constructor: it creates the instance and returns it. Along the way, it calls __init__ on the *already-created* instance, to ask it to initialise itself ready for use. So, __init__ is an "initialiser" for the instance. Python, unlike many other OO languages, fortunately has these two areas of functionality separate. It's far more common to need to customise instance initialisation than to customise creation of the instance. I override __init__ for just about every class I write; I can count the number of times I've needed to override __new__ on the fingers of one foot. -- \ "Reichel's Law: A body on vacation tends to remain on vacation | `\ unless acted upon by an outside force." -- Carol Reichel | _o__) | Ben Finney From d.l.goldsmith at gmail.com Mon Jan 7 18:08:01 2008 From: d.l.goldsmith at gmail.com (dgoldsmith_89) Date: Mon, 7 Jan 2008 15:08:01 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python References: Message-ID: On Jan 7, 2:47 pm, Fredrik Lundh wrote: > dgoldsmith_89 wrote: > > Can anyone point me to a downloadable open source English dictionary > > suitable for programmatic use with python: I'm programming a puzzle > > generator, and I need to be able to generate more or less complete > > lists of English words, alphabetized. Thanks! DG > > here's one: > > http://www.dcs.shef.ac.uk/research/ilash/Moby/ > > Excellent, that'll do nicely! Thanks!!! DG From safealattar at gmail.com Wed Jan 30 03:36:09 2008 From: safealattar at gmail.com (Safe Alattar) Date: Wed, 30 Jan 2008 00:36:09 -0800 Subject: help using python on Vista Message-ID: I have no issues using python on XP. However on Vista I cant get the python gui (IDLE) to open! I did some research and found out that I need to unhide .idlerc but I cannot find any hidden files by that name whatsoever. Please help me. Im fairly new to python but I want to get this going. User friendly instructions would be much appreciated. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Jan 23 13:32:01 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Jan 2008 19:32:01 +0100 Subject: pairs from a list References: Message-ID: Matthew_WARREN wrote: > I'm just fiddling with this, am no great expert, but I added > > def pairs5(x): > o=[] > for n in zip(x[::2],x[1:2]): The second argument should be x[1::2]. > o.append(n) > return o > > I dont know if that breaks any constraints placed on the problem, but I It breaks the constraints unless the above is not cut-n-paste ;) Also note that your pairs5() offers no advantage over def pairs6(x): return zip(x[::2], x[1::2]) Peter From mark.e.tolonen at mailinator.com Sun Jan 27 15:58:10 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Sun, 27 Jan 2008 12:58:10 -0800 Subject: strftime return value encoding (mbcs, locale, etc.) References: <%D5nj.2630$Xg7.935@tornado.fastwebnet.it> Message-ID: <7oudne7Kqp3DbQHanZ2dnUVZ_tadnZ2d@comcast.com> "Giovanni Bajo" wrote in message news:%D5nj.2630$Xg7.935 at tornado.fastwebnet.it... > Hello, > > I am trying to find a good way to portably get the output of strftime() > and put it onto a dialog (I'm using PyQt, but it doesn't really matter). > The problem is that I need to decode the byte stream returned by strftime > () into Unicode. > > This old bug: > http://mail.python.org/pipermail/python-bugs-list/2003- > November/020983.html > > (last comment) mentions that it is "byte string in the locale's encoding". > > The comment also suggests to use "mbcs" in Windows (which, AFAIK, it's > sort of an "alias" encoding for the current Windows codepage), and to > find out the exact encoding using locale.getpreferredencoding(). > > Thus, I was hoping that something like: > > strftime("%#c", localtime()).decode(locale.getpreferredencoding()) > > would work... but alas I was reported this exception: > > LookupError: unknown encoding: cp932 > > So: what is the correct code to achieve this? Will something like this > work: > > data = strftime("%#c", localtime()) > if os.name == "nt": > data = data.decode("mbcs") > else: > data = dada.decode(locale.getpreferredencoding()) > > Is this the correct way of doing it? (Yes, it sucks). > > Shouldn't Python automatically alias whatever is returned by > locale.getpreferredencoding() to "mbcs", so that my original code works > portably? > > Thanks in advance! > -- > Giovanni Bajo Odd, what version of Python are you using? Python 2.5 works: >>> import time,locale >>> time.strftime('%#c').decode(locale.getpreferredencoding()) # cp1252 on >>> my system u'Sunday, January 27, 2008 12:56:30' >>> time.strftime('%#c').decode('cp932') u'Sunday, January 27, 2008 12:56:40' >>> time.strftime('%#c').decode('mbcs') u'Sunday, January 27, 2008 12:56:48' --Mark From terry at jon.es Wed Jan 9 09:32:39 2008 From: terry at jon.es (Terry Jones) Date: Wed, 9 Jan 2008 15:32:39 +0100 Subject: Open a List of Files In-Reply-To: Your message at 00:40:56 on Wednesday, 9 January 2008 References: <874pdomrrd.fsf@mulj.homelinux.net> <18308.12959.742868.758136@terry.local> Message-ID: <18308.56071.859777.102224@terry.local> >>>>> "BJ" == BJ Swope writes: I (at least) think the code looks much nicer. BJ> #Referring to files to write in various places... BJ> open_files['deliveries'].write(flat_line) BJ> open_files['deliveries'].write('\n') If you were doing a lot with the deliveries file at some point, you could put the file descriptor into a local variable deliveries = open_files['deliveries'] deliveries.write(flat_line) deliveries.write('\n') BJ> #And finally to close the opened files BJ> for fn in open_files.keys(): BJ> open_files[fn].close() You don't need "for fn in open_files.keys():", you can just use "for fn in open_files:", but simpler than that is to just use the dictionary values: for fn in open_files.values(): fn.close() Regards, Terry From bill.mill at gmail.com Sun Jan 27 11:18:19 2008 From: bill.mill at gmail.com (Bill Mill) Date: Sun, 27 Jan 2008 11:18:19 -0500 Subject: Klik2 Project, Python apps on linux In-Reply-To: <94dd8f6f0801262249v1c07cf3em2548c470a523291e@mail.gmail.com> References: <94dd8f6f0801262249v1c07cf3em2548c470a523291e@mail.gmail.com> Message-ID: <797fe3d40801270818n3c34c5f5lda0d6b6eab6d9261@mail.gmail.com> Jason, Can you give a little more detail on the problem? What's the directory structure of a Klik package that's failing look like? What program is trying to import what module from where that's failing? -Bill Mill On Jan 27, 2008 1:49 AM, Jason Taylor wrote: > Hi > > We've been working on klik2, http://code.google.com/p/klikclient/, which > implements OSX like application files on linux (with applications working on > all distros), In which every user desktop application is 1 file > > We've run into a bit of a problem with python apps, so while we can run a > complicated application like openoffice.org on ubuntu, fedora and suse from > a single file we cant run any python applications such as > jokosher > gnome-specimen > angrydd > gausssum > pathological > quodlibet > webboard > istanbul > exaile > ccsm > bittornado > pessulus > labyrinth > wammu > accerciser > > We'd like to fix this in a clean way with out resorting to nasty hacks > involving $PYTHON_PATH. > > If any one has any suggestions please email me or drop by #klik on freenode > > Issue http://code.google.com/p/klikclient/issues/detail?id=144 > > Cheers > > Jason Taylor > > -- > "Why isn't my life like a situation comedy? Why don't I have a bunch of > friends with nothing better to do but drop by and instigate wacky > adventures? Why aren't my conversations peppered with spontaneous > witticisms? Why don't my friends demonstrate heartfelt concern for my well > being when I have problems? ...I gotta get my life some writers." - Calven > -- > http://mail.python.org/mailman/listinfo/python-list > From cokofreedom at gmail.com Wed Jan 9 05:40:41 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jan 2008 02:40:41 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <8089de25-76c7-426a-a9c7-9ac0a3641e30@f3g2000hsg.googlegroups.com> On Jan 9, 11:34 am, cesco wrote: > Hi, > > say I have a string like the following: > s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... > > Thanks in advance > Cesco For replacing every other one, I tend to use the modulo, with a counter. count = (if u want even start with 0 else do 1) while/for replacing /in lalastring: if count % 2 == 0: do even else: do odd count += 1 This is a rather basic way of doing it, and I am sure people will sure much more efficient ways, but it generally works for me. Though I am now wondering if count % 2 when count == 2 is true or false as it returns 0 Of course you still need to do your replace but you should be able to do that. From paddy3118 at googlemail.com Thu Jan 17 01:10:55 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 16 Jan 2008 22:10:55 -0800 (PST) Subject: assigning values in python and perl References: Message-ID: On Jan 17, 3:34 am, "J. Peng" wrote: > I just thought python's way of assigning value to a variable is really > different to other language like C,perl. :) > > Below two ways (python and perl) are called "pass by reference", but > they get different results. > Yes I'm reading 'Core python programming', I know what happened, but > just a little confused about it. > > $ cat t1.py > def test(x): > x = [4,5,6] > Hi J, Unlike C or Perl , there is hardly ever any good reason for functions to act by purposefully modifying their arguments. Don't do it. Stick a return in your function and use that result. It is much more maintainable and readable. (It will also work, and look a lot more like, the same function written in other languages :-) - Paddy. From stef.mientki at gmail.com Thu Jan 10 18:31:17 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 11 Jan 2008 00:31:17 +0100 Subject: getting absolute path ? In-Reply-To: References: Message-ID: <4786AAC5.3030905@gmail.com> thanks Mike, with your links I managed to write some code that seems to work well. Still I stay surprised that these kind of functions are not available ;-) cheers, Stef kyosohma at gmail.com wrote: > On Jan 9, 3:22 pm, Stef Mientki wrote: > >> hello, >> >> I'm trying to convert the links in html pages to absolute links, >> these pages can either be webpages or files on local harddisk (winXP). >> Now I've struggling for a while, and this code works a lilttle: >> >> i = line.find ( 'href=' ) >> if i < 0 : >> i = line.find ( ' src=' ) >> if i >= 0 : >> ii = line.find ( '"', i+6 ) >> file = line [ i+6 : ii ] >> #print urlparse.urljoin ( p, file ) >> if file.find ( 'http:' ) < 0 : >> abspath = os.path.normpath ( os.path.join ( p, file ) ) >> line = line.replace ( file, abspath ) >> print line >> >> but it only covers files on local disk and just 1 link per line, >> so I guess it's a lot of trouble to catch all cases. >> Isn't there a convenient function for (OS independent preferable) ? >> Googled for it, but can't find it. >> >> thanks, >> Stef Mientki >> > > I googled a bit too. The Perl forums talk about using a regular > expression. You can probably take that and translate it into the > Python equivalent: > > http://forums.devshed.com/perl-programming-6/how-to-parse-relatives-links-to-absolute-links-8173.html > > I also found this, which appears to be an old c.l.py thread: > > http://www.dbforums.com/archive/index.php/t-320359.html > > You might have more luck if you google for "relative to absolute > links". I would also take a look at how django or cherrypy creates > their URLs. > > Mike > From thelanguageofcities at gmail.com Sun Jan 27 18:09:52 2008 From: thelanguageofcities at gmail.com (Max) Date: Sun, 27 Jan 2008 15:09:52 -0800 (PST) Subject: Python Genetic Algorithm Message-ID: Hi all. I'm just getting introduced to Python (mostly through Dive Into Python), and I've decided to use it for a project where I have to write my own Genetic Algorithm. Even if you don't know about GAs, you might be able to help with an issue I'm having. I'm just starting the project off, so I'm still in the conceptual phase, and I'm stuck on how I'm going to be able to implement something. In GAs, you operate on a Population of solutions. Each Individual from the Population is a potential solution to the problem you're optimizing, and Individuals have what's called a chromosome - a specification of what it contains. For example, common chromosomes are bit strings, lists of ints/floats, permutations...etc. I'm stuck on how to implement the different chromosomes. I have a Population class, which is going to contain a list of Individuals. Each individual will be of a certain chromosome. I envision the chromosomes as subclasses of an abstract Individual class, perhaps all in the same module. I'm just having trouble envisioning how this would be coded at the population level. Presumably, when a population is created, a parameter to its __init__ would be the chromosome type, but I don't know how to take that in Python and use it to specify a certain class. I'm doing something similar with my crossover methods, by specifying them as functions in a module called Crossover, importing that, and defining crossover_function = getattr(Crossover, "%s_crossover" % xover) Where xover is a parameter defining the type of crossover to be used. I'm hoping there's some similar trick to accomplish what I want to do with chromosomes - or maybe I'm going about this completely the wrong way, trying to get Python to do something it's not made for. Any help/ feedback would be wonderful. Thanks, Max Martin From yantao at telus.com Sun Jan 27 00:48:48 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 05:48:48 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: References: Message-ID: <4XUmj.43653$fj2.34204@edtnps82> For sure I can calculate the number of characters and do the padding myself, but what's the point, and i surely hope that python does it for me. ============ "Peter Pei" wrote in message news:cjTmj.43610$fj2.37903 at edtnps82... >I am using things like "%-20s%-60s%-10s" in tkinter listbox to make it look >like a table, with mono sized font like lucie system. But this does not >work with data contains "Les mis?rables", because it is unicode, and one >byte is not neccessary one character. Now how can I resolve this issue? > > My issue is "how to make format operator % work with unicode as expected", > and has nothing to do with tkinter. If I want to use a table widget or > something, I can. But that's not the question. From mail at timgolden.me.uk Wed Jan 23 06:06:34 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Jan 2008 11:06:34 +0000 Subject: subprocess and & (ampersand) In-Reply-To: References: Message-ID: <47971FBA.8080104@timgolden.me.uk> Steven Bethard wrote: > I'm having trouble using the subprocess module on Windows when my > command line includes special characters like "&" (ampersand):: > > >>> command = 'lynx.bat', '-dump', 'http://www.example.com/?x=1&y=2' > >>> kwargs = dict(stdin=subprocess.PIPE, > ... stdout=subprocess.PIPE, > ... stderr=subprocess.PIPE) > >>> proc = subprocess.Popen(command, **kwargs) > >>> proc.stderr.read() > "'y' is not recognized as an internal or external command,\r\noperable > program or batch file.\r\n" > > As you can see, Windows is interpreting that "&" as separating two > commands, instead of being part of the single argument as I intend it to > be above. Is there any workaround for this? How do I get "&" treated > like a regular character using the subprocess module? A little experimentation suggests that the problem's somehow tied up with the .bat file. ie this works for me (doubly complicated because of the long firefox path: import subprocess cmd = [ r"c:\Program Files\Mozilla Firefox\firefox.exe", "http://local.goodtoread.org/search?word=tim&cached=0" ] subprocess.Popen (cmd) but this doesn't: "c:\Program Files\Mozilla Firefox\firefox.exe" "%*" import subprocess cmd = [ r"c:\temp\firefox.bat", "http://local.goodtoread.org/search?word=tim&cached=0" ] subprocess.Popen (cmd) although, interestingly, it seems to cut off at the "=" before the "&". Not sure how significant that is. So, even assuming we're looking at the same situation, I suppose one solution for you is to break out the .bat file. But that may not be a possibility. TJG From nick.fabry at coredump.us Tue Jan 29 00:10:23 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Tue, 29 Jan 2008 00:10:23 -0500 Subject: ISO with timezone In-Reply-To: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> References: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Message-ID: Hello, nik. On Jan 28, 2008, at 21:03, nik wrote: > Hi, > > How does one express the time in ISO format with the timezone > designator? > > what I want is YYYY-MM-DDThh:mm:ss.sTZD > >> From the documentation I see: >>>> from datetime import tzinfo, timedelta, datetime >>>> class TZ(tzinfo): > ... def utcoffset(self, dt): return timedelta(minutes=-399) > ... >>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') > '2002-12-25 00:00:00-06:39' > > and I've also figured out: >>>> datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3] > '2008-01-23T11:22:54.130' > > But can't figure out how to fit them together. > There is nothing there to 'fit together' - in the first example given, the datetime object has no time component specified, so it fills in default vaules of zero. The following should make this clear: >>> your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ()) >>> print your_time 2008-02-29 15:30:11-05:00 >>> print your_time.isoformat('T') 2008-02-29T15:30:11-05:00 If you wish to append the NAME of the tzinfo object instead of its offset, that requires a bit more playing around (along with a properly defined tzinfo object - check out dateutil or pytz for a concrete implementation of tzinfo subclasses (i.e. timezones)), but the following would work: >>> print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z') 2008-02-29T15:30:11 EST For details on how the .strftime method works, see Python Standard Library, Section 14.2. I hope this helps! Nick Fabry > Thank you, > Nik > -- > http://mail.python.org/mailman/listinfo/python-list From hakim_ouaras at yahoo.com Sun Jan 20 11:35:52 2008 From: hakim_ouaras at yahoo.com (hakim ouaras) Date: Sun, 20 Jan 2008 08:35:52 -0800 (PST) Subject: change values of array in dictionary Message-ID: <321201.92447.qm@web63707.mail.re1.yahoo.com> Hi all, I have two dictionays like these: dict1={"id1":[1,2,3,4,5],"id2":[1,2,3,1,3], "var1":[10,11,12,13,14]} dict2={"id2":[1,2,3,4,], "var2":[20,21,22,23]} I want to replace the values of dict1["var1"] with those of dict["var2"] with taking count the correspondance between dict1["id1"] and dict2["id2"]. result that I want to have is like this: dict1={"id1":[1,2,3,4,5],"id2":[1,2,3,1,3], "var1":[20,21,22,20,22]} Are there any predefined python function to do this. Thak you for your answers Hakim ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Fri Jan 4 18:36:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 4 Jan 2008 15:36:27 -0800 (PST) Subject: Questions about subclassing an int References: Message-ID: <38614926-19fe-49f8-aa08-fe68449aae70@f3g2000hsg.googlegroups.com> On Jan 4, 10:55?pm, "Steven W. Orr" wrote: > class S(int): > ? ? ?def __init__(self, value): > ? ? ? ? self.value = value > ? ? ?def addStr(self, str): > ? ? ? ? self.doc = str > > s = S(44) > s.addStr('Hello') > > print 's = ', s > print 's.doc = ', s.doc > > class T(int): > ? ? ?def __init__(self, value, str): > ? ? ? ? self.value = value > ? ? ? ? self.doc = str > > t = T(44, 'Goodbye') > > print 't = ', t > print 't.doc = ', t.doc > > It works ok with S but it fails when I try to instantiate T with a syntax > error. Why? > > Also, I don't understand why S works. If I change the name of value and > use something else, the print of s still works by printing the integer > value out. How does it know what value to use? Also, in S.__init__, should > I be calling super(S, self).__init__(value) or is there a difference? I suggest you read http://www.python.org/download/releases/2.2.3/descrintro/ Briefly, S(44) calls first S.__new__(S, 44) which does not exist, so falls back to int.__new__(S, 44) which creates the new object s which is 44 as an integer. Then *only*, s.__init__(44) is called and your code is executed. Try changing self.value=value to self.value='SPAM', you will see that 'print s' still returns 44. As for T(44, 'Goodbye'), the same happens. First T.__new__ does not exist, so int.__new__(T, 44, 'Goodbye') is executed and this is where the error comes from (shouldn't it be a TypeError?) as this means "create the integer whose representation in base 'Goodbye' is 44". As for calling int.__init__, there is no point: integers don't have an __init__() since they are immutable. > And just for fun: > > class R(int): > ? ? ?def __init__(self, value, doc): > ? ? ? ? ?super(R, self).__init__(value) > ? ? ? ? ?self.doc = doc > > r = R(66,'GGG') > Traceback (most recent call last): > ? ?File "", line 1, in ? > TypeError: an integer is required > > Now it's no longer a syntax error but I don't see why it's different? Same as above, though I don't understand why you get a SyntaxError for T and a TypeError for R. AFAICT both shoult give a TypeError. -- Arnaud From eefacm at gmail.com Thu Jan 3 16:15:15 2008 From: eefacm at gmail.com (eefacm at gmail.com) Date: Thu, 3 Jan 2008 13:15:15 -0800 (PST) Subject: New-style objects are not instances, apparently Message-ID: <3c386519-8de3-4e50-8b96-e4c5f3cc8e78@d21g2000prf.googlegroups.com> I have a class that derives from Exception. In Python 2.4, isinstance(MyClass(), types.InstanceType) was True. In 2.5, it's False. Further experimentation showed that derivation from object was the culprit; new-style objects are not considered "instances" in the above sense. I wasn't able to figure out a workaround. Is there one, or is the distinction between traditional classes and built-in types only going to get more and more hazy? From sjmachin at lexicon.net Thu Jan 24 15:44:00 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 24 Jan 2008 12:44:00 -0800 (PST) Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> Message-ID: <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> On Jan 25, 6:18 am, Ira.Ko... at gmail.com wrote: > Hello all, > > I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like > to sort based on first two characters. If you mean 1.6 American billion i.e. 1.6 * 1000 ** 3 lines, and 2 * 1024 ** 3 bytes of data, that's 1.34 bytes per line. If you mean other definitions of "billion" and/or "GB", the result is even fewer bytes per line. What is a "Unicode text file"? How is it encoded: utf8, utf16, utf16le, utf16be, ??? If you don't know, do this: print repr(open('the_file', 'rb').read(100)) and show us the results. What does "based on [the] first two characters" mean? Do you mean raw order based on the ordinal of each character i.e. no fancy language- specific collating sequence? Do the first two characters always belong to the ASCII subset? You'd like to sort a large file? Why? Sorting a file is just a means to an end, and often another means is more appropriate. What are you going to do with it after it's sorted? > I'd greatly appreciate if someone can post sample code that can help > me do this. I'm sure you would. However it would benefit you even more if instead of sitting on the beach next to the big arrow pointing to the drop zone, you were to read the manual and work out how to do it yourself. Here's a start: http://docs.python.org/lib/typesseq-mutable.html > Also, any ideas on approximately how long is the sort process going to > take (XP, Dual Core 2.0GHz w/2GB RAM). If you really have a 2GB file and only 2GB of RAM, I suggest that you don't hold your breath. Instead of writing Python code, you are probably better off doing an external sort. You might consider looking for a Windows port of a Unicode-capable Unix sort utility. Google "GnuWin32" and see if their sort does what you want. From jeba.ride at gmail.com Wed Jan 16 02:47:10 2008 From: jeba.ride at gmail.com (Clement) Date: Tue, 15 Jan 2008 23:47:10 -0800 (PST) Subject: Memory problem with threading References: <55f016fb-42f9-47d6-903a-a068f846b795@e10g2000prf.googlegroups.com> Message-ID: On Jan 16, 5:24 am, "rewo... at gmail.com" wrote: > Hi! > > I made a string parser program, it has a main function and a working > thread class. When it is running in 24h non-stop, the memory run out. > I dont Know why. Do anybody know somekind of debugger that can i see > what is eating the memory? Maybe there is a list or value or > dictionary that is growing continually but i dont know which one. > Maybe there is a program for that kind of debugging, what can > monitoring the memory and values size in the memory. Or it is a sience > fiction :) > > p.s.: sorry for my english > Rew Hi I got the same problem when i did my crawler..... the simple soloution what i did is... created one therad at the start up time of my program.. it will run all the time of the life of the program... it's duty is frequently calling gc.college() function in garbage collector package of python http://arctrix.com/nas/python/gc/ i used it as temporary solution.... if any other way please share........... ...... Thanking you... Clement http://www.squzer.com/ From bignose+hates-spam at benfinney.id.au Tue Jan 29 17:14:30 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jan 2008 09:14:30 +1100 Subject: Removing Pubic Hair Methods References: Message-ID: <878x28e0u1.fsf@benfinney.id.au> xikom01 at yahoo.com.tw writes: > Shaving is the most common removing pubic hair method. However, it > is not the only one. Clearly you haven't done the Python tutorial, otherwise you'd realise there's no distinction between pubic methods and privy methods. Also, there's one, and preferably only one, obvious way to do it:: >>> del foo.hair -- \ "A man's only as old as the woman he feels." -- Groucho Marx | `\ | _o__) | Ben Finney From remco at gerlich.nl Mon Jan 28 12:22:24 2008 From: remco at gerlich.nl (Remco Gerlich) Date: Mon, 28 Jan 2008 18:22:24 +0100 Subject: validate string is valid maths In-Reply-To: References: Message-ID: <7ae3ca10801280922r7463a725ye52b872a45af6aff@mail.gmail.com> Hi, It seems that for every group of 2 or more +-/* signs, one of the following holds: - The group starts with '-', everything after it should be dropped, otherwise - The second character is '-', everything after it should be dropped, otherwise - Drop everything after the first. That should turn into one short regex. Did I miss something? Remco On Jan 28, 2008 4:10 PM, wrote: > Hi pythoners. > > I am generating strings of length n, randomly from the symbols > > +-/*0123456789 > > What would be the 'sensible' way of transforming the string, for example > changing '3++++++8' into 3+8 > or '3++--*-9' into '3+-9' such that eval(string) will always return a > number? > > in cases where multiple symbols conflict in meaning (as '3++--*-9' the > earliest valid symbols in the sequence should be preserved > > so for example, > > '3++*/-9' = 3+-9 > '45--/**/+7' = 45-+7 > '55/-**+-6**' = 55/-6 > > ...that is, unless there is a canonical method for doing this that does > something else instead.. > > > this sounds like homework. It's not. I like making problems up and it's a > slow work day. So, as an aside, there is no real reason I want to do this, > nor other problem to solve, nor other background to what I'm trying to > achieve ;) other than twiddling with python. > > 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. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Fri Jan 4 04:17:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 10:17:01 +0100 Subject: PyObject_CallObject code dump after calling 4 times In-Reply-To: <0d763f52-6845-4822-807a-130c9c46c327@i12g2000prf.googlegroups.com> References: <938001bf-33d2-4071-9b08-f7bb041505b1@s19g2000prg.googlegroups.com> <0d763f52-6845-4822-807a-130c9c46c327@i12g2000prf.googlegroups.com> Message-ID: grbgooglefan wrote: > char* plevel = NULL; > if(NULL != (plevel = PyString_AsString(pResult))){ > ret = 0; > strncpy(szEvalResult,plevel,strlen(plevel)); strncpy doesn't check the size of the target buffer, so that's no different from just doing strcpy(szEvalResult, plevel). or in other words, it's still trivial to crash your program simply by returning too much data from the Python code. From arnodel at googlemail.com Wed Jan 23 16:23:46 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 13:23:46 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> <457550e3-f5e1-4fad-b553-c3e5e400dbb1@u10g2000prn.googlegroups.com> Message-ID: On Jan 23, 8:40?pm, Terry Jones wrote: > >>>>> "Arnaud" == Arnaud Delobelle writes: > > Arnaud> FWIW, I have a clear idea of what the space of solutions is, and > Arnaud> which solutions I consider to be equivalent. ?I'll explain it > Arnaud> below. ?I'm not saying it's the right model, but it's the one > Arnaud> within which I'm thinking. > > OK. This reinforces why I'm not going to work on it anymore, the solution > is subjective (once you start pruning). > > Arnaud> I think it's best to forbid negatives. ?Solutions always be written > Arnaud> without any negative intermediate answer. ?E.g. 1-7*6*(3-9) can be > Arnaud> done as 1+7*6*(9-3). > > That's a good optimization, and I think it's easy to prove that it's > correct supposing the target is positive and the inputs are all positive. > > If you consider the intermediate results in a solution, then if you ever go > negative it's because of an operation X (must be a sub or a div) and when > you next become positive it's due to an operation Y (must be add or > mul). So you can "reflect" that part of the computation by doing the > opposite operations for that formerly sub-zero intermediate sequence. > > Arnaud> I don't consider these to be equivalent, because their equivalence > Arnaud> depends on understanding the meaning of subtraction and addition. > > Ha - you can't have it both ways Arnaud! You don't want the computation to > go negative... doesn't that (and my "proof") have something to do with the > inverse nature of add and sub? :-) I think I can have it both ways, here's why: the "big then small" and "no negatives" rules are applied indiscriminately by the algorithm: it doesn't need to know about the history of operations in order to make a decision depending on their nature. OTOH, identifying (a + b) - c and a + (b - c) for example, requires inspection of the stack/tree/ calculation history. It is an *informed* decision made by the algorithm > Arnaud> (I've also applied the 'big then small' rule explained below) > > And now you're taking advantage of your knowledge of > and < ... Again, *I* have the knowledge, the algorithm does it indiscriminately... [...] > Arnaud> To be perfectly honest (and expose my approach a little to your > Arnaud> argument) I added a three additional rules: > > Arnaud> * Don't allow x - x > Arnaud> * Don't allow x * 1 > Arnaud> * Don't allow x / 1 > > Yes, I do these too, including not allowing a zero intermediate (which is a > useless calculation that simply could not have been done - see, I have deep > knowledge of zero!). Note that disallowing 0 and disallowing x - x are equivalent, as the only way to get your first 0 is by doing x - x. Thanks for the discussion, it's made me realise more clearly what I was doing. -- Arnaud From cokofreedom at gmail.com Wed Jan 30 04:06:38 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 30 Jan 2008 01:06:38 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <7xabmnbxh7.fsf@ruckus.brouhaha.com> <98e4151d-2253-4872-aa79-b391ddb7af77@k39g2000hsf.googlegroups.com> Message-ID: On Jan 30, 9:50 am, Santiago Romero wrote: > On 30 ene, 08:09, Paul Rubin wrote: > > > Santiago Romero writes: > > > > > >>> li = [1,2,3,4,5] > > > > >>> filter(lambda x: x != 3, li) > > > > [1, 2, 4, 5] > > > > I haven't measured it, but this should be the fast solution in all > > > the thread ... > > > li.remove(3) is probably faster. > > But that only removes the first ocurrence of item==3. > > In a = [1, 2, 3, 3, 3, 4, 3, 3, 2, 3], the filter solution will > efectively remove all items with value == 3 while li.remove(3) will > only remove the first ocurrence. > > Bye! from itertools import ifilter print [x for x in ifilter(lambda x: x != 99, li)] Will this one be faster or slower than filter? From lists at cheimes.de Tue Jan 22 10:06:47 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 22 Jan 2008 16:06:47 +0100 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <4795F398.2050306@strank.info> References: <5vm8t3F1m1797U1@mid.uni-berlin.de> <4795F398.2050306@strank.info> Message-ID: Stefan Rank wrote: > on 22.01.2008 14:20 Diez B. Roggisch said the following: >> def isgenerator(v): >> def _g(): yield >> return type(v) == type(_g()) >> >> But I wonder why there is no such method already available? > > > This tests for generator objects, and you could also use:: > > return type(v) is types.GeneratorType > > I think that this is pretty direct already. > > I also need to test for generator functions from time to time for which > I use:: > > def _isaGeneratorFunction(func): > '''Check the bitmask of `func` for the magic generator flag.''' > return bool(func.func_code.co_flags & CO_GENERATOR) Can you please write a function for the inspect module + docs + a small unit tests and submit a patch? The inspect module is missing the isgenerator function. Christian From MartinRinehart at gmail.com Sat Jan 5 05:31:15 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Sat, 5 Jan 2008 02:31:15 -0800 (PST) Subject: Basic inheritance question Message-ID: Working on parser for my language, I see that all classes (Token, Production, Statement, ...) have one thing in common. They all maintain start and stop positions in the source text. So it seems logical to have them all inherit from a base class that defines those, but this doesn't work: import tok class code: def __init__( self, start, stop ): startLoc = start stopLoc = stop class token(code): pass x = token( tok.Loc(0, 0), tok.Loc(3, 4) ) print x.startLoc.repr(), x.stopLoc.repr() AttributeError: token instance has no attribute 'startLoc' 1) Is my design thinking good, or hopelessly unPythonic? 2) If it's good, how do you access base class data attributes? (The doc is rich in method access info, impoverished when it comes to other attributes.) From paddy3118 at googlemail.com Wed Jan 9 16:29:10 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 13:29:10 -0800 (PST) Subject: alternating string replace: Extended input (Long). References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: On Jan 9, 8:56 pm, Fredrik Lundh wrote: > Donald 'Paddy' McCarthy wrote: > > I created some more test strings and ran posters solutions against them. > > the point being? > > To see how they act against 'corner cases' and an exercise for me in trying to create corner cases. (I'm in to functional testing at the mo'). - Paddy. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 18 04:16:26 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 18 Jan 2008 10:16:26 +0100 Subject: Loop in a loop? In-Reply-To: References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <47906e35$0$16946$426a74cc@news.free.fr> Roel Schroeven a ?crit : > Sacred Heart schreef: >> On Jan 17, 1:35 pm, cokofree... at gmail.com wrote: >>> for i in zip(array1, array2): >>> print i >>> >>> Although I take it you meant four d, the issue with this method is >>> that once you hit the end of one array the rest of the other one is >>> ignored. >> >> Yes, small typo there. >> >> Okey, so if my array1 is has 4 elements, and array2 has 6, it won't >> loop trough the last 2 in array2? How do I make it do that? > > One solution is with map() instead if zip(). map() with None as the > first argument works much like zip(), but it keeps looping if one of the > lists is exhausted. When that happens, it uses None for those values: Yek ! Should have read the doc more carefully. Height years of Python, and I didn't knew this one :( From travis.jensen at gmail.com Thu Jan 24 18:26:31 2008 From: travis.jensen at gmail.com (Travis Jensen) Date: Thu, 24 Jan 2008 16:26:31 -0700 Subject: OS X, Python, and Emacs Message-ID: Honestly, I don't know if this is a python problem or an emacs problem; I'm leaning towards something to do with python, but I'm hoping somebody here might know the answer. The problem is that whenever I start python inside of emacs (both emacs.app and aquamacs), anything I type gets echoed back to the buffer before being processed. For example: >>> 'a' 'a' 'a' >>> for x in xrange(5): for x in xrange(5): ... print x print x ... 0 1 2 3 4 Any ideas on what is causing this or how I can fix it? Thanks. tj Travis Jensen travis.jensen at gmail.com http://softwaremaven.innerbrane.com/ You should read my blog; it is more interesting than my signature. -------------- next part -------------- An HTML attachment was scrubbed... URL: From MrJean1 at gmail.com Fri Jan 11 12:53:12 2008 From: MrJean1 at gmail.com (MrJean1) Date: Fri, 11 Jan 2008 09:53:12 -0800 (PST) Subject: Detecting OS platform in Python References: Message-ID: <0524f8e0-e0b0-43a4-84c0-aa7d92f173e7@v46g2000hsv.googlegroups.com> On Jan 10, 7:53?pm, Benjamin wrote: > On Jan 10, 8:37 pm, Devraj wrote:> Hi everyone, > > > My Python program needs reliably detect which Operating System its > > being run on, infact it even needs to know which distribution of say > > Linux its running on. The reason being its a GTK application that > > needs to adapt itself to be a Hildon application if run on devices > > like the N800. > > platform.dist might help you. It's not very complete at all, though. > (This is supposed to improve in 2.6, though) > Better yet, first use sys.platform. If that is 'linux2', then use platform.dist(). /Jean Brouwers > > I have been searching around for an answer to this, and did find some > > messages on a lists that suggested the use of sys.platform to detect > > platform, with counter posts saying that it didn't work on Windows > > etc. > > > Can anyone please shed some light on this? > > > Thanks a lot. From mccredie at gmail.com Wed Jan 16 16:25:12 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 16 Jan 2008 13:25:12 -0800 (PST) Subject: Creating unique combinations from lists References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> Message-ID: On Jan 16, 11:15 am, breal wrote: > I have three lists... for instance > > a = ['big', 'small', 'medium']; > b = ['old', 'new']; > c = ['blue', 'green']; > > I want to take those and end up with all of the combinations they > create like the following lists > ['big', 'old', 'blue'] > ['small', 'old', 'blue'] > ['medium', 'old', 'blue'] > ['big', 'old', 'green'] > ['small', 'old', 'green'] > ['medium', 'small', 'green'] > ['big', 'new', 'blue'] > ['small', 'new', 'blue'] > ['medium', 'new', 'blue'] > ['big', 'new', 'green'] > ['small', 'new', 'green'] > ['medium', 'new', 'green' ] > > I could do nested for ... in loops, but was looking for a Pythonic way > to do this. Ideas? I would probably just create a generator: def permute(a,b,c): for x in a: for y in b: for z in c: yield [x,y,z] all_combos = list(permute( ['big', 'small', 'medium'], ['old', 'new'], ['blue', 'green'])) print all_combos I'm using nested for loops, but I sure find it easy to read that way. Though, using list comprehension does pretty much the same thing. It appears that Tim Chase has posted a more generic version of the above. Matt From wmcbrine at users.sf.net Tue Jan 29 11:34:17 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Tue, 29 Jan 2008 16:34:17 GMT Subject: Removal of element from list while traversing causes the next element to be skipped Message-ID: Look at this -- from Python 2.5.1: >>> a = [1, 2, 3, 4, 5] >>> for x in a: ... if x == 3: ... a.remove(x) ... print x ... 1 2 3 5 >>> a [1, 2, 4, 5] >>> Sure, the resulting list is correct. But 4 is never printed during the loop! What I was really trying to do was this: apps = [name for name in os.listdir(ROOT) if os.path.isdir(os.path.join(ROOT, name))] apptitles = {} for name in apps: try: app = __import__(name) except: apps.remove(name) else: apptitles[name] = getattr(app, 'TITLE', name.title()) which worked fine, until I actually had a directory with no module in it. Then that directory was correctly removed from the list, but the _next_ one was skipped, so its title was never assigned, which caused problems later in the program. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From bruno.desthuilliers at gmail.com Thu Jan 31 18:28:31 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 31 Jan 2008 15:28:31 -0800 (PST) Subject: python modules collection References: <47A129B1.6000301@block.duxieweb.com> Message-ID: <39945886-aaf9-4255-a636-c38198158bba@h11g2000prf.googlegroups.com> On 31 jan, 02:57, "Guilherme Polo" wrote: > 2008/1/30, J. Peng : > > > Hello, > > > Is there a site for python,which collects most kinds of python modules? > > like CPAN for Perl. > > Sometime I want to use a module,like the time/date modules,don't know > > where I should search from. > > Sorry if I have repeated this question on the list. > > Thanks! > > There ishttp://pypi.python.org/pypi > > And the module index for the standard lib, of course: http://docs.python.org/modindex.html From finite.automaton at gmail.com Fri Jan 11 12:14:59 2008 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: Fri, 11 Jan 2008 09:14:59 -0800 (PST) Subject: Help with Windows build of Yapgvb Python extension References: <4bfd40d3-61f5-4c88-b6b2-c8ebef1b13dc@m34g2000hsf.googlegroups.com> Message-ID: <161c71e8-274c-4e96-a14f-b790f69809e6@q39g2000hsf.googlegroups.com> On Jan 11, 9:44 am, Mike wrote: > On Jan 11, 8:41 am, Lonnie Princehouse > wrote: > > > > > I'm the author of Yapgvb, a Python binding for Graphviz. Yapgvb > > enjoys modest success, but for some time it has been in dire need of a > > Python 2.5 build for Windows. I'm posting this message in the hopes of > > finding someone who is interested in making this build. > > > This is a relatively quick task for someone who is comfortable with > > building C extensions and has an operational Windows build environment > > for Python 2.5 (which I don't). Alternately, it's a great way to > > learn about these things, and to get involved with a small open source > > project. > > > Technologies used: > > graphviz > > distutils > > boost.python > > boost.graph > > > See:http://yapgvb.sourceforge.net > > What do you need exactly? One of those executables created using bdist > or are you going for the msi? > > I usually attempt to create these things doing > > python setup.py bdist_wininst > > ...for executable installers. > > If you can provide a valid setup.py, I can probably create the exe/ > msi. > > Mike Yes, a bdist_wininst installer is what I had in mind. MSI would be fine, too --- whichever is easier. If anyone wants to have a look, there's a README file that details what I did to build yapgvb for Python 2.4. The source is available from anonymous subversion: svn co https://yapgvb.svn.sourceforge.net/svnroot/yapgvb yapgvb and is also web-browseable, http://yapgvb.svn.sourceforge.net/viewvc/yapgvb/ From george.sakkis at gmail.com Fri Jan 11 08:27:15 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 05:27:15 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> <478732db$0$19250$426a74cc@news.free.fr> Message-ID: <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> On Jan 11, 4:12 am, Bruno Desthuilliers wrote: > George Sakkis a ?crit : > > > On Jan 10, 3:37 am, Bruno Desthuilliers wrote: > > >> I fail to see how the existence of JIT compilers in some Java VM changes > >> anything to the fact that both Java (by language specification) and > >> CPython use the byte-code/VM scheme. > > > Because these "some Java VMs" with JIT compilers are the de facto > > standard used by millions; > > Repeating an argument doesn't make it more true nor more relevant. Once > again, this doesn't change anything to the fact exposed above. > > > the spec is pretty much irrelevant > > I mentionned this because this kind of choice is usually not part of the > language spec but of a specific implementation. Java is AFAIK the only > language where this implementation stuff is part of the spec. > > > (unless > > you're a compiler writer or language theorist). > > I thought it was quite clear and obvious that I was talking about points > relating to these fields. No it wasn't, and besides the OP is most likely interested in these as a simple user so the distinction between a spec and a de facto standard implementation (such as JDK for Java and CPython for Python) are almost pedantic if not misleading. We're not Lisp (yet ;-)), with five major implementations and a dozen of minor ones. George From list-ener at strank.info Tue Jan 22 08:46:00 2008 From: list-ener at strank.info (Stefan Rank) Date: Tue, 22 Jan 2008 14:46:00 +0100 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <5vm8t3F1m1797U1@mid.uni-berlin.de> References: <5vm8t3F1m1797U1@mid.uni-berlin.de> Message-ID: <4795F398.2050306@strank.info> on 22.01.2008 14:20 Diez B. Roggisch said the following: > > def isgenerator(v): > def _g(): yield > return type(v) == type(_g()) > > But I wonder why there is no such method already available? This tests for generator objects, and you could also use:: return type(v) is types.GeneratorType I think that this is pretty direct already. I also need to test for generator functions from time to time for which I use:: def _isaGeneratorFunction(func): '''Check the bitmask of `func` for the magic generator flag.''' return bool(func.func_code.co_flags & CO_GENERATOR) cheers, stefan From ramashish.lists at gmail.com Thu Jan 3 23:24:07 2008 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: Thu, 3 Jan 2008 20:24:07 -0800 (PST) Subject: Problem reading csv files Message-ID: <1788604d-5fed-435a-a9f3-f7e9f652b5a3@s12g2000prg.googlegroups.com> Hi, I am trying to read a csv file using csv.reader. The file is created using Open Office and saved in Excel format. import csv reader = csv.reader(open('test.xls')) for row in reader: print row It however throws the exception _csv.Error: : line contains NULL byte Any idea whats going wrong here? Thanks in advance, Ram From patrick.waldo at gmail.com Thu Jan 3 09:41:25 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Thu, 3 Jan 2008 06:41:25 -0800 (PST) Subject: Pivot Table/Groupby/Sum question References: <148c3214-77b9-47b0-a680-ffb85dd3efcd@e6g2000prf.googlegroups.com> <9f7b6dcc-216d-46a9-a9d5-022c00ee9d7d@d21g2000prf.googlegroups.com> <1caf93fd-3a50-4c77-87b0-5312cdebd35f@d21g2000prf.googlegroups.com> <63a5a87e-3385-4ef0-80a3-cd1a01eeeac3@w38g2000hsf.googlegroups.com> <276d150b-6b2a-4973-8569-bd8cad6df948@s19g2000prg.googlegroups.com> <018c37d5-67c0-4995-88e3-86f701580c26@e23g2000prf.googlegroups.com> <5d6721cc-1912-4adc-9e47-0afa21c51c89@21g2000hsj.googlegroups.com> <17de023b-8dfd-4478-8271-96e21968d489@s8g2000prg.googlegroups.com> Message-ID: <39fd9ee5-d874-4cea-a7bb-64ab62594332@m34g2000hsf.googlegroups.com> Yes in the sense that the top part will have merged cells so that Horror and Classics don't need to be repeated every time, but the headers aren't the important part. At this point I'm more interested in organizing the data itself and i can worry about putting it into a new excel file later. From stef.mientki at gmail.com Tue Jan 1 13:39:21 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 01 Jan 2008 19:39:21 +0100 Subject: Some specific exec behavior ? Message-ID: <477A88D9.4090708@gmail.com> hello, I find 2 strange behaviors in exec-function, and I can't find anything in the documentation. (Python 2.4.3 Enthought edition) 1. A function definition may not span more than 1 line, e.g. This generates an exception: def _func (x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) while this works correct: def _func (x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) 2. an emtpy line at the end also generates an exception Is this behavior correct ? where should I find information about it ? thanks, Stef Mientki From generalcody at gmail.com Sat Jan 12 14:49:45 2008 From: generalcody at gmail.com (GeneralCody) Date: Sat, 12 Jan 2008 20:49:45 +0100 Subject: Great Python books for the beginner References: Message-ID: <2008011220494516807-generalcody@gmailcom> On 2008-01-12 08:03:42 +0100, Landon said: > Hi, I'm a freshman in college and I'm going to be taking an intro to > programming course next semester which mainly uses Python, so I > thought it might be a good time to pick up Python beyond the scope of > the class as well. The text book for this class is Python for the > Absolute Beginner or something similar to that name. > > I was wondering if anyone had any opinions on what other titles I > could look into since this one seems from a glance at reviews to be > teaching mainly through game programming (a topic I'm not too > interested in) or if this one is a quality book by itself. I would definetly go for Learning Python first, maybe Apress "Python, from novice to Professional" as well... From socyl at 987jk.com.invalid Wed Jan 30 07:36:21 2008 From: socyl at 987jk.com.invalid (kj) Date: Wed, 30 Jan 2008 12:36:21 +0000 (UTC) Subject: Python noob SOS (any [former?] Perlheads out there?) References: <479f7492$0$27193$9b4e6d93@newsspool1.arcor-online.net> Message-ID: In <479f7492$0$27193$9b4e6d93 at newsspool1.arcor-online.net> Wildemar Wildenburger writes: >kj wrote: >> Is there any good reading (to ease the transition) for Perl >> programmers trying to learn Python? >> >www.diveintopython.org Thanks. Not for Perl programmers specifically, but it looks useful all the same. kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From stephen at theboulets.net Tue Jan 8 22:43:01 2008 From: stephen at theboulets.net (Stephen_B) Date: Tue, 8 Jan 2008 19:43:01 -0800 (PST) Subject: Default location of python on OS X Message-ID: <1519661f-97bd-4fdd-b2d5-a46dd9a81c81@e25g2000prg.googlegroups.com> I've installed the latest 2.5 python today from python.org, and I think it ended up in "/Applications/MacPython 2.5". I also have a "/Applications/MacPython 2.4" and a "/Applications/ MacPython-2.4". Can I delete these, or did one of them come with Leopard? I still have a "/Library/Python/2.3" and a "/Library/Python/2.5". Thanks. Stephen From deets at nospam.web.de Thu Jan 3 08:05:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 14:05:20 +0100 Subject: Installing pcaplib References: Message-ID: <5u44sgF1gldn9U1@mid.uni-berlin.de> ashish wrote: > Hi All, > > I am trying to install "pylibpcap-0.6.1" but i am getting these errors . > > > python ./setup.py install > > . > . > . > . > . > > constants.c:172: (near initialization for `pcapmodule_DLT[52]') > pcap.c: In function `init_pcap': > pcap.c:4246: structure has no member named `value' > pcap.c:4260: warning: passing arg 3 of `PyModule_AddStringConstant' > discards qualifiers from pointer target type > error: command 'gcc' failed with exit status 1 > > Please tell me how to solve this problem.Do i have to install anything > else before installing this library. Seems like a version-conflict. See which structure pcap.c:4246 refers to, and from what include it stems. If it's a 3rd-party-lib, install the proper version. Diez From sgeiger at ncee.net Tue Jan 15 02:14:18 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 15 Jan 2008 01:14:18 -0600 Subject: Is there some Python function that searches "sys.path" for a module? In-Reply-To: <478c5755$0$36354$742ec2ed@news.sonic.net> References: <478c5755$0$36354$742ec2ed@news.sonic.net> Message-ID: <478C5D4A.7090705@ncee.net> If I understand you correctly, you want this: module.__file__ John Nagle wrote: > Python's own loader searches "sys.path" for module names, but is there > some function that makes that search functionality accessible to > Python programs? I need the absolute pathname of a module, with the > search being done exactly the same way "import" does it. The loader for > "egg" files has this functionality, but I'd like to find out if there's > a standard way to do this before looking into that source code. > > Also, it seems that the environment variable "PYTHONPATH" applies to > "import", but not to the starting module named on the Python command > line. Is that correct? Thanks. > > John Nagle > -- 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 http Fri Jan 11 06:50:53 2008 From: http (Paul Rubin) Date: 11 Jan 2008 03:50:53 -0800 Subject: Learning Python via a little word frequency program References: <205c99df-2550-47b0-9c82-020b99ed3122@l1g2000hsa.googlegroups.com> Message-ID: <7x63y0ins2.fsf@ruckus.brouhaha.com> rent writes: > keys = freq.keys() > keys.sort(key = freq.get, reverse = True) > for k in keys: > print "%-10s: %d" % (k, freq[k]) I prefer (untested): def snd((x,y)): return y # I wish this was built-in sorted_freq = sorted(freq.iteritems(), key=snd, reverse=True) for k,f in sorted_freq: print "%-10s: %d" % (k, f) From pavlovevidence at gmail.com Sun Jan 6 12:08:10 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 6 Jan 2008 12:08:10 -0500 Subject: python interfaces References: <96b70141-f872-413a-a433-08b217cecb27@e4g2000hsg.googlegroups.com> Message-ID: On Sat, 05 Jan 2008 23:31:02 -0800, r.grimm wrote: > They force the user of a framework to use it in a defined way. This is the arrogance of the provider thinking that he can anticipate all the needs of the user. Even when interfaces exist, they should be there to guide the user rather than to force the user. A user should be able to refuse to implement the interface, if the user knows that full implmentation is not necessary, or dangerous. Frankly, a lot of interfaces suck. The user is often a lot smarter than the provider, and nearly always knows his needs better. My sympathies in these matters are entirely on the user's side--I know that's very different from the philosophies of languages like C++ and Java. There's a time and a place for interfaces. Your average run-of-the-mill polymorphism is not it. Usually interfaces are more of a burden than a benefit, especially in code that is young and still subject to lots of redesign and refactoring. And ehen interfaces do make sense, such as in a plugin system or a complex framework, the user should be free to ignore the interface at his own risk. Carl Banks From fetchinson at googlemail.com Wed Jan 30 19:55:09 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 30 Jan 2008 16:55:09 -0800 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> Message-ID: > I do not understand why no one has answered the following question: > > Has anybody worked with Gene Expression Programming???? Hmmmmm, maybe because nobody did? Just a thought. It can also be that everyone worked with it but everyone is part of a big conspiracy not to answer any of your emails just to make you act weird. I'm not sure, I'm really not sure. From arnodel at googlemail.com Mon Jan 28 14:19:33 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 28 Jan 2008 11:19:33 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> Message-ID: On Jan 28, 4:08?pm, "Andr?" wrote: [...] > If I may suggest, I would extend this so that autoassign's signature > would be as follows: > > autoassign(all=True, include_only=None, exclude=None) > > Either one of include_only or exclude could be a list of function to > which the automatic assignment would apply (or not). ? I was planning > to write this up and submit it to the cookbook later this evening, but > since the suggestion has been made, someone else can jump on it. ;-) > > Andr? I've modified my little decorator (see Test1, Test2, Test3 for usage). I'll post it later on the cookbook if there seems to be no bugs and noone raises valid point against it:) from functools import wraps from inspect import getargspec, isfunction from itertools import izip, ifilter, starmap def autoassign(*names, **kwargs): if kwargs: exclude, f = set(kwargs['exclude']), None sieve = lambda l:ifilter(lambda nv: nv[0] not in exclude, l) elif len(names) == 1 and isfunction(names[0]): f = names[0] sieve = lambda l:l else: names, f = set(names), None sieve = lambda l: ifilter(lambda nv: nv[0] in names, l) def decorator(f): fargnames, _, _, fdefaults = getargspec(f) # Remove self for fargnames and make sure fdefaults is a tuple fargnames, fdefaults = fargnames[1:], fdefaults or () defaults = list(sieve(izip(reversed(fargnames), reversed(fdefaults)))) @wraps(f) def decorated(self, *args, **kwargs): assigned = dict(sieve(izip(fargnames, args))) assigned.update(sieve(kwargs.iteritems())) # It would be nice to have a builtin to exhaust iterators: for _ in starmap(assigned.setdefault, defaults): pass self.__dict__.update(assigned) return f(self, *args, **kwargs) return decorated return f and decorator(f) or decorator class Test(object): @autoassign('foo', 'bar') def __init__(self, foo, bar=3, baz=6): print 'baz =', baz class Test2(object): @autoassign def __init__(self, foo, bar): pass class Test3(object): @autoassign(exclude=('foo', 'bar')) def __init__(self, foo, bar, baz=5, **kwargs): pass t = Test(1, 2, 5) u = Test(foo=8) v = Test2(10, 11) w = Test3(100, 101, foobar=102) print t.foo # 1 print t.bar # 2 print u.foo # 8 print u.bar # 3 (default) print v.foo, v.bar # 10 11 print w.baz, w.foobar # 5 102 for obj, attr in ('w', 'foo'), ('w', 'bar'), ('t', 'baz'): try: getattr(globals()[obj], attr) except AttributeError: print '%s.%s raises AttributeError' % (obj, attr) ==== output ==== baz = 5 baz = 6 1 2 8 3 10 11 5 102 w.foo raises AttributeError w.bar raises AttributeError t.baz raises AttributeError -- Arnaud From steven.klass at gmail.com Mon Jan 21 15:03:32 2008 From: steven.klass at gmail.com (rh0dium) Date: Mon, 21 Jan 2008 12:03:32 -0800 (PST) Subject: Building a pretrigger / posttrigger framework class Message-ID: <3b913ec9-aebd-49bf-b938-074df787afd8@q39g2000hsf.googlegroups.com> Hi all, I am thinking about a class which can automatically determine the order which it is run. I would like to implement a super class which has a run() method and a pretrigger() method. The purpose of the pretrigger method is to state what classes need to be run before this class.run() method is executed. So for example: class superclass(object): def run(self): """Method which will get overriden""" def pretrigger(self): """Method which will get overriden and determine the order""" class subclassA(superclass): def run(self): print "I am subclass A" def pretrigger(self): return [subclassB(),] class subclassB(superclass): def run(self): print "I am subclass B" def pretrigger(self): None return [subclassC(), ] class subclassC(superclass): def run(self): print "I am subclass C" def pretrigger(self): None return None Now what I am looking for is some logic which can look at this and draw the following conclusion. - In order to run subclassA, I first need to run subclassB. In order to run subclassB I need to run subclassC. So the order to run this would be subclassC, subclassB, then subclassA. I would also like some information on is this a good approach to using a superclass or not? Any and all comments are welcome. Thanks!! From http Mon Jan 28 01:17:30 2008 From: http (Paul Rubin) Date: 27 Jan 2008 22:17:30 -0800 Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <7xbq76pva9.fsf@ruckus.brouhaha.com> Message-ID: <7x1w82xymd.fsf@ruckus.brouhaha.com> Paddy writes: > Given the complexity of current microprocessors i'm guessing that > their previous testing methods would be too good to just junk in > totality because the FDIV bug was not found. Similarly if they were > not using formal methods then it makes sense to add it too your > arsenal; and unfortunately it takes a mistake like that to allow > different methods to be explored and incorporated. Fair enough. My main issue was against the notion that random testing is the only thing necessary. From fn681 at ncf.ca Sun Jan 27 08:29:56 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sun, 27 Jan 2008 08:29:56 -0500 Subject: how to make format operator % work with unicode as expected In-Reply-To: References: <13po55nc0q0s06@corp.supernews.com> Message-ID: Peter Pei wrote: > You didn't understand my question, but thanks any way. > > Yes, it is true that %s already support unicode, and I did not > contradict that. But it counts the number of bytes instead of > characters, and makes things like %-20s out of alignment. If you don't > understand my assertion, please don't argue back and I am only > interested in answers from those who are qualified. Peter, Rudeness is inappropriate whether the person being attacked is a frequent or infrequent contributer to this list. Colin W From tjreedy at udel.edu Mon Jan 14 22:21:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Jan 2008 22:21:08 -0500 Subject: SimCity GPLed Message-ID: http://weblogs.asp.net/bsimser/archive/2008/01/10/simcity-source-code-released-to-the-wild-let-the-ports-begin.aspx The release appears to include both a C/Tcl/TK version and a C++/Python version of at least part. "The code hopefully serves as a good example of how to use SWIG to integrate C++ classes into Python and Cairo, in a portable cross platform way that works on Linux and Windows." I have not gotten the code yet. From fredrik at pythonware.com Wed Jan 9 15:56:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 21:56:16 +0100 Subject: alternating string replace: Extended input (Long). In-Reply-To: References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: Donald 'Paddy' McCarthy wrote: > I created some more test strings and ran posters solutions against them. the point being? From usenet at nicko.org Fri Jan 25 13:45:02 2008 From: usenet at nicko.org (Nicko) Date: Fri, 25 Jan 2008 10:45:02 -0800 (PST) Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> Message-ID: <690cb460-fa8a-49a1-a6fa-69cdf480a918@i3g2000hsf.googlegroups.com> On Jan 24, 9:26 pm, Ira.Ko... at gmail.com wrote: > > If you really have a 2GB file and only 2GB of RAM, I suggest that you don't hold your breath. > > I am limited with resources. Unfortunately. As long as you have at least as much disc space spare as you need to hold a copy of the file then this is not too hard. Split the file into chunks that are small enough to fit in memory, sort each chunk and write it to a file and then interleave the chunks. Below is a cheap and cheesy outline of code to do this, from which you can start. For files which are hugely larger than your available memory you can do this recursively but for files which are 10 to 100 times too big the single-pass code below will probably work just fine. The complexity is technically O(n.(log(c)+(n/c))) where n is the size of input and c is the chunk size; once n/c (the number of chunks) exceeds log(c) the cost of merging the chunks will start to dominate, though a recursive version would be slowed by needing a lot more disc access. #!/usr/bin/env python from itertools import islice from tempfile import TemporaryFile import sys # Tweak this number to fill your memory lines_per_chunk = 100000 chunkfiles = [] mergechunks = [] while True: chunk = list(islice(sys.stdin, lines_per_chunk)) if not chunk: break chunk.sort() f = TemporaryFile() f.writelines(chunk) f.seek(0) mergechunks.append((chunk[0], len(chunkfiles))) chunkfiles.append(f) while mergechunks: # The next line is order O(n) in the number of chunks (line, fileindex) = min(mergechunks) mergechunks.remove((line, fileindex)) sys.stdout.write(line) nextline = chunkfiles[fileindex].readline() if nextline == "": chunkfiles[fileindex].close() else: mergechunks.append((nextline, fileindex)) From workitharder at gmail.com Fri Jan 4 11:51:45 2008 From: workitharder at gmail.com (bukzor) Date: Fri, 4 Jan 2008 08:51:45 -0800 (PST) Subject: how to use bool References: Message-ID: <05c5df8b-15c4-47e6-8c14-72c57a84a0ea@y5g2000hsf.googlegroups.com> On Jan 3, 7:49 am, jimgarde... at gmail.com wrote: > hi, i have some code where i set a bool type variable and if the value > is false i would like to return from the method with an error msg.. > being a beginner I wd like some help here > > class myclass: > ......... > def mymethod(self): > success=True > msg="all validation OK" > success=validateSthing() > if(success==False): > msg="sthing failed" > return (success,msg) > > dosomeprocessing() > ..... > success=validateSthingelse() > if(success==False): > msg="sthingelse failed" > return (success,msg) > domoreprocessing() > .... > return(success,msg) > > i would like to know if this way of doing this is OK..I have need of > many kinds of validations in this ..is there a better way of doing > this ? > > thank you class SthingError(Exception): def __init__(self, success, msg): class myclass: ......... def mymethod(self): success=True if not validateSthing(): msg="sthing failed" return (success,msg) dosomeprocessing() ..... if not validateSthingelse(): msg="sthingelse failed" return (success,msg) domoreprocessing() .... return(success,"all validation OK") From arnodel at googlemail.com Mon Jan 21 05:49:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 21 Jan 2008 02:49:19 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: <0cb72e5b-8fb4-453a-bd3e-f53a47c9b6bc@m34g2000hsb.googlegroups.com> On Jan 21, 9:01?am, dg.google.gro... at thesamovar.net wrote: > Hi all, > > It's great how many different sorts of solutions (or almost solutions) > this puzzle has generated. Speedwise, for reference my solution posted > above takes about 40 seconds on my 1.8GHz laptop, and the less elegant > version (on my webpage linked to in the original post) takes about 15 > seconds. It seems to me like surely this problem can be more > efficiently solved than that? I haven't had the time to look at your solution yet. I wanted to have a go without being influenced. > Arnaud: I haven't had time to play with your solution yet - how quick > does it run? I can't run test from here (work) but last night it seemed of the order of a second on my 2GHz MacBook Pro (it was late and I was quite tired so I didn't have the energy to time anything...). It depends if you stop when you hit the first solution or you want to go through all of them. I guess it will run quicker if I don't build a string representation of each calculation. You should run a test on your own machine though to make comparisons meaningful. > My fantasy is that there is a solution that isn't TOO slow where you > can just look at the code and go 'Oh yes, of course that works!' and > understand it immediately. Maybe that's too much to ask even of > Python! ;-) It's a laudable goal. We might get there :) -- Arnaud From hat at se-162.se.wtb.tue.nl Mon Jan 14 03:01:42 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 14 Jan 2008 09:01:42 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: On 2008-01-13, Erik Lind wrote: > I'm new to Python, and OOP. I've read most of Mark Lutz's book and more > online and can write simple modules, but I still don't get when __init__ > needs to be used as opposed to creating a class instance by assignment. For > some strange reason the literature seems to take this for granted. I'd > appreciate any pointers or links that can help clarify this. I think you mean the following: You'd like to do p = Person('me', 'here', 31) and you are wondering why you need the __init__() function in class Person(object): def __init__(self, name, addres, age): self.name = name self.address = address self.age = age right? If so, the answer is that while you think you are doing "Person('me', 'here', 31)", you are in reality executing "Person.__init__(self, 'me', 'here', 31)", where 'self' is refers to a shiny new, empty object created for you. (and the 'self' is obtained by the Person.__new__ function I think, but others here have much better knowledge about this). Sincerely, Albert From cokofreedom at gmail.com Wed Jan 23 03:58:54 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 23 Jan 2008 00:58:54 -0800 (PST) Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? References: Message-ID: <89c55be4-9110-4945-873e-00718994da68@u10g2000prn.googlegroups.com> On Jan 23, 9:45 am, Kristian Domke wrote: > Hello to all > > I am trying to learn python at the moment studying an example program > (cftp.py from the twisted framework, if you want to know) > > There I found a line > > foo = (not f and 1) or 0 > > In this case f may be None or a string. > > If I am not wrong here, one could simply write > > foo = not f > > because if f = None: > > (not f) = true, > (true and 1) = true, > (true or 0) = true > > or if f = 'bar' > > (not f) = false > (false and 1) = false > (false or 0) = false > > So why bothering with the longer version? > > I hope, I made clear, what I want... > > CU > > Kristian f = None foo = (not f and 1) or 0 # this gives you 1 f = None foo = not f # this gives you True From http Mon Jan 14 20:13:44 2008 From: http (Paul Rubin) Date: 14 Jan 2008 17:13:44 -0800 Subject: Dynamical scoping References: <1a3243ef-13f6-40d6-97eb-198b8742ac3d@d4g2000prg.googlegroups.com> Message-ID: <7xabn7hovr.fsf@ruckus.brouhaha.com> George Sakkis writes: > What's the best way to simulate dynamically scoped variables ala Lisp ? Ugh.... check the docs for the python 2.5 "with" statement, which gives you sort of a programmable unwind-protect (more powerful than try/except). You'd have an environment dictionary and use the "with" statement to maintain a stack of shallow-binding cells like in an old-time lisp system, automatically unwinding when the "with" suite finishes. The whole concept sounds hopelessly crufty--I think nobody even does it that way in Lisp any more, you're better off passing an environment around explicitly. If there were a lot of variables, this could be a good application for functional maps, which I've been wanting to implemetn for python. From dikkie at nospam.org Tue Jan 1 11:48:44 2008 From: dikkie at nospam.org (Dikkie Dik) Date: Tue, 01 Jan 2008 17:48:44 +0100 Subject: pexpect ssh login and ls | grep In-Reply-To: <3eb81375-3e4a-4e0f-a4e7-bbb1d6cd0f8c@s19g2000prg.googlegroups.com> References: <3eb81375-3e4a-4e0f-a4e7-bbb1d6cd0f8c@s19g2000prg.googlegroups.com> Message-ID: <477a6eec$0$17448$bf4948fe@news.tele2.nl> > shell_cmd = 'ls -l | grep mytest.log' > child = pexpect.spawn ('ssh my at mycomp2') I think you can give the ssh command an option to execute a file remotely. That way, one command would be enough. From rdm at rcblue.com Sat Jan 12 21:28:51 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 12 Jan 2008 18:28:51 -0800 Subject: Great Python books for the beginner In-Reply-To: References: Message-ID: <20080113022855.B97011E401B@bag.python.org> At 11:03 PM 1/11/2008, Landon wrote: >Hi, I'm a freshman in college and I'm going to be taking an intro to >programming course next semester which mainly uses Python, so I >thought it might be a good time to pick up Python beyond the scope of >the class as well. The text book for this class is Python for the >Absolute Beginner or something similar to that name. > >I was wondering if anyone had any opinions on what other titles I >could look into since this one seems from a glance at reviews to be >teaching mainly through game programming (a topic I'm not too >interested in) or if this one is a quality book by itself. Yes, it's a quality book, IMO. I hope by now you've gotten over your dislike for online tutorials. Please take a look at these 3: Hands-On Python How to Think Like a (Python) Programmer Alan Gauld's Learning to Program (heavy emphasis on Python) Also, do take advantage of the VERY helpful Tutor mailing list. . Dick Moores >-- >http://mail.python.org/mailman/listinfo/python-list From tarun.kap at gmail.com Wed Jan 16 13:02:15 2008 From: tarun.kap at gmail.com (Tarun Kapoor) Date: Wed, 16 Jan 2008 10:02:15 -0800 (PST) Subject: paramiko References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> Message-ID: <8ceaad4c-c725-4093-a204-ab09162d4629@c23g2000hsa.googlegroups.com> On Jan 16, 11:38 am, "Guilherme Polo" wrote: > 2008/1/16, Tarun Kapoor : > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across > > the connection > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > sock.connect((hostname, port)) > > > t = paramiko.Transport(sock) > > t.start_client() > > key = t.get_remote_server_key() > > > event = threading.Event() > > t.auth_password(username=username, password=password, event=event) > > event.wait() > > > if not t.is_authenticated(): > > print "not authenticated" > > > output: > > not authenticated > > This is a different problem I guess, now you are usin get_remote_server_key. > And why are you creating event after calling start_client without > specifying it ? > > > > > > > On Jan 16, 11:11 am, "Guilherme Polo" wrote: > > > 2008/1/16, Tarun Kapoor : > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > > > > the remote server using an SFTP client I have just to make sure that > > > > username and password are working.. This is the code. > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > > > > connection > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > > sock.connect((hostname, port)) > > > > > t = paramiko.Transport(sock) > > > > > event = threading.Event() > > > > > t.start_client(event) > > > > > event.wait(15) > > > > > if not t.is_active(): > > > > > print 'SSH negotiation failed.' > > > > > sys.exit(1) > > > > > else: > > > > > print "SSH negotiation sucessful" > > > > > event.clear() > > > > > t.auth_password(username=username, password=password,event=event) > > > > > if not t.is_authenticated(): > > > > > print "not authenticated" > > > > > output: > > > > > SSH negotiation successful > > > > > not authenticated > > > > > Tarun > > > > > Waterstone Capital Management > > > > > 2 Carlson Parkway, Suite 260 > > > > > Plymouth, MN 55447 > > > > > Direct: 952-697-4123 > > > > > Cell: 612-205-2587 > > > > Disclaimer This e-mail and any attachments is confidential and intended > > > > solely for the use of the individual(s) to whom it is addressed. Any views > > > > or opinions presented are solely those of the author and do not necessarily > > > > represent those of Waterstone Capital Management, L.P and affiliates. If you > > > > are not the intended recipient, be advised that you have received this > > > > e-mail in error and that any use, dissemination, printing, forwarding or > > > > copying of this email is strictly prohibited. Please contact the sender if > > > > you have received this e-mail in error. You should also be aware that > > > > e-mails are susceptible to interference and you should not assume that the > > > > contents of this e-mail originated from the sender above or that they have > > > > been accurately reproduced in their original form. Waterstone Capital > > > > Management, L.P. and affiliates accepts no responsibility for information, > > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > > > > please verify the authenticity with the sender. > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > You are missing an event.wait() after t.auth_password. > > > Also, why are you passing this magic value "15" to event.wait() ? That > > > parameter is passed to class _Verbose to indicate if debug messages > > > should be displayed or not, so typical values would be 0/1 or > > > False/True. > > > > -- > > > -- Guilherme H. Polo Goncalves > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves ok here is the problem... I don't know what is the correct way... The only demos i have from the paramiko library use a hostkeyfile. since i don't have that i thought i would use the get_remote_key to get the key and then connect it using the code in the demo.. But clearly nothing is working...I should not HAVE to use the key since i should be able to authenticate using the password... Can you please suggest the right way to go ? Thanks for your time ! From mail at timgolden.me.uk Wed Jan 30 07:01:51 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 30 Jan 2008 12:01:51 +0000 Subject: find nearest time in datetime list In-Reply-To: <15180398.post@talk.nabble.com> References: <15180398.post@talk.nabble.com> Message-ID: <47A0672F.3090702@timgolden.me.uk> washakie wrote: > Hello, > > I have a list of datetime objects: DTlist, I have another single datetime > object: dt, ... I need to find the nearest DTlist[i] to the dt .... is > there a simple way to do this? There isn't necessarily an exact match... import datetime dates = [datetime.date (2007, 1, (1+i)*2) for i in range (10)] one_date = datetime.date (2007, 1, 7) print sorted (dates, key=lambda x: abs (x-one_date))[0] TJG From pavloutefkros at gmail.com Mon Jan 28 16:32:45 2008 From: pavloutefkros at gmail.com (pavloutefkros at gmail.com) Date: Mon, 28 Jan 2008 13:32:45 -0800 (PST) Subject: post variable References: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> <87ir1dr8ms.fsf@mulj.homelinux.net> Message-ID: <0f634854-7d7a-4ad8-ba04-38d239ecf850@d70g2000hsb.googlegroups.com> 1. yes i've tried that technique but its annoying, the user can easily stop the redirection and not "elegant". 2. yes i'm aware of that, however what i've mentioned above is just an example, it's actually way more serious. guess i'll have to bare with it. From kar1107 at gmail.com Sat Jan 26 00:43:48 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Fri, 25 Jan 2008 21:43:48 -0800 (PST) Subject: finding child cpu usage of a running child Message-ID: Hi, Wondering if there is a way to measure a child process's cpu usage (sys and user) when the child is still running. I see os.times() working fine in my system (Linux 2.6.9-42.7.ELsmp), but it gives valid data only after the child has exited. When the child is alive, os.times() data for child is zero for both child-sys and child-user cpu. My script (process P1) launches child process P2 (using popen2.Popen3). P2 is a long running process (big compilation). Every minute or so, from P1, I want to measure how much cpu P2 has consumed and based on that I can make some estimate on the completion time of P2 (I have a rough idea how much total cpu P2 needs to complete). I understand it may be too expensive to update this information to the parent process when any of the child/grand-child completes; but wondering if any there is any way to get this info; the expensive operations is on-demand only when the request is made. Thanks, Karthik From steve at REMOVE-THIS-cybersource.com.au Sat Jan 26 06:46:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 26 Jan 2008 11:46:49 -0000 Subject: Hashable References: Message-ID: <13pm7d9sse1aba4@corp.supernews.com> On Sat, 26 Jan 2008 11:10:03 +0000, Simon Pickles wrote: > Hi, > > The term 'hashable'. > > Am I right in thinking it means it can be indexed? like a string or a > dict? No. A hash function is a function which takes an arbitrary object and generates an integer from it. Python has a built-in hash function hash(). It says: help(hash): hash(...) hash(object) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely. Examples: >>> hash(5.5) 1476493312 >>> hash('five') 202874452 >>> hash('fivf') 202874455 >>> hash(None) 54045056 Not all objects are hashable: >>> hash([]) Traceback (most recent call last): File "", line 1, in TypeError: list objects are unhashable Python dictionaries are "hash tables". A hash table is a data structure that let's you look up a key in (virtually) a constant amount of time no matter how many items there are in the table. It does this by calculating the hash of the key, then using that hash to calculate the index in the table where it expects to find the key's data. A good hash table (like Python dicts) is *very* fast. But notice that the object which _uses_ the hash (the dict) is not hashable itself; and that the objects which are hashable (strings, ints, floats, etc.) don't necessarily have an index. Strings do, tuples do, but ints and floats and other objects don't. -- Steven From Russ.Paielli at gmail.com Sun Jan 27 17:19:02 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 14:19:02 -0800 (PST) Subject: optional static typing for Python Message-ID: A while back I came across a tentative proposal from way back in 2000 for optional static typing in Python: http://www.python.org/~guido/static-typing Two motivations were given: -- faster code -- better compile-time error detection I'd like to suggest a third, which could help extend Python into the safety-critical domain: -- facilitates automated source-code analysis There has been much heated debate in the past about whether Python is appropriate for safety-critical software. Some argue that, with thorough testing, Python code can be as reliable as code in any language. Well, maybe. But then, a famous computer scientist once remarked that, "Program testing can be used to show the presence of bugs, but never to show their absence!" --Edsger Dijkstra The next step beyond extensive testing is automated, "static" analysis of source-code ("static" in the sense of analyzing it without actually running it). For example, Spark Ada is a subset of Ada with programming by contract, and in some cases it can formally prove the correctness of a program by static analysis. Then there is Java Pathfinder (http://javapathfinder.sourceforge.net), an "explicit state software model checker." The developers of JPF wanted to use it on a prototype safety-critical application that I wrote in Python, but JPF only works on Java code. We considered somehow using Jython and Jythonc, but neither did the trick. So they ended up having someone manually convert my Python code to Java! (The problem is that my code was still in flux, and the Java and Python versions have now diverged.) In any case, optional static typing in Python would help tremendously here. The hardest part of automated conversion of Python to a statically typed language is the problem of type inference. If the types are explicitly declared, that problem obviously goes away. Explicit typing would also greatly facilitate the development of a "Python Pathfinder," so the conversion would perhaps not even be necessary in the first place. Note also that, while "static" type checking would be ideal, "explicit" typing would be a major step in the right direction and would probably be much easier to implement. That is, provide a syntax to explicitly declare types, then just check them at run time. A relatively simple pre-processor could be implemented to convert the explicit type declarations into "isinstance" checks or some such thing. (A pre-processor command-line argument could be provided to disable the type checks for more efficient production runs if desired.) I noticed that Guido has expressed further interest in static typing three or four years ago on his blog. Does anyone know the current status of this project? Thanks. From bignose+hates-spam at benfinney.id.au Thu Jan 31 08:35:46 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 01 Feb 2008 00:35:46 +1100 Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> <58d1bc12-206f-4cec-ad86-928d16e962f5@i3g2000hsf.googlegroups.com> <8d69e9e8-c892-4c65-ac54-c184ce303a2e@i3g2000hsf.googlegroups.com> Message-ID: <87zlumjex9.fsf@benfinney.id.au> Dustan writes: > On Jan 30, 7:02 pm, FireNWater wrote: > > Thank you for the explanation. . . I think I now have a (foggy) > > understanding of hash tables. It seems to be a way to create order > > (an index) out of disorder (random numbers or characters) behind > > the scenes. . > > The key thing to realize is, quite simply, don't rely on order in a > dictionary. The poster to which you replied is using "order" as contrasted with "disorder". Clearly dictionaries *do* have order that can be relied upon. I think you're using "order" in the colloquial manner; more accurate would be to say "don't rely on *sequence* in a dictionary". -- \ "Our task must be to free ourselves from our prison by widening | `\ our circle of compassion to embrace all humanity and the whole | _o__) of nature in its beauty." ?Albert Einstein | Ben Finney From steven at REMOVE.THIS.cybersource.com.au Mon Jan 21 04:06:44 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 09:06:44 -0000 Subject: When is min(a, b) != min(b, a)? References: Message-ID: On Sun, 20 Jan 2008 21:15:02 -0600, Albert Hopkins wrote: > This issue may have been referred to in > news: but I didn't > entirely understand the explanation. Basically I have this: > > >>> a = float(6) > >>> b = float('nan') > >>> min(a, b) > 6.0 > >>> min(b, a) > nan > >>> max(a, b) > 6.0 > >>> max(b, a) > nan > > Before I did not know what to expect, but I certainly didn't expect > this. So my question is what is the min/max of a number and NaN or is > it not defined (for which I would have expected either an exception to > be raised or NaN returned in each case). According to the IEEE-754 standard the usual trichotomy of "x is less than y, x is equal to y, or x is greater than y" has to be extended to include "x and y are unordered". Comparisons with NaNs are unordered, and so expressions like "x < nan" should signal an exception. (However both == and != do not signal exceptions, they return False and True respectively.) Unfortunately, the standard conflicts with Python's requirement that comparisons should always return True or False, so the next "least bad" alternative is to have comparisons with NaN to return False. That is: >>> 5 < float('nan') False >>> 5 >= float('nan') False So BEWARE of assuming that if x < y returns False, y >= x must return True. That does not hold for floats. Aside: Apple's Power PC Numerics math library extended the usual six comparison operators to fourteen. I don't judge whether this was a good idea or not. http://developer.apple.com/documentation/mac/PPCNumerics/PPCNumerics-37.html#MARKER-9-1 Given that NaNs are unordered, the "right" thing for max() and min() to do is raise an exception. But failing that, the next best thing would be for them to ignore any NaNs. Any way you look at it, for min or max to return a nan is a mistake. Possibly even a bug. > As a corrollary would I be able to rely on the above behavior or is it > subject to change (to fix a bug in min/max perhaps :-)? Presently, you can't rely on *any* behaviour of NaNs and INFs in Python, since they all depend on the underlying C library. Even whether or not you can create them is not defined in Python. -- Steven From lizm at rcsltd.co.uk Wed Jan 23 09:41:32 2008 From: lizm at rcsltd.co.uk (LizzyLiz) Date: Wed, 23 Jan 2008 06:41:32 -0800 (PST) Subject: csv to xls using python 2.1.3 Message-ID: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> Hi I need to convert a .csv file to .xls file using python 2.1.3 which means I can't use pyExcelerator! Does anyone know how I can do this? Many thanks LizzyLiz From cesmiga at gmail.com Tue Jan 29 15:23:41 2008 From: cesmiga at gmail.com (epsilon) Date: Tue, 29 Jan 2008 12:23:41 -0800 (PST) Subject: Decision (if, else) routine is not working as intended with CGI module Message-ID: <9dc9f5d3-2392-48d6-8cb4-8b31c1ce4af9@e6g2000prf.googlegroups.com> All: I'm running into trouble figuring this one out. It seems that my decision routine is not working as intended. Does anyone know why my output continues to utilize the "else" portion of the routine. Thank you, Christopher ++++++++++ #!/usr/bin/python import cgi print "Content-type: text/plain\n" tag_form = cgi.FieldStorage(keep_blank_values=True) #if not tag_form.has_key("fse00"): if tag_form["fse00"] == "": fse000 = {"fse00": "0"} tag_form.update(fse000) print "Printing fse000: ", tag_form["fse00"] else: print "Printing fse00: ", tag_form["fse00"] From deets at nospam.web.de Fri Jan 11 11:16:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jan 2008 17:16:13 +0100 Subject: Python Frontend/GUI for C Program In-Reply-To: References: Message-ID: <5upj2dF1fbbb8U1@mid.uni-berlin.de> byte8bits at gmail.com schrieb: > I have a C program that works very well. However, being C it has no > GUI. Input and Output are stdin and stdout... works great from a > terminal. Just wondering, has anyone every written a Python GUI for an > existing C program? Any notes or documentation available? > > I have experience using wxPython from within Python apps and I like it > a lot for its cross-platform capabilities. I was hoping to use > wxPython for this as well. Modules subprocess and pexpect (3rd-party-package) are your friends. Alternatively, if you have the source for the C-app, exposing it's functionality as DLL/SO and using ctypes as means to access it might work as well. Diez From dwblas at gmail.com Wed Jan 23 20:14:35 2008 From: dwblas at gmail.com (dwblas at gmail.com) Date: Wed, 23 Jan 2008 17:14:35 -0800 (PST) Subject: Linux Journal Survey Message-ID: The annual Linux Journal survey is online now for any Linux users who want to vote for Python. http://www.linuxjournal.com/node/1006101 From Matthew_WARREN at bnpparibas.com Thu Jan 31 11:43:38 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Thu, 31 Jan 2008 16:43:38 +0000 Subject: very simple Genetic Algorithm completed Message-ID: 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 sum that evaluates to n using */+-0123456789' it's a really simple GA that would be useful for someone who doesn't quite get GA's to look at. I think it's simple enough to be fairly self explanatory. to see it come up with evolved solutions to n=1000 >>>from quickga import * >>>evolve() I like playing with stuff like this. I'm going to use this little toy to investigate how mutation rates/crossover gene length, pop size etc.. etc.. interact with each other. All completely unscientifically and for my own bemusement. One point, it's a good idea to keep mutationrate around 1000 - 10000 with genome and population sizes of say 50 - 100. Too low and you get no solution as the mutations mix up the genome too much for selection pressure to work. ...as this actually does need to go as quick as it can, and if anyone feels like it, I'd really appreciate picking it over on the list for optimization. I'm not too familiar with Pthon internals, nor programming for speed in general.
from random import randint
from operator import itemgetter


genes=['+','-','*','/','0','1','2','3','4','5','6','7','8','9']
signs=['+','-','*','/']
digits=['1','2','3','4','5','6','7','8','9']

table = {"++": "+", "+-": "-", "+*": "+", "+/": "+",
    "-+": "-", "--": "+", "-*": "-", "-/": "-",
    "*+": "*", "**": "*", "*/": "*",
    "/+": "/", "/*": "/", "//": "/",
         "+0":"+","*0":"*","-0":"-","/0":"/"} # keep out octal literals

def rationalise_signs(s):
        """Takes the genome string and twiddles it so eval() will work as
expected
        """
        prev = ''
        while s != prev:
                prev=s
                for z in ['+','-','*','/']:
                        s=s.replace(z+'0',z)
                for key, value in table.items():
                        s = s.replace(key, value)
        s=s.lstrip('0')
        s=s.strip('+-*/')
        return s



def generate(number,length):
        """Generate the initial population of genome strings
        """
        population=[]
        for i in range(number):
                s=rationalise_signs(''.join([
genes[randint(0,len(genes))-1] for n in range(length) ]))
                population.append(s)
        return population


def floatify(intstring):#So eval() be floating point.
        """kludge to ensure eval() does floating point math
        """
        prev=''
        while intstring != prev:
                prev=intstring
                for sign in signs:
                        for digit in digits:

intstring=intstring.replace(digit+sign,digit+'.0'+sign)
        return intstring

def express(population):
        """Get the 'expression' of the genome.
        """
        expressed_population=[]
        for individual in population:
                s=floatify(individual)
                expressed_population.append((individual,eval(s)))
        return expressed_population

def fitness(expressed_population,fitvalue,tolerance):
        """Test the expressed genome for fitness
        """
        population_fitness=[]
        sumfitness=0
        for expressed_individual in expressed_population:
                individual,expression=expressed_individual
                fitness=abs(fitvalue-expression)
                sumfitness=sumfitness+fitness
                population_fitness.append((individual,expression,fitness))
        avgfitness=sumfitness/len(expressed_population)
        return (population_fitness,avgfitness)



def get_fittest(population_fitness,pct,full=False):
        """Quick n dirty way of selecting - top n% fittest individuals
        """
        population_fitness.sort(key=itemgetter(2))#sort on fitness
        npct=(len(population_fitness)/100.0)*pct
        if not full:
                return [ n[0] for n in population_fitness[0:int(npct)] ]
        else:
                return population_fitness[0:int(npct)]


def mutate(individual,rate):
        """Does what it says on the tin. Mutates per gene
        if rate is 10000 mutatuion rate is 1 in 10000 on avg
        """
        newindividual=''
        for gene in individual:
                if randint(0,rate)==1:
                        newgene=genes[randint(0,14)-1]
                        newindividual=newindividual+newgene
                else:
                        newindividual=newindividual+gene
        return newindividual

def breed_new(individuals,number,mutationrate):#crossover with mutation
        """simple crossover of the two genomes around a point, then mutate
        """
        newpopulation=[]
        num_individuals=len(individuals)
        while len(newpopulation)<=number:
                lady=individuals[randint(0,num_individuals-1)]
                man=individuals[randint(0,num_individuals-1)]
                xpoint=randint(0,100)
                xlady=(len(lady)/100.0)*xpoint
                xman=(len(man)/100.0)*xpoint
                leftxlady=lady[:int(xlady)]
                rightxlady=lady[int(xlady):]
                leftxman=man[:int(xman)]
                rightxman=man[int(xman):]

new1=rationalise_signs(mutate(leftxlady+rightxman,mutationrate))

new2=rationalise_signs(mutate(leftxman+rightxlady,mutationrate))
                newpopulation.append(new1)
                newpopulation.append(new2)
        return newpopulation


def
evolve(popsize=50,genomelength=100,mutationrate=10000,fitcullpct=10,numsolutions=5,target=1000,tolerance=1):
        """Controls the whole process.
        """
        pop=generate(popsize,genomelength)
        fitgens=[]
        generation=1
        while len(fitgens)tolerance:

pop=breed_new(get_fittest(fpop,fitcullpct),popsize,mutationrate)
                        generation=generation+1
                else:
                        print "Pop avg fitness within tolerance"
                        print "********************************"
                        fitgens.append((fpop[0:],generation))
                        pop=generate(popsize,genomelength)
                        generation=1
        outlist=[]
        for fitpop,generation in fitgens:
                bestfitpop=get_fittest(fitpop,20,full=True)
                for fitgeneinfo in bestfitpop:
                        genome,number,avgfit=fitgeneinfo
                        prev=''
                        s=floatify(genome)
                        outlist.append(genome+" in "+str(generation)+"
generations got "+str(number)+" avg fit ="+str(avgfit))
        for line in set(outlist):
                print line

Matt. (Apologies for any 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 paddy3118 at googlemail.com Fri Jan 25 10:30:14 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 25 Jan 2008 07:30:14 -0800 (PST) Subject: Text-based data inspector for Python? References: <6398ab68-da01-408e-902b-0b488310e9b0@e10g2000prf.googlegroups.com> Message-ID: <98d4d552-20d6-42f4-9d50-2c9ca1b3a4d0@e25g2000prg.googlegroups.com> On Jan 25, 1:47 pm, kj wrote: > In <6398ab68-da01-408e-902b-0b488310e... at e10g2000prf.googlegroups.com> Paddy writes: > > >I tend to do the following at the python prompt: > > from pprint import pprint as pp > > Thanks, that's a good one to know, but isn't there a way to automate > it??? > > I looked around, but I couldn't find the name of any *rc-type file > that would hold interpreter customizations. The closest I found > was ~/.pythonrc.py, but that still requires doing "import user" at > every interpreter session. (As annoyances go, this is certainly > a minor one, but with me the psychological effects of such small > annoyances gets magnified in proportion to how unnecessary they > seem.) Plus, I'm not sure that it'd be such a great idea to execute > code intended to customize the interpreter every time that the user > module gets loaded... > > kynn > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. python -h gives me: ... Other environment variables: PYTHONSTARTUP: file executed on interactive startup (no default) ... - Paddy. From gagsl-py2 at yahoo.com.ar Fri Jan 25 18:00:02 2008 From: gagsl-py2 at yahoo.com.ar (gagsl-py2 at yahoo.com.ar) Date: Fri, 25 Jan 2008 20:00:02 -0300 (ART) Subject: paging in python shell In-Reply-To: Message-ID: <857659.95304.qm@web32813.mail.mud.yahoo.com> --- Alex K escribi?: > Thank you for this interesting tip. However I'm not > sure to know how > to use it. It seems pydoc.pager('text') just pages > the text passed in. > How do I actually make the python shell use a > different pager? I'm unsure of what you want. Do you want the print statement, inside the Python interpreter, to page its output? Write a function to page the output the way you like, and assign it to sys.displayhook (see http://docs.python.org/lib/module-sys.html#l2h-5124 ) -- Gabriel Genellina Tarjeta de cr?dito Yahoo! de Banco Supervielle. Solicit? tu nueva Tarjeta de cr?dito. De tu PC directo a tu casa. www.tuprimeratarjeta.com.ar From lists at cheimes.de Sun Jan 20 11:09:30 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 20 Jan 2008 17:09:30 +0100 Subject: Memory errors with imaplib In-Reply-To: <13p6pf5he8am89e@corp.supernews.com> References: <6012daff-0fd3-4835-a9ca-c18d2a2ac53c@v29g2000hsf.googlegroups.com> <13p6pf5he8am89e@corp.supernews.com> Message-ID: Grant Edwards wrote: > The problem and the one-line soulution have been known for over > two years and it's still an open bug? Nobody was interested to provide a patch. I raised the level of the bug. It's going to be fixed soonish. Christian From thermostat at gmail.com Wed Jan 16 13:45:46 2008 From: thermostat at gmail.com (Dan) Date: Wed, 16 Jan 2008 10:45:46 -0800 (PST) Subject: Interesting Thread Gotcha References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> <5v70v9F1kmtinU1@mid.uni-berlin.de> Message-ID: On Jan 16, 1:33 pm, "Diez B. Roggisch" wrote: > Dan schrieb: > > > > > On Jan 16, 11:06 am, "Diez B. Roggisch" wrote: > >> Hendrik van Rooyen wrote: > >>> "Dan" wrote: > >>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) > >>>> Needs to be > >>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) > >>>> Commas are important! > >>>> -Dan > >>> Absolutely! - well spotted! > >>> As the first correct respondent, you win the freedom to spend a week in > >>> Naboomspruit at your own expense. > >>> It would have been nice, however, to have gotten something like: > >>> TypeError - This routine needs a tuple. > >>> instead of the silent in line calling of the routine in question, > >>> while failing actually to start a new thread. > >> You can't prevent the silent inline-calling - otherwise, how would you do > >> this: > > >> def compute_thread_target(): > >> def target(): > >> pass > >> return target > > >> thread.start_new_thread(compute_thread_target()) > > >> Of course start_new_thread could throw an error if it got nothing callable > >> as first argument. No idea why it doesn't. > > >> Diez > > > Of course, in his case, having start_new_thread throw an error > > wouldn't have helped, since he went into an infinite loop while > > evaluating the parameters for start_new_thread. > > > Would it be possible to have pychecker (or some such) warn that there > > is an insufficient parameter count to start_new_thread? I guess that > > would require knowing the type of thread. . . > > What has this to do with the second argument? It's perfectly legal to > have a function as thread-target that takes no arguments at all, so > enforcing a second argument wouldn't be helpful - all it would do is to > force all developers that don't need an argument tuple to pass the empty > tuple. So there was no insufficient argument count. > > And none of these would solve the underlying problem that in python > expressions are evaluated eagerly. Changing that would mean that you end > up with a totally new language. > > the only thing that could help to a certain extend would be static > types. Which we don't want here :) > > Diez It doesn't seem to be legal in my version of python (or the doc): >>> import thread >>> def bat(): print "hello" >>> thread.start_new_thread(bat) Traceback (most recent call last): File "", line 1, in thread.start_new_thread(bat) TypeError: start_new_thread expected at least 2 arguments, got 1 >>> thread.start_new_thread(bat, ()) 2256hello >>> -Dan From lists at cheimes.de Fri Jan 11 15:55:24 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 11 Jan 2008 21:55:24 +0100 Subject: virtualpython / workingenv / virtualenv ... shouldn't this be part of python In-Reply-To: References: <4787981c$0$90268$14726298@news.sunsite.dk> Message-ID: Goldfish wrote: > What about security holes, like a malicious version of socket getting > downloaded into a user's directory, and overriding the default, safe > version? Don't forget that in your PEP. A malicious piece of software has already hundreds of way to overwrite modules. It could add a python executable to ~/bin and add ~/bin to PATH. it could modify .bashrc and add PYTHONPATH. Or it could drop some site.py and sitecustomize.py files in various directories. If you allow malicious or potential harmful software to write in your home directory you are lost. The new feature doesn't add new attack vectors. Christian From hrochonwo at googlemail.com Tue Jan 22 13:38:29 2008 From: hrochonwo at googlemail.com (hrochonwo) Date: Tue, 22 Jan 2008 10:38:29 -0800 (PST) Subject: printing escape character Message-ID: Hi, I want to print string without "decoding" escaped characters to newline etc. like print "a\nb" -> a\nb is there a simple way to do it in python or should i somehow use string.replace(..) function ? thanks for any reply hrocho From jyoung79 at kc.rr.com Wed Jan 2 09:23:07 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Wed, 2 Jan 2008 8:23:07 -0600 Subject: os.tmpfile() Message-ID: <12129859.93841199283787583.JavaMail.root@hrndva-web22-z01> > It's a file. You read strings from it and write strings to it. It > isn't a string itself. Given that what you're trying to do doesn't make > any sense, it's hard to know where to begin to identify what's confusing > you. > -- > Erik Max Francis Erik, I am going to be displaying sections of text in the Terminal Window on OS X. I wanted to format the text in a specific way and thought it might be quicker to output all the text to a temporary file that I could quickly read sections from instead of storing in memory. Not sure if this is the most efficient way to do this or not but thought at least it'd be a good way to learn something new in Python. I was assuming tmpfile() would automatically create some sort of temporary file that would automatically delete itself when the code was finished. -- > Try this: > >>> import os > >>> c = os.tmpfile() > >>> c.write('dude') > >>> c.seek(0) > >>> c.read() > 'dude' redawgts, thank you very much for the example! I appreciate you showing me how this works! -- > Please don't use os.tmpfile(). It's not safe and exists only for legacy > reasons. The tempfile module contains methods to create safe temporary > files and directories. > Christian Thanks Christian for this info! I'll look into using the tempfile module instead. Thank you all for sharing your knowledge of Python... this is extremely helpful to me! Jay From guptaabhishek1983 at gmail.com Fri Jan 4 10:35:39 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Fri, 4 Jan 2008 07:35:39 -0800 (PST) Subject: problem in importing .pyd Message-ID: hello group , I have build a python c extension. Using python 2.5 , VS.Net 2005 on Win server 2003. But when i am trying to imort this .pyd file into python interperter or my project source code . Code compilation as well as interpreter fails. Resulting in c/c++ runtime error "R6034". The description says " An application attempted to load a c runtime library without using manifest" What should i do to resolve this problem. Looking forward to your suggestions. Thank You Abhishek From faber at linuxnj.com Fri Jan 11 18:11:41 2008 From: faber at linuxnj.com (Faber J. Fedor) Date: Fri, 11 Jan 2008 18:11:41 -0500 Subject: Newbie Q: modifying SQL statements In-Reply-To: <20080110225352.2c112555@bhuda.mired.org> References: <20080111013206.GA18259@neptune.faber.nom> <20080110225352.2c112555@bhuda.mired.org> Message-ID: <20080111231141.GA24213@neptune.faber.nom> On 10/01/08 22:53 -0500, Mike Meyer wrote: > Personally, I think it would be more pythonic to not try and use two > different APIs to walk the list of jobs (... One Way To Do it): > > def __call__(self, where=None): > q = "select * from %s" % (self.name,) + ("" if not where else (" where %s" % where)) Does this '("" if not where...' syntax actually work? I couldn't get it to compile and I couldn't find any examples of such syntax (but you can't expect googling for 'if not' to be too successful). I ended up changing that line to: q = "select * from %s" % (self.name,) if where: q += "where %s" %where > for r in self.dbc.iterresults() # I assume it has something like this I don't think it does, if I read http://dustman.net/andy/python/MySQLdb_obsolete/doc/MySQLdb-3.html correctly. -- Regards, Faber Fedor -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From kyosohma at gmail.com Thu Jan 24 11:16:57 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 24 Jan 2008 08:16:57 -0800 (PST) Subject: Connecting to Sql Server from Python References: <56f14ea0-defb-445b-b957-7f379a000add@x69g2000hsx.googlegroups.com> Message-ID: <00bb6a7c-7e92-4ddf-af79-4ed6827f2a6b@s13g2000prd.googlegroups.com> On Jan 24, 9:44 am, bg... at yahoo.com wrote: > Hi, > > I have an sql server from which I'd like to read and write to. The > connection string is as follows - > > "Data Source=localhost\SQLExpress;Initial Catalog=Test;Integrated > Security=True;Pooling=False" > > Other properties as they appear in Visual Studio 2005 include - > > Data Provider: .NET Framework Data Provider for SQL Server > State: Open > Type: Microsoft SQL Server > > So my question is, how might I connect to my Test Catalog and update > data within its tables via perl, > > Thanks, > > Barry. If you want to do this in Perl, then why are you asking on a Python list? In Python, there are many ways to accomplish this task. Take a look at SQLAlchemy, SQLObject, pymssql or the adodb package. http://pymssql.sourceforge.net/ www.sqlalchemy.org http://www.sqlobject.org/ http://phplens.com/lens/adodb/adodb-py-docs.htm Mike From bernhard.merkle at googlemail.com Thu Jan 3 08:42:54 2008 From: bernhard.merkle at googlemail.com (Bernhard Merkle) Date: Thu, 3 Jan 2008 05:42:54 -0800 (PST) Subject: reassign to builtin possible !? References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> Message-ID: On Jan 3, 2:07 pm, "Diez B. Roggisch" wrote: > This hal always been possible. But it's not reassigning, it's shadowing - > which is a totally different beast. Shadowing builtins is bad style, but > lokal to your context. Which can get nasty of course, if you do the above > on e.g. module level. > > But you can't alter the values for True/False globally with this. Are you sure ? what about the following example ? Is this also shadowing ? Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import __builtin__ >>> __builtin__.True = False >>> __builtin__.True False >>> True False Berni From john.deas at gmail.com Fri Jan 25 17:45:01 2008 From: john.deas at gmail.com (John Deas) Date: Fri, 25 Jan 2008 14:45:01 -0800 (PST) Subject: basic output question Message-ID: <45577bb9-d0f2-42bf-adea-2ccf34d053ba@l32g2000hse.googlegroups.com> Hi, I am very new to Python (1 evening...) I need to process a series of files (toto-1.txt toto-2.txt toto-3.txt toto-4.txt), and as such I created a small program to go through the files in a directory. I want to call the script with arguments, like python script.py toto- 1 1 4 my script is as follow : import sys sys.argv header= sys.argv[1] start =eval(sys.argv[2]) step =eval(sys.argv[3]) nbit =eval(sys.argv[4]) for i in range(nbit): filename=header+str(start+i*step)+'.txt' f=open(filename,'r') f.read() f.close() My problem is that f.read() outputs nothing, and should I print filename, I can check that they are well formed, and the files sits in the same directory as my script. Anyone could help me on this ? From arian at sanusi.de Sun Jan 27 06:30:30 2008 From: arian at sanusi.de (Arian Sanusi) Date: Sun, 27 Jan 2008 12:30:30 +0100 Subject: python regex: misbehaviour with "\r" (0x0D) as Newline character in Unicode Mode Message-ID: <479C6B56.5030402@sanusi.de> Hi, concerning to unicode, "\n", "\r "and "\r\n" (0x000A, 0x000D and 0x000D+0x000A) should be threatened as newline character at least this is how i understand it: (http://en.wikipedia.org/wiki/Newline#Unicode) obviously, the re module does not care, and on unix, only threatens \n as newline char: >>> a=re.compile(u"^a",re.U|re.M) >>> a.search(u"bc\ra") >>> a.search(u"bc\na") <_sre.SRE_Match object at 0xb5908fa8> same thing for $: >>> b = re.compile(u"c$",re.U|re.M) >>> b.search(u"bc\r\n") >>> b.search(u"abc") <_sre.SRE_Match object at 0xb5908f70> >>> b.search(u"bc\nde") <_sre.SRE_Match object at 0xb5908fa8> is this a known bug in the re module? i couldn't find any issues in the bug tracker. Or is this just a user fault and you guys can help me? arian p.s.: appears in both python2.4 and 2.5 From gandalf at shopzeus.com Tue Jan 8 06:21:12 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 08 Jan 2008 12:21:12 +0100 Subject: Want a strange XML RPC server Message-ID: <47835CA8.1070009@shopzeus.com> Hi, I would like to have a strage XML RPC server. It should use one main thread for all connections. I have some code like this (using a custom RPC server class): server_address = (LISTEN_HOST, LISTEN_PORT) # (address, port) server = mess.SecureXMLRPCServer.SecureXMLRPCServer( server_address, RequestHandler, KEYFILE,CERTFILE, allow_none=True, logger = servicelog.getLogger('SecureXMLRPCServer',filename=LOGFILENAME), logRequests=False, stop_requested = stop_requested ) rpcserver = RPCServer() # Object containing public RPC methods. server.register_instance(rpcserver) It works perfectly. Now here is the tricky part. I would like to send back events. It is implemented by an RPC callback: #1. client calls server.get_event() #2. server waits until the event happens (or until a given timeout) #3. server returns the event (if any) The clients are running on multiple threads, and the idea is that any client can send an event by calling server.send_event(event). That event will be returned to another client by the server. Since the clients are blocking (waiting for the RPC call to return), events will go from one client to another immediatelly (through the rpc server). This goes through different kinds of proxies, and can be used from different programming languages (Python and PHP clients, in my case...) The problem is that in #2, waiting for the event to happen inside the RPC server's handler method will block all other connections to the RPC server. Preferred solution: The get_event() method should run in a different thread inside the server, and return the event to its xmlrpc client from that thread. However, all other methods should use one main thread. I would like to implement this as a decorator like: class RPCServer(object): """Object containing public RPC methods.""" def method1(self,arg1): ..... def method2(self,arg1): ..... def method3(self,arg1): ..... @nonblocking def get_event1(self): try: # Wait for 10 seconds until an event is available. return self.asinharvester.queued_events1.get(True,10) except Queue.Empty: return None # Indicates that there was no queued event. @nonblocking def get_event2(self): try: # Wait for 10 seconds until an event is available. return self.asinharvester.queued_events2.get(True,10) except Queue.Empty: return None # Indicates that there was no queued event. Is this possible? I have no idea how to write this "nonblocking" decorator. Thanks, Laszlo From grante at visi.com Thu Jan 24 11:56:22 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 24 Jan 2008 16:56:22 -0000 Subject: Beginner Pyserial Question References: <93223c7c-c891-424c-bc4f-00d61592663a@l32g2000hse.googlegroups.com> Message-ID: <13phgpma9fb3cb8@corp.supernews.com> On 2008-01-24, JAMoore84 at gmail.com wrote: > Hi Guys, > > I have a project where I'd like to save GPS data that is streamed to a > Sony Vaio over bluetooth. I can monitor the data stream over Hyper > Terminal, but I'd like to use python to capture it as well. I've > installed Python 2.5, pyserial 2.2 and the appropriate pywin program > (pywin32-210.win32-py2.5.exe). > > My problem comes when I try to open a serial port. After importing > "serial", I issue the following statement: > >>>> GPS = serial.Serial(0) > > Traceback (most recent call last): > File "", line 1, in > GPS = serial.Serial(0) > File "C:\Python25\lib\site-packages\serial\serialutil.py", line 156, > in __init__ > self.open() > File "C:\Python25\lib\site-packages\serial\serialwin32.py", line 55, > in open > raise SerialException("could not open port: %s" % msg) > SerialException: could not open port: (2, 'CreateFile', 'The system > cannot find the file specified.') > > I'm not sure where the source of the problem is. I was > wondering if someone could recognize what might be be. It's Windows... it's not expected to work. ;) My guess is that for whatever reason the 'first' serial port (which is what you're asking for by specifying a 0 when instantiating the Serial class) doesn't actually exist. Serial device names under Windows are broken. Just because you have only one serial port, it doesn't mean that serial port is the first serial port. Try using the actual name of the com port (e.g. 'COM3' or 'COM5') instead of 0. Oh, if you end up having to use a com port higher than COM9, that's broken in Windows as well, and you've got to sprinkle a bunch of backslashes into the device name (I don't remember the exact syntax). -- Grant Edwards grante Yow! ... this must be what at it's like to be a COLLEGE visi.com GRADUATE!! From tjreedy at udel.edu Tue Jan 29 04:26:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jan 2008 04:26:22 -0500 Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: "Roy Smith" wrote in message news:roy-3C105C.23015128012008 at 70-1-84-166.area1.spcsdns.net... | But, surely Python has plenty of "implementation defined" aspects. | Especially in the libraries. I personally do not consider the libraries as part of the language (as opposed to the distribution) and was not referring to them. The semantics of the syntax is pretty tightly defined. The main exception is floating point, which is a nuisance. Which is why one implementation aspect thereof is being standardized in the next version. | Especially those parts of the libraries which | are thin layers on top of operating system services (os and socket come to | mind as two highly variable areas). I am sure that sockets are not part of the C89 standard. Hence the high variability. (I don't know about the newer C standard). I would expect that socket.py makes the variability no worse and presume that it masks at least a bit of it. Ditto for some os services. tjr From mwm-keyword-python.b4bdba at mired.org Fri Jan 11 17:24:11 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 17:24:11 -0500 Subject: Import and execfile() In-Reply-To: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> References: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> Message-ID: <20080111172411.7323f1bc@bhuda.mired.org> On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis wrote: > I maintain a few configuration files in Python syntax (mainly nested > dicts of ints and strings) and use execfile() to read them back to > Python. This has been working great; it combines the convenience of > pickle with the readability of Python. So far each configuration is > contained in a single standalone file; different configurations are > completely separate files. You know, I've been there before. It's kinda neat, but not something you really want to put in the hands of most users. You can make the syntax cleaner by using classes to hold the values instead of nested dicts, etc. That way you don't have to quote the names of the values: class Foo: bar = 1 baz = 2 The really slick part was that if the config classes line up with the implementation classes, you can create an instance of the config class for the implementation object, and it can then change those values to change it's behavior without changing the defaults other instances see. > Now I'd like to factor out the commonalities of the different > configurations in a master config and specify only the necessary > modifications and additions in each concrete config file. I tried the > simplest thing that could possibly work: With classes you factor out the commonality by factoring it into a base class that the others inherit from. > ====================== > # some_config.py > > # master_config.py is in the same directory as some_config.py > from master_config import * > > # override non-default options > foo['bar']['baz] = 1 > ... > > ====================== > # trying to set the configuration: > CFG = {} > execfile('path/to/some_config.py', CFG) > > Traceback (most recent call last): > ... > ImportError: No module named master_config > > > I understand why this fails but I'm not sure how to tell execfile() to > set the path accordingly. Any ideas ? Manipulate sys.path yourself? http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From http Sun Jan 20 22:24:32 2008 From: http (Paul Rubin) Date: 20 Jan 2008 19:24:32 -0800 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> Message-ID: <7xir1nsvwv.fsf@ruckus.brouhaha.com> Terry Jones writes: > Here's a solution that doesn't use any copying of lists in for recursion. > It also eliminates a bunch of trivially equivalent solutions. The countdown > function is 37 lines of non-comment code. Sample (RPN) output below. Nice, I realized after I posted my 2nd solution that it was missing some cases and it's good to see confirmation that 239 is reachable. I'll see if I can fix my version. I think the list copying is ok given that the recursion depth always must be fairly small if the generator is to complete in any reasonable amount of time. From fw3 at hotmail.co.jp Thu Jan 3 20:51:46 2008 From: fw3 at hotmail.co.jp (wang frank) Date: Fri, 4 Jan 2008 01:51:46 +0000 Subject: calling system command in window is very slow in python 2.5.1 In-Reply-To: References: <3da337d8-2de0-4fdb-8c38-2f6fcd8348ac@i72g2000hsd.googlegroups.com> Message-ID: Hi, I am running a python script that will change the attribute of a directory and its subdiretory by command: os.system("chmod -R 7777 .") or os.system("attrib -R * /S") Both commands chmod and attrib run quite fast in dos command shell. However, inside python, they are very slow and I have to kill them by Control-C. I do not know why? Can anyone help me to figure it out? Thanks Frank _________________________________________________________________ Hotmail?????????????????????????????????? http://go.windowslive.jp/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Fri Jan 11 12:24:35 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 11 Jan 2008 09:24:35 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: On 9 Jan, 20:11, "dongie.ag... at gmail.com" wrote: > Is there a better way to do color tracking, or is Python just too slow > as an interpreted language to do any effective color tracking? You should code numerically intensive tasks using NumPy arrays. If things are getting slow, chances are you are using Python for loops instead of vectorized NumPy expressions. This is the same trick you would use in e.g. Matlab for boosting performance. If things are running slow despite of having properly vectorized your code, chances are that porting to C will not make a big difference. If you need to resort to C or Fortran, it is easy to interface Python with these languages (e.g. ctypes, Pyrex, Swig, f2py, or weave). Put the offending bottleneck in a lower level language (detect it using the profiler module) and leave everything else in Python. From ggpolo at gmail.com Mon Jan 7 10:15:08 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 13:15:08 -0200 Subject: introspection question In-Reply-To: References: Message-ID: 2008/1/7, Alex K : > Nice thank you. But anyway to make it look pretty? > pprint.pprint(inspect.getmembers(someobject)) > On 07/01/2008, Peter Otten <__peter__ at web.de> wrote: > > Alex K wrote: > > > > > What would be the simplest way of enumerating all methods and members > > > (including inherited) of a given object? Thank you. > > > > inspect.getmembers() > > > > Peter > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From http Fri Jan 11 15:57:39 2008 From: http (Paul Rubin) Date: 11 Jan 2008 12:57:39 -0800 Subject: removeall() in list References: Message-ID: <7xlk6ww058.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > Any ideas for a thread-safe list.removeall( X ): removing all > occurrences of X within list L, when L might be modified concurrently? That way lies madness. Do something sensible instead. Put a lock around the list, or put all mutators for the list into a single thread, or whatever. Don't do what you're describing. From hat at se-162.se.wtb.tue.nl Fri Jan 11 02:47:46 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 11 Jan 2008 08:47:46 +0100 Subject: Help needed References: <0da27dc1-785a-4796-a5a3-6ba1a0290cab@e25g2000prg.googlegroups.com> <66390246-aada-40fe-b8d3-4816771b950f@i3g2000hsf.googlegroups.com> Message-ID: On 2008-01-11, tijo wrote: > Hi mate > i created the socket and the connection with tcp and udp i dont know > how to check the bytes send and time > could you help me with this Have a look at the time or timeit modules. Albert From duncan.booth at invalid.invalid Fri Jan 11 03:27:48 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Jan 2008 08:27:48 GMT Subject: HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? References: <7243c2ac-fa22-4b5b-bd8c-34235123ab69@t1g2000pra.googlegroups.com> Message-ID: abhishek wrote: > Hi group any idea on HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? > > Yes, it indicates you haven't read http://catb.org/~esr/faqs/smart-questions.html From lloyd at paisite.com Sat Jan 12 14:22:58 2008 From: lloyd at paisite.com (lloyd at paisite.com) Date: Sat, 12 Jan 2008 14:22:58 -0500 (EST) Subject: =?UTF-8?Q?RE:=20where=20do=20my=20python=20files=20go=20in=20linux=3F?= Message-ID: <42229.192.168.1.35.1200165778.webmail@192.168.1.35> Hello, > Question 1. Where do I put the bulk of python scripts in a normal > linux environment? In my system I put them in /usr/local/lib/python2.4/site-packages/my_scripts. And, I have *.pth file in /usr/local/lib/python2.4/site-packages that points to my_scripts. The *.pth file simply reads "my_scripts" -- without the quotes, of course. This one area where Python docs are pretty vague. It took me awhile to piece this together. But it works. Best wishes, Lloyd -------------- next part -------------- An HTML attachment was scrubbed... URL: From horacius.rex at gmail.com Tue Jan 8 03:19:25 2008 From: horacius.rex at gmail.com (Horacius ReX) Date: Tue, 8 Jan 2008 00:19:25 -0800 (PST) Subject: Look for a string on a file and get its line number Message-ID: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> Hi, I have to search for a string on a big file. Once this string is found, I would need to get the number of the line in which the string is located on the file. Do you know how if this is possible to do in python ? Thanks From rajarshi.guha at gmail.com Fri Jan 11 17:02:21 2008 From: rajarshi.guha at gmail.com (Rajarshi) Date: Fri, 11 Jan 2008 14:02:21 -0800 (PST) Subject: extracting Javadocs using Python Message-ID: <30a4948a-7293-43d6-9381-824654e44416@s19g2000prg.googlegroups.com> Hi, I work on a Java project and I was thinking out creating a hook in the subversion repo for the project that would check whether a class and it's associated methods were documented with Javadocs. Since I have written Subversion hooks for other purposes in Python, I'd like to try and do this task in Python as well. However, it seems that I'd need a full fledged Java/Javadoc parser written in Python. Does anybody know if something like this is available? Or would I need to implement a parser from scratch? Thanks, From deets at nospam.web.de Tue Jan 29 07:20:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jan 2008 13:20:26 +0100 Subject: Executing other python code References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: <608k0aF1ovmf7U1@mid.uni-berlin.de> Tim Rau wrote: > I'm working on a game, and I'd like players to be able to define thier > ships with scripts. Naturally, I don't want to give them the entire > program as thier romping ground. I would like to invoke a seperate > interpreter for these files, and give it a limited subset of the > functions in my game. What is the best way to achieve this effect? You might consider spawning a process and using Pyro to communicate. I've done that before and it worked pretty well. Diez From tarun.kap at gmail.com Wed Jan 16 14:33:24 2008 From: tarun.kap at gmail.com (Tarun Kapoor) Date: Wed, 16 Jan 2008 11:33:24 -0800 (PST) Subject: paramiko References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> <8ceaad4c-c725-4093-a204-ab09162d4629@c23g2000hsa.googlegroups.com> Message-ID: <685fabb3-c9e8-47ac-84f2-405b831bccad@v4g2000hsf.googlegroups.com> On Jan 16, 12:22 pm, "Guilherme Polo" wrote: > 2008/1/16, Tarun Kapoor : > > > > > On Jan 16, 11:38 am, "Guilherme Polo" wrote: > > > 2008/1/16, Tarun Kapoor : > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across > > > > the connection > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > sock.connect((hostname, port)) > > > > > t = paramiko.Transport(sock) > > > > t.start_client() > > > > key = t.get_remote_server_key() > > > > > event = threading.Event() > > > > t.auth_password(username=username, password=password, event=event) > > > > event.wait() > > > > > if not t.is_authenticated(): > > > > print "not authenticated" > > > > > output: > > > > not authenticated > > > > This is a different problem I guess, now you are usin get_remote_server_key. > > > And why are you creating event after calling start_client without > > > specifying it ? > > > > > On Jan 16, 11:11 am, "Guilherme Polo" wrote: > > > > > 2008/1/16, Tarun Kapoor : > > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > > > > > > the remote server using an SFTP client I have just to make sure that > > > > > > username and password are working.. This is the code. > > > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > > > > > > connection > > > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > > > > sock.connect((hostname, port)) > > > > > > > t = paramiko.Transport(sock) > > > > > > > event = threading.Event() > > > > > > > t.start_client(event) > > > > > > > event.wait(15) > > > > > > > if not t.is_active(): > > > > > > > print 'SSH negotiation failed.' > > > > > > > sys.exit(1) > > > > > > > else: > > > > > > > print "SSH negotiation sucessful" > > > > > > > event.clear() > > > > > > > t.auth_password(username=username, password=password,event=event) > > > > > > > if not t.is_authenticated(): > > > > > > > print "not authenticated" > > > > > > > output: > > > > > > > SSH negotiation successful > > > > > > > not authenticated > > > > > > > Tarun > > > > > > > Waterstone Capital Management > > > > > > > 2 Carlson Parkway, Suite 260 > > > > > > > Plymouth, MN 55447 > > > > > > > Direct: 952-697-4123 > > > > > > > Cell: 612-205-2587 > > > > > > Disclaimer This e-mail and any attachments is confidential and intended > > > > > > solely for the use of the individual(s) to whom it is addressed. Any views > > > > > > or opinions presented are solely those of the author and do not necessarily > > > > > > represent those of Waterstone Capital Management, L.P and affiliates. If you > > > > > > are not the intended recipient, be advised that you have received this > > > > > > e-mail in error and that any use, dissemination, printing, forwarding or > > > > > > copying of this email is strictly prohibited. Please contact the sender if > > > > > > you have received this e-mail in error. You should also be aware that > > > > > > e-mails are susceptible to interference and you should not assume that the > > > > > > contents of this e-mail originated from the sender above or that they have > > > > > > been accurately reproduced in their original form. Waterstone Capital > > > > > > Management, L.P. and affiliates accepts no responsibility for information, > > > > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > > > > > > please verify the authenticity with the sender. > > > > > > -- > > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > You are missing an event.wait() after t.auth_password. > > > > > Also, why are you passing this magic value "15" to event.wait() ? That > > > > > parameter is passed to class _Verbose to indicate if debug messages > > > > > should be displayed or not, so typical values would be 0/1 or > > > > > False/True. > > > > > > -- > > > > > -- Guilherme H. Polo Goncalves > > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > -- > > > -- Guilherme H. Polo Goncalves > > > ok here is the problem... I don't know what is the correct way... The > > only demos i have from the paramiko library use a hostkeyfile. since i > > don't have that i thought i would use the get_remote_key to get the > > key and then connect it using the code in the demo.. But clearly > > nothing is working...I should not HAVE to use the key since i should > > be able to authenticate using the password... > > > Can you please suggest the right way to go ? > > You don't need to use key to authenticate using username and password, > indeed. And you don't. Your first email was almost correct, you just > needed to add event.wait() after t.auth_password. It worked here after > doing that change. You can check out my version: > > import sys > import socket > import paramiko > import threading > > if len(sys.argv) != 4: > print "%s hostname user password" % sys.argv[0] > sys.exit(1) > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((sys.argv[1], 22)) > > t = paramiko.Transport(sock) > event = threading.Event() > t.start_client(event) > > event.wait() > > if not t.is_active(): > print 'SSH negotiation failed.' > sys.exit(1) > else: > print "SSH negotiation sucessful" > > event.clear() > t.auth_password(username=sys.argv[2], password=sys.argv[3], event=event) > event.wait() > if not t.is_authenticated(): > print "Authentication failed." > else: > print "Authenticated!" > > t.close() > > > > > Thanks for your time ! > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves ok i tried the exact same code and here is the output SSH negotiation sucessful Authentication failed. I am positive that the username and paddword are correct. ! From f.guerrieri at gmail.com Sun Jan 6 16:48:04 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Sun, 6 Jan 2008 22:48:04 +0100 Subject: Basic inheritance question In-Reply-To: References: Message-ID: <79b79e730801061348m8f8594bmbf34c716a3fa6564@mail.gmail.com> On Jan 5, 2008 11:31 AM, wrote: > import tok > > class code: > def __init__( self, start, stop ): > startLoc = start > stopLoc = stop > > class token(code): > pass > Apart from the missing self, remember that the __init__(...) of the base classes is not automatically called, unless you do it explicitly or you do not provide one in the derived class. So for instance you could have something like class token(code): def __init__(self, ...): # do the token specific initialization here .... # Now init the base class code.__init__(self, ....) Or, better, you could use super if you were using new-style classes (which you are not...), like in the following: class token(code): def __init__(self, ...): # do your initialization here super(token, self).__init__(....) which is much better suited to allow multiple inheritance (there has been a discussion in these days about the MRO, look for a paper by Michele Simionato). Quoting Alex Martelli in Python in a nutshell (page 97): "If you get into the habit of always coding superclass calls with super, your classes will fit smoothly even in complicated inheritance structures. There are no ill effects whatsoever if the inheritance structure instead turns out to be simple, as long, of course, as you're only using the new-style object model, as I recommend". bye, Francesco From dg.google.groups at thesamovar.net Wed Jan 23 15:54:20 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Wed, 23 Jan 2008 12:54:20 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> Message-ID: Well I tried the NumPy array thing that I was talking about, to parallelise the problem, and there were some difficulties with it. Firstly, the pruning makes a really big difference to the speed, and you don't get that if you're trying to parallelise the problem because what is an equivalent calculation for one set of numbers is obviously not for another set. I think this problem disappears when you consider very large sets of numbers though (where the cost of doing equivalent computations vanishes in comparison to the alternative cost of starting up the whole recursive computation from scratch many times). The second problem is that you can't weed out division by zero and intermediate fractions. I haven't looked at the internals of how NumPy deals with these though, so this might be fixable or it might not. For my part, I'd consider the following equivalences to be right for defining equivalent expressions (where here a, b and c are any subexpression, and 1 and 0 means any subexpression that evaluates to 1 and 0). Commutativity: a*b <-> b*a a+b <-> b+a Associativity: (a+b)+c <-> a+(b+c) (a+b)-c <-> a+(b-c) (a-b)+c <-> a-(b-c) (a-b)-c <-> a-(b+c) (a*b)*c <-> a*(b*c) (a*b)/c <-> a*(b/c) (a/b)*c <-> a/(b/c) (a/b)/c <-> a/(b*c) Units (1 is multiplicative unit, 0 is additive unit): a*1 <-> a a/1 <-> a a+0 <-> a a-0 <-> a Substitution (swapping equal starting numbers is equivalent): expr(a,b,c,...,z) <-> expr(s(a,b,c,...,z)) where a,b,c,...,z are the original numbers given and s is a permutation of (a,b,c...,z) so that (a,b,c,...z) evaluates to the same thing as s(a,b,c,...,z) or equivalently, expr1 <-> expr2 if str(expr1)==str(expr2) Then, any two expressions which can be transformed into one another by the equivalences above are equivalent. Commutativity and units can be easily implemented as you go and most of the programs suggested so far do this, by for example only allowing a*b or a+b if a>=b, and not allowing a*1 or 1*a, etc. Substitution can be implemented by just taking set(map(str,expressions)) at the end. The associativity ones are a little more tricky to implement, but Arnaud's idea of the fully ordered binary tree seems to do it. Another way of saying it is that any subexpression consisting only of + and - operations should be reduced to a+b+c+...-z-y-x-.... where a>b>c>... and z>y>x>... (and similarly for an expression involving only * and /). Terry, I'd also be interested in a copy of your stack simulation code, btw. From phillip.sitbon at gmail.com Fri Jan 11 19:42:33 2008 From: phillip.sitbon at gmail.com (Phillip Sitbon) Date: Fri, 11 Jan 2008 16:42:33 -0800 (PST) Subject: Python in IIS + WSGI References: <86d01390-fb1c-4806-a10b-92446c008b10@k2g2000hse.googlegroups.com> Message-ID: <728a3b8a-074f-4435-89e3-4cdb095f193a@q39g2000hsf.googlegroups.com> Pardon my typo! http://pyisapie.sourceforge.net On Jan 11, 4:37 pm, Phillip Sitbon wrote: > Recently (finally) updated the PyISAPIe project. Version 1.0.4 > includes WSGI support (tested with current Django SVN and Trac 0.10) > and a Django-native handler, as well as other examples of using it as > a standalone web app. > > Also added some installation/usage docs on the project page. > > Comments/feedback welcome! > > http://pyisapie.sourceforege.net > > Cheers, > > Phillip From mnordhoff at mattnordhoff.com Tue Jan 15 22:47:02 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 15 Jan 2008 22:47:02 -0500 Subject: Is str/unicode.encode supposed to work? with replace/ignore In-Reply-To: References: Message-ID: <478D7E36.9020009@mattnordhoff.com> BerlinBrown wrote: > With this code, ignore/replace still generate an error > > # Encode to simple ascii format. > field.full_content = field.full_content.encode('ascii', 'replace') > > Error: > > [0/1] 'ascii' codec can't decode byte 0xe2 in position 14317: ordinal > not in ran > ge(128) > > The document in question; is a wikipedia document. I believe they use > latin-1 unicode or something similar. I thought replace and ignore > were supposed to replace and ignore? Is field.full_content a str or a unicode? You probably haven't decoded it from a byte string yet. >>> field.full_content = field.full_content.decode('utf8', 'replace') >>> field.full_content = field.full_content.encode('ascii', 'replace') Why do you want to use ASCII? UTF-8 is great. :-) -- From BjornSteinarFjeldPettersen at gmail.com Sun Jan 13 09:31:56 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 13 Jan 2008 06:31:56 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> Message-ID: On Jan 13, 1:51 pm, Richard Szopa wrote: > On Jan 13, 8:59 am, Marc 'BlackJack' Rintsch wrote: > > > On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: > > > However, I am very surprised to learn that > > > > super_object.__getattr__(name)(*args, **kwargs) > > > > getattr(super_object, name)(*args, **kwargs) > > > > are not equivalent. This is quite odd, at least when with len() > > > and .__len__, str() and .__str__. Do you maybe know what's the > > > rationale behind not following that convention by getattr? > > > I think you are confusing `__getattr__` and `__getattribute__` here! > > `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's > > different. > > Well, in my code calling super_object.__getattr__(name)(*args, > **kwargs) and getattr(super_object, name)(*args, **kwargs) gives > *different* effects (namely, the latter works, while the former > doesn't). That kinda suggests that they don't map to each other :-). > And that makes me feel confused. > > Cheers, > > -- Richard They do, except for when it comes to what super(..) returns. It isn't really an object in the sense that they're presented in the tutorial, but rather a sort of proxy to the methods in the ancestor classes of the concrete object (self), relative to the current method's class. I can't imagine that sentence would ease any confusion however, suffice it to say that you have to call getattr(super(..), 'name') instead of super(..).__getattr__('name') and you have to call super(..).__len__() instead of len(super(..)) -- I can't imagine that lessens any confusion either :-/ super(..) is designed to handle situations like this correctly class Root(object): n = 1 class Left(Root): def foo(self): print 'n =', self.n print 'super n = ', super(Left, self).n class Right(Root): n = 2 class Leaf(Left,Right): n = 3 x = Leaf() x.foo() the correct output is n = 3 super n = 2 -- bjorn From nstjelja at gmail.com Wed Jan 9 00:49:56 2008 From: nstjelja at gmail.com (Nikola Stjelja) Date: Wed, 9 Jan 2008 06:49:56 +0100 Subject: module pickle In-Reply-To: References: Message-ID: <2d24984a0801082149k4d0f5cb9y53e6094c756727ab@mail.gmail.com> On Jan 9, 2008 5:29 AM, Beema shafreen wrote: > Hi I am beginner in python. and I am not able to understand the Pickle > concept in python can. some body explain me about the use of this module, > few examples. which will help me a lot. > > regards > shafreen > > -- > http://mail.python.org/mailman/listinfo/python-list > You can find a good documentation of the pickle module here: http://docs.python.org/dev/library/pickle.html with exmaples to show you how you can use it. Pickle is used to serialize objects. What does that mean? In short you save your objects( remeber everything is an object in python, strings, lists, touples, dictionaries ...) to an external file (eg. object.pcl) for later usage( eg. you save your users personal data when exiting your software, and then you load it later when your software is restarted by the user. -- Please visit this site and play my RPG! http://www.1km1kt.net/rpg/Marinci.php -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Jan 21 10:10:17 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Jan 2008 16:10:17 +0100 Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> <13p998o7mskm7e0@corp.supernews.com> Message-ID: Steven D'Aprano wrote: >> The following relies on undocumented (I hope) behaviour: >>>>> preferences = [10, 30, 20] >>>>> hosts = [ "mx1.domain.com", "anotherhost.domain.com", >>... "mx2.domain.com"] >>>>> hosts.sort(key=lambda x, p=iter(preferences).next: p()) >>>>> preferences.sort() >>>>> hosts >> ['mx1.domain.com', 'mx2.domain.com', 'anotherhost.domain.com'] > What bit are you suggesting is undocumented? The lambda spits out the items in preferences in the same order as they occur in that list. If hosts.sort(key=...) in its C-implemented decoration phase would iterate over the items in hosts in, say, reverse order hosts would not be sorted correctly. Here's an illustration in Python: >>> def dsu(items, key, reorder=lambda x: x): ... for i in reorder(range(len(items))): ... items[i] = key(items[i]), items[i] ... items.sort() ... items[:] = [v for k, v in items] ... return items ... >>> dsu([1,2,3], lambda x, n=iter("acb").next: n()) [1, 3, 2] >>> dsu([1,2,3], lambda x, n=iter("acb").next: n(), reversed) [3, 1, 2] Peter From salgerman at gmail.com Tue Jan 8 13:11:08 2008 From: salgerman at gmail.com (gsal) Date: Tue, 8 Jan 2008 10:11:08 -0800 (PST) Subject: copy a numpy array References: Message-ID: <0cc33c4e-bb6b-4f80-8b4d-d702dc7789ec@v29g2000hsf.googlegroups.com> I am new to python and everything related to it, and it so happens that I just went through the numpy tutorial last night, it is in http://www.scipy.org/Tentative_NumPy_Tutorial and the answer to your question is in section 3.7 Basically, if you want to make a (deep) copy of it: destarray = srcarray.copy() gsal From alexandru.dumitrescu at gmail.com Mon Jan 14 09:52:34 2008 From: alexandru.dumitrescu at gmail.com (Alexandru Dumitrescu) Date: Mon, 14 Jan 2008 16:52:34 +0200 Subject: csv add lines Message-ID: Hi, I'm new to this list and to python. I am wondering, am I able to make my program read the *.txt files from a directory and to add, at the top of the file, three new lines which are stored in a *.csv file? For each *.txt file I have a line in the *.csv file which has in the first column the name of the *.txt file and in the next three columns the lines that I want to add in the corresponding *.txt file. If it is possible I'd appreciate some help. Thank you! Alex -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Mon Jan 21 05:49:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Jan 2008 11:49:55 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <5vi1r8F1mjs0rU1@mid.uni-berlin.de> <5360e13d-215d-4d3e-9930-daa6cddd996a@f10g2000hsf.googlegroups.com> <5vj79dF1m2nmlU1@mid.uni-berlin.de> <677d61a1-16be-40ae-8332-a5ff45ff8905@j78g2000hsd.googlegroups.com> Message-ID: <5vjbmjF1mp0hgU1@mid.uni-berlin.de> > > Diez, > > I repeat I am a newbie, so please don't be angry against me, if I say > something stupid or if I propose a method not efficient. Where did I sound angry? > An easy way to get the absolute path of site-packages seems very > useful to me, in order to check anything (all extensions available and > not provided by sys.path, etc.) related to the files on the > filesystem, if necessary. As I said - this is a wrong assumption. The whole purpose of the sys.path is to specify locations where modules/packages are installed. Note the plural. And matter of factly (as I told you in the last post already), this happens in e.g. debian based distributions install certain packages under /usr/share, which is by no means a prefix of /usr/python2.5 where the site-packages are. So if you want to find out if something is already installed, you need to consider ALL the contents of sys.path. Besides, I don't understand why you want to do it that way anyway. If you need a certain package, do try: import package except ImportError: do_install_package() This should/could be part of your installer script (most probably setup.py) And have you heard of setuptools? They do actually manage and install pytthon packages with dependencies. Before reinventing another wheel... > For the automatic installation of missing extensions (using admin > rights), I think that it is not difficult to do it on both > platforms... You are underestimating that task. It is, on both platforms. There are many discussions about this, why some people don't like setuptools because it works with python as center of it's perspective whereas linux often has package management for the whole system. I suggest you start acquainting yourself with setuptools and how and what they did to essentially solve what you seem to be wanting. And try and see if that's not a route you can go - just using setuptools. Diez From noahdain at gmail.com Thu Jan 10 12:31:53 2008 From: noahdain at gmail.com (Noah Dain) Date: Thu, 10 Jan 2008 12:31:53 -0500 Subject: run shell commands In-Reply-To: References: Message-ID: On Jan 10, 2008 9:24 AM, Riccardo Maria Bianchi wrote: > > Hello! :) > > I'm trying to run shell commands both with os.system() and > subprocess.Popen() class. > > But I can't run aliases or function defined in my .bashrc file, like in > the login interactive shell. > > Can you help me? > Maybe have I to add some commands to load the .bashrc? > > Thanks a lot! :) > > Ric. > > -- > http://mail.python.org/mailman/listinfo/python-list > you'd need to run an instance of the shell from python and probably as a login shell so that it pulls in .bashrc. so you'd need a command line like: /bin/bash -l -c "shell commands to run go here" if you want to feed more commands to bash, then use -s. It will read commands from standard input, which you would feed it from python, probably by writing to a Popen pipe. A lot of people also use the pexpect python library to "drive" other programs, especially if you need python to act differently depending upon the output of the called programs. Either way, this list's archives do have some good examples as to the uses and limitations of both subprocess and pexpect. -- Noah Dain "The beatings will continue, until morale improves" - the Management From projecteclipsor at gmail.com Sat Jan 12 15:04:42 2008 From: projecteclipsor at gmail.com (Landon) Date: Sat, 12 Jan 2008 14:04:42 -0600 Subject: Great Python books for the beginner In-Reply-To: <1a4d8dae-4722-4a10-a638-ac1b2d85227a@i72g2000hsd.googlegroups.com> References: <1a4d8dae-4722-4a10-a638-ac1b2d85227a@i72g2000hsd.googlegroups.com> Message-ID: One thing I wonder about is the examples these books use to teach the concepts. I found myself really attached to K&R because the end of section projects were utilities that I would find be able to find useful in day to day work such as a version of wc and a program that would take collapse all consecutive whitespace in a document into one space. I could just use the projects from K&R, but I imagine a Python book would have a better selection that highlight Python's abilities. On another note, I would prefer to have a paper book so I don't have to keep switching back and forth between documents on my computer. From ncoghlan at gmail.com Tue Jan 1 00:26:38 2008 From: ncoghlan at gmail.com (NickC) Date: Mon, 31 Dec 2007 21:26:38 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <6aba9463-f0ea-43a2-b8de-9c7026c4d14e@e4g2000hsg.googlegroups.com> Message-ID: <75ea72e9-f69f-4b3a-98fe-ffc364fa7543@l6g2000prm.googlegroups.com> On Jan 1, 3:22 am, Arnaud Delobelle wrote: > On Dec 31, 10:58 am, Odalrick wrote: > > > I'm surprised noone has said anything about the why of default > > mutables. I think it is becasue it isn't easy to do it an other way. > > [...] > > There is an easy enough way: evaluate default values when the function > is called rather than when it is defined. This behaviour comes with > its own caveats as well I imagine, and it's not 'as easy' to implement > as the current one. As Odalrick notes, there is no way to give different calls to a function their own copies of mutable default arguments without re- evaluating the defaults every time the function is called. The horrendous performance implications mean that that simply isn't going to happen. So the status quo, where the defaults are calculated once when the function is defined and the result cached in the function object is unlikely to change. > What's good about the current behaviour is that it is easy to reason > with (once you know what happens), even though you almost have to get > bitten once. But using this to have static variable is extremely ugly > IMHO. The only thing it doesn't give you is a static variable that isn't visible to the caller. Py3k's keyword-only arguments (PEP 3102) will make those cases a little tidier, since it won't be possible to accidentally replace the static variables by providing too many positional arguments. I believe the suggestion of permitting static variables after the ** entry in a function's parameter list was raised during the PEP 3102 discussions, but never gained much traction over a '_cache={}' keyword- only argument approach (and the latter has the distinct advantage of being *much* easier to test, since you can override the cache from the test code to ensure it is being handled correctly). Cheers, Nick. From bill.pursell at gmail.com Tue Jan 29 13:22:24 2008 From: bill.pursell at gmail.com (William Pursell) Date: Tue, 29 Jan 2008 10:22:24 -0800 (PST) Subject: object vs class oriented -- xotcl References: Message-ID: <2dfb6cd3-921a-4692-9627-d35bda40a93e@v29g2000hsf.googlegroups.com> On Jan 24, 9:16 pm, "Guilherme Polo" wrote: > 2008/1/24, William Pursell : > > Can I do it in Python? > > > class A(object): pass > class B(object): pass > > a = A() > a.__class__ = B > > That ? Maybe you meant something else. That is what I was referring to, but it isn't the core functionality that I'm after. (My bad for a poor description.) I'm fairly excited at the idea of being able to do per-object mixins in xotcl. I guess it would look like this in python: BROKEN CODE: a = object() a.__class__.append( foo ) a.__class__.append( bar ) In python, if you want an object to me a member of 2 classes, it seems that you have no choice but to declare a new class that inherits from both. eg: class foobar( foo, bar): pass a = foobar() Is it possible to make an object be a member of 2 classes without defining such a class? I believe "per object mixin" is the correct term for such an animal. The first several google hits on that phrase all reference xotcl, so I'm not sure if that is an xotcl inspired vocabulary that isn't really standard. From nagle at animats.com Thu Jan 24 18:14:32 2008 From: nagle at animats.com (John Nagle) Date: Thu, 24 Jan 2008 15:14:32 -0800 Subject: Testing whether something is of type Exception Message-ID: <47991a8a$0$36353$742ec2ed@news.sonic.net> How can I tell whether an object is of type Exception? At least in Python 2.4, "Exception" is an old-style class, and the "type" of Exception objects is "instance". Clearly "repr" knows; it returns: John Nagle From jatinpatni at gmail.com Wed Jan 9 11:29:03 2008 From: jatinpatni at gmail.com (jatin patni) Date: Wed, 9 Jan 2008 16:29:03 +0000 Subject: Problem in importing modules using py2exe Message-ID: I am trying to generate binaries on Windows platform using py2exe, but it is unable to import this module named "Mechanize". The error says " it could not find this module"...while the module is present along with all the other modules "Python/Lib/site-packages/"... Any help would be appreciated...Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Sun Jan 6 13:44:02 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 06 Jan 2008 19:44:02 +0100 Subject: Unexpected __metaclass__ method behavior In-Reply-To: References: <2273796e-87c6-4100-a5b5-1c6afa32a276@i29g2000prf.googlegroups.com> Message-ID: <4781216f$0$24469$426a74cc@news.free.fr> anne.nospam01 at wangnick.de a ?crit : > Well, you see, I have some database functions that deal with "things" > which are either classes or instances thereof. I though polymorphism > would be a nice way to handle them identically, like: > > def do(thing): thing.Foo() > do(t) > do(Test) > > But never mind, I now understand that Test.__dict__ can contain only > one entry for 'Foo', and that this must be matched. You may want to have a look at FormEncode's "declarative" API, with particular attention to the 'classinstancemethod' stuff. From miki.tebeka at gmail.com Tue Jan 15 02:02:41 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 14 Jan 2008 23:02:41 -0800 (PST) Subject: Is there some Python function that searches "sys.path" for a module? References: <478c5755$0$36354$742ec2ed@news.sonic.net> Message-ID: <6c9fb69f-04fb-460e-b78e-9b342e6f83ed@d21g2000prf.googlegroups.com> Hello John, > ? ?Python's own loader searches "sys.path" for module names, but is there > some function that makes that search functionality accessible to > Python programs? ?I need the absolute pathname of a module, with the > search being done exactly the same way "import" does it. ?The loader for > "egg" files has this functionality, but I'd like to find out if there's > a standard way to do this before looking into that source code. > > ? ?Also, it seems that the environment variable "PYTHONPATH" applies to > "import", but not to the starting module named on the Python command > line. ?Is that correct? ?Thanks. http://docs.python.org/lib/module-imp.html HTH, -- Miki Tebeka http://pythonwise.blogspot.com From henry.baxter at gmail.com Fri Jan 11 21:14:54 2008 From: henry.baxter at gmail.com (Henry Baxter) Date: Fri, 11 Jan 2008 18:14:54 -0800 Subject: ctypes, GetWindowLongPtr Message-ID: <8d04436f0801111814p31b3a98brd9fb5eed48860505@mail.gmail.com> Hello, I have been happily using ctypes for a while to do win32 programming. I use the Microsoft documentation to understand the function, then call it with the help of ctypes. The problem is that the docs says user32.dll has GetWindowLongPtr, but ctypes can't find it using windll.user32.GetWindowLongPtrA or windll.user32.GetWindowLongPtrW or windll.user32.GetWindowLongPtr. Errors look like this: Traceback (most recent call last): File "Z:\experiments\windowsapp3.py", line 106, in GetWindowLongPtr = windll.user32.GetWindowLongPtrA File "C:\Python25\lib\ctypes\__init__.py", line 353, in __getattr__ func = self.__getitem__(name) File "C:\Python25\lib\ctypes\__init__.py", line 358, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'GetWindowLongPtrA' not found I have the same problem with the SetWindowLongPtr function. I can use plenty of other functions (GetParent, CreateWindowExA, DefWindowProcA, and etc) but not these ones. I don't understand what goes on with ctypes under the hood really, so my troubleshooting abilities at this point are quite lacking! I would appreciate any help you could offer. Thanks! -- Henry -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Tue Jan 22 20:00:27 2008 From: wescpy at gmail.com (wesley chun) Date: Tue, 22 Jan 2008 17:00:27 -0800 (PST) Subject: Core Python Programming . . . References: <7xir1q29j5.fsf@ruckus.brouhaha.com> Message-ID: <40385ed1-6594-403e-934d-3d54a294101e@e25g2000prg.googlegroups.com> > > 6-11 Conversion. > > ? (a) Create a program that will convert from an integer to an > > Internet Protocol (IP) address in the four-octet format of WWW.XXX.YYY.ZZZ > > ? (b) Update your program to be able to do the vice verse of the above. > > I think it's is asking to convert a 32-bit int to the dotted form. > > It's a little known fact, but IP addresses are valid in non-dotted > long-int form. ?Spammers commonly use this trick to disguise their IP > addresses in emails from scanners. that is correct. don't read too much into it. i'm not trying to validate anything or any format, use old or new technology. it is simply to exercise your skills with numbers (specifically 32-bit/4- byte integers), string manipulation, and bitwise operations. if you wish to use different sizes of numbers, forms of addressing, IPv6, etc., that's up to you. don't forget about part (b), which is to take an IP address and turn it into a 32-bit integer. enjoy! -- wesley ps. since you're on p. 248, there is also a typo in the piece of code right above this exercise, Example 6.4, which is tied to exercise 6-7. "'fac_list'" should really be "`fac_list`", or even better, "repr(fac_list)". see the Errata at the book's website http://corepython.com for more details. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From fredrik at pythonware.com Wed Jan 9 14:38:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 20:38:38 +0100 Subject: problem of converting a list to dict In-Reply-To: <962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.googlegroups.com> References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> <962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.googlegroups.com> Message-ID: Louis.Soninhu at gmail.com wrote: >> to see what's going on on your machine, try printing "a" after the >> split, but before you use it to populate the dictionary. > > 'print a' works so what does it tell you? From washakie at gmail.com Wed Jan 30 17:34:33 2008 From: washakie at gmail.com (washakie) Date: Wed, 30 Jan 2008 14:34:33 -0800 (PST) Subject: dynamically set up ssh -r & paramiko? Message-ID: <15193757.post@talk.nabble.com> Hello, I'm trying to write a script which will allow me to initiate (spawn?) an SSH reverse tunnel from an internal box (inside a firewall) to an external box, while logged into the external box. I posted to another list and was pointed in the direction of paramiko. I've read the tutorials, but cannot seem to figure out exactly how I can do this... I'm hoping someone can look at what I'm trying to do below and provide an example... #!/usr/bin/python import os, time, subprocess REMOTE_HOME='/my/remote/mount' #mounted drive to REMOTE_HOME from LOCAL_MACHINE cmd = 'while true; do ssh -R 8022:localhost:22 MyUserName at RemoteHost ; sleep 60; done' while 1: while os.path.exists(os.path.join(REMOTE_HOME,'mySecretFile'): proc= subprocess.call(cmd,shell='True') if proc: os.kill(proc.pid) if os.path.exists(os.path.join(REMOTE_HOME,'KillScript'): break -- Note, I know the reverse tunnel script works on it's own run from the shell, but I don't want to leave it open always... furthermore it seems to be a rather 'brute force' method. It seems paramiko might provide a more elegant solution! Does anyone have any ideas on how to make this work? Thanks, john -- View this message in context: http://www.nabble.com/dynamically-set-up-ssh--r---paramiko--tp15193757p15193757.html Sent from the Python - python-list mailing list archive at Nabble.com. From fredrik at pythonware.com Tue Jan 8 06:03:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 Jan 2008 12:03:45 +0100 Subject: Open a List of Files In-Reply-To: References: Message-ID: BJ Swope wrote: > given a list such as > > ['messages', 'recipients', 'viruses'] > > how would I iterate over the list and use the values as variables and > open the variable names a files? > > I tried > > for outfile in ['messages', 'recipients', 'viruses']: > filename = os.path.join(Host_Path, outfile) > outfile = open(filename, 'w') > > But it's not working. the code looks ok. please define "not working". From gagsl-py2 at yahoo.com.ar Tue Jan 1 13:48:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Jan 2008 16:48:33 -0200 Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <6aba9463-f0ea-43a2-b8de-9c7026c4d14e@e4g2000hsg.googlegroups.com> <5c6a5515-a6ee-455d-83d4-48b2a2ae46c3@n20g2000hsh.googlegroups.com> <579f378d-d948-4c99-8507-a8c4e9a28096@i29g2000prf.googlegroups.com> <74a7edcf-f4ea-4835-b08e-499faaed8d81@i12g2000prf.googlegroups.com> Message-ID: En Tue, 01 Jan 2008 15:45:00 -0200, bukzor escribi?: > On Jan 1, 9:00 am, bukzor wrote: >> On Dec 31 2007, 1:30 pm, "Chris Mellon" wrote: >> >> > And also removing the only way you can currently do early binding in >> > Python. I agree that it's a gotcha, but unless someone comes up with >> > an answer to the following questions, I'll stick with the status quo >> > (Note that this is not blind Python group-think as a previous poster >> > implied, but a pragmatic decision that this is the most practical >> > solution): >> >> > a) If we don't evaluate default arguments at function compilation, >> > when do we do it? >> > b) If you do it at call time, how do you implement early binding? >> >> I'm confused by what you mean by 'early binding'. Can you give a quick- >> n-dirty example? > Is an 'early bound' variable synonymous with a 'static' variable (in > C)? No. It means, in which moment the name gets its value assigned. Usually Python does "late binding", that is, names are resolved at the time the code is executed, not when it's compiled or defined. Consider this example: z = 1 def foo(a) print a+z foo(3) # prints 4 z = 20 foo(3) # prints 23 The second time it prints 23, not 4, because the value for z is searched when the code is executed, so the relevant value for z is 20. Note that if you later assign a non-numeric value to z, foo(3) will fail. If you want to achieve the effect of "early binding", that is, you want to "freeze" z to be always what it was at the time the function was defined, you can do that using a default argument: z = 1 def foo(a, z=z) print a+z z = None foo(3) # prints 4 This way, foo(3) will always print 4, independently of the current value of z. Moreover, you can `del z` and foo will continue to work. This is what I think Chris Mellon was refering to. This specific default argument semantics allows one to achieve the effect of "early binding" in a language which is mostly "late binding". If someone changes this, he has to come with another way of faking early binding semantics at least as simple as this, else we're solving an [inexistant for me] problem but creating another one. -- Gabriel Genellina From martin at marcher.name Tue Jan 8 07:04:13 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 08 Jan 2008 13:04:13 +0100 Subject: Open a List of Files References: Message-ID: BJ Swope wrote: > On Jan 8, 2008 6:03 AM, Fredrik Lundh wrote: > >> BJ Swope wrote: >> >> > given a list such as >> > >> > ['messages', 'recipients', 'viruses'] >> > >> > how would I iterate over the list and use the values as variables and >> > open the variable names a files? >> > >> > I tried >> > >> > for outfile in ['messages', 'recipients', 'viruses']: >> > filename = os.path.join(Host_Path, outfile) >> > outfile = open(filename, 'w') files = dict() l = ['messages', 'recipients', 'viruses'] for f in l: files[f] = open(s.path.join(Host_Path, outfile), "w") files["messages].write("a string") hth martin PS: Code is untested -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From steven at REMOVE.THIS.cybersource.com.au Tue Jan 22 02:08:43 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 22 Jan 2008 07:08:43 -0000 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Mon, 21 Jan 2008 21:34:28 -0800, George Sakkis wrote: > I believe the "what is the fastest way" question for such small well- > defined tasks is worth asking on its own, regardless of whether it makes > a difference in the application (or even if there is no application to > begin with). Just because cpu cycles are cheap these days is not a good > reason to be sloppy. Moreover, often the fastest pure Python version > happens to be among the most elegant and concise, unlike other languages > where optimization usually implies obfuscation. I wonder why it is that people automatically assume that "optimization" means optimize the time taken, and not the developer effort to write it in the first place, the effort required to maintain it over time, or the memory used at runtime, let alone some combination of all four factors. Memory is cheap, but applications are hungry. CPUs are fast, and for most applications the difference between 3ms and 30ms is undetectable by the user. Why do we care so little about saving memory and so much about ever-decreasing time savings? -- Steven From bladedpenguin at gmail.com Sat Jan 26 00:20:23 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 21:20:23 -0800 (PST) Subject: Doesn't know what it wants Message-ID: Traceback (most recent call last): File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox \sandbox.py", line 242, in player = ship() File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox \sandbox.py", line 121, in __init__ self.phyInit() File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox \sandbox.py", line 147, in phyInit moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) ArgumentError: argument 4: : expected vec2d instance instead of vec2d As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't seems like it doesn't know what it wants, but I thought only teenagers did that, no programming languages. clearly, Im missing something. Line 147 reads: moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) From fredrik at pythonware.com Wed Jan 9 12:07:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 18:07:37 +0100 Subject: sqlite fetchall breacking because decoding. In-Reply-To: <8e81ff71-5e2e-4135-8159-6411a65e4100@v67g2000hse.googlegroups.com> References: <514759dc-faf7-4e34-bf6d-624a0cc540ae@e4g2000hsg.googlegroups.com> <8e81ff71-5e2e-4135-8159-6411a65e4100@v67g2000hse.googlegroups.com> Message-ID: tyoc wrote: >> well, the database *is* corrupt, since sqlite3 (both the engine and the >> Python binding) expects you to use a supported encoding for the data >> stored in the database: >> >> http://www.sqlite.org/datatype3.html >> http://docs.python.org/lib/node346.html > > Still like I said before, I have imported that data from python source > was a CVS with that encoding, I readed the lines with module CSV, then > used insert to the database like: the CSV module doesn't decode stuff for you; that's up to your code. see http://docs.python.org/lib/csv-examples.html#csv-examples for sample code (scroll down to the paragraph that starts with "The csv module doesn't directly support reading and writing Unicode"). From paul at boddie.org.uk Fri Jan 25 06:04:34 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 25 Jan 2008 03:04:34 -0800 (PST) Subject: time.gmtime References: <293bb767-603b-4aef-b9c8-23af565b090f@s8g2000prg.googlegroups.com> Message-ID: <6d8d8eac-3d4a-4b9a-9624-a1087c45ed6d@q39g2000hsf.googlegroups.com> On 25 Jan, 11:43, asit wrote: > we know that time.gmtime(secs) takes a parameter secs. what does this > secs suggest ??What is it's significance ?? >From the documentation [1] with some editing: """ gmtime([secs]) Convert a time expressed in seconds since the epoch to a time structure employing UTC. If secs is not provided or None, the current time as returned by time.time() is used. The epoch is the point where the time starts. On January 1st of that year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the epoch is 1970. To find out what the epoch is, look at gmtime(0). """ So, the significance of the secs parameter is that it indicates a specific point in time. Generally, you'll get this from functions like time.time or from "UNIX timestamps" stored in things like files and databases where people have wanted to indicate a point in time without having to mention things like dates, times and timezones. Paul P.S. The datetime module is preferable to the time module, really. The latter can drive you quite mad when things like timezones start to be taken into account. [1] http://docs.python.org/lib/module-time.html From mail at microcorp.co.za Sat Jan 12 03:44:39 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 12 Jan 2008 10:44:39 +0200 Subject: [Kamaelia] TCPClient: How to sense connection failure? References: <5uq49vF1jkgcoU1@mid.individual.net> Message-ID: <00c701c854f7$7b3cda20$03000080@hendrik> "Bjoern Schliessmann" wrote: >I'm currently trying to implement a simulation program with Kamaelia >and need a reliable TCP connection to a data server. > >From Twisted, I know that a method is called if the connection fails >by whatever reason. I tried to get the same results with Kamaelia's >TCPClient component. If I start up the component and try to connect >to a closed TCP port it fails and sends a message out of the signal >box, that's okay. > >But if the connection attempt succeeds and, after some time, the >server drops the connection with full TCP handshake (FIN, FIN+ACK, >ACK), the component just hangs and does nothing. Is this by design, >or could there be an error in my setup? > Not sure about Kamelia, but I have found that when a FIN comes along, a socket.recv() gives back an empty string, just like EOF on a file. I always have my sockets unblocked and fitted with time outs, but then I am basically a broken down assembler programmer, so there are probably better techniques around. Below is what I use - a sort of netstring, synced on a tilde, with human readable length implementation and escaping of tildes and the escape character. It seems to work reliably for me, and detects when the server goes down. The code for a typical client is below. If anybody is interested I will post the server too, but it should be trivial to make, given the example below. I hope the tabs survive the journey - Hendrik #start of code fragment def sockget_len(s,L,data): """ This fills a buffer of given length from the socket s, recursively. s is the socket L is the length to receive data is the buffer """ error = 0 req_L = L - len(data) try: data = data+s.recv(req_L) except socket.error,msg: # broken pipes again if 'timed out' in msg: rec = '2'*L return 2,rec # time out print 'socket error while receiving',msg rec = '1'*L return 1,rec # error = 1 is a snafu if not data: print 'end of file while receiving' rec = '0'*L return 3,rec # This is end of file if len(data) != L: error,data = sockget_len(s,L,data) return error,data def sockget(s): """ Gets a transmission from host. """ while True: tilde = '' error,tilde = sockget_len(s,1,tilde) # sync up on tilde if error == 1: return error,'' elif error == 2: return error,'' elif error == 3: return error,'' if tilde == '~': break length = '' error,length = sockget_len(s,4,length) # get the length of the data if error == 1: return error,'' # real error elif error == 2: return error,'' # Time out elif error == 3: return error,'' # End of file L = int(length) buf = '' error,data = sockget_len(s,L,buf) # get the data of length L return error, data # same errors as above 0 is all right # client communications program def comms_thread(qi,qo): """This listens for the latest values, and sends requests up.""" while True: HOST = 'Linuxbox' # The remote host PORT = 50007 # The same port as used by the server socket.setdefaulttimeout(10.00) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: qi.put('Connecting,') s.connect((HOST, PORT)) break except socket.error,msg: print 'error msg is:',msg time.sleep(10) continue print 'Connected - Time out is:',s.gettimeout() qi.put('Connected,') last_rx_time = time.time() last_tx_time = time.time() while True: while True: error,data = sockget(s) # see if a message from host if error == 0 and data: msg2 = data.replace('/\x81','~') msg1 = msg2.replace('/\xd0','/') qi.put(msg1) print 'received',msg1 last_rx_time = time.time() break elif error == 1: print 'Error after sockget' break if time.time() - last_rx_time > 180: print 'no comms from host for 3 minutes' error = 1 break # time out ok, unless they are too long if error == 2: error = 0 # time outs are all right here break if error == 3: error = 1 break # end of files are a snafu if error == 1: break try: i_string = qo.get(block=False) # see if stuff to transmit except Queue.Empty: if time.time()-last_tx_time > 8.5: i_string = 'Keepalive' # if not for a while, tell server we are alive print 'sending keepalive' else: time.sleep(0.1) # else wait a while and carry on continue msg1 = i_string.replace('/','/\xd0') msg2 = msg1.replace('~','/\x81') length = str(len(msg2)) L = len(length) if L == 1: length = '000'+length elif L == 2: length = '00'+length elif L == 3: length = '0'+length try: s.send('~'+length+msg2) last_tx_time = time.time() except socket.error,msg: print 'Socket error on transmit',msg break time.sleep(0.1) s.close() # Formally close the broken thing qi.put('Quit,') # Tell main thread its hopeless sys.exit() # Clobber this thread From aisaac at american.edu Fri Jan 25 18:41:08 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 25 Jan 2008 23:41:08 GMT Subject: find minimum associated values In-Reply-To: References: Message-ID: bearophileHUGS at lycos.com wrote: > I'd use the first solution. It can be speeded up a bit with a try/except: for k,v in kv: try: if d[k] > v: d[k] = v except KeyError: d[k] = v Cheers, Alan Isaac From steve at REMOVE-THIS-cybersource.com.au Sat Jan 26 07:01:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 26 Jan 2008 12:01:59 -0000 Subject: Custom class to a dictionary? References: <5025a3f7-9dcf-49d7-876c-df5c8d8a8df5@e6g2000prf.googlegroups.com> Message-ID: <13pm89n9avfl146@corp.supernews.com> On Sat, 26 Jan 2008 03:35:18 -0800, Oliver Beattie wrote: > Just wondering if it is possible to pass a custom class instance > instance to dict() by way of using methods like you can for iterators > (__iter__, __getitem__ etc.) I see there is no __dict__ -- is there > anything else I can use to achieve this? Just write a method to return (key, value) pairs, and call that: >>> class Parrot(object): ... def __init__(self): ... self.keys = [1, 2, 3, 4] ... self.values = ["one", "two", "three", "four"] ... def generate_tuples(self): ... for k,v in zip(self.keys, self.values): ... yield (k,v) ... >>> p = Parrot() >>> p.generate_tuples() >>> dict(p.generate_tuples()) {1: 'one', 2: 'two', 3: 'three', 4: 'four'} Here's another way: >>> class Foo(object): ... def __getitem__(self, i): ... if i > 4: ... raise IndexError ... return (i, 'foo %d' % i) ... >>> dict(Foo()) {0: 'foo 0', 1: 'foo 1', 2: 'foo 2', 3: 'foo 3', 4: 'foo 4'} Bonus marks if you can explain why they both work :) (Hint: consider the "sequence protocol" and the "iterator protocol".) -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Jan 17 23:36:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 18 Jan 2008 04:36:35 -0000 Subject: array and list References: <87bq7jbwxo.fsf@benfinney.id.au> Message-ID: <13p0b6jbn2ut6b4@corp.supernews.com> On Fri, 18 Jan 2008 15:05:23 +1100, Ben Finney wrote: > "J. Peng" writes: > >> what's the difference between an array and a list in python? > > In Python, 'list' is a basic built-in type. Python has no 'array' type, > though that term is often used to refer to the 'array' type defined in > Numeric Python (which is not part of the standard library, so not really > part of Python). Did you forget the array module? >>> import array >>> array >> I see list has all features of array in C or perl. > > You may also want to compare and constrast Python 'list' and 'dict'. The Original Poster might also like to check out the help() and dir() functions in the interactive interpreter: help(list) dir(list) help(array) help(array.array) etc. -- Steven From terry at jon.es Wed Jan 23 15:40:31 2008 From: terry at jon.es (Terry Jones) Date: Wed, 23 Jan 2008 21:40:31 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 10:12:22 on Wednesday, 23 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> <457550e3-f5e1-4fad-b553-c3e5e400dbb1@u10g2000prn.googlegroups.com> Message-ID: <18327.42559.997192.308761@jon.es> >>>>> "Arnaud" == Arnaud Delobelle writes: Arnaud> FWIW, I have a clear idea of what the space of solutions is, and Arnaud> which solutions I consider to be equivalent. I'll explain it Arnaud> below. I'm not saying it's the right model, but it's the one Arnaud> within which I'm thinking. OK. This reinforces why I'm not going to work on it anymore, the solution is subjective (once you start pruning). Arnaud> I think it's best to forbid negatives. Solutions always be written Arnaud> without any negative intermediate answer. E.g. 1-7*6*(3-9) can be Arnaud> done as 1+7*6*(9-3). That's a good optimization, and I think it's easy to prove that it's correct supposing the target is positive and the inputs are all positive. If you consider the intermediate results in a solution, then if you ever go negative it's because of an operation X (must be a sub or a div) and when you next become positive it's due to an operation Y (must be add or mul). So you can "reflect" that part of the computation by doing the opposite operations for that formerly sub-zero intermediate sequence. Arnaud> I don't consider these to be equivalent, because their equivalence Arnaud> depends on understanding the meaning of subtraction and addition. Ha - you can't have it both ways Arnaud! You don't want the computation to go negative... doesn't that (and my "proof") have something to do with the inverse nature of add and sub? :-) Arnaud> (I've also applied the 'big then small' rule explained below) And now you're taking advantage of your knowledge of > and < ... My original code did this big then small canonicalization too. That's my point exactly - pruning depends on who you are, how smart you are, how hard you work, your personal taste, etc. Arnaud> I see a solution as a full ordered binary tree. Each node has a Arnaud> weight (which is the result of the calculation it represents) and Arnaud> the left child of a node has to be at least as heavy as the right Arnaud> child. Each parent node can be labeled + - * or /. If a node x Arnaud> has two children y and z and is labeled , let me write x = (y Arnaud> z) Where does the sequence of numbers enter into this? You have a tree of operations - is it acting on a stack? What's on the stack? It sounds similar to what I've done. I walk up and down the tree, keeping the stack and the stack history, doing operations (including pushing onto the stack) and undoing them. There are several more prunings I could be doing, but these require looking further back in the stack. E.g., I force div before mul and sub before add, and I also apply the "big then small" rule to the intermediate stack results if there are series of identical operations (not just to a single operation). E.g. X / Y / Z can be re-ordered so that Y >= Z, and A + B + C can be reordered so A >= B >= C. Doing it on the stack results is different (but similar) to doing it on the raw input numbers. There are lots of other little and more complex things you can do to prune. You want to prune early, of course. The stack model of computation make this hard because it's always legitimate to push all the numbers onto the stack, by which point you're already deep in the tree. And this approach only lets you do local pruning - i.e., that affect the branch of the tree you're on. If you stored the state of the stack, the operation you're about to do, and the (sorted) numbers remaining to be input, then if you ever hit that configuration elsewhere in the massive tree, you could know that you'd been that way before. But are you justified in pruning at that point? The identical state of the computation could have been arrived at via a very different method. But that's where the big speed-up in this approach is. At this realization I decided to give up :-) Arnaud> To be perfectly honest (and expose my approach a little to your Arnaud> argument) I added a three additional rules: Arnaud> * Don't allow x - x Arnaud> * Don't allow x * 1 Arnaud> * Don't allow x / 1 Yes, I do these too, including not allowing a zero intermediate (which is a useless calculation that simply could not have been done - see, I have deep knowledge of zero!). Arnaud> If there are repeats in the list of starting numbers, I don't worry Arnaud> about repeating solutions. I handle most of those cases, but I didn't push all the way. With target 32 and input 8, 8, 8, 8 my code still gives 2 answers: 8 8 add 8 8 add add 8 8 add 8 add 8 add >> If anyone wants the stack simulation code, send me an email. Arnaud> I'd like to see it :) I'll send it. Terry From bignose+hates-spam at benfinney.id.au Wed Jan 23 18:06:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 24 Jan 2008 10:06:38 +1100 Subject: Increment Variable Name References: Message-ID: <87myqw87lt.fsf@benfinney.id.au> David Brochu writes: > I know the length of a list and I want to pass each element of a > list to a unique variable, thus I want to increment variable names. > If the list length = 4, i want to have the following variables: > var1, var2, var3, var4. This has a very bad code smell. What problem are you trying to solve by doing this? I strongly suspect there's a better solution. -- \ "If you do not trust the source do not use this program." | `\ ?Microsoft Vista security dialogue | _o__) | Ben Finney From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 08:41:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 27 Jan 2008 13:41:54 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> Message-ID: <13pp2h2eugn8594@corp.supernews.com> On Sun, 27 Jan 2008 10:55:20 +0000, over wrote: > I can understand people thinking I'm full of beans. Oh no, not full of beans. Full of something, but not beans. Everything you have written about assembly, machine code, compilers, Linux, Python and so forth has been a confused mish-mash of half-truths, distortions, vaguely correct factoids and complete nonsense. I'm starting to wonder if it is possible for somebody to be simultaneously so self-assured and so ignorant, or if we're being trolled. -- Steven From paul.hankin at gmail.com Wed Jan 16 11:10:35 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 16 Jan 2008 08:10:35 -0800 (PST) Subject: Generic string import like in strptime? References: Message-ID: On Jan 16, 8:34 am, Andre wrote: > Hi there > > Is there a function like strptime, which takes a string and converts it > into an array depending on a format string I provide. Like:>>> a = '3456\tblub-blib.0.9' > >>> b = '%d\t%s-%s.%f' > >>> c = mysticalfunction(a,b) > >>> print c > > [3456,'blub','blib',0.9] Use regular expressions: see http://docs.python.org/lib/node49.html -- Paul Hankin From asmodai at in-nomine.org Wed Jan 2 10:22:43 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 2 Jan 2008 16:22:43 +0100 Subject: Network-Packets In-Reply-To: <52da23100801020657v2d6e001ck5a9e126db77eb511@mail.gmail.com> References: <52da23100801020657v2d6e001ck5a9e126db77eb511@mail.gmail.com> Message-ID: <20080102152243.GE67953@nexus.in-nomine.org> -On [20080102 16:00], Sunil Ghai (sunilkrghai at gmail.com) wrote: >I know this is not the right place for asking about this but i am sure some of >you must have an idea about this. The networking community would be more appropriate, methinks. >I would like to know what do we actually mean by "Bandwidth". It is actually a fairly standardized term by now, to borrow Wikipedia's definition: In website hosting, the term "bandwidth" is often used metaphorically, to describe the amount of data that can be transferred to or from the website or server, measured in bytes transferred over a prescribed period of time. Even if a system discards packets, your NSP, ISP or webhost will still count it towards your total since it traversed their network. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ I must be cruel, only to be kind... From bernard.desnoues at univ-paris1.fr Mon Jan 21 09:02:11 2008 From: bernard.desnoues at univ-paris1.fr (Bernard Desnoues) Date: Mon, 21 Jan 2008 15:02:11 +0100 Subject: stdin, stdout, redmon Message-ID: <4794a5e3$0$9014$426a74cc@news.free.fr> Hi, I've got a problem with the use of Redmon (redirection port monitor). I intend to develop a virtual printer so that I can modify data sent to the printer. Redmon send the data flow to the standard input and lauchs the Python program which send modified data to the standard output (Windows XP and Python 2.5 context). I can manipulate the standard output. "import sys sys.stdout.write(data)" it works. But how to manipulate standard input so that I can store data in a string or in an object file ? There's no "read" method. "a = sys.stdin.read()" doesn't work. "f = open(sys.stdin)" doesn't work. I don't find anything in the documentation. How to do that ? Thanks in advance. Bernard Desnoues Librarian Biblioth?que de g?ographie - Sorbonne From software at ginstrom.com Thu Jan 17 20:55:21 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Fri, 18 Jan 2008 10:55:21 +0900 Subject: [OT] "Code Friendly" Blog? In-Reply-To: References: Message-ID: <0e1801c85975$2f89b9e0$0203a8c0@MOUSE> > On Behalf Of Miki > Posting code examples to blogger.com hosted blog is not fun > (need to remember alway escape < and >). > Is there any free blog hosting that is more "code friendly" > (easy to post code snippets and such)? I use WordPress with the Dean's Code Highlighter plugin[1] (which uses the Geshi code highlighter). You write your code like this:
print "hello, world!"
You do need to escape angle brackets, though. You also have to turn off WYSIWYG editing in WordPress, or it'll mess things up. Here's an example of how it turns out: http://ginstrom.com/scribbles/2007/11/17/fixing-jis-mojibake-with-python/ [1] http://www.deanlee.cn/wordpress/code_highlighter_plugin_for_wordpress/ Regards, Ryan Ginstrom From arnodel at googlemail.com Sat Jan 26 11:13:01 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 26 Jan 2008 16:13:01 +0000 Subject: Just for fun: Countdown numbers game solver In-Reply-To: <18327.47084.736074.304302@jon.es> References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> <457550e3-f5e1-4fad-b553-c3e5e400dbb1@u10g2000prn.googlegroups.com> <18327.47084.736074.304302@jon.es> Message-ID: <201F42DF-C0B1-482F-A0AB-59AD07AE77E0@gmail.com> Right, I've cleaned up my efforts a bit: * tried to improve the efficiency of the 'fold' technique that I posted earlier. * taken on Dan's email about equivalence of expressions * created a problem random generator * created a little function test to time and compare various things, and a 'random test' function. In the file there are two methods for combining two expressions: 'ops' and 'cleverops'. Ops is vanilla, cleverops only returns canonical expressions (roughly) as defined in Dan's email. The two strategies for walking the solution tree are 'divide and conquer' (divide) and 'origami' (fold). The code is pretty straighforward and is commented! Then there are some convenience functions for running the algorithms: print_countdown, all_countdown and first_countdown. Here's an example of how it works: >>> # print all solutions using the divide method, and cleverops: >>> print_countdown([50, 8, 5, 4, 9, 10], 983, method=divide, ops=cleverops) 50*5*4-9-8 (50*5+8-10)*4-9 (50+8/4)*(10+9)-5 50*(10-5)*4-9-8 >>> # Test which method is fastest, divide or fold: >>> randtest(10, 'method', method=[divide, fold], ops=cleverops) divide fold 0.317304 0.366359 ([1, 2, 4, 3, 6, 7], 249) 0.495667 0.660426 ([75, 100, 50, 25, 9, 3], 289) 0.443912 0.562409 ([50, 8, 5, 4, 9, 10], 399) 0.199696 0.231997 ([100, 1, 5, 7, 1, 4], 833) 0.406256 0.527588 ([50, 25, 10, 9, 3, 8], 123) 0.263348 0.315722 ([9, 8, 7, 5, 1, 7], 730) 0.403028 0.517426 ([25, 75, 9, 4, 10, 6], 605) 0.420140 0.564138 ([10, 6, 10, 9, 5, 4], 900) 0.278489 0.343525 ([4, 10, 5, 9, 9, 1], 388) 0.485815 0.643627 ([100, 10, 2, 6, 3, 9], 146) ------------ ------------ 0.371365 0.473322 >>> # Test which method is best for finding just one solution: >>> randtest(10, 'method', method=[divide, fold], countdown=first_countdown) divide fold 0.001674 0.043920 ([50, 75, 25, 9, 5, 8], 333) 0.164332 0.072060 ([75, 2, 7, 8, 8, 5], 409) 0.028889 0.212317 ([50, 100, 75, 6, 3, 9], 782) 0.049070 0.005830 ([75, 4, 3, 2, 1, 6], 471) 0.014728 0.091845 ([100, 75, 25, 50, 8, 7], 483) 0.290982 0.367972 ([3, 1, 7, 6, 5, 3], 794) 0.240363 0.118508 ([50, 100, 75, 3, 1, 10], 537) 0.001693 0.009519 ([50, 75, 8, 7, 5, 5], 180) 0.000289 0.037539 ([3, 9, 2, 4, 4, 1], 123) 0.079161 0.174323 ([50, 75, 100, 25, 4, 10], 723) ------------ ------------ 0.087118 0.113383 >>> # Test how cleverops improves over ops for the fold method: >>> randtest(10, 'ops', method=fold, ops=[ops, cleverops]) ops cleverops 1.689920 0.671041 ([75, 9, 6, 10, 3, 9], 874) 0.938402 0.338120 ([5, 7, 8, 2, 1, 7], 258) 0.982800 0.333443 ([25, 50, 9, 4, 8, 1], 309) 1.152037 0.407845 ([25, 50, 3, 5, 10, 1], 736) 0.892541 0.323406 ([9, 7, 1, 9, 4, 10], 108) 1.794778 0.677161 ([25, 50, 10, 8, 2, 6], 357) 1.534185 0.591878 ([50, 100, 25, 7, 7, 3], 773) 1.013421 0.350179 ([50, 6, 3, 1, 8, 9], 761) 0.612838 0.228354 ([25, 1, 4, 3, 1, 4], 148) 1.213055 0.430611 ([50, 100, 5, 3, 10, 1], 814) ------------ ------------ 1.182398 0.435204 I have found that the 'divide & conquer' strategy is faster than the 'origami' one. Moreover cleverops (i.e. clever pruning) improves origami by much more than divide&conquer. Code follows. Terry: I'm going to look at your code tonight and see if I can interface it with my little testing suite. Thanks for posting it! It was a lot of fun thinking about this, although I am sure that there is a lot of room for improvement. In particular, there must be a simple way to avoid the amount of list tinkering in fold(). Any feedback greatly appreciated. -- Arnaud ====================== countdown.py ======================= def getop(h): return 'n' if isinstance(h, int) else h[1] # An ops function takes two numbers with histories and yield all suitable # ways of combining them together. def ops(a, b): if a < b: a, b = b, a x, hx = a y, hy = b yield x + y, (a, '+', b) if x != 1 and y != 1: yield x * y, (a, '*', b) if x != y: yield x - y, (a, '-', b) if not x % y and y != 1: yield x / y, (a, '/', b) def cleverops(a, b, getop=getop): if a < b: a, b = b, a x, hx = a y, hy = b opx, opy = getop(hx), getop(hy) # rx is the right operand of hx (or x if no history) rx = x if opx == 'n' else hx[2][0] if opy not in '+-': # Only allow a+b+c-x-y-z if a >= b >= c... if (opx == '+' and rx >= y) or (opx not in '+-' and x >= y): yield x + y, (a, '+', b) # ... and x >= y >= z if x > y and (opx != '-' or rx >= y): yield x - y, (a, '-', b) if y != 1 and opy not in '*/': # Only allow a*b*c/x/y/z if a >= b >= c... if (opx == '*' and rx >= y) or (opx not in '*/' and x >= y): yield x * y, (a, '*', b) # ... and x >= y >= z if not x % y and (opx != '/' or rx >= y): yield x / y, (a, '/', b) # a method function takes a list of numbers, an action, and and ops # function. It should go through all ways of combining the numbers # together (using ops) and apply action to each. def fold(nums, action, ops=cleverops): "Use the 'origami' approach" nums = zip(nums, nums) # Attach a history to each number def recfold(start=1): for i in xrange(start, len(nums)): a, ii = nums[i], i-1 # Pick a number; for j in xrange(i): b = nums.pop(j) # Take out another before it; for x in ops(a, b): # combine them nums[ii] = x # into one; action(*x) # (with side-effect) recfold(ii or 1) # then fold the shorter list. nums.insert(j, b) nums[i] = a recfold() def divide(nums, action, ops=cleverops): "Use the 'divide and conquer' approach" def partitions(l): "generate all 2-partitions of l" for i in xrange(1, 2**len(l)-1, 2): partition = [], [] for x in l: i, r = divmod(i, 2) partition[r].append(x) yield partition def recdiv(l): if len(l) == 1: # if l in a singleton, yield l[0] # we're done. else: for l1, l2 in partitions(l): # Divide l in two; for a in recdiv(l1): # conquer the two for b in recdiv(l2): # smaller lists; for x in ops(a, b): # combine results action(*x) # (with side-effect) yield x # and yield answer. for x in recdiv(zip(nums, nums)): pass # Countdown functions def all_countdown(nums, target, method=fold, ops=cleverops): "Return all ways of reaching target with nums" all = [] def action(n, h): if n == target: all.append(h) method(nums, action, ops) return all def print_countdown(nums, target, method=fold, ops=cleverops): "Print all solutions" def action(n, h): if n == target: print pretty(h) method(nums, action, ops) class FoundSolution(Exception): "Helper exception class for first_countdown" def __init__(self, sol): self.sol = sol def first_countdown(nums, target, method=fold, ops=cleverops): "Return one way of reaching target with nums" def action(n, h): if n == target: raise FoundSolution(h) try: method(nums, action, ops) except FoundSolution, fs: return pretty(fs.sol) # Pretty representation of a number's history lbracket = ['+*', '-*', '+/', '-/', '/*'] rbracket = ['*+', '*-', '/+', '/-', '/*', '-+', '--'] def pretty(h): "Print a readable form of a number's history" if isinstance(h, int): return str(h) else: x, op, y = h x, y = x[1], y[1] x, y, xop, yop = pretty(x), pretty(y), getop(x), getop(y) if xop + op in lbracket: x = "(%s)" % x if op + yop in rbracket: y = "(%s)" % y return ''.join((x, op, y)) # This test function times a call to a countdown function, it allows # comparisons between differents things (methods, ops, ...) def test(enumkey=None, **kwargs): from time import time def do_countdown(countdown=all_countdown, target=758, nums=[2, 4, 5, 8, 9, 25], **kwargs): return countdown(nums, target, **kwargs) enum = kwargs.pop(enumkey) if enumkey else ['time'] for val in enum: if enumkey: kwargs[enumkey] = val t0 = time() do_countdown(**kwargs) t1 = time() yield t1-t0 # Tools for generating random countdown problems and doing random # tests. bignums, smallnums = [25, 50, 75, 100], range(1, 11)*2 from random import sample, randrange def randnums(nbig=None): if nbig is None: nbig = randrange(5) return sample(bignums, nbig) + sample(smallnums, 6-nbig) def randtarget(): return randrange(100, 1000) # Like test() but generates n tests with a new random problem to solve # each time, and prints the results. def randtest(n=1, enumkey=None, col=12, **kwargs): if enumkey: enums = kwargs[enumkey] nenums = len(enums) enums = [getattr(obj, '__name__', obj) for obj in enums] print ' '.join("%*s" % (col, obj[:col]) for obj in enums) else: nenums = 1 acc = [0] * nenums for i in xrange(n): target, nums = randtarget(), randnums() kwargs.update(target=target, nums=nums) times = tuple(test(enumkey, **kwargs)) print ' '.join("%*f" % (col, t) for t in times), print ' (%s, %s)' % (nums, target) for i, t in enumerate(times): acc[i] += t if n > 1: print ' '.join(['-'*col]*nenums) print ' '.join("%*f" % (col, t/n) for t in acc) From stanc at al.com.au Tue Jan 15 18:08:49 2008 From: stanc at al.com.au (Astan Chee) Date: Wed, 16 Jan 2008 10:08:49 +1100 Subject: Restart crashing modules in windows In-Reply-To: <86a0b31e-de71-4820-a37f-3c0fa26b768f@i72g2000hsd.googlegroups.com> References: <86a0b31e-de71-4820-a37f-3c0fa26b768f@i72g2000hsd.googlegroups.com> Message-ID: <478D3D01.9060303@al.com.au> Mike Driscoll wrote: > On Jan 14, 9:02 pm, Astan Chee wrote: > >> Hi, >> I have a python module that keeps on crashing with various windows >> errors (not BSOD but the less lethal windows XP popup ones). Now these >> are intentional and rather sporadic so I cant really solve it by >> attempting to fix the crash; rather what Im trying to do is make another >> module outside it that restarts this module every time it crashes. Is >> this possible? >> > > If you're not going to catch the error that is causing the crash, then > I think your only option is to restart your application with an > external program. > My understanding of using an external application to do this is to first create my module as an executable using py2exe. Then I have another python script that runs this module like this while (1): os.popen("program_module.exe") and make this other python script into another executable and execute this one. If Im not mistaken, when the python program crashes, the thread is killed. is this correct or how should I do it? Thanks again. Astan -------------- next part -------------- An HTML attachment was scrubbed... URL: From tkapoor at wscm.net Wed Jan 16 09:56:55 2008 From: tkapoor at wscm.net (Tarun Kapoor) Date: Wed, 16 Jan 2008 08:56:55 -0600 Subject: paramiko Message-ID: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> I am using paramiko to do an SFTP file transfer... I was able to connect to the remote server using an SFTP client I have just to make sure that username and password are working.. This is the code. # now, connect and use paramiko Transport to negotiate SSH2 across the connection sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) t = paramiko.Transport(sock) event = threading.Event() t.start_client(event) event.wait(15) if not t.is_active(): print 'SSH negotiation failed.' sys.exit(1) else: print "SSH negotiation sucessful" event.clear() t.auth_password(username=username, password=password,event=event) if not t.is_authenticated(): print "not authenticated" output: SSH negotiation successful not authenticated Tarun Waterstone Capital Management 2 Carlson Parkway, Suite 260 Plymouth, MN 55447 Direct: 952-697-4123 Cell: 612-205-2587 Disclaimer This e-mail and any attachments is confidential and intended solely for the use of the individual(s) to whom it is addressed. Any views or opinions presented are solely those of the author and do not necessarily represent those of Waterstone Capital Management, L.P and affiliates. If you are not the intended recipient, be advised that you have received this e-mail in error and that any use, dissemination, printing, forwarding or copying of this email is strictly prohibited. Please contact the sender if you have received this e-mail in error. You should also be aware that e-mails are susceptible to interference and you should not assume that the contents of this e-mail originated from the sender above or that they have been accurately reproduced in their original form. Waterstone Capital Management, L.P. and affiliates accepts no responsibility for information, or errors or omissions in this e-mail or use or misuse thereof. If in doubt, please verify the authenticity with the sender. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sromero at gmail.com Wed Jan 30 02:01:18 2008 From: sromero at gmail.com (Santiago Romero) Date: Tue, 29 Jan 2008 23:01:18 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> Message-ID: > how about > > >>> li = [1,2,3,4,5] > >>> filter(lambda x: x != 3, li) > [1, 2, 4, 5] I haven't measured it, but this should be the fast solution in all the thread ... From DustanGroups at gmail.com Wed Jan 16 20:13:38 2008 From: DustanGroups at gmail.com (Dustan) Date: Wed, 16 Jan 2008 17:13:38 -0800 (PST) Subject: anti-spam policy for c.l.py? References: <08ed32c4-6230-4b14-9c31-4b94e0231cf2@c4g2000hsg.googlegroups.com> <478dee4e$0$28424$426a34cc@news.free.fr> <478e1068$0$27280$426a34cc@news.free.fr> <63a12990-5e3f-4761-b0d3-785623199a7c@c4g2000hsg.googlegroups.com> Message-ID: <646b2724-4600-40c8-85c2-63775c1b1646@h11g2000prf.googlegroups.com> On Jan 16, 11:31 am, _wolf wrote: > On Jan 16, 3:11 pm, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > Jeroen Ruigrok van der Werven a ?crit : > > > > -On [20080116 12:51], Bruno Desthuilliers (bruno.42.desthuilli... at wtf.websiteburo.oops.com) wrote: > > >> Apart from checking posts headers and complaining about the relevant > > >> ISPs, there's not much you can do AFAIK. This is usenet, not a mailing-list. > > > > It is both actually. python-l... at python.org is linked to comp.lang.python due > > > to a news gateway. > > > Yes, I know - but the OP explicitely mentionned c.l.py (re-read the > > title), not the ML. > > technically correct, but the idea is of course to keep all those > archives relatively clean and informative. the new fad i've observed > seems to be to initiate whole threads where previously spam very often > stopped short of any second post. The ones that have received more than 2 responses have, the vast majority of the time, been cross posts. From fetchinson at googlemail.com Wed Jan 9 16:11:10 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 9 Jan 2008 13:11:10 -0800 Subject: Natural-language datetime parsing and display (was: user friendly datetime features) In-Reply-To: References: <873at7lq0d.fsf@benfinney.id.au> Message-ID: > For PARSING see http://code-bear.com/code/parsedatetime/ > > The OP was looking for presentation though. I know roundup has code for > this if an independent library can't be found. Thanks for all the responses! Indeed I was looking for presentation and not parsing, I'll take a look at roundup. Cheers, Daniel From python.list at tim.thechases.com Mon Jan 21 16:11:28 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 21 Jan 2008 15:11:28 -0600 Subject: Transforming ascii file (pseduo database) into proper database In-Reply-To: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> Message-ID: <47950A80.8060200@tim.thechases.com> > I need to take a series of ascii files and transform the data > contained therein so that it can be inserted into an existing > database. [snip] > I need to transform the data from the files before inserting > into the database. Now, this would all be relatively simple if > not for the following fact: The ascii files are each around > 800MB, [snip] > My questions are: > 1. Has anyone done anything like this before, and if so, do > you have any advice? Yes, I regularly do ETL on files from cellular providers to transform hundreds of megs worth (some approach a gig) of data into our internal system. > 2. In the abstract, can anyone think of a way of amassing all > the related data for a specific identifier from all the > individual files without pulling all of the files into memory > and without having to repeatedly open, search, and close the > files over and over again? if the file is sorted by something you can use, you can iterate over it and just deal with one grouping at a time. In my case, iterating over gobs of call-detail, the file happens to be sorted by the phone-number on the account. So I iterate over the file maintaining a list of calls for the given phonenumber, and when the phonenumber changes, I deal with the previous cache of data, then re-initialize with the new phone's data. Other ideas: 1) create a temp DB (such as sqlite), skim through the file inserting all your data into a table in this DB, then use DB functionality on it 2) in a light-weight way, assuming there's lots of data per row, and that you have multiple rows associated with a given ID (in my case, such as a phonenumber), you can create a dictionary of an ID to a list of file-offsets in which that ID is used. You can then skim through the file once gathering all the offsets with calls to tell() and then when you want to process an item, you can seek to that particular offset and read in the line. Not greatly efficient, but hackable. But mostly, it helps if you have a sorted field that's useful to you :) -tkc From toby at tobiah.org Wed Jan 16 14:58:14 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 16 Jan 2008 11:58:14 -0800 Subject: itertools.groupby In-Reply-To: <7xejcii3zb.fsf@ruckus.brouhaha.com> References: <478d0b7d$0$26094$88260bb3@free.teranews.com> <7xejcii3zb.fsf@ruckus.brouhaha.com> Message-ID: <478e55db$0$26033$88260bb3@free.teranews.com> Paul Rubin wrote: > Tobiah writes: >> I tried doing this with a simple example, but noticed >> that [].sort(func) passes two arguments to func, whereas >> the function expected by groupby() uses only one argument. > > Use: [].sort(key=func) Oh cool. Thanks. Only in 2.4+ it seems. >>> a = [1,2,3,4,5] >>> def sorter(thing): ... return thing % 2 == 0 ... >>> a.sort(key = sorter) >>> print a [1, 3, 5, 2, 4] >>> Nifty -- Posted via a free Usenet account from http://www.teranews.com From paddy3118 at googlemail.com Mon Jan 7 03:14:01 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 7 Jan 2008 00:14:01 -0800 (PST) Subject: Should HTML entity translation accept "&"? References: <47817BDC.7020707@animats.com> Message-ID: On Jan 7, 1:09 am, John Nagle wrote: > Another in our ongoing series on "Parsing Real-World HTML". > > It's wrong, of course. But Firefox will accept as HTML escapes > > & > > > < > > as well as the correct forms > > & > > > < > > To be "compatible", a Python screen scraper at > > http://zesty.ca/python/scrape.py > > has a function "htmldecode", which is supposed to recognize > HTML escapes and generate Unicode. (Why isn't this a standard > Python library function? Its inverse is available.) > > This uses the regular expression > > charrefpat = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?',re.UNICODE) > > to recognize HTML escapes. > > Note the ";?", which makes the closing ";" optional. > > This seems fine until we hit something valid but unusual like > > http://www.example.com?foo=1?? > > for which "htmldecode" tries to convert "1234567" into > a Unicode character with that decimal number, and gets a > Unicode overflow. > > For our own purposes, I rewrote "htmldecode" to require a > sequence ending in ";", which means some bogus HTML escapes won't > be recognized, but correct HTML will be processed correctly. > What's general opinion of this behavior? Too strict, or OK? > > John Nagle > SiteTruth Maybe htmltidy could help: http://tidy.sourceforge.net/ ? From paddy3118 at googlemail.com Mon Jan 28 02:24:22 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 27 Jan 2008 23:24:22 -0800 (PST) Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> <790eec65-c7dc-4a5e-bc1b-f9138d18eae0@1g2000hsl.googlegroups.com> Message-ID: <2577f982-523e-4ced-8e04-295a638d3b19@e10g2000prf.googlegroups.com> On Jan 28, 4:44 am, "Russ P." wrote: > On Jan 27, 5:41 pm, Roy Smith wrote: > > > > > In article > > , > > > ajaksu wrote: > > > On Jan 27, 10:32 pm, Paddy wrote: > > > > I would value the opinion of fellow Pythoneers who have also > > > > contributed to Wikipedia, on the issue of "Is Python Standardized". > > > > Specifically in the context of this table: > > > > http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Gene... > > > > (Comparison of programming languages) > > > > And this entry in the talk page > > > > http://en.wikipedia.org/wiki/Talk:Comparison_of_programming_languages... > > > > (Talk:Comparison of programming languages#Standardized Python?) > > > > > - Thanks. > > > > Hmmm. Seems to me that "Is X Standardized" in the given context means > > > having a formal, published standard issued by some Standards > > > organization. > > > That's exactly what it means. For example, if I'm buying a C++ compiler, I > > can specify in the contract, "Must comply with ISO 14882", and everybody > > will know what I'm talking about. > > > On the other side of the fence, if I'm a free-lance C++ developer, I can > > specify to my customers that the code I write will work properly when > > compiled with a compiler that meets ISO 14882. Whether such a compiler > > actually exists, is besides the point :-) > > > Python has no such standard. Sure, there's the stuff on docs.python.org, > > but it's kind of hard to write a contract which says, "Must comply with the > > stuff on docs.python.org", and have it be meaningful in a legal sense. > > > So, I think the "No" in the "Standardized?" column for python is exactly > > right. That's not to say you can't have something good which isn't > > standardized. Sometimes standards committees even go off into left field > > and field break stuff in the process of standardizing it. Some things have > > so many different standards (i.e. the pletora of unix standards), it's > > almost worthless to say it's standardized. But, as it stands, the > > Wikipedia article is correct. > > I agree. As far as I know, Python is not formally > "standardized" by any recognized standards > authority such as ANSI or ISO. (If it were, it > wouldn't have a "BDFL.") > > For most domains in which Python is used, that is > not an issue, but for some potential uses it could > be (e.g., safety-critical). > > FWIW, the "most" standardized language is probably > Ada. Not only does it have a formal written > standard, but I believe it also has a formal > suite of tests that a standard Ada compiler is > required to pass. [For some reason, Ada does not > get the respect or the attention it deserves, but > that's another topic.] Thanks Roy, Russ. I agree that Python is not standardized the way other languages are. But still, I look at the table, read the article linked as the column header, and can see that their is discrepancy. The column header links to the article on standardization: http://en.wikipedia.org/wiki/Standardization Which has a definition of standardization which is very different from what you may cite. I read the column headings article and just can't help feeling that Python conforms to *that* definition. - Paddy. From rong.xian at gmail.com Wed Jan 23 22:49:01 2008 From: rong.xian at gmail.com (glacier) Date: Wed, 23 Jan 2008 19:49:01 -0800 (PST) Subject: Some questions about decode/encode Message-ID: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> I use chinese charactors as an example here. >>>s1='???' >>>repr(s1) "'\\xc4\\xe3\\xba\\xc3\\xc2\\xf0'" >>>b1=s1.decode('GBK') My first question is : what strategy does 'decode' use to tell the way to seperate the words. I mean since s1 is an multi-bytes-char string, how did it determine to seperate the string every 2bytes or 1byte? My second question is: is there any one who has tested very long mbcs decode? I tried to decode a long(20+MB) xml yesterday, which turns out to be very strange and cause SAX fail to parse the decoded string. However, I use another text editor to convert the file to utf-8 and SAX will parse the content successfully. I'm not sure if some special byte array or too long text caused this problem. Or maybe thats a BUG of python 2.5? From remco at gerlich.nl Thu Jan 17 07:35:48 2008 From: remco at gerlich.nl (Remco Gerlich) Date: Thu, 17 Jan 2008 13:35:48 +0100 Subject: Loop in a loop? In-Reply-To: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <7ae3ca10801170435x8803cc0rad2c3453c503a0a0@mail.gmail.com> Use zip() to combine them into a single list, then loop over that: for x, y in zip(array1, array2): ... Remco On Jan 17, 2008 1:21 PM, Sacred Heart wrote: > Hi, > I'm new to Python and have come across a problem I don't know how to > solve, enter com.lang.python :) > > I'm writing some small apps to learn the language, and I like it a lot > so far. > > My problem I've stumbled upon is that I don't know how to do what I > want. I want to do a loop in a loop. I think. > > I've got two arrays with some random stuff in, like this. > > array1 = ['one','two','three','four'] > array2 = ['a','b','c','d'] > > I want to loop through array1 and add elements from array2 at the end, > so it looks like this: > > one a > two b > three c > four c > > I'm stuck. I know how to loop through the arrays separatly and print > them, but both at the same time? Hmmm. > > A push in the right direction, anyone? > > R, > SH > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Tue Jan 15 19:00:25 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 15 Jan 2008 16:00:25 -0800 (PST) Subject: Data mapper - need to map an dictionary of values to a model References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com> <2d59f289-2def-43a8-93b7-f326b8f12066@z17g2000hsg.googlegroups.com> Message-ID: On Jan 15, 6:53 pm, George Sakkis wrote: > name_tranformer = lambda input: dict( > zip(('first_name', 'last_name'), > input['name'])) Of course that should write: name_tranformer = lambda input: dict( zip(('first_name', 'last_name'), input['name'].split())) George From workitharder at gmail.com Tue Jan 1 12:45:00 2008 From: workitharder at gmail.com (bukzor) Date: Tue, 1 Jan 2008 09:45:00 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <6aba9463-f0ea-43a2-b8de-9c7026c4d14e@e4g2000hsg.googlegroups.com> <5c6a5515-a6ee-455d-83d4-48b2a2ae46c3@n20g2000hsh.googlegroups.com> <579f378d-d948-4c99-8507-a8c4e9a28096@i29g2000prf.googlegroups.com> Message-ID: <74a7edcf-f4ea-4835-b08e-499faaed8d81@i12g2000prf.googlegroups.com> On Jan 1, 9:00 am, bukzor wrote: > On Dec 31 2007, 1:30 pm, "Chris Mellon" wrote: > > > > > On Dec 31, 2007 2:08 PM, Odalrick wrote: > > > > On 31 Dec, 18:22, Arnaud Delobelle wrote: > > > > On Dec 31, 10:58 am, Odalrick wrote: > > > > > > On 30 Dec, 17:26, George Sakkis wrote: > > > > > > > On Dec 29, 9:14 pm, bukzor wrote: > > > > > > > > Here's the answer to the question:http://www.python.org/doc/faq/general/#why-are-default-values-shared-... > > > > > > > > It looks like Guido disagrees with me, so the discussion is closed. > > > > > > > Note that the FAQ mainly explains *what* happens, not *why* was this > > > > > > decision taken. Although it shows an example where "this feature can > > > > > > be useful", it's neither the only way to do it nor is memoization as > > > > > > common as wanting fresh default arguments on every call. > > > > > > I'm surprised noone has said anything about the why of default > > > > > mutables. I think it is becasue it isn't easy to do it an other way. > > > > > [...] > > > > > There is an easy enough way: evaluate default values when the function > > > > is called rather than when it is defined. This behaviour comes with > > > > its own caveats as well I imagine, and it's not 'as easy' to implement > > > > as the current one. > > > > Adding overhead to *all* function calls, even the ones without mutable > > > defaults. That doesn't sound like an attractive tradeoff. > > > And also removing the only way you can currently do early binding in > > Python. I agree that it's a gotcha, but unless someone comes up with > > an answer to the following questions, I'll stick with the status quo > > (Note that this is not blind Python group-think as a previous poster > > implied, but a pragmatic decision that this is the most practical > > solution): > > > a) If we don't evaluate default arguments at function compilation, > > when do we do it? > > b) If you do it at call time, how do you implement early binding? > > c) If you want to introduce new syntax for the current behavior, what > > is it and can you justify it? > > d) What are the performance implications of your proposal versus the > > current behavior? > > > Note that the desired behavior can be implemented under the current > > behavior, at the expense of verbosity - using factories and sentinel > > values as the default arguments, and then expanding them in the > > function. It's not possible to implement the current behavior of > > early-bound arguments if default arguments are evaluated with every > > call. This alone is a good reason to keep the current behavior until > > someone actually has a good alternative that covers the current use > > cases and isn't just upset by the behavior. > > I'm confused by what you mean by 'early binding'. Can you give a quick- > n-dirty example? > > Thanks, > --Buck Is an 'early bound' variable synonymous with a 'static' variable (in C)? From arnodel at googlemail.com Thu Jan 24 02:25:30 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 23:25:30 -0800 (PST) Subject: Smart factory class References: Message-ID: On Jan 24, 7:11?am, kramer31 wrote: > Can anyone tell me if there is a way in python that I can implement a > factory function which takes as input a string ClassName and returns > an object of type ClassName? >>> def mkobj(classname, ns=globals()): return ns[classname]() ... >>> class A: pass ... >>> mkobj('A') <__main__.A instance at 0x6bd28> >>> But why do you want to do this? -- Arnaud From paddy3118 at googlemail.com Fri Jan 11 22:26:26 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 11 Jan 2008 19:26:26 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: On Jan 11, 8:55 pm, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of cesco > > Sent: Wednesday, January 09, 2008 5:34 AM > > To: python-l... at python.org > > Subject: alternating string replace > > > Hi, > > > say I have a string like the following: > > s1 = 'hi_cat_bye_dog' > > and I want to replace the even '_' with ':' and the odd '_' with ',' > > so that I get a new string like the following: > > s2 = 'hi:cat,bye:dog' > > Is there a common recipe to accomplish that? I can't come up with any > > solution... > > For those of us who still think in Perl, here's an easy to read, lazy > solution: > > s = 'hi_cat_bye_dog' > print s > s = re.sub(r'_(.*?(_|$))', r':\1', s) ## every odd '_' to ':' > print s > s = re.sub(r'_', r',', s) ## every even '_' to ',' > print s > > > hi_cat_bye_dog > > hi:cat_bye:dog > > hi:cat,bye:dog > > The equivalent Perl code: > my $s = 'hi_cat_bye_dog'; > > print $s, "\n"; > $s =~ s/_(.*?(_|$))/:$1/g; > print $s, "\n"; > $s =~ s/_/,/g; > print $s, "\n"; def altrep8(s): import re s = re.sub(r'_(.*?(_|$))', r':\1', s) ## every odd '_' to ':' return re.sub(r'_', r',', s) ## every even '_' to ',' altrep8.author="Reedick, Andrew" Gives: ## Program by: Reedick, Andrew '' RETURNS '' '1' RETURNS '1' '2_' RETURNS '2:' '3_4' RETURNS '3:4' '5_6_' RETURNS '5:6,' '7_8_9' RETURNS '7:8,9' '10_11_12_' RETURNS '10:11,12:' '13_14_15_16' RETURNS '13:14,15:16' '17_18_19_20_' RETURNS '17:18,19:20,' '_' RETURNS ':' '_21' RETURNS ':21' '_22_' RETURNS ':22,' '_23_24' RETURNS ':23,24' '_25_26_' RETURNS ':25,26:' '_27_28_29' RETURNS ':27,28:29' '_30_31_32_' RETURNS ':30,31:32,' '_33_34_35_36' RETURNS ':33,34:35,36' '__' RETURNS ':,' '___' RETURNS ':,:' '____' RETURNS ':,:,' '_____' RETURNS ':,:,:' From kvutza at gmail.com Sun Jan 27 09:23:50 2008 From: kvutza at gmail.com (Martin Saturka) Date: Sun, 27 Jan 2008 06:23:50 -0800 (PST) Subject: Python System information References: Message-ID: <35d49700-9def-478e-8047-de548553e8c0@s8g2000prg.googlegroups.com> > How can i get system information like CPU load and RAM usage in linux. What about 'pystatgrab'? It provides good info, with a limitation - it does not have CPU info for particular CPUs, it takes just the cumulative CPU info. http://www.i-scream.org/pystatgrab/ http://packages.debian.org/statgrab M. From steve at holdenweb.com Thu Jan 31 19:15:00 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 19:15:00 -0500 Subject: Design question - Sharing of single object by multiple processes In-Reply-To: <2b54d4370801311423y52904ed9o1e26ac98dced45c6@mail.gmail.com> References: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> <47A1AC61.7080007@holdenweb.com> <2b54d4370801311206j457ef51cm33d2a2420b11e688@mail.gmail.com> <2b54d4370801311208s4af458cdp8cea665a04c3bd7a@mail.gmail.com> <2b54d4370801311423y52904ed9o1e26ac98dced45c6@mail.gmail.com> Message-ID: Mike D wrote: > Steve, > > You raise some very good (and obvious) issues I did'nt consider. I'll > look further into this sort of implementation as I'm quite interested. > > I suppose a compromise could be to load the objects from a pickle, that > may have issues in terms of updating the pickle perhaps, though it would > be much safer. > > I'll continue to investigate, thanks for your input. > No problem - I've had a long time to think about these things. You might also want to investigate the ConfigParser module, or Michael Foord's ConfigObj. In practice it would have to be a pretty complex configuration to make it worth pre-compiling it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stefan.behnel-n05pAM at web.de Thu Jan 24 16:35:57 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 24 Jan 2008 22:35:57 +0100 Subject: Sorting Large File (Code/Performance) In-Reply-To: References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> Message-ID: <479904BD.9090400@web.de> Ira.Kovac at gmail.com wrote: >> What are you going to do with it after it's sorted? > I need to isolate all lines that start with two characters (zz to be > particular) "Isolate" as in "extract"? Remove the rest? Then why don't you extract the lines first, without sorting the file? (or sort it afterwards if you still need to). That would heavily cut down your memory footprint. Stefan From paddy3118 at googlemail.com Wed Jan 9 17:03:23 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 14:03:23 -0800 (PST) Subject: alternating string replace: Extended input (Long). References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: On Jan 9, 9:39 pm, Fredrik Lundh wrote: > Paddy wrote: > > To see how they act against 'corner cases' and > > an exercise for me in trying to create corner cases. (I'm in to > > functional testing at the mo'). > > sounds more like "pulling requirements out of thin air". not sure that > helps the OP get a better understanding of Python, really. > > Not really out of thin air. The OP transforming alternating occurrences of _ so corners would include a null string; strings with 1, 2 and 3 occurrences of the character to be replaced and the char to be replaced separated or not by other chars.... Ideally I would create a randomized interesting string generator and try each prog against a lot of generated examples and computed 'correct' answers, but I am unsure of what should be the right answer in some cases so the earlier posting can be used to give extra information for the spec. to be fleshed out with. You may be right in that the OP might see the extended input and dismiss them because he knows that the input data is never going to be like that - or - he may find that his input validation might well allow some of the cases through and he needs to either improve his input validation or define what to do with more types of input. Your also right in that its mostly not Python specific but it helps me think of corner cases and the interpretation of specs which is very important in helping solve the right problem. - Paddy. From grante at visi.com Fri Jan 4 16:08:00 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 04 Jan 2008 21:08:00 -0000 Subject: Question on os.tempnam() vulnerability References: Message-ID: <13nt81gftkfa32d@corp.supernews.com> On 2008-01-04, Fredrik Lundh wrote: > you get a name instead of a file, so someone else can create that file > after you've called tempnam/tmpnam, but before you've actually gotten > around to create the file yourself. which means that anyone on the > machine might be able to mess with your application's data. > > use the functions marked as "safe" in the tempfile module instead. Under Windows, is there a "safe" way to create a temp file that has a name that can be passed to a program which will then open it? I never figured out a way to do that and had to fall back on the "unsafe" tmpnam method. -- Grant Edwards grante Yow! I have seen these EGG at EXTENDERS in my Supermarket visi.com ... I have read the INSTRUCTIONS ... From martin at v.loewis.de Mon Jan 7 18:02:56 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 Jan 2008 00:02:56 +0100 Subject: What is the encoding of __file__? In-Reply-To: References: <736ae822-54a9-4ee6-91fe-92c2c6eb43db@21g2000hsj.googlegroups.com> <4782A255.8070604@v.loewis.de> Message-ID: <4782afa0$0$8649$9b622d9e@news.freenet.de> > Thanks, I'll then use sys.getfilesystemencoding() to decode _file__ > and re-encode into utf-8, which is the default encoding of all strings > in our software, as we deal a bit with Chinese terms. > > Windows-1252 on my box. I just created a directory containing Chinese > characters (on Vista), and whoa, files opened with IDLE are empty, > import doesn't find modules in that directory. Of course Windows-1252 > can't encode these ... > > But I understand that Python 3 will clean this up? In theory, yes. The current implementation doesn't. Contributions are welcome. Regards, Martin From ptmcg at austin.rr.com Tue Jan 29 07:38:28 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 29 Jan 2008 04:38:28 -0800 (PST) Subject: Error in parsing XML for following test data References: <479F03ED.6080308@web.de> Message-ID: <88a2fad8-d125-4946-a57e-d055c0649973@l1g2000hsa.googlegroups.com> On Jan 29, 4:46?am, Stefan Behnel wrote: > > How is this related to XML? > > Stefan I guess that's what makes so **nasty**! -- Paul From larry.bates at websafe.com Wed Jan 23 12:15:41 2008 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 23 Jan 2008 11:15:41 -0600 Subject: csv to xls using python 2.1.3 In-Reply-To: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> Message-ID: <4797763D.70604@websafe.com> LizzyLiz wrote: > Hi > > I need to convert a .csv file to .xls file using python 2.1.3 which > means I can't use pyExcelerator! Does anyone know how I can do this? > > Many thanks > LizzyLiz FYI - Excel can read .CSV files directly and convert them to .XLS. -Larry From mcfletch at vrplumber.com Sun Jan 20 10:48:12 2008 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Sun, 20 Jan 2008 10:48:12 -0500 Subject: TopSort in Python? In-Reply-To: <1deb5d71-a514-44d8-ae9e-dc320155628a@d21g2000prf.googlegroups.com> References: <0000161d@bossar.com.pl> <358cc5a3-300f-49ba-9857-2f0cd629a4df@i12g2000prf.googlegroups.com> <12f0f54e-5d30-40bc-9135-2c59b8a5acc2@i3g2000hsf.googlegroups.com> <1deb5d71-a514-44d8-ae9e-dc320155628a@d21g2000prf.googlegroups.com> Message-ID: <47936D3C.8090509@vrplumber.com> Paddy wrote: ... > I searched for dependancy sort, and later dependency sort (cos I > couldn't spell). I had convinced that I was using the right term and > was flummoxed by the lack of hits. Even today the term topological > sort means far less than what it describes: sorting items based on > their interdependencies. > "dependency sort python" typed into Google today gives a post pointing to http://www.vrplumber.com/programming/ (which has Tim and my algorithms (toposort.py)) as the second link... vagaries of Google I suppose. > Is this a case of something being named after its mathematical/ > technical description and so obscuring its wider practical use cases? > Could be, I tried to make sure that the word dependency was in the description on the download page (since I had the same problem starting out (I implemented the algorithm before I knew the name IIRC)). > P.S. we have revived a thread started in 1999! > For some of us 1999 is well into our Pythonic life-cycle :) Have fun, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From bladedpenguin at gmail.com Mon Jan 28 19:18:28 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Mon, 28 Jan 2008 16:18:28 -0800 (PST) Subject: Executing other python code Message-ID: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> I'm working on a game, and I'd like players to be able to define thier ships with scripts. Naturally, I don't want to give them the entire program as thier romping ground. I would like to invoke a seperate interpreter for these files, and give it a limited subset of the functions in my game. What is the best way to achieve this effect? From terry at jon.es Mon Jan 21 04:12:54 2008 From: terry at jon.es (Terry Jones) Date: Mon, 21 Jan 2008 10:12:54 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 23:21:04 on Sunday, 20 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> Message-ID: <18324.25110.878721.763191@terry.local> >>>>> "Arnaud" == Arnaud Delobelle writes: Arnaud> In countdown you are not required to use all numbers to reach the Arnaud> target. This means you are missing solutions, e.g. (1, 3, 6, Arnaud> 'mul', 'add', 7 , 'add', 9, 'mul') Hi Arnaud. Thanks, I didn't know that. The fix is a simple change to the first if my function below. WRT to the missing solution, note that my code only allowed multiplication by 1 if it was the last thing done. That was because you can multiply by 1 at any time, and I didn't want to see those trivially equivalent solutions (same goes for adding 0). Seeing as you're allowed to omit numbers, I've now gotten rid of those trivial operations altogether in my solution. Code and output below. Terry from operator import * def countdown(target, nums, numsAvail, value, partialSolution, solutions, ops=(add, mul, sub, div)): if value == target or not any(numsAvail): # Ran out of available numbers. Add the solution, if we're right. if value == target: solutions.add(tuple(partialSolution)) elif value is None: # Use each distinct number as a starting value. used = set() for i, num in enumerate(nums): if num not in used: numsAvail[i] = False used.add(num) partialSolution.append(num) countdown(target, nums, numsAvail, num, partialSolution, solutions, ops) numsAvail[i] = True partialSolution.pop() else: for op in ops: for i, num in enumerate(nums): if numsAvail[i]: numsAvail[i] = False moreAvail = any(numsAvail) try: lastNum, lastOp = partialSolution[-2:] except ValueError: lastNum, lastOp = partialSolution[-1], None # Don't allow any of: if not any(( # Div: after mul, by 1, by 0, producing a fraction. (op == div and (lastOp == 'mul' or num <= 1 or value % num != 0)), # If initial mul/add, canonicalize to 2nd operator biggest. ((op == mul or op == add) and lastOp is None and num > lastNum), # Don't allow add or sub of 0. ((op == add or op == sub) and num == 0), # Don't allow mult by 1. (op == mul and num == 1), # Don't allow sub after add (allow add after sub). (op == sub and lastOp == 'add'), # If same op twice in a row, canonicalize operand order. (lastOp == op.__name__ and num > lastNum) )): partialSolution.extend([num, op.__name__]) countdown(target, nums, numsAvail, op(value, num), partialSolution, solutions, ops) del partialSolution[-2:] numsAvail[i] = True for nums, target in (((100, 9, 7, 6, 3, 1), 253), ((100, 9, 7, 6, 3, 1), 234), ((2, 3, 5), 21), ((7, 8, 50, 8, 1, 3), 923), ((8, 8), 16), ((8, 8, 8), 8), ((8, 0), 8), ((7,), 8), ((), 8), ((8, 8, 8, 8), 32)): solutions = set() countdown(target, nums, [True,] * len(nums), value=None, partialSolution=[], solutions=solutions) print "%d solutions to: target %d, numbers = %s" % (len(solutions), target, nums) for s in sorted(solutions, cmp=lambda a, b: cmp(len(a), len(b)) or cmp(a, b)): print '\t', s $ time countdown.py 8 solutions to: target 253, numbers = (100, 9, 7, 6, 3, 1) (6, 3, 'mul', 1, 'sub', 9, 'mul', 100, 'add') (7, 6, 'mul', 9, 'add', 3, 'mul', 100, 'add') (9, 3, 'sub', 7, 'mul', 6, 'mul', 1, 'add') (100, 9, 'sub', 7, 'sub', 3, 'mul', 1, 'add') (3, 1, 'add', 6, 'mul', 7, 'sub', 9, 'mul', 100, 'add') (7, 1, 'add', 6, 'mul', 3, 'mul', 100, 'add', 9, 'add') (7, 6, 'add', 3, 'add', 1, 'add', 9, 'mul', 100, 'add') (100, 7, 'sub', 6, 'sub', 3, 'mul', 9, 'sub', 1, 'add') 19 solutions to: target 234, numbers = (100, 9, 7, 6, 3, 1) (6, 3, 'mul', 7, 'add', 1, 'add', 9, 'mul') (7, 1, 'add', 9, 'mul', 6, 'add', 3, 'mul') (7, 3, 'mul', 1, 'sub', 6, 'add', 9, 'mul') (7, 6, 'mul', 3, 'mul', 100, 'sub', 9, 'mul') (100, 1, 'sub', 3, 'div', 7, 'sub', 9, 'mul') (100, 1, 'sub', 7, 'mul', 9, 'add', 3, 'div') (100, 7, 'mul', 3, 'mul', 6, 'add', 9, 'div') (100, 9, 'sub', 7, 'div', 6, 'mul', 3, 'mul') (100, 9, 'sub', 7, 'sub', 6, 'sub', 3, 'mul') (6, 1, 'add', 100, 'mul', 7, 'sub', 9, 'add', 3, 'div') (6, 9, 'sub', 7, 'mul', 1, 'sub', 100, 'add', 3, 'mul') (7, 3, 'mul', 6, 'sub', 9, 'mul', 1, 'sub', 100, 'add') (7, 6, 'mul', 3, 'mul', 1, 'sub', 100, 'add', 9, 'add') (100, 1, 'sub', 3, 'div', 7, 'mul', 6, 'sub', 9, 'add') (100, 1, 'sub', 7, 'mul', 9, 'sub', 3, 'div', 6, 'add') (100, 7, 'mul', 6, 'sub', 1, 'sub', 9, 'add', 3, 'div') (100, 7, 'sub', 3, 'div', 1, 'sub', 9, 'add', 6, 'mul') (100, 7, 'sub', 3, 'div', 6, 'sub', 1, 'add', 9, 'mul') (100, 9, 'add', 7, 'add', 1, 'add', 3, 'div', 6, 'mul') 1 solutions to: target 21, numbers = (2, 3, 5) (5, 2, 'add', 3, 'mul') 1 solutions to: target 923, numbers = (7, 8, 50, 8, 1, 3) (50, 8, 'mul', 1, 'sub', 3, 'div', 7, 'mul', 8, 'sub') 1 solutions to: target 16, numbers = (8, 8) (8, 8, 'add') 1 solutions to: target 8, numbers = (8, 8, 8) (8,) 1 solutions to: target 8, numbers = (8, 0) (8,) 0 solutions to: target 8, numbers = (7,) 0 solutions to: target 8, numbers = () 1 solutions to: target 32, numbers = (8, 8, 8, 8) (8, 8, 'add', 8, 'add', 8, 'add') real 0m1.423s user 0m1.371s sys 0m0.047s From george.sakkis at gmail.com Mon Jan 14 18:09:08 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 14 Jan 2008 15:09:08 -0800 (PST) Subject: SyntaxError: 'import *' not allowed with 'from .' References: <9ac37212-7521-454d-a35f-afd6f7ec24f6@m34g2000hsf.googlegroups.com> <87ve5wdnbg.fsf@benfinney.id.au> Message-ID: <8d86398a-a16e-4e73-9d22-7a58bc234f91@s8g2000prg.googlegroups.com> On Jan 14, 6:01 pm, Ben Finney wrote: > George Sakkis writes: > > Unless I missed it, PEP 328 doesn't mention anything about this. > > What's the reason for not allowing "from .relative.module import *' > > ? > > It makes the code much harder to follow visually and inspect with > static analysis tools, since there's no way to see where names come > from in the code. It defeats the purpose of separate namespaces, > confusing the imported module's names with the current module's names > in a way that makes the indistinguishable. > > If you want to use all or most of the names in a module, keep them in > their own namespace: > > import spam > import eggs > > spam.do_stuff() > eggs.do_stuff() > > If you don't like the name of the module, then use whatever one suits > you: > > import your_mother_was_a_hamster as spam > import your_father_smelled_of_elderberries as eggs > > spam.do_stuff() > eggs.do_stuff() > > Both of these are superior to 'from spam import *' because it's clear > (to the reader and to static analysis tools) where every name comes > from: unqualified names must be defined in the current module, any > ones from the imported module are qualified with the module name. > > You also, in cases like the above example, avoid unknowingly > clobbering existing names by importing from another module into the > current namespace. All the above are well-known and apply to both absolute and relative imports. I was asking why it's a syntax error specifically for relative imports. George From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 19:15:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 00:15:44 -0000 Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> Message-ID: <13og1lgcespv6c2@corp.supernews.com> On Fri, 11 Jan 2008 08:29:18 -0800, dg.google.groups wrote: > Hi all, > > I'm part of a small team writing a Python package for a scientific > computing project. The idea is to make it easy to use for relatively > inexperienced programmers. ... > This is fine, but we decided that for clarity of these programs, and to > make it easier for inexperienced programmers, we would like to be able > to write something like: > > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > run() > > The idea is that the run() function inspects the stack, and looks for > object which are instances of class Obj, creates a Bigobj with those > objects and calls its run() method. > > So, any comments on that approach? Your users are *scientists*, and you don't trust their intellectual ability to learn a programming language as simple as Python? Instead of spending time and effort writing, debugging and maintaining such a fragile approach, why not invest in a couple of introductory books on Python programming and require your scientists to go through the first few chapters? Or write out a one-page "cheat sheet" showing them simple examples. Or, and probably most effectively, make sure all your classes have doc strings with lots of examples, and teach them how to use help(). Some people problems are best dealt with by a technical solution, and some are not. -- Steven From deets at nospam.web.de Tue Jan 29 17:45:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jan 2008 23:45:07 +0100 Subject: breaking out of outer loops In-Reply-To: References: Message-ID: <609ojrF1phb32U1@mid.uni-berlin.de> noemailplease0001 at gmail.com schrieb: > Any elegant way of breaking out of the outer for loop than below, I > seem to have come across something, but it escapes me > > for i in outerLoop: > for j in innerLoop: > if condition: > break > else: > continue > break It's working because for-loops else statements are are executed only if the loop hasn't been terminated unexpectedly. Which is what happens here: if the inner loop is breaked, it's else is not executed. So the outer loop's break is called. Diez From jgardner at jonathangardner.net Thu Jan 24 16:41:04 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 24 Jan 2008 13:41:04 -0800 (PST) Subject: a newbie regex question References: Message-ID: <4227b8d4-c2c7-4395-97a3-5aadcec94b7d@p69g2000hsa.googlegroups.com> On Jan 24, 12:14 pm, Shoryuken wrote: > Given a regular expression pattern, for example, \([A-Z].+[a-z]\), > > print out all strings that match the pattern in a file > > Anyone tell me a way to do it? I know it's easy, but i'm completely > new to python > > thanks alot You may want to read the pages on regular expressions in the online documentation: http://www.python.org/doc/2.5/lib/module-re.html The simple approach works: import re # Open the file f = file('/your/filename.txt') # Read the file into a single string. contents = f.read() # Find all matches in the string of the regular expression and iterate through them. for match in re.finditer(r'\([A-Z].+[a-z]\)', contents): # Print what was matched print match.group() From odysseus1479-at at yahoo-dot.ca Sat Jan 12 23:15:06 2008 From: odysseus1479-at at yahoo-dot.ca (Odysseus) Date: Sun, 13 Jan 2008 04:15:06 GMT Subject: Elementary string-formatting Message-ID: Hello, group: I've just begun some introductory tutorials in Python. Taking off from the "word play" exercise at I've written a mini-program to tabulate the number of characters in each word in a file. Once the data have been collected in a list, the output is produced by a while loop that steps through it by incrementing an index "i", saying print '%2u %6u %4.2f' % \ (i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0]) My problem is with the last entry in each line, which isn't getting padded: 1 0 0.00 2 85 0.07 3 908 0.80 4 3686 3.24 5 8258 7.26 6 14374 12.63 7 21727 19.09 8 26447 23.24 9 16658 14.64 10 9199 8.08 11 5296 4.65 12 3166 2.78 13 1960 1.72 14 1023 0.90 15 557 0.49 16 261 0.23 17 132 0.12 18 48 0.04 19 16 0.01 20 5 0.00 21 3 0.00 I've tried varying the number before the decimal in the formatting string; "F", "g", and "G" conversions instead of "f"; and a couple of other permutations (including replacing the arithmetical expression in the tuple with a variable, defined on the previous line), but I can't seem to get the decimal points to line up. I'm sure I'm missing something obvious, but I'd appreciate a tip -- thanks in advance! FWIW I'm running Python 2.3.5 (#1, Oct 5 2005, 11:07:27) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin from the Terminal on Mac OS X v10.4.11. P.S. Is there a preferable technique for forcing floating-point division of two integers to that used above, multiplying by "100.0" first? What about if I just wanted a ratio: is "float(n / m)" better than "1.0 * n / m"? -- Odysseus From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 21:52:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 02:52:33 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: <13ogarhbepg9l29@corp.supernews.com> On Fri, 11 Jan 2008 09:55:08 -0800, sturlamolden wrote: > It seems the code he is referring to is doing k-means clustering on each > frame. The clustering is done by from SciPy's cluster module, which is > doing 'vector quantitization'. The algorithm is written in plain C. It > is not Python that is slow. It is the amount of processing done on each > frame. As the bottleneck is already in C, it cannot be done any faster > without radically changing the algorithm and/or the hardware. Thank you for taking the effort to actually investigate the OP's *actual* problem. Such a pity that the chances are he's probably gone away in disgust at the pedantry and insults in this thread. He'll probably become another one of those people convinced that Python is "slow" because it's interpreted when in fact this is an example of C being slow in spite of being compiled. -- Steven From tommy.nordgren at comhem.se Wed Jan 9 00:33:16 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Wed, 9 Jan 2008 06:33:16 +0100 Subject: Default location of python on OS X In-Reply-To: <1519661f-97bd-4fdd-b2d5-a46dd9a81c81@e25g2000prg.googlegroups.com> References: <1519661f-97bd-4fdd-b2d5-a46dd9a81c81@e25g2000prg.googlegroups.com> Message-ID: <830C7771-6EB1-48FC-9A96-D34266C15E4C@comhem.se> On 9 jan 2008, at 04.43, Stephen_B wrote: > I've installed the latest 2.5 python today from python.org, and I > think it ended up in "/Applications/MacPython 2.5". > > I also have a "/Applications/MacPython 2.4" and a "/Applications/ > MacPython-2.4". Can I delete these, or did one of them come with > Leopard? > > I still have a "/Library/Python/2.3" and a "/Library/Python/2.5". > > Thanks. > > Stephen > -- > http://mail.python.org/mailman/listinfo/python-list Leopard INCLUDES Python 2.5, there is no need to install it. ------------------------------------- This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren tommy.nordgren at comhem.se From siona at chiark.greenend.org.uk Wed Jan 30 08:03:08 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Jan 2008 13:03:08 +0000 (GMT) Subject: refcount References: Message-ID: Benjamin wrote: >> [ help(sys.getrefcount) says: ] >> [ ... ] The count returned is generally >> one higher than you might expect, because it includes the (temporary) >> reference as an argument to getrefcount(). >Are there any cases when it wouldn't? When the temporary reference which is the argument to getrefcount is the *only* reference, eg: >>> sys.getrefcount (set()) 1 The return value for a weakly referenced object may also be not what you "expect": >>> s = set() >>> sys.getrefcount(s) 2 >>> r = weakref.ref(s) >>> r() is s True >>> sys.getrefcount(r()) 2 -- \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 rong.xian at gmail.com Sun Jan 27 05:18:48 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 02:18:48 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <5vr1ekF1njt09U2@mid.uni-berlin.de> Message-ID: <84f39f37-4d18-47c1-9349-bf3f471b2bf5@s19g2000prg.googlegroups.com> On 1?24?, ??4?44?, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote: > > My second question is: is there any one who has tested very long mbcs > > decode? I tried to decode a long(20+MB) xml yesterday, which turns out > > to be very strange and cause SAX fail to parse the decoded string. > > That's because SAX wants bytes, not a decoded string. Don't decode it > yourself. > > > However, I use another text editor to convert the file to utf-8 and > > SAX will parse the content successfully. > > Because now you feed SAX with bytes instead of a unicode string. > > Ciao, > Marc 'BlackJack' Rintsch Yepp. I feed SAX with the unicode string since SAX didn't support my encoding system(GBK). Is there any way to solve this better? I mean if I shouldn't convert the GBK string to unicode string, what should I do to make SAX work? Thanks , Marc. :) From Scott.Daniels at Acm.Org Tue Jan 1 18:16:40 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 01 Jan 2008 15:16:40 -0800 Subject: confusion about package/module imports In-Reply-To: References: <13nlc7fecs63099@corp.supernews.com> Message-ID: <13nli6lenc9vdc1@corp.supernews.com> Jugdish wrote: > Thanks very much for your helpful response! > >> You'll see that b is executed (making module __main__), >> (1) it imports pkg.subpkg.a, >> (2) which is accomplished by importing pkg (successfully), >> (3) then by importing pkg.subpkg >> (4) which imports pkg.subpkg.a (successfully) >> (5) and then imports pkg.subpkg.b >> (6) which then attempts to import pkg.subpkg.a > > What I'm not really understanding here is why this fails at lines (5) > and (6). If pkg.subpkg.a has already been successfully imported at > line (4), then (6) should be detected as a duplicate import and just > be skipped, right? So the import at line (5) should succeed. I'm sorry, I used shorthand. While a module is being imported, it only provisionally has a name. Until subpkg is fully imported, there is no module named pkg.subpkg. At the root level (pkg, for example), the module is provisionally added. Further down the tree, the module (such as that for pkg/subpkg/__init__.py) is only added to the symbol table (the packages __dict__) when the module has been completely imported. -Scott From Rens.Duijsens at gmail.com Mon Jan 28 04:12:12 2008 From: Rens.Duijsens at gmail.com (Dox33) Date: Mon, 28 Jan 2008 01:12:12 -0800 (PST) Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> <87dd811e-3095-41d0-80fd-7312338e5254@i3g2000hsf.googlegroups.com> <489b6fc5-e871-425e-b242-45be618fc9f4@n20g2000hsh.googlegroups.com> <87r6g4q7hq.fsf@mulj.homelinux.net> Message-ID: <37633f9e-64c1-406f-9e30-d9b56f2a61cc@u10g2000prn.googlegroups.com> YES! This is what I was looking for. Great! All works fine now. Thank you very much Gabriel. Gabriel Genellina schreef: > Add this on your sitecustomize.py module (or create one) > > import sys > def raw_input(prompt=None): > if prompt: sys.stdout.write(prompt) > return original_raw_input() > > import __builtin__ > original_raw_input = __builtin__.raw_input > __builtin__.raw_input = raw_input > > It just replaces the builtin raw_input with a custom function. From alisonken1 at gmail.com Wed Jan 9 00:29:06 2008 From: alisonken1 at gmail.com (alisonken1) Date: Tue, 8 Jan 2008 21:29:06 -0800 (PST) Subject: pipes python cgi and gnupg References: <8aa1d294-cbef-45b2-9e0f-dcc44323e520@v4g2000hsf.googlegroups.com> Message-ID: <38031e39-f1a6-482c-a196-d2f9e6fef22c@u10g2000prn.googlegroups.com> On Dec 28 2007, 7:07 pm, byte8b... at gmail.com wrote: > form = cgi.FieldStorage() > if not form.has_key("pass"): > print "Enter password" > > filename = "test.gpg" > pass = form.getvalue("pass").strip() > os.system("gpg --version > gpg.out") > os.system("echo %s | gpg --batch --password-fd 0 --decrypt %s > d.out" > %(pass,filename)) The last time I checked, "pass" is a reserved word in Python. Since you are using a reserved word as a variable, maybe that's what's messing with your output? From wuwei23 at gmail.com Wed Jan 30 19:55:07 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 30 Jan 2008 16:55:07 -0800 (PST) Subject: Events in Python References: Message-ID: <8157c4a1-3c6b-49b0-9cad-b633a7bb891e@e6g2000prf.googlegroups.com> Hey Si, The PEAK lib Trellis (http://peak.telecommunity.com/DevCenter/Trellis) is worth checking out. I haven't had a chance to use it yet but am keen to. There are several other modules that may apply, I recommend searching on the Python Package Index (http://pypi.python.org/pypi), for "observer" or "dispatcher". Hope this helps. -alex23 From ggpolo at gmail.com Wed Jan 16 11:23:43 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 16 Jan 2008 14:23:43 -0200 Subject: list classes in package In-Reply-To: <5v6mk4F1kbh4nU1@mid.uni-berlin.de> References: <5cff1706-3bb1-4a54-bccb-175ff384788c@q77g2000hsh.googlegroups.com> <5v6mk4F1kbh4nU1@mid.uni-berlin.de> Message-ID: 2008/1/16, Diez B. Roggisch : > Dmitry wrote: > > > Hi All, > > > > I've trying to develop one Python application, and > > neet to solve one problem. I need to list all classes defined in one > > package (not module!). > > > > Could anybody please show me more convinient (correct) way to > > implement this? > > Look at the module inspect and it's predicates. Something like > > > for name in dir(module_or_package): > if inspect.isclass(getattr(module_or_package, name)): > print "%s is a class" % name > > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > You should be able to adapt this one. You need to pass a directory to it (warning: directory names including dots will cause you errors): import os import sys import pyclbr def pkg_modules(package): return filter(lambda x: x.endswith(".py"), os.listdir(package)) def module_classes(module): dict = pyclbr.readmodule_ex(module, []) objs = dict.values() objs.sort(lambda a, b: cmp(getattr(a, 'lineno', 0), getattr(b, 'lineno', 0))) print module for obj in objs: if isinstance(obj, pyclbr.Class): print " class %s %s line: %d" % (obj.name, obj.super, obj.lineno) def pkg_classes(package): for module in pkg_modules(package): module_classes("%s.%s" % (package, module[:-3])) if __name__ == "__main__": pkg_classes(sys.argv[1]) -- -- Guilherme H. Polo Goncalves From lists at cheimes.de Fri Jan 18 03:31:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 18 Jan 2008 09:31:19 +0100 Subject: Unique thread ID In-Reply-To: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> References: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> Message-ID: Benjamin wrote: > Is there a way to obtain a unique ID for the current thread? I have an > object that I need to store local thread data in, and I don't want to > use threading.local because each thread might have multiple instances > of my object. threading.get_ident() but please use threading.local. Nobody is going to stop you if you use a list or dict in threading.local. Christian From p at ulmcnett.com Thu Jan 31 15:25:05 2008 From: p at ulmcnett.com (Paul McNett) Date: Thu, 31 Jan 2008 12:25:05 -0800 Subject: PIL linux err In-Reply-To: <15211773.post@talk.nabble.com> References: <15211773.post@talk.nabble.com> Message-ID: <47A22EA1.1020101@ulmcnett.com> dzizes wrote: > I'm trying to run simple .py on linux, which is using PIL. Below error > message which I receive: > > IOError: decoder jpeg not available > > Do you know what might be the problem? No, but google seems to: http://effbot.org/zone/pil-decoder-jpeg-not-available.htm Paul -- http://paulmcnett.com From seberino at spawar.navy.mil Wed Jan 23 09:03:05 2008 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: Wed, 23 Jan 2008 06:03:05 -0800 (PST) Subject: How avoid both a newline and a space between 2 print commands? Message-ID: print "foo" print "bar" has a newline in between "foo" and "bar" print "foo", print "bar" has a space in between "foo" and "bar" How prevent ANYTHING from going in between "foo" and "bar" ?? (Without defining a string variable.) Chris From martin at v.loewis.de Sat Jan 12 18:19:05 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jan 2008 00:19:05 +0100 Subject: different encodings for unicode() and u''.encode(), bug? In-Reply-To: <1c3f85a5-6bf3-4534-afb2-186f50a060cd@v29g2000hsf.googlegroups.com> References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> <76ba16c8-6ba0-4609-80bd-cd54aa08d74b@5g2000hsg.googlegroups.com> <590e6f12-16ad-4919-a87d-a2f2cc0b3516@t1g2000pra.googlegroups.com> <1c3f85a5-6bf3-4534-afb2-186f50a060cd@v29g2000hsf.googlegroups.com> Message-ID: <47894AE9.5020706@v.loewis.de> > What I'd like to understand better is the "compatibility heirarchy" of > known encodings, in the positive sense that if a string decodes > successfully with encoding A, then it is also possible that it will > encode with encodings B, C; and in the negative sense that is if a > string fails to decode with encoding A, then for sure it will also > fail to decode with encodings B, C. Any ideas if such an analysis of > the relationships between encodings exists? Most certainly. You'll have to learn a lot about many encodings though to really understand the relationships. Many encodings X are "ASCII supersets", in the sense that if you have only characters in the ASCII set, the encoding of the string in ASCII is the same as the encoding of the string in X. ISO-8859-X, ISO-2022-X, koi8-x, and UTF-8 fall in this category. Other encodings are "ASCII supersets" only in the sense that they include all characters of ASCII, but encode them differently. EBCDIC and UCS-2/4, UTF-16/32 fall in that category. Some encodings are 7-bit, so that they decode as ASCII (producing moji-bake if the input wasn't ASCII). ISO-2022-X is an example. Some encodings are 8-bit, so that they can decode arbitrary bytes (again producing moji-bake if the input wasn't that encoding). ISO-8859-X are examples, as are some of the EBCDIC encodings, and koi8-x. Also, things will successfully (but meaninglessly) decode as UTF-16 if the number of bytes in the input is even (likewise for UTF-32). HTH, Martin From agnel.joel at gmail.com Tue Jan 22 02:23:00 2008 From: agnel.joel at gmail.com (Joel) Date: Mon, 21 Jan 2008 23:23:00 -0800 (PST) Subject: Boa constructor debugging - exec some code at breakpoint? References: <7f96223d-e5bd-4bbc-a242-75826eeb100a@d70g2000hsb.googlegroups.com> Message-ID: Can you please tell me how this can be done.. are there any other IDEs for the same purpose if Boa can't do it? Joel On Jan 6, 11:01?am, Joel wrote: > Hey there.. > I'm using boa constructor to debug a python application. For my > application, I need to insert break points and execute some piece of > code interactively through shell or someother window when the > breakpoint has been reached. Unfortunately the shell I think is a > seperate process so whatever variables are set while executing in > debugger dont appear in the shell when I try to print using print > statement. > > Can anyone tell me how can I do this? > > Really appreciate any support, Thanks > > Joel > P.S. Please CC a copy of reply to my email ID if possible. From gagsl-py2 at yahoo.com.ar Thu Jan 31 19:25:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 31 Jan 2008 22:25:42 -0200 Subject: Removal of element from list while traversing causes the next element to be skipped References: <51302a8c0801300504i30c02ea3jfbf3228a62532720@mail.gmail.com> Message-ID: En Thu, 31 Jan 2008 15:45:42 -0200, escribi?: > Hmm, how does this fare?? > > for i in range(len(a)): > if a[i]==99: a=a[:i]+a[i+1:] > > > I like following your guys code noodling. I can come up with something > that does what it appears your doing, sometimes, but as to it's relevant > merits I havent a clue :) It's worse than the original `del a[i]`; not only skips over some elements, but you'll get an IndexError at the end -- Gabriel Genellina From kyosohma at gmail.com Fri Jan 18 10:55:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jan 2008 07:55:25 -0800 (PST) Subject: get the size of a dynamically changing file fast ? References: Message-ID: <198fd91f-912b-4f56-a840-af96225125a7@c23g2000hsa.googlegroups.com> On Jan 17, 3:56 pm, Stef Mientki wrote: > hello, > > I've a program (not written in Python) that generates a few thousands > bytes per second, > these files are dumped in 2 buffers (files), at in interval time of 50 msec, > the files can be read by another program, to do further processing. > > A program written in VB or delphi can handle the data in the 2 buffers > perfectly. > Sometimes Python is also able to process the data correctly, > but often it can't :-( > > I keep one of the files open en test the size of the open datafile each > 50 msec. > I have tried > os.stat ( ....) [ ST_SIZE] > os.path.getsize ( ... ) > but they both have the same behaviour, sometimes it works, and the data > is collected each 50 .. 100 msec, > sometimes 1 .. 1.5 seconds is needed to detect a change in filesize. > > I'm using python 2.4 on winXP. > > Is there a solution for this problem ? > > thanks, > Stef Mientki Tim Golden has a method to watch for changes in a directory on his website: http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html This old post also mentions something similar: http://mail.python.org/pipermail/python-list/2007-October/463065.html And here's a cookbook recipe that claims to do it as well using decorators: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/426620 Hopefully that will get you going. Mike From gherron at islandtraining.com Fri Jan 11 03:46:52 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 11 Jan 2008 00:46:52 -0800 Subject: python recursive function In-Reply-To: References: Message-ID: <47872CFC.9080303@islandtraining.com> Tom_chicollegeboy wrote: > here is what I have to do: > > This question involves a game with teddy bears. The game starts when I > give you some bears. You then start giving me back some bears, but you > must follow these rules (where n is the number of bears that you > have): > This sounds very much like a homework assignment, and so should probably not be answered here. (Neither should it have been asked here.) If, in your attempt to write this program, you have some questions about Python, then I encourage to ask those questions here. Gary Herron > If n is even, then you may give back exactly n/2 bears. (Hint: To test > whether n is even, use the expression ((n % 2) == 0).) > If n is divisible by 3 or 4, then you may multiply the last two digits > of n and give back this many bears. (By the way, the last digit of n > is n%10, and the next-to-last digit is (n%100)/10; this rule may not > be used if either of the last two digits is 0.) > > If n is divisible by 5, then you may give back exactly 42 bears. > The goal of the game for you is to end up with EXACTLY 42 bears. > > For example, suppose that you start with 250 bears. Then you could > make these moves: > > Start with 250 bears. > Since 250 is divisible by 5, you may return 42 of the bears, leaving > you with 208 bears. > Since 208 is even, you may return half of the bears, leaving you with > 104 bears. > Since 104 is even, you may return half of the bears, leaving you with > 52 bears. > Since 52 is divisible by 4, you may multiply the last two digits > (resulting in 10) and return these 10 bears. This leaves you with 42 > bears. > You have reached the goal! > Now, you are to write a program that, if I give you n bears, returns > true if it is at all possible for you to win the game. Your program > must use recursion to check all possible ways in which you can apply > the rules. > > > Usage: > > >>>> bears(42) >>>> > True > >>>> bears(250) >>>> > True > >>>> bears(50) >>>> > False > >>>> bears(84) >>>> > True > >>>> bears(41) >>>> > False > > > As you see my program must use recursion. > > I came up with this idea but I am not sure if its right or are there > any minor errors that I can easily fix: > > def bears (n): > if n==42: > return True > if n%5==0: > bears(n-42) > if n%2==0: > bears(n/2) > if n%3==0 or n%4==0: > one = (n%10) > two = ((n%100)/10) > if one!=0 and two!=0: > bears(n-(one*two)) > return False > > If a game hits 42 it should return True, otherwise False. If program > never hits 42 and return True, then it returns False. I figured out > base case, but I still get False when I enter bears(250). Any help > would be very appreciated! > From __peter__ at web.de Mon Jan 7 08:48:58 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 7 Jan 2008 14:48:58 +0100 Subject: code doesn't reference immutables? References: <5e6d3674-fddb-402f-9e5c-19afcd7fcc22@i7g2000prf.googlegroups.com> Message-ID: MartinRinehart wrote: > From the manual: > > "code objects are immutable and contain no references (directly or > indirectly) to mutable objects" (3.2) > > I thought my code worked with both mutable and immutable objects. > Whassup? A code object is an internal data structure that describes a piece of compiled python code. You can create one using compile(): >>> code = compile("a = 42", "", "exec") It is immutable: >>> code.a = 42 Traceback (most recent call last): File "", line 1, in TypeError: 'code' object has only read-only attributes (assign to .a) And you can use it like so: >>> a = "whatever" >>> exec code >>> a 42 If you have some spare time you can explore its attributes using dir(code); otherwise: don't bother. Peter From guptaabhishek1983 at gmail.com Fri Jan 11 03:07:36 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Fri, 11 Jan 2008 00:07:36 -0800 (PST) Subject: HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? Message-ID: <7243c2ac-fa22-4b5b-bd8c-34235123ab69@t1g2000pra.googlegroups.com> Hi group any idea on HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? Thank you From albert at spenarnc.xs4all.nl Tue Jan 29 08:37:49 2008 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 29 Jan 2008 13:37:49 GMT Subject: Changing module variables. Message-ID: I have made a sudoku solver, and discovered I simply can turn it into a hexadoku solver, like so: _______________________________ # sudoku solver using sets import sudoku sudoku.symbols="0123456789ABCDEF" sudoku.size=16 sudoku.sqs=4 # square root of size . _______________________________ Example of usage: _______________________________ y=sudoku.sudoku( " " " B " "95E " "8 1C" " 9 7" " 1 C" " 8 B" "A 46" " 4 " "0 8" " 71" "3 59" " C 8" "7F " "A 24" "BD " " 7 " "4 1" " 5" " " "42 " " 0" " BAC" " 1" "8 6A" "F 5" "2 9 " " D " " " "C28 " " 1 7" " 9 " " A3 " " " " E " " 5 B" "08 E" "B C " " 96 " "1A3 " "D 5 " " " "0 A" " E" "6 1" " A F" "5DC2" " 8" " 58 " "3C " " 6" "41AD" "1E 6" "542 " " 73D" " 08F" "B3 " " 8 " "14 " " 67" "240D" "16F " " 8 " " 3" ) y.show() y.solve() y.show() _______________________________ I like this. It certainly is reusability. Still I wonder what you guys think of this? (I know some OO-boys who would spank me for it.) Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- like all pyramid schemes -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From jr9445 at ATT.COM Thu Jan 17 09:56:02 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 17 Jan 2008 08:56:02 -0600 Subject: Creating unique combinations from lists In-Reply-To: <478E6BA7.5030509@tim.thechases.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> <478E6BA7.5030509@tim.thechases.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 Tim Chase > Sent: Wednesday, January 16, 2008 3:40 PM > To: breal > Cc: python-list at python.org > Subject: Re: Creating unique combinations from lists > > You can use a recursive generator: > > def iterall(*iterables): > if iterables: > for head in iterables[0]: > for remainder in iterall(*iterables[1:]): > yield [head] + remainder > else: > yield [] > > for thing in iterall( > ['big', 'medium', 'small'], > ['old', 'new'], > ['blue', 'green'], > ): > print thing Recursion definitely makes for an elegant solution. However you do take a bit of a performance hit. If performance matters (and comprehensions are supposed to be optimized/fast) and you want a "works for N nested loops solution," then you could build a N deep comprehension on the fly and eval() it: def gen(lists): out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in range(len(lists))]) return eval('[ ' + out + comp + ' ]') gen([a, b, c]) So for a three item list, it would build and execute the following comprehension: [ [v0,v1,v2] for v0 in lists[0] for v1 in lists[1] for v2 in lists[2] ] Seven item list: [ [v0,v1,v2,v3,v4,v5,v6] for v0 in lists[0] for v1 in lists[1] for v2 in lists[2] for v3 in lists[3] for v4 in lists[4] for v5 in lists[5] for v6 in lists[6] ] Some rough performance numbers in seconds for 1,000 iterations over a three item list: list comprehension: 0.74 nested for loop : 0.97 31% slower recursion : 3.91 428% slower =P eval : 1.11 50% slower from timeit import Timer s = "a = [ i for i in range(10) ]; b = a; c = a" t = Timer( "l = [ [i, j, k] for i in a for j in b for k in c]", s) iterations = 1000 print "list comprehension: %4.2f" % t.timeit(iterations) t = Timer(''' l = [] for i in a: for j in b: for k in c: l.append([i, j, k]) ''', s) print "nested for loop : %4.2f" % t.timeit(iterations) t = Timer(''' def iterall(*iterables): if iterables: for head in iterables[0]: for remainder in iterall(*iterables[1:]): yield [head] + remainder else: yield [] for thing in iterall(a, b, c): pass #print thing ''', s) print "recursion : %4.2f" % t.timeit(iterations) t = Timer(''' def gen(lists): out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in range(len(lists))]) return eval('[ ' + out + comp + ' ]') gen([a, b, c]) ''', s) print "eval : %4.2f" % t.timeit(iterations) ***** 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 mrmakent at cox.net Thu Jan 24 16:04:28 2008 From: mrmakent at cox.net (Mike Kent) Date: Thu, 24 Jan 2008 13:04:28 -0800 (PST) Subject: Can someone explain this unexpected raw_input behavior? References: Message-ID: <13ff90c7-60ee-4306-8459-890a2b2b178a@e25g2000prg.googlegroups.com> > If it weren't for the documentation... > > "If the prompt argument is present, it is written to *standard output* > without a trailing newline." > > -- > mvh Bj?rn I have reported this issue to the python-dev mailing list, and Guido agrees that this is a bug in Python. It turns out that the key is that my site does not have GNU readline installed, so Python falls back to its own implementation of readline. Using GNU readline, raw_input will write its prompt to stdout. Python's own implementation of readline sends the output to stderr. As Bjorn states, the documentation for raw_input says it writes its prompt to stdout. A bug issue has been opened in the Python Trac system for this. From nytrokiss at gmail.com Tue Jan 8 15:02:27 2008 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 8 Jan 2008 21:02:27 +0100 Subject: Python's great, in a word In-Reply-To: <7c77bd1c-3930-4078-b687-12cc7df849a9@d21g2000prf.googlegroups.com> References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <7c77bd1c-3930-4078-b687-12cc7df849a9@d21g2000prf.googlegroups.com> Message-ID: <8a6b8e350801081202q7f043b37q224584f023effd51@mail.gmail.com> We have such nice names so the word Python will be something people like and not something people fear (A massive 12 foot snake) and Pythonic is a behavior pattern we should all follow! In layman's terms it means we should all act like snakes a little more! On Jan 8, 2008 5:13 PM, Carl Banks wrote: > On Jan 7, 6:29 pm, MRAB wrote: > > On Jan 7, 5:40 pm, Martin Marcher wrote:> > MartinRineh... at gmail.com wrote: > > > > The best thing about Python is _______. > > > > > it's pythonicness. > > > > I think it sounds better as "its pythonicity". > > Mixing Greek and Latin suffixes usually works better than mixing Greek > and Germanic, doesn't it. > > > Carl Banks > -- > 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 Russ.Paielli at gmail.com Sun Jan 27 18:00:57 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 15:00:57 -0800 (PST) Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> Message-ID: <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> On Jan 27, 2:49 pm, "Andr?" wrote: > On Jan 27, 6:19 pm, "Russ P." wrote: > > > > > A while back I came across a tentative proposal from way back in 2000 > > for optional static typing in Python: > > >http://www.python.org/~guido/static-typing > > > Two motivations were given: > > > -- faster code > > -- better compile-time error detection > > > I'd like to suggest a third, which could help extend Python into the > > safety-critical domain: > > > -- facilitates automated source-code analysis > > > There has been much heated debate in the past about whether Python is > > appropriate for safety-critical software. Some argue that, with > > thorough testing, Python code can be as reliable as code in any > > language. Well, maybe. But then, a famous computer scientist once > > remarked that, > > > "Program testing can be used to show the presence of bugs, but never > > to show their absence!" --Edsger Dijkstra > > > The next step beyond extensive testing is automated, "static" analysis > > of source-code ("static" in the sense of analyzing it without actually > > running it). For example, Spark Ada is a subset of Ada with > > programming by contract, and in some cases it can formally prove the > > correctness of a program by static analysis. > > > Then there is Java Pathfinder (http://javapathfinder.sourceforge.net), > > an "explicit state software model checker." The developers of JPF > > wanted > > to use it on a prototype safety-critical application that I wrote in > > Python, but JPF only works on Java code. We considered somehow using > > Jython and Jythonc, but neither did the trick. So they ended up having > > someone manually convert my Python code to Java! (The problem is that > > my code was still in flux, and the Java and Python versions have now > > diverged.) > > > In any case, optional static typing in Python would help tremendously > > here. The hardest part of automated conversion of Python to a > > statically typed language is the problem of type inference. If the > > types are explicitly declared, that problem obviously goes away. > > Explicit typing would also greatly facilitate the development of a > > "Python Pathfinder," so the conversion would perhaps not even be > > necessary in the first place. > > > Note also that, while "static" type checking would be ideal, > > "explicit" typing would be a major step in the right direction and > > would probably be much easier to implement. That is, provide a syntax > > to explicitly declare types, then just check them at run time. A > > relatively simple pre-processor could be implemented to convert the > > explicit type declarations into "isinstance" checks or some such > > thing. (A pre-processor command-line argument could be provided to > > disable the type checks for more efficient production runs if > > desired.) > > > I noticed that Guido has expressed further interest in static typing > > three or four years ago on his blog. Does anyone know the current > > status of this project? Thanks. > > Perhaps this:http://www.python.org/dev/peps/pep-3107/might be > relevant? > Andr? Thanks. If I read this correctly, this PEP is on track for Python 3.0. Wonderful! From cptnwillard at gmail.com Thu Jan 17 10:05:49 2008 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Thu, 17 Jan 2008 07:05:49 -0800 (PST) Subject: Is this a bug, or is it me? Message-ID: Hello all, For some reason, the following does not work : class C: TYPES = [None] DICT = {} for Type in TYPES: DICT.update((E,Type) for E in [1]) >>> NameError: global name 'Type' is not defined What do you think? Is this a bug? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 18 04:18:01 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 18 Jan 2008 10:18:01 +0100 Subject: Loop in a loop? In-Reply-To: <7xy7aong73.fsf@ruckus.brouhaha.com> References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> <7xy7aong73.fsf@ruckus.brouhaha.com> Message-ID: <47906e95$0$16946$426a74cc@news.free.fr> Paul Rubin a ?crit : > George Sakkis writes: >> And if the iterables don't necessarily support len(), here's a more >> general solution: > > Not trying to pick on you personally but there's this disease > when a newbie comes with a basically simple question (in this case, > how to solve the problem with ordinary lists) and gets back a lot > of complex, overly general "graduate level" solutions. As far as I'm concerned, it's certainly a GoodThing(tm) - everyone learns in the process. From gagsl-py2 at yahoo.com.ar Thu Jan 24 02:08:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 Jan 2008 05:08:46 -0200 Subject: Can someone explain this unexpected raw_input behavior? References: Message-ID: En Thu, 24 Jan 2008 01:00:53 -0200, Mike Kent escribi?: > Gabriel, thank you for clarifying the source of this behavior. Still, > I'm surprised it would be hard-coded into Python. Consider an > interactive program, that asks the user several questions, and > displays paragraphs of information based on those questions. The > paragraphs are output using print, and the questions are asked via > raw_input. You want to do some simple debugging of the program by > printing some debugging statements via 'print >>sys.stderr', and you > don't want the debug output mixed in with the normal output on the > screen, so you try to route the debugging output to a file by adding > '2>filename' to the end of the command line. > > Unfortunately, you will no longer see any of the questions being > printed via raw_input. The rest of the output will be fine, but the > questions disappear. Your program just stops, without asking > anything... you have to guess what should be there. You have one console, two streams to output data (stdout and stderr), and three data sources (program output, user prompt, and debugging messages). Someone has to give. I'm now convinced that the current behavior is rather reasonable... > I'm surprised that Python hard-codes this behavior without giving the > programmer any way to change it. It leaves me with two options: to > either always use the logging module for debugging messages (which is > not odious at all, it's just that the code in question predates the > logging module, which is why debugging was done as it is), or change > the program so that raw_input is never used with a prompt parameter; > the prompt must always be printed separately. Perhaps raw_input could have a use_stderr=True parameter; with False would display the prompt on stdout. -- Gabriel Genellina From sjmachin at lexicon.net Wed Jan 9 15:26:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 9 Jan 2008 12:26:33 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> Message-ID: <9baa43c2-2a39-4f09-a62c-54f29cc08473@e4g2000hsg.googlegroups.com> On Jan 10, 7:12 am, Tim Chase wrote: > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] > > > I'd like to remove the first and the last item as they are irrevalent, > > and convert it to the dict: > > {'tom':'boss','mike':'manager','paul':'employee'} > > > I tried this but it didn't work: > > > mydict={} > > for i in mylist[1:-1]: > > a=i.split('=') # this will disect each item of mylist into a 2-item > > list > > mydict[a[0]]=a[1] > > > and I got this: > > File "srch", line 19, in > > grab("a/tags1") > > File "srch", line 15, in grab > > mydict[mylist[0]]=mylist[1] > > IndexError: list index out of range > > This can be rewritten a little more safely like > > mydict = dict(pair.split('=',1) > for pair in mylist > if '=' in pair) > > Some of John Machin's caveats still apply: > (2) a[0] is empty or not what you expect (a person's name) > (3) a[1] is empty or not what you expect (a job title) > (consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = ' > boss') > (4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...] > > to which I'd add > > (5) what happens if you have more than one equals-sign in your > item? ("bob=robert=manager" or "bob=manager=big-cheese") > or "bob==manager" ummm ... isn't more than one equals-sign covered by check #1: len(a) == 2 ? From bladedpenguin at gmail.com Sat Jan 26 00:33:48 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 21:33:48 -0800 (PST) Subject: Puzzled by behaviour of class with empty constructor References: <99b8e2ac-1c72-430a-9172-a809e169f96a@i12g2000prf.googlegroups.com> <5vv75rF1nt2o7U1@mid.individual.net> Message-ID: On Jan 25, 5:54 pm, dbas... at gmail.com wrote: > On Jan 25, 5:46 pm, Bjoern Schliessmann > > > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > dbas... at gmail.com wrote: > > > print x.ends,y.ends,z.ends > > > ############# > > > Running the following code outputs: > > >>>> [(0, 2)] [(0, 2)] [(0, 2)] > > > > Can anyone explain this? > > > Yes. You bound a single list to the name "ends" inside the class. > > This name is shared by all instances. > > > If you want the instances to each have separate lists, delete > > the "ends" definition from class declaration and insert "self.ends > > = []" into __init__. > > > I also suggest you to have a look at the tutorial. > > > Regards, > > > Bj?rn > > > -- > > BOFH excuse #49: > > > Bogon emissions > > Bj?rn, > > Thanks for the help. I had misguidedly defined the members of all of > my classes as in the example above; I never noticed the issue with any > of the others because they did not have empty constructors. > > Thanks again for the correction. Yeah! thanks all. I did not realize the distinction either. From pablo at decode.com.ar Mon Jan 7 08:15:12 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Mon, 07 Jan 2008 11:15:12 -0200 Subject: Python's great, in a word In-Reply-To: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <478225E0.8060506@decode.com.ar> MartinRinehart at gmail.com wrote: > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is _______. Hi Martin, here is my top three: 1) Fun 2) Simplicity 3) Productivity From python at rcn.com Wed Jan 23 00:29:48 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 22 Jan 2008 21:29:48 -0800 (PST) Subject: Cleanup when a object dies References: <601f19ce-ac60-4145-9e99-6eacb8ea74e2@e6g2000prf.googlegroups.com> Message-ID: <7c1171cb-f463-420a-8abe-70d68f587f55@u10g2000prn.googlegroups.com> On Jan 22, 7:54?pm, Benjamin wrote: > I writing writing a class to allow settings (options, preferences) to > written file in a cross platform manner. I'm unsure how to go a about > syncing the data to disk. Of course, it's horribly inefficient to > write the data every time something changes a value, however I don't > see how I can do it on deletion. I've read that __del__ methods should > be avoided. So am I just going to have to force the client of my > object to call sync when they're done? Lots of ways 1. Try the atexit module 2. Use a weakref callback 3. Embed a client callback in a try/finally. 4. Or, like you said, have the client call a sync() method -- this is explicit and gives the client control over when data is written. Raymond From steven at REMOVE.THIS.cybersource.com.au Mon Jan 21 04:25:04 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 09:25:04 -0000 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: On Mon, 21 Jan 2008 01:15:50 -0800, dg.google.groups wrote: > Decided I may as well post my other solution while I'm at it. The neat > trick here is redefining the add, mul, etc. functions so that they raise > exceptions for example if x>y then add(x,y) raises an exception which is > handled by the search algorithm to mean don't continue that computation > - this stops you from having to evaluate x+y AND y+x, etc. Setting up a try...except block is very fast, but actually responding to an exception is very slow. You _might_ find that it is quicker to evaluate both expressions than it is to catch the exception. Better still is to find another way of avoiding both the exception and the symmetrical calls. -- Steven From bignose+hates-spam at benfinney.id.au Mon Jan 14 17:35:22 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 09:35:22 +1100 Subject: [ANN] pylint 0.14 / logilab-astng 0.17.2 References: Message-ID: <878x2sf32t.fsf@benfinney.id.au> Sylvain Th?nault writes: > I'm pleased to announce a new release of pylint [1] and logilab-astng > [2]. I haven't personally found a lot of time to work on those projects > since the latest releases but others contributors have and so I decided > to publish releases including various contributions and other minor bug > or crash fixes (some of which were pending for a while now). You're > greatly encouraged to upgrade, see projects'changelog for more > information about what changed. Thanks very much for this. Can you please give an overview of the major user-visible changes? That will help in convincing people to upgrade. -- \ "Most people don't realize that large pieces of coral, which | `\ have been painted brown and attached to the skull by common | _o__) wood screws, can make a child look like a deer." -- Jack Handey | Ben Finney From bj_666 at gmx.net Mon Jan 21 14:18:18 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Jan 2008 19:18:18 GMT Subject: problem with 'global' References: Message-ID: <5vk9fqF1n19plU1@mid.uni-berlin.de> On Mon, 21 Jan 2008 17:08:46 -0200, Gabriel Genellina wrote: > The future statement is another example, even worse: > > if 0: > from __future__ import with_statement > > with open("xxx") as f: > print f In Python >=2.5 it's a compile time error if that import is not the very first statement in a source file. Ciao, Marc 'BlackJack' Rintsch From steven at REMOVE.THIS.cybersource.com.au Wed Jan 2 04:09:24 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 02 Jan 2008 09:09:24 -0000 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au> <87bq85rp2d.fsf@physik.rwth-aachen.de> <87abnoc13h.fsf@benfinney.id.au> Message-ID: On Wed, 02 Jan 2008 15:17:54 +1100, Ben Finney wrote: > Torsten Bronger writes: > >> [...] the width of a tab is nowhere defined. It really is a matter of >> the editor's settings. > > RFC 678 "Standard File Formats" > : Dated 19 December 1974. I really recommend that anyone following this thread read the RFC. It will give you a good mindset of how things were THIRTY YEARS AGO, before Unicode, before extended ASCII character sets, before Postscript, before laser printers, before graphical monitors, before you could choose your display resolution and typeface. Some recommendations from the RFC, with my comments in braces {}: The end of line convention is the Telnet end of line convention which is the sequence . { anyone here like to predict what Ben, a Linux user, uses as his end of line terminator? } Format 1 [Basic Document] This format is designed to be used for documents to be printed on line printers, which normally have 66 lines to a physical page, but often have forced top and bottom margins of 3 lines each. Active Format Effectors , , . Page Length 60 lines. Page Width 72 Characters. { who measures page width in characters any more? doesn't that depend on how wide each character is? and lines per page? } I think it tells a lot about the spaces-only argument that it is based on the state of the art thirty years ago, when people's choice in displaying and printing code was limited to one fixed width typeface per platform. If you actually view the RFC in question, it demonstrates just how obsolete it really is: fixed page breaks, hard coded page numbers, and with a hard coded 72 characters per line, the page's text takes up just over a third of my browser window, leaving 2/3rds blank. Printed is a little better: only 1/3rd of the printed page is left blank. Follow this RFC, and you too can needlessly waste screen real estate and paper! That's the world the spaces-only proponents still live in: everybody must write to the lowest common denominator just in case some day, some where some programmer might have to edit a source file by telnet on a fixed width character terminal using ed. If you are writing in an environment where it is likely, or even conceivable, that this could happen, then of course you should set in place an appropriate coding convention. That's the beauty of it: your code base, you get to tell everybody who works on it what conventions to follow. But for the rest of us, needlessly writing to the technology of 1974 is such a waste -- and I guarantee the 90% of programmers who aren't using a Unix-based OS aren't doing the same. And without the limitations of the 72 character line printer, there is no advantage to using fixed spaces for indents, and significant disadvantages. > How many columns to indent source code is an orthogonal question to how > wide an ASCII TAB (U+0009) should be rendered. The former question is > open to matters of style; the latter at least is standardised, even > given the caveats about enforcement. The existence of an RFC that nobody pays any attention to is not a standard. >> If all Python code used tabs, eveybody could use their own preferences, >> for both reading and writing code, and interoperability would be >> maintained nevertheless. > > Interoperability isn't the only criterion though. On the contrary, > source code is primarily for reading by programmers, and only > incidentally for reading by the compiler. Exactly, and allowing programmers to set their own indent width aids readability. Forcing your choice on others works against readability. It also hurts *editability*. Consider copying code from a source file with 8-space indents into a source file with 4-space indents, or vice versa. If you're lucky, your editor has a command to "clean spaces", or otherwise re-indent, and it might even get it right. At worst, you have to laboriously add or delete spaces by hand. That problem simply does not exist if you use the rule one tab = one indent level. You only need to re-indent when you are actually changing the number of indent levels, not as a side-effect of different conventions for the number of spaces per level. -- Steven From kyosohma at gmail.com Thu Jan 3 16:40:34 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 3 Jan 2008 13:40:34 -0800 (PST) Subject: How is AI implemented References: Message-ID: On Jan 3, 11:49 am, "Martin Marcher" wrote: > Hi, > > I know it's not a trivial field but I had some readings about > artificial intelligence lately and my personal conclusion is that it's > mostly just statistics. > > Naively explained: > > continiously gather and store information and apply a default rating > > 1) answer "questions" with gathered information according to rating > 2) store/calculate rating based upon input (be it an interface or user input) > 3) goto 1 (sorry for the goto) > > So I think that in general there hasn't yet been any artificial > intelligence programmed (Note: I believe I'm aware of the difference > between artificial intelligence and artificial conscusiness where the > second would be able to answer things like: "How are you today" and > the first can answer factual knowledge) > > Am I thinking right here or is there some (preferrably) web reading > available on that or in depth links about the topic? > > thanks and sorry for OT posting > martin > > --http://noneisyours.marcher.namehttp://feeds.feedburner.com/NoneIsYours Some readings: http://www-formal.stanford.edu/jmc/whatisai/whatisai.html http://www.sciencedaily.com/news/computers_math/artificial_intelligence/ http://www.jair.org/ http://dir.yahoo.com/Science/computer_science/artificial_intelligence/ Fuzzy Logic usually crops up as a related topic: http://www.seattlerobotics.org/encoder/mar98/fuz/flindex.html http://www.austinlinks.com/Fuzzy/ I'm not involved in this field, but I think saying that AI is just statistics is a pretty sweeping statement. It's more like super complicated stats using algorithms worthy of Calculus with branch logic thrown in for good measure. How's that for a load of buzz words!? Hope those links give you lots of info. Let us know when you've got a cool talking Python program! Mike From Russ.Paielli at gmail.com Thu Jan 10 02:39:38 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 9 Jan 2008 23:39:38 -0800 (PST) Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: On Jan 9, 9:47 pm, "Steve Brown" wrote: > I've got a series of modules which look like this: > > #************ > # > # Temperature Sense Test > # > #************ > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > I don't like the duplicated information: But the comment is attractive, and > the docstring self.__doc__ is already in use in the test log. I've read that > all modules and classes should have docstrings, but I don't really have > anything else to say, and each module contains only one class. I don't think > that > > """Temperature Sense Test""" > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > would be a real improvement. > > What do you think? > > Steve. I tend to be a bit skimpy with one-line comments for classes and methods, but I think a more complete (""" style) comment is often appropriate for the top of the file. I'm sure you can think of more to say than "Temperature Sense Test." What temperature? What kind of temperature sensor? What kind of test is it, and why are you doing it? That may all be obvious in context, but you've provided no context in your post. Also, if the module is of any significant size, you might want to provide a clue about who wrote it. Then, if someone has a question about it later, they will know who to ask. From george.sakkis at gmail.com Mon Jan 21 14:16:02 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 21 Jan 2008 11:16:02 -0800 (PST) Subject: is it possible to set namespace to an object. References: <27529efd-b8d8-4a8e-b72d-379a607366b7@i7g2000prf.googlegroups.com> <4794dd6c$0$27198$9b4e6d93@newsspool1.arcor-online.net> <62e9433b-4f04-4020-b1e6-581496ba3f3e@s19g2000prg.googlegroups.com> Message-ID: <9b656006-3b97-4ee8-b992-ff06b970904b@q77g2000hsh.googlegroups.com> On Jan 21, 1:56 pm, glomde wrote: > On 21 Jan, 18:59, Wildemar Wildenburger > > > > wrote: > > glomde wrote: > > > Hi, > > > > is it somehow possible to set the current namespace so that is in an > > > object. > > > [snip] > > > set namespace testObj > > > Name = "Test" > > > > Name would set testObj.Name to "Test". > > > > [snip] > > > > Is the above possible? > > > Don't know, sorry. But let me ask you this: Why do you want to do this? > > Maybe there is another way to solve the problem that you want to solve. > > The reason is that I do not want to repeat myself. It is to set up XML > type like > trees and I would like to be able to do something like. > > with ElemA(): > Name = "Top" > Description "Blahaha..." > with ElemB(): > Name = "ChildA" > Description "Blahaha..." > .... > > This would be the instead of. > with ElemA() as node: > node.Name = "Top" > node.Description "Blahaha..." > with ElemB() as node: > node.Name = "ChildA" > node.Description "Blahaha..." > .... > > So to save typing and have something that I think looks nicer. ... and more confusing for anyone reading the code (including you after a few weeks/months). If you want to save a few keystrokes, you may use 'n' instead of 'node' or use an editor with easy auto completion. By the way, is there any particular reason for generating the XML programmatically like this ? Why not have a separate template and use one of the dozen template engines to populate it ? George From not at valid.com Fri Jan 4 18:08:48 2008 From: not at valid.com (yomgui) Date: Fri, 04 Jan 2008 23:08:48 GMT Subject: opensg or openscenegraph Message-ID: <40zfj.33787$lD6.31634@newssvr27.news.prodigy.net> Hi, I need to use a scengraph for my python/opengl application but I have trouble finding out which one I should use. opensg or openscenegraph (OSG) ? I suppose the quality of the python bindings will make the decision. any advice ? thanks yomgui From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 21 18:34:31 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 22 Jan 2008 00:34:31 +0100 Subject: Max Long References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> Message-ID: <5vkog7F1m4dhvU1@mid.individual.net> tjhnson at gmail.com wrote: > How can I figure out the largest long available? Why would you? AFAIK, longs are only limited by available memory. > I was hoping for something like sys.maxint, but I didn't see it. > Also, can someone point me to where I can (concisely) read about > size of such types (int, float, long). Well, how about the docs? http://docs.python.org/lib/typesnumeric.html Regards, Bj?rn -- BOFH excuse #397: T-1's congested due to porn traffic to the news server. From arnodel at googlemail.com Sun Jan 20 11:22:28 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 20 Jan 2008 08:22:28 -0800 (PST) Subject: Bug in __init__? References: Message-ID: <88580064-3590-471e-8036-a631dd5a38b4@i3g2000hsf.googlegroups.com> On Jan 20, 3:39?pm, Bart Ogryczak wrote: > On 2008-01-18, citizen Zbigniew Braniecki testified: > > > It's really a nice pitfall, I can hardly imagine anyone expecting this, > > AFAIR, it's described in Diving Into Python. Still there seems to be about one message a week about this. Indeed I reckon the greatest benefit of early binding of default function arguments is that it attracts lots of new people to comp.lang.python. > It's quiet elegant way of creating cache. IMHO, calling it 'elegant' is pushing it too far! -- Arnaud From fredrik at pythonware.com Wed Jan 9 05:43:43 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 11:43:43 +0100 Subject: alternating string replace In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: cesco wrote: > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... how about splitting on "_", joining pairs with ":", and finally joining the result with "," ? >>> s1 = "hi_cat_bye_dog" >>> s1 = s1.split("_") >>> s1 ['hi', 'cat', 'bye', 'dog'] >>> s1 = [s1[i]+":"+s1[i+1] for i in range(0,len(s1),2)] >>> s1 ['hi:cat', 'bye:dog'] >>> s1 = ",".join(s1) >>> s1 'hi:cat,bye:dog' (there are many other ways to do it, but the above 3-liner is short and straightforward. note the use of range() to step over every other item in the list) From over at thepond.com Sun Jan 27 05:55:20 2008 From: over at thepond.com (over at thepond.com) Date: Sun, 27 Jan 2008 10:55:20 GMT Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> Message-ID: On Sat, 26 Jan 2008 14:47:50 +0100, Bjoern Schliessmann wrote: >over at thepond.com wrote: > >> Intel processors can only process machine language[...] There's no >> way for a processor to understand any higher level language, even >> assembler, since it is written with hexadecimal codes and basic >> instructions like MOV, JMP, etc. The assembler compiler can >> convert an assembler file to a binary executable, which the >> processor can understand. > >This may be true, but I think it's not bad to assume that machine >language and assembler are "almost the same" in this context, since >the translation between them is non-ambiguous (It's >just "recoding"; this is not the case with HLLs). I have no problem with your explanation. It's nearly impossible to program in machine code, which is all 1's and 0's. Assembler makes it infinitely easier by converting the machine 1's and 0's to their hexadecimal equivalent and assigning an opcode name to them, like PUSH, MOV, CALL, etc. Still, the older machine-programmable processors used switches to set the 1's and 0's. Or, the machine code was fed in on perforated cards or tapes that were read. The computer read the switches, cards or tapes, and set voltages according to what it scanned. the difference is that machine code can be read directly, whereas assembler has to be compiled in order to convert the opcodes to binary data. > >> Both Linux and Windows compile down to binary files, which are >> essentially 1's and 0's arranged in codes that are meaningful to >> the processor. > >(Not really -- object code files are composed of header data and >different segments, data and code, and only the code segments are >really meaningful to the processor.) I agree that the code segments, and the data, are all that's meaningful to the processor. There are a few others, like interrupts that affect the processor directly. I understand what you're saying but I'm refering to an executable file ready to be loaded into memory. It's stored on disk in a series of 1's and 0's. As you say, there are also control codes on disk to separate each byte along with CRC codes, timing codes, etc. However, that is all stripped off by the hard drive electronics. The actual file on disk is in a certain format that only the operating system understands. But once the code is read in, it goes into memory locations which hold individual arrays of bits. Each memory location holds a precise number of bits corresponding to the particular code it represents. For example, the ret instruction you mention below is represent by hex C3 (0xC3), which represents the bits 11000011. That's a machine code, since starting at 00000000 to 11111111, you have 256 different codes available. When those 1's and 0's are converted to volatges, the computer can analyze them and set circuits in action which will bring about the desired operation. Since Linux is written in C, it must convert down to machine code, just as Windows must. > >> Once a python py file is compiled into a pyc file, I can >> disassemble it into assembler. > >But you _do_ know that pyc files are Python byte code, and you could >only directly disassemble them to Python byte code directly? that's the part I did not understand, so thanks for pointing that out. What I disassembled did not make sense. I was looking for assembler code, but I do understand a little bit about how the interpreter reads them. For example, from os.py, here's part of the script: # Note: more names are added to __all__ later. __all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep", "defpath", "name", "path", "devnull"] here's the disassembly from os.pyc: 00000C04 06 00 00 00 dd 6 00000C08 61 6C 74 73 65 70 74 db 'altsept' 00000C0F 06 00 00 00 dd 6 00000C13 63 75 72 64 69 72 74 db 'curdirt' 00000C1A 06 00 00 00 dd 6 00000C1E 70 61 72 64 69 72 74 db 'pardirt' 00000C25 03 00 00 00 dd 3 00000C29 73 65 70 db 'sep' 00000C2C 74 07 00 00 dd 774h 00000C30 00 db 0 00000C31 70 61 74 68 73 65 70 db 'pathsep' 00000C38 74 07 00 00 dd 774h 00000C3C 00 db 0 00000C3D 6C 69 6E 65 73 65 70 db 'linesep' 00000C44 74 07 00 00 dd 774h 00000C48 00 db 0 00000C49 64 65 66 70 61 74 68 db 'defpath' 00000C50 74 04 00 00 dd offset unk_474 00000C54 00 db 0 00000C55 6E 61 6D 65 db 'name' 00000C59 74 04 00 00 dd offset unk_474 00000C5D 00 db 0 00000C5E 70 61 74 68 db 'path' 00000C62 74 07 00 00 dd 774h 00000C66 00 db 0 00000C67 64 65 76 6E 75 6C 6C db 'devnull' you can see all the ASCII names in the disassembly like altsep, curdir, etc. I'm not clear as to why they are all terminated with 0x74 = t, or if that's my poor interpretation. Some ASCII strings don't use a 0 terminator. The point is that all the ASCII strings have numbers between them which mean something to the interpreter. Also, they are at a particular address. The interpreter has to know where to find them. The script is essentially gone. I'd like to know how to read the pyc files, but that's getting away from my point that there is a link between python scripts and assembler. At this point, I admit the code above is NOT assembler, but sooner or later it will be converted to machine code by the interpreter and the OS and that can be disassembled as assembler. I realize this is a complicated process and I can understand people thinking I'm full of beans. Python needs an OS like Windows or Linux to interface it to the processor. And all a processor can understand is machine code. > >> Assembler is nothing but codes, which are combinations of 1's and >> 0's. > >No, assembly language source is readable text like this (gcc): > >.LCFI4: > movl $0, %eax > popl %ecx > popl %ebp > leal -4(%ecx), %esp > ret > Yes, the source is readable like that, but the compiled binary is not. A disaasembly shows both the source and the opcodes. The ret statement above is a mneumonic for hex C3 in assembler. You have left out the opcodes. Here's another example of assembler which is disassembled from python.exe: 1D001250 FF 74 24 04 push [esp+arg_0] 1D001254 E8 D1 FF FF FF call 1D00122A 1D001259 F7 D8 neg eax 1D00125B 1B C0 sbb eax, eax 1D00125D F7 D8 neg eax 1D00125F 59 pop ecx 1D001260 48 dec eax 1D001261 C3 retn the first column is obviously the address in memory. The second column are opcodes, and the third column are mneumonics, English words attached to the codes to give them meaning. The second and third column mean the same thing. A single opcode instruction like 59 = pop ecx and 48 = dec eax, are self-explanatory. 59 is hexadecimal for binary 01011001, which is a binary code. When a processor receives that binary as voltages, it is wired to push the contents of the ecx register onto the stack. The second instruction, call 1D00122A is not as straight forward. it is made up of two parts: E8 = the opcode for CALL and the rest 'D1 FF FF FF' is the opcode operator, or the data which the call is referencing. In this case it's an address in memory that holds the next instruction being called. It is written backward, however, which is convention in certain assemblers. D1 FF FF FF actually means FF FF FF D1. This instruction uses F's to negate the instruction, telling the processor to jump back. The signed number FFFFFFD1 = -2E. A call counts from the end of it's opcode numbers which is 1D001258, and 1D001258 - 2E = 1D00122A, the address being called. As you can see, it's all done with binary codes. The English statements are purely for the convenience of the programmer. If you look at the Intel definitons for assembler instructions, it lists both the opcodes and the mneumonics. I would agree with what you said earlier, that there is a similarity between machine code and assembler. You can actually write in machine code, but it is often entered in hexadecimal, requiring a hex to binary interpreter. In tht case, the similarity to compiled assembler is quite close. >Machine language is binary codes, yes. > >> You can't read a pyc file in a hex editor, > if I knew what the intervening numbers meant I could. :-) >By definition, you can read every file in a hex editor ... > >> but you can read it in a disassembler. It doesn't make a lot of >> sense to me right now, but if I was trying to trace through it >> with a debugger, the debugger would disassemble it into >> assembler, not python. > >Not at all. Again: It's Python byte code. Try experimenting with >pdb. I will eventually...thanks for reply. From http Wed Jan 16 03:12:08 2008 From: http (Paul Rubin) Date: 16 Jan 2008 00:12:08 -0800 Subject: itertools.groupby References: <478d0b7d$0$26094$88260bb3@free.teranews.com> Message-ID: <7xejcii3zb.fsf@ruckus.brouhaha.com> Tobiah writes: > I tried doing this with a simple example, but noticed > that [].sort(func) passes two arguments to func, whereas > the function expected by groupby() uses only one argument. Use: [].sort(key=func) From aekidens at yahoo.es Sun Jan 13 05:09:11 2008 From: aekidens at yahoo.es (Gabriel) Date: Sun, 13 Jan 2008 02:09:11 -0800 (PST) Subject: Graphics Module References: Message-ID: On 11 ene, 22:51, Mike wrote: > On Jan 11, 3:31 pm, "Gabriel" wrote: > > > Hi all ! > > > I'm developing a math program that shows graphics of functions. > > I would hear suggestions about the way of drawing 2D . > > > Thanks a lot for your answers. > > > - Gabriel - > > That's not a very descriptive question, however most people talk about > matplotlib for graphing and 2D drawings. > > Here's a few links on graphing in Python: > > http://matplotlib.sourceforge.net/http://wiki.python.org/moin/PythonGraphApihttp://alpha-leonis.lids.mit.edu/nlp/pygraph/http://boost.org/libs/graph/doc/python.htmlhttp://www.python.org/doc/essays/graphs.html > > Some of these may have dependencies, such as numpy or scipy. Be sure > to read the docs for full details either way. > > Mike Thanks ! Yes. This is what I was looking for.. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 21 07:48:45 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 13:48:45 +0100 Subject: Basic inheritance question In-Reply-To: <34aa1a1f-2034-471d-91ee-2a758dab555b@f47g2000hsd.googlegroups.com> References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> <478e1e3e$0$18054$426a74cc@news.free.fr> <34aa1a1f-2034-471d-91ee-2a758dab555b@f47g2000hsd.googlegroups.com> Message-ID: <47949466$0$18516$426a34cc@news.free.fr> Lie a ?crit : > On Jan 16, 9:23 pm, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: >> Lie wrote: >>> 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >>>> I used to systematically use it - like I've always systematically >>>> used 'this' in C++ and Java. >>> And that is what reduces readability. >> IMHO not, IOPHO not. This is the nth time (n >> 1) this discussion >> comes up here. If I have learned one thing from those very lengthy >> discussions, it's that Python's "self" handling is not going to >> change. > > And ah... yes, I don't wish it go away either. In VB, excessive Me > reduces readability, but in Python it doesn't. > >>> A proficient VB/C/Java programmer would frown upon the extra, >>> unneeded garbage as they thought it was clear already that the >>> variable refers to a class-level variable. >> C programmers surely have no opinion concerning C because it has no >> native classes. > > C-family, ok? Well... I'm not sure what "C-family" means, but to me it would consist in C, C++, Objective C, and D. > Please stop taking my words to its letters. So we're supposed to actually guess what you really mean ??? >> Personally, I've seen many C++ programs with complex class designs >> where it definitely helps to consistently use "this->". I cannot >> remember all local (and global) variables in bigger methods. > > In that case, you have the _option_ to do it. Make no sens when maintaining code wrote by someone that didn't use this 'option'. (snip) >>>> it's the first argument of the function - which usually happens to be >>>> the current instance when the function is used as a method. >>> And that's the point, self (or anything you name it) is almost always >>> the current instance >> # this is a plain function. In this function, >> # 'obj' can be whatever that happens to have a (numeric) >> # 'stuff' attribute >> def func(obj, arg): >> return (obj.stuff + arg) / 2.0 >> >> # this is a class with an instance attribute 'stuff' >> class Foo(object): >> def __init__(self, bar): >> self.stuff = bar + 42 >> >> # this is another (mostly unrelated) class >> # with a class attribute 'stuff' >> class Bar(object): >> stuff = 42 >> >> # this is a dummy container class: >> class Dummy(object): pass >> >> # now let's play: >> import new >> >> d = Dummy() >> d.stuff = 84 >> print func(d, 1) >> >> d.baaz = new.instancemethod(func, d, type(d)) >> print d.baaz(2) >> >> f = Foo(33) >> print func(f, 3) >> Foo.baaz = func >> f.baaz(4) >> >> print func(Bar, 5) >> Bar.baaz = classmethod(func) >> Bar.baaz(6) >> >>> and that makes it functionally the same as Me and >>> this in VB and Java. >> Depends on the context, cf above !-) > > Please again, stop taking letters to the words, I don't meant them to > be exactly the same, rather the same would meant that they generally > can be considered equal, If you still think that way after having read the above code, then I can't help. We obviously don't share the same mental model here. > exceptions exists of course. And btw, I don't > understand what you meant by your example, they seemed to be a > completely OK program for me, Indeed it's ok (even if totally useless by itself). The point is that 'self' (or whatever you name it) is just and only the first argument of a function, period. > even though it's a bit confusing to > follow[2]. Nothing in it should be confusing to anyone having a decent knowledge of Python's object model IMHO. > [2] btw, the reason it's a bit confusing to follow is one of my > points: It is a Bad Thing(tm) to use the same name for different > variables Where do I "use the same name for different variables" here ? > even in a language like Python that enforce explicit naming > of classes Python doesn't "enforce" explicit name of classes - IIRC, there are ways to instanciate anonymous class objects. But I definitively don't see how this relate to this discussion. Yes, I know, "please guess what I mean" !-) but sorry, there's no sens discussing a technical point without using accurate and appropriate technical naming of technical concepts invlved. >>>>> Most other languages >>>>> 1) automatically assign the containing class' object >>>> s/containing class' object/current instance/ >>>>> in a keyword >>>>> (Java: this, VB: Me) behind the screen, >>>> That's not very far from what a Python method object does - >>>> automatically assign the current instance to something. The difference >>>> is that Python uses functions to implement methods (instead of having >>>> two distinct contructs), so the only reliable way to "inject" the >>>> reference to the current instance is to pass it as an argument to the >>>> function (instead of making it pop from pure air). >>> It isn't very far, but Python makes it obvious about the assignment >>> (not behind the screen). >> Exactly. And given both the simplicity of the solution and what it let >> you do, that's a *very* GoodThing(tm) IMHO. > > I agree, it's a Good Thing but it doesn't make the point less pointy, > the difference between Me/this and self is just the explicit > assignment. Other things that is possible because of the explicit > assignment is just a "coincidence" of design choice. Are you sure ? As far as I'm concerned, I think that the design choice somehow results from what it makes possible. (snip pointless discussion wrt/ # of attributes) >>> And it is always a Bad Thing(tm) to use the same name for two >>> variable in the class and in function (which is the main and only >>> source of possible ambiguity) in ANY language, even in Python. >> Ho, yes.... Like, this would be bad ? >> >> class Person(object): >> def __init__(self, firstname, lastname, birthdate, gender): >> self.firstname = firstname >> self.lastname = lastname >> self.birthdate = birthdate >> self.gender = gender >> >> C'mon, be serious. It's often hard enough to come with sensible names, >> why would one have to find synonyms too ? Try to come with something >> more readable than the above, and let us know. Seriously, this braindead >> rule about "not using the same name for an attribute and a local var" >> obviously comes from languages where the "this" ref is optional, and >> FWIW it's obviously the wrong solution to a real problem (the good >> solution being, of course, to use the fully qualified name for >> attributes so there's no possible ambiguity). > > The code fragment you've given way above (about the Foo, Bar, bazz, > and func) also suffers from the bad habits of using the same name for > different variables. Where ? And how does this answer the question above ? > And it's not a "braindead" rule The way you express it, and as far as i'm concerned, it is, definitively. > The example you've given IS the most readable form since the function > is _simple_, consider a function that have complex codes, possibly > calculations instead of simply assigning initial values I'm sure you'd > slip up between the self.* variables and the * variables once or > twice, *you* would perhaps have this problem. And you would indeed have this problem in Java or C++. In Python, this problem just don't exist. > possibly becoming the source of hard-to-find bugs. Consistant and intelligible naming is quite another problem. And it's too much dependant on the context, language, domain and whatnot for any rule like your one above to be universally applyable. > And in languages that doesn't enforce explicit naming of classes, I still don't understand how all this relates to the naming of class objects ? Oops, sorry: you meant "in languages that has implicit instance reference available in methods" ? Python doesn't have it, so any rule deriving from this "feature" is out of scope here. > when > there is the two or more same names, the one with the smallest scope > is picked, so in _simple_ functions, the trick of using full qualified > names and overloaded local names is still possible and feasible. In > complex functions, the trick fails even in Python, because even if > Python and our full-concentration-brain is aware of the difference > between self.* and *, our spreaded-concentration-brain that is > scanning the code for the source of bugs might get stumbled on the > confusing use of self.* and *. Here again, *you* may have this problem. I don't, since I always used explicit instance reference. >>>> Anyway, I actually know 3 languages (4 if C# works the same) that has >>>> this implicit 'this' (or whatever the name) 'feature', and at least 5 >>>> that don't. So I'm not sure that the "most other languages" qualifier >>>> really applies to point 2 !-) >>> What's this 5 languages? >> Smalltalk, Python, PHP, javascript, Ruby. I don't remember how Scheme, >> CLOS and OCaml handle the case. > > Among all them, only Javascript is considerably mainstream. Is that a joke ? PHP is probably the most used language for web apps (server side of course). And Python is certainly not an obscure unknown geek-only language no more. But anyway: you were talking about "most other languages" - not "most mainstream languages". >>> Are they a mainstream, high-level languages >>> or lesser known, low-level languages? C-family, Java, and Basic are >>> the Big Three of high-level programming language. >> None of C, C++, Java nor Basic qualify as "hi-level". C is the lowest >> possible level above assembly, C++ is often refered to as an "object >> oriented assembler", Java is way too static, crippled, verbose an >> unexpressive to qualify as "hi-level" (even if it suffers from some >> problems usually associated with higher level languages). I won't even >> comment on basic (is that really a language at all ?). > > Your criteria on being high-level is simply just odd. My criteria on being hi-level seems quite common: automatic memory management, portability, "rich" builtin data types, functions as first class citizens, lexical closures, strong introspection features, strong metaprogramming support, etc... > The rest of the > world recognizes C-family, Java, and Basic as high-level languages. C was "hi-level" wrt/ assembler, indeed. And Java is "hi-level" wrt/ C++. Ho, and _please_ don't get me started on basic !-) > If I have to say it, Python is actually lower level than Basic. No comment. > While > Java is just below Python and C and C++ is just below Java. Why do I > consider Basic the highest-level? Because it is the cleanest to scan > (no confusing symbols, i.e. no curly braces, no confusing use of > parens (Python uses (), [], and {}, VB only use ()[3]), Basic != VB. There are quite a few other basics here. Now if you choose this criteria, you may want to learn some Lisp dialect. > > In what way C++ resembles an assembler? C++ is some OO stuff bolted on a very close-to-the-metal language itself designed to write operating systems, drivers and other low-level stuff. > Have you ever programmed in > assembly? I did. > How hard is it to create a simple program in assembly? And > how hard is it to create a complex program in C++ Roughly the same, thanks to scoping rules, dependencies hell, lack of automatic memory management and overcomplex features. > (which AFAIK is used > by hundreds of mega projects including CPython)? CPython - as the name implies - is written in C. > And have you ever used Basic at all? I did. And not only VB. > Some programmers would instantly frown upon Basic, simply because they > don't know that Basic is "just another language". I've used at least four different variants of Basic. >>>>> In VB, Me is extremely rarely used, >>>> I used to systematically use it - like I've always systematically used >>>> 'this' in C++ and Java. >>> And that is what reduces readability. A proficient VB/C/Java >>> programmer >> There are quite a few proficient C/C++/Java programmers here. As far as >> I'm concerned, I would not pretend being one - I just have a good enough >> knowledge of C, Java and (alas) VB to be able to get up to speed in a >> reasonnable time frame. >> >> As a side note, the problem just doesn't exists in C, which has >> absolutely no support for OO. > > When I said C, it might mean C and C-family, When you say "C", it means "C" to everyone reading you. > so please stop > misunderstanding me. Please learn to express yourself clearly. If you say "X" when you mean "Y", *you* are the one responsible for misunderstandings. This is human communication 101 skill. (snip) > I'm not saying my mindset is better than yours (it have its positives > and negatives), in fact I apologize for getting you confused. My "mindset", as you say, is the one you'll find in each and every technical communication. You can't discuss technical points without a clear, unambiguous naming of technical concepts. And when a community exists, it usually has it's own technical idiom, whether highly specific (ie : "member variables" in C++, "attributes" in Python), or more general (ie: C is not the same thing as C++, whenever language you're using). >>> would frown upon the extra, unneeded garbage as they >>> thought it was clear already that the variable refers to a class-level >>> variable. >> In C++, the canonical way to make this "clear" is to use the m_name >> convention. There must be some reason C++ programmers feel a need for >> this "extra, unneeded garbage" ?-) > > In some cases, an extremely complex class that can't be fragmented any > further, the m_ convention is surely useful, but in most cases you > could skip them out. You "could" skip this convention, but it's really considered bad practice by quite a lot of C++ programmers. > And the canonical way to make this "clear" is not > the m_ convention, it's the name itself. A well-designed class would > choose names that is recognizable instantly from the name itself, even > without the pseudo-name appended to it (or prepended). I await for your exemples. > btw you must have been memorizing names braindeadly, because the only > way you could stumble on that is by memorizing names braindeadly. > Names shouldn't be memorized, it should be inferred and memorized. For > example, when you met a variable name firstname and lastname inside a > class called Person, you'd immediately realize that it is Class Level > variable because you know that the function you're currently working > on use the name initialfirstname and initiallastname. Fine, I now have four names to handle, each of them being possibly an argument, a local variable, a member variable or a global variable. Great. Sorry but I won't buy this. (snip) >>> As I've pointed out, there is little harm in class-level variable's >>> implicit reference. >> Have some working experience on any non-trivial C++ project ? > > No I would have been surprised if you had answer otherwise. > (you could say I'm a student so I've never "worked"[1]). But I've > done some medium-sized projects in other languages. > > [1] If you understand the irony, you'd realized I was deliberately > misunderstanding you Not sure. >>>>> Compare the following codes: >>>>> VB.NET: >>>>> Public Class A >>>>> Dim var >>>>> Public Function aFunction() >>>>> return var >>>> Add three levels of inheritence and a couple globals and you'll find out >>>> that readability count !-) >>> It's the mental model that have to be adapted here, if the current >>> class is inheriting from another class, you've got to think it as >>> names from parent class as it is a native names, so you don't actually >>> need to know where the variable comes from >> In C++ (and VB IIRC), it might as well be a global So sorry but yes, I >> have to know where it comes from. > > How many times would you use globals, it is a Bad Thing(tm) to use > globals in the first case. It is, most of the time, indeed. The problem is that you rarely start a project from scratch - most of the time, you have to work on legacy code. And you really seldom have the possibility to do a major rewrite to fix all warts. > In some exceptional cases globals might be > unavoidable, but it is trivial to work out that you have to reduce the > amount of globals to a minimum, in almost any cases to a number you > can use a hand to count with. That very nice, from a theoretical POV. That's alas just not how it works in real life. > And applying the hacks mentioned, why > don't you use the m_ convention for globals, and retains the > convenience of m_-free variables in your class variable. You use class > variable much more often than globals, and in most projects class- > level variable is used just as often as local-variable. The problem is not what *I* (would) do, but how is the existing code. >>> since knowing where it >>> comes from is breaking the encapsulation >> Nope, it's knowing what you're doing and how the piece of software at >> hand is working. And FWIW, while data hiding is one possible mean of >> encapsulation, it's by no way a synonym for encapsulation. > > I agree that knowing an underlying class's implementation is useful > (in fact, very useful) but what I'm talking is about should-ness, > we > shouldn't _need_ to know the underlying implementation, How can you hope to extend a class without _any_ knowledge of it's implementation ? (snip) > >>> (which, in Python is very >>> weakly implemented, which favors flexibility in many cases[1]). >>> [1] In Python, it is impossible to create a completely private >>> variable, which is the reason why the mental model of these other >>> languages doesn't fit Python. >> Never heard about the infamous '#define private public' hack in C++ ? >> And don't worry, there are also ways to get at so called 'private' vars >> in Java. > > No, but it's violating the language's rule. Nope. It's just making use of some part of the language's rules. > Python OTOH, provides > formal ways to got to private vars. Python doesn't have "private vars" at all. >>>> In any non-trivial piece of C++ code, and unless the author either used >>>> the explicit 'this' reference or the 'm_xxx' naming convention, you'll >>>> have hard time figuring out where a given name comes from when browsing >>>> a function's code. >>> If you're used to the implicit naming scheme it's easy to know where a >>> variable came from, if not the current scope, it's the class' scope >> You forgot the global scope. > > How many global variables do you have in your projects on average? If > you always have a pageful list of globals in your projects, then you > should consider unlearning and relearning the basic programming > concepts. I'll come to you when I'll need more training, don't worry. > It's easy to keep track of globals, as you shouldn't have a > lot of them even in a huge project. Can't you understand that starting a new project afresh is *not* the common case ? >>> As a final note: >>> I don't think implicit class reference is superior to explicit class >>> reference, neither >> ... > > I'm sure you don't believe it since I'm talking on implicit's side, > but that's the fact, I just pointed you out that implicits do have its > positive side (even if you don't consider them positive in _your_ > book) but that doesn't meant I believe it is better than the other. > > To clear things up: > As a final note: > I don't think implicit class reference is superior to explicit class > reference, but I don't think the vice versa is true either. Once again : what classes have to do with this ? Seriously, how can you hope to be taken seriously when you're obviously confusing such important concepts as instance and class ? From robert.kern at gmail.com Sat Jan 12 17:44:27 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 12 Jan 2008 16:44:27 -0600 Subject: Is unicode.lower() locale-independent? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Robert Kern wrote: > >>> However it appears from your bug ticket that you have a much narrower >>> problem (case-shifting a small known list of English words like VOID) >>> and can work around it by writing your own locale-independent casing >>> functions. Do you still need to find out whether Python unicode >>> casings are locale-dependent? >> I would still like to know. There are other places where .lower() is used in >> numpy, not to mention the rest of my code. > > "lower" uses the informative case mappings provided by the Unicode > character database; see > > http://www.unicode.org/Public/4.1.0/ucd/UCD.html > > afaik, changing the locale has no influence whatsoever on Python's > Unicode subsystem. Even if towlower() gets used? I've found an explicit statement that the conversion it does can be locale-specific: http://msdn2.microsoft.com/en-us/library/8h19t214.aspx Thanks, Fredrik. -- 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 mario at ruggier.org Thu Jan 3 16:03:08 2008 From: mario at ruggier.org (mario) Date: Thu, 3 Jan 2008 13:03:08 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> Message-ID: <76ba16c8-6ba0-4609-80bd-cd54aa08d74b@5g2000hsg.googlegroups.com> On Jan 2, 2:25 pm, Piet van Oostrum wrote: > Apparently for the empty string the encoding is irrelevant as it will not > be used. I guess there is an early check for this special case in the code. In the module I an working on [*] I am remembering a failed encoding to allow me, if necessary, to later re-process fewer encodings. In the case of an empty string AND an unknown encoding this strategy failed... Anyhow, the question is, should the behaviour be the same for these operations, and if so what should it be: u"".encode("non-existent") unicode("", "non-existent") mario [*] a module to decode heuristically, that imho is actually starting to look quite good, it is at http://gizmojo.org/code/decodeh/ and any comments very welcome. From bignose+hates-spam at benfinney.id.au Thu Jan 17 19:31:53 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 18 Jan 2008 11:31:53 +1100 Subject: Complex discussions of "simple" problems (was: Loop in a loop?) References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> <7xy7aong73.fsf@ruckus.brouhaha.com> Message-ID: <87ir1sas92.fsf_-_@benfinney.id.au> Paul Rubin writes: > Not trying to pick on you personally but there's this disease when a > newbie comes with a basically simple question (in this case, how to > solve the problem with ordinary lists) and gets back a lot of > complex, overly general "graduate level" solutions. Is that a disease? I would characterise it as symptomatic of a very healthy programming community. We like interesting problems, and enjoy coming up with ever more elegant solutions. The discussions that ensue are healthy, not diseased. Whether that's exactly what the original poster in such a thread wants is beside the point. This forum is for the benefit of all participants, and discussing an apparently simple problem to discover its complexities is part of the enjoyment. Enjoyment of the discussion, after all, is the main reward most people can ever hope to get for participation in most threads here. -- \ "Remember: every member of your 'target audience' also owns a | `\ broadcasting station. These 'targets' can shoot back." -- | _o__) Michael Rathbun to advertisers, news.admin.net-abuse.email | Ben Finney From xena-die-kriegerprinzessin at gmx.de Thu Jan 17 10:08:14 2008 From: xena-die-kriegerprinzessin at gmx.de (Heiko Niedermeyer) Date: Thu, 17 Jan 2008 15:08:14 +0000 (UTC) Subject: How to create graphs an embed them in GUI? Message-ID: Sorry for the fuzzy subject... Currently I'm writing a little programm to extract some chemical information out of a text file, and then present it in a pleasant way. The Extraction works so far, so now the presentation will be next. As I'm learning Python from scratch, I don't care wether to use (=learn) TKinter or PyQt or whatever, I just need some advice, which suits my needs best. It would be nice to have the programm working under win and linux (shouldn't be a big Problem) and my requirements concerning the standard elements should be met by almost every framework. My problem is, that I want to add graph (simple, line connected X,Y- scatter plots) and if possible the 3D representation of atoms in a molecule (-> coloured spheres in space). I think it would take me years to program those by myself, so I would ne ready to use packages, if available. Long story short: Are there packages that could do this, and does it matter which GUI I want to embed them in? best wishes From mwm-keyword-python.b4bdba at mired.org Fri Jan 11 18:21:45 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 18:21:45 -0500 Subject: encrypting python modules In-Reply-To: <87sl14getd.fsf@benfinney.id.au> References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <87sl14getd.fsf@benfinney.id.au> Message-ID: <20080111182145.6be85d50@bhuda.mired.org> On Sat, 12 Jan 2008 09:47:26 +1100 Ben Finney wrote: > Paul Sijben writes: > > I know that I can not stop a dedicated hacker deconstructing my code. > A direct consequence of this is that you can not stop *anyone* from > deconstructing your code if it's in their possession. It takes only > one dedicated, skilled person to crack your obfuscation system and > distribute an automated process for doing so to anyone interested. Except that's not what he's trying to do. > > However I can not imagine that I would be the first one planning to > > do this. So is there a solution like this available somewhere? > Trying to make bits uncopyable and unmodifiable is like trying to make > water not wet. And again, that's not what he's trying to do. He wants to arrange things so that he doesn't have to support unmodified versions of his code, by making it impossible to import modified modules. While that's still impossible, once you decide how difficult you want to make it for people to do that, you can *probably* make it that difficult - but the process gets progressively more difficult and expensive as you make it harder. I think he's contemplating only the simplest, least expensive step: adding an import hook that only allows imports of digitally signed modules. If planning to deploy on Windows, where he has to bundle a python with his application, he may well implement the hook in the interpreter instead of in python, so it's harder to find. If you wanted to go to the expense, you could probably arrange things so that the digital signatures are the more vulnerable attack vectors, but I'd expect to spend millions of dollars doing so. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From jr9445 at ATT.COM Fri Jan 11 15:55:18 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 11 Jan 2008 14:55:18 -0600 Subject: alternating string replace In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.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 cesco > Sent: Wednesday, January 09, 2008 5:34 AM > To: python-list at python.org > Subject: alternating string replace > > Hi, > > say I have a string like the following: > s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... > For those of us who still think in Perl, here's an easy to read, lazy solution: s = 'hi_cat_bye_dog' print s s = re.sub(r'_(.*?(_|$))', r':\1', s) ## every odd '_' to ':' print s s = re.sub(r'_', r',', s) ## every even '_' to ',' print s > hi_cat_bye_dog > hi:cat_bye:dog > hi:cat,bye:dog The equivalent Perl code: my $s = 'hi_cat_bye_dog'; print $s, "\n"; $s =~ s/_(.*?(_|$))/:$1/g; print $s, "\n"; $s =~ s/_/,/g; print $s, "\n"; From xng at xs4all.nl Thu Jan 10 08:47:22 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Thu, 10 Jan 2008 14:47:22 +0100 Subject: Python or PowerShell ? In-Reply-To: <225fb03f-a385-4651-be3b-7f8998901d46@q77g2000hsh.googlegroups.com> References: <87hchodstr.fsf@physik.rwth-aachen.de> <4783d594$0$8926$e4fe514c@dreader16.news.xs4all.nl> <225fb03f-a385-4651-be3b-7f8998901d46@q77g2000hsh.googlegroups.com> Message-ID: <478621d7$0$30541$e4fe514c@dreader32.news.xs4all.nl> kyosohma at gmail.com wrote: > On Jan 8, 1:57 pm, "Martin P. Hellwig" wrote: >> And adding to that, if you don't care about cross platform anyway, why >> even bother with python? I am sure that MS has tools that can do in a >> point and click kind of way all the things you might encounter. > > I code mostly for Windows users, but I use Python almost exclusively. > Why? > > 1) Python is "free" > 2) Microsoft Visual Studio is very expensive > 3) Python is Open Source > 4) Visual Studio is not Open Source > 5) I can actually take the code from IDLE and refine it for my > purposes if it doesn't suit me. Good luck doing that with practically > anything Microsoft supplies. > 6) With relative ease, I can go cross-platform with my code if > requirements change > > I could go on. There are many good reasons to use Python (or some > other good open source language, like Ruby) even if you just program > for Windows. > > Mike Well if that are your requirements, which are all good ones btw, then you have answered your own question :-) -- mph From timr at probo.com Sat Jan 12 00:52:37 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 12 Jan 2008 05:52:37 GMT Subject: ISO Python example projects (like in Perl Cookbook) References: Message-ID: <4clgo35m078db7q0i4gt615fsvb6g74kk3@4ax.com> "Delaney, Timothy (Tim)" wrote: > >You know you've been working at a large company for too long when you >see that subject and think "ISO-certified Python?" That's exactly what I thought, too. After reading the post I assume he actually meant "In Search Of"? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From grante at visi.com Sun Jan 27 10:56:25 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 27 Jan 2008 15:56:25 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <13ppad9ahqrqh92@corp.supernews.com> On 2008-01-27, over at thepond.com wrote: > Whatever is typed in a Python script must be converted to > binary code. Python scripts _are_ in a binary code when the start out. -- Grant Edwards grante Yow! What UNIVERSE is at this, please?? visi.com From manugarg at gmail.com Wed Jan 23 05:28:36 2008 From: manugarg at gmail.com (Manu Garg) Date: Wed, 23 Jan 2008 15:58:36 +0530 Subject: Announcement: Python module for pacparser (parses proxy auto-config files) Message-ID: <8ea71edb0801230228y249bff93x3fc9b174b3187453@mail.gmail.com> Fellas, I am mighty pleased to announce the release of python module for pacparser. pacparser is a library to parse proxy auto-config (PAC) files. Proxy auto-config files are already a vastly used web proxy configuration method these days (either directly or via web proxy autodiscovery protocol) and almost all popular web browsers support them. pacparser python module brings in PAC file parsing capability to python programs. Using it, python web software can now work with proxy auto-config files. I am hoping, web software programmers will appreciate it. At least I've been looking for such a thing for a while :). For documentation and available packages, please visit project homepage at http://code.google.com/p/pacparser Direct download links: Source archive: http://pacparser.googlecode.com/files/pacparser-1.0.3.tar.gz Compiled module for python 2.5 and win32: http://pacparser.googlecode.com/files/pacparser-python25-1.0.3-win32.zip I have tested the module to work on Python 2.2 - 2.5 on Linux and Win32. Cheers :-), Manu -- Manu Garg http://www.manugarg.com "Journey is the destination of life." From nagle at animats.com Thu Jan 3 13:22:24 2008 From: nagle at animats.com (John Nagle) Date: Thu, 03 Jan 2008 10:22:24 -0800 Subject: urllib timeout hole - long timeout if site doesn't send headers. Message-ID: <477d26f4$0$36384$742ec2ed@news.sonic.net> urllib has a "hole" in its timeout protection. Using "socket.setdefaulttimeout" will make urllib time out if a site doesn't open a TCP connection in the indicated time. But if the site opens the TCP connection and never sends HTTP headers, it takes about 20 minutes for the read in urllib's "open" to time out. There are some web servers that produce this behavior, and many seem to be associated with British universities and nonprofits. With these, requesting "http://example.com" opens a TCP connection on which nothing is ever sent, while "http://www.example.com" yields a proper web page. Even Firefox doesn't time this out properly. Try "http://soton.ac.uk" in Firefox, and be prepared for a long wait. There was some active work in the urllib timeout area last summer. What happened to that? John Nagle From hv at tbz-pariv.de Fri Jan 4 03:03:25 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Fri, 04 Jan 2008 09:03:25 +0100 Subject: Resetting Signal Mask Message-ID: <5u67idF1g380iU1@mid.individual.net> Hi, with mod_wsgi (apache2) a process created with os.system() has a modified signal mask, that SIGPWR gets ignored. A small wrapper (see bottom) resets the signal mask and uses execv to run the programm. Unfortunately python does not support sigprocmask. Is there any other way to reset the signal mask? I guess it could be done with ctypes (I never used it up to now). Why is sigprocmask not available in Python? Python exposes most of the other POSIX API. Thomas 1 #include 2 #include 3 #include 4 5 int main(int argc, char *argv[]) { 6 sigset_t newmask; 7 8 sigemptyset(&newmask); 9 sigprocmask(SIG_SETMASK, &newmask, NULL); 10 int ret=execv(argv[1], &argv[1]); 11 if (ret != 0) { perror(argv[0]); } 12 return ret; 13 } From Lie.1296 at gmail.com Fri Jan 11 06:24:01 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 11 Jan 2008 03:24:01 -0800 (PST) Subject: what does **kw mean? References: <99cc3280-bffd-4004-a3ae-a06244a82759@e6g2000prf.googlegroups.com> Message-ID: On Jan 11, 4:38?pm, "zsl... at gmail.com" wrote: > I've been reading the following example, and couldn't figure out, what > **kw mean. (It's an empty dictionary, but what's the semantics): It's a keyword argument. It's some kind of repository for arguments that aren't recognized. If you have function like this: def func(a, *args, *kw): print a print args print kw and you call the functin like this: func('value A', 'value B', 'value C', argumentA = 'value D', argumentB = 'value D') the extra arguments would normally raise an error, but with the * and **, Python would: - assign 'value B' and 'value C' to args - assign 'argumentA':'value D' and 'argumentB':'value E' to kw so if you run the function, it will output: #### value A ('value B', 'value C') {'argumentB': 'value E', 'argumentA': 'value D'} #### this args and kw can be accessed like a tuple and dictionary respectively See '4.7.2 Keyword Arguments' and '4.7.3 Arbitrary Argument Lists' on Python Help File From lepto.python at gmail.com Wed Jan 9 01:48:39 2008 From: lepto.python at gmail.com (oyster) Date: Wed, 9 Jan 2008 14:48:39 +0800 Subject: hkimball's question on ctypes Message-ID: <6a4f17690801082248i7d9119a3s57264b062e86345b@mail.gmail.com> 2008/1/9, python-list-request at python.org : > Date: Tue, 8 Jan 2008 17:11:18 -0800 (PST) > Subject: ctypes 1. please make your title more specific > >>> from ctypes import * > >>> cdecl = > cdll.LoadLibrary("c:\projects\python\geinterface.dll") 2. are you sure '\' is ok? cdll.LoadLibrary(r"c:\projects\python\geinterface.dll") or cdll.LoadLibrary("c:/projects/python/geinterface.dll") 3. if possibile, you can upload your dll and post the link in the mail-list 4. there is a ctypes official maillist on http://sourceforge.net/projects/ctypes/. but it seems that it is closed to the users since some of my mail from 2007.12 does not appear here. but maybe you can have a try. From asmodai at in-nomine.org Wed Jan 9 01:54:52 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 9 Jan 2008 07:54:52 +0100 Subject: Pet Store In-Reply-To: <44713824-c8c9-4a4c-af7e-042260068c0c@x69g2000hsx.googlegroups.com> References: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com> <5ugv69F1hqn2cU3@mid.uni-berlin.de> <44713824-c8c9-4a4c-af7e-042260068c0c@x69g2000hsx.googlegroups.com> Message-ID: <20080109065452.GN75977@nexus.in-nomine.org> -On [20080108 19:36], George Maggessy (george.maggessy at gmail.com) wrote: >Yeap. It is. I'm looking for something like that app. Smth that I >could base my future developments on. If you want to go the Ruby on Rails-like road then you have Django, Pylons, TurboGears, Zope, to name four of the bigger ones. If you want a basic HTTP handling framework under which you can hang your own code more easily then you should look at things like Paste, WebOb, CherryPy, Werkzeug, Twisted and others. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Teachers open the door, but you must enter by yourself. -Chinese Proverb From kyosohma at gmail.com Fri Jan 18 14:00:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jan 2008 11:00:13 -0800 (PST) Subject: Pythonland documentation References: Message-ID: <0ca3afaa-9e35-42e6-b3fd-da6d2cf012b5@i7g2000prf.googlegroups.com> On Jan 18, 12:51 pm, Simon Pickles wrote: > Hi > > I am new to python (fairly) but can't stop pythonning. > > c++ seems so far away now.... from here it looks like a horrid scribble :) > > Anyway.... my question is really about doc tools. I've been used to > doxygen in c++ land, and although it makes a reasonable stab with a > python project in java mode, the output is a bit messy. > > Can any one suggest a more tailored tool? or do I risk a flamewar? :) > > Thanks > > SiPi > > -- > Linux user #458601 -http://counter.li.org. Well, there's DocUtils: http://docutils.sourceforge.net/ And here are some others: http://peak.telecommunity.com/protocol_ref/protocols-example1.html And finally, there's this: http://www.python.org/community/sigs/current/doc-sig/otherlangs/ Mike From sjmachin at lexicon.net Fri Jan 11 15:22:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 12 Jan 2008 07:22:39 +1100 Subject: scope question in a switch mixin In-Reply-To: References: Message-ID: <4787D00F.7030900@lexicon.net> browerg at verizon.net wrote: > The code that follows is the result of noodling around with switches as a learning tool. I've played with python for a few years, but I'm self-taught, so . . . > > Class Switch builds a set of functions. Method switch executes one of them given a value of the switch variable. > > My question is, why are modules imported at the top of the program not visible to the functions Switch builds? There is > no problem when the import is in the function, but I thought initially that imports at the top would be in its globals. The global namespace of the to-be-exec'ed code is the dictionary that you supply. That dictionary doesn't contain "math". More comments below. [snip] > > #import math > > class Switch(object): > > def __init__(self, keys, vals, base): > self.dictionary = {} > tmpd = {} Uncomment the above import, remove the import from your constructed source code and try tmpd = {'math': math} > for i in range(len(vals)): > func = ''.join([base[0] % keys[i], vals[i], base[1]]) > compile(func, '', 'exec') > exec(func, tmpd) compile returns a code object, which you are throwing away. Comment out that statement, and the behaviour of your code will not change. This is because if the first argument to exec is a string, it is compiled into a code object. It's a long time since exec has been documented as a *function*. Why? Because it isn't: >>> exec "print 'xxx'" xxx >>> exec("print 'xxx'") xxx >>> foo = compile >>> foo >>> foo = exec File "", line 1 foo = exec ^ SyntaxError: invalid syntax >>> What book/tutorial did you get that from? Cheers, John From lasses_weil at klapptsowieso.net Sat Jan 12 08:21:30 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sat, 12 Jan 2008 14:21:30 +0100 Subject: extracting Javadocs using Python In-Reply-To: <30a4948a-7293-43d6-9381-824654e44416@s19g2000prg.googlegroups.com> References: <30a4948a-7293-43d6-9381-824654e44416@s19g2000prg.googlegroups.com> Message-ID: <4788bedd$0$5968$9b4e6d93@newsspool3.arcor-online.net> Rajarshi wrote: > Does anybody know if something like this is available? Or would I need > to implement a parser from scratch? > Probably. But using pyparsing, you shouldn't have a lot of trouble with it. You may want to take a look at epydoc, a python API-doc generator. I seem to remember that in addition to using rST markup, it also provides markup similar to Javadocs. Maybe you can get some "inspiration" from the epydoc sources. regards /W From piet at cs.uu.nl Fri Jan 4 15:02:23 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 04 Jan 2008 21:02:23 +0100 Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: >>>>> bukzor (B) wrote: >B> Why cant you implement < for complex numbers? Maybe I'm being naive, >B> but isn't this the normal definition? >B> a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) There doesn't exist a `normal' definition of < for the complex numbers. For example you would expect that x URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From jr9445 at ATT.COM Tue Jan 29 12:26:30 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 29 Jan 2008 11:26:30 -0600 Subject: Python noob SOS (any [former?] Perlheads out there?) 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 kj > Sent: Tuesday, January 29, 2008 11:39 AM > To: python-list at python.org > Subject: Python noob SOS (any [former?] Perlheads out there?) > > > > For many months now I've been trying to learn Python, but I guess > I'm too old a dog trying to learn new tricks... For better or > worse, I'm so used to Perl when it comes to scripting, that I'm > just having a very hard time getting a hang of "The Python Way." > > It's not the Python syntax that I'm having problems with, but rather > with larger scale issues such as the structuring of packages, > techniques for code reuse, test suites, the structure of > distributions,... Python and Perl seem to come from different > galaxies altogether... It sound like less of a "How to do Things the Python Way" problem, a more of a "How to do Object Oriented Programming" problem. Coming from a C++/Perl background, I found the O'Reilly 'Learning Python' book to be useful. It has a section on OOP, which covers basic OO theory that you may find useful. I can't think of a decent OO book to recommend though. > Be that as it may, the activation barrier to using Python for my > scripting remains too high. > > I'd written a Perl module to facilitate the writing of scripts. > It contained all my boilerplate code for parsing and validating > command-line options, generating of accessor functions for these > options, printing of the help message and of the full documentation, > testing, etc. Bleh. Perl and Python have really good libraries. Why waste time rolling your own when you can use Python's getopt or optparse, or Perl's Getopt and Getopt::Long? From hniksic at xemacs.org Mon Jan 14 11:29:16 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 14 Jan 2008 17:29:16 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> Message-ID: <873at0mkv7.fsf@mulj.homelinux.net> Mel writes: >> I don't understand the purpose of this "correction". After all, >> __init__ *is* the closest equivalent to what other languages would >> call a constructor. > > Nevertheless, __init__ doesn't construct anything. Only if by "construct" you mean "allocate". __init__ starts out with an empty object and brings it to a valid state, therefore "constructing" the object you end up with. That operation is exactly what other languages call a constructor. From thynnus at gNOTmail.com Tue Jan 22 11:33:48 2008 From: thynnus at gNOTmail.com (Thynnus) Date: Tue, 22 Jan 2008 16:33:48 GMT Subject: stdin, stdout, redmon In-Reply-To: <372ff091-2739-4178-bc36-4f8aaffe2972@e23g2000prf.googlegroups.com> References: <4794a5e3$0$9014$426a74cc@news.free.fr> <4794ab22$0$19179$426a74cc@news.free.fr> <4795ba80$0$17176$426a74cc@news.free.fr> <372ff091-2739-4178-bc36-4f8aaffe2972@e23g2000prf.googlegroups.com> Message-ID: On 1/22/2008 8:54 AM, Konstantin Shaposhnikov wrote: > Hi, > > This is Windows bug that is described here: http://support.microsoft.com/default.aspx?kbid=321788 > > This article also contains solution: you need to add registry value: > > HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies > \Explorer > InheritConsoleHandles = 1 (REG_DWORD type) > > Do not forget to launch new console (cmd.exe) after editing registry. > > Alternatively you can use following command > > cat file | python script.py > > instead of > > cat file | python script.py > > Regards, > Konstantin Nice one, Konstantin! I can confirm that adding the registry key solves the problem on XPsp2: -----After adding InheritConsoleHandles DWORD 1 key----- Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. D:\temp>type test3.py | test3.py ['import sys\n', '\n', 'print sys.stdin.readlines ()\n'] D:\temp> The KB article is quite poorly written. Even though it seems to state that issue was 'solved for win2k with sp4, for XP with sp1', and gives no indication that the key is needed after the sp's are applied *even though* it is in fact necessary to the solution. Questions: -Any side effects to look out for? -If the change is relatively benign, should it be part of the install? -Is this worth a documentation patch? If yes to where, and I'll give it a shot. -Thynnus From cptnwillard at gmail.com Thu Jan 17 10:29:28 2008 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Thu, 17 Jan 2008 07:29:28 -0800 (PST) Subject: Is this a bug, or is it me? References: Message-ID: > > You cannot access a class's class variables in it's class-statement > scope, since the name of the type is not bound until after the class > statement is completed. > Thanks for the answer, but then why is there no error with the variable 'TYPES'? This one is accessed first... From sromero at gmail.com Tue Jan 29 12:51:19 2008 From: sromero at gmail.com (Santiago Romero) Date: Tue, 29 Jan 2008 09:51:19 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: Message-ID: > Look at this -- from Python 2.5.1: > > >>> a = [1, 2, 3, 4, 5] > >>> for x in a: > ... if x == 3: > ... a.remove(x) > ... print x Well ... you could use: >>> for i in range(len(a)-1, -1, -1): ... print a[i] ... if a[i] == 3: del a[i] ... 5 4 3 2 1 >>> print a [1, 2, 4, 5] Bye. From bj_666 at gmx.net Thu Jan 10 09:30:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Jan 2008 14:30:19 GMT Subject: Embedding python code into text document question. References: Message-ID: <5umofrF1hs5vpU2@mid.uni-berlin.de> On Thu, 10 Jan 2008 14:10:05 +0100, Thomas Troeger wrote: > I've written a program that parses a string or file for embedded python > commands, executes them and fills in the returned value. The input might > look like this: > > process id: $$return os.getpid()$$ > current date: $$return time.ctime()$$ > superuser: $$ > if os.geteuid(): > return "Yes" > else: > return "No"$$ > > I've tried several solutions using eval, execfile or compile, but none > of those would solve my problem. Does anyone have a solution that works? > Any suggestions? Any help will be appreciated :) My suggestion would be: use one of the many already existing templating systems. Ciao, Marc 'BlackJack' Rintsch From nagle at animats.com Sat Jan 26 15:26:15 2008 From: nagle at animats.com (John Nagle) Date: Sat, 26 Jan 2008 12:26:15 -0800 Subject: Portably killing/signalling another process not supported? In-Reply-To: References: <479b6c58$0$36354$742ec2ed@news.sonic.net> Message-ID: <479b961b$0$36377$742ec2ed@news.sonic.net> Christian Heimes wrote: > John Nagle wrote: >> There doesn't seem to be any way to portably kill another process >> in Python. "os.kill" is Mac/Unix only. The "signal" module only lets >> you send signals to the current process. And the "subprocess" module >> doesn't have a "kill" function. >> >> Subprocess objects really should have a portable "interrupt" or >> "kill" function. They already have "poll" and "wait", which have >> to be implemented differently for different systems; that's the >> logical place for "kill". >> >> Yes, there are nonportable workarounds >> (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462) >> but no portable solution. > > We are looking for somebody to implement a portable and cross platform > implementation of kill() and send_signal() for the subprocess module. > Are you interested in working on a patch for Python 2.6 and 3.0? > Since I use 2.4 and 2.5, I'm interested in something that goes back to at least 2.4. The ActiveState solution above needs C modules that aren't part of the regular CPython distribution, unfortunately. John Nagle From brian at briansmith.org Sun Jan 20 11:09:19 2008 From: brian at briansmith.org (Brian Smith) Date: Sun, 20 Jan 2008 08:09:19 -0800 Subject: HTTP POST uploading large files In-Reply-To: References: Message-ID: <000601c85b7e$d31a4420$0501a8c0@T60> Wolfgang Draxinger wrote: > The problem is, that videos, by nature are rather big files, > however urllib2 wants it's Request objects being prepared > beforehand, which would mean to first load the whole file to memory. Try using mmap. Here is some untested code: map = mmap(file.fileno(), len(file), access=ACCESS_READ) try: data = mmap.read() request = Request(url, data, headers) ... finally: map.close() - Brian From pablo at decode.com.ar Wed Jan 23 18:19:39 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Wed, 23 Jan 2008 21:19:39 -0200 Subject: Increment Variable Name In-Reply-To: <87myqw87lt.fsf@benfinney.id.au> References: <87myqw87lt.fsf@benfinney.id.au> Message-ID: <4797CB8B.3090500@decode.com.ar> Ben Finney wrote: > This has a very bad code smell (...) > > \ `\ _o__) Ben Finney That is forcefulness. (sorry, couldn't resist) From jholg at gmx.de Fri Jan 4 05:43:46 2008 From: jholg at gmx.de (jholg at gmx.de) Date: Fri, 04 Jan 2008 11:43:46 +0100 Subject: adding class functionality, nested scoping Message-ID: <20080104104346.39070@gmx.net> Hi, regarding automatically adding functionality to a class (basically taken from the cookbook recipee) and Python's lexical nested scoping I have a question wrt this code: #----------------- import types # minor variation on cookbook recipee def enhance_method(cls, methodname, replacement): 'replace a method with an enhancement' method = getattr(cls, methodname) def _f(*args, **kwargs): return replacement(method, *args, **kwargs) _f.__name__ = methodname setattr(cls, methodname, types.MethodType(_f, None, cls)) # loop over class dict and call enhance_method() function # for all methods to modify def enhance_all_methods(cls, replacement): for methodname in cls.__dict__: if not methodname.startswith("__"): method = getattr(cls, methodname) def _f(*args, **kwargs): return replacement(method, *args, **kwargs) _f.__name__ = methodname enhance_method(cls, methodname, replacement) # Does not work: all enhanced methods only call the last wrapped originial # method. It seems the name 'method' in the surrounding scope of the # def _(...) function definition only refers to the last loop value(?) def ERRONEOUS_enhance_all_methods(cls, replacement): for methodname in cls.__dict__: if not methodname.startswith("__"): method = getattr(cls, methodname) def _f(*args, **kwargs): return replacement(method, *args, **kwargs) _f.__name__ = methodname setattr(cls, methodname, types.MethodType(_f, None, cls)) class Foo(object): def foo(self, x): print "foo", x def bar(self, x): print "bar", x def logme(method, *args, **kwargs): print "-->", method.__name__, args, kwargs try: return method(*args, **kwargs) finally: print "<--" #enhance_all_methods(Foo, logme) ERRONEOUS_enhance_all_methods(Foo, logme) foo = Foo() foo.foo(2) foo.bar(2) #----------------- ...give this output: >>> foo = Foo() >>> foo.foo(2) --> foo (<__main__.Foo object at 0x1b08f0>, 2) {} foo 2 <-- >>> foo.bar(2) --> foo (<__main__.Foo object at 0x1b08f0>, 2) {} foo 2 <-- >>> So, while using enhance_all_methods() to add functionality does work, ERRONEOUS_enhance_all_methods() does not. Why is this? Is the explanation I tried to give in the code comment on the right track: # Does not work: all enhanced methods only call the last wrapped originial # method. It seems the name 'method' in the surrounding scope of the # def _(...) function definition only refers to the last loop value(?) Thanks for any hint, Holger -- Psssst! Schon vom neuen GMX MultiMessenger geh?rt? Der kann`s mit allen: http://www.gmx.net/de/go/multimessenger?did=10 From ganeshborse at gmail.com Thu Jan 31 05:49:29 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 31 Jan 2008 02:49:29 -0800 (PST) Subject: PyImport_ImportModule("cStringIO") failure with undefined symbol References: Message-ID: <30aeea04-d4bf-4864-a2c4-518311b10677@c23g2000hsa.googlegroups.com> On Jan 11, 9:31?am, "Borse, Ganesh" wrote: > Hi, > Can you please guide me for the following problem? > The call to "PyImport_ImportModule("cStringIO");" is failing with an error of "undefined symbol:PyObject_SelfIter". > > Before importing this module, I am importing only the sys module. > > ? ?Py_SetProgramName("/usr/bin/python"); > ? ?Py_Initialize(); > ? ?char* argv[] = { "python","-v",""}; > ? ?PySys_SetArgv(2,argv); > ? ?PyRun_SimpleString("import sys"); > > ? ?PyObject *modStringIO = NULL; > ? ?// Import cStringIO module > ? ?modStringIO = PyImport_ImportModule("cStringIO"); > > Should I be importing any other additional module(s) to make this import work? > > Please help. > > I am trying to use the function GetPythonErrorMessage provided in this post:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > Thanks in advance for your help. > Regards. ========================================== Function "PyObject_SelfIter" is part of libPython.a. But when library which is linked with libPython.a tries to import cStringIO (which is nothing but dlopen("lib-dynload/cStringIO.so"), ld.so does not find this symbol. So, as a workaround, we can get the cStringIO.so also linked with the library which has linked libPython.a. By this we ensure that PyObject_SelfIter is already resolved in the library. Then at the time of importing cStringIO at runtime, this symbol is already referenced & won't cause problems. From timr at probo.com Thu Jan 3 02:36:56 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 03 Jan 2008 07:36:56 GMT Subject: Choosing a new language References: <20071228162351.f29a3ce4.coolzone@it.dk> Message-ID: Joachim Durchholz wrote: >> Xah Lee wrote: >>> [...] PHP and Perl are practically identical in their >>> high-levelness or expressiveness or field of application (and >>> syntax), > >That must have been a very, very distant point of view with narrowly >squinted eyes. Do you really think so? It seems clear to me that the syntax of PHP was heavily influenced by Perl. PHP lacks the @array and %hash weirdnesses, but most PHP code will work just fine as Perl. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From vfmevm at gmail.com Tue Jan 1 04:45:19 2008 From: vfmevm at gmail.com (vfmevm at gmail.com) Date: Tue, 1 Jan 2008 09:45:19 +0000 (UTC) Subject: M-I,5.Perse cution - cost of the operati on Message-ID: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -= MI5: cost of the. operation -= -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Here's what a couple of other people on Usenet (uk.misc) had to. say regarding the cost. of running such an operation... PO: >Have some sense, grow up. and smell reality. What you are talking about PO: >would take loads of planning, tens of thousands of pounds and. lots of PO: >people involved. in the planning, execution and maintenance of it. You PO: >must have a very high opinion of yourself to think you are. worth it. PM: >But. why? And why you? Do you realize how much it would cost to keep PM: >one person under continuous. surveillance for five years? Think about PM: >all the man/hours. Say they. _just_ allocated a two man team and a PM:. >supervisor. OK., Supervisor's salary, say, #30,000 a year. Two men, PM: >#20,000 a year each. But. they'd need to work in shifts -- so it would PM: >be six men at #20,000 (which with on-costs would work. out at more like PM: >#30,000 to the. employer.) PM:. > PM: >So, we're talking. #30,000 x 6. #180,000. plus say, #40,000 for the PM: >supervisor. #220,000. Then you've got the hardware involved.. And PM: >any transcription that needs doing. You don't think. the 'Big Boss' PM: >would listen. to hours and hours of tapes, do you. PM:. > PM: >So, all in all, you couldn't actually do. the job for much less than PM: >a quarter million a year. Over five years. What are you doing that. makes PM: >it worth the while of the state to spend over one and a quarter. million PM: >on. you? Those are pretty much the sort of calculations that went through. my head once I stopped to consider what it must be. costing them to run this operation. The partial answer is,. there have been periods when the intensity. has been greater, and times when little has happened. In fact, for. much of 1993 and the first half of 1994, very little happened. Although I. don't think that was for reasons of money - if they can tap into the taxpayer they're not going to be short of resources,. are they? The more complete answer is in the enormity of what. they're doing. Relative to the cost to British pride of seeing their country humiliated. for the persecution of their own citizens, isn't is worth the. cost of four or five people to try. to bring things to a close in the manner they would wish? To the government a million or. two is quite honestly nothing - if they can convince themselves of the necessity of what. they're doing, resources will not be the limiting. factor. 7633 From sjmachin at lexicon.net Tue Jan 29 17:49:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 29 Jan 2008 14:49:31 -0800 (PST) Subject: Removing Pubic Hair Methods References: <878x28e0u1.fsf@benfinney.id.au> Message-ID: <32f6097f-9d77-4005-b05c-30d857b83074@e23g2000prf.googlegroups.com> On Jan 30, 9:14 am, Ben Finney wrote: > xiko... at yahoo.com.tw writes: > > Shaving is the most common removing pubic hair method. However, it > > is not the only one. > > Clearly you haven't done the Python tutorial, otherwise you'd realise > there's no distinction between pubic methods and privy methods. > > Also, there's one, and preferably only one, obvious way to do it:: > > >>> del foo.hair > Brazilians allegedly have some expertise in this area -- the OP could try comp.lang.lua From timr at probo.com Thu Jan 3 02:32:37 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 03 Jan 2008 07:32:37 GMT Subject: Choosing a new language References: <20071228162351.f29a3ce4.coolzone@it.dk> <81737bc2-99df-4295-b894-19d3ba47662e@c4g2000hsg.googlegroups.com> Message-ID: <1m3pn3pntfj99vd85gedvplrlonv96p1ea@4ax.com> kevin cline wrote: > >As if there were such a thing as an 'Ada programmer'. Any decent >programmer should be productive in Ada long before their security >clearance is approved. That's only true because the security clearance process has become so complicated. Ada is not a trivial language by any means. Even an experienced C programmer is going to find enough sharp edges to send him back to the reference manuals on a regular basis. >The real problem the DoD has is that defense work is not attractive to >the best and brightest. Bull crap. You don't HEAR about them because of that same security clearance issue, but some of the most complicated and certainly some of the LARGEST computing systems in the world come out of the DoD. You don't create reliable large systems using a corral full of bright-eyed college new hires. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From deets at nospam.web.de Mon Jan 28 10:27:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jan 2008 16:27:31 +0100 Subject: Encryption Recommendation References: <6b40b773-8554-4e9c-838f-e6934212d16e@n20g2000hsh.googlegroups.com> Message-ID: <606aj3F1pa0tfU1@mid.uni-berlin.de> rogerrath2 at gmail.com wrote: > Hello - > > I'm still using Python 2.4. In my code, I want to encrypt a password > and at another point decrypt it. What is the standard way of doing > encryption in python? Is it the Pycrypto module? Usually, one doesn't store clear-text passwords. Instead, use a hash-algorithm like md5 or crypt (the former is in the standard lib, don't know of the other out of my head) and hash the password, and store that hash. If a user enters the password, use the same algorithm, and compare the resulting hashes with the stored one. Diez From asmodai at in-nomine.org Thu Jan 3 08:58:19 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 3 Jan 2008 14:58:19 +0100 Subject: reassign to builtin possible !? In-Reply-To: References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> Message-ID: <20080103135819.GN67953@nexus.in-nomine.org> -On [20080103 14:47], Bernhard Merkle (bernhard.merkle at googlemail.com) wrote: >Are you sure ? what about the following example ? >Is this also shadowing ? It is, as it is local to your current executing interpreter. Any other Python process that is currently running is unaffected by your shadowing. So as Diez says, you are not tampering with it on a persistent global level. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Any fool can make a rule. And every fool will mind it... From doug.farrell at gmail.com Wed Jan 16 14:30:00 2008 From: doug.farrell at gmail.com (writeson) Date: Wed, 16 Jan 2008 11:30:00 -0800 (PST) Subject: handlers.SocketHandler and exceptions Message-ID: <02de2e9c-331d-45c0-afaa-578ddad55664@j78g2000hsd.googlegroups.com> Hi all, On our Linux systems at work I've written a Twisted logging server that receives log messages from multiple servers/processes to post them to a log file, essentially serializing all the process log messages. This works well, that is until I tried this test code: try: t = 10 / 0 except Exception, e: log.exception("divide by zero") where log is the logger instance retreived from a call to getLogger(). The problem is the handlers.SocketHandler tries to cPickle.dump() the log record, which in this case contains an exc_info tuple, the last item of which is a Traceback object. The pickling fails with an "unpickleable error" and that's that. Does anyone have any ideas how to handle this situation? I'd hate to have to give up using the log.exception(...) call as it's useful to get strack trace information in the log file. Thanks in advance, Doug Farrell From aezell at gmail.com Mon Jan 21 22:06:47 2008 From: aezell at gmail.com (Alex Ezell) Date: Mon, 21 Jan 2008 21:06:47 -0600 Subject: read files In-Reply-To: <47955C65.8080604@block.duxieweb.com> References: <47955C65.8080604@block.duxieweb.com> Message-ID: <71dd7f400801211906v17e383a1m34cfa9187ed8d9c3@mail.gmail.com> You might could do one of these two methods: fd.readlines() or: for line in fd: print line These are both from the Python tutorial found here: http://docs.python.org/tut/node9.html#SECTION009210000000000000000 /alex On Jan 21, 2008 9:00 PM, J. Peng wrote: > first I know this is the correct method to read and print a file: > > fd = open("/etc/sysctl.conf") > done=0 > while not done: > line = fd.readline() > if line == '': > done = 1 > else: > print line, > > fd.close() > > > I dont like that flag of "done",then I tried to re-write it as: > > fd = open("/etc/sysctl.conf") > while line = fd.readline(): > print line, > fd.close() > > > this can't work.why? > -- > http://mail.python.org/mailman/listinfo/python-list > From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 15 05:10:53 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 15 Jan 2008 11:10:53 +0100 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> Message-ID: <478c868a$0$7040$426a34cc@news.free.fr> Jaimy Azle a ?crit : > wrote: > >>>> fact 1: CPython compiles source code to byte-code. >>>> fact 2: CPython executes this byte-code. >>>> fact 3: Sun's JDK compiles source code to byte-code. >>>> fact 4: Sun's JDK executes this byte-code. >>> Fact 4 is misleading because it is only one option available to Sun's >>> JDK. Sun's JDK is also capable of transforming the byte-code to >>> native code and letting the processor execute that instead of the >>> original byte code, and that is where the most significant speed >>> increase comes from. Most importantly, it does so automatically, by >>> default, with no programmer intervention or configuration, and with >>> 100% compatibility, so it doesn't compare well to Python accelerators >>> like psyco. >> Then fact 1 is misleading too since Python handles the compilation >> automatically without programmer's intervention while Java requires >> someone to explicitely invoke the byte-code compiler. >> > > Sadly it is true also, I read somewhere this silly point was used also to > make distinction between java and python, then claiming python is just like > another interpreter, while java has it's own (what they call as) 'compiler'. > :) > > perhaps in the future another sillly point could be added also, Java has > Jython, while Python doesn't have some thing like PyJava or... perhaps Py-va > (Python based Java Language). Lol. At least some common sens in this stupid thread. Thanks Jaimy, you made my day !-) > Salam, Peace. PS : and BTW : my apologies to the community - I should have made my point only once and then shut up. Sorry. From __peter__ at web.de Fri Jan 18 17:27:58 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jan 2008 23:27:58 +0100 Subject: Is this a bug, or is it me? References: <87myr4o3sg.fsf@mulj.homelinux.net> <8afa3779-6803-43ed-ae4d-d0a102eda00d@x69g2000hsx.googlegroups.com> Message-ID: cptnwillard wrote: > I filed a bug report, and here is the short answer to my question: > genexps are code blocks, and code blocks cannot see variables in class > scopes. Congrats to Neil Cerutti who figured it out. > > Now here is another one for your enjoyment: > > class C: > @staticmethod > def f1(): pass > F = { '1' : f1 } > > C().F['1']() > >>>> TypeError: 'staticmethod' object is not callable > > > What do you think of this one? If you want it to be callable you can subclass: >>> class static(staticmethod): ... def __call__(self, *args, **kw): ... return self.__get__(object)(*args, **kw) ... >>> class A(object): ... @static ... def f(x="yadda"): print x ... f() ... yadda >>> A.f() yadda >>> A().f() yadda Peter From martin at v.loewis.de Mon Jan 7 18:06:28 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 Jan 2008 00:06:28 +0100 Subject: Does PIL work with Tk 8.5? In-Reply-To: <2870$4782a5c4$4275d90a$673@FUSE.NET> References: <2870$4782a5c4$4275d90a$673@FUSE.NET> Message-ID: <4782B074.8080709@v.loewis.de> > Since Python itself is the same version number (2.5.1), the only thing I > can find to account for the crash is the different version of Tk--could > this be making a difference, or am I doing something wrong? Yes, Tk 8.5 isn't quite compatible with existing Tkinter code; there have been a lot of changes which break Tkinter applications (though not Tkinter itself). OTOH, it's more likely that the PIL binaries you are using conflict with your Tk installation - if the binaries were for Tk 8.4 (which isn't quite clear to me whether that's indeed the case), then they can't work with Tk 8.5, as Tk doesn't provide that kind of binary compatibility. Regards, Martin From marcroy.olsen at gmail.com Wed Jan 23 10:16:34 2008 From: marcroy.olsen at gmail.com (marcroy.olsen at gmail.com) Date: Wed, 23 Jan 2008 07:16:34 -0800 (PST) Subject: Lxml on mac Message-ID: Hi, What to one do if one what to use lxml(http://codespeak.net/lxml/ index.html) on a mac? Best regards From arnodel at googlemail.com Thu Jan 31 17:45:51 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 31 Jan 2008 14:45:51 -0800 (PST) Subject: helper function in a class' namespace References: <47a226bb$0$2982$ba620e4c@news.skynet.be> <47a22a17$0$8306$9b622d9e@news.freenet.de> <13q4jg6edfvi970@corp.supernews.com> Message-ID: On Jan 31, 10:39?pm, Steven D'Aprano wrote: > On Thu, 31 Jan 2008 20:05:44 +0000, Stargaming wrote: > > String concatenation is generally considered unpythonic, better use > > string interpolation:: > > > ? ? 'H> %s' % (M,) [...] > Also, the tuple above is totally unnecessary. 'H> %s' % M will work fine. ...except if M is a tuple: >>> M = 'spam', 'eggs' >>> 'H> %s' % (M,) "H> ('spam', 'eggs')" >>> 'H> %s' % M Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting Pedantically yours, -- Arnaud From Russ.Paielli at gmail.com Sun Jan 27 23:44:43 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 20:44:43 -0800 (PST) Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: <790eec65-c7dc-4a5e-bc1b-f9138d18eae0@1g2000hsl.googlegroups.com> On Jan 27, 5:41 pm, Roy Smith wrote: > In article > , > > > > ajaksu wrote: > > On Jan 27, 10:32 pm, Paddy wrote: > > > I would value the opinion of fellow Pythoneers who have also > > > contributed to Wikipedia, on the issue of "Is Python Standardized". > > > Specifically in the context of this table: > > > http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Gene... > > > (Comparison of programming languages) > > > And this entry in the talk page > > > http://en.wikipedia.org/wiki/Talk:Comparison_of_programming_languages... > > > (Talk:Comparison of programming languages#Standardized Python?) > > > > - Thanks. > > > Hmmm. Seems to me that "Is X Standardized" in the given context means > > having a formal, published standard issued by some Standards > > organization. > > That's exactly what it means. For example, if I'm buying a C++ compiler, I > can specify in the contract, "Must comply with ISO 14882", and everybody > will know what I'm talking about. > > On the other side of the fence, if I'm a free-lance C++ developer, I can > specify to my customers that the code I write will work properly when > compiled with a compiler that meets ISO 14882. Whether such a compiler > actually exists, is besides the point :-) > > Python has no such standard. Sure, there's the stuff on docs.python.org, > but it's kind of hard to write a contract which says, "Must comply with the > stuff on docs.python.org", and have it be meaningful in a legal sense. > > So, I think the "No" in the "Standardized?" column for python is exactly > right. That's not to say you can't have something good which isn't > standardized. Sometimes standards committees even go off into left field > and field break stuff in the process of standardizing it. Some things have > so many different standards (i.e. the pletora of unix standards), it's > almost worthless to say it's standardized. But, as it stands, the > Wikipedia article is correct. I agree. As far as I know, Python is not formally "standardized" by any recognized standards authority such as ANSI or ISO. (If it were, it wouldn't have a "BDFL.") For most domains in which Python is used, that is not an issue, but for some potential uses it could be (e.g., safety-critical). FWIW, the "most" standardized language is probably Ada. Not only does it have a formal written standard, but I believe it also has a formal suite of tests that a standard Ada compiler is required to pass. [For some reason, Ada does not get the respect or the attention it deserves, but that's another topic.] From radiosrfun at radiosrfun.com Sat Jan 12 14:00:16 2008 From: radiosrfun at radiosrfun.com (radiosrfun) Date: Sat, 12 Jan 2008 14:00:16 -0500 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> <4788de48$0$26887$ecde5a14@news.coretel.net> Message-ID: <47890e3e$0$26886$ecde5a14@news.coretel.net> "ChairmanOfTheBored" wrote in message news:batho35a2r7pog5n67ajc1dpta4g5qt3k9 at 4ax.com... > On Sat, 12 Jan 2008 10:35:38 -0500, "radiosrfun" > wrote: > >>"default" wrote in message >>news:91hho3tr56dpsfqsav4lnr8sl944bbrviv at 4ax.com... >>> On Sat, 12 Jan 2008 02:01:09 -0500, "radiosrfun" >>> wrote: >>> >>>>I WISH - that the President and Congress of this country would shut off >>>>ALL >>>>foreign aid. >>> >>> Ditto that. >>> >>> Israel is the chief beneficiary of our foreign aid largesse. Some 8 >>> billion dollars annually. What doesn't find its way into politicians >>> pockets goes to pay for a military that is winning us a lot of new >>> friends in the Arab world. >>> >>> We pay Egypt ~ 2 billion a year in extortion to keep them from >>> attacking Israel. >>> >>> The actually amount Israel receives is not really known to the public. >>> The official numbers read something like 3 billion in aid, and another >>> 5 billion in guaranteed loans - which are turned into grants year >>> after year. This is money we borrow so there's an additional interest >>> burden. >>> >>> Actually when you talk about shutting off "foreign aid" you may be >>> making thermate's point for him. >>> -- >> >>Well - the first cup of coffee hasn't exactly kicked in yet - but I >>believe >>I know what you're saying and if correct - you may have a point there. >> > You are both fucked in the head, coffee or not. He more than you, but > still, you both don't know what you are talking about. > > If we stop giving aid to other nations, we are letting the retarded US > hating bastards win, dipshit. > I'm not so sure I agree there - money or no money - they hate our guts. Case in point - Mushariff. It has long been rumored that Bin-Laden is lurking near by - yet "Mushariff" seems to be too weak in the knees to try to hunt him down or allow us to. If he doesn't have the balls to do it - let us! I am willing to bet - Bin - Laden will eventually cause Mushariff's downfall too. > This nation has to be strong within, DESPITE what we give out. > I couldn't agree with you more! > Some of us are... some of us just want to piss and moan about things > they know nothing about. > I DO know - I'm sick of our tax dollars being blown on every damned "emergency" abroad - and we get kicked in the teeth each and every time - following. > Which do you think both of you fucktards are? None of the above. Chairman - I don't think "anyone" (American) will disagree with you - least of all me - that "WE" need to be strong from "within". The question comes - at what cost? IS it an investment? OR "Black mail"? In some cases - it could be a fine line. I would find it hard to believe that 100% of our money is distributed to those who are "supposed" to get it. I think we would be fooling ourselves to think that. Maybe I don't operate with "all" facts in hand - but up until now - you and I have pretty much been on the same page. Regardless which sentence or paragraph we parted company on - the fact remains - "I" am a U.S.citizen - born and raised here - and tired of the shit from all those piss ants. It is bad enough we have to put up with "crooked" politicians sucking us dry for all they can get - without the rest coming in to play their games. We can agree to disagree with respect to "how" it is done - but we both want to see it "BE" done - for the benefit of this country. You and I - or anyone else can debate this in a friendly manner - or be pissed off at each other over it - the fact remains - those in charge will do as they please - and we have little say in the matter. Any time some outsider slams this country or our people - it just pisses me off - which is why I bothered to reply to this thread at all. Whether we agree on "tactics" or not - if it come to a battlefield with the two of us - or any Americans there - we're still going to fight the same enemy - not each other. From python.list at tim.thechases.com Tue Jan 8 10:53:07 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 08 Jan 2008 09:53:07 -0600 Subject: stupid/style/list question In-Reply-To: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> References: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> Message-ID: <47839C63.3050001@tim.thechases.com> > To flush a list it is better doing "del mylist[:]" or "mylist = []"? > Is there a preferred way? If yes, why? It depends on what you want. The former modifies the list in-place while the latter just reassigns the name "mylist" to point to a new list within the local scope as demonstrated by this: def d1(mylist): "Delete in place" del mylist[:] def d2(mylist): "Just reassign" mylist = [] for test in [d1,d2]: input = [1,2,3] print 'Before:', input print test.__doc__ test(input) print 'After:', input print As performance goes, you'd have to test it, but I suspect it's not a glaring difference, and would suspect that the latter is a bit faster. -tkc From gagsl-py2 at yahoo.com.ar Tue Jan 29 18:28:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jan 2008 21:28:44 -0200 Subject: Decision (if, else) routine is not working as intended with CGI module References: <9dc9f5d3-2392-48d6-8cb4-8b31c1ce4af9@e6g2000prf.googlegroups.com> Message-ID: En Tue, 29 Jan 2008 18:23:41 -0200, epsilon escribi?: > I'm running into trouble figuring this one out. It seems that my > decision routine is not working as intended. Does anyone know why my > output continues to utilize the "else" portion of the routine. > > tag_form = cgi.FieldStorage(keep_blank_values=True) > > #if not tag_form.has_key("fse00"): > if tag_form["fse00"] == "": tag_form["fse00"] is a FieldStorage instance, not a string. To get its value, use: if tag_form["fse00"].value == "" if tag_form.getvalue("fse00")=="" if tag_form.getfirst("fse00")=="" See http://docs.python.org/lib/module-cgi.html -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Thu Jan 31 00:44:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 31 Jan 2008 05:44:08 -0000 Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> <9275bfdb-8f07-4c63-abbf-40c136388bf3@i7g2000prf.googlegroups.com> <87sl0en02e.fsf@benfinney.id.au> Message-ID: <13q2o18fif6ml6b@corp.supernews.com> (Top-posting corrected.) On Wed, 30 Jan 2008 22:38:30 -0500, Sergio Correia wrote: > On Jan 30, 2008 10:30 PM, Ben Finney > wrote: >> MRAB writes: >> >> > On Jan 31, 12:57 am, Asun Friere wrote: >> > > Ouch!! If on the other hand 'females' is populated by instances of >> > > (or merely includes instances of) class 'Human', I suggest you test >> > > for female.consent somewhere in your code! >> > > >> > The Pythonic approach would be to try the action and catch a >> > NoConsentException. >> >> You're making the classic Pythonista mistake: you behave as though EAFP >> applies everywhere. I assure you, in the above situation, it does not >> apply. > > So in this case it is REALLY better to ask for permission rather than > forgiveness? Oh yes. The NoConsentException has a number of extremely unpleasant side- effects on both the code that raises it and the code that catches it. -- Steven From aahz at pythoncraft.com Fri Jan 18 09:42:17 2008 From: aahz at pythoncraft.com (Aahz) Date: 18 Jan 2008 06:42:17 -0800 Subject: Some Berkeley DB questions (being maintained? queries?) References: <0ba30836-8e2d-4061-94ea-ccddb24bc290@s19g2000prg.googlegroups.com> <003601c85904$904150c0$0401a8c0@T60> Message-ID: In article , Terry Jones wrote: > >I'm also interested in any ongoing or planned work on the Python interface. Someone recently volunteered to take over primary maintenance, but I can't find the mailing list post. -- 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 jarausch at igpm.rwth-aachen.de Tue Jan 15 06:19:41 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 15 Jan 2008 12:19:41 +0100 Subject: common problem - elegant solution sought In-Reply-To: <5v3gg1F1kkla5U1@mid.dfncis.de> References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <5v3j6fF1kcmmvU1@mid.dfncis.de> Thanks to you all for your help. The solution to regenerate the list skipping the one to be deleted is fine for me since my lists are of moderate size and the operation is infrequent. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From milusi.pysiaczek at buziaczek.pl Fri Jan 4 10:51:40 2008 From: milusi.pysiaczek at buziaczek.pl (Artur M. Piwko) Date: Fri, 4 Jan 2008 15:51:40 +0000 (UTC) Subject: What's the limit of variables size in pyhton? References: <5673329f-2269-4696-837b-079ef041fc3c@j20g2000hsi.googlegroups.com> <6fa8f652-3893-4132-8f6a-519bea467d88@t1g2000pra.googlegroups.com> Message-ID: In the darkest hour on Mon, 31 Dec 2007 20:53:28 -0200, Gabriel Genellina screamed: >> Is that mean that i can deal with files with size more than 2GB only >> if the available memory allow > > To be more precise, that depends on the OS. On Windows there is a limit of > 2GB adressable memory per process (this is unrelated to the amount of > physical memory). That's the 32bit Windows limit only (afaik). -- [ Artur M. Piwko : Pipen : AMP29-RIPE : RLU:100918 : From == Trap! : SIG:240B ] [ 16:51:04 user up 11576 days, 4:46, 1 user, load average: 0.97, 0.71, 0.01 ] No wonder people are so horrible when they start life as children. -- K. Amis From washakie at gmail.com Tue Jan 15 06:27:31 2008 From: washakie at gmail.com (washakie) Date: Tue, 15 Jan 2008 03:27:31 -0800 (PST) Subject: MySQL-python-1.2.2 install with no mysql In-Reply-To: References: <14836669.post@talk.nabble.com> Message-ID: <14837853.post@talk.nabble.com> Okay, I've installed mysql then using yum... it installed the same version running on another machine with identical python where all works well... but now I get this error during build... thoughts?!?? mysql_config is there, and the site.cfg file is pointing correctly to it... : [root@ MySQL-python-1.2.2]# python setup.py build running build running build_py copying MySQLdb/release.py -> build/lib.linux-i686-2.4/MySQLdb running build_ext building '_mysql' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC -fPIC -Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/usr/include/mysql -I/usr/include/python2.4 -c _mysql.c -o build/temp.linux-i686-2.4/_mysql.o -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing -fwrapv _mysql.c:35:23: error: my_config.h: No such file or directory _mysql.c:40:19: error: mysql.h: No such file or directory _mysql.c:41:26: error: mysqld_error.h: No such file or directory _mysql.c:42:20: error: errmsg.h: No such file or directory _mysql.c:78: error: expected specifier-qualifier-list before ?MYSQL? _mysql.c:92: error: expected specifier-qualifier-list before ?MYSQL_RES? _mysql.c: In function ?_mysql_Exception?: _mysql.c:122: warning: implicit declaration of function ?mysql_errno? _mysql.c:122: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:125: error: ?CR_MAX_ERROR? undeclared (first use in this function) _mysql.c:125: error: (Each undeclared identifier is reported only once _mysql.c:125: error: for each function it appears in.) _mysql.c:133: error: ?CR_COMMANDS_OUT_OF_SYNC? undeclared (first use in this function) _mysql.c:134: error: ?ER_DB_CREATE_EXISTS? undeclared (first use in this function) _mysql.c:135: error: ?ER_SYNTAX_ERROR? undeclared (first use in this function) _mysql.c:136: error: ?ER_PARSE_ERROR? undeclared (first use in this function) _mysql.c:137: error: ?ER_NO_SUCH_TABLE? undeclared (first use in this function) _mysql.c:138: error: ?ER_WRONG_DB_NAME? undeclared (first use in this function) _mysql.c:139: error: ?ER_WRONG_TABLE_NAME? undeclared (first use in this function) _mysql.c:140: error: ?ER_FIELD_SPECIFIED_TWICE? undeclared (first use in this function) _mysql.c:141: error: ?ER_INVALID_GROUP_FUNC_USE? undeclared (first use in this function) _mysql.c:142: error: ?ER_UNSUPPORTED_EXTENSION? undeclared (first use in this function) _mysql.c:143: error: ?ER_TABLE_MUST_HAVE_COLUMNS? undeclared (first use in this function) _mysql.c:172: error: ?ER_DUP_ENTRY? undeclared (first use in this function) _mysql.c:215: warning: implicit declaration of function ?mysql_error? _mysql.c:215: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:215: warning: passing argument 1 of ?PyString_FromString? makes pointer from integer without a cast _mysql.c: In function ?_mysql_server_init?: _mysql.c:310: warning: label ?finish? defined but not used _mysql.c:236: warning: unused variable ?item? _mysql.c:235: warning: unused variable ?groupc? _mysql.c:235: warning: unused variable ?i? _mysql.c:235: warning: unused variable ?cmd_argc? _mysql.c:234: warning: unused variable ?s? _mysql.c: In function ?_mysql_ResultObject_Initialize?: _mysql.c:365: error: ?MYSQL_RES? undeclared (first use in this function) _mysql.c:365: error: ?result? undeclared (first use in this function) _mysql.c:370: error: ?MYSQL_FIELD? undeclared (first use in this function) _mysql.c:370: error: ?fields? undeclared (first use in this function) _mysql.c:379: error: ?_mysql_ResultObject? has no member named ?use? _mysql.c:382: warning: implicit declaration of function ?mysql_use_result? _mysql.c:382: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:384: warning: implicit declaration of function ?mysql_store_result? _mysql.c:384: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:385: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:388: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:391: warning: implicit declaration of function ?mysql_num_fields? _mysql.c:392: error: ?_mysql_ResultObject? has no member named ?nfields? _mysql.c:393: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:394: warning: implicit declaration of function ?mysql_fetch_fields? _mysql.c:438: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c: In function ?_mysql_ResultObject_traverse?: _mysql.c:450: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:451: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c: In function ?_mysql_ResultObject_clear?: _mysql.c:462: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:462: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:462: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:462: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:463: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c: In function ?_mysql_ConnectionObject_Initialize?: _mysql.c:475: error: ?MYSQL? undeclared (first use in this function) _mysql.c:475: error: ?conn? undeclared (first use in this function) _mysql.c:484: error: ?MYSQL_PORT? undeclared (first use in this function) _mysql.c:500: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:501: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:524: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:546: warning: implicit declaration of function ?mysql_init? _mysql.c:546: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:549: warning: implicit declaration of function ?mysql_options? _mysql.c:549: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:549: error: ?MYSQL_OPT_CONNECT_TIMEOUT? undeclared (first use in this function) _mysql.c:553: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:553: error: ?MYSQL_OPT_COMPRESS? undeclared (first use in this function) _mysql.c:554: error: ?CLIENT_COMPRESS? undeclared (first use in this function) _mysql.c:557: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:557: error: ?MYSQL_OPT_NAMED_PIPE? undeclared (first use in this function) _mysql.c:559: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:559: error: ?MYSQL_INIT_COMMAND? undeclared (first use in this function) _mysql.c:561: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:561: error: ?MYSQL_READ_DEFAULT_FILE? undeclared (first use in this function) _mysql.c:563: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:563: error: ?MYSQL_READ_DEFAULT_GROUP? undeclared (first use in this function) _mysql.c:566: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:566: error: ?MYSQL_OPT_LOCAL_INFILE? undeclared (first use in this function) _mysql.c:574: warning: implicit declaration of function ?mysql_real_connect? _mysql.c:574: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:589: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c: In function ?_mysql_ConnectionObject_traverse?: _mysql.c:670: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:671: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c: In function ?_mysql_ConnectionObject_clear?: _mysql.c:679: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:679: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:679: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:679: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:680: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c: In function ?_mysql_ConnectionObject_close?: _mysql.c:695: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:697: warning: implicit declaration of function ?mysql_close? _mysql.c:697: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:699: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c: In function ?_mysql_ConnectionObject_affected_rows?: _mysql.c:721: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:722: warning: implicit declaration of function ?mysql_affected_rows? _mysql.c:722: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_debug?: _mysql.c:738: warning: implicit declaration of function ?mysql_debug? _mysql.c: In function ?_mysql_ConnectionObject_dump_debug_info?: _mysql.c:756: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:758: warning: implicit declaration of function ?mysql_dump_debug_info? _mysql.c:758: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_autocommit?: _mysql.c:782: warning: implicit declaration of function ?mysql_query? _mysql.c:782: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_commit?: _mysql.c:805: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_rollback?: _mysql.c:827: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_errno?: _mysql.c:939: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:940: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_error?: _mysql.c:955: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:956: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:956: warning: passing argument 1 of ?PyString_FromString? makes pointer from integer without a cast _mysql.c: In function ?_mysql_escape_string?: _mysql.c:980: warning: implicit declaration of function ?mysql_escape_string? _mysql.c: In function ?_mysql_escape?: _mysql.c:1087: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c: In function ?_mysql_ResultObject_describe?: _mysql.c:1167: error: ?MYSQL_FIELD? undeclared (first use in this function) _mysql.c:1167: error: ?fields? undeclared (first use in this function) _mysql.c:1170: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1171: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1172: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1183: warning: implicit declaration of function ?IS_NOT_NULL? _mysql.c: In function ?_mysql_ResultObject_field_flags?: _mysql.c:1203: error: ?MYSQL_FIELD? undeclared (first use in this function) _mysql.c:1203: error: ?fields? undeclared (first use in this function) _mysql.c:1206: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1207: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1208: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: At top level: _mysql.c:1249: error: expected declaration specifiers or ?...? before ?MYSQL_ROW? _mysql.c: In function ?_mysql_row_to_tuple?: _mysql.c:1255: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1257: warning: implicit declaration of function ?mysql_fetch_lengths? _mysql.c:1257: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1257: warning: assignment makes pointer from integer without a cast _mysql.c:1260: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:1261: error: ?row? undeclared (first use in this function) _mysql.c: At top level: _mysql.c:1274: error: expected declaration specifiers or ?...? before ?MYSQL_ROW? _mysql.c: In function ?_mysql_row_to_dict?: _mysql.c:1279: error: ?MYSQL_FIELD? undeclared (first use in this function) _mysql.c:1279: error: ?fields? undeclared (first use in this function) _mysql.c:1281: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1283: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1283: warning: assignment makes pointer from integer without a cast _mysql.c:1284: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1287: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:1288: error: ?row? undeclared (first use in this function) _mysql.c: At top level: _mysql.c:1313: error: expected declaration specifiers or ?...? before ?MYSQL_ROW? _mysql.c: In function ?_mysql_row_to_dict_old?: _mysql.c:1318: error: ?MYSQL_FIELD? undeclared (first use in this function) _mysql.c:1318: error: ?fields? undeclared (first use in this function) _mysql.c:1320: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1322: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1322: warning: assignment makes pointer from integer without a cast _mysql.c:1323: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1326: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:1327: error: ?row? undeclared (first use in this function) _mysql.c: At top level: _mysql.c:1349: error: expected declaration specifiers or ?...? before ?MYSQL_ROW? _mysql.c: In function ?_mysql__fetch_row?: _mysql.c:1360: error: ?MYSQL_ROW? undeclared (first use in this function) _mysql.c:1360: error: expected ?;? before ?row? _mysql.c:1364: error: ?_mysql_ResultObject? has no member named ?use? _mysql.c:1365: error: ?row? undeclared (first use in this function) _mysql.c:1365: warning: implicit declaration of function ?mysql_fetch_row? _mysql.c:1365: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1368: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:1371: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1379: error: too many arguments to function ?convert_row? _mysql.c: In function ?_mysql_ResultObject_fetch_row?: _mysql.c:1403: error: expected declaration specifiers or ?...? before ?MYSQL_ROW? _mysql.c:1418: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1430: error: ?_mysql_ResultObject? has no member named ?use? _mysql.c:1444: warning: implicit declaration of function ?mysql_num_rows? _mysql.c:1444: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ConnectionObject_character_set_name?: _mysql.c:1511: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c: In function ?_mysql_get_client_info?: _mysql.c:1602: warning: implicit declaration of function ?mysql_get_client_info? _mysql.c:1602: warning: passing argument 1 of ?PyString_FromString? makes pointer from integer without a cast _mysql.c: In function ?_mysql_ConnectionObject_get_host_info?: _mysql.c:1616: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1617: warning: implicit declaration of function ?mysql_get_host_info? _mysql.c:1617: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1617: warning: passing argument 1 of ?PyString_FromString? makes pointer from integer without a cast _mysql.c: In function ?_mysql_ConnectionObject_get_proto_info?: _mysql.c:1631: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1632: warning: implicit declaration of function ?mysql_get_proto_info? _mysql.c:1632: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_get_server_info?: _mysql.c:1646: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1647: warning: implicit declaration of function ?mysql_get_server_info? _mysql.c:1647: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1647: warning: passing argument 1 of ?PyString_FromString? makes pointer from integer without a cast _mysql.c: In function ?_mysql_ConnectionObject_info?: _mysql.c:1663: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1664: warning: implicit declaration of function ?mysql_info? _mysql.c:1664: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1664: warning: assignment makes pointer from integer without a cast _mysql.c: In function ?_mysql_ConnectionObject_insert_id?: _mysql.c:1696: error: ?my_ulonglong? undeclared (first use in this function) _mysql.c:1696: error: expected ?;? before ?r? _mysql.c:1698: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1700: error: ?r? undeclared (first use in this function) _mysql.c:1700: warning: implicit declaration of function ?mysql_insert_id? _mysql.c:1700: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_kill?: _mysql.c:1717: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1719: warning: implicit declaration of function ?mysql_kill? _mysql.c:1719: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_field_count?: _mysql.c:1738: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1740: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ResultObject_num_fields?: _mysql.c:1755: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1756: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ResultObject_num_rows?: _mysql.c:1771: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1772: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ConnectionObject_ping?: _mysql.c:1801: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1802: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1804: warning: implicit declaration of function ?mysql_ping? _mysql.c:1804: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_query?: _mysql.c:1825: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1827: warning: implicit declaration of function ?mysql_real_query? _mysql.c:1827: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_select_db?: _mysql.c:1855: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1857: warning: implicit declaration of function ?mysql_select_db? _mysql.c:1857: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_shutdown?: _mysql.c:1876: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1878: warning: implicit declaration of function ?mysql_shutdown? _mysql.c:1878: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_stat?: _mysql.c:1903: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1905: warning: implicit declaration of function ?mysql_stat? _mysql.c:1905: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:1905: warning: assignment makes pointer from integer without a cast _mysql.c: In function ?_mysql_ConnectionObject_store_result?: _mysql.c:1926: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1927: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:1936: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ConnectionObject_thread_id?: _mysql.c:1965: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1967: warning: implicit declaration of function ?mysql_thread_id? _mysql.c:1967: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ConnectionObject_use_result?: _mysql.c:1987: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:1988: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:1997: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ConnectionObject_dealloc?: _mysql.c:2015: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c: In function ?_mysql_ConnectionObject_repr?: _mysql.c:2027: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:2028: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c: In function ?_mysql_ResultObject_data_seek?: _mysql.c:2046: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:2047: warning: implicit declaration of function ?mysql_data_seek? _mysql.c:2047: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ResultObject_row_seek?: _mysql.c:2060: error: ?MYSQL_ROW_OFFSET? undeclared (first use in this function) _mysql.c:2060: error: expected ?;? before ?r? _mysql.c:2062: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:2063: error: ?_mysql_ResultObject? has no member named ?use? _mysql.c:2068: error: ?r? undeclared (first use in this function) _mysql.c:2068: warning: implicit declaration of function ?mysql_row_tell? _mysql.c:2068: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:2069: warning: implicit declaration of function ?mysql_row_seek? _mysql.c:2069: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ResultObject_row_tell?: _mysql.c:2081: error: ?MYSQL_ROW_OFFSET? undeclared (first use in this function) _mysql.c:2081: error: expected ?;? before ?r? _mysql.c:2083: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:2084: error: ?_mysql_ResultObject? has no member named ?use? _mysql.c:2089: error: ?r? undeclared (first use in this function) _mysql.c:2089: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c:2090: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: In function ?_mysql_ResultObject_dealloc?: _mysql.c:2098: warning: implicit declaration of function ?mysql_free_result? _mysql.c:2098: error: ?_mysql_ResultObject? has no member named ?result? _mysql.c: At top level: _mysql.c:2329: error: ?_mysql_ConnectionObject? has no member named ?open? _mysql.c:2336: error: ?_mysql_ConnectionObject? has no member named ?converter? _mysql.c:2343: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:2350: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:2357: error: ?_mysql_ConnectionObject? has no member named ?connection? _mysql.c:2420: error: ?_mysql_ResultObject? has no member named ?converter? _mysql.c:2420: error: initializer element is not constant _mysql.c:2420: error: (near initialization for ?_mysql_ResultObject_memberlist[0].offset?) _mysql.c: In function ?_mysql_ConnectionObject_getattr?: _mysql.c:2442: error: ?_mysql_ConnectionObject? has no member named ?open? error: command 'gcc' failed with exit status 1 [root@ MySQL-python-1.2.2]# Jarek Zgoda wrote: > > >> >> How can I install MySQL-python-1.2.2 without installing MySQL??? > > In short: without installing client libraries you cann't. > > -- > 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 > > &-(&-( -- View this message in context: http://www.nabble.com/MySQL-python-1.2.2-install-with-no-mysql-tp14836669p14837853.html Sent from the Python - python-list mailing list archive at Nabble.com. From bearophileHUGS at lycos.com Fri Jan 18 19:59:34 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 18 Jan 2008 16:59:34 -0800 (PST) Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> <54efb87e-5a54-42a4-adcc-3d05e03a4859@s8g2000prg.googlegroups.com> <2f5524f1-2a9b-4d04-8b37-15d20940da72@v4g2000hsf.googlegroups.com> Message-ID: ...and just for fun this D code is about 3.2 times faster than the Psyco version for the same dataset (30% lines with a space): import std.stdio, std.conv, std.string, std.stream; int[int] get_hist(string file_name) { int[int] hist; foreach(string line; new BufferedFile(file_name)) { int pos = find(line, ' '); if (pos == -1) hist[toInt(line)]++; else hist[toInt(line[0 .. pos])] += toInt(line[pos+1 .. $]); } return hist; } void main(string[] args) { writefln( get_hist(args[1]).length ); } Bye, bearophile From berlin.brown at gmail.com Mon Jan 14 18:05:01 2008 From: berlin.brown at gmail.com (BerlinBrown) Date: Mon, 14 Jan 2008 15:05:01 -0800 (PST) Subject: Append zip files together, just get the binary data (in memory) References: <53f66038-ccc3-4c3d-97b2-fa5deb148809@d4g2000prg.googlegroups.com> <5v27oiF1kavhlU1@mid.uni-berlin.de> Message-ID: <3c56d5b5-2dfb-4fd7-9a70-8022bd822430@j78g2000hsd.googlegroups.com> On Jan 14, 5:58 pm, "Diez B. Roggisch" wrote: > BerlinBrown schrieb: > > > Is it possible to just build the binary content of a zip file. I want > > to create the content in memory (e.g. return binary data) and then get > > those byte strings representing the zip file? Is that possible? > > > Or could I possibly override functions in the zip class. > > > 1. Create a zip file object (e.g. dont actually create the file). > > 2. Append stuff to the zip file (e.g. a file) > > 3. Zip that content into memory (but still not touching the > > filesystem) > > 4. Extract those byte strings for (an array?) later use. > > > My goal is to concatenate multiple zip files into another binary file. > > Module StringIO is your friend. > > Diez Clearly, someone doesn't know python as well as he should. That is good idea, thanks. So basically treat StringIO as the in memory container to write the zip file data to. From george.sakkis at gmail.com Sat Jan 19 13:14:17 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 19 Jan 2008 10:14:17 -0800 (PST) Subject: Default attribute values pattern Message-ID: A situation that often comes up is having to initialize several instance attributes that accept a default value. For a single class, passing the default values in __init__ is fine: class Base(object): def __init__(self, x=0, y=None): self.x = x self.y = y For inherited classes that need to override __init__ while keeping a compatible interface though, the default values have to be repeated: class Derived(Base): def __init__(self, x=0, y=None, z=''): super(Derived,self).__init__(self,x,y) self.z = '' For just two attributes and two classes that's maybe not too bad but for many attributes and/or derived classes that may span multiple modules, that doesn't seem to scale from a maintenance point of view, especially if the defaults change over time. A pattern I've been using lately instead is store the defaults in class attributes and let __init__ accept keyword arguments: class Base(object): x = 0 y = None def __init__(self, **kwds): setattrs(self, kwds) where setattrs is: def setattrs(self, attrvals, strict=True): if strict: # raise AttributeError if some attr doesn't exist already for attr in attrvals.iterkeys(): getattr(self,attr) for attr,val in attrvals.iteritems(): setattr(self, attr, val) This way, only the new and overriden default attributes have to repeated in derived classes: class Derived(Base): x = 1 z = '' def __init__(self, **kwds): super(Derived,self).__init__(**kwds) print 'In Derived.__init__' Is this a good way of doing it ? Is there a better pattern ? George From tejovathi.p at gmail.com Tue Jan 8 06:04:29 2008 From: tejovathi.p at gmail.com (Teja) Date: Tue, 8 Jan 2008 03:04:29 -0800 (PST) Subject: COM server and EXE References: Message-ID: On Jan 8, 3:33?pm, Teja wrote: > Hi All, > > I have a Python COM server. I need to deploy it on various sytems. > When I run the COM server from > python its showing an output " Registered : sample.lib" > > If I try to use the COM obj from a VB client like: > > obj = CreateObject("sample.lib") > > Its working fine without any errors > > Now I am trying to convert this COM server to an exe through py2exe > and after I run the exe, I am > getting the same output " Registered : sample.lib" > > But If I try to use the COM obj from a VB client like > > obj = CreateObject("sample.lib") > > A console pops up saying " Registered : sample.lib" and VB application > hangs there. > Its throwing a VB error that "ActiveX object cannot be > created......etc etc" > > Any suggestions please....... > > Regards, > Tejovathi Here is my sample COM server and py2exe setup file testCOM.py import win32com.client import os.path import shutil from win32api import Sleep import string import os import sys import pythoncom class FirstEx: _reg_clsid_ = "{A6DE9DF8-5EBF-48E6-889E-C71CB84CFF2C}" pythoncom.frozen = 1 if hasattr(sys, 'importers'): # In the py2exe-packed version, specify the module.class # to use. In the python script version, python is able # to figure it out itself. _reg_class_spec_ = "__main__.FirstEx" _reg_desc_ = "My first COM server" _reg_progid_ = "SAMPLE.Lib" _public_methods_ = ['init', 'Version'] _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER def __init__(self): self.softspace = 1 self.noCalls = 0 def Version(self): self.noCalls = self.noCalls + 1 # insert "softspace" number of spaces return "Version: 0.0.1" if __name__=='__main__': import sys if hasattr(sys, 'importers'): # running as packed executable. if '--register' in sys.argv[1:] or '--unregister' in sys.argv[1:]: # --register and --unregister work as usual import win32com.server.register win32com.server.register.UseCommandLine(FirstEx) else: # start the server. from win32com.server import localserver localserver.main() else: import win32com.server.register win32com.server.register.UseCommandLine(FirstEx) Here is my setup file: #Start here from distutils.core import setup import py2exe setup(options = {"py2exe": {"compressed": 1, "optimize": 2, "ascii": 1, "bundle_files": 1}}, zipfile = None, com_server = ["win32com.servers.interp"], console = ["testCOM.py"]) #End here Here is my VB code: Sub subRoutine() Dim connection As Object Dim returnvalue1 As String Dim returnvalue2 As String Dim flag3 As Boolean Set connection = CreateObject("SAMPLE.Lib") returnvalue1 = connection.Version() MsgBox (returnvalue1) End Sub The non exe version of the COM server ie. directlly running the testCOM.py registers the library properly and in the VB application, the message box displays the version as 0.0.1. But, after I create the EXE file using the setup.py file and run it, it registers the library. When I run the VB application, it hangs at the line Set connection = CreateObject("SAMPLE.Lib") and displays. " ACTIVEX cannot create the object" Any suggestions please.... From bearophileHUGS at lycos.com Tue Jan 15 11:48:30 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 15 Jan 2008 08:48:30 -0800 (PST) Subject: Benchmark [was Re: common problem - elegant solution sought] References: <5v3gg1F1kkla5U1@mid.dfncis.de> <478ccc9e$0$29264$ba620e4c@news.skynet.be> Message-ID: Helmut Jarausch: > The clear winner is > > def del_by_key(L,key) : > for pos, (k,d) in enumerate(L): > if k == key : > del L[pos] > break If you use Psyco this is faster: def del_by_key(L,key): pos = 0 for pair in L: if pair[0] == key : del L[pos] break pos += 1 Bye, bearophile From caca at mailinator.com Sat Jan 5 11:14:46 2008 From: caca at mailinator.com (caca at mailinator.com) Date: Sat, 5 Jan 2008 08:14:46 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> Message-ID: <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> On Jan 5, 5:07 pm, c... at mailinator.com wrote: > Hello, Paul and Arnaud. > While I think about your answers: do you think there is any way to > avoid shuffle? > It may take unnecessary long on a long list most of whose elements > have the property. Umm... You provide nice answers in the case many elements are picked from the same list. Any ideas for the case when the picker is called many times on a program, but never twice with the same list? From jimgardener at gmail.com Sun Jan 6 11:56:14 2008 From: jimgardener at gmail.com (jimgardener at gmail.com) Date: Sun, 6 Jan 2008 08:56:14 -0800 (PST) Subject: how to use bool References: <05c5df8b-15c4-47e6-8c14-72c57a84a0ea@y5g2000hsf.googlegroups.com> <2c516040-0193-4de3-bf7d-b61e739cdc2d@l57g2000hsa.googlegroups.com> Message-ID: some more doubts in this area,,forgive the ignorance of a beginner i have class MyError(Exception): def __init__(self,msg) self.msg=msg now my method that can raise this is class SomeClass: ........... def mymethod(self): if (somecondition): raise MyError("somecondn failed") if another method in the same class calls this method but wants to pass the error to a gui code which calls it,,can i do like this def callingmethode(self): try: mymethod() except MyError,myerr: raise myerr so that I can handle the error in a gui code that calls callingmethode() class MyGUI: def guimethode(self): someinst=SomeClass() try: someinst.callingmethode() except MyError,myer: self.dealwithMyError(myer) is this kind of raising exception the correct way?I am getting syntax error at except MyError,myerr: raise myerr From bignose+hates-spam at benfinney.id.au Fri Jan 18 03:07:51 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 18 Jan 2008 19:07:51 +1100 Subject: array and list References: <87bq7jbwxo.fsf@benfinney.id.au> <13p0b6jbn2ut6b4@corp.supernews.com> Message-ID: <877ii7blpk.fsf@benfinney.id.au> Steven D'Aprano writes: > On Fri, 18 Jan 2008 15:05:23 +1100, Ben Finney wrote: > > In Python, 'list' is a basic built-in type. Python has no 'array' > > type [...] > Did you forget the array module? Yes. -- \ "Always code as if the guy who ends up maintaining your code | `\ will be a violent psychopath who knows where you live." ?John | _o__) F. Woods | Ben Finney From bigblueswope at gmail.com Wed Jan 9 00:40:56 2008 From: bigblueswope at gmail.com (BJ Swope) Date: Wed, 9 Jan 2008 00:40:56 -0500 Subject: Open a List of Files In-Reply-To: <18308.12959.742868.758136@terry.local> References: <874pdomrrd.fsf@mulj.homelinux.net> <18308.12959.742868.758136@terry.local> Message-ID: On Jan 8, 2008 9:34 PM, Terry Jones wrote: > > I think you should revisit this decision. Something like Fredrik's code > is > the way to go. It has multiple advantages: > > - It's much shorter. > - It's arguably easier to add/remove to/from. > - It has less risk of error (much less repetition). > - It allows your code to later take a string file tag and > write to that file by looking up its file descriptor in the dict. > - You can close all open files with a trivial loop. > > Also, if you start writing code like Fredrik's instead of like what you > fell back on you'll make yourself a better programmer (in general, not > just > in Python). > > Terry > Thanks for the advice Terry. With your prompting I went back and looked at the examples and sought to understand them. The results are... #File Creations/Openings def getfilename(host_path, fn): return os.path.join(host_path, '%s.txt' % fn) outfiles_list = ['messages', 'deliveries', 'actions', 'parts', 'recipients', 'viruses', 'esp_scores'] open_files = {} for fn in outfiles_list: open_files[fn] = open(getfilename(host_path, fn), 'wb') #Referring to files to write in various places... open_files['deliveries'].write(flat_line) open_files['deliveries'].write('\n') #And finally to close the opened files for fn in open_files.keys(): open_files[fn].close() I sure am glad I posted this to the list. It is exactly the kind of stuff I was hoping to find. Again, to all who answered, Thank You! BJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Jan 10 13:42:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 19:42:40 +0100 Subject: What is "lambda x=x : ... " ? In-Reply-To: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> Message-ID: zslevi at gmail.com wrote: > #################### > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ################### > > What does "y=y" and "c=c" mean in the lambda function? they bind the argument "y" to the *object* currently referred to by the outer "y" variable. for example, y = 10 f = lambda y=y: return y y = 11 calling f() will return 10 no matter what the outer "y" is set to. in contrast, if you do y = 10 f = lambda: y y = 11 calling f() will return whatever "y" is set to at the time of the call. or in other words, default arguments bind to values, free variables bind to names. > I thought it bounds the outer variables, so I experimented a little > bit: > > ################# > x = 3 > y = lambda x=x : x+10 > > print y(2) > ################## > > It prints 12, so it doesn't bind the variable in the outer scope. it does, but you're overriding the bound value by passing in a value. try: x = 3 y = lambda x=x : x+10 y() x = 10 y() instead. From khoard at gmail.com Wed Jan 30 20:02:18 2008 From: khoard at gmail.com (FireNWater) Date: Wed, 30 Jan 2008 17:02:18 -0800 (PST) Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> Message-ID: <58d1bc12-206f-4cec-ad86-928d16e962f5@i3g2000hsf.googlegroups.com> On Jan 30, 3:09 pm, Berteun Damman wrote: > On Wed, 30 Jan 2008 14:47:36 -0800 (PST), FireNWater wrote: > > I'm curious why the different outputs of this code. If I make the > > dictionary with letters as the keys, they are not listed in the > > dictionary in alphabetical order, but if I use the integers then the > > keys are in numerical order. > > > I know that the order of the keys is not important in a dictionary, > > but I was just curious about what causes the differences. Thanks!! > > I don't know the exact way Python's hash function works, but I can take > a guess. I'm sorry if I explain something you already know. > > A hash is for quickly looking up data. Yet, you don't want to waste too > much memory. So there is a limit number of spaces allocated, in which to > store objects. This number of spaces can be thought of as a list. Then, > if you put something into the dict, Python computes the 'hash' of this > object, which basically forms the index in the list where to store it. > So every object should be mapped onto some index within the list. (If > you retrieve it, the hash is computed again, and the value on that index > is looked up, like list indexing, these are fast operations.) > > Say, if you have 100 spaces, and someone puts in integer in the list, > the hashfunction used might be % 100. So the first 100 integers would > always be placed at consecutive places. For strings however, a more > complicated hash-function would be used, which takes into account more > characters, so strings don't end up in order. > > For integers, if you put in integers that are spread very widely apart, > they won't end up in order either (see the mod 100 example, 104 will > come before 10). > > If you replace the list2 in your example by: > list2 = [10000 * x for x in range(1,9)] > > You will see that this one doesn't end up in order either. So, there's > no exception for integers when it comes to the order, yet the particular > properties of the hash function will cause sequential integers to end up > in order under some circumstances. > > Berteun > > PS: > What happens if two values map onto the same space is of course an > obvious question, and the trick is choosing your hashfunction so this > occurs not very often on average. If it happens there are several > strategies. Wikipedia probably has an explanation of how hash-functions > can work in such a case. Thank you for the explanation. . . I think I now have a (foggy) understanding of hash tables. It seems to be a way to create order (an index) out of disorder (random numbers or characters) behind the scenes. . From lists at cheimes.de Sun Jan 20 08:59:06 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 20 Jan 2008 14:59:06 +0100 Subject: finding memory leak in edgewall trac 0.11 In-Reply-To: <4f9304e4-3847-41ee-8064-b881f7b9e073@f47g2000hsd.googlegroups.com> References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> <0c6fc35d-91d2-4767-968d-e6eb56096eba@z17g2000hsg.googlegroups.com> <4f9304e4-3847-41ee-8064-b881f7b9e073@f47g2000hsd.googlegroups.com> Message-ID: rupert.thurner wrote: > i forgot to mention that i cannot see any explicit sys._getframe(), or > __del__ in the genshi code, while the ones in trac-core seemed to be > there in 0.10.4. Does the code keep a reference to a traceback object or an attribute of a traceback object? Christian From boblatest at yahoo.com Wed Jan 9 05:01:14 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 10:01:14 GMT Subject: "Canonical" way of deleting elements from lists Message-ID: <5ujkbaF1e11ksU1@mid.dfncis.de> Hello, >From a list of strings I want to delete all empty ones. This works: while '' in keywords: keywords.remove('') However, to a long-term C programmer this looks like an awkward way of accomplishing a simple goal, because the list will have to be re-evaluated in each iteration. Is there a way to just walk the list once and throw out unwanted elements as one goes along? I started programming back when such little things were real performance issues, so I have some sort of cringe reflex when something looks inefficient. robert From castironpi at gmail.com Wed Jan 23 21:16:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 23 Jan 2008 18:16:01 -0800 (PST) Subject: Function wrappers Message-ID: def f( callback, *bar, **bkwar ): def preg ( callfore, *far, **fkwar ): return g( callback, callfore, bar, bkwar, far, fkwar ) return preg Does anyone see a way to rewrite this, perhaps along the lines of partial( partial, partial )? Ok to modify 'g' call. From gagsl-py2 at yahoo.com.ar Tue Jan 22 21:50:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 00:50:57 -0200 Subject: Don't want child process inheriting open sockets References: <800886C2A4A73E44BA0FE45152C023702503AD6561@ADSK-NAMSG-02.MGDADSK.autodesk.com> Message-ID: En Tue, 22 Jan 2008 13:02:35 -0200, Steven Watanabe escribi?: > I'm using subprocess.Popen() to create a child process. The child > process is inheriting the parent process' open sockets, but I don't want > that. I believe that on Unix systems I could use the FD_CLOEXEC flag, > but I'm running Windows. Any suggestions? You could use the DuplicateHandle Windows API function with bInheritHandle=False to create a non inheritable socket handle, then close the original one. This should be done for every socket you don't want to be inherited. -- Gabriel Genellina From mensanator at aol.com Mon Jan 7 18:50:57 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 7 Jan 2008 15:50:57 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python References: Message-ID: On Jan 7, 5:10?pm, dgoldsmith_89 wrote: > On Jan 7, 2:54 pm, "mensana... at aol.com" wrote: > > > On Jan 7, 4:37 pm, dgoldsmith_89 wrote: > > > > Can anyone point me to a downloadable open source English dictionary > > > suitable for programmatic use with python: I'm programming a puzzle > > > generator, and I need to be able to generate more or less complete > > > lists of English words, alphabetized. ?Thanks! ?DG > > >www.puzzlers.orghasnumerous word lists & dictionarys in text > > format that can be downloaded. I recommend you insert them into > > some form of database. I have most of them in an Access db and > > it's 95 MB. That's a worse case as I also have some value-added > > stuff, the OSPD alone would be a lot smaller. > > > > > Sorry for my ignorance: I can query an Access DB w/ standard SQL > queries (and this is how I would access it w/ Python)? Yes, if you have the appropriate way to link to the DB. I use Windows and ODBC from Win32. I don't know what you would use on a Mac. As Paul McGuire said, you could easily do this with SqlLite3. Personnaly, I always use Access since my job requires it and I find it much more convenient. I often use Crosstab tables which I think SqlLite3 doesn't support. Typically, I'll write complex queries in Access and simple select SQL statements in Python to grab them. Here's my anagram locator. (the [signature] is an example of the value-added I mentioned). ## I took a somewhat different approach. Instead of in a file, ## I've got my word list (562456 words) in an MS-Access database. ## And instead of calculating the signature on the fly, I did it ## once and added the signature as a second field: ## ## TABLE CONS_alpha_only_signature_unique ## -------------------------------------- ## CONS text 75 ## signature text 26 ## ## The signature is a 26 character string where each character is ## the count of occurences of the matching letter. Luckily, in ## only a single case was there more than 9 occurences of any ## given letter, which turned not to be a word but a series of ## words concatenated so I just deleted it from the database ## (lots of crap in the original word list I used). ## ## Example: ## ## CONS signature ## aah 20000001000000000000000000 # 'a' occurs twice & 'h' once ## aahed 20011001000000000000000000 ## aahing 20000011100001000000000000 ## aahs 20000001000000000010000000 ## aaii 20000000200000000000000000 ## aaker 20001000001000000100000000 ## aal 20000000000100000000000000 ## aalborg 21000010000100100100000000 ## aalesund 20011000000101000010100000 ## ## Any words with identical signatures must be anagrams. ## ## Once this was been set up, I wrote a whole bunch of queries ## to use this table. I use the normal Access drag and drop ## design, but the SQL can be extracted from each, so I can ## simply open the query from Python or I can grab the SQL ## and build it inside the program. The example ## ## signatures_anagrams_select_signature ## ## is hard coded for criteria 9 & 10 and should be cast inside ## Python so the criteria can be changed dynamically. ## ## ## QUERY signatures_anagrams_longest ## --------------------------------- ## SELECT Len([CONS]) AS Expr1, ## Count(Cons_alpha_only_signature_unique.CONS) AS CountOfCONS, ## Cons_alpha_only_signature_unique.signature ## FROM Cons_alpha_only_signature_unique ## GROUP BY Len([CONS]), ## Cons_alpha_only_signature_unique.signature ## HAVING (((Count(Cons_alpha_only_signature_unique.CONS))>1)) ## ORDER BY Len([CONS]) DESC , ## Count(Cons_alpha_only_signature_unique.CONS) DESC; ## ## This is why I don't use SQLite3, must have crosstab queries. ## ## QUERY signatures_anagram_summary ## -------------------------------- ## TRANSFORM Count(signatures_anagrams_longest.signature) AS CountOfsignature ## SELECT signatures_anagrams_longest.Expr1 AS [length of word] ## FROM signatures_anagrams_longest ## GROUP BY signatures_anagrams_longest.Expr1 ## PIVOT signatures_anagrams_longest.CountOfCONS; ## ## ## QUERY signatures_anagrams_select_signature ## ------------------------------------------ ## SELECT Len([CONS]) AS Expr1, ## Count(Cons_alpha_only_signature_unique.CONS) AS CountOfCONS, ## Cons_alpha_only_signature_unique.signature ## FROM Cons_alpha_only_signature_unique ## GROUP BY Len([CONS]), ## Cons_alpha_only_signature_unique.signature ## HAVING (((Len([CONS]))=9) AND ## ((Count(Cons_alpha_only_signature_unique.CONS))=10)) ## ORDER BY Len([CONS]) DESC , ## Count(Cons_alpha_only_signature_unique.CONS) DESC; ## ## QUERY signatures_lookup_by_anagram_select_signature ## --------------------------------------------------- ## SELECT signatures_anagrams_select_signature.Expr1, ## signatures_anagrams_select_signature.CountOfCONS, ## Cons_alpha_only_signature_unique.CONS, ## Cons_alpha_only_signature_unique.signature ## FROM signatures_anagrams_select_signature ## INNER JOIN Cons_alpha_only_signature_unique ## ON signatures_anagrams_select_signature.signature ## = Cons_alpha_only_signature_unique.signature; ## ## ## Now it's a simple matter to use the ODBC from Win32 to extract ## the query output into Python. import dbi import odbc con = odbc.odbc("words") cursor = con.cursor() ## This first section grabs the anagram summary. Note that ## queries act just like tables (as long as they don't have ## internal dependencies. I read somewhere you can get the ## field names, but here I put them in by hand. ##cursor.execute("SELECT * FROM signature_anagram_summary") ## ##results = cursor.fetchall() ## ##for i in results: ## for j in i: ## print '%4s' % (str(j)), ## print ## (if this wraps, each line is 116 characters) ## 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 23 ## 2 259 None None None None None None None None None None None None None None None None None ## 3 487 348 218 150 102 None None None None None None None None None None None None None ## 4 1343 718 398 236 142 101 51 26 25 9 8 3 2 None None None None None ## 5 3182 1424 777 419 274 163 106 83 53 23 20 10 6 4 5 1 3 1 ## 6 5887 2314 1051 545 302 170 114 54 43 21 15 6 5 4 4 2 None None ## 7 7321 2251 886 390 151 76 49 37 14 7 5 1 1 1 None None None None ## 8 6993 1505 452 166 47 23 8 6 4 2 2 None None None None None None None ## 9 5127 830 197 47 17 6 None None 1 None None None None None None None None None ## 10 2975 328 66 8 2 None None None None None None None None None None None None None ## 11 1579 100 5 4 2 None None None None None None None None None None None None None ## 12 781 39 2 1 None None None None None None None None None None None None None None ## 13 326 11 2 None None None None None None None None None None None None None None None ## 14 166 2 None None None None None None None None None None None None None None None None ## 15 91 None 1 None None None None None None None None None None None None None None None ## 16 60 None None None None None None None None None None None None None None None None None ## 17 35 None None None None None None None None None None None None None None None None None ## 18 24 None None None None None None None None None None None None None None None None None ## 19 11 None None None None None None None None None None None None None None None None None ## 20 6 None None None None None None None None None None None None None None None None None ## 21 6 None None None None None None None None None None None None None None None None None ## 22 4 None None None None None None None None None None None None None None None None None ## From the query we have the word size as row header and size of ## anagram set as column header. The data value is the count of ## how many different anagram sets match the row/column header. ## ## For example, there are 7321 different 7-letter signatures that ## have 2 anagram sets. There is 1 5-letter signature having a ## 23 member anagram set. ## ## We can then pick any of these, say the single 10 member anagram ## set of 9-letter words, and query out out the anagrams: cursor.execute("SELECT * FROM signatures_lookup_by_anagram_select_signature") results = cursor.fetchall() for i in results: for j in i: print j, print ## 9 10 anoretics 10101000100001100111000000 ## 9 10 atroscine 10101000100001100111000000 ## 9 10 certosina 10101000100001100111000000 ## 9 10 creations 10101000100001100111000000 ## 9 10 narcotise 10101000100001100111000000 ## 9 10 ostracine 10101000100001100111000000 ## 9 10 reactions 10101000100001100111000000 ## 9 10 secration 10101000100001100111000000 ## 9 10 tinoceras 10101000100001100111000000 ## 9 10 tricosane 10101000100001100111000000 ## Nifty, eh? > > DG From thelanguageofcities at gmail.com Sun Jan 27 19:19:13 2008 From: thelanguageofcities at gmail.com (Max) Date: Sun, 27 Jan 2008 16:19:13 -0800 (PST) Subject: Python Genetic Algorithm References: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Jan 27, 6:35 pm, Wildemar Wildenburger wrote: > Max wrote: > > In GAs, you operate on a Population of solutions. Each Individual from > > the Population is a potential solution to the problem you're > > optimizing, and Individuals have what's called a chromosome - a > > specification of what it contains. For example, common chromosomes are > > bit strings, lists of ints/floats, permutations...etc. I'm stuck on > > how to implement the different chromosomes. I have a Population class, > > which is going to contain a list of Individuals. Each individual will > > be of a certain chromosome. I envision the chromosomes as subclasses > > of an abstract Individual class, perhaps all in the same module. I'm > > just having trouble envisioning how this would be coded at the > > population level. Presumably, when a population is created, a > > parameter to its __init__ would be the chromosome type, but I don't > > know how to take that in Python and use it to specify a certain class. > > I'm not sure I'm following you here. So a "chromosome" is bit of > functionality, right? So basically it is a function. So my advice would > be to write these functions and store it to the "indivuals"-list like so: > > class Population(object): > def __init__(self, *individuals): > self.individuals = list(individuals) > > Then you can say: > p = Population(indiv1, indiv2, indiv3) > for individual in p.individual: > individual(whatever_your_problem) > > (Don't know if this is the way GA's are supposed to work) > > You can also create callable classes (that is, classes that implement > the __call__ method), and use instances of these as the individuals. For > example you can create a Permutation class that returns a permutation > (defined in it's __init__()) when it's __call__ method is called. (Am I > making sense?) > > This is just generic advice, maybe this helps and maybe it doesn't at > all. :) > > > I'm doing something similar with my crossover methods, by specifying > > them as functions in a module called Crossover, importing that, and > > defining > > > crossover_function = getattr(Crossover, "%s_crossover" % xover) > > > Where xover is a parameter defining the type of crossover to be used. > > I'm hoping there's some similar trick to accomplish what I want to do > > with chromosomes - or maybe I'm going about this completely the wrong > > way, trying to get Python to do something it's not made for. Any help/ > > feedback would be wonderful. > > This isn't too bad, but for such things dictionaries are your Go-To > datatype. Just have a dictionary of xover-functions handy and call the > thusly: > > crossover_function = Crossover.function[xover] > > > Thanks, > > Max Martin > > If that helps :) > > regards > /W This is definitely useful information, but I don't think I explained chromosomes very well. A chromosome is a choice of representation. So let's say your problem is diagnosis, so a representation of a solution will be a list of diagnoses (e.g. Disease1 = yes, Disease2 = no, Disease3 = yes, etc.). Your chromosome choice could be a bitstring, in which the previous solution would = 101, or it could be a list of floats to represent the probability that you have Disease x, etc. So a chromosome is like a choice of representation. In the case of humans, the chromosome is, well, chromosomes. From mr.cerutti at gmail.com Wed Jan 30 08:45:03 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 30 Jan 2008 08:45:03 -0500 Subject: Removal of element from list while traversing causes the next element to be skipped In-Reply-To: <7xwsprxxe6.fsf@ruckus.brouhaha.com> References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> <7xwsprxxe6.fsf@ruckus.brouhaha.com> Message-ID: <51302a8c0801300545i4d4f9460pbbbc489f11bef5ee@mail.gmail.com> On 30 Jan 2008 05:20:49 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Neil Cerutti" writes: > > Or one can put on his bellbottoms, horn-rimmed glasses, and wear a mullet: > > > > i = 0 > > while i < len(a): > > if a[i] == 99: > > del a[i] > > else: > > i += 1 > > Quadratic time!! Yowch!! Back to the future: > > def rocket_science(xs): > for x in xs: > if x != 99: > yield x > > a[:] = list(rocket_science(a)) Heh. It's probably a fairly peppy quadratic operation though. Besides, wherever will I find plutonium or a bolt of lightning? -- Neil Cerutti From m.schibler at gmail.com Thu Jan 3 03:14:43 2008 From: m.schibler at gmail.com (Matthew Schibler) Date: Thu, 3 Jan 2008 00:14:43 -0800 (PST) Subject: shelve and nested dictionaries Message-ID: I'm a newbie to Python, with some experience using perl (where I used nested arrays and hashes extensively). I am building a script in python for a MUD I play, and I want to use the shelve module to store persistent information between script executions. The following code does not work for me, import shelve, sys, os, string db = shelve.open(os.path.abspath(os.path.dirname(sys.argv[0])) + '/' + 'sandbox.dat', 'c') db['JustSomeVariable'] = 'apple' db['subdb'] = {} db['subdb']['anotherdict'] = {} db['subdb']['anotherdict']['bleh'] = 'hello world' db.close() of course, that's just a working example but it illustrates the problem i'm having. I think shelve objects act like dictionaries in a way, at least they seem to have dictionary keys beneath them. And I don't seem to have this problem when I use a normal dictionary as opposed to shelve for nesting other dictionaries. So i'm now confused, i've hit a brick wall and i'm not sure how to solve this problem. Can anyone explain what i'm doing wrong? Thanks From bignose+hates-spam at benfinney.id.au Fri Jan 25 18:45:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 26 Jan 2008 10:45:38 +1100 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> Message-ID: <87k5lx5v19.fsf@benfinney.id.au> "Gabriel Genellina" writes: > You can also put, in animal/__init__.py: > from monkey import Monkey > and now you can refer to it as org.lib.animal.Monkey, but keep the > implementation of Monkey class and all related stuff into > .../animal/monkey.py This (as far as I can understand) is exactly the solution the original poster desired to "shoot down", for reasons I still don't understand. -- \ "Reichel's Law: A body on vacation tends to remain on vacation | `\ unless acted upon by an outside force." -- Carol Reichel | _o__) | Ben Finney From hoo.smth at gmail.com Thu Jan 10 03:59:43 2008 From: hoo.smth at gmail.com (BlackjadeLin) Date: Thu, 10 Jan 2008 00:59:43 -0800 (PST) Subject: Why my program (using pexpect to switch user) doesn't work well? Message-ID: <97b80c0e-9199-464e-a52e-615f98972ee0@e4g2000hsg.googlegroups.com> I'm new to python I want to write a simple script to switch user,for example,from user_A to user_B. This my codes: #!/usr/bin/python import pexpect import os passwd="user_B" child = pexpect.spawn('su user_B') child.expect('Password:') child.sendline(passwd) child.expect('$') child.close() Maybe it's the easiest pexpect program.Sometimes ,it work well,it switch to user_B successfully .But after i type the command exit to switch back to user_A,execute the python script again,it can't work,do nothing or just waiting.Why it have different results? Sorry for my poor English,and many thanks to all. Blackjade From asmodai at in-nomine.org Wed Jan 16 06:55:56 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 16 Jan 2008 12:55:56 +0100 Subject: anti-spam policy for c.l.py? In-Reply-To: <478dee4e$0$28424$426a34cc@news.free.fr> References: <08ed32c4-6230-4b14-9c31-4b94e0231cf2@c4g2000hsg.googlegroups.com> <478dee4e$0$28424$426a34cc@news.free.fr> Message-ID: <20080116115556.GA61556@nexus.in-nomine.org> -On [20080116 12:51], Bruno Desthuilliers (bruno.42.desthuilliers at wtf.websiteburo.oops.com) wrote: >Apart from checking posts headers and complaining about the relevant >ISPs, there's not much you can do AFAIK. This is usenet, not a mailing-list. It is both actually. python-list at python.org is linked to comp.lang.python due to a news gateway. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ I accept that some things will never change, I've let your tiny minds magnify my agony... From richarwils at gmail.com Wed Jan 23 05:19:47 2008 From: richarwils at gmail.com (Richi) Date: Wed, 23 Jan 2008 02:19:47 -0800 (PST) Subject: Computer Laptops Message-ID: Zenith Director Laptop, Lenovo Laptop Model No: 3000 Y500, HCL Notebook Model No: AXX2202, Zenith Presidio Laptop many model of laptop.... please visit - http://www.homeshop18.com/hs18shop/faces/tiles/category.jsp?catalogueID=2&categoryID=920&parentCategoryID=909&q=&sid=&bid=&prc=&k1=&k2=&k3=&k4=&k5=&k6=&k7=&k8=&k9=&k10=&k11=&k12= From theCodeMaiden at gmail.com Thu Jan 3 15:15:27 2008 From: theCodeMaiden at gmail.com (Adeola Bannis) Date: Thu, 3 Jan 2008 12:15:27 -0800 (PST) Subject: PyOpenGL, wxPython weird behaviour References: <71ae5a6b-31e9-41e9-a39e-919138dc4a03@l6g2000prm.googlegroups.com> Message-ID: Thanks, will do... On Jan 3, 2:07 pm, kyoso... at gmail.com wrote: > On Jan 3, 11:50 am, Adeola Bannis wrote: > > > > > Hi everyone, > > > I'm doing a project using wxPython and pyopengl, and I seem to have a > > problem rendering textures. This is code that worked before my hard > > drive had a meltdown, but not since I re-installed everything. > > > I've determined the problem is in the OpenGL part of my program. I do > > some calculations to generate a 2D numpy array that holds the image > > data, and pylab.imshow() shows me the image as it is meant to be. I > > used the same algorithm in Octave and MATLAB, and all are giving me > > the right picture. > > > However, using pyOpenGL and the numpyhandler functions (http://cours- > > info.iut-bm.univ-fcomte.fr/docs/python/OpenGL/ > > OpenGL.arrays.numpymodule.NumpyHandler-class.html) doesn't seem to > > work. I get a garbled screen pocked with black pixels. I am including > > my openGL code below. What am I doing wrong? > > > And yes, I did make the dtype of my array 'float32'. > > > -------code snippets------ > > > import wx > > from wx.glcanvas import GLCanvas > > > from OpenGL.GLU import * > > from OpenGL.GL import * > > from OpenGL.arrays.numpymodule import NumpyHandler > > > PC = 1 > > RI = 0 > > > class myGLCanvas(GLCanvas): > > def __init__(self, parent): > > GLCanvas.__init__(self, parent,-1) > > wx.EVT_PAINT(self, self.OnPaint) > > self.init = 0 > > self.mode = -1 > > # making a texture for the range image > > self.texture = glGenTextures(1) > > # making a spot for the point cloud points > > self.cloud = None > > return > > > def OnPaint(self,event): > > dc = wx.PaintDC(self) > > self.SetCurrent() > > if not self.init: > > self.InitGL() > > self.init = 1 > > self.OnDraw() > > return > > > def OnDraw(self): > > glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) > > if self.mode == RI: > > self.drawRange() > > elif self.mode == PC: > > self.drawCloud() > > > def InitGL(self): > > glClearColor(0.0, 0.0, 0.0, 0.0); > > glClearDepth(1.0) > > glEnable(GL_DEPTH_TEST) > > glDepthFunc(GL_LEQUAL) > > glClear(GL_COLOR_BUFFER_BIT) > > > glPixelStorei(GL_UNPACK_ALIGNMENT, 1) > > glPixelStorei(GL_PACK_ALIGNMENT, 1) > > > #NTSC colour scales... > > glPixelTransferf(GL_RED_SCALE, 0.299); > > glPixelTransferf(GL_GREEN_SCALE, 0.587); > > glPixelTransferf(GL_BLUE_SCALE, 0.114); > > > glMatrixMode(GL_PROJECTION) > > glLoadIdentity() > > glOrtho(0.0,1.0,0,1.0,-1.0,1.0) > > glMatrixMode(GL_MODELVIEW) > > glLoadIdentity() > > > return > > > def rangeImage(self, image): > > > glBindTexture(GL_TEXTURE_2D, self.texture) > > glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) > > > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, > > GL_LINEAR) > > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) > > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) > > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) > > > # flatten it into a list so the OpenGL calls work > > n = NumpyHandler() > > fI = image.flatten() > > flatImage = n.dataPointer(n.contiguous(fI)) > > > print n.contiguous(fI) > > > gluBuild2DMipmaps(GL_TEXTURE_2D, 1, image.shape[0]+1, > > image.shape[1]+1, > > GL_LUMINANCE, GL_FLOAT, flatImage) > > self.mode = RI > > self.OnDraw() > > > def drawRange(self): > > ''' Controls the actual drawing of the range image''' > > > glMatrixMode(GL_MODELVIEW) > > glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) > > > glColor3f(1.0,1.0,1.0) > > glEnable(GL_TEXTURE_2D) > > glBindTexture(GL_TEXTURE_2D, self.texture) > > glBegin(GL_TRIANGLE_FAN) > > glTexCoord2d(1,1); glVertex3f(0.0, 0.0, 0.0) > > glTexCoord2d(1,0); glVertex3f(0.0, 1.0, 0.0) > > glTexCoord2d(0,0); glVertex3f(1.0, 1.0, 0.0) > > glTexCoord2d(0,1); glVertex3f(1.0, 0.0, 0.0) > > glEnd() > > self.SwapBuffers() > > > --------end snippet----------- > > I've never messed with pyOpenGL, but it seems that they have their own > user's group, which would probably be better at answering your > question: > > http://sourceforge.net/mail/?group_id=5988 > > Of course, it could be that you upgraded your wxPython to the latest > version and as I recall, they were discussing some subtle differences > in DCs, blitting, paint events and other things that I just don't > understand at this point in my "Pythoneering". You might ask them at > their group, which is usually very helpful: wxPython.org > > Mike From tinnews at isbd.co.uk Fri Jan 4 11:31:39 2008 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: 04 Jan 2008 16:31:39 GMT Subject: how to use bool References: <477d08d1$0$510$bed64819@news.gradwell.net> Message-ID: <477e5f6b$0$514$bed64819@news.gradwell.net> Chris Mellon wrote: > On 03 Jan 2008 16:09:53 GMT, wrote: > > > > jimgardener at gmail.com wrote: > > > hi, i have some code where i set a bool type variable and if the value > > > is false i would like to return from the method with an error msg.. > > > being a beginner I wd like some help here > > > > > > class myclass: > > > ......... > > > def mymethod(self): > > > success=True > > > msg="all validation OK" > > > success=validateSthing() > > > if(success==False): > > > msg="sthing failed" > > > return (success,msg) > > > > > > dosomeprocessing() > > > ..... > > > success=validateSthingelse() > > > if(success==False): > > > msg="sthingelse failed" > > > return (success,msg) > > > domoreprocessing() > > > .... > > > return(success,msg) > > > > > > i would like to know if this way of doing this is OK..I have need of > > > many kinds of validations in this ..is there a better way of doing > > > this ? > > > > > With my philosophical programming hat on the first thing I'd say (as a > > fairly beginning python programmer) is "avoid multiple returns from a > > function/method if at all possible". They breed all sorts of problems > > and errors, in particular if there's any clearing up to do you have to > > do it in lots of places (or you forget it in some places). > > > > This advice is highly controversial, and in the presence of exceptions > it is, at best, voodoo coding. Since your function can exit at any > point whether you do it intentionally or not, if you have crucial > cleanup it's best to write your code in a way that does it correctly > even if you return early. Following this style also often leads to odd > contortions, like extra layers of indentation, and a proliferation of > temporary flags and value-holders that aren't necessary if you write > the code in a more straight forward manner. > OK, I agree, I had my C hat on (no exceptions). On the other hand if you end with lots of levels of indentation going this way it suggests to me that maybe breaking up into more functions would be a good idea. > Make your decisions on a case by case basis of complexity, > readability, and reliability instead of following pronouncements from > on high (especially decades old pronouncements made in a different > context). Forcing a single return site in the code below adds > complexity, arguable harms readability, and provides *zero* benefit in > the code at hand. > > > So:- > > > > def mymethod(self): > > msg="sthing failed" > > success=validateSthing() > > if success: > > dosomeprocessing() > > ..... > > success=validateSthingelse() > > if success: > > domoreprocessing() > > .... > > msg="all validation OK" > > return (success,msg) > > > > I've lost the different messages for different errors but you get the > > idea. > > > > > > "if success:" rather than "if (success==True)", more readable. For > > the opposite "if not success:". > > > > > > > > -- > > Chris Green > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > -- Chris Green From bruno.desthuilliers at gmail.com Mon Jan 28 17:20:36 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 28 Jan 2008 14:20:36 -0800 (PST) Subject: post variable References: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> <87ir1dr8ms.fsf@mulj.homelinux.net> <0f634854-7d7a-4ad8-ba04-38d239ecf850@d70g2000hsb.googlegroups.com> Message-ID: <2bc110e7-de2d-47ac-89e8-c87793ec1a14@b2g2000hsg.googlegroups.com> On 28 jan, 22:32, "pavloutefk... at gmail.com" wrote: > 1. yes i've tried that technique but its annoying, the user can easily > stop the redirection and not "elegant". It's a very canonical technique with HTTP (at least after a successful POST). But I suspect you're not doing it the right way, since you're talking about "the user (...) stop(ing) the redirection". "Redirecting" here means "sending an HTTP redirection status code and the appropriate location header" (according to the rfc, code should be 303, but for legacy reasons it's often a 302). You must indeed *not* have send *anything* else to the client before (which means that you'd better use a log file to trace your code) ! From oliver at obeattie.com Sat Jan 26 06:35:18 2008 From: oliver at obeattie.com (Oliver Beattie) Date: Sat, 26 Jan 2008 03:35:18 -0800 (PST) Subject: Custom class to a dictionary? Message-ID: <5025a3f7-9dcf-49d7-876c-df5c8d8a8df5@e6g2000prf.googlegroups.com> Just wondering if it is possible to pass a custom class instance instance to dict() by way of using methods like you can for iterators (__iter__, __getitem__ etc.) I see there is no __dict__ -- is there anything else I can use to achieve this? Kind Regards, Oliver From ceccarelli.aldo at gmail.com Thu Jan 24 17:49:33 2008 From: ceccarelli.aldo at gmail.com (Aldo Ceccarelli) Date: Thu, 24 Jan 2008 14:49:33 -0800 (PST) Subject: Anybody has ported talib to Python via SWIG Message-ID: <6fa2a3e3-ab77-41dc-a01e-55770a764b0e@k39g2000hsf.googlegroups.com> Hi Everybody, TaLib (technical analysis package with function indicators coded in C/C ++, http://www.ta-lib.org ) has a complete library with source in C/C+ +. I am new to SWIG (wrapper interface generator) and would really appreciate any Python (.py) port of TaLib to be able to call and test TaLib's functions (f.i. MACD, Parabolic SAR and so on) in some Python (2.5) script. Do you have idea whether TaLib Python package has already been generated and can be eventually downloaded anywhere? Many thanks, kind regards. Aldo From Matthew_WARREN at bnpparibas.com Tue Jan 29 05:49:16 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Tue, 29 Jan 2008 10:49:16 +0000 Subject: validate string is valid maths In-Reply-To: <25d89a47-6380-4129-a7b8-3a70ca1b216f@c4g2000hsg.googlegroups.com> Message-ID: It was a very loosely thought out problem, and my Maths isn't good enough to define 'sane' rules for collapsing the signs/operators to make a sensible expression; so take my constraints with a pinch of salt. I guess a better way of putting it may be - now it has been pointed out that 8+++++++9 is valid; Remove the smalles number of symbols such that eval() will always return a number, and the result is always the same. ....and I havent had a chance to play with the couple of solutions posted yet, so those criteria may have already been met. One thing I have discovered is you cant just pass arbitrary valid (expression wise) numeral/symbol strings to eval and have it work as expected; >>> eval('8-038') Traceback (most recent call last): File "", line 1, in File "", line 1 8-038 ^ SyntaxError: invalid token becasue of >>> eval('8-010') 0 Can I escape the meaning of the leading 0's on an integer? ....and despite my initial claims, there is an overall aim. Still purely just to play with python though - after someone mentioned Genetic Algorithms on the list yesterday I thought I'd have a go at a very simple one. These long symbol/number strings are the 'genomes/chromosomes' (not certain on correct terms), the 'genes' are 1234567890+/-* I'm generating large populations of arbitrary length chromosomes. Using eval(chromosome) to compute a number. The fittest individuals are the ones who's genome evaluates closest to 10000000, so in essence I'm evolving solutions to making the number 10000000 using 1234567890/*-+ (this was partially inspired by the countdown numbers game discussed here too.). Trivial and possibly pointless, but shiny enough for me to play with :) Matt. Internet gagsl-py2 at yahoo.com.ar To python-list Sent by: cc python-list-bounces+matthew.warren=uk.bnpparibas.com@ python.org Subject Re: validate string is valid maths 28/01/2008 18:30 impor tOn 28 ene, 14:31, Matthew_WAR... at bnpparibas.com wrote: > What would be the 'sensible' way of transforming the string, for example > changing '3++++++8' into 3+8 > or '3++--*-9' into '3+-9' such that eval(string) will always return a > number? '3++++++8' is already a valid expresion, like '3++---9' > in cases where multiple symbols conflict in meaning (as '3++--*-9' the > earliest valid symbols in the sequence should be preserved > > so for example, > > '3++*/-9' = 3+-9 > '45--/**/+7' = 45-+7 > '55/-**+-6**' = 55/-6 Why not 3++-9, 45--+7? Does it have to be two operators? Why not 3++9 instead? they're the two earliest valid symbols. Can't repeat yourself then? (I'm trying to understand the rules...) This approach uses regular expressions. It doesn't follow all your rules, and tries to get the longest valid expression: import re def repl_middle(match): g = match.group() if g[0] in '*/': g0 = g[0] g = g[1:] else: g0 = '' return g0 + g.replace('*','').replace('/','') def repl_start(match): g = match.group() return g.replace('*','').replace('/','') def dropinvalid(s): s = re.sub(r'(?<=\d)[+*/-]+(?=\d)', repl_middle, s) s = re.sub(r'^[+*/-]+', repl_start, s) s = re.sub(r'[+*/-]+$', '', s) return s cases = [ ('3++++++8', '3+8'), ('3++--*-9', '3+-9'), ('3++*/-9', '3+-9'), ('45--/**/+70', '45-+70'), ('55/-**+-6**', '55/-6'), ('55/**6**', '55/6'), ] for expr, matthew in cases: print expr, dropinvalid(expr), matthew > I've tried testing, but I'm not certain wether repeated iterations over a > dict return different sequences of key,value pairs or wether I'll be > getting the same (but arbitrary) sequence each time even though they are > unordered, etc If the dictionary hasn't changed, you'll get the same sequence each time (see note (3) in http://docs.python.org/lib/typesmapping.html ) > So for testing, what could I do to guarantee the next iteration over the > dict will give keys/pairs in a different sequence to last time? items = dict.items() random.shuffle(items) for key,value in items: ... (Ok, no guarantee, there is only a certain probability that it will be different each time...) -- Gabriel Genellina -- 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 kimsmith005 at googlemail.com Fri Jan 4 13:53:33 2008 From: kimsmith005 at googlemail.com (kimsmith005 at googlemail.com) Date: Fri, 4 Jan 2008 10:53:33 -0800 (PST) Subject: :::> A Powerful, Safe and Economical Alternative to VIAGRA <::: Message-ID: <75cc7d70-af4b-41a3-bc96-de4fa5cc5883@s8g2000prg.googlegroups.com> :::>> A Powerful, Safe and Economical Alternative to VIAGRA <<::: >>> Naturally improves Erectile Dysfunction increasing your Sex Drive, Endurance,and Pleasure. * Creates Firmer Harder Erections. * Increases SEMINAL VOLUME & SPERM COUNT Naturally with NO SIDE EFFECTS. * Creates Heightened Desire, Sensitivity and Pleasure. * Sub-lingual tablets are dissolved under the tongue offering complete and rapid absorption. .::>> 100% Full MONEY BACK guarantee if not completely satisfied with results. For More Details >>> http://lovetools.cq.bz/ __________________________________________________________________________________________________ Learn Why ProVIGRAX is Better than Viagra >>> http://proviagrax.blogspot.com/ From rowen at cesmail.net Thu Jan 24 18:27:25 2008 From: rowen at cesmail.net (Russell E. Owen) Date: Thu, 24 Jan 2008 15:27:25 -0800 Subject: Problem with Tkinter scrollbar callback References: Message-ID: In article , "Ivan Van Laningham" wrote: > Hi All-- > I'm having two problems with the scrollbar callback on linux systems > (Fedora 7, Suse 10.1,2 and 3 all exhibit the issues). > > Problem one: on Windows, the callback is called with the arguments as > specified in the doc: "scroll", "1" or "-1", "units". When I run the > identical code on linux, the callback is invoked with only one > argument, "1" or "-1". Here's a small program which demos the > problem: > > ========begin============ > #!/usr/bin/env python > > from Tkinter import * > import sys > > def die(event): > sys.exit(0) > def sDoit(*args): > for i in args: > print "scrollbar:",i, type(i) > root=Tk() > f=Frame(root) > f.pack(expand=1,fill=BOTH) > button=Button(f,width=25) > button["text"]="Quit" > button.bind("
this is in a table, woo-hoo!
19 """ 20 Thank you, Christopher From tangjin93 at hotmail.com Sun Jan 20 00:15:33 2008 From: tangjin93 at hotmail.com (Janet93) Date: Sat, 19 Jan 2008 21:15:33 -0800 (PST) Subject: an Invitation to be Involved in a Survey on Developing Scientific Computing Software Message-ID: If you are involved in the development of scientific computing software, you are invited to participate in a survey on developing this kind of software. If you have already received this request, I apologize for the cross-posting, but I am attempting to advertise to as many developers as possible. I would appreciate it if you could take 20-30 minutes to complete this questionnaire. If you know others involved in the development of scientific computing software, could you please forward this survey to them. Your assistance is highly appreciated. There are 37 questions in the survey, which can be accessed via the following link: http://www.eSurveysPro.com/Survey.aspx?id=b67ce1c1-84c2-4c2b-b66d-70db013d8038 The survey is for a research experiment conducted by myself, Jin Tang, a master student at the Department of Computing and Software, McMaster University, Canada, under the supervision of Dr. Spencer Smith. The result of this survey will help me with my research on the processes used to develop scientific computing software, where scientific computing is defined as the use of computer tools to analyze or simulate mathematical models of continuous real world system of engineering or scientific importance so that we can better understand and potentially predict the system's behaviour. The short term goal of this survey is to find the processes that industry and academia follow to develop their scientific computing software. The mid term objective is to direct research on adapting software engineering methodologies to improve the quality of scientific computing software. Questions in this survey are related to the process of developing scientific computing software. For example: What kind of libraries do you use to develop scientific computing software? In your current group, do you consider software reuse? What level of software reuse do you reach? What method(s) do you use for software validation and verification. All questions are voluntary and you need only answer those questions that you wish to. If you agree to participate in the survey, you can change your mind and discontinue the survey at any time. This research will pose risks no greater than what you would experience in the course of your day-to-day work life. If you are interested in this study, we are very happy to share our survey report with you. Please provide your email address in the survey, the survey report will be sent to you. All your answers to the survey questions will be kept in Excel files, which will be completely confidential and only available to myself and Dr. Spencer Smith. If you have any questions, please contact Jin Tang or Dr. Spencer Smith. The following is our contact information. Jin Tang Department of Computing and Software McMaster University 1280 Main Street West Hamilton, Ontario, Canada L8S 4K1 Phone: 905-525-9140 Ext. 27029 Email: tangj29 at mcmaster.ca Spencer Smith, Ph.D. Associate Professor Department of Computing and Software McMaster University 1280 Main Street West Hamilton, Ontario, Canada L8S 4K1 Phone: 905-525-9140 Ext. 27929 Fax: 905-524-0340 Email: smiths at mcmaster.ca This study has been reviewed and approved by the McMaster Research Ethics Board. If you have concerns or questions about your right as a participant or about the way the study is conducted, you may contact McMaster Research Ethics Board Secretariat at 905-525-9140 ext. 23142, email: ethicsoffice at mcmaster.ca. Thank you. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 28 04:51:00 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 28 Jan 2008 10:51:00 +0100 Subject: optional static typing for Python In-Reply-To: References: Message-ID: <479da584$0$25625$426a74cc@news.free.fr> Russ P. a ?crit : > A while back I came across a tentative proposal from way back in 2000 > for optional static typing in Python: > (snip) > In any case, optional static typing in Python would help tremendously > here. The hardest part of automated conversion of Python to a > statically typed language is the problem of type inference. If the > types are explicitly declared, that problem obviously goes away. (snip) > Note also that, while "static" type checking would be ideal, > "explicit" typing would be a major step in the right direction Lord have mercy(tm). From bg_ie at yahoo.com Mon Jan 7 08:27:27 2008 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Mon, 7 Jan 2008 05:27:27 -0800 (PST) Subject: Launching a wx GUI from within our python framework Message-ID: <0f4a1b94-9fc0-457f-81c3-b8986f5086cd@d70g2000hsb.googlegroups.com> Hi, At my work we have a framework writen in python which allows us to test our equipment. This framework is quite large and uses a Singelton called frameworkExec which we pass around between objects in order to share functionailty. For example, frameWorkExec stores an instance of the BatteryManagement module which I use to set the voltage during certain tests. I've just writen a gui using wx which I wish to use to calibrate our voltage supply. I launch this app at the moment within python win as follows - app = VoltageCalibrationApp(0) app.MainLoop() class VoltageCalibrationApp(wx.App): def OnInit(self): voltageCalibration = {} voltageCalibration[0.0] = 1.2 voltageCalibration[9.0] = 10.1 voltageCalibration[22.0] = 22.7 voltageCalibration[24.0] = 24.8 voltageCalibration[30.0] = 31.1 voltageCalibration[35.0] = 36.9 frame = VoltageCalibrationFrame(None, -1, 'Voltage Calibration', voltageCalibration) frame.Show(True) frame.Centre() return True I hope that by adding the code above into the framework, I will be able to call this app as part of the framework before the execution of certain tests, as follows - app = VoltageCalibrationApp(0) app.MainLoop() test1.run() test2.run() As you can see in the VoltageCalibrationApp class, I am currently hardcoding voltageCalibration. Rather than doing this, I wish to store them in our singleton which is available at the scope at which I create my VoltageCalibrationApp instance. But I can't figure our a way of referencing my singleton with the OnInit function. Normally, you would pass the reference via __init__ How can I do this? Thanks, Barry. From kay.schluehr at gmx.net Mon Jan 7 09:27:36 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 7 Jan 2008 06:27:36 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Message-ID: On Jan 7, 12:53 pm, Berco Beute wrote: > Cool! We knew it would happen one day :) > What could be the reason? Python 3? Jython 2.2? Java's loss of > sexiness? Python eats Perls lunch as a scripting language. From sebastien.ramage at gmail.com Wed Jan 16 05:37:58 2008 From: sebastien.ramage at gmail.com (=?ISO-8859-1?Q?S=E9bastien_Ramage?=) Date: Wed, 16 Jan 2008 02:37:58 -0800 (PST) Subject: using pyopengl 3.0.0b1 with py2exe Message-ID: Hi ! How can I make an exe that use the new pyopengl 3.0.0b1 ??? I use py2exe 0.6.6 with the 3.0.0a6 version I have make it working by copying the egg and by forcing loading it at the start of the app but it doesn't work with this version py2exe correctly detect it and include it in the app but I get this Traceback (most recent call last): File "texas.py", line 8, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\GL\__init__.pyo", line 2, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\raw\GL\__init__.pyo", line 6, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\raw\GL\constants.pyo", line 7, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\platform\__init__.pyo", line 20, in ImportError: No module named pkg_resources if I add an unzipped copy of setuptools in my app folder, py2exe include pkg_resources but I get this Traceback (most recent call last): File "texas.py", line 8, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\GL\__init__.pyo", line 2, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\raw\GL\__init__.pyo", line 6, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\raw\GL\constants.pyo", line 7, in File "zipextimporter.pyo", line 82, in load_module File "OpenGL\platform\__init__.pyo", line 57, in File "OpenGL\platform\__init__.pyo", line 53, in _load RuntimeError: Unable to find an implementation for the 'win32' ('nt') platform if anybody ahs a solution.... Seb From mr.cerutti at gmail.com Wed Jan 9 08:41:35 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 9 Jan 2008 08:41:35 -0500 Subject: alternating string replace In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <51302a8c0801090541u921bee9k79eebf2a84463e31@mail.gmail.com> On Jan 9, 2008 5:34 AM, cesco wrote: > Hi, > > say I have a string like the following: > s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... > > Thanks in advance Hum, hum... If I had a hammer... from pyparsing import * word = Word(alphas) sep = Literal('_').suppress() pair = Group(word + sep + word) pairs = delimitedList(pair, '_') print ','.join(':'.join(t) for t in pairs.parseString('hi_cat_bye_dog').asList()) -- Neil Cerutti From ckuanglim at yahoo.com Fri Jan 11 05:05:21 2008 From: ckuanglim at yahoo.com (Chan Kuang Lim) Date: Fri, 11 Jan 2008 02:05:21 -0800 (PST) Subject: help for installing PIL Message-ID: <32600.51914.qm@web60520.mail.yahoo.com> I'm using Window XP. How to install PIL 1.1.6? The Python i installed, is come with Plone. So, is it ok? Thank you. Regards, Chan Kuang Lim --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 28 04:53:37 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 28 Jan 2008 10:53:37 +0100 Subject: optional static typing for Python In-Reply-To: <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> Message-ID: <479da620$0$25625$426a74cc@news.free.fr> Russ P. a ?crit : > On Jan 27, 5:03 pm, Paddy > >> If static typing is optional then a program written in a dynamic >> language that passes such an automated static analysis of source code >> would have to be a simple program written in a simplistic way, and >> also in a static style. > > Yes, but for safety-critical software you usually want the simplest > possible solution. The last think you want is an unnecessarily "fancy" > design. Unless there is a darn good reason to write a "non-static" > program, you just don't do it. > > You might want to check into what the FAA allows in "flight-critical" > code, for example. I am certainly not an expert in that area, but I've > had a passing exposure to it. My understanding is that every possible > branch of the code must be fully and meticulously analyzed and > verified. Hence, the dynamic dispatching of ordinary object-oriented > code is either prohibited or severely frowned upon. Then Python is definitively out, so this whole thread is pointless. From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 19:25:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 28 Jan 2008 00:25:36 -0000 Subject: Python Genetic Algorithm References: Message-ID: <13pq880abaohbe4@corp.supernews.com> On Sun, 27 Jan 2008 15:09:52 -0800, Max wrote: > Hi all. I'm just getting introduced to Python (mostly through Dive Into > Python), and I've decided to use it for a project where I have to write > my own Genetic Algorithm. Even if you don't know about GAs, you might be > able to help with an issue I'm having. I'm just starting the project > off, so I'm still in the conceptual phase, and I'm stuck on how I'm > going to be able to implement something. > > In GAs, you operate on a Population of solutions. Each Individual from > the Population is a potential solution to the problem you're optimizing, > and Individuals have what's called a chromosome - a specification of > what it contains. For example, common chromosomes are bit strings, lists > of ints/floats, permutations...etc. I'm stuck on how to implement the > different chromosomes. I have a Population class, which is going to > contain a list of Individuals.Each individual will be of a certain > chromosome. Presumably all the individuals in the same population need to have the same kind of chromosome (differing only in the specific genes). > I envision the chromosomes as subclasses of an abstract > Individual class, perhaps all in the same module. How would that work? Shouldn't the different kinds of chromosomes (strings, lists of ints, etc.) be subclasses of an abstract Chromosome kind? What you need to think of is the difference between Is-A and Has-A relationships. An individual Has A chromosome, so you want a relationship something like this: class Individual(object): def __init__(self): self.chromosome = get_chromosome() On the other hand, something like a string chromosome Is A chromosome, and so is a list-of-ints Chromosome: class Chromosome(object): pass # abstract class class StringChromosome(Chromosome): pass # implement extra/different functionality class ListIntsChromosome(Chromosome): pass > I'm just having > trouble envisioning how this would be coded at the population level. There are so many ways... here's one possibility that doesn't even use a Population class. chromosome = StringChromosome # the class, not an instance default_genes = "GATACATATGGATTAGGGACCACTAC" size = 100 population = [] for i in range(size): genes = chromosome(default_genes) genes.mutate() population.append(Individual(genes)) I'm sure you can modify that to work on a class instance basis. > Presumably, when a population is created, a parameter to its __init__ > would be the chromosome type, but I don't know how to take that in > Python and use it to specify a certain class. Just pass the class itself. For example: # Define a class. class Parrot(object): pass x = "Parrot" # x is the NAME of the class y = Parrot # y is the CLASS itself z = Parrot() # z is an INSTANCE of the class You can use the class as a object, exactly the same as you can use a dict or a string or a float or any other object. y() will create a new Parrot instance exactly the same way that Parrot() would. Here's one possibility: class Population(object): def __init__(self, size=1000, chromosome_type=StringChromosome): individuals = [] for i in xrange(size): genes = chromosome_type() # create new set of genes x = Individual(genes) # add them to a new individual individuals.append(x) # and store it in the population self.individuals = individuals > I'm doing something similar with my crossover methods, by specifying > them as functions in a module called Crossover, importing that, and > defining > > crossover_function = getattr(Crossover, "%s_crossover" % xover) > > Where xover is a parameter defining the type of crossover to be used. The only time you need something like that is when you need to go from user-input (a string) to a binary object (e.g. a class, a function...). Suppose you read the crossover type from a text config file, or user input: import Crossover xover = raw_input("Enter a crossover type: valid values are X, Y, Z: ") crossover_function = getattr(Crossover, "%s_crossover" % xover) Instead of passing the string xover around as a parameter, you use it *once* to get the actual function object itself, and pass that around. Another alternative is to define something like this in the Crossover module, assuming you have three functions xcrossover etc.: user_map = {"X": xcrossover, "Y": ycrossover, "Z": zcrossover} Again, use it once to get the function object from the user input. Hope this helps, -- Steven From zugnush at gmail.com Wed Jan 16 17:40:38 2008 From: zugnush at gmail.com (zugnush at gmail.com) Date: Wed, 16 Jan 2008 14:40:38 -0800 (PST) Subject: Creating unique combinations from lists References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> <13osvl1j4pvka15@corp.supernews.com> Message-ID: <001640bd-7759-423b-ad74-275b27e5d5d6@v4g2000hsf.googlegroups.com> > > for a in range(5): ... > for z in range(5): means the inner loop runs 5**26 times so perhaps it's not only unpythonic but also uncomputable... From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 28 12:09:17 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 28 Jan 2008 18:09:17 +0100 Subject: sharing objects between classes In-Reply-To: <606aolF1pa0tfU2@mid.uni-berlin.de> References: <606aolF1pa0tfU2@mid.uni-berlin.de> Message-ID: <479e0c3b$0$1158$426a74cc@news.free.fr> Diez B. Roggisch a ?crit : > Gerardo Herzig wrote: > >> Hi all. Im wondering the way to share a database connection between some >> classes: >> >> So far, i came up with a simple class schema, where each class means >> each different relation, i mean i have the follow classes >> >> class Database(object): >> ## make the connection >> self.conn = make_conn(....) >> >> class Table(object): >> def get_fields: >> .... >> (snip) > > Take a look at the sources of e.g. SQLObject and how they do it (in SO, the > concept is called "HUB") > And while you're at it, take a look at SQLAlchemy too, and ask yourself if you really need to roll your own solution !-) From paddy3118 at googlemail.com Fri Jan 18 19:01:57 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 18 Jan 2008 16:01:57 -0800 (PST) Subject: TopSort in Python? References: <0000161d@bossar.com.pl> Message-ID: <358cc5a3-300f-49ba-9857-2f0cd629a4df@i12g2000prf.googlegroups.com> On Jan 18, 9:47 pm, startec... at gmail.com wrote: > Tim, > > Thanks for the topsort code. It would be useful in a project I'm > working on. Can I use the code for free under public domain? Thanks! > When I needed one I didn't know the name. I'm curious, how did you know to look for the topological sort algorithm by name? (http://paddy3118.blogspot.com/2007/10/whats-in-name.html) - Paddy. From DustanGroups at gmail.com Thu Jan 31 07:39:28 2008 From: DustanGroups at gmail.com (Dustan) Date: Thu, 31 Jan 2008 04:39:28 -0800 (PST) Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> <58d1bc12-206f-4cec-ad86-928d16e962f5@i3g2000hsf.googlegroups.com> Message-ID: <8d69e9e8-c892-4c65-ac54-c184ce303a2e@i3g2000hsf.googlegroups.com> On Jan 30, 7:02 pm, FireNWater wrote: > Thank you for the explanation. . . I think I now have a (foggy) > understanding of hash tables. It seems to be a way to create order > (an index) out of disorder (random numbers or characters) behind the > scenes. . The key thing to realize is, quite simply, don't rely on order in a dictionary. If you do, bad things can happen. The underlying implementation is not important to know. But if you really do want to know, let me correct you here, and give a perhaps clearer explanation (if not, there's no need to read any further): The 'order' that your speaking of is not implemented by the hash *table*, per se, but rather by the hash function, which returns an integer (the hash code). The hash table takes the hash code and calculates where in its list to place the object (as explained before, using modulo to shrink the integer into the range of the list). If multiple items end up in the same list, they are placed into a kind of linked list, with each node containing an object and pointing to the next. Of course, if too many objects end up in the same bucket, the efficiency of finding an object in the hash table reduces to that of a linked list, so hash functions are generally implemented to ensure a unique number (or as unique as possible) to every object. Python dictionaries are hash tables that automatically grow as space is needed. While integers in the range of the list will never change location unless the list shrinks, larger hash codes can move around quite apparently randomly. Space available is also a factor, as others have found out on this list. The order of a dictionary *is* determined, but factors involved in deciding that order may appear surprisingly mundane, and certainly variable across runs of your program. From software at ginstrom.com Tue Jan 8 05:29:11 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Tue, 8 Jan 2008 19:29:11 +0900 Subject: Look for a string on a file and get its line number In-Reply-To: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> Message-ID: <03a301c851e1$4f211a00$0203a8c0@MOUSE> > On Behalf Of Horacius ReX > I have to search for a string on a big file. Once this string > is found, I would need to get the number of the line in which > the string is located on the file. Do you know how if this is > possible to do in python ? This should be reasonable: >>> for num, line in enumerate(open("/python25/readme.txt")): if "Guido" in line: print "Found Guido on line", num break Found Guido on line 1296 >>> Regards, Ryan Ginstrom From lists at cheimes.de Sun Jan 27 20:37:08 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 28 Jan 2008 02:37:08 +0100 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: <92e2e361-68f4-4cd2-b0d4-750e19a06faf@s19g2000prg.googlegroups.com> References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net><60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <92e2e361-68f4-4cd2-b0d4-750e19a06faf@s19g2000prg.googlegroups.com> Message-ID: Paul McGuire wrote: > I thought at one time there was to be a "decorators" module in the > stdlib for just this kind of useful item. At minimum, you could post > this to the Python wiki at http://wiki.python.org/moin/PythonDecoratorLibrary. Please take the idea to the Python developer list. Several decorators are either already implemented (e.g. the first decorator is functools.wraps) and others are too special but some of the decorators including auto assignment seem useful. Christian From fredrik at pythonware.com Wed Jan 9 16:39:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 22:39:28 +0100 Subject: alternating string replace: Extended input (Long). In-Reply-To: References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: Paddy wrote: > To see how they act against 'corner cases' and > an exercise for me in trying to create corner cases. (I'm in to > functional testing at the mo'). sounds more like "pulling requirements out of thin air". not sure that helps the OP get a better understanding of Python, really. From kyosohma at gmail.com Sat Jan 12 09:32:35 2008 From: kyosohma at gmail.com (Mike) Date: Sat, 12 Jan 2008 06:32:35 -0800 (PST) Subject: Great Python books for the beginner References: <87fxx3gnoz.fsf@benfinney.id.au> Message-ID: <6d07f64b-beba-4e81-a4a9-4a7f21de473d@v46g2000hsv.googlegroups.com> On Jan 12, 7:47 am, Ben Finney wrote: > Landon writes: > > I was wondering if anyone had any opinions on what other titles I > > could look into since this one seems from a glance at reviews to be > > teaching mainly through game programming (a topic I'm not too > > interested in) or if this one is a quality book by itself. > > The book "Learning Python" is currently proving very useful to an > associate of mine. I'm watching his knowledge of Python grow > substantially every week, from what was an essentially zero start. > > Learning Python, 3rd Edition > Mark Lutz > O'Reilly > > > Looking through the text, it is very well structured, thoroughly > teaching all the fundamentals of the language and types and idioms > while referring back to already-learned material. The author makes a > living training people in Python, and the third edition has benefited > from his many years of experience finding effective ways to teach the > language. > > -- > \ "If you ever teach a yodeling class, probably the hardest thing | > `\ is to keep the students from just trying to yodel right off. | > _o__) You see, we build to that." -- Jack Handey | > Ben Finney I would recommend Lutz's other book, the wonderful Python tome "Programming Python 3rd Ed." as well. It's good for getting into the deepest part of Python's jungle. Mike From mail at timgolden.me.uk Wed Jan 23 10:10:07 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Jan 2008 15:10:07 +0000 Subject: subprocess and & (ampersand) In-Reply-To: References: Message-ID: <479758CF.5070600@timgolden.me.uk> Ross Ridge wrote: > Tim Golden wrote: >> but this doesn't: >> >> >> "c:\Program Files\Mozilla Firefox\firefox.exe" "%*" >> >> >> >> import subprocess >> >> cmd = [ >> r"c:\temp\firefox.bat", >> "http://local.goodtoread.org/search?word=tim&cached=0" >> ] >> subprocess.Popen (cmd) >> >> > > You need to use double quotes both in the .BAT file and in the string > you pass to subprocess.Popen(). > > Ross Ridge In the context of my example above, could you just say which bit you thing should be quoted and isn't? (That sounds sarcastic, but isn't; I just want to understand if I've missed something). If you simply requote the second element in the cmd list ('"http:/....."') then the internal quotes are escaped by some part of the mechanism and it still doesn't work. TJG From deets at nospam.web.de Sun Jan 20 13:50:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 20 Jan 2008 19:50:44 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt In-Reply-To: References: Message-ID: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> pythonewbie schrieb: > On 20 jan, 12:20, Christian Heimes wrote: >> pythonewbie wrote: >>> I am stucked on creating a function to get the Python install >>> directory (and site-packages directory) with a 100% reliable method... >> Only one method is 100% reliable: >> >> try: >> import yourextension >> except ImportError: >> available = False >> else: >> available = True >> >> Christian > > Hi Christian, > > OK thanks, interesting to detect if an extension is available or not. > > But for different reasons I also want to get the absolute path of > Python install directory (not only the executable under Linux) and > site-packages directory. > > How could I proceed ? Maybe sys.path is a starter? Diez From grante at visi.com Mon Jan 28 15:49:35 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 28 Jan 2008 20:49:35 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> <6067h9F1otsbrU1@mid.individual.net> <13ps3djqrl4ap5b@corp.supernews.com> <606s53F1p4slrU1@mid.individual.net> Message-ID: <13psfuvk77f5oc3@corp.supernews.com> On 2008-01-28, Bjoern Schliessmann wrote: > Grant Edwards wrote: >> No, it doesn't output corresponding machine code (that's what >> some Java JIT implementations do, but I'm not aware of any >> Python implementations that do that). The virtual machine >> interpreter just does the action specified by the bytecode. > > By "outputs corresponding machine code" I meant "feeds corresponding > machine code to the CPU" to make the analogy clearer. Which can > mean a function call. OK, but I think you're reaching a little. :) It's pretty hard for me to think of a program as something that's "feeding machine code to the CPU". In my mind, the VM is a program that's reading data from one source (the bytecode files) and performing operations on a second set of data (in-memory structures representing Python objects) based on what is found in that first set of data. -- Grant Edwards grante Yow! Is it clean in other at dimensions? visi.com From Karsten.Hilbert at gmx.net Mon Jan 14 12:46:33 2008 From: Karsten.Hilbert at gmx.net (Karsten Hilbert) Date: Mon, 14 Jan 2008 18:46:33 +0100 Subject: problem with logging exceptions with non-ASCII __str__ result Message-ID: <20080114174633.GH3926@merkur.hilbert.loc> Dear all, I have a problem with logging an exception. environment: Python 2.4, Debian testing ${LANGUAGE} not set ${LC_ALL} not set ${LC_CTYPE} not set ${LANG}=de_DE.UTF-8 activating user-default locale with returns: [de_DE.UTF-8] locale.getdefaultlocale() - default (user) locale: ('de_DE', 'utf-8') encoding sanity check (also check "locale.nl_langinfo(CODESET)" below): sys.getdefaultencoding(): [ascii] locale.getpreferredencoding(): [UTF-8] locale.getlocale()[1]: [utf-8] sys.getfilesystemencoding(): [UTF-8] _logfile = codecs.open(filename = _logfile_name, mode = 'wb', encoding = 'utf8', errors = 'replace') logging.basicConfig ( format = fmt, datefmt = '%Y-%m-%d %H:%M:%S', level = logging.DEBUG, stream = _logfile ) I am using psycopg2 which in turn uses libpq. When trying to connect to the database and providing faulty authentication information: try: ... try to connect ... except StandardError, e: _log.error(u"login attempt %s/%s failed:", attempt+1, max_attempts) print "exception type :", type(e) print "exception dir :", dir(e) print "exception args :", e.args msg = e.args[0] print "msg type :", type(msg) print "msg.decode(utf8):", msg.decode('utf8') t,v,tb = sys.exc_info() print "sys.exc_info() :", t, v _log.exception(u'exception detected') the following output is generated: exception type : exception dir : ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] exception args : ('FATAL: Passwort-Authentifizierung f\xc3\xbcr Benutzer \xc2\xbbany-doc\xc2\xab fehlgeschlagen\n',) msg type : msg.decode(utf8): FATAL: Passwort-Authentifizierung f?r Benutzer ?any-doc? fehlgeschlagen sys.exc_info() : psycopg2.OperationalError FATAL: Passwort-Authentifizierung f?r Benutzer ?any-doc? fehlgeschlagen Traceback (most recent call last): File "/usr/lib/python2.4/logging/__init__.py", line 739, in emit self.stream.write(fs % msg.encode("UTF-8")) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 191: ordinal not in range(128) Now, the string "FATAL: Passwort-Auth..." comes from libpq via psycopg2. It is translated to German via gettext within libpq (at the C level). As we can see it is of type string. I know from the environment that it is likely encoded in utf8 manually applying which (see the decode call) succeeds. On _log.exception() the logging module wants to output the message as encoded as utf8 (that's what the log file is set up as). So it'll look at the string, decide it is of type "str" and decode with the *Python default encoding* to get to type "unicode". Following which it'll re-encode with utf8 to get back to type "str" ready for outputting to the log file. However, since the Python default encoding is "ascii" that conversion fails. Changing the Python default encoding isn't really an option as it is advocated against and would have to be made to work reliably on other users machines. One could, of course, write code to specifically check for this condition and manually pre-convert the message string to unicode but that seems not as things should be. How can I cleanly handle this situation ? Should the logging module internally use an encoding gotten from the locale module rather than the default string encoding ? Karsten -- GPG key ID E4071346 @ wwwkeys.pgp.net E167 67FD A291 2BEA 73BD 4537 78B9 A9F9 E407 1346 From marduk at python.invalid Sun Jan 20 22:15:02 2008 From: marduk at python.invalid (Albert Hopkins) Date: Sun, 20 Jan 2008 21:15:02 -0600 Subject: When is min(a, b) != min(b, a)? Message-ID: This issue may have been referred to in news: but I didn't entirely understand the explanation. Basically I have this: >>> a = float(6) >>> b = float('nan') >>> min(a, b) 6.0 >>> min(b, a) nan >>> max(a, b) 6.0 >>> max(b, a) nan Before I did not know what to expect, but I certainly didn't expect this. So my question is what is the min/max of a number and NaN or is it not defined (for which I would have expected either an exception to be raised or NaN returned in each case). As a corrollary would I be able to rely on the above behavior or is it subject to change (to fix a bug in min/max perhaps :-)? From arkanes at gmail.com Fri Jan 25 21:55:41 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 25 Jan 2008 20:55:41 -0600 Subject: looking for a light weighted library/tool to write simple GUI above the text based application In-Reply-To: <45a8d4a7-d24d-461e-9783-59a7d697a041@q77g2000hsh.googlegroups.com> References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> <45a8d4a7-d24d-461e-9783-59a7d697a041@q77g2000hsh.googlegroups.com> Message-ID: <4866bea60801251855s305da3ebx4eb4c51a202b5a8a@mail.gmail.com> On Jan 25, 2008 5:17 PM, Paul Boddie wrote: > On 25 Jan, 22:06, "Lorenzo E. Danielsson" > wrote: > > > > What you need then is something like SVGAlib (http;//svgalib.org). Only > > really old people like myself know that it exists. I've never heard of > > any Python bindings for it, but that might be where you come in. I > > haven't looked at SVGAlib for years, and I'm not sure about the state of > > the video drivers. I suggest you look at that first. > > I believe that SVGAlib was superseded by GGI and other projects, and I > recall that SVGAlib was considered to be something of a nightware with > respect to how it handles various resources. Certainly, I haven't been > very impressed by the behaviour of software using it. > > > You could also look at GGI (http://ggi-project.org). GGI has different > > output targets. IIRC, one of them is directfb. To tell you the truth > > I've never really used GGI. There seems to be a python wrapper for GGI, > > although it is fairly old. Maybe you could look at the code for some ideas. > > I've had to build software using GGI, and the biggest problem has been > getting packages for it. That said, it seemed to work fairly > acceptably once built and installed. Meanwhile, some people favour > Allegro [1] for this kind of work, and I've been confronted with newly > developed software which uses Allegro, so it's arguably in a different > maintenance state than something like SVGAlib or GGI. > > > You should also be able to compile SDL to be able to use directfb as a > > target. If your libSDL handles it, then that should apply to wrapper > > libraries as well, including pygame. I've never tried running SDL apps > > this way, but if it works well, that would probably be your 'best' option. > > I'd agree with these sentiments; SDL seems to be the best supported > technology of this kind in the Python universe, and one of the most > widely deployed in general; I've felt quite comfortable building > software against it. It would be very interesting to see whether a > framebuffer-based SDL could support Pygame, and I imagine that the > Pygame mailing list might already have some answers in its archives on > this topic. > I agree that SDL is probably the best choice but for the sake of completeness, Gtk can (at least in theory - I've never tried it) be built against directfb and run without X. From duncan.booth at invalid.invalid Fri Jan 25 13:39:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Jan 2008 18:39:31 GMT Subject: is possible to get order of keyword parameters ? References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> Message-ID: rndblnch wrote: > (sorry, draft message gone to fast) > > i.e. is it possible to write such a function: > > def f(**kwargs): > > return result > > such as : > f(x=12, y=24) == ['x', 'y'] > f(y=24, x=12) == ['y', 'x'] > > what i need is to get the order of the keyword parameters inside the > function. > any hints ? > It would be best to do something which makes it obvious to someone reading the function call that something magic is going on. Either get people to pass a tuple, or if you want you could wrap a tuple in some sugar: class _OrderedVal(object): def __init__(self, name, current): self._name = name self._current = current def __call__(self, value): return _Ordered(self._current + ((self._name, value),)) class _Ordered(tuple): def __init__(self, current=()): self._current = current def __getattr__(self, name): return _OrderedVal(name, self._current) ordered = _Ordered() def f(args): return [ k for (k,v) in args] print f(ordered.x(12).y(24)) print f(ordered.y(24).x(12)) The question remains, what use is there for this? From ggpolo at gmail.com Mon Jan 7 08:57:38 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 11:57:38 -0200 Subject: dealing with binary files In-Reply-To: <47822DA4.9020401@fmed.uba.ar> References: <47822DA4.9020401@fmed.uba.ar> Message-ID: 2008/1/7, Gerardo Herzig : > Hi all. Im trying to read a binary data from an postgres WAL archive. > If i make a > xfile = open('filename', 'rb').xreadlines() > line = xfile.next() > > i see this sort of thing: > ']\xd0\x03\x00\x01\x00\x00\x00\r\x00\x00\x00\x00\x00\x00JM//DI+,D\x00\x00\x00\x01$\x00\x00\x00\x7f\x06\x00\x00y\r\t\x00\x02\x0f\t\x00\x00\x00\x10\x00)\x00\x01\x00\x12\x08 > \x00^\xc2\x0c\x00\x08\x00\x00\x003001({\xe8\x10\r\x00\x00\x00\xe4\xff\xffI\x10?l\x01@\x00\x00\x00$\x00\x00\x00\x00\n' > > This file suppose to have some information about database activity, but > at this point i cant do more than this, because i cant figure out what > to do in order to have some 'readable' text. > > Im guessing is some C code, im reading the struct module to see if it > helps, but im not into C programming, and im lost at the start of my > problem. You are looking at the correct module, struct. But in order to understand or even correctly extract data from a binary file, you need to know its structure. There should be some document describing the Postgre WAL file format. > > Can someone point me out some advice? > Thanks! > > Gerardo > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From ivan.illarionov at gmail.com Thu Jan 31 17:58:22 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 31 Jan 2008 14:58:22 -0800 (PST) Subject: REALLY simple xml reader 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: > 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. From nagle at animats.com Fri Jan 11 14:41:41 2008 From: nagle at animats.com (John Nagle) Date: Fri, 11 Jan 2008 11:41:41 -0800 Subject: Analyzing Python GC output - turns out to be MySQLdb problem In-Reply-To: References: <478707f2$0$36360$742ec2ed@news.sonic.net> <4787a42e$0$36403$742ec2ed@news.sonic.net> Message-ID: <4787C675.3030201@animats.com> Francesco Guerrieri wrote: > On Jan 11, 2008 6:20 PM, John Nagle wrote: >> Tried: >> print item.dir() >> got: >> 'cell' object has no attribute 'dir' It's a problem inside MySQLdb's "connections.py": def _get_unicode_literal(): def unicode_literal(u, dummy=None): return db.literal(u.encode(unicode_literal.charset)) return unicode_literal Each time a MySQLdb Connection object is created, it generates a closure, with another instance of the function "unicode_literal" plus some other junk. That generates circular references. Eventually those things get garbage-collected, but if you're running GC in leak detection mode, they show up. The reason for the closure is that "unicode_literal.charset" of the function is being stored into from outside the function. So there actually is a reason to use a closure. John Nagle From nospam-abuse at ilyaz.org Sat Jan 26 16:39:02 2008 From: nospam-abuse at ilyaz.org (Ilya Zakharevich) Date: Sat, 26 Jan 2008 21:39:02 +0000 (UTC) Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> Message-ID: [A complimentary Cc of this posting was sent to Summercool ], who wrote in article <27249159-9ff3-4887-acb7-99cf0d2582a8 at n20g2000hsh.googlegroups.com>: > so for example, it will grep for > > winter tire > tire > retire > tired > > but will not grep for > > snow tire > snow tire > some snowtires This does not describe the problem completely. What about thisnow tire snow; tire etc? Anyway, one of the obvious modifications of (^ | \b(?!snow) \w+ ) \W* tire should work. Hope this helps, Ilya From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 04:16:35 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 10:16:35 +0100 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <478733e8$0$18055$426a34cc@news.free.fr> Fredrik Lundh a ?crit : > A.T.Hofkamp wrote: > >> Now the question you need to answer for yourself, is how much more >> worth is >> your own time compared to the gain in CPU time. If you think they are >> equal (ie >> the problem as a whole should be solved as fast as possible, thus the >> sum of >> development time + execution time should be as short as possible), you >> can >> spend an additional 1.5 seconds development in the alternative solution. > > so you only run your programs once? Lol !-) From robert.kern at gmail.com Sat Jan 5 19:59:49 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 05 Jan 2008 18:59:49 -0600 Subject: Request for help with Image color space conversion In-Reply-To: <37094242-5728-466f-a3b9-c5ae76a9f3c5@s12g2000prg.googlegroups.com> References: <8586a895-f238-4a22-a1bb-31c39f22b4cc@n20g2000hsh.googlegroups.com> <37094242-5728-466f-a3b9-c5ae76a9f3c5@s12g2000prg.googlegroups.com> Message-ID: ttest wrote: >> Reimplement colorsys.rgb_to_hsv() such that it operates on arrays instead of >> scalars. Only minor modifications are necessary. >> >> -- >> Robert Kern > > Thanks! I'll try and see if a newcomer like me can get his head > around the array-centric modifications to colorsys. If you hit any roadblocks, drop in on numpy-discussion, and we'll help you out. http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mensanator at aol.com Mon Jan 7 17:54:02 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 7 Jan 2008 14:54:02 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python References: Message-ID: On Jan 7, 4:37?pm, dgoldsmith_89 wrote: > Can anyone point me to a downloadable open source English dictionary > suitable for programmatic use with python: I'm programming a puzzle > generator, and I need to be able to generate more or less complete > lists of English words, alphabetized. ?Thanks! ?DG www.puzzlers.org has numerous word lists & dictionarys in text format that can be downloaded. I recommend you insert them into some form of database. I have most of them in an Access db and it's 95 MB. That's a worse case as I also have some value-added stuff, the OSPD alone would be a lot smaller. From dg.google.groups at thesamovar.net Sun Jan 20 15:51:36 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Sun, 20 Jan 2008 12:51:36 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Message-ID: <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> Hi Marek, That's a really nice solution (and ultrafast). Unfortunately I realise I stated the problem imprecisely. You're only allowed to use each number once (otherwise there's a trivial solution for every problem, i.e. x/x + x/x + x/x + ... + x/x repeated y times for target y given any source number x). Trying your program on 234 from [100,9,7,6,3,1] gives you 9*9*3-9 using the 9 three times. Does your solution adjust to deal with this additional requirement? At first I thought it would be an easy fix, but maybe it's a little more complicated than I thought... Dan Goodman From HoustonJuliet at yahoo.com Sat Jan 26 19:54:55 2008 From: HoustonJuliet at yahoo.com (HoustonJuliet) Date: Sat, 26 Jan 2008 16:54:55 -0800 (PST) Subject: do design patterns still apply with Python? In-Reply-To: <15114748.post@talk.nabble.com> References: <8SINf.1718$No6.40137@news.tufts.edu> <120eok46fkf0j2b@corp.supernews.com> <15114746.post@talk.nabble.com> <15114748.post@talk.nabble.com> Message-ID: <15114781.post@talk.nabble.com> I think the world of Oliver Reed, and I was so sad to learn about his death. I always had a crush on Oliver Reed, and I have been a fan for over 35 years now. I was born on June 13, 1972, and I am 35 years old. HoustonJuliet wrote: > > I am a fan of Oliver Reeds since a toddler > > HoustonJuliet wrote: >> >> I am a fan of these people: >> >> Goldie Hawn >> Kate Hudson >> Oliver Reed >> Robert Conrad >> Vic Morrow >> Bill Bixby >> >> >> >> >> Grant Edwards wrote: >>> >>> On 2006-03-02, John Salerno wrote: >>> >>>> Since Python does so many things different, especially compared to >>>> compiled and statically typed languages, do most of the basic design >>>> patterns still apply when writing Python code? >>> >>> Definitely. Especially plaid, paisley, and a nice medium >>> houndstooth check. But please, not all at the same time. >>> >>> -- >>> Grant Edwards grante Yow! Maybe we could >>> paint >>> at GOLDIE HAWN a rich >>> PRUSSIAN >>> visi.com BLUE -- >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> :drunk: >> > > :drunk: -- View this message in context: http://www.nabble.com/do-design-patterns-still-apply-with-Python--tp3210321p15114781.html Sent from the Python - python-list mailing list archive at Nabble.com. From roman.yakovenko at gmail.com Sat Jan 12 02:24:33 2008 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Sat, 12 Jan 2008 09:24:33 +0200 Subject: opensg or openscenegraph In-Reply-To: <88ef87d8-d63b-4a7e-96db-07bc2a7a1fc9@s19g2000prg.googlegroups.com> References: <40zfj.33787$lD6.31634@newssvr27.news.prodigy.net> <88ef87d8-d63b-4a7e-96db-07bc2a7a1fc9@s19g2000prg.googlegroups.com> Message-ID: <7465b6170801112324p72bc8f77ye044438e47663afa@mail.gmail.com> On Jan 11, 2008 10:01 PM, wrote: > On Jan 4, 3:08pm, yomgui wrote: > > Hi, > > > > I need to use a scengraph for my python/opengl application > > but I have trouble finding out which one I should use. > > > > opensg or openscenegraph (OSG) ? > > > > I suppose the quality of the python bindings will make the decision. > > > > any advice ? > > > > thanks > > > > yomgui > > Hi yomgui, > > I am considering either of these as well for writing a simulation > game. > The Python Bindings I have found to date are: > > For OpenSG: > https://realityforge.vrsource.org/trac/pyopensg > > For OSG (there seems to be several variations of these): > http://code.astraw.com/projects/pyosg > > I suppose you could also use something like Py++ to create your own. PyOpenSG uses Py++ too :-) -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From george.sakkis at gmail.com Mon Jan 14 09:01:31 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 14 Jan 2008 06:01:31 -0800 (PST) Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> Message-ID: By the way, why do we need both NotImplementedError and the NotImplemented singleton object ? Couldn't we have just one of them ? From tjreedy at udel.edu Sun Jan 27 18:58:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jan 2008 18:58:48 -0500 Subject: Python self-evaluating strings References: <1BEEBF03-1A38-4745-B08B-DCA3106D1CC5@gmail.com> Message-ID: "Arnaud Delobelle" wrote in message news:1BEEBF03-1A38-4745-B08B-DCA3106D1CC5 at gmail.com... | An earlier post today got me thinking about "quines" (programs that | output themselves) in Python. I tried to find some on the web but | didn't find many ([1]). In particular I didn't find any that | corresponded to my instinctive (LISP-induced, probably) criterion: ... | I'd like to know if anyone on the list has indulged in this time- | bending/mind-wasting activity before. If so, it would be nice to | create a list of such expressions. Some years ago there was a substantial thread on this, (Shortest Self-Reproducing Programs, or some such) including a fairly long one from me that gave several 'shortest' (depending of definition and input method). It included a Python tranlation of at least one standard Lisp version. I presume you could find it on groups.google Terry J. Reedy From brunoacf at gmail.com Fri Jan 4 07:31:55 2008 From: brunoacf at gmail.com (Bruno Ferreira) Date: Fri, 4 Jan 2008 09:31:55 -0300 Subject: problem with global var In-Reply-To: References: Message-ID: <3448388f0801040431y37d9b58chdd4c7b120a17e30f@mail.gmail.com> Hello all, Amazing :) The program is working properly now, the code is much better and I learned a bit more Python. Thank you all, guys. Bruno. 2008/1/4, Peter Otten <__peter__ at web.de>: > Bruno Ferreira wrote: > > > I wrote a very simple python program to generate a sorted list of > > lines from a squid access log file. > > Now that your immediate problem is solved it's time to look at the heapq > module. It solves the problem of finding the N largest items in a list > much more efficiently. I think the following does the same as your code: > > import heapq > > def key(record): > return int(record[4]) > > logfile = open("squid_access.log", "r") > records = (line.split() for line in logfile) > topsquid = heapq.nlargest(50, records, key=key) > > for record in topsquid: > print record[4] > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From martin at marcher.name Sun Jan 20 14:58:34 2008 From: martin at marcher.name (Martin Marcher) Date: Sun, 20 Jan 2008 20:58:34 +0100 Subject: Looping through the gmail dot trick References: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> Message-ID: On Sunday 20 January 2008 17:38 Joshua Gilman wrote: > So I have a very interesting task ahead of me and it is to loop through an > email using the 'gmail dot trick'. Essentially this trick puts periods > throughout your email to make it look different. Even though it has > periods gmail will replace them all and send it to that email. are you saying that when i have 2 gmail addresses "foo.bar at gmail.com" and "foobar at gmail.com" they are actually treated the same? That is plain wrong and would break a lot of mail addresses as I have 2 that follow just this pattern and they are delivered correctly! Do you have any reference on that where one could read up why gmail would have such a behaviour? > So blah at gmail.com is the same as bl.ah at gmail.com. To my best knowledge it is not the same and must not be the same. The localpart of an email is entirely up to the receiving mailserver and cannot be tempered with without risking misdelivery (at least). If I'm wrong I'd be gladly corrected, just point me to the references. /martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From globophobe at gmail.com Fri Jan 25 21:11:28 2008 From: globophobe at gmail.com (globophobe) Date: Fri, 25 Jan 2008 18:11:28 -0800 (PST) Subject: ElementTree.fromstring(unicode_html) Message-ID: <58b4d6e5-da52-4247-9892-3fbcfd0f1979@m34g2000hsb.googlegroups.com> This is likely an easy problem; however, I couldn't think of appropriate keywords for google: Basically, I have some raw data that needs to be preprocessed before it is saved to the database e.g. In [1]: unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f \u3044\r\n' I need to turn this into an elementtree, but some of the data is japanese whereas the rest is html. This string contains a
. In [2]: e = ET.fromstring('%s' % unicode_html) In [2]: e.text Out[3]: u'\u3055\u3080\u3044\uff0f\n\u3064\u3081\u305f\u3044\n' In [4]: len(e) Out[4]: 0 How can I decode the unicode html
into a string that ElementTree can understand? From zorg724 at yahoo.fr Tue Jan 29 18:25:26 2008 From: zorg724 at yahoo.fr (sccs cscs) Date: Wed, 30 Jan 2008 00:25:26 +0100 (CET) Subject: Python UML Metamodel Message-ID: <183729.1052.qm@web90504.mail.mud.yahoo.com> Hello, I find an OPEN SOURCE tool (http://bouml.free.fr/) that Recently generates Python code from UML model. I like to model the Python language metamodel himself, with it, e.g the model of the language: I need that to better understand the language constraint of the language. for example, i like to model that : -a class "class" may inherit from 0..* class -a class "class" is create from a class that is its "metaclass" -a class "class" has 0..n attributes and 0..n method -a class "module" has 0..n class "class" Does anyone know a document that describes it already, because I think it is complicated to find this information in the documentation of Python. For example, can i say that: -a class "class" has 0..n properties ? It seems that the Python metamodel is not perfect, because I do not find attribute which give me the property list with a code like: "myPropertyList = myclass.properties" - a class "method" can contains nested "method", but what is the way to get a list of internal methods, without use ? Can i just write: "myNestedMethodList = method.nestedMethodList" I think a metamodel Python would be welcome to complement the BNF (http://docs.python.org/ref/grammar.txt), so as to know fully understand the relationships between the various elements of language. Thank you --------------------------------- Ne gardez plus qu'une seule adresse mail ! Copiez vos mails vers Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Mon Jan 14 06:30:04 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 14 Jan 2008 05:30:04 -0600 Subject: Threaded server References: Message-ID: Giampaolo Rodola' wrote: > I'm trying to run an asynchronous FTP server I wrote into a thread for > being able to run a test suite against it. > The code below is the threaded FTP server code I'm using: > > class FTPd(threading.Thread): > > def __init__(self): > self.active = False > threading.Thread.__init__(self) > > def start(self, flag=None): > assert not self.active > self.flag = flag > threading.Thread.start(self) > > def run(self): > assert not self.active > ftpd = ftpserver.FTPServer(address, ftp_handler) > if self.flag: > self.flag.set() > self.active = True > while self.active: > ftpd.server_forever(timeout=1, count=1) > ftpd.close() > > def stop(self): > assert self.active > self.active = False > > flag = threading.Event() > ftpd = FTPd() > ftpd.start(flag) > flag.wait() # wait for it to start > unittest.main() # run the test suite > ftpd.stop() > > Sometimes I get a strange error when all the tests have finished, the > server is stopped and Python is exiting: > > Ran 50 tests in 1.515s > > OK > Exception exceptions.TypeError: "'NoneType' object is not callable" in > thod FTPHandler.__del__ of 127.0.0.1:2 > 249 at 0xa4b080>> ignored > Exception exceptions.TypeError: "'NoneType' object is not callable" in > thod FTPServer.__del__ of 127.0.0.1:543 > 21 at 0x9e1a30>> ignored > > > I sincerely don't know why that happens but it's likely because I'm > not using threads properly. > My concern is that this could be caused by a sort of race condition > (e.g. Python tries to exit when ftpd.close call is not yet > completed). It looks like when python is shutting down, it has removed an object the ftphandler code relies on. I see you attempt to kill the ftp server with ftpd.stop(). That is good, but you don't wait for the thread to finish (it might take up to a second in ftpd.server_forever if I understand correctly). I expect if you put a self.join() at the end of the stop() method the problem will go away. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bronger at physik.rwth-aachen.de Thu Jan 10 07:20:10 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 10 Jan 2008 13:20:10 +0100 Subject: Conventions for dummy name References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de> <873at6k2qt.fsf_-_@benfinney.id.au> <87sl1613c8.fsf@physik.rwth-aachen.de> Message-ID: <87odbt27ph.fsf@physik.rwth-aachen.de> Hall?chen! David.Reksten at sweco.no writes: > Torsten Bronger wrote: > >> [...] >> >> Right, that's because I've used "__" where not all returning >> values are interesing to me such as >> >> a, b, __ = function_that_returns_three_values(x, y) > > Variable name "dummy" serves the same purpose, such as: > > a, b, dummy = function_that_returns_three_values(x, y) Granted, but my rationale is that "__" is less visible in the source code, so there is more emphasis on the actually interesting variables. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From a at b.c Thu Jan 10 08:37:05 2008 From: a at b.c (Caleb) Date: Thu, 10 Jan 2008 15:37:05 +0200 Subject: Python's great, in a word In-Reply-To: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: > The best thing about Python is _______. this. From sambo at voidstar.com Wed Jan 23 18:09:11 2008 From: sambo at voidstar.com (Sambo) Date: Wed, 23 Jan 2008 18:09:11 -0500 Subject: port forwarding: python scrypt or C ? Message-ID: Anyone aware of something that I could test my new DSL modem with. when I finally unlocked it ( Siemens 4200 ) some setting I saw made me wonder if it is filtering at all, but tiberian sun internet play was having problems. After going through the instructions at {http://portforward.com/english/routers/port_forwarding/Siemens/4200/Command_and_Conquer_Tiberian_Sun.htm} although not carefully since later I realized they entered the stuff in different order (not lowest to highest like I did, but it's not IPtables so hopefully it shouldn't matter). Soooo, I'd like to see it to believe it. Since I'll most likely going test from dialup on Linux to DSL on windows, Python would be best. Cheers. From mr.cerutti at gmail.com Fri Jan 18 13:20:33 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 18 Jan 2008 13:20:33 -0500 Subject: Bug in __init__? In-Reply-To: References: Message-ID: <51302a8c0801181020m3b5d4bebjf7ba6db9672bed9d@mail.gmail.com> On Jan 18, 2008 12:33 PM, Zbigniew Braniecki wrote: > > class A: > > def __init__ (self, val=[]): > > print val > > self.lst = val > > > > val is created only *once* and shared across all instaces of A. > > Thanks for help guys! > > It's really a nice pitfall, I can hardly imagine anyone expecting this, > or how easily could I find this info (e.g. what query should I give to > google to get it without bothering people on this group) In this unfortunate case, useful searches were "default arguments", which would be hard to guess without already knowing what's going wrong, or "python gotchas pitfalls", which is a good general purpose search for when you can't understand what's happening in simple code. -- Neil Cerutti From __peter__ at web.de Thu Jan 17 13:07:04 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jan 2008 19:07:04 +0100 Subject: Interesting Thread Gotcha References: Message-ID: Hendrik van Rooyen wrote: > "Duncan Booth" wrote: > >> Given that the start_new_thread function never actually got called, what >> code exactly do you expect to complain about the absence of a tuple? > > I don't understand this assertion. > > I thought that start_new_thread was called with a missing comma in > its argument list, which had the effect that I am complaining about. > > Putting the comma in place solved the problem, without any other > changes, so why do you say that start_new_thread was not called? Well, when kbd_driver() is called the kbd_q queue is probably empty, and as kbd_driver() runs in the main thread, who could ever put something into that queue? The function will therefore never terminate. Peter From SSchukat at dspace.de Fri Jan 4 08:50:45 2008 From: SSchukat at dspace.de (Stefan Schukat) Date: Fri, 4 Jan 2008 14:50:45 +0100 Subject: pydepend (checking dependencies like jdepend) ? References: <1969e240-9e80-4df1-b085-7956dfa4f7ae@t1g2000pra.googlegroups.com> <71a1c5ae-2051-44ff-998e-a342fa88ffab@e25g2000prg.googlegroups.com> Message-ID: <3E7E58237D756A4D85E7A36CB8C953ED01E24A@exchange2003.dspace.de> No, py2exe does not display such information but has an algorithm to collect such information. Perhaps this is a starting point for you. Stefan -----Original Message----- From: python-list-bounces+sschukat=dspace.de at python.org [mailto:python-list-bounces+sschukat=dspace.de at python.org] On Behalf Of Bernhard Merkle Sent: Friday, January 04, 2008 2:25 PM To: python-list at python.org Subject: Re: pydepend (checking dependencies like jdepend) ? On Jan 4, 1:57 pm, "Stefan Schukat" wrote: > Hi, > > try to look at py2exe. This module scans all dependencies to pack them > into one executable. my intention is to _know_ (or display or list or whatever) the dependencies. (see also my original posting). The aim is to control and have a view on modularization and e.g. avoid unnecessary bidirectional dependencies etc. does py2.exe display such information ? Berni. -- http://mail.python.org/mailman/listinfo/python-list From arnodel at googlemail.com Sun Jan 27 17:46:56 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 27 Jan 2008 14:46:56 -0800 (PST) Subject: explicit protocols and duck typing References: <5e28034f-a20f-4aa7-b299-9c9132ef2566@c4g2000hsg.googlegroups.com> Message-ID: On Jan 27, 7:10?pm, dg.google.gro... at thesamovar.net wrote: > Hi all, > > As I understand it, the idea behind duck typing is that you just take > an object and if it has the methods you want to use you use it > assuming it to be the right type of object. I'm interested in > extending this idea a bit, but I feel the sort of thing I have in mind > has already been thought of. So for example, in the program I'm > writing a 'state variable' specifier can be either an integer or a > string (the string name is mapped to an integer by another function > getvarindex(name)). In this case, I can't do duck typing by seeing if > the object has a method or not, because both of the types are built in > types. I don't want to have to force the user to have objects like > StateVariableSpecifier(name). Now at the moment, what I'm doing is > accepting anything as a state variable specifier, and just passing it > through the getvarindex function when I want to use it. This sort of > specifies a protocol for state variable specifiers without making it > explicit (like the sequence or mapping protocols built in to Python). > > What I'm wondering though is whether there is any value in making this > more explicit? Say, have a class which makes explicit the various > relationships involved, such as that the type of a state variable > specifier can be correct or incorrect (it has to be an int or a > string), that the value has to be correct (the integer has to be > between 0 and n for some n, and the string has to be in a dict of > names), and that there is a relationship between state variable > specifiers (int, string) and the underlying data type (the index of > the variable in an array). Making it more explicit seems like a good > idea, the question is in what way to make it more explicit. I can make > it explicit just by documenting the behaviour, or I can make it > explicit by adding code that enforces certain ways of using things. I would filter uses of a state variable specifier through a 'decode' function: def decode_svs(svs): for decode in decode_as_int, decode_as_str: try: return decode_as_int(svs) except DecodeError: continue raise DecodeError("Invalid svs") That could be done via overloading (see below) > For this simple example, it seems like just documenting it is the best > route, but I have similar issues with other more complicated parts of > the code. At the moment, a model for instance can be a Model object, > an Equation object or a tuple of functions, but this could be subject > to change in the future. What does object have to promise to be able to do in order to be a 'model'? > The issue I want to address is the long term maintainability of the > code when possibly many people might be contributing, the transparency > for other users, and the ease of documenting it. Any opinions? Maybe I'm way off mark here, but have you looked at overloading/ generic functions? The concept is explained in PEP 3124 [http://www.python.org/dev/peps/ pep-3124/] There's an implementation by Philip J. Eby in the svn repository: Some documentation: http://svn.python.org/view/sandbox/trunk/Overload3K/overloading.txt?rev=45971&view=markup The implementation: http://svn.python.org/view/sandbox/trunk/Overload3K/overloading.py?rev=45971&view=markup From ppetrick at gmail.com Mon Jan 21 15:51:59 2008 From: ppetrick at gmail.com (p.) Date: Mon, 21 Jan 2008 12:51:59 -0800 (PST) Subject: Transforming ascii file (pseduo database) into proper database Message-ID: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> I need to take a series of ascii files and transform the data contained therein so that it can be inserted into an existing database. The ascii files are just a series of lines, each line containing fields separated by '|' character. Relations amongst the data in the various files are denoted through an integer identifier, a pseudo key if you will. Unfortunately, the relations in the ascii file do not match up with those in the database in which i need to insert the data, i.e., I need to transform the data from the files before inserting into the database. Now, this would all be relatively simple if not for the following fact: The ascii files are each around 800MB, so pulling everything into memory and matching up the relations before inserting the data into the database is impossible. My questions are: 1. Has anyone done anything like this before, and if so, do you have any advice? 2. In the abstract, can anyone think of a way of amassing all the related data for a specific identifier from all the individual files without pulling all of the files into memory and without having to repeatedly open, search, and close the files over and over again? From paul at boddie.org.uk Tue Jan 22 17:36:22 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 22 Jan 2008 14:36:22 -0800 (PST) Subject: Processing XML that's embedded in HTML References: <6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> Message-ID: On 22 Jan, 21:48, Mike Driscoll wrote: > On Jan 22, 11:32 am, Paul Boddie wrote: > > > [1]http://www.python.org/pypi/libxml2dom > > I must have tried this module quite a while ago since I already have > it installed. I see you're the author of the module, so you can > probably tell me what's what. When I do the above, I get an empty list > either way. See my code below: > > import libxml2dom > d = libxml2dom.parse(filename, html=1) > rows = d.xpath('//XML[@id="grdRegistrationInquiryCustomers"]/BoundData/ > Row') > # rows = d.xpath("//XML/BoundData/Row") > print rows It may be namespace-related, although parsing as HTML shouldn't impose namespaces on the document, unlike parsing XHTML, say. One thing you can try is to start with a simpler query and to expand it. Start with the expression "//XML" and add things to make the results more specific. Generally, namespaces can make XPath queries awkward because you have to qualify the element names and define the namespaces for each of the prefixes used. Let me know how you get on! Paul From bdesth.quelquechose at free.quelquepart.fr Mon Jan 21 17:15:40 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 23:15:40 +0100 Subject: Transforming ascii file (pseduo database) into proper database In-Reply-To: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> Message-ID: <47952796$0$17606$426a74cc@news.free.fr> p. a ?crit : > I need to take a series of ascii files and transform the data > contained therein so that it can be inserted into an existing > database. The ascii files are just a series of lines, each line > containing fields separated by '|' character. Relations amongst the > data in the various files are denoted through an integer identifier, a > pseudo key if you will. Unfortunately, the relations in the ascii file > do not match up with those in the database in which i need to insert > the data, i.e., I need to transform the data from the files before > inserting into the database. Now, this would all be relatively simple > if not for the following fact: The ascii files are each around 800MB, > so pulling everything into memory and matching up the relations before > inserting the data into the database is impossible. > > My questions are: > 1. Has anyone done anything like this before, More than once, yes. > and if so, do you have > any advice? 1/ use the csv module to parse your text files 2/ use a temporary database (which schema will mimic the one in the flat files), so you can work with the appropriate tools - ie: the RDBMS will take care of disk/memory management, and you'll have a specialized, hi-level language (namely, SQL) to reassemble your data the right way. > 2. In the abstract, can anyone think of a way of amassing all the > related data for a specific identifier from all the individual files > without pulling all of the files into memory and without having to > repeatedly open, search, and close the files over and over again? Answer above. From gowricp at gmail.com Sat Jan 12 02:31:48 2008 From: gowricp at gmail.com (Gowri) Date: Fri, 11 Jan 2008 23:31:48 -0800 (PST) Subject: converting JSON to string References: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> <13og5g06rvrtefa@corp.supernews.com> Message-ID: On Jan 11, 7:21 pm, Adonis Vargas wrote: > Gowri wrote: > > Hello, > > > I actually have two questions: > > 1. Are there any libraries which convert XML to JSON? > > 2. I am currently doing the above using the DOM parser and creating a > > JSON array > > > > > for node in doc.getElementsByTagName("book"): > > isbn = node.getAttribute("isbn") > > titleNode = (node.getElementsByTagName("title") > > [0]).childNodes[0] > > title = titleNode.data > > primarykeys.append({'isbn': isbn, 'title': title}) > > return primarykeys > > > I want to send primarykeys as a response to my client. i use > > mod_python and apache. The problem is, I have not been able to figure > > out how to convert my JSON output to a string. > > > Could someone please help me? > > > Thanks in advance > > do: > > return str(primarykeys) > > Also there are Python modules for just this. Here is the very first link > from Google: > > http://pypi.python.org/pypi/python-json > > I have used this one personally and have been very satisfied with it. > There is another one (CJSON?) which is similar, but written in C, for > when performance may be an issue. > > Hope this helps. > > Adonis Actually, I have one other problem after all this. I see that if I try to construct JSON output as above, it is of the form [{'isbn': u'1-56592-724-9', 'title': u'The Cathedral & the Bazaar'}, {'isbn': u'1-56592-051-1', 'title': u'Making TeX Work'}] The extra 'u' seems to causing syntax error in JavaScript which is not able to parse this response string. Any idea how I can fix this? From paddy3118 at googlemail.com Fri Jan 11 22:18:14 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 11 Jan 2008 19:18:14 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <7x7iifsrur.fsf@ruckus.brouhaha.com> Message-ID: On Jan 12, 2:55 am, Pablo Ziliani wrote: > * die, thread! :-) def altrep7(s): from itertools import cycle import re a = cycle(':,') return re.sub('_', lambda x: a.next(), s) altrep7.author="George Sakkis(&Paul Rubin)" Gives: ## Program by: George Sakkis(&Paul Rubin) '' RETURNS '' '1' RETURNS '1' '2_' RETURNS '2:' '3_4' RETURNS '3:4' '5_6_' RETURNS '5:6,' '7_8_9' RETURNS '7:8,9' '10_11_12_' RETURNS '10:11,12:' '13_14_15_16' RETURNS '13:14,15:16' '17_18_19_20_' RETURNS '17:18,19:20,' '_' RETURNS ':' '_21' RETURNS ':21' '_22_' RETURNS ':22,' '_23_24' RETURNS ':23,24' '_25_26_' RETURNS ':25,26:' '_27_28_29' RETURNS ':27,28:29' '_30_31_32_' RETURNS ':30,31:32,' '_33_34_35_36' RETURNS ':33,34:35,36' '__' RETURNS ':,' '___' RETURNS ':,:' '____' RETURNS ':,:,' '_____' RETURNS ':,:,:' - Paddy. From duncan.booth at invalid.invalid Thu Jan 3 08:45:59 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Jan 2008 13:45:59 GMT Subject: Treating a unicode string as latin-1 References: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Message-ID: Simon Willison wrote: > How can I tell Python "I know this says it's a unicode string, but I > need you to treat it like a bytestring"? Can you not just fix your xml file so that it uses the same encoding as it claims to use? If the xml says it contains utf8 encoded data then it should not contain cp1252 encoded data, period. If you really must, then try encoding with latin1 and then decoding with cp1252: >>> print u'Bob\x92s Breakfast'.encode('latin1').decode('cp1252') Bob?s Breakfast The latin1 codec will convert unicode characters in the range 0-255 to the same single-byte value. From timr at probo.com Fri Jan 18 02:04:50 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 18 Jan 2008 07:04:50 GMT Subject: ANN:proxysocket(socks4,socks5)v0.1 References: <7228288b-cb34-40ba-8483-a2dc57115511@d21g2000prf.googlegroups.com> Message-ID: Samuel wrote: > >http://code.google.com/p/proxysocket/downloads/list Allow me to introduce you to the concept of comments. Python allows you to include descriptive sentences in your program that explain what the functions do, what your intentions were, what the variables do, what the states mean, etc. It's easy to do; you just start the text with # signs. # This function allows you to ... # These variables define the connection state as the connection is # made. They're great. You should try them. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From boblatest at yahoo.com Tue Jan 8 05:42:39 2008 From: boblatest at yahoo.com (Robert Latest) Date: 8 Jan 2008 10:42:39 GMT Subject: (SOLVED) Re: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> <5ugulaF1hqn2cU1@mid.uni-berlin.de> <5ugv5dF1i0edtU1@mid.dfncis.de> <87fxx8mycm.fsf@mulj.homelinux.net> <5uh0gcF1hoialU2@mid.dfncis.de> Message-ID: <5uh2cvF1hpvl4U1@mid.dfncis.de> pexpect is the solution. Seems to wrap quite a bit of dirty pseudo-tty hacking. robert From aipa_6 at msn.com Mon Jan 28 21:06:03 2008 From: aipa_6 at msn.com (aida) Date: Mon, 28 Jan 2008 18:06:03 -0800 (PST) Subject: LEELO NO TE ARREPENTIRAS Message-ID: <9e7f5fc4-ebe7-4f8c-a192-82a460573680@l32g2000hse.googlegroups.com> L?elo, no te arrepentir?sPOR FAVOR ANTES DE ELIMINAR ESTE MENSAJE, LEAN PRIMEROY TOMEN LA DECISI?N DESPU?S.ESTO TE PUEDE AYUDAR A PAGAR TUS DEUDAS O TUS ESTUDIOSHola amigos:Esto es lo me pas? d?as atr?s, mientras navegaba por estas p?ginas de noticias, as? como usted lo est? haciendo ahora. Se me apareci? un art?culo similar a este que dec?a:"Usted puede recibir miles de d?lares en pocas semanas con una inversi?n de US $6.00 d?lares (seis d?lares)". Enseguida pens?: "?Oh no, otra estafa m?s?" Pero como la mayor?a de nosotros, la curiosidad pudo m?s y segu? leyendo; segu?a diciendo: " Usted enviar? US $1.00 (un d?lar) a cada uno de los 6 nombres y direcciones mencionados en este art?culo. Despu?s, anote usted su nombre y direcci?n al final de la lista reemplazando al numero #6, y env?e o ponga este art?culo en por lo menos 200 NEWSGROUPS (hay miles de estos en todo el mundo).Nota: Si te encuentras en otro pa?s, debes cambiar tu moneda nacional a d?lares, pues en todos los pa?ses cambian d?lares y es m?s f?cil para todos.No existe ning?n truco, la diferencia de este sistema y otros, es que usted tiene una lista de 6 en vez de 5, esto significa que el promedio de ayuda ser? aproximadamente ?????15 veces mayor!!!!! Despu?s de pensarlo una y otra vez y de consultarlo con unos amigos, decid? probarlo. Pens? que lo ?nico que podr?a perder eran 6 estampillas y US $6 d?lares y que me quedar?a la satisfacci?n de haber contribuido a ayudar a 6 personas en el mundo, que como yo se encuentran con serios problemas econ?micos.Como probablemente muchos de nosotros estaba un poco preocupado por la legalidad de todo esto. Entonces consulte al Servicio de Correos y me confirmaron que en realidad era legal!!!!!!!. Me qued? asombrado y de inmediato envi? mis US $6 d?lares... IMAG?NENSE QUE!!!!...Siete d?as despu?s, empec? a recibir DINERO por correo!!!!Estaba feliz, como ni?o con juguete nuevo, y muy sorprendido!!!! Y pensaba que esto se acabar?a en)unos pocos d?as m?s. Me trat? de olvidar del tema, en todo caso ya hab?a recibido una ayuda similar a la que hab?a dado... pero el dinero segu?a llegando. En mi primera semana recib? entre US $20 y US $30 d?lares. Para el final de la segunda semana hab?a recibido un total de US $1,000 (mil d?lares)!!!!!! No lo POD?A CREER!! En la tercera semana $10,000 (diez mil) y todav?a segu?a llegando m?s!!! En mi cuarta semana ten?a un total de $41,000 d?lares y a?n sigue llegando m?s ayuda (en mi casa se la pasan abriendo sobres y yo consiguiendo "NEWSGROUP" para continuar ayudando a m?s gente y retribuir la ayuda recibida hasta este momento. ESTO SE PUSO SERIO.Todo esto vali? la pena, la ayuda de US $6 d?lares que ofrec? las 6 estampillas dio sus frutos; y pensar que yo gastaba m?s de US $6 d?lares semanales en sorteos y loter?a tratando de obtener los recursos que necesitaba para salir de mis problemas econ?micos y no pasaba nada.AHORA PERM?TANME EXPLICARLES COMO FUNCIONA ESTOY LO MAS IMPORTANTE......... EL POR QU? FUNCIONA EXCELENTEMENTEUsted aseg?rese de imprimir este art?culo AHORA, para sacar toda la informaci?n a medida que la necesite. El proceso es muy f?cil y consiste en 3 (tres) sencillos pasos:PASO N?.1: Obtenga 6 hojas de papel y escriba en cada una de ellas: "FAVOR DE INCLUIRME EN SU LISTA DE CORRESPONDENCIA O E-MAIL".Ahora consiga 6 billetes de US $1 (un d?lar) e introduzca cada d?lar en un sobre, procurando envolverlo con la hoja de manera que el billete no se vea a trav?s del sobre!!Es mejor que el papel sea de color oscuro para prevenir los robos de correspondencia. En este momento usted deber?a tener 6 sobres sellados y en ellos un papel con la frase mencionada, su nombre y direcci?n, y un billete de US $1 (un dolar). Lo que usted est? haciendo con esto es crear un "servicio de ayuda" y esto hace que sea ABSOLUTAMENTE LEGAL!!!Env?e los 6 sobres a las siguientes direcciones: #1.- NAYVI DEL CARMEN LEAL FLORESCalle 47 #215 x 20 y 43 DiagonalFraccionamiento BrisasC.P. 97144 M?rida, Yucat?n, M?xico.# 2.- ERNESTO JAVIER ESTRELLA ALCOCERCalle 50 #117-A x 39 y 39CFracc. Francisco de MontejoC.P. 97203 M?rida, Yucat?n, M?xico. #3.- PATRICIA NAVARRO FUENTESTabunco # 1697.Villa la Providencia de Macul La FloridaSantiago, Chile#4.-ANDREA LEBLANC ORDENESNUEVA MATURANA #0495, VILLA ALEMANAQUINTA REGION, CHILE #5.- CATALINA INOSTROZA CATALANVOLCAN PARINACOTA #642, VILLA CORDILLERA TALAGANTE, CHILE #6.-AIDA PACHECO SAAVEDRA.Casilla 3612. Oficina Moneda. Santiago. Chile PASO N? 2: Ahora elimine el numero #1 de lista de arriba y mueva los otros nombres un numero para arriba ( el #6 se convierte en el #5, y el # 5 se convierte en el #4, etc...) y agregue su NOMBRE Y SU DIRECCI?N en el #6 de la lista.LES COMENTO QUE SON DIRECCIONES VERDADERAS Y CREO QUE NO CUALQUIER PERSONA PONE LA DIRECCI?N DE SU CASA O NEGOCIO S?LO PORQUE S?.PASO N? 3: Cambie todo lo que crea conveniente de este art?culo, pero trate de mantenerlo lo m?s cercano posible al original. Ahora ponga su art?culo en por lo menos 200 NEWSGROUP (existen m?s de 24,000,000 Newsgroups). S?lo necesita 200, pero en cuantos m?s ponga esta carta con sus datos, m?s dinero recibir? como ayuda.Aqu? van algunas indicaciones de c?mo introducirse a los Newsgroups:COMO MANEJAR LOS "NEWSGROUPS" (GRUPOS):N? 1.-Usted no necesita redactar toda esta carta para hacer la suya propia. Solamente ponga su cursor al comienzo de esta carta, haga "click" con el bot?n izquierdo del mouse y d?jelo presionado; b?jelo hasta el final de la carta y suelte el bot?n del mouse.Toda la carta deber? estar "sombreada". Entonces haga un "click" con el bot?n derecho del mouse en cualquier lugar de la parte sombreada y seleccione "COPY" o "COPIAR". Esto har? que toda la carta quede en la memoria temporal de su computadora.N? 2.- Abra un archivo nuevo "NOTEPAD" o "WORD". Haga un "clik" con el bot?n derecho del mouse y elija "PASTE" o "PEGAR". Grabe el)archivo con el nombre que desee y que le permita identificarlo en cualquier momento. Desde ese momento tendr? esta carta en su computadora y podr? agregar su nombre en el lugar #6 de la lista siguiendo las instrucciones que aparecen m?s arriba.N? 3.- Teniendo grabada esta carta en su computadora, cada vez que lo desee le podr? agregar o cambiar algo sin problemas.PARA LOS QUE USAN INTERNET EXPLORER.N? 4.- Vaya a Newsgroups y seleccione "post an article" o "escribir nuevo mensaje/discusi?n"N? 5.- Cargue el art?culo que guard? previamente.N? 6.- Seleccione el contenido completo del archivo que contiene la carta y copie usando el mismo procedimiento descrito anteriormente. Regrese a Newsgroups y elija "TO NEWS" o "NUEVA DISCUSI?N", de esta forma est? creando el espacio para poder "pegar" el contenido de la carta.N? 7.- Presione el bot?n "post" ("Enviar Mensaje")PARA LOS QUE MANEJAN NETSCAPE.N? 4. Dentro del programa Netscape, vaya a la ventana titulada "Window" y seleccione "NetscapeNews". Entonces elija del men? "Options", seleccione "Show all Newsgroups".En seguida aparecer? una lista de todos los newsgroups de su server , haga clic en cualquier nuewsgroup. De este newsgroup haga clic debajo de "TO NEWS", el cual deber?a estar arriba, en el extremo izquierdo de la pagina de newsgroup. Esto le llevara a la caja de mensajes.N? 5.-Llene este espacio. Este ser? el titulo que ver?n todos cuando recorran por la lista de un grupo en particular.N? 6.- Marque Seleccione el contenido completo del archivo que contiene la carta y copie usando el mismo procedimiento descrito anteriormente. Regrese a newsgroup "TO NEWS" y usted esta creando y empastando esta carta dentro de su programa o "posting".N? 7.- Presione "send", que est? en la parte superior izquierda y usted ha finalizado con su primer newsgroup.........FELICIDADES!!!!!!!!!!!!!!!!!!!!!!!!!!ESO ES TODO!!! Todo lo que tiene que hacer es meterse en diferentes Newsgroups (grupos) y empastarlos; cuando ya tenga pr?ctica, solo le tomar? unos 30 segundos yor cada newsgroupRECUERDE: MIENTRAS MAS NEWSGROUPS CONSIGA, MAS RESPUESTAS Y DINERO RECIBIR?!!!!, PERO DEBE DE ENTRAR EN PO[ LO MENOS... 200 NEWSGROUPS...Y YA ESTA!!!!!... Usted estar? recibiendo dinero de todo el mundo, de lugares que ni conoce y en unos pocos d?as!!!. Eventualmente querr? rentar un P.O. BOX. por la cantidad de sobres que ir? recibiendo!!!(((ASEGURESE DE QUE TODAS LAS DIRECCIONES EST?N CORRECTAS)))Ahora el POR QU? de todo esto:De 200 cartas que ya coloqu? en igual n?mero de Newsgroups (Grupos), digamos que recibiera s?lo 5 repuestas (baj?simo ejemplo). Entonces recib? $5 D?lares de ayuda From deets at nospam.web.de Sun Jan 27 09:15:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jan 2008 15:15:10 +0100 Subject: how to make format operator % work with unicode as expected In-Reply-To: References: Message-ID: <603hvkF1orqggU1@mid.uni-berlin.de> Peter Pei schrieb: > I am using things like "%-20s%-60s%-10s" in tkinter listbox to make it > look like a table, with mono sized font like lucie system. But this does > not work with data contains "Les mis?rables", because it is unicode, and > one byte is not neccessary one character. Now how can I resolve this issue? By learning that unicode is not UTF-8, instead of insulting others of being incompetent. Diezz From thelanguageofcities at gmail.com Sun Jan 27 20:28:10 2008 From: thelanguageofcities at gmail.com (Max) Date: Sun, 27 Jan 2008 17:28:10 -0800 (PST) Subject: Python Genetic Algorithm References: Message-ID: On Jan 27, 8:01 pm, "Terry Reedy" wrote: > "Max" wrote in message > > news:caf75b0d-7ed3-421a-93f8-6f7d90a98923 at p69g2000hsa.googlegroups.com... > | In GAs, you operate on a Population of solutions. Each Individual from > | the Population is a potential solution to the problem you're > | optimizing, and Individuals have what's called a chromosome - a > | specification of what it contains. For example, common chromosomes are > | bit strings, lists of ints/floats, permutations...etc. I'm stuck on > | how to implement the different chromosomes. I have a Population class, > | which is going to contain a list of Individuals. Each individual will > | be of a certain chromosome. I envision the chromosomes as subclasses > | of an abstract Individual class, perhaps all in the same module. I'm > | just having trouble envisioning how this would be coded at the > | population level. Presumably, when a population is created, a > | parameter to its __init__ would be the chromosome type, but I don't > | know how to take that in Python and use it to specify a certain class. > | > | I'm doing something similar with my crossover methods, by specifying > | them as functions in a module called Crossover, importing that, and > | defining > | > | crossover_function = getattr(Crossover, "%s_crossover" % xover) > | > | Where xover is a parameter defining the type of crossover to be used. > | I'm hoping there's some similar trick to accomplish what I want to do > | with chromosomes - or maybe I'm going about this completely the wrong > | way, trying to get Python to do something it's not made for. Any help/ > | feedback would be wonderful. > > 'Python genetic algorithm' returns 25000 hits with Google. > But here is what I would do without looking at them. > > Start with the Individual base class and common methods, some virtual (not > implemented). An example of a virtual method would be the > crossover(self,other) method, since its implementation depends on the > concrete chromosome implementation. Make subclasses with concrete > chromosome types (initialized in .__init__). For each, implement the > methods that depend on that type. In particular, the mutate(self, args) > and crossover(self,other, args) methods. > > For the Population class, give __init__ an 'individual' parameter and > store it as an attribute. If you want, check that it > 'issubclass(Individual)'. To add members to the population, call the > stored subclass. To operate on the population, write Population methods. > There should not depend on the particular chromosome implementations. To > operate on the members within the Population methods, call their Individual > methods. b = a.mutate(args); c = a.crossover(b, args). > > I see two ways to deal with scoring the fitness of individuals within a > Population instance. Once is to write a particular fitness function, pass > it to the Population init to save as an attribute, and then call as needed. > The other is to subclass an Individual subclass, give it that funtion > fitness method, and pass that subsubclass to Population. The difference is > between having Population methods calling self.fitness(some_member) versus > some_member.fitness(). > > I hope this is helpful for getting started. > > Terry Jan Reedy Yeah, I looked up some of those GAs, but talking with people about code helps me a lot more than looking at other code. I know it's strange for a programmer to prefer social interaction, but...just something about how I'm wired. This sounds a lot like what I was thinking of doing. In particular, I was planning on having the problem's program itself (which would create an instance of a GA to optimize something) specify the fitness function and pass it upwards to the population (or maybe to the GA, which contains a population). Thanks for the help. From jigisbert.etra-id at grupoetra.com Sun Jan 13 16:06:55 2008 From: jigisbert.etra-id at grupoetra.com (j igisbert.etra-id) Date: Sun, 13 Jan 2008 22:06:55 +0100 Subject: *SPAM*: 04.6/4.0 - Re: Manually installing PIL In-Reply-To: References: <001001c84dda$23d26760$2000a8c0@depid.local> Message-ID: My PDA runs with Windows Mobile 2003 SE.... could you or someone please explain me what to do? Thanks a lot for your effort. -----Original Message----- From: Fredrik Lundh To: python-list at python.org Date: Sun, 13 Jan 2008 21:18:37 +0100 Subject: *SPAM*: 04.6/4.0 - Re: Manually installing PIL j igisbert.etra-id wrote: > this. I have download Imaging-1.1.6 source code, and I found PIL folder, > but not binary file. If I download windows exe installer, it works > great, but I want to install manually for installing it on my PDA.... as the name implies, the source code distribution contains source code only. to turn that into a binary component, you need a working compiler for your target platform. what OS does your PDA run? -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet at rudnyi.ru Sat Jan 5 11:12:50 2008 From: usenet at rudnyi.ru (Evgenii Rudnyi) Date: Sat, 5 Jan 2008 08:12:50 -0800 (PST) Subject: Fortran to Python References: Message-ID: On Jan 4, 2:21?pm, Jeroen Ruigrok van der Werven wrote: > I got someone who asked me to make changes in an old Fortran program she is > using for some calculations. > The calculations are pretty standard aside from 2 calls to DLINCG (an IMSL > numerical_libraries function to calculate an inverse matrix). > > What I wonder about, does anybody have a Fortran to Python conversion page > somewhere to map some of the basic types to Python equivalents? > What kind of speed difference should I expect? When it comes to matrices the difference can be quite big. You can find the comparison of NumPy, Fortran 77, C, and C++ for matrix multiplication with and without optimized BLAS at http://matrixprogramming.com/MatrixMultiply/ NumPy interfaces optimized BLAS, and you can find a LAPACK interface in SciPy, so it is a good choice. Evgenii From Scott.Daniels at Acm.Org Thu Jan 10 20:33:33 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 10 Jan 2008 17:33:33 -0800 Subject: What is "lambda x=x : ... " ? In-Reply-To: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> Message-ID: <13odhiipb1ddi45@corp.supernews.com> zslevi at gmail.com wrote: > I'm reading this page: http://www.ps.uni-sb.de/~duchier/python/continuations.html > and I've found a strange usage of lambda: > > #################### > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ################### > > What does "y=y" and "c=c" mean in the lambda function? > I thought it bounds the outer variables, so I experimented a little > bit: > > ################# > x = 3 > y = lambda x=x : x+10 > > print y(2) > ################## > > It prints 12, so it doesn't bind the variable in the outer scope. Primary use: funcs = [lambda x=x: x+2 for x in range(10)] print funcs[3]() _or_ funcs = [] for x in range(10): funcs.append(lambda x=x: x+2) print funcs[3]() Try these w/o the default binding. --Scott David Daniels Scott.Daniels at Acm.Org From menkaur at gmail.com Sun Jan 20 05:17:03 2008 From: menkaur at gmail.com (menkaur at gmail.com) Date: Sun, 20 Jan 2008 02:17:03 -0800 (PST) Subject: Quixote cookies Message-ID: <0f43cf8f-0ce1-42ea-bd8e-4a5d7925c6dd@s12g2000prg.googlegroups.com> Hi, guys I'm trying to use cookies in Quixote. This is the code: env = copy(os.environ) req = HTTPRequest(sys.stdin, env) req.response.set_cookie("xxx","666") cc = req.get_cookie("xxx"); For some reason it cc is always None. What am I doing wrong? From arnodel at googlemail.com Tue Jan 29 08:26:25 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 29 Jan 2008 05:26:25 -0800 (PST) Subject: Executing other python code References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: On Jan 29, 12:18?am, Tim Rau wrote: > I'm working on a game, and I'd like players to be able to define thier > ships with scripts. Naturally, I don't want to give them the entire > program as thier romping ground. I would like to invoke a seperate > interpreter for these files, and give it a limited subset of the > functions in my game. What is the best way to achieve this effect? One simple solution would be to forbid import statements in the scripts, to import the scripts as modules and inject whatever functions you want them to be able to use in the module's namespace. So: ====== script.py ======= def play(): if enemy_is_near(): fire_gun() else: move_forward() ======================= ====== Game engine ==== scriptobjs = [enemy_is_near, fire_gun, move_forward, turn_left, turn_right] def getscript(scriptname): script = __import__(scriptname) for obj in scriptobjs: setattr(script, obj.__name__, obj) return script def playscript(script): script.play() ======================= Something like this. Obviously this is over simplified! -- Arnaud From king.a.joe at gmail.com Mon Jan 21 14:52:34 2008 From: king.a.joe at gmail.com (Joseph king) Date: Mon, 21 Jan 2008 14:52:34 -0500 Subject: question Message-ID: I just need to pass this through....... How does everyone feel about the fact that SUN bought mySQL for $1 billion. I don't find it possible that they would keep it a free product if they invested that much money on it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tiwarishravan at gmail.com Wed Jan 30 06:26:33 2008 From: tiwarishravan at gmail.com (tiwarishravan at gmail.com) Date: Wed, 30 Jan 2008 03:26:33 -0800 (PST) Subject: HI all Message-ID: <1b6a8d39-8077-4d4e-b05f-1e0037472ed8@d4g2000prg.googlegroups.com> I am shravan tiwari, i want to know that how i'll run any python file(*.py) on command prompt r python GUI. i tried this python test.py but i have got error, syntax error. so can i get the solution. From martin at v.loewis.de Sat Jan 5 12:12:48 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 05 Jan 2008 18:12:48 +0100 Subject: fastest method to choose a random element In-Reply-To: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> Message-ID: <477fba91$0$8348$9b622d9e@news.freenet.de> > Any other ideas? How about this: def random_pick(list, property): L = len(list) pos = start = random.randrange(L) while 1: x = list[pos] if property(x): return x pos = (pos + 1) % L if pos == start: raise ValueError, "no such item" Regards, Martin From bj_666 at gmx.net Sun Jan 27 04:39:21 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jan 2008 09:39:21 GMT Subject: how to make format operator % work with unicode as expected References: <13po55nc0q0s06@corp.supernews.com> Message-ID: <6031q9F1oh17aU1@mid.uni-berlin.de> On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: > You didn't understand my question, but thanks any way. > > Yes, it is true that %s already support unicode, and I did not contradict > that. But it counts the number of bytes instead of characters, and makes > things like %-20s out of alignment. If you don't understand my assertion, > please don't argue back and I am only interested in answers from those who > are qualified. I have the impression from your original post [?] because it is unicode, and one byte is not neccessary one character. that you confuse unicode and utf-8. Are you sure you are qualified to ask such a question in the first place!? :-? Ciao, Marc 'BlackJack' Rintsch From washakie at gmail.com Wed Jan 30 06:50:27 2008 From: washakie at gmail.com (washakie) Date: Wed, 30 Jan 2008 03:50:27 -0800 (PST) Subject: find nearest time in datetime list Message-ID: <15180398.post@talk.nabble.com> Hello, I have a list of datetime objects: DTlist, I have another single datetime object: dt, ... I need to find the nearest DTlist[i] to the dt .... is there a simple way to do this? There isn't necessarily an exact match... Thanks! .john -- View this message in context: http://www.nabble.com/find-nearest-time-in-datetime-list-tp15180398p15180398.html Sent from the Python - python-list mailing list archive at Nabble.com. From nagle at animats.com Tue Jan 15 01:53:36 2008 From: nagle at animats.com (John Nagle) Date: Mon, 14 Jan 2008 22:53:36 -0800 Subject: Is there some Python function that searches "sys.path" for a module? Message-ID: <478c5755$0$36354$742ec2ed@news.sonic.net> Python's own loader searches "sys.path" for module names, but is there some function that makes that search functionality accessible to Python programs? I need the absolute pathname of a module, with the search being done exactly the same way "import" does it. The loader for "egg" files has this functionality, but I'd like to find out if there's a standard way to do this before looking into that source code. Also, it seems that the environment variable "PYTHONPATH" applies to "import", but not to the starting module named on the Python command line. Is that correct? Thanks. John Nagle From fliot at kyriba.com Fri Jan 4 12:48:57 2008 From: fliot at kyriba.com (Francois Liot) Date: Fri, 4 Jan 2008 18:48:57 +0100 Subject: Simple calculation error Message-ID: <3CDC4613E97B134A9A7E61A5E43DCA55010FDE36@fr-mail1.fr.kyriba.com> Dear all, I observed a strange calculation answer, on both python 2.3.4 and 2.4.4 >>> print 753343.44 - 753361.89 -18.4500000001 >>> print ( (753361.89*100) - (753343.44*100) ) / 100 18.45 Can somebody help me to play correctly with decimal values? Thanks in advance, Francois Liot -------------- next part -------------- An HTML attachment was scrubbed... URL: From ndbecker2 at gmail.com Mon Jan 21 13:28:40 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 21 Jan 2008 13:28:40 -0500 Subject: index of min element of sequence Message-ID: What's a good/fast way to find the index of the minimum element of a sequence? (I'm fairly sure sorting the sequence is not the fastest approach) From over at thepond.com Fri Jan 25 20:10:26 2008 From: over at thepond.com (over at thepond.com) Date: Sat, 26 Jan 2008 01:10:26 GMT Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: On Thu, 24 Jan 2008 08:02:06 GMT, Tim Roberts wrote: >Bjoern Schliessmann wrote: > >>Grant Edwards wrote: >> >>> Trying to find assembly language stuff to look at is futile. >>> Python doesn't get compiled into assembly language. >> >>So, how do processors execute Python scripts? :) > >Is that a rhetorical question? Grant is quite correct; Python scripts (in >the canonical CPython) are NOT compiled into assembly language. Scripts >are compiled to an intermediate language. Processors execute Python >scripts when the interpreter, written in a high-level language and compiled >to assembly, interprets the intermediate language created by the Python >"compiler". Intel processors can only process machine language, which is essentially binary 1's and 0's. All a processor understands is voltages, either 0 Volts or 5 volts on older systems, or 3.3 volts and less on newer systems. Generally, a positive voltage is a logical 1 and 0 volts is a logical 0. There's no way for a processor to understand any higher level language, even assembler, since it is written with hexadecimal codes and basic instructions like MOV, JMP, etc. The assembler compiler can convert an assembler file to a binary executable, which the processor can understand. If you look at the Python interpreter, Python.exe, or Pythonw, the Windows interface, or the Python24.dll, the main library for python, you will see they are normal 32 bit PE files. That means they are stored on disk in codes of 1's and 0's, and decompile into assembler. You can't decompile them into Python directly, although I'm sure someone is trying. No compiled file can be decompiled into it's original format easily or automatically, although there are decompilers that will convert them to a reasonable assembler decompilation. If a Python script was understood directly by the processor, no interpreter would be necessary. Ask yourself what the interpreter is doing. It's taking the scripting language and converting to the language of the operating system. However, it's the processor that dictates how programs are written, not the OS. That's why a Linux OS will run on an Intel machine, as a Windows OS does. Both Linux and Windows compile down to binary files, which are essentially 1's and 0's arranged in codes that are meaningful to the processor. Once a python py file is compiled into a pyc file, I can disassemble it into assembler. Assembler is nothing but codes, which are combinations of 1's and 0's. You can't read a pyc file in a hex editor, but you can read it in a disassembler. It doesn't make a lot of sense to me right now, but if I was trying to trace through it with a debugger, the debugger would disassemble it into assembler, not python. From haag at lsu.edu.invalid Thu Jan 3 22:08:55 2008 From: haag at lsu.edu.invalid (Alaric) Date: Fri, 04 Jan 2008 03:08:55 GMT Subject: Information on PyGMT? Message-ID: Hello - I'm seeking info on the PyGMT python wrapper for the Generic Mapping Tools package. Unfortunately, the only site (forge.nesc.ac.uk) that seems to offer the code (written by Magnus Hagdorn) is not responding. I don't know if that's a temporary condition or if that site is out of commission. Google isn't revealing much recent discussion either.... which is sad, as I would imagine this to be a valuable tool! Can anyone shed any light?? Better yet, does anyone have the latest tarball, and an FTP site they can offer it on? :) Many thanks! Alaric From JO3chiang at gmail.com Fri Jan 4 01:11:04 2008 From: JO3chiang at gmail.com (jo3c) Date: Thu, 3 Jan 2008 22:11:04 -0800 (PST) Subject: linecache and glob References: <0e16ca26-9e34-4f97-83de-9ddc3693d085@i12g2000prf.googlegroups.com> <0a62d553-7fe9-41c0-84dc-a1f3749b46f8@e23g2000prf.googlegroups.com> Message-ID: <3682a1dd-a3a6-436f-87a0-37feaef65ccc@h11g2000prf.googlegroups.com> i have a 2000 files with header and data i need to get the date information from the header then insert it into my database i am doing it in batch so i use glob.glob('/mydata/*/*/*.txt') to get the date on line 4 in the txt file i use linecache.getline('/mydata/myfile.txt/, 4) but if i use linecache.getline('glob.glob('/mydata/*/*/*.txt', 4) won't work i am running out of ideas thanks in advance for any help jo3c From dfabrizio51 at gmail.com Thu Jan 31 21:34:13 2008 From: dfabrizio51 at gmail.com (chewie54) Date: Thu, 31 Jan 2008 18:34:13 -0800 (PST) Subject: Will Python on day replace MATLAB????????????????????????????????????????????????????? References: Message-ID: > 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 From q16941 at motorola.com Thu Jan 3 07:58:41 2008 From: q16941 at motorola.com (ashish) Date: Thu, 03 Jan 2008 18:28:41 +0530 Subject: Installing pcaplib Message-ID: <477CDC01.4050508@motorola.com> Hi All, I am trying to install "pylibpcap-0.6.1" but i am getting these errors . python ./setup.py install . . . . . constants.c:172: (near initialization for `pcapmodule_DLT[52]') pcap.c: In function `init_pcap': pcap.c:4246: structure has no member named `value' pcap.c:4260: warning: passing arg 3 of `PyModule_AddStringConstant' discards qualifiers from pointer target type error: command 'gcc' failed with exit status 1 Please tell me how to solve this problem.Do i have to install anything else before installing this library. Thanks in Advance Ashish From sjmachin at lexicon.net Mon Jan 21 15:06:19 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jan 2008 12:06:19 -0800 (PST) Subject: index of min element of sequence References: <7xfxwrt1dx.fsf@ruckus.brouhaha.com> Message-ID: <6243b2e3-e2eb-41fb-bb7c-88b40ffcef60@e25g2000prg.googlegroups.com> On Jan 22, 6:38 am, Paul Rubin wrote: > Neal Becker writes: > > What's a good/fast way to find the index of the minimum element of a > > sequence? (I'm fairly sure sorting the sequence is not the fastest > > approach) > > Python 2.5 (untested): > > from operator import itemgetter > minindex = min(enumerate(seq), key=itemgetter(1))[1] Bzzzt! >>> seq = [1000, 9, 8, 7, 2000, 3000] >>> from operator import itemgetter >>> minindex = min(enumerate(seq), key=itemgetter(1))[1] >>> minindex 7 >>> min(enumerate(seq), key=itemgetter(1)) (3, 7) s/[1]/[0]/ or more generally: minindex, minvalue = min(enumerate(seq), key=itemgetter(1)) From python at rcn.com Wed Jan 2 11:44:49 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 2 Jan 2008 08:44:49 -0800 (PST) Subject: Two candies References: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com> Message-ID: [bearophileH] > > 1) A fast and memory efficient way to create an array.array at a > certain size. > At the moment I can see some ways to do it: > > from array import array > from itertools import repeat > a = array("l", repeat(0, n)) #3 . . . > - #3 interacts badly with Psyco (Psyco doesn't digest itertools at > all), and it seems not memory efficient. #3 is a fine choice. It is memory efficient -- the repeat() itertool takes-up only a few bytes. It doesn't need psyco, you already have to fast C routines talking to each other without having to go through the interpreter loop. Raymond From odysseus1479-at at yahoo-dot.ca Mon Jan 14 03:38:51 2008 From: odysseus1479-at at yahoo-dot.ca (Odysseus) Date: Mon, 14 Jan 2008 08:38:51 GMT Subject: Elementary string-formatting References: <7d17fa05-67c5-4acb-91b6-c53fdf70ae27@q77g2000hsh.googlegroups.com> Message-ID: In article <7d17fa05-67c5-4acb-91b6-c53fdf70ae27 at q77g2000hsh.googlegroups.com>, John Machin wrote: > > div operator? The integer division operator is // Yes, sorry, that's what I meant. -- Odysseus From ptmcg at austin.rr.com Fri Jan 4 11:46:27 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 4 Jan 2008 08:46:27 -0800 (PST) Subject: how to use bool References: <477d08d1$0$510$bed64819@news.gradwell.net> Message-ID: On Jan 3, 10:09?am, tinn... at isbd.co.uk wrote: > > With my philosophical programming hat on the first thing I'd say (as a > fairly beginning python programmer) is "avoid multiple returns from a > function/method if at all possible". ?They breed all sorts of problems > and errors, in particular if there's any clearing up to do you have to > do it in lots of places (or you forget it in some places). > This conventional wisdom predates the introduction of constructs such as try-catch-finally. In fact, you are just lulling yourself into some false security if you think that that single return at the end of your method is the only exit point of your routine. Exceptions can (and will) happen just about anywhere. I know, you had your C hat on, but even C++'ers fall into this trap. I was on a project that cited explicit delete statements during code reviews as likely memory leaks in the face of exceptions, and each was to be replaced with auto-cleanup objects such as auto_ptr. The same was done for other resource alloc/release pairs, such as locks, database connections, cursors, etc. These were looooong-running server processes, and they ran for months with no memory growth at all. If I were to suggest a similar topic for Python code reviews, it would be to look at paired statements and to ensure that the cleanup/ recovery statement was wrapped in a finally block. There's more than just memory that needs bookkeeping, so garbage collection wont solve all these other resource management problems. -- Paul From khoard at gmail.com Wed Jan 30 17:47:36 2008 From: khoard at gmail.com (FireNWater) Date: Wed, 30 Jan 2008 14:47:36 -0800 (PST) Subject: Dictionary Keys question Message-ID: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> I'm curious why the different outputs of this code. If I make the dictionary with letters as the keys, they are not listed in the dictionary in alphabetical order, but if I use the integers then the keys are in numerical order. I know that the order of the keys is not important in a dictionary, but I was just curious about what causes the differences. Thanks!! list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] list2 = [1,2,3,4,5,6,7,8] Dictionary = dict(zip(list1, list2)) print Dictionary Dictionary1 = dict(zip(list2, list1)) print Dictionary1 From dstromberglists at gmail.com Mon Jan 21 18:13:35 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Mon, 21 Jan 2008 23:13:35 GMT Subject: bags? 2.5.x? References: <478bbae6$0$25383$9b4e6d93@newsspool4.arcor-online.net> <437501ef-1b38-4e47-9106-c846a456dd49@c23g2000hsa.googlegroups.com> Message-ID: On Thu, 17 Jan 2008 18:18:53 -0800, Raymond Hettinger wrote: >> >> I keep wanting something like them - especially bags with something >> >> akin to set union, intersection and difference. >> >> > How about this recepie >> > > >> The author of the bag class said that he was planning to submit bags >> for inclusion in 2.5 - is there a particular reason why they didn't go >> in? > > Three reasons: > > 1. b=collections.defaultdict(int) went a long way towards meeting the > need to for a fast counter. > > 2. It's still not clear what the best API would be. What should list(b) > return for b.dict = {'a':3, 'b':0, 'c':-3}? Perhaps, [('a', 3), ('b', > 0), ('c', -3)] or ['a', 'a', 'a'] > or ['a'] > or ['a', 'b', 'c'] > or raise an Error for the negative entry. I'd suggest that .keys() return the unique list, and that list() return the list of tuples. Then people can use list comprehensions or map() to get what they really need. It might not be a bad thing to have an optional parameter on __init__ that would allow the user to specify if they need negative counts or not; so far, I've not needed them though. > 3. I'm still working on it and am not done yet. > Decent reasons. :) Thanks! Here's a diff to bag.py that helped me. I'd like to think these meanings are common, but not necessarily! $ diff -b /tmp/bag.py.original /usr/local/lib/bag.py 18a19,58 > def _difference(lst): > left = lst[0] > right = lst[1] > return max(left - right, 0) > _difference = staticmethod(_difference) > > def _relationship(self, other, operator): > if isinstance(other, bag): > self_keys = set(self._data.keys()) > other_keys = set(other._data.keys()) > union_keys = self_keys | other_keys > #print 'union_keys is',union_keys > result = bag() > for element in list(union_keys): > temp = operator([ self[element], other [element] ]) > #print 'operator is', operator > #print 'temp is', temp > result[element] += temp > return result > else: > raise NotImplemented > > def union(self, other): > return self._relationship(other, sum) > > __or__ = union > > def intersection(self, other): > return self._relationship(other, min) > > __and__ = intersection > > def maxunion(self, other): > return self._relationship(other, max) > > def difference(self, other): > return self._relationship(other, self._difference) > > __sub__ = difference > From levilista at gmail.com Fri Jan 11 04:38:05 2008 From: levilista at gmail.com (zslevi@gmail.com) Date: Fri, 11 Jan 2008 01:38:05 -0800 (PST) Subject: what does **kw mean? Message-ID: <99cc3280-bffd-4004-a3ae-a06244a82759@e6g2000prf.googlegroups.com> I've been reading the following example, and couldn't figure out, what **kw mean. (It's an empty dictionary, but what's the semantics): def wrap(method): def wrapped(self, *args, **kw): print "begin" method(self, *args, **kw) print "end" return wrapped class Test(object): def method(self, name): print "method(%r)" % name t = Test() t.method("pure") Test.method = wrap(Test.method) t.method("wrapped") From montyphyton at gmail.com Thu Jan 3 16:46:47 2008 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: Thu, 3 Jan 2008 13:46:47 -0800 (PST) Subject: How is AI implemented References: Message-ID: On Jan 3, 6:49 pm, "Martin Marcher" wrote: > Hi, > > I know it's not a trivial field but I had some readings about > artificial intelligence lately and my personal conclusion is that it's > mostly just statistics. > > Naively explained: > > continiously gather and store information and apply a default rating > > 1) answer "questions" with gathered information according to rating > 2) store/calculate rating based upon input (be it an interface or user input) > 3) goto 1 (sorry for the goto) really naively :) > > So I think that in general there hasn't yet been any artificial > intelligence programmed (Note: I believe I'm aware of the difference > between artificial intelligence and artificial conscusiness where the > second would be able to answer things like: "How are you today" and > the first can answer factual knowledge) > What you want to do is look up the difference between weak AI and strong AI. Everything we have to this day is weak AI, and there is still a debate between various scientists as to whether strong AI is even possible. Be sure to look at Chinese room argument to see if strong AI is really what you need. (http://en.wikipedia.org/wiki/Chinese_room) > Am I thinking right here or is there some (preferrably) web reading > available on that or in depth links about the topic? > > thanks and sorry for OT posting > martin > > --http://noneisyours.marcher.namehttp://feeds.feedburner.com/NoneIsYours From lefevrol at yahoo.com Thu Jan 24 18:04:50 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Fri, 25 Jan 2008 00:04:50 +0100 Subject: read and readline hanging Message-ID: I am calling subprocess.Popen with p = Popen(args, bufsize=-1, stdin=PIPE, stdout=PIPE, stderr=PIPE) and after sending come command to the process, I try to read from p.stdout but after a few calls I hang. What is the correct way to do this, i.e., to read everything w/o getting stuck? I am not familiar with all these low-level functions and their annoying blocking behaviour. Note that I don't want to close the process because I want to send more commands to it after that, read the results, and so on and on. Thanks, -- O.L. From aspineux at gmail.com Tue Jan 15 09:02:48 2008 From: aspineux at gmail.com (aspineux) Date: Tue, 15 Jan 2008 06:02:48 -0800 (PST) Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> <7xsl105fvv.fsf@ruckus.brouhaha.com> <13onli9dk7mu926@corp.supernews.com> <7xhchgatin.fsf@ruckus.brouhaha.com> Message-ID: <4dc54032-e139-49d6-9270-793915ec3612@i29g2000prf.googlegroups.com> On Jan 15, 12:15 am, Paul Rubin wrote: > Steven D'Aprano writes: > > map = {'a': Aclass, 'b': Bclass, 'c': Cclass} > > class_ = map.get(astring, default=Zclass) > > > The result I want is the class, not the result of calling the class > > (which would be an instance). If I wanted the other semantics, I'd be > > using defaultdict instead. > > I used default as a keyward arg name indicating the presence of > a callable. I probably should have called it defaultfunc or something. > > x = d.get('a', f) # --> default value is f > x = d.get('a', defaultfunc=f) # --> default value is result of f() . Nice idea, but if I want args I need to write it like that: x=d.get('a', defaultfunc=f, funcargs=(1,2,3)) instead of d['a', f(1,2,3)] From dzizes451 at gmail.com Thu Jan 31 13:41:38 2008 From: dzizes451 at gmail.com (dzizes) Date: Thu, 31 Jan 2008 10:41:38 -0800 (PST) Subject: PIL linux err Message-ID: <15211773.post@talk.nabble.com> Hi, I'm trying to run simple .py on linux, which is using PIL. Below error message which I receive: File "/usr/lib/python2.4/site-packages/PIL/Image.py", line 960, in histogram self.load() File "/usr/lib/python2.4/site-packages/PIL/ImageFile.py", line 180, in load d = Image._getdecoder(self.mode, d, a, self.decoderconfig) File "/usr/lib/python2.4/site-packages/PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available Do you know what might be the problem? michal -- View this message in context: http://www.nabble.com/PIL-linux-err-tp15211773p15211773.html Sent from the Python - python-list mailing list archive at Nabble.com. From ejensen at visi.com Wed Jan 9 20:41:10 2008 From: ejensen at visi.com (Ed Jensen) Date: Thu, 10 Jan 2008 01:41:10 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: <13oattm5ijqvf58@corp.supernews.com> Bruno Desthuilliers wrote: > And the reference implementation of Python (CPython) is not > interpreted, it's compiled to byte-code, which is then executed by a VM > (just like Java). Wow, this is pretty misleading. Java is, indeed, compiled to bytecode; however, modern JVMs typically compile the bytecode to native code and then execute the native code. CPython strictly interprets bytecode; it does not compile the bytecode to native code. From Russ.Paielli at gmail.com Sun Jan 27 18:13:54 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 15:13:54 -0800 (PST) Subject: optional static typing for Python References: Message-ID: <23f7c55a-949f-41a4-b558-81861ede258f@f10g2000hsf.googlegroups.com> On Jan 27, 3:08 pm, Jarek Zgoda wrote: > Russ P. pisze: > > >>> I noticed that Guido has expressed further interest in static typing > >>> three or four years ago on his blog. Does anyone know the current > >>> status of this project? Thanks. > >> I thought it was april fools joke? > > > On January 21, 2000? Which calendar do you use? > > Static typing in Python is usual theme of april fools jokes. I hope Guido doesn't find out about that! From aaron.watters at gmail.com Wed Jan 2 10:33:22 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Wed, 2 Jan 2008 07:33:22 -0800 (PST) Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <13nn9k48n7ohr95@corp.supernews.com> Message-ID: <69337707-ff18-4b39-af0a-78cf0a14b667@1g2000hsl.googlegroups.com> > I must admit I feel a hint of amusement though at your comment above, when > it's sent from precisely the sort of setup you appear bemused by - since > you appear to have already bought into it without realising ! :-D Ok, so if we include yahoo mail and gmail in "cloud computing" then I guess usenet is also cloud computing. How about ftp? ssh? nfs? Oh I get it. It's another meaningless marketing buzz phrase. I mean, really, I've been using web-mail and various varieties of remote storage for over a decade. What is *new* about the concept? (I see some hints above, but it's mixed in with a lot of other stuff...) -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=fud From bkasterm at gmail.com Fri Jan 25 09:03:24 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Fri, 25 Jan 2008 06:03:24 -0800 (PST) Subject: Convert list to file object without creating an actual file. References: <32ae7d79-248a-4ac3-b51c-756699f11837@t1g2000pra.googlegroups.com> <13piogo8c3edd02@corp.supernews.com> Message-ID: <88916c48-11ed-4e18-b164-c1fd30023ff8@c4g2000hsg.googlegroups.com> The suggestion to use StringIO to make a string have the same interface as a file works perfect in my situation. Here is now the working result (just in case it is useful to anyone) part of this is still a definite hack and suggestions for improvement are certainly appreciated. Want: have an easily maintainable file containing homework assignments, but have it nicely formatted on my webpage. Solution: have a file with due dates and assignments as follows: Mon Jan 28 1.1: 1,2,3 (at this point only the indentation is taken into account). Then use the following script (setting some variables and server, login, and passwd for the ftp connection): #!/usr/bin/env python homeworktxt = "homework.txt" homeworkhtml = [] import sys import ftplib import StringIO Indent = ' ' StartTable = '
\n' EndTable = '
DueAssignment
' StartTitle = Indent + '\n' + Indent + Indent +'' EndTitle = Indent + Indent + '\n' + Indent + Indent + '' BeforeItems = Indent + Indent + Indent + '' AfterItems = Indent + Indent + Indent + '
\n' + Indent + Indent + '\n' + Indent + '' StartItem = Indent + Indent + Indent + Indent + '' EndItem = Indent + Indent + Indent + Indent + '' #if 1 >=len (sys.argv): # print "Need an filename as an argument" # print sys.argv[0] + " " #else: hw = open (homeworktxt).readlines() Last = 0 # 0: at the start, 1: just printed an item, 2: just printed a title #print StartTable homeworkhtml.append(StartTable) for x in hw: if ' ' == x[0]: if 2 == Last: homeworkhtml.append(BeforeItems) homeworkhtml.append(StartItem) homeworkhtml.append(Indent + Indent + Indent + Indent + Indent + x.strip()) homeworkhtml.append(EndItem) Last = 1 elif '#' != x[0]: if 1 == Last: homeworkhtml.append(AfterItems) homeworkhtml.append(StartTitle) homeworkhtml.append(Indent + Indent + Indent + x.strip()) homeworkhtml.append(EndTitle) Last = 2 # else : # homeworkhtml.append('COMMENT') # homeworkhtm if 1 == Last: homeworkhtml.append(AfterItems) homeworkhtml.append(EndTable) for i in range(0,len(homeworkhtml)): homeworkhtml[i] = homeworkhtml[i] + '\n' homeworkhtmlfile = StringIO.StringIO() homeworkhtmlfile.writelines(homeworkhtml) homeworkhtmlfile.seek(0) # open connection to the server ftp = ftplib.FTP('server', 'login', 'password' ) # go to location of root of website on server ftp.cwd('httpdocs') # put the contends of a file filename = "test.html" ftp.storlines("STOR " + filename, homeworkhtmlfile) # quite the connection ftp.quit() This will result in an html file that you can include (say with php include) into a webpage displaying a table. Examples of the result are currently on my webpage (www.bartk.nl/teach.php ) (if you read this much later look on the waybackmachine). Again, thanks for the suggestions, Best, Bart PS: apologies for the mixing of spaces and tabs. I had a computer crash and have not yet corrected the settings. So this is a combination of default behavior and my preferred settings. From ian at neustyle.com Sun Jan 6 05:13:40 2008 From: ian at neustyle.com (Soviut) Date: Sun, 6 Jan 2008 02:13:40 -0800 (PST) Subject: Point Object References: <4673edc3-b76c-4c6e-98f0-4f2becee930e@j20g2000hsi.googlegroups.com> Message-ID: On Jan 5, 6:37 am, "pjmu... at googlemail.com" wrote: > I am nes to python and need some help. Can anyone lead me in the > right direction to create and print a Point object, and then use id to > print the object's unique identifier. Translate the hexadecimal form > into decimal and confirm that they match. > > Any help woul be much appreciated. > > Pete You shouldn't have to compare the hex IDs. Just a simple comparison operator will work: firstPoint = Point() secondPoint = Point() print(firstPoint == secondPoint) result: True From hacker.stevenson at gmail.com Wed Jan 16 14:15:16 2008 From: hacker.stevenson at gmail.com (breal) Date: Wed, 16 Jan 2008 11:15:16 -0800 (PST) Subject: Creating unique combinations from lists Message-ID: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> I have three lists... for instance a = ['big', 'small', 'medium']; b = ['old', 'new']; c = ['blue', 'green']; I want to take those and end up with all of the combinations they create like the following lists ['big', 'old', 'blue'] ['small', 'old', 'blue'] ['medium', 'old', 'blue'] ['big', 'old', 'green'] ['small', 'old', 'green'] ['medium', 'small', 'green'] ['big', 'new', 'blue'] ['small', 'new', 'blue'] ['medium', 'new', 'blue'] ['big', 'new', 'green'] ['small', 'new', 'green'] ['medium', 'new', 'green' ] I could do nested for ... in loops, but was looking for a Pythonic way to do this. Ideas? From deets at nospam.web.de Wed Jan 23 09:12:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 Jan 2008 15:12:29 +0100 Subject: How avoid both a newline and a space between 2 print commands? References: Message-ID: <5vp0adF1n7mjfU1@mid.uni-berlin.de> seberino at spawar.navy.mil wrote: > print "foo" > print "bar" > > has a newline in between "foo" and "bar" > > print "foo", > print "bar" > > has a space in between "foo" and "bar" > > How prevent ANYTHING from going in between "foo" and "bar" ?? > > (Without defining a string variable.) sys.stdout.write("foo") sys.stdout.write("bar") Diez From peterdonis at alum.mit.edu Thu Jan 10 19:54:30 2008 From: peterdonis at alum.mit.edu (Peter Donis) Date: Thu, 10 Jan 2008 19:54:30 -0500 Subject: doctest.testfile universal newline -- only when module_relative=True? Message-ID: <200801101954.31330.peterdonis@alum.mit.edu> When running a doctest text file with doctest.testfile, I noticed that universal newline support did not appear to work when module_relative is False. My text file was saved on a Windows machine but I was testing it on a Linux machine, hence the newline mismatch (doctest would throw a SyntaxError for every incorrect newline). I looked at the svn trunk history for doctest.py and found the following patch: http://svn.python.org/view?rev=59082&view=rev This patch corrected for the lack of universal newline support in package.__loader__ .get_data(), but that only applies when module_relative is True. If it is False, the _load_testfile function just calls open(filename) with the default mode of 'r'. It seems to me that, for consistent behavior when module_relative is False, the mode should be 'rU'. Here's a diff against the current svn trunk that corrects this' I've tested it on my machine and it runs correctly: --- doctest_trunk.py 2008-01-10 18:59:15.000000000 -0500 +++ doctest_modified.py 2008-01-10 18:59:15.000000000 -0500 @@ -213,7 +213,8 @@ # get_data() opens files as 'rb', so one must do the equivalent # conversion as universal newlines would do. return file_contents.replace(os.linesep, '\n'), filename - return open(filename).read(), filename + # Here we just need to ensure universal newline mode when opening + return open(filename, 'rU').read(), filename def _indent(s, indent=4): """ Has anyone else noticed this behavior? If it seems worthwhile, I can submit this to the patch tracker. (It would also seem that there should be a corresponding patch to test_doctest to include this case--that should be easy enough for me to generate from what I have already.) Peter Donis From jazle at localhost.com Fri Jan 11 00:56:31 2008 From: jazle at localhost.com (Jaimy Azle) Date: Fri, 11 Jan 2008 12:56:31 +0700 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> Message-ID: "Ed Jensen" wrote: > > Wow, this is pretty misleading. > > Java is, indeed, compiled to bytecode; however, modern JVMs typically > compile the bytecode to native code and then execute the native code. > > CPython strictly interprets bytecode; it does not compile the > bytecode to native code. By the existence of psyco which has equal functionality, i think he is right in term of terminology. Salam, -Jaimy. From alnilam at gmail.com Tue Jan 22 11:07:52 2008 From: alnilam at gmail.com (Alnilam) Date: Tue, 22 Jan 2008 08:07:52 -0800 (PST) Subject: Problem with processing XML References: <13pbudgks88rcf3@corp.supernews.com> Message-ID: <0bca5d25-ec4a-49d9-8264-0446697d4bbb@h11g2000prf.googlegroups.com> On Jan 22, 9:11?am, John Carlyle-Clarke wrote: > By the way, is pyxml a live project or not? ?Should it still be used? > It's odd that if you go tohttp://www.python.org/and click the link > "Using python for..." XML, it leads you tohttp://pyxml.sourceforge.net/topics/ > > If you then follow the download links tohttp://sourceforge.net/project/showfiles.php?group_id=6473you see that > the latest file is 2004, and there are no versions for newer pythons. > It also says "PyXML is no longer maintained". ?Shouldn't the link be > removed from python.org? I was wondering that myself. Any answer yet? From rridge at caffeine.csclub.uwaterloo.ca Wed Jan 23 10:56:58 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 23 Jan 2008 10:56:58 -0500 Subject: subprocess and & (ampersand) References: Message-ID: Tim Golden wrote: > but this doesn't: > > > "c:\Program Files\Mozilla Firefox\firefox.exe" "%*" > > > > import subprocess > > cmd = [ > r"c:\temp\firefox.bat", > "http://local.goodtoread.org/search?word=tim&cached=0" > ] > subprocess.Popen (cmd) > > Ross Ridge wrote: > You need to use double quotes both in the .BAT file and in the string > you pass to subprocess.Popen(). Tim Golden wrote: >... If you simply requote the second element in the cmd list >('"http:/....."') then the internal quotes are escaped by some part of >the mechanism and it still doesn't work. Hmm... I guess things are much more messy than that. CMD doesn't do standard quote processing of it's arguments or .BAT file arguments, and so is incompatible with how subprocess quotes args lists. It looks like you need use a string instead of list with subprocess.Popen and not use quotes in the batch file. So something like: firefox.bat: "c:\Program Files\Mozilla Firefox\firefox.exe" %1 code: subprocess.Popen(r'c:\temp\firefox.bat "http://local.goodtoread.org/search?word=tim&cached=0"') Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From rocco.rossi at gmail.com Mon Jan 7 04:01:28 2008 From: rocco.rossi at gmail.com (rocco.rossi at gmail.com) Date: Mon, 7 Jan 2008 01:01:28 -0800 (PST) Subject: Noob question References: <17e045f1-7891-4afc-a98b-42dffdc45dd4@41g2000hsy.googlegroups.com> Message-ID: <37473f96-8a12-4667-94b3-c264618d6bf2@u10g2000prn.googlegroups.com> On Jan 7, 12:09 am, GHZ wrote: > Had the same issue. What you want is: reload() Thanks :) From rw at smsnet.pl Mon Jan 28 08:36:29 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Mon, 28 Jan 2008 05:36:29 -0800 (PST) Subject: Set ulimit when using subprocess.Popen? References: Message-ID: Jarek Zgoda napisa?(a): > Hi, all, > > anybody has an idea on how to set ulimit (-v in my case, linux) for > process started using subprocess.Popen? What about: from subprocess import call call('ulimit -v 1000 && ulimit -v && ls', shell=True) HTH, Rob From jhouzard at gmail.com Tue Jan 29 11:42:55 2008 From: jhouzard at gmail.com (=?ISO-8859-1?Q?Jean-Fran=E7ois_Houzard?=) Date: Tue, 29 Jan 2008 17:42:55 +0100 Subject: Reflection and aspect programming in Python Message-ID: <5bf046ee0801290842i58a82fa1xac8f8d3a7ef2598d@mail.gmail.com> Hello, I'm a student at UCL Belgium and I have to write a paper about reflection and introspection in Python. It is somewhat difficult to find advanced information about reflection in Python, not only introspection but also the other sides of reflection. I'm using the book: "Programming Python, Thrid Edition" but the chapter only describes briefly some useful functions. The IBM site talks somewhat about the concept of "metaclass" but is there more about reflection than only metaclass programming? I'm also looking for a class diagram of the hierachy of the python classes "metaclass", "class", "object" but didn't find it nor did I find lots of information about that subject. I looked around on the site www.python.org and some others about what could be a killer application using reflection in Python an maybe more information about it. Like how does it use reflection to do the trick. Is there an advanced and completed Aspect Python plugin or are they all experimental? Are there some papers about that part of reflection or more detailed sites that talks about it. It's a wide subject with open questions. I lack a lot of information about it and finding advanced topics on the subject isn't that easy. That's why I ask those questions here, to have some enlightments and maybe some leads to explore. Thanks a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Jan 22 08:20:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 14:20:35 +0100 Subject: isgenerator(...) - anywhere to be found? Message-ID: <5vm8t3F1m1797U1@mid.uni-berlin.de> For a simple greenlet/tasklet/microthreading experiment I found myself in the need to ask the question isgenerator(v) but didn't find any implementation in the usual suspects - builtins or inspect. I was able to help myself out with a simple (out of my head, hope its def isgenerator(v): def _g(): yield return type(v) == type(_g()) But I wonder why there is no such method already available? Diez From MartinRinehart at gmail.com Tue Jan 8 11:45:23 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Tue, 8 Jan 2008 08:45:23 -0800 (PST) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> <1d895d6d-a649-439e-8223-0ae7d3a4eb40@l6g2000prm.googlegroups.com> Message-ID: <4fb7129f-3887-4e3b-a827-3255344047f3@c23g2000hsa.googlegroups.com> That's a great list, grflanagan! Thanks. I looked at each and copied to my disk either as a .txt (cut/paste from the browser) for a page or less or as .html (view source, chop off head and non-guideline stuff, save). This is the list plus PEP 8 minus the software. (No disrespect for the software, just sticking to written standards.) Zope may be a substantial guideline, but it linked to a page of Zope links, all of which were broken. This CSV file is sorted by filesize on my disk. One presumes that a relationship exists between size and extent of coverage. (Warning: Wiki text could be as much as twice the size of non-wiki for the same content.) The third column is empty (spacer between size and URL). A quick look (thorough analysis still required) shows that OLPC and PyPy are, indeed, extensive standards. one-laptop-per-child.html (olpc),74.3,,http://wiki.laptop.org/go/ Python_Style_Guide pypy.html,64.2,,http://codespeak.net/pypy/dist/pypy/doc/coding- guide.html pep-008.html,35.6,,http://www.python.org/dev/peps/pep-0008/ knight.html,33.7,,http://jaynes.colorado.edu/PythonGuidelines.html pep-257.html,23.8,,http://www.python.org/dev/peps/pep-0257/ webware.html,23.4,,http://www.webwareforpython.org/Docs/ StyleGuidelines.html twisted.html,23.3,,http://twistedmatrix.com/trac/browser/trunk/doc/ development/policy/co... voice-code.html,17.9,,http://voicecode.iit.nrc.ca/VoiceCode/uploads/ codingGuidelines.html fsl.html,15.0,,http://www-md.fsl.noaa.gov/eft/developer/ PythonCodingStandards.html wx.html,14.6,,http://www.wxpython.org/codeguidelines.php mnet.html,14.5,,http://mnet.sourceforge.net/coding_standards.html michael-foord.html,14.2,,http://www.voidspace.org.uk/python/weblog/ arch_d7_2006_04_01.shtml#e296 bazaar.html,10.4,,http://doc.bazaar-vcs.org/bzr.dev/en/developer-guide/ HACKING.html#cod... ipython.html,10.2,,http://ipython.scipy.org/moin/Developer_Zone/ Developer_Guidelines barry-warsaw.html,6.2,,http://barry.warsaw.us/software/STYLEGUIDE.txt django.html,5.6,,http://www.djangoproject.com/documentation/ contributing/#coding-style chandler.txt,4.0,,http://chandlerproject.org/Projects/ ChandlerCodingStyleGuidelines pyblosxom.txt,3.8,,http://pyblosxom.sourceforge.net/blog/static/ development#coding freevo.txt,3.4,,http://jaynes.colorado.edu/PythonGuidelines.html sql-object.txt,2.7,,http://www.sqlobject.org/DeveloperGuide.html#style- guide biopython.txt,2.5,,http://biopython.org/wiki/ Contributing#Coding_conventions tracdev.txt,1.8,,http://trac.edgewall.org/wiki/TracDev/CodingStyle docutils,1.8,,http://docutils.sourceforge.net/docs/dev/ policies.html#python-coding-... moinmoin.txt,1.8,,http://moinmoin.wikiwikiweb.de/CodingStyle cherrypy.txt,1.5,,http://www.cherrypy.org/wiki/CodeConventions skeletonz-naming.txt,1.4,,http://orangoo.com/skeletonz/Developer_guide/ Naming_convention/ mercurial.txt,0.9,,http://www.selenic.com/mercurial/wiki/index.cgi/ Basic_Coding_Style skeletonz-coding.txt,0.6,,http://orangoo.com/skeletonz/Developer_guide/ Coding_convention/ software-carpentry.txt,0.1,,http://www.swc.scipy.org/lec/style.html zope.txt,0.0,,http://wiki.zope.org/zope3/CodingStyle From nicola.musatti at gmail.com Fri Jan 4 09:39:22 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Fri, 4 Jan 2008 06:39:22 -0800 (PST) Subject: Who's to blame? References: <92dfc2fc-0677-43c0-b34f-4f240fa40205@e4g2000hsg.googlegroups.com> <255d32d0-43f5-4d34-a074-b87082dc6043@e23g2000prf.googlegroups.com> <2b076973-b132-4666-a163-b80bcbeaedfb@s8g2000prg.googlegroups.com> <8749bb13-4f31-4cfc-8878-cc19bd417275@f10g2000hsf.googlegroups.com> Message-ID: <2f03c850-14fc-40c3-a95b-5711e254f4e1@h11g2000prf.googlegroups.com> On Jan 4, 3:12 pm, kyoso... at gmail.com wrote: [...] > I have sub-classed wx.Dialog to do my own custom modal dialogs as > well. You can use sizers and put whatever widgets you want onto it > that way. Just make sure that when you create the Yes/No buttons, you > give them the wx.ID_YES or wx.ID_NO ids, rather than -1 or wx.ID_ANY. > > yesBtn = wx.Button(parent, wx.ID_YES, 'Yes') > noBtn = wx.Button(parent, wx.ID_NO, 'No') As far as I understand this should be taken care of by the XRC/ wxStdDialogButtonSizer combination. Anyway, I solved my problem by binding the following event handler to both buttons: def OnButton(self, event): if self.IsModal(): self.EndModal(event.GetId()) By the way, my assumption above appears to be supported by the fact that a call to ShowModal() on my dialog does return wx.ID_YES when I press the Yes button. I'm still a bit puzzled, but right now I can't afford to let it bother me too much. Thanks for your help! Cheers, Nicola From peng.kyo at gmail.com Fri Jan 18 00:55:17 2008 From: peng.kyo at gmail.com (J. Peng) Date: Fri, 18 Jan 2008 13:55:17 +0800 Subject: too long float Message-ID: <18c1e5f20801172155k32d2297fn669114a1ce220ed8@mail.gmail.com> hello, why this happened on my python? >>> a=3.9 >>> a 3.8999999999999999 I wanted 3.9 but got 3.89................ How to avoid it? thanks. this is my python version: >>> sys.version '2.3.4 (#1, Feb 6 2006, 10:38:46) \n[GCC 3.4.5 20051201 (Red Hat 3.4.5-2)]' From HerbAsher at googlemail.com Thu Jan 17 04:09:33 2008 From: HerbAsher at googlemail.com (HerbAsher at googlemail.com) Date: Thu, 17 Jan 2008 01:09:33 -0800 (PST) Subject: Some Berkeley DB questions (being maintained? queries?) Message-ID: <0ba30836-8e2d-4061-94ea-ccddb24bc290@s19g2000prg.googlegroups.com> Hi! I have some questions. I'm evaluating berkeley db as a embeddable storage engine for a project I'm working on. My questions: 1. Now that Berkeley DB is part of Oracle, is it still being maintained? Is it free? 2. Are there good python libraries for bdb available, that are being maintained? 3. Is it possible to query a berkeley db database? Just simple queries like: find me all items where key "name" = "John" 4. What are good, stable alternatives? thanks, herb From fetchinson at googlemail.com Sat Jan 12 19:56:09 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 12 Jan 2008 16:56:09 -0800 Subject: __init__ explanation please In-Reply-To: <47895d25$0$30708$4c368faf@roadrunner.com> References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: > I'm new to Python, and OOP. I've read most of Mark Lutz's book and more > online and can write simple modules, but I still don't get when __init__ > needs to be used as opposed to creating a class instance by assignment. For > some strange reason the literature seems to take this for granted. I'd > appreciate any pointers or links that can help clarify this. I'm not sure if I understand your question correctly but maybe this will help: If you want code to be run upon creating an instance of your class you would use __init__. Most common examples include setting attributes on the instance and doing some checks, e.g. class Person: def __init__( self, first, last ): if len( first ) > 50 or len( last ) > 50: raise Exception( 'The names are too long.' ) self.first = first self.last = last And you would use your class like so, p1 = Person( 'John', 'Smith' ) p2 = Person( "Some long fake name that you don't really want to except, I don't know if it's really longer than 50 but let's assume it is", "Smith" ) # This last one would raise an exception so you know that something is not okay HTH, Daniel From tjreedy at udel.edu Wed Jan 9 22:41:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 Jan 2008 22:41:55 -0500 Subject: ISO books of official Python docs References: Message-ID: "Doug Morse" wrote in message news:slrnfoae1t.c2f.morse at ikrg.com... | Hi Fredrik, | | I'm terribly confused. You want me to apologize for recommending that someone | buy your books? To apologize for noting that they are a quality reference | sources for Python? As a past and future technical writer, I can understand Fredrik's reaction. Your recommendation seemed somewhat lukewarm to me ("So, while not exactly what you asked for, the ORA books might be a viable alternative if what you want isn't available" ) and looking back at the original, I do not see 'quality' anywhere. If someone thinks of the docs as low quality, as some do, then labelling others' work as a reproduction would imply the same of the reproduction. There is a HUGH difference between a 'reproduction' and an intended-to-be more literate and readable writing that covers the same material. (I have not seen Fredrik's book, so I cannot comment on how well he succeeded.) Terry Jan Reedy | On Wed, 09 Jan 2008 21:59:34 +0100, Fredrik Lundh | wrote: | > Doug Morse wrote: | > | > > Several of the O'Reilly & Assoc. books -- such as Python in a Nutshell, The | > > Python Standard Library, etc -- are in large part reproductions of the | > > official docs and references. | > | > if you're using "reproduction" to mean "copy", I think you owe both me | > and Alex a big apology. From robert.kern at gmail.com Sat Jan 12 21:11:29 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 12 Jan 2008 20:11:29 -0600 Subject: Is unicode.lower() locale-independent? In-Reply-To: <47894E09.6030104@v.loewis.de> References: <47894E09.6030104@v.loewis.de> Message-ID: Martin v. L?wis wrote: >> Even if towlower() gets used? I've found an explicit statement that the >> conversion it does can be locale-specific: >> >> http://msdn2.microsoft.com/en-us/library/8h19t214.aspx > > Right. However, the build option of Python where that's the case is > deprecated. Excellent. Thank you. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From george.sakkis at gmail.com Mon Jan 21 14:30:07 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 21 Jan 2008 11:30:07 -0800 (PST) Subject: Default attribute values pattern References: Message-ID: <2b7d114d-f29d-49f8-8ef0-6e9f1013958d@k2g2000hse.googlegroups.com> On Jan 19, 6:02 pm, "David Tweet" wrote: > Hello, > > Seems to me that setattrs sort of assumes that you want to have all your > initialization arguments set as attributes of the same name. I would think > you'd sometimes want to be able to process the extra arguments inside of each > __init__, assign them to attributes with different names, etc. > > My approach would be to treat each __init__ as a wrapping function, grabbing > the items it needs out of the keyword dictionary and then calling the next > __init__. Curious to hear other approaches though: > > def Grab(argdict, key, default): > """Like argdict.get(key, default), but also deletes key from argdict.""" > if key in argdict: > retval = argdict["key"] > del(argdict[key]) > else: > retval = default > return retval > > class Base(object): > def __init__(self, x=0, y=None): > print "in Base init" > self.x = x > self.y = y > > class Derived1(Base): > def __init__(self, **kwargs): > print "in Derived1 init" > self.z = Grab(kwargs, "z", None) > super(Derived1, self).__init__(**kwargs) > > class Derived2(Derived1): > def __init__(self, **kwargs): > print "in Derived2 init" > self.a = Grab(kwargs, "a", 0) > self.b = Grab(kwargs, "b", False) > super(Derived2, self).__init__(**kwargs) > print self.__dict__ > > newthing = Derived2(x=234, y="blah", a=55555) The problem with this (apart from being somewhat more verbose and less explicit) is that you have to set existing attributes (like x and y) *after* the call to super __init__ while new attributes (like z, a and b) *before* the call. Mixing it up will either raise a runtime error for passing an unknown argument to the parent, or (worse) set the parent's default instead of the child's. So for the common attribute setting case it involves more error-prone boilerplate code. George From kyosohma at gmail.com Fri Jan 25 08:59:46 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 25 Jan 2008 05:59:46 -0800 (PST) Subject: Ideas for Python Programming References: <9daf42a0-90bf-4881-8c07-3851a2b3f564@c23g2000hsa.googlegroups.com> Message-ID: <146bcf41-28a1-4510-915e-bf764ba66ff3@k2g2000hse.googlegroups.com> On Jan 25, 2:22 am, mistersexy wrote: > I have been programming in python for some time but I have become > short of ideas. A software exhibition is coming up, and I plan to show > python's worth 'cos it is quite underrated in this part of the world. > Could anyone suggest any really good program ideas and information on > how to implement them? I heartily welcome any good ideas. Why not do a search on SourceForge and see what's being programmed in Python? Then you could get ideas and/or join some of those projects. Mike From grante at visi.com Sat Jan 26 00:03:06 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 26 Jan 2008 05:03:06 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <13plfoacnodml55@corp.supernews.com> On 2008-01-26, ajaksu wrote: > On Jan 25, 11:10 pm, o... at thepond.com wrote: >> Once a python py file is compiled into a pyc file, I can disassemble >> it into assembler. Assembler is nothing but codes, which are >> combinations of 1's and 0's. You can't read a pyc file in a hex >> editor, but you can read it in a disassembler. It doesn't make a lot >> of sense to me right now, but if I was trying to trace through it with >> a debugger, the debugger would disassemble it into assembler, not >> python. > > Please, tell me you're kidding... I think we've been trolled. Nobody could be that stubbornly ignorant. -- Grant Edwards grante Yow! This is PLEASANT! at visi.com From tjhnson at gmail.com Mon Jan 21 18:22:12 2008 From: tjhnson at gmail.com (tjhnson at gmail.com) Date: Mon, 21 Jan 2008 15:22:12 -0800 (PST) Subject: Max Long Message-ID: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> How can I figure out the largest long available? I was hoping for something like sys.maxint, but I didn't see it. Also, can someone point me to where I can (concisely) read about size of such types (int, float, long). From over at thepond.com Wed Jan 23 02:04:35 2008 From: over at thepond.com (over at thepond.com) Date: Wed, 23 Jan 2008 07:04:35 GMT Subject: python24 symbol file...pyhon24.pdb Message-ID: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> I've seen a few references on the net to a python24.pdb file. I assume it's a symbol file along the lines of the pdb files issued by microsoft for their products. Maybe I'm wrong. Has anyone seen such an animal? Also, is there source code available for python24 for Windoze? I have seen reference to source code but not in a package for Windows. thanks From jeremy+complangpython at jeremysanders.net Tue Jan 29 17:18:03 2008 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 29 Jan 2008 22:18:03 +0000 Subject: breaking out of outer loops References: Message-ID: noemailplease0001 at gmail.com wrote: > Any elegant way of breaking out of the outer for loop than below, I > seem to have come across something, but it escapes me > > for i in outerLoop: > for j in innerLoop: > if condition: > break > else: > continue > break Perhaps Python needs a "continue N" or a "break N" statement :-) for i in outerLoop: for j in innerLoop: if condition: break 2 Seeing as we can't have a goto :-) Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From thomas.troeger.ext at siemens.com Thu Jan 10 09:01:37 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 10 Jan 2008 15:01:37 +0100 Subject: Embedding python code into text document question. References: Message-ID: Ok I've written a small example program to clarify matters: ================ [SNIP] ================ #!/usr/bin/python import os, sys, time def template(src, dst, sep): """ Copy file from src to dst, executing embedded python code. """ try: # read template file. f=open(src, "rU") data="".join(f.readlines()) f.close() # find embedded python code and execute it. while True: # find embedded embedded python command. offset=data.find(sep) if offset < 0: break offset2=data.find(sep, offset+1) if offset2 < 0: break cmd=data[offset+len(sep):offset2] # execute command. try: ret="" exec(compile(cmd, '', 'exec')) except: print "error compiling code `%s'." % cmd # substitute command with return value. data=data[:offset]+str(ret)+\ data[offset2+len(sep):] # write translated input. f=open(dst, "w") f.write(data) f.close() except: print "error processing template file `%s'." % src # ------------------------------ main ------------------------------- if len(sys.argv) > 2: template(sys.argv[1], sys.argv[2], '$$') ================ [SNIP] ================ This is the example input that works: ================ [SNIP] ================ process id: $$ret=os.getpid()$$ current date: $$ret=time.ctime()$$ superuser: $$ if os.geteuid(): ret="No" else: ret="Yes"$$ ================ [SNIP] ================ Now the `ret= ...' mechanism is not nice, I'd prefer to have a return statement instead. From wanzathe at gmail.com Fri Jan 4 09:54:43 2008 From: wanzathe at gmail.com (wanzathe) Date: Fri, 4 Jan 2008 06:54:43 -0800 (PST) Subject: how to build a dict including a large number of data References: Message-ID: <92b6eaea-715f-4a4d-8603-4fa1aab8f3e7@v4g2000hsf.googlegroups.com> On 1?4?, ??10?17?, Fredrik Lundh wrote: > wanzathe wrote: > > i have a binary file named test.dat including 9600000 records. > > the record format is int a + int b + int c + int d > > i want to build a dict like this: key=int a,int b values=int c,int d > > i choose using bsddb and it takes about 140 seconds to build the dict. > > you're not building a dict, you're populating a persistent database. > storing ~70000 records per second isn't that bad, really... > > > what can i do if i want to make my program run faster? > > or is there another way i can choose? > > why not just use a real Python dictionary, and the marshal module for > serialization? > > hi,Fredrik Lundn you are right, i'm populating a persistent database. i plan to use a real Python dictionary and use cPickle for serialization at first, but it did not work because the number of records is too large. Thanks From shriphanip at gmail.com Wed Jan 2 06:23:12 2008 From: shriphanip at gmail.com (Shriphani) Date: Wed, 2 Jan 2008 03:23:12 -0800 (PST) Subject: pdf library. References: <133097f4-de83-4e13-93f1-1404213333a4@l6g2000prm.googlegroups.com> <3b429178-8c07-4dcb-8034-1912c0597830@d21g2000prf.googlegroups.com> <5tuqhgF187o9eU2@mid.uni-berlin.de> Message-ID: <1ebe3b15-8d14-4056-a112-f7c57063bf79@l6g2000prm.googlegroups.com> On Jan 1, 5:38 pm, Marc 'BlackJack' Rintsch wrote: > On Tue, 01 Jan 2008 04:21:29 -0800,Shriphaniwrote: > > On Jan 1, 4:28 pm, Piet van Oostrum wrote: > >> >>>>>Shriphani (S) wrote: > >> >S> I tried pyPdf for this and decided to get the pagelinks. The trouble > >> >S> is that I don't know how to determine whether a particular page is the > >> >S> first page of a chapter. Can someone tell me how to do this ? > > >> AFAIK PDF doesn't have the concept of "Chapter". If the document has an > >> outline, you could try to use the first level of that hierarchy as the > >> chapter starting points. But you don't have a guarantee that they really > >> are chapters. > > > How would a pdf to html conversion work ? I've seen Google's search > > engine do it loads of times. Just that running a 500odd page ebook > > through one of those scripts might not be such a good idea. > > Heuristics? Neither PDF nor HTML know "chapters". So it might be > guesswork or just in your head. > > Ciao, > Marc 'BlackJack' Rintsch I could parse the html and check for the words "unit" or "chapter" at the beginning of a page. I am using pdftohtml on Debian and it seems to be generating the html versions of pdfs quite fast. I am yet to run a 500 page pdf through it though. Regards, Shriphani From http Mon Jan 21 17:36:24 2008 From: http (Paul Rubin) Date: 21 Jan 2008 14:36:24 -0800 Subject: Prioritization function needed (recursive help!) References: <51180fda-304d-4f7e-812a-32032585675b@e23g2000prf.googlegroups.com> Message-ID: <7xbq7e4xhz.fsf@ruckus.brouhaha.com> rh0dium writes: > I am really struggling on simply how to organize the data and write > the corresponding function - I tried classes but I don't know if > that's the best approach. See my other post on this. We just had a discussion thread about this. Is it a homework problem? Anyway, look up "topological sorting" in a CS textbook or on Wikipedia. From dbaston at gmail.com Fri Jan 25 17:33:02 2008 From: dbaston at gmail.com (dbaston at gmail.com) Date: Fri, 25 Jan 2008 14:33:02 -0800 (PST) Subject: Puzzled by behaviour of class with empty constructor Message-ID: <99b8e2ac-1c72-430a-9172-a809e169f96a@i12g2000prf.googlegroups.com> Hello, I have a class called 'Axis' that I use as a base class for several types of axes that can be created by a grid generation program that I have written: equally-spaced grids, logarithmic grids, etc. In any case, if I use this base class by itself, I see some puzzling behaviour: ############# class Axis: ends = [] N = None def __init__(self): pass x = Axis() y = Axis() z = Axis() x.ends.append((0,2)) print x.ends,y.ends,z.ends ############# Running the following code outputs: >>> [(0, 2)] [(0, 2)] [(0, 2)] Can anyone explain this? From ryan at ryankaskel.com Wed Jan 23 15:23:53 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 12:23:53 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> <12d19814-b7b9-44b0-aee3-299befac7279@i12g2000prf.googlegroups.com> <66446d1e-189c-4c24-bd7a-83cbd66deb60@i12g2000prf.googlegroups.com> Message-ID: On Jan 23, 3:02 pm, John Machin wrote: > On Jan 24, 6:57 am, ryan k wrote: > > > So yea i will just have to count dashes. > > Read my lips: *you* counting dashes is dumb. Writing your code so that > *code* is counting dashes each time it opens the file is smart. Okay it's almost working ... new parser function: def _load_table(self): counter = 0 for line in self.table_fd: # Skip the second line if counter == 0: # This line contains the columns, parse it column_list = line.split() elif counter == 1: # These are the dashes line_l = line.split() column_width = [len(i) for i in line_l] print column_width else: # This is a row, parse it marker = 0 row_vals = [] for col in column_width: start = sum(column_width[:marker]) finish = sum(column_width[:marker+1]) print line[start:finish].strip() row_vals.append(line[start:finish].strip()) marker += 1 self.rows.append(Row(column_list, row_vals)) counter += 1 Something obvious you can see wrong with my start finish code? ['rimon', 'rimon', 'Barr', 'Rimon', '22 Greenside Cres., Thornhill, ON L3T 6W9', '2', '', 'm', '102', '100 -', '22.13 1234567890', 'barr at cs.cornell.edu', ''] ['UNAME', 'PASSWD', 'LNAME', 'FNAME', 'ADDR', 'ZONE', 'SEX', 'AGE', 'LIMIT', 'BALANCE', 'CREDITCARD', 'EMAIL', 'ACTIVE'] From dg.google.groups at thesamovar.net Sun Jan 27 13:47:13 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Sun, 27 Jan 2008 10:47:13 -0800 (PST) Subject: Python self-evaluating strings References: Message-ID: It's a bit cheap, but how about >>> from inspect import getsource >>> print getsource(getsource) or similarly def f(g): import inspect return inspect.getsource(g) print f(f) Dan From lewisnorton90 at googlemail.com Thu Jan 17 06:13:34 2008 From: lewisnorton90 at googlemail.com (Ionis) Date: Thu, 17 Jan 2008 03:13:34 -0800 (PST) Subject: Opening/Running files through python Message-ID: <239efd0e-5ac8-485c-b316-aa52b0a2c316@i72g2000hsd.googlegroups.com> Hey guys, hope you can help me here. I am running in windows and I am trying to open a file via python. I want the file (a text file) to open up in the users default text editor. I'm not wanting to read a file, I just want to open it. Is there a way? Thanks in advance. From michele.simionato at gmail.com Mon Jan 14 07:53:49 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 14 Jan 2008 04:53:49 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> Message-ID: <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> On Jan 14, 1:41 pm, Richard Szopa wrote: > However, there's one piece that doesn't completely fit to the puzzle: > why does getattr work? The help says: > > getattr(...) > getattr(object, name[, default]) -> value > > Get a named attribute from an object; getattr(x, 'y') is > equivalent to x.y. > When a default argument is given, it is returned when the > attribute doesn't > exist; without it, an exception is raised in that case. > > Does it work on the basis that "getattr(x, 'y') is equivalent to x.y"? > What is then a "named attribute for an object" in Python? It seems not > to be equivalent to the value of the item whose name is 'y' in the > object's class __dict__... > > Cheers, > > -- Richard I really need to publish this one day or another, since these questions about super keeps coming out: http://www.phyast.pitt.edu/~micheles/python/super.html From deets at nospam.web.de Fri Jan 18 03:15:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 18 Jan 2008 09:15:22 +0100 Subject: Unique thread ID In-Reply-To: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> References: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> Message-ID: <5vb5h0F1l2itoU1@mid.uni-berlin.de> Benjamin schrieb: > Is there a way to obtain a unique ID for the current thread? I have an > object that I need to store local thread data in, and I don't want to > use threading.local because each thread might have multiple instances > of my object. You can use the thread itself, it's usable as key (that's what threadlocals use for their implementation anyway) But I don't understand your problem - all thread-local implementations I know of (is there a standard?) can be instantiated in each object and then offer a get/set method (keyed or not) - but without interfering with outher instances of themselves of course. Diez From stefaan.himpe at gmail.com Fri Jan 4 06:31:55 2008 From: stefaan.himpe at gmail.com (stefaan) Date: Fri, 4 Jan 2008 03:31:55 -0800 (PST) Subject: storing setup.py (for py2exe) in other directory than main script directory Message-ID: <9cf3764d-fa07-499a-8c94-27b4fdeb98e9@j20g2000hsi.googlegroups.com> Hello list, I have the following problem after upgrading to python 2.5 and py2exe 0.6.6 It seems that py2exe is using the location of the setup.py file as its search path, instead of the current working folder. (This used to be different with an older version of py2exe) Can I tell py2exe somehow to use the current working directory as search path instead of the location of the setup.py file ? Also: is this a feature or a bug ? The reason I am asking is because I'd like to keep the build scripts in a "win32specific" subfolder of my code folder, and then run the following command in the code folder: python win32specific\setup.py py2exe Alternative suggestions also welcome! Best regards, Stefaan. From mtobis at gmail.com Fri Jan 11 20:36:10 2008 From: mtobis at gmail.com (Michael Tobis) Date: Fri, 11 Jan 2008 17:36:10 -0800 (PST) Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> <13og1lgcespv6c2@corp.supernews.com> Message-ID: On Jan 11, 6:15 pm, Steven D'Aprano wrote: > Your users are *scientists*, and you don't trust their intellectual > ability to learn a programming language as simple as Python? > > Instead of spending time and effort writing, debugging and maintaining > such a fragile approach, why not invest in a couple of introductory books > on Python programming and require your scientists to go through the first > few chapters? Or write out a one-page "cheat sheet" showing them simple > examples. Or, and probably most effectively, make sure all your classes > have doc strings with lots of examples, and teach them how to use help(). > > Some people problems are best dealt with by a technical solution, and > some are not. > > -- > Steven I am currently talking very similar trash on my blog, See http://initforthegold.blogspot.com/2008/01/staying-geeky.html and http://initforthegold.blogspot.com/2007/12/why-is-climate-modeling-stuck.html You seem to think that learning the simple language is equivalent to grasping the expressive power that the language provides. Yes, users are scientists. Therefore they do not have the time or interest to gain the depth of skill to identify the right abstractions to do their work. There are many abstractions that could be useful in science that are currently provided with awkward libraries or messy one-off codes. The idea that a scientist should be expected to be able to write correct and useful Python is reasonable. I and the OP are relying on it. The idea that a scientist should be expected to identify and build clever and elegant abstractions is not. If you think every scientist can be a really good programmer you underestimate at least one of what good scientists do or what good programmers do or what existing high performance scientific codes are called upon to do. mt From gbacon at hiwaay.net Tue Jan 29 12:12:09 2008 From: gbacon at hiwaay.net (Greg Bacon) Date: Tue, 29 Jan 2008 17:12:09 -0000 Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> <13ps95mg8am3l37@corp.supernews.com> Message-ID: <13punj94ev46910@corp.supernews.com> In article , Dr.Ruud wrote: : I negated the test, to make the regex simpler: [...] Yes, your approach is simpler. I assumed from the "need it all in one pattern" constraint that the OP is feeding the regular expression to some other program that is looking for matches. I dunno. Maybe it was the familiar compulsion with Perl to attempt to cram everything into a single pattern. Greg -- What light is to the eyes -- what air is to the lungs -- what love is to the heart, liberty is to the soul of man. -- Robert Green Ingersoll From mal at egenix.com Wed Jan 23 03:54:14 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 23 Jan 2008 09:54:14 +0100 Subject: HTML parsing confusion In-Reply-To: References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> <50269e4a-af44-4d73-b6cb-c42af6b5164d@e10g2000prf.googlegroups.com> <5vmkiiF1nadr7U1@mid.uni-berlin.de> Message-ID: <479700B6.1060505@egenix.com> On 2008-01-23 01:29, Gabriel Genellina wrote: > En Tue, 22 Jan 2008 19:20:32 -0200, Alnilam escribi?: > >> On Jan 22, 11:39 am, "Diez B. Roggisch" wrote: >>> Alnilam wrote: >>>> On Jan 22, 8:44 am, Alnilam wrote: >>>>>> Pardon me, but the standard issue Python 2.n (for n in range(5, 2, >>>>>> -1)) doesn't have an xml.dom.ext ... you must have the >>> mega-monstrous >>>>>> 200-modules PyXML package installed. And you don't want the 75Kb >>>>>> BeautifulSoup? >>>> Ugh. Found it. Sorry about that, but I still don't understand why >>>> there isn't a simple way to do this without using PyXML, BeautifulSoup >>>> or libxml2dom. What's the point in having sgmllib, htmllib, >>>> HTMLParser, and formatter all built in if I have to use use someone >>>> else's modules to write a couple of lines of code that achieve the >>>> simple thing I want. I get the feeling that this would be easier if I >>>> just broke down and wrote a couple of regular expressions, but it >>>> hardly seems a 'pythonic' way of going about things. >>> This is simply a gross misunderstanding of what BeautifulSoup or lxml >>> accomplish. Dealing with mal-formatted HTML whilst trying to make _some_ >>> sense is by no means trivial. And just because you can come up with a >>> few >>> lines of code using rexes that work for your current use-case doesn't >>> mean >>> that they serve as general html-fixing-routine. Or do you think the >>> rather >>> long history and 75Kb of code for BS are because it's creator wasn't >>> aware >>> of rexes? >> I am, by no means, trying to trivialize the work that goes into >> creating the numerous modules out there. However as a relatively >> novice programmer trying to figure out something, the fact that these >> modules are pushed on people with such zealous devotion that you take >> offense at my desire to not use them gives me a bit of pause. I use >> non-included modules for tasks that require them, when the capability >> to do something clearly can't be done easily another way (eg. >> MySQLdb). I am sure that there will be plenty of times where I will >> use BeautifulSoup. In this instance, however, I was trying to solve a >> specific problem which I attempted to lay out clearly from the >> outset. >> >> I was asking this community if there was a simple way to use only the >> tools included with Python to parse a bit of html. There are lots of ways doing HTML parsing in Python. A common one is e.g. using mxTidy to convert the HTML into valid XHTML and then use ElementTree to parse the data. http://www.egenix.com/files/python/mxTidy.html http://docs.python.org/lib/module-xml.etree.ElementTree.html For simple tasks you can also use the HTMLParser that's part of the Python std lib. http://docs.python.org/lib/module-HTMLParser.html Which tools to use is really dependent on what you are trying to solve. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jan 23 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 usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Jan 20 18:54:58 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 21 Jan 2008 00:54:58 +0100 Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> <478e1e3e$0$18054$426a74cc@news.free.fr> <34aa1a1f-2034-471d-91ee-2a758dab555b@f47g2000hsd.googlegroups.com> Message-ID: <5vi5aiF1m1n0oU1@mid.individual.net> (messed up references?) Lie wrote: > Please again, stop taking letters to the words Please don't mix up followups. Regards, Bj?rn -- BOFH excuse #11: magnetic interference from money/credit cards From gherron at islandtraining.com Wed Jan 23 11:36:40 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 23 Jan 2008 08:36:40 -0800 Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? In-Reply-To: References: Message-ID: <47976D18.8040503@islandtraining.com> Boris Borcic wrote: > I am surprised nobody pointed out explicitely that > > True==1 and False==0 > Several of us did indeed point this out by saying that bool's are a subclass of ints. > so that for instance > > 5*(True+True)==10 > > and even (but implementation-dependent) : > > 5*(True+True) is 10 > > BB > > From lists at cheimes.de Thu Jan 17 03:14:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 17 Jan 2008 09:14:17 +0100 Subject: Extending the readline module? In-Reply-To: References: Message-ID: Casey Rodarmor wrote: > What is the best way to go about doing this? You need some basic knowledge about C, the readline headers, Python sources and a compiler. Are you interested to contribute the extended code to the Python code base? We are always looking for new developers and additional features. Please join the Python developer list and tell us about your idea. Christian From pataphor at gmail.com Thu Jan 24 17:17:54 2008 From: pataphor at gmail.com (pataphor) Date: Thu, 24 Jan 2008 23:17:54 +0100 Subject: sudoku solver in Python ... References: <43b2a56b-c8eb-4851-a9f6-10aa7e32e3ce@i29g2000prf.googlegroups.com> <1r589888wvzss$.17bg43io6of00.dlg@40tude.net> Message-ID: <20080124231754.2706d426@hyperspace> On Thu, 24 Jan 2008 21:09:42 +0100 Thomas Thiel wrote: > Neither fast nor user friendly, but very concise: This is a bit faster: options = set([str(i) for i in range(1, 10)]) def allow(puzzle,i): exclude = set(x if i//9 == j//9 or i%9 == j%9 or i//27 == j//27 and (i%9)//3 == (j%9)//3 else '0' for j,x in enumerate(puzzle)) return options-exclude def solve(puzzle): zeros = [i for i,x in enumerate(puzzle) if x == '0'] if not zeros: print puzzle else: i,R = min(((j,allow(puzzle,j)) for j in zeros), key=lambda x: len(x[1])) for option in R: solve(puzzle[:i] + option + puzzle[i+1:]) P. From george.sakkis at gmail.com Fri Jan 11 10:18:15 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 07:18:15 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> Message-ID: On Jan 11, 9:41 am, Hrvoje Niksic wrote: > Bruno Desthuilliers > writes: > > > fact 1: CPython compiles source code to byte-code. > > fact 2: CPython executes this byte-code. > > fact 3: Sun's JDK compiles source code to byte-code. > > fact 4: Sun's JDK executes this byte-code. > > > Care to prove me wrong on any of these points ? Don't bother: you > > can't. > > Fact 4 is misleading because it is only one option available to Sun's > JDK. Sun's JDK is also capable of transforming the byte-code to > native code and letting the processor execute that instead of the > original byte code, and that is where the most significant speed > increase comes from. Most importantly, it does so automatically, by > default, with no programmer intervention or configuration, and with > 100% compatibility, so it doesn't compare well to Python accelerators > like psyco. Plus, IIRC Java's JIT is not limited to optimizing special cases, while psyco helps primarily with number-crunching code (admittedly an important special case) and can have zero or even (small) negative effect on arbitrary Python programs. George From tarun.kap at gmail.com Wed Jan 16 10:05:28 2008 From: tarun.kap at gmail.com (Tarun Kapoor) Date: Wed, 16 Jan 2008 07:05:28 -0800 (PST) Subject: Paramiko/SSH blues.... Message-ID: I am using paramiko to do an SFTP file transfer... I was able to connect to the remote server using an SFTP client I have just to make sure that username and password are working.. But when i try to connect using this script it fails .... **hostname, username and password are declared. # now, connect and use paramiko Transport to negotiate SSH2 across the connection sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) t = paramiko.Transport(sock) event = threading.Event() t.start_client(event) event.wait(15) if not t.is_active(): print 'SSH negotiation failed.' sys.exit(1) else: print "SSH negotiation sucessful" event.clear() t.auth_password(username=username, password=password,event=event) if not t.is_authenticated(): print "not authenticated" output: SSH negotiation successful not authenticated From deets at nospam.web.de Mon Jan 14 08:53:36 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 14 Jan 2008 14:53:36 +0100 Subject: Threaded server References: <7decdf29-aab4-4fc6-93d8-7b2565e23f78@m34g2000hsf.googlegroups.com> Message-ID: <5v17r0F1jvjc2U1@mid.uni-berlin.de> Giampaolo Rodola' wrote: > On 14 Gen, 12:30, Nick Craig-Wood wrote: >> Giampaolo Rodola' wrote: >> > I'm trying to run an asynchronous FTP server I wrote into a thread for >> > being able to run a test suite against it. >> > The code below is the threaded FTP server code I'm using: >> >> > class FTPd(threading.Thread): >> >> > def __init__(self): >> > self.active = False >> > threading.Thread.__init__(self) >> >> > def start(self, flag=None): >> > assert not self.active >> > self.flag = flag >> > threading.Thread.start(self) >> >> > def run(self): >> > assert not self.active >> > ftpd = ftpserver.FTPServer(address, ftp_handler) >> > if self.flag: >> > self.flag.set() >> > self.active = True >> > while self.active: >> > ftpd.server_forever(timeout=1, count=1) >> > ftpd.close() >> >> > def stop(self): >> > assert self.active >> > self.active = False >> >> > flag = threading.Event() >> > ftpd = FTPd() >> > ftpd.start(flag) >> > flag.wait() ?# wait for it to start >> > unittest.main() # run the test suite >> > ftpd.stop() >> >> > Sometimes I get a strange error when all the tests have finished, the >> > server is stopped and Python is exiting: >> >> > Ran 50 tests in 1.515s >> >> > OK >> > Exception exceptions.TypeError: "'NoneType' object is not callable" in >> > > > thod FTPHandler.__del__ of > > 127.0.0.1:2 >> > 249 at 0xa4b080>> ignored >> > Exception exceptions.TypeError: "'NoneType' object is not callable" in >> > > > thod FTPServer.__del__ of > > 127.0.0.1:543 >> > 21 at 0x9e1a30>> ignored >> >> > I sincerely don't know why that happens but it's likely because I'm >> > not using threads properly. >> > My concern is that this could be caused by a sort of race condition >> > (e.g. Python tries to exit when ftpd.close call is not yet >> > completed). >> >> It looks like when python is shutting down, it has removed an object >> the ftphandler code relies on. >> >> I see you attempt to kill the ftp server with ftpd.stop(). ?That is >> good, but you don't wait for the thread to finish (it might take up to >> a second in ftpd.server_forever if I understand correctly). >> >> I expect if you put a self.join() at the end of the stop() method the >> problem will go away. >> >> -- >> Nick Craig-Wood --http://www.craig-wood.com/nick- >> Nascondi testo tra virgolette - >> >> - Mostra testo tra virgolette - > > Tried it but the problem remains. > The strange thing is that it sometimes happens, sometimes doesn't. AFAIK you can safely ignore this error. It essentially stems from non-determinism when shutting down threads. Diez From JO3chiang at gmail.com Mon Jan 7 22:15:36 2008 From: JO3chiang at gmail.com (jo3c) Date: Mon, 7 Jan 2008 19:15:36 -0800 (PST) Subject: use fileinput to read a specific line Message-ID: hi everybody im a newbie in python i need to read line 4 from a header file using linecache will crash my computer due to memory loading, because i am working on 2000 files each is 8mb fileinput don't load the file into memory first how do i use fileinput module to read a specific line from a file? for line in fileinput.Fileinput('sample.txt') ???? From aahz at pythoncraft.com Wed Jan 2 23:32:43 2008 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2008 20:32:43 -0800 Subject: cloud computing (and python)? References: <69337707-ff18-4b39-af0a-78cf0a14b667@1g2000hsl.googlegroups.com> <4715e05f-456b-4274-9718-b6c009af7698@1g2000hsl.googlegroups.com> Message-ID: In article , Terry Reedy wrote: > >2. yes, cost. University mainframes cost $s/minute. I remember >blowing about $200 due to a misplaced comma or something in a >statistical analysis setup. So it was cost-effective (and rather >liberating) to spend $10000 on a desktop Unix system for both >statistics and text work. Same here, only it was not remembering that the filesystem disallowed names starting with digits. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From mark.e.tolonen at mailinator.com Wed Jan 30 22:43:05 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Wed, 30 Jan 2008 19:43:05 -0800 Subject: small problem with re.sub References: Message-ID: "Astan Chee" wrote in message news:mailman.78.1201748496.9267.python-list at python.org... > Hi, > I have a html text stored as a string. Now I want to go through this > string and find all 6 digit numbers and make links from them. > Im using re.sub and for some reason its not picking up the previously > matched condition. Am I doing something wrong? This is what my code looks > like: > htmlStr = re.sub('(?P\d{6})',' href=\"http://linky.com/(?P=id).html\">(?P=id)',htmlStr) > It seems that it replaces it alright, but it replaces it literally. Am I > not escaping certain characters? > Thanks again for the help. > Cheers > > Animal Logic > http://www.animallogic.com > > Please think of the environment before printing this email. > > This email and any attachments may be confidential and/or privileged. If > you are not the intended recipient of this email, you must not disclose or > use the information contained in it. Please notify the sender immediately > and delete this document if you have received it in error. We do not > guarantee this email is error or virus free. > > See the help for re.sub: "Backreferences, such as "\6", are replaced with the substring matched by group 6 in the pattern." This should work: htmlStr = re.sub('(?P\d{6})','\\1',htmlStr) --Mark From cwitts at gmail.com Tue Jan 8 07:04:01 2008 From: cwitts at gmail.com (Chris) Date: Tue, 8 Jan 2008 04:04:01 -0800 (PST) Subject: Open a List of Files References: Message-ID: <0cc061f5-fa3e-48ca-aff3-36e09de4e894@h11g2000prf.googlegroups.com> On Jan 8, 1:03 pm, Fredrik Lundh wrote: > BJ Swope wrote: > > given a list such as > > > ['messages', 'recipients', 'viruses'] > > > how would I iterate over the list and use the values as variables and > > open the variable names a files? > > > I tried > > > for outfile in ['messages', 'recipients', 'viruses']: > > filename = os.path.join(Host_Path, outfile) > > outfile = open(filename, 'w') > > > But it's not working. > > the code looks ok. please define "not working". > > Bad coding style in that one. Do you have Write permissions to that 'Host_path' ? import os, sys FILELIST = ['messages', 'recipients', 'viruses'] HOST_PATH = os.getcwd() # Or whatever path you are using if not os.access(HOST_PATH, os.W_OK): sys.exit('Unable to write to path specified.') for file in FILELIST: output_file = open(os.path.join(HOST_PATH, file), 'wb') do_something_with_file() A better definition of not working would be appreciated, Tracebacks if you have. From martin at v.loewis.de Wed Jan 16 23:56:59 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 Jan 2008 05:56:59 +0100 Subject: -fno-strict-aliasing turned off when cross compiling In-Reply-To: <66c2d5b4-c84f-47d9-aa4a-1cca3ae594b2@q39g2000hsf.googlegroups.com> References: <66c2d5b4-c84f-47d9-aa4a-1cca3ae594b2@q39g2000hsf.googlegroups.com> Message-ID: <478ee01b$0$4589$9b622d9e@news.freenet.de> > Does anyone have an idea why -fno-strict-aliasing is turned off when > cross compiling? Because detection of -fno-strict-aliasing is made through running the compiler output (AC_TRY_RUN, see configure.in instead). For cross-compilation, running the program isn't actually possible, so a default must be specified. Since we can't know whether the cross-compiler accepts -fno-strict-aliasing, we leave it out. Regards, Martin From python.list at tim.thechases.com Mon Jan 28 12:39:18 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 28 Jan 2008 11:39:18 -0600 Subject: referer url In-Reply-To: References: <0e7fb40e-809c-4979-bbb8-0cd9a7e816c2@t1g2000pra.googlegroups.com> Message-ID: <479E1346.90507@tim.thechases.com> > 1) CGI so i'm doing it right. that's helpful to know > 2) this is impossible as i'm doing the exact same thing with another > language and it utterly works. Just making sure...same browser/setup/configuration, different language? > 3) the same as above kinda figured...most servers give you the HTTP_REFERER, so you' have to > 4) no.. > > this gets nerve breaking! Well, you can always dump the contents of os.environ into your output to see if you can find why. from cgi import escape out.write('
'.join([ '%s:%s' % (escape(k), escape(v)) for k,v in os.environ.iteritems() ]) -tkc From hkimball at eti-web.com Mon Jan 7 09:51:51 2008 From: hkimball at eti-web.com (hkimball at eti-web.com) Date: Mon, 7 Jan 2008 06:51:51 -0800 (PST) Subject: ctypes Message-ID: <90434049-2860-4b6f-aece-be6f896e5ece@s19g2000prg.googlegroups.com> I am trying to call a funtinon in a third party dll that spawns another exe and I am using ctypes. Python does not complain at all but the other process does not get spawned. It appears that I am gaining access to the functions but with no results. Any ideas? Thanks in advance. >>> from ctypes import * >>> cdecl = cdll.LoadLibrary("c:\projects\python\geinterface.dll") >>> cdecl._GE_Connect <_FuncPtr object at 0x00B7E378> >>> cdecl._GE_Connect() 0 >>> cdecl._GE_IsConnected() 0 From mik3l3374 at gmail.com Mon Jan 7 07:43:55 2008 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: Mon, 7 Jan 2008 04:43:55 -0800 (PST) Subject: Delete lines containing a specific word References: Message-ID: <3bfab8d6-bcb6-46c3-8fd2-536a502d343d@41g2000hsy.googlegroups.com> On Jan 7, 1:21 am, Francesco Pietra wrote: > Please, how to adapt the following script (to delete blank lines) to delete > lines containing a specific word, or words? > > f=open("output.pdb", "r") > for line in f: > line=line.rstrip() > if line: > print line > f.close() > > If python in Linux accepts lines beginning with # as comment lines, please also > a script to comment lines containing a specific word, or words, and back, to > remove #. > > Thanks > francesco pietra > > ____________________________________________________________________________________ > Looking for last minute shopping deals? > Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping for line in open("file"): if not "word" in line: print line on the command, use the ">" operator to redirect to a file From grahn+nntp at snipabacken.dyndns.org Sun Jan 20 09:35:26 2008 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 20 Jan 2008 14:35:26 GMT Subject: writing Python in Emacs References: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> Message-ID: ["Followup-To:" header set to comp.lang.python.] On Sat, 19 Jan 2008 17:51:50 +0100, Terry Jones wrote: >>>>>> "Richard" == Richard Szopa writes: > >Richard> I am a devoted Emacs user and I write a lot in Python. > > Me too. > >Richard> I need the following features: > >Richard> 1) Tab completion, ideally Slime like. That is, when there's not >Richard> enough letters to unambiguously complete a symbol, I want it to >Richard> show a buffer (w/o taking the focus) w/ the possible >Richard> completions. In an ideal world, it would be able to complete >Richard> fo.ba to foo.bar. I imagine this would require quite tight >Richard> Emacs-Python integration. > > I know this is not what you want, but I use hippie expand (M-/) to cycle > through possible completions. It's not Python aware, but it is of some use. Also known as dabbrev-expand, and tied to Ctrl-TAB. I like it *a lot*, and I like it even more because it *isn't* Python aware. I can use the same function no matter what I am typing, often with files noone would dream of writing a mode for. ... >Richard> 4) (optional) I would like to see the definition of a function >Richard> function or class by hitting M-. on its name. (I understand that >Richard> this may be impossible for methods, as Emacs would have to >Richard> automagically infer the type of the object). > > This is just an emacs tag file need. Have you googled for something like > emacs tags python? Tags works fine, or at least as well as can be expected. I use the 'etags' which comes with 'ctags', apparently. > If you have the time, please summarize your findings. The emacs/python > world has always seemed quite amorphous to me too. I don't know; python-mode colorizes well and it knows how to help me keep the indentation sane. The Eclipse users I have seen seem to have more problems than I have, for example. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From michele.simionato at gmail.com Tue Jan 1 02:59:20 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 31 Dec 2007 23:59:20 -0800 (PST) Subject: using super References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> Message-ID: <58c1aa27-98e4-4129-852c-f9a8477605db@i7g2000prf.googlegroups.com> On Jan 1, 7:56 am, iu2 wrote: > no one has to remember to call the parent's get_name method. It's done > automatically. > > (A PEP maybe? I sense you don't really like it.. ;-) > What do you think? Good? Too implicit? > > iu2 No PEP, this would never pass. There would be no way to stop a method from calling its parent: you would lose control of your classes, so I think this is a bad idea. Having said so, it is easy to implement what you want with a metaclass: def callParent(*methodnames): class Meta(type): def __init__(cls, name, bases, dic): for methodname in methodnames: if methodname in dic: def new_meth(self, method=methodname): parent = getattr(super(cls, self), method, None) if parent: parent() child = dic.get(method) if child: child(self) setattr(cls, methodname, new_meth) return Meta class B(object): __metaclass__ = callParent('get_name') def get_name(self): print "This is B.get_name" class C(B): def get_name(self): print "This is C.get_name" C().get_name() Now every subclass of B defining a get_name method will automagically call its parent method. Michele Simionato From http Tue Jan 15 13:18:09 2008 From: http (Paul Rubin) Date: 15 Jan 2008 10:18:09 -0800 Subject: Benchmark [was Re: common problem - elegant solution sought] References: <5v3gg1F1kkla5U1@mid.dfncis.de> <478ccc9e$0$29264$ba620e4c@news.skynet.be> Message-ID: <7xbq7ngdge.fsf@ruckus.brouhaha.com> Helmut Jarausch writes: > def del_by_key(L,key) : > for pos, (k,d) in enumerate(L): > if k == key : > del L[pos] > break This looks very dangerous, mutating L while iterating over it. From thegooddale at gmail.com Mon Jan 28 16:28:12 2008 From: thegooddale at gmail.com (Yansky) Date: Mon, 28 Jan 2008 13:28:12 -0800 (PST) Subject: Problems installing Python on server Message-ID: I asked my hosting company if they would upgrade Python on my server to the latest version. They responded with: "Sorry no. We tend to stick with what comes packaged with the unix distribution to ease maintenance issues. There is nothing stopping you from running your own version of python from within your own account. Download the source and compile it and install it into your own space. Adjust the fist line of your python scripts to reflect the location of YOUR python binary: #! /home/youraccount/yourlibs/python and you should be all set." The build instructions for Python are: To start building right away (on UNIX): type "./configure" in the current directory and when it finishes, type "make". This creates an executable "./python"; to install in usr/local, first do "su root" and then "make install". The problem is, I don't have root access to the server so I can't do the "make install". I have ubuntu on my computer, but from what I understand I can't compile it on that and upload it because the server runs Red Had and the ./configure would have made it incompatible right? So how can I build Python without root access? From python.list at tim.thechases.com Thu Jan 10 13:39:16 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 10 Jan 2008 12:39:16 -0600 Subject: What is "lambda x=x : ... " ? In-Reply-To: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> Message-ID: <47866654.4090407@tim.thechases.com> > What does "y=y" and "c=c" mean in the lambda function? the same thing it does in a function definition: def myfunct(a, b=42, y=3.141): pass > ################# > x = 3 > y = lambda x=x : x+10 > > print y(2) > ################## > > It prints 12, so it doesn't bind the variable in the outer scope. You're mostly correct, as it does pull it out of the local context. Try x = 3 y = lambda x=x: x+10 print y(2) print y() to get "12" then "13" back. -tkc From arnodel at googlemail.com Wed Jan 30 08:22:45 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 30 Jan 2008 05:22:45 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> Message-ID: <091ecd90-0193-43b9-8abc-eddbb52e47af@z17g2000hsg.googlegroups.com> On Jan 30, 11:57?am, Arnaud Delobelle wrote: > n = len(a) > for i, x in enumerate(a): > ? ? if x == 99: del a[i-n] Oops. That can't work. Don't know what I was thinking here. I probably did had one mental refactoring too many... -- Arnaud From gagsl-py2 at yahoo.com.ar Sat Jan 19 20:53:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 Jan 2008 23:53:57 -0200 Subject: Gui front-end to version control program References: Message-ID: En Sat, 19 Jan 2008 17:15:21 -0200, David Delony escribi?: > I want something that can work with any file, as Subversion does. I can't > think of any > GUI wrappers written in Python off the top of my head. I would like to There exist TortoiseCVS and TortoiseSVN. They are very intuitive and easy to use front ends, but being Explorer extensions, they're tied to Windows. They're not written in Python, but in C++. -- Gabriel Genellina From kar1107 at gmail.com Tue Jan 8 19:58:54 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 8 Jan 2008 16:58:54 -0800 (PST) Subject: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> Message-ID: <14d3e04e-4bfb-4b1f-b8b6-3183de48f921@i3g2000hsf.googlegroups.com> On Jan 8, 1:20 am, Robert Latest wrote: > Hello, > > look at this function: > > -------------- > def test(): > child = os.popen('./slow') > for line in child: > print line > ------------- > > The program "slow" just writes the numbers 0 through 9 on stdout, one line a > second, and then quits. > > I would have expected the python program to spit out a numbers one by one, > instead I see nothing for 10 seconds and then the whole output all at once. > > How can I get and process the pipe's output at the pace it is generated? I've seen this problem and it took me a while to figure out what is happening. As other posts, I too first suspected it's a problem related to line/ full buffering on the sender side (./slow here). It turned out that the "for line in child:" line in the iterator is the culprit. The iterator does something like a child.readlines() underneath (in it's __iter__ call) instead of a more logical single line read. Change your reading to force line-by-line read e.g. While True: line = child.readline() if not line: break print line Karthik > > Thanks, > > robert From default at defaulter.net Sat Jan 12 13:27:16 2008 From: default at defaulter.net (default) Date: Sat, 12 Jan 2008 13:27:16 -0500 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> <4788de48$0$26887$ecde5a14@news.coretel.net> Message-ID: On Sat, 12 Jan 2008 09:15:44 -0800, ChairmanOfTheBored wrote: > You are both fucked in the head, coffee or not. He more than you, but >still, you both don't know what you are talking about. Any castigation from Bored is an accolade . . . I must be on the right track to get that knee jerk reaction. -- From http Sat Jan 26 00:32:10 2008 From: http (Paul Rubin) Date: 25 Jan 2008 21:32:10 -0800 Subject: Generational Interfaces References: <1b7b3b47-72f0-4a5d-9185-4903e75dba47@d70g2000hsb.googlegroups.com> Message-ID: <7xhch16tk5.fsf@ruckus.brouhaha.com> Carl Banks writes: > AirplaneInterface = InterfaceTracker("Airplane") > ... > set_up_initial_state() > ... > AirplaneInterface.report(self) > Thoughts? (Surely someone's thought to do this before.) A decorator might express the idea a little more naturally. Also, I'd say the interface tracker really should be told explicitly when something is part of the interface and when it's specific to a particular class implementing the interface. It shouldn't try to guess this based on some operation appearing in more than one class. Maybe there's some operation done on all jet planes and on no propeller planes, that shouldn't be part of the top level airplane interface. From ryan at ryankaskel.com Wed Jan 23 14:17:55 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 11:17:55 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> Message-ID: <12d19814-b7b9-44b0-aee3-299befac7279@i12g2000prf.googlegroups.com> I am taking a database class so I'm not asking for specific answers. Well I have this text tile: http://www.cs.tufts.edu/comp/115/projects/proj0/customer.txt And this code: # Table and row classes used for queries class Row(object): def __init__(self, column_list, row_vals): print len(column_list) print len(row_vals) for column, value in column_list, row_vals: if column and value: setattr(self, column.lower(), value) class Table(object): def __init__(self, table_name, table_fd): self.name = table_name self.table_fd = table_fd self.rows = [] self._load_table() def _load_table(self): counter = 0 for line in self.table_fd: # Skip the second line if not '-----' in line: if counter == 0: # This line contains the columns, parse it column_list = line.split() else: # This is a row, parse it row_vals = line.split() # Create a new Row object and add it to the table's # row list self.rows.append(Row(column_list, row_vals)) counter += 1 Because the addresses contain spaces, this won't work because there are too many values being unpacked in row's __init__'s for loop. Any suggestions for a better way to parse this file? I don't want to cheat but just some general ideas would be nice. Thanks! From fredrik at pythonware.com Wed Jan 9 05:37:21 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 11:37:21 +0100 Subject: Open a List of Files In-Reply-To: References: <874pdomrrd.fsf@mulj.homelinux.net> <4f67337a-14ea-4552-8a5a-6de9703e58ff@d70g2000hsb.googlegroups.com> Message-ID: Paul Hankin wrote: > Thanks Fredrik! I learnt something today. > > I wonder if there's a reason why it doesn't raise an exception when > you try to write to it? That would seem better to me than having it > sometimes update variables and sometimes not. probably because it returns a standard dictionary object, and Python's dictionary objects are writable. (and if someone wants to reopen the old discussion about how Python absolutely definitely needs frozen dictionaries to be useful at all, please do so in a new thread ;-) From ganeshborse at gmail.com Thu Jan 3 07:49:57 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 3 Jan 2008 04:49:57 -0800 (PST) Subject: PyObject_CallObject code dump after calling 4 times References: Message-ID: <938001bf-33d2-4071-9b08-f7bb041505b1@s19g2000prg.googlegroups.com> On Jan 3, 8:02?pm, Phil Thompson wrote: > On Thursday 03 January 2008, grbgooglefan wrote: > > > I have a following C++ code which uses PyObject_CallObject to evaluate > > expressions dynamically. This code sets the input parameters for the > > function also dynamically. After calling this function 4 times (with > > these shown values), PyObject_CallObject ?causes application to crash > > in frame_dealloc. > > 1) Can some one please help me understand why is this crash happening > > in frame_dealloc & how to solve it? > > 2) Is there anything wrong I am doing about incrementing or > > decrementing the reference counts of the object passed to > > PyObject_CallObject? > > Yes. > > > > > > > 3) Is it because of the big value (2299265.500000) I am trying to > > convert from double to float using PyFloat_FromDouble? > > > //========================= code reduced for readability > > =============== > > switch(ndtyp){ > > ? ? ?case(INT_T): > > ? ? ? ? ?{ > > ? ? ? ? ?printf("PyInt_FromLong val %d, var %s > > \n",inputVar.nionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > ? ? ? ? ?val = PyInt_FromLong(inputVar.nionum); > > ? ? ? ? ?break; > > ? ? ? ? ?} > > ? ? ? case(LONG_T): > > ? ? ? ? ?{ > > ? ? ? ? ?printf("PyLong_FromLong val %ld, var %s > > \n",inputVar.lionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > ? ? ? ? ?val = PyLong_FromLong(inputVar.lionum); > > ? ? ? ? ?break; > > ? ? ? ? ?} > > ? ? ? case(FLOAT_T): > > ? ? ? ? ?{ > > ? ? ? ? ?printf("PyFloat_FromDouble val %f, var %s > > \n",inputVar.fionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > ? ? ? ? ?val = PyFloat_FromDouble(inputVar.fionum); > > ? ? ? ? ?break; > > ? ? ? ? ?} > > ? ? ? case(DOUBLE_T): > > ? ? ? ? ?{ > > ? ? ? ? ?printf("PyFloat_FromDouble val %f, var %s > > \n",inputVar.dionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > ? ? ? ? ?val = PyFloat_FromDouble(inputVar.dionum); > > ? ? ? ? ?break; > > ? ? ? ? ?} > > ? ? ? ?case(STRING_T): > > ? ? ? ? ?{ > > ? ? ? ? ?printf("PyString_FromString val %s, var %s > > \n",inputVar.ioString,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > ? ? ? ? ?val = PyString_FromString(inputVar.ioString); > > ? ? ? ? ?break; > > ? ? ? ? ?} > > ? ? ? ?default: > > ? ? ? ? ?printf("Unknown data type [%d] for %s\n",ndtyp,pEvalFunc- > > > >pExprVarsArray[nCtr].szVarName); > > > } > > if(!val){ > > ? ?ret = -1; > > ? ?printf("Failed to convert %d %s to PyObject\n",ndtyp,pEvalFunc- > > > >pExprVarsArray[nCtr].szVarName); fflush(stdout); > > > ? ?Py_XDECREF(pTuple); > > ? ?break; > > } > > ? PyTuple_SetItem(pTuple, nCtr, val); > > ? Py_XDECREF(val); > > Don't do this - PyTuple_SetItem() steals a reference to val. > > > } > > // all variables are set, call Python function > > Py_XINCREF(pTuple); > > Why do this? > > > ? PyObject *pResult = PyObject_CallObject(pEvalFunc- > > > >pPyEvalFunction,pTuple); > > > Py_XDECREF(pTuple); > > Why do this? > > > if(PyErr_Occurred()){ > > ?PyErr_Print(); > > } else { > > ? ? ? char* plevel = NULL; > > ? ? ? if(NULL != (plevel = PyString_AsString(pResult))){ > > ? ? ? ? ret = 0; > > ? ? ? ? sprintf(szEvalResult,"%s",plevel); > > ? ? ? } > > } > > Py_XDECREF(pResult); > > pTuple will now have the same number of references as when you started the > above code, so you may want to Py_DECREF() it. > > Phil- Hide quoted text - > > - Show quoted text - Thanks for all the responses. These help me. I could simulate this crash in my small test program & I think (I could be wrong also) it is because of extraneous Py_XDECREF of "PyObject *val" which I am using to convert variables to tuple. When I change the code to simple do like this, it works fine. PyTuple_SetItem(pytuple,0,PyLong_FromLong(size)); PyTuple_SetItem(pytuple,1,PyLong_FromLong(maxvol)); PyTuple_SetItem(pytuple,2,PyFloat_FromDouble(adv)); From DustanGroups at gmail.com Mon Jan 7 15:25:37 2008 From: DustanGroups at gmail.com (Dustan) Date: Mon, 7 Jan 2008 12:25:37 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: On Jan 7, 11:40 am, Martin Marcher wrote: > it's pythonicness. "it is pythonicness"??? From alex.holkner at gmail.com Thu Jan 17 08:42:20 2008 From: alex.holkner at gmail.com (Alex Holkner) Date: Fri, 18 Jan 2008 00:42:20 +1100 Subject: ANN: pyglet 1.0 Message-ID: The first stable/production version of pyglet has been released. http://www.pyglet.org --- pyglet provides an object-oriented programming interface for developing games and other visually-rich applications for Windows, Mac OS X and Linux. Some of the features of pyglet are: * No external dependencies or installation requirements. For most application and game requirements, pyglet needs nothing else besides Python, simplifying distribution and installation. * Take advantage of multiple windows and multi-monitor desktops. pyglet allows you to use as many windows as you need, and is fully aware of multi-monitor setups for use with fullscreen games. * Load images, sound, music and video in almost any format. pyglet can optionally use AVbin to play back audio formats such as MP3, OGG/Vorbis and WMA, and video formats such as DivX, MPEG-2, H.264, WMV and Xvid. pyglet is provided under the BSD open-source license, allowing you to use it for both commercial and other open-source projects with very little restriction. Cheers Alex. From mail at timgolden.me.uk Tue Jan 15 05:55:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jan 2008 10:55:03 +0000 Subject: common problem - elegant solution sought In-Reply-To: <5v3gg1F1kkla5U1@mid.dfncis.de> References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <478C9107.9050406@timgolden.me.uk> Helmut Jarausch wrote: > I'm looking for an elegant solution of the following tiny but common problem. > > I have a list of tuples (Unique_ID,Date) both of which are strings. > I want to delete the tuple (element) with a given Unique_ID, but > I don't known the corresponding Date. > > My straight forward solution is a bit lengthy, e.g. > > L=[("a","070501"),("b","080115"),("c","071231")] > pos=-1 > found=-1 > for (Key,Date) in L : > pos+= 1 > if Key == "b" : > found= pos > break > > if found >= 0 : > del L[found] > > print L > > Most probably there are much more elegant solutions. > Unfortunately, the index-list-method doesn't take an > additional function argument for the comparisons. Probably the most common solution to this in Python is to produce a second list which has all the items in the first except for the one(s) you wish to delete: L=[("a","070501"),("b","080115"),("c","071231")] L2 = [(uniqid, date) for (uniqid, date) in L if not uniqid == 'b'] It might look a little wasteful, but since Python lists are supremely fast and since the tuples themselves aren't copied, only their references, the result is probably what you need. Obviously you've given us a toy example, which is fine for demonstrating the problem. Suggestions might vary if, for example, your data set were much bigger or if the tuples were more complex. TJG From google at mrabarnett.plus.com Thu Jan 10 15:52:21 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 10 Jan 2008 12:52:21 -0800 (PST) Subject: Embedding python code into text document question. References: Message-ID: On Jan 10, 1:10 pm, Thomas Troeger wrote: > Dear all, > > I've written a program that parses a string or file for embedded python > commands, executes them and fills in the returned value. The input might > look like this: > > process id: $$return os.getpid()$$ > current date: $$return time.ctime()$$ > superuser: $$ > if os.geteuid(): > return "Yes" > else: > return "No"$$ > > I've tried several solutions using eval, execfile or compile, but none > of those would solve my problem. Does anyone have a solution that works? > Any suggestions? Any help will be appreciated :) > You could wrap the bits of code in a def statement and then exec it: >>> print field return os.getpid() >>> exec("def field_func():\n" + "".join(" %s\n" % line for line in field.splitlines())) >>> print field_func() 3904 From peixu.zhu at gmail.com Sun Jan 20 23:02:23 2008 From: peixu.zhu at gmail.com (Bonjour) Date: Sun, 20 Jan 2008 20:02:23 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: <761690ad-0e00-42b4-a902-32bbb50fc074@v67g2000hse.googlegroups.com> 'NaN' means "Not a number". according to Python semantics, if you try to compare it with any other float numbers, it should return FALSE. just like >>> >>>1.0 > 'abc' False >>> Since it always return FALSE, it is not a surprise for your question. If you wish to get infinitive number, you'd use 'inf' or '-inf', from IEEE 754 semantics: >>>a=float(6) >>>b=float('inf') >>>c=float('-inf') Albert Hopkins wrote: > This issue may have been referred to in > news: but I didn't > entirely understand the explanation. Basically I have this: > > >>> a = float(6) > >>> b = float('nan') > >>> min(a, b) > 6.0 > >>> min(b, a) > nan > >>> max(a, b) > 6.0 > >>> max(b, a) > nan > > Before I did not know what to expect, but I certainly didn't expect > this. So my question is what is the min/max of a number and NaN or is it > not defined (for which I would have expected either an exception to be > raised or NaN returned in each case). > > As a corrollary would I be able to rely on the above behavior or is it > subject to change (to fix a bug in min/max perhaps :-)? From gagsl-py2 at yahoo.com.ar Wed Jan 23 18:14:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 21:14:07 -0200 Subject: Can someone explain this unexpected raw_input behavior? References: Message-ID: En Wed, 23 Jan 2008 18:27:56 -0200, Mike Kent escribi?: > It's often useful for debugging to print something to stderr, and to > route the error output to a file using '2>filename' on the command > line. > > However, when I try that with a python script, all prompt output from > raw_input goes to stderr. Consider the following test program: > [...] > This indicates to me that the prompt output of raw_input is being sent > to stderr. I did check the source code for raw_input, and it appears > to be sending it to stdout as expected. Surely you've seen that in bltinmodule.c, builtin_raw_input calls PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout), prompt); where fin and fout are sys.stdin and sys.stdout respectively. That function is defined in Parser/myreadline.c, and eventually calls PyOS_StdioReadline with the same arguments. But PyOS_StdioReadline doesn't use its sys_stdout parameter to output the prompt; instead, it always uses stderr, no matter what arguments it receives. Looking at the svn history, PyOS_StdioReadline always has used stderr; got its current signature in rev 29400 (2002). Perhaps that behavior is based on the reverse of your use case, which may be more common. A script writes most of its output to stdout, and you capture that using >filename. If raw_input prompted the user using stdout, that would not be visible in this case, so using stderr is more useful. -- Gabriel Genellina From mark.e.tolonen at mailinator.com Wed Jan 16 21:42:55 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Wed, 16 Jan 2008 18:42:55 -0800 Subject: handlers.SocketHandler and exceptions References: <02de2e9c-331d-45c0-afaa-578ddad55664@j78g2000hsd.googlegroups.com> Message-ID: "writeson" wrote in message news:02de2e9c-331d-45c0-afaa-578ddad55664 at j78g2000hsd.googlegroups.com... > Hi all, > > On our Linux systems at work I've written a Twisted logging server > that receives log messages from multiple servers/processes to post > them to a log file, essentially serializing all the process log > messages. This works well, that is until I tried this test code: > > try: > t = 10 / 0 > except Exception, e: > log.exception("divide by zero") > > where log is the logger instance retreived from a call to getLogger(). > The problem is the handlers.SocketHandler tries to cPickle.dump() the > log record, which in this case contains an exc_info tuple, the last > item of which is a Traceback object. The pickling fails with an > "unpickleable error" and that's that. > > Does anyone have any ideas how to handle this situation? I'd hate to > have to give up using the log.exception(...) call as it's useful to > get strack trace information in the log file. > > Thanks in advance, > Doug Farrell Check out the traceback module. It can translate the traceback into a variety of formats (such as a string) that can be pickled. --Mark From agnel.joel at gmail.com Fri Jan 11 23:38:45 2008 From: agnel.joel at gmail.com (Joel) Date: Fri, 11 Jan 2008 20:38:45 -0800 (PST) Subject: Boa constructor References: Message-ID: On Jan 12, 9:37?am, Joel wrote: > Hi, > In BOA constructor, is there any way to do the following: > Once a breakpoint has reached, I want to enter some code > and execute it. > Can anyone tell me of a technique? > > Also input stream doesn't seem to work, I do a standard input read and > then i enter something in the input window, but it isn't accepted. > What could be the reason? > > Thanks > Joel I wanted to clarify, when I say "enter code", I mean I want to enter some custom code, like print a or something to see the condition of variable 'a' at the breakpoint. From python.list at tim.thechases.com Mon Jan 7 15:47:22 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 07 Jan 2008 14:47:22 -0600 Subject: any() and all() shorthand In-Reply-To: <94640f15-6dde-4ef1-a737-5ee248ae32eb@j20g2000hsi.googlegroups.com> References: <2e589a86-02cf-4903-98aa-c28be2b0b48f@1g2000hsl.googlegroups.com> <94640f15-6dde-4ef1-a737-5ee248ae32eb@j20g2000hsi.googlegroups.com> Message-ID: <47828FDA.7050705@tim.thechases.com> > The idea is a shorthand for reduce. Here, _next_ meant the next item > in the iterable c. You mean like one of these: def lookahead(iterator): i = iter(iterator) x = i.next() for item in i: yield x, item x = item def lookahead2(iterator, **kwarg): i = iter(iterator) if 'initial' in kwarg: x = kwarg['initial'] else: x = i.next() for item in i: yield x, item x = item if 'last' in kwarg: yield x, kwarg['last'] print 'lookahead()' for this, next in lookahead([1,2,3,4,5]): print this, next print 'lookahead2()' for this, next in lookahead2([1,2,3,4,5]): print this, next print 'lookahead2(initial=42)' for this, next in lookahead2([1,2,3,4,5], initial=42): print this, next print 'lookahead2(last=42)' for this, next in lookahead2([1,2,3,4,5], last=42): print this, next print 'lookahead2(initial=3.14159, last=42)' for this, next in lookahead2([1,2,3,4,5], initial=3.14159, last=42): print this, next There are some alternate behaviors that can happen at the end points, so depending on which behavior you want, the lookahead() is cleanest, but doesn't allow you to handle edge cases. The lookahead2() is a little more complex, but allows you to specify a first item for pairing (so "next" touches every item in your list) or a trailing element (so "this" touches every item). -tkc From paddy3118 at googlemail.com Fri Jan 18 09:41:40 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 18 Jan 2008 06:41:40 -0800 (PST) Subject: array and list References: <24f854eb-93a8-414d-a518-842bb2d185fb@s13g2000prd.googlegroups.com> <010888f2-7755-4ec1-9f56-be8a43097a1f@i12g2000prf.googlegroups.com> Message-ID: > Paddy: > > > I guess 'under the hood' Python (& Perl?), arrays might be more like > > an implementation of what the C programmer might call a linked list, > > but even then there are differences as most linked list examples > > given in C tutorials are lists of the same type of object,.... > > Both Python "array.array" and "list" are implemented as dyn arrays, > not as lists. Only the good "deque" by Hettinger is something similar > to a list (of small arrays). > > Bye, > bearophile Ta! From nick at craig-wood.com Wed Jan 9 07:30:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 09 Jan 2008 06:30:05 -0600 Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <87ejcri96v.fsf@mulj.homelinux.net> <87abnfi84i.fsf@mulj.homelinux.net> <5ujp20F1ehvg2U2@mid.dfncis.de> Message-ID: Robert Latest wrote: > Hrvoje Niksic wrote: > > > keywords[:] = (s for s in keywords if s) > > Looks good but is so far beyond my own comprehension that I don't dare > include it in my code ;-) :-) Worth understanding thought I think - here are some hints keywords[:] = (s for s in keywords if s) is equivalent to this (but without creating a temporary list) keywords[:] = list(s for s in keywords if s) which is equivalent to keywords[:] = [s for s in keywords if s] This keywords[:] = .... Replaces the contents of the keywords list rather than making a new list. Here is a demonstration of the fundamental difference >>> a=[1,2,3,4] >>> b=a >>> a=[5,6,7] >>> print a, b [5, 6, 7] [1, 2, 3, 4] >>> a=[1,2,3,4] >>> b=a >>> a[:]=[5,6,7] >>> print a, b [5, 6, 7] [5, 6, 7] Using keywords[:] stops the creation of another temporary list. The other behaviour may or may not be what you want! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From tarundevnani at gmail.com Mon Jan 28 02:39:49 2008 From: tarundevnani at gmail.com (tarun) Date: Mon, 28 Jan 2008 13:09:49 +0530 Subject: [wxPython-users] Issue with docking wx.listctrl window In-Reply-To: <479A145C.40802@alldunn.com> References: <4798D1B1.7020908@alldunn.com> <479A145C.40802@alldunn.com> Message-ID: Thanks Robin. Can you please elobrate more on this. Regards, Tarun Devnani On Jan 25, 2008 10:24 PM, Robin Dunn wrote: > tarun wrote: > > Thanks a lot Robin. > > > > I tried using self.log and instead of self.log.list. *Code is attached.* > > But this gives me a panel and listctrl in it. The extra blank space > > around the listctrl in window1 is something that I don't need. > > Use a sizer to manage the layout of the listctrl. > > -- > Robin Dunn > Software Craftsman > http://wxPython.org Java give you jitters? Relax > with wxPython! > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Sun Jan 27 05:39:17 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jan 2008 10:39:17 GMT Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <5vr1ekF1njt09U2@mid.uni-berlin.de> <84f39f37-4d18-47c1-9349-bf3f471b2bf5@s19g2000prg.googlegroups.com> Message-ID: <6035alF1oh17aU3@mid.uni-berlin.de> On Sun, 27 Jan 2008 02:18:48 -0800, glacier wrote: > Yepp. I feed SAX with the unicode string since SAX didn't support my > encoding system(GBK). If the `decode()` method supports it, IMHO SAX should too. > Is there any way to solve this better? > I mean if I shouldn't convert the GBK string to unicode string, what > should I do to make SAX work? Decode it and then encode it to utf-8 before feeding it to the parser. Ciao, Marc 'BlackJack' Rintsch From casey at rodarmor.com Thu Jan 17 03:48:35 2008 From: casey at rodarmor.com (Casey Rodarmor) Date: Thu, 17 Jan 2008 00:48:35 -0800 Subject: Replace stop words (remove words from a string) In-Reply-To: <01be01c858e4$c6b8b280$542a1780$@com> References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> <01be01c858e4$c6b8b280$542a1780$@com> Message-ID: That's much better than what I was about to post: for s in stoplist: string.join(mystr.split(s, "")) Berlin: Why are you keen on avoiding split()? On 1/17/08, Karthik wrote: > > How about - > > for s in stoplist: > string.replace(mystr, s, "") > > Hope this should work. > > -----Original Message----- > From: python-list-bounces+karthik3186=gmail.com at python.org > [mailto:python-list-bounces+karthik3186=gmail.com at python.org] On Behalf Of > BerlinBrown > Sent: Thursday, January 17, 2008 1:55 PM > To: python-list at python.org > Subject: Replace stop words (remove words from a string) > > if I have an array of "stop" words, and I want to replace those values > with something else; in a string, how would I go about doing this. I > have this code that splits the string and then does a difference but I > think there is an easier approach: > > E.g. > > mystr = > > kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsldf > sd; > > if I have an array stop_list = [ "[BAD]", "[BAD2]" ] > > I want to replace the values in that list with a zero length string. > > I had this before, but I don't want to use this approach; I don't want > to use the split. > > line_list = line.lower().split() > res = list(set(keywords_list).difference(set(ENTITY_IGNORE_LIST))) > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajaksu at gmail.com Fri Jan 25 20:44:07 2008 From: ajaksu at gmail.com (ajaksu) Date: Fri, 25 Jan 2008 17:44:07 -0800 (PST) Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> On Jan 25, 11:36 pm, ajaksu wrote: > On Jan 25, 11:10 pm, o... at thepond.com wrote: [...] Gaah, is this what's going on? ajaksu at Belkar:~$ cat error.txt This is not assembler... ajaksu at Belkar:~$ ndisasm error.txt 00000000 54 push sp 00000001 686973 push word 0x7369 00000004 206973 and [bx+di+0x73],ch 00000007 206E6F and [bp+0x6f],ch 0000000A 7420 jz 0x2c 0000000C 61 popa 0000000D 7373 jnc 0x82 0000000F 656D gs insw 00000011 626C65 bound bp,[si+0x65] 00000014 722E jc 0x44 00000016 2E db 0x2E 00000017 2E db 0x2E 00000018 0A db 0x0A :/ From duncan.booth at invalid.invalid Mon Jan 21 14:36:29 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jan 2008 19:36:29 GMT Subject: problem with 'global' References: <5vk9fqF1n19plU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 21 Jan 2008 17:08:46 -0200, Gabriel Genellina wrote: > >> The future statement is another example, even worse: >> >> if 0: >> from __future__ import with_statement >> >> with open("xxx") as f: >> print f > > In Python >=2.5 it's a compile time error if that import is not the very > first statement in a source file. > That doesn't appear to be the case. With Python 2.5.1 the example Gabriel quoted will compile and run. From sunilkrghai at gmail.com Tue Jan 1 08:40:03 2008 From: sunilkrghai at gmail.com (Sunil Ghai) Date: Tue, 1 Jan 2008 19:10:03 +0530 Subject: Network Module Message-ID: <52da23100801010540s122337aci470e2ee4fa85fa1b@mail.gmail.com> Hello people, I am searching for a python module to interact with the network connections/interfaces. For example the number of active TCP/IP connections via eth0 interface and all that stuff. I have done googling and search at pythonorg but couldn't find any. Thanks Sunil Kumar Ghai -------------- next part -------------- An HTML attachment was scrubbed... URL: From BjornSteinarFjeldPettersen at gmail.com Sun Jan 13 10:01:49 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 13 Jan 2008 07:01:49 -0800 (PST) Subject: How to get user home directory on Windows References: <0bb27916-5416-47b2-b58c-1eb82ccb6d3e@k2g2000hse.googlegroups.com> Message-ID: On Jan 12, 6:50 pm, "Giampaolo Rodola'" wrote: > Update. > I found a way for getting the home directory of the user but it > requires to validate the user by providing username+password: > > def get_homedir(username, password): > token = win32security.LogonUser( > username, > None, > password, > win32security.LOGON32_LOGON_NETWORK, > win32security.LOGON32_PROVIDER_DEFAULT > ) > return win32profile.GetUserProfileDirectory(token) > > What I'd like to do is avoiding the requirement of the password, the > same way as if I would on UNIX where it would be enough just using the > pwd module: > > >>> import pwd > >>> pwd.getpwnam('user').pw_dir > '/home/user' Check out http://msdn2.microsoft.com/en-us/library/bb762181(VS.85).aspx for some of the complexities of special directories on Windows. If you give more details on what you need to get done, someone might come up with a better solution (my instinct tells me this might be a database problem, but then I'm a database person so that might not be terribly relevant ;-) -- bjorn From tonylabarbara at aol.com Fri Jan 25 11:12:27 2008 From: tonylabarbara at aol.com (tonylabarbara at aol.com) Date: Fri, 25 Jan 2008 11:12:27 -0500 Subject: Automatically Writing a Dictionary In-Reply-To: <47979785.502@tim.thechases.com> References: <8CA2C0BF25FCAA6-1374-117B@WEBMAIL-DC15.sysops.aol.com> <47979785.502@tim.thechases.com> Message-ID: <8CA2D8436C5B761-E80-5C4@FWM-D40.sysops.aol.com> d = {}? ? for line in input:? ? key, value = line.split(',').rstrip('\n')? ? d[key] = value? Thanks. That worked except for the rstrip. So I did this: for line in input: ? line = string.rstrip(line, '\n') ? key, value = line.split(',') ? dictionary[key] = value Thanks again, Tony -----Original Message----- From: Tim Chase To: tonylabarbara at aol.com Cc: python-list at python.org Sent: Wed, 23 Jan 2008 3:37 pm Subject: Re: Automatically Writing a Dictionary > input = "/usr/local/machine-lang-trans/dictionary.txt"? > > input = open(input,'r')? > > dict = "{"? > for line in input:? > ? tup = re.split(','line)? > ? dict += '"' + tup[0] +'":"' + tup[1] +'", '? > dict += "}"? > input.close()? > > > Of course, that will just give me a string. How do I convert? > it to, or make from scratch, a dictionary of that?? ? Don't bother with the string (and as a side-note, it's bad style to mask the built-in dict() so I'll use "d"):? ? ? d = {}? ? for line in input:? ? key, value = line.split(',').rstrip('\n')? ? d[key] = value? ? or even just? ? ? d = dict(line.split(',').rstrip('\n')? ? for line in input)? ? using the aforementioned dict() function :-)? ? You may want to clean it up a bit in case there are spurious leading/trailing spaces to be trimmed:? ? ? from string import strip? ? d = dict(map(strip, line.split(','))? ? for line in input)? ? or even ignore lines with the wrong number of commas:? ? ? d = dict(map(strip, line.split(','))? ? for line in input? ? if line.count(',') == 1)? ? or assume any extra commas are part of the value:? ? ? d = dict(map(strip, line.split(',',1))? ? for line in input? ? if line.count(',') > 0)? ? HTH,? ? -tkc? ? ? ________________________________________________________________________ More new features than ever. Check out the new AOL Mail ! - http://webmail.aol.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From peixu.zhu at gmail.com Sun Jan 20 23:12:19 2008 From: peixu.zhu at gmail.com (Bonjour) Date: Sun, 20 Jan 2008 20:12:19 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: <73891c67-4726-44b0-a815-9620279fb0f0@c4g2000hsg.googlegroups.com> 'NaN' means "Not a number". according to Python semantics, if you try to compare it with any other float numbers, it should return FALSE. just like: >>>1.0 > 'abc' False Since it always return FALSE, it is not a surprise for your question. If you wish to get infinitive number, you'd use 'inf' for positive infinitive or '-inf' for negative infinitive, from IEEE 754 semantics, just like: >>>a=float(6) >>>b=float('inf') >>>c=float('-inf') For more information, PEP-0754 may be helpful. From cp02sdh02 at sneakemail.com Tue Jan 8 12:22:45 2008 From: cp02sdh02 at sneakemail.com (C Martin) Date: 8 Jan 2008 17:22:45 -0000 Subject: Tkinter variable trace problem Message-ID: <16157-56584@sneakemail.com> Thank you for your replies. I understand there are better ways to handle 'normal' UI behavior, but I was curious about the trace feature and wanted to understand how it worked. I may not actually need it in my project, but I wanted to see what my options were. Thanks again. -------------------------------------- Protect yourself from spam, use http://sneakemail.com From fredrik at pythonware.com Wed Jan 9 17:41:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 23:41:17 +0100 Subject: for loop without variable In-Reply-To: References: Message-ID: erik gartz wrote: > Hi. I'd like to be able to write a loop such as: > for i in range(10): > pass > but without the i variable. The reason for this is I'm using pylint > and it complains about the unused variable i. if a computer tells you to do something stupid, it's often better to find a way to tell the computer to shut up than to actually do some- thing stupid. (pylint's online documentation is remarkably unreadable, so I cannot help you with the details, but surely there's a way to disable that test, either globally, or for a specific region of code?). From sjmachin at lexicon.net Wed Jan 2 06:28:38 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 2 Jan 2008 03:28:38 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> Message-ID: <4af890f4-acbc-467c-995d-0593b0ef08ee@e6g2000prf.googlegroups.com> On Jan 2, 9:57 pm, mario wrote: > On Jan 2, 10:44 am, John Machin wrote: > > > > > Two things for you to do: > > > (1) Try these at the Python interactive prompt: > > > unicode('', 'latin1') > > unicode('', 'mbcs') > > unicode('', 'raboof') > > unicode('abc', 'latin1') > > unicode('abc', 'mbcs') > > unicode('abc', 'raboof') > > $ python > Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> unicode('', 'mbcs') > u'' > >>> unicode('abc', 'mbcs') > > Traceback (most recent call last): > File "", line 1, in > LookupError: unknown encoding: mbcs > > > > Hmmn, strange. Same behaviour for "raboof". > > > (2) Read what the manual (Library Reference -> codecs module -> > > standard encodings) has to say about mbcs. > > Page athttp://docs.python.org/lib/standard-encodings.htmlsays that > mbcs "purpose": > Windows only: Encode operand according to the ANSI codepage (CP_ACP) > > Do not know what the implications of encoding according to "ANSI > codepage (CP_ACP)" are. Neither do I. YAGNI (especially on darwin) so don't lose any sleep over it. > Windows only seems clear, but why does it only > complain when decoding a non-empty string (or when encoding the empty > unicode string) ? My presumption: because it doesn't need a codec to decode '' into u''; no failed codec look-up, so no complaint. Any realistic app will try to decode a non-empty string sooner or later. From bg_ie at yahoo.com Fri Jan 25 05:26:35 2008 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Fri, 25 Jan 2008 02:26:35 -0800 (PST) Subject: The dimensions of a tuple Message-ID: Hi, I wish to pass an argument to a function which will inset rows in a db. I wish to have the follow possibilities - ("one","two") (("one","two"),("three","four")) The first possibility would mean that one row is added with "one and "two" being its column values. The second possibility means that two rows are added. So to do this I need to establish the dimension of the duple. Is it a one dimentional or two dimentional. How do I do this? Thanks, Barry. From carsten at uniqsys.com Fri Jan 4 09:32:27 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 04 Jan 2008 09:32:27 -0500 Subject: Cursors in a Loop In-Reply-To: References: <3da337d8-2de0-4fdb-8c38-2f6fcd8348ac@i72g2000hsd.googlegroups.com> Message-ID: <1199457147.3453.5.camel@dot.uniqsys.com> On Fri, 2008-01-04 at 00:03 -0800, Chris wrote: > You should bind all variables to save the pool. > > cursor = connection.cursor() > cursor.executemany("""insert into as_siebel_hosts_temp > values (:whole, :lot, :of, :bind, :variables) > """ > ,[(i,)[0] for i in hostlist] > ) > connection.commit() > connection.close() Huh? In the OP's example, the table one has one column. I'll openly admit that I don't know anything about Oracle, but that code doesn't make sense to me. Maybe you're trying to execute a multi-row insert, but that would be done with execute(), not executemany(), wouldn't it? Also, isn't "[(i,)[0] for i in hostlist]" exactly the same as "[i for i in hostlist]" which in turn is exactly the same as "hostlist"? -- Carsten Haese http://informixdb.sourceforge.net From bearophileHUGS at lycos.com Sat Jan 26 04:51:51 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 26 Jan 2008 01:51:51 -0800 (PST) Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> Message-ID: <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> > Henry Baxter wrote: > > def maxi(l): > > m = max(l) > > for i, v in enumerate(l): > > if m == v: > > return i > > What's about l.index(max(l)) ? The version I use: def posmax(seq, key=None): """Return the position of the first maximum item of a sequence. It accepts the usual key parameter too.""" if key: return max(enumerate(seq), key=lambda k: key(k[1]))[0] else: return max(enumerate(seq), key=itemgetter(1))[0] Bye, bearophile From berlin.brown at gmail.com Mon Jan 14 17:15:38 2008 From: berlin.brown at gmail.com (BerlinBrown) Date: Mon, 14 Jan 2008 14:15:38 -0800 (PST) Subject: Append zip files together, just get the binary data (in memory) Message-ID: <53f66038-ccc3-4c3d-97b2-fa5deb148809@d4g2000prg.googlegroups.com> Is it possible to just build the binary content of a zip file. I want to create the content in memory (e.g. return binary data) and then get those byte strings representing the zip file? Is that possible? Or could I possibly override functions in the zip class. 1. Create a zip file object (e.g. dont actually create the file). 2. Append stuff to the zip file (e.g. a file) 3. Zip that content into memory (but still not touching the filesystem) 4. Extract those byte strings for (an array?) later use. My goal is to concatenate multiple zip files into another binary file. From bazwal at googlemail.com Mon Jan 7 13:30:04 2008 From: bazwal at googlemail.com (Baz Walter) Date: Mon, 7 Jan 2008 18:30:04 +0000 (UTC) Subject: Does Python cache the startup module? Message-ID: Hello I remember reading somewhere (probably this list) that python may cache the module that starts a program (e.g. 'main.py'). I'm asking because I have found that this can sometimes cause problems when making small edits to the module. For instance, in my current module I changed the name of the main gui widget. When I ran the program, the program started to leak memory like a sieve. I then changed the name back again, and the problem went away. This looks very much like some sort of weird caching behaviour to me. I've tried deleting the .pyc file and even re-booting, but I can't make the problem go away! Can anyone confirm that this caching happens? And if so, is it documented anywhere? TIA From f.guerrieri at gmail.com Fri Jan 11 12:29:33 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Fri, 11 Jan 2008 18:29:33 +0100 Subject: Analyzing Python GC output - what is a "cell", and what information is available about it. In-Reply-To: <4787a42e$0$36403$742ec2ed@news.sonic.net> References: <478707f2$0$36360$742ec2ed@news.sonic.net> <4787a42e$0$36403$742ec2ed@news.sonic.net> Message-ID: <79b79e730801110929w35169d0fhd4ed9785f7ea7c36@mail.gmail.com> On Jan 11, 2008 6:20 PM, John Nagle wrote: > Tried: > print item.dir() > got: > 'cell' object has no attribute 'dir' I don't know nothing about cell objects... but why don't you try dir(item) instead? Francesco From devraj at gmail.com Tue Jan 29 01:18:58 2008 From: devraj at gmail.com (Devraj) Date: Mon, 28 Jan 2008 22:18:58 -0800 (PST) Subject: Where do glade files go? Message-ID: <384ee7e6-3776-4ed1-a947-db1c3067023c@i3g2000hsf.googlegroups.com> Hi everyone, I am writing an application using Python/GTK/Hildon/Glade. I will be creating a debian package as the final distribution mechanism for the package. What would be the ideal place to put glade files that my application uses on the target system? Thanks. From rbianchi at physik.uni-freiburg.de Thu Jan 10 09:24:37 2008 From: rbianchi at physik.uni-freiburg.de (Riccardo Maria Bianchi) Date: Thu, 10 Jan 2008 15:24:37 +0100 Subject: run shell commands Message-ID: Hello! :) I'm trying to run shell commands both with os.system() and subprocess.Popen() class. But I can't run aliases or function defined in my .bashrc file, like in the login interactive shell. Can you help me? Maybe have I to add some commands to load the .bashrc? Thanks a lot! :) Ric. From Thomas.Ploch at gmx.net Mon Jan 28 14:47:25 2008 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Mon, 28 Jan 2008 20:47:25 +0100 Subject: [Q] Is there a way to minimize a Tkinter application to the system tray? Message-ID: <10253dff3d5784edf50d5d2ac78662c9@gmx.net> Hello folks, I already found some answers on the net, which said that the Tk library that Tkinter wraps does not offer functionality to minimize an application to the system tray. But I hope there are some wizards in here that might tell me that how it (possibly) could be done. Thomas From stanc at al.com.au Mon Jan 14 00:45:00 2008 From: stanc at al.com.au (Astan Chee) Date: Mon, 14 Jan 2008 16:45:00 +1100 Subject: (bit)torrent source code help Message-ID: <478AF6DC.8040600@al.com.au> Hi, Im using windows XP and I was wondering if anyone had any experience in compiling (using py2exe) the official bittorrent client ( http://download.bittorrent.com/dl/BitTorrent-5.2.0.tar.gz ) or any bittorrent client open source and written in python. I ask since I am trying to make several of my own modification to the protocol but the official open source client keeps on giving me missing modules (I have all the required modules and components and it keeps on failing due to platform-based errors) when I try to create an executable of it using py2exe. Can anyone either suggest another source code for a torrent client or any torrent client in python that compiles nicely with py2exe in windows? Thanks Astan From stefan.behnel-n05pAM at web.de Mon Jan 7 16:07:32 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 07 Jan 2008 22:07:32 +0100 Subject: Python's great, in a word In-Reply-To: References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <08f0c528-0619-432a-80a1-569cd9183e09@s12g2000prg.googlegroups.com> Message-ID: <47829494.2010000@web.de> Henry Chang wrote: > On Jan 7, 2008 5:41 AM, alain wrote: >> Paraphrasing Steve Jobs but in this context: >> PYTHON = a bycycle for the mind > What exactly does it mean "a bycycle for the mind"?? Ask the Dutch guy near you. Stefan From MartinRinehart at gmail.com Wed Jan 9 08:02:24 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 9 Jan 2008 05:02:24 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <5cf4c5bb-01b1-4ece-a09a-24c4491764b1@f47g2000hsd.googlegroups.com> Message-ID: <7486a4ff-e801-4036-86d3-2ad0aaf542df@v29g2000hsf.googlegroups.com> Thanks to all for many helpful suggestions. Python, by the way, is verbose when compared to APL. (See http://catpad.net/michael/apl/ if you don't believe this.) You need to stick in an adverb (maybe "gracefully concise") as standalone "concise" is owned by APL. Basilisk96 wrote: > Did programmers stop writing programs on punch cards because they ran > out of punch paper? If you drive on the NYS Thruway, you still get a punch card when you enter. You turn it in when you pay your toll. From pablo at decode.com.ar Fri Jan 11 21:55:47 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Sat, 12 Jan 2008 00:55:47 -0200 Subject: alternating string replace In-Reply-To: <7x7iifsrur.fsf@ruckus.brouhaha.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <7x7iifsrur.fsf@ruckus.brouhaha.com> Message-ID: <47882C33.5010500@decode.com.ar> Paul Rubin wrote: > George Sakkis writes: > >> from itertools import chain, izip, cycle >> print ''.join(chain(*izip(s1.split('_'),cycle(':,'))))[:-1] >> > > from itertools import cycle > a = cycle(':,') > print re.sub('_', lambda x: a.next(), s1) > Lovely. If there OP didn't vanished into thin air*, I'd declare you the winner (although you forgot to import re). This said, I'm still kind of partial to any re-only solution, but it would require someone outlines the behavior in the corner cases. * die, thread! -- Pablo From bignose+hates-spam at benfinney.id.au Wed Jan 23 23:59:35 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 24 Jan 2008 15:59:35 +1100 Subject: Terminology: "script" versus "program" (was: Linux Journal Survey) References: <1666950d-e9a5-4b7c-a614-5bba90e5b4ca@y5g2000hsf.googlegroups.com> Message-ID: <87ir1j7r9k.fsf_-_@benfinney.id.au> George Sakkis writes: > 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. I agree entirely. The term "script" has the strong connotation of a limited-purpose program designed to solve a problem expressed almost entirely as a simple series of steps. Languages that are often used to write such scripts are usually referred to as "scripting languages", which becomes a denigration because such a language need not have support for much else. In contrast, the term "program" (and hence "programming language") implies support for a much broader set of practices and solutions. This term seems quite prevalent among the Python core developers, unfortunately. The 'distutils' module even has the term 'script' used in its interface, to refer to the programs that are to be distributed. -- \ "Money is always to be found when men are to be sent to the | `\ frontiers to be destroyed: when the object is to preserve them, | _o__) it is no longer so." -- Voltaire, _Dictionnaire Philosophique_ | Ben Finney From george.sakkis at gmail.com Fri Jan 11 21:06:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 18:06:48 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: On Jan 9, 6:34 am, Duncan Booth wrote: > cesco wrote: > > Hi, > > > say I have a string like the following: > > s1 = 'hi_cat_bye_dog' > > and I want to replace the even '_' with ':' and the odd '_' with ',' > > so that I get a new string like the following: > > s2 = 'hi:cat,bye:dog' > > Is there a common recipe to accomplish that? I can't come up with any > > solution... > > Here's yet another answer: > > from itertools import islice, cycle > > def interleave(*iterators): > iterators = [ iter(i) for i in iterators ] > while 1: > for i in iterators: > yield i.next() > > def punctuate(s): > parts = s.split('_') > punctuation = islice(cycle(':,'), len(parts)-1) > return ''.join(interleave(parts, punctuation)) > > s1 = 'hi_cat_bye_dog' > print punctuate(s1) > > # Or as a one-liner (once you have interleave): > > print ''.join(list(interleave(s1.split('_'), cycle(':,')))[:-1]) And yet another itertools-addicted one-liner (leaving out the import): from itertools import chain, izip, cycle print ''.join(chain(*izip(s1.split('_'),cycle(':,'))))[:-1] George From bernhard.merkle at googlemail.com Fri Jan 4 07:14:14 2008 From: bernhard.merkle at googlemail.com (Bernhard Merkle) Date: Fri, 4 Jan 2008 04:14:14 -0800 (PST) Subject: pydepend (checking dependencies like jdepend) ? Message-ID: <1969e240-9e80-4df1-b085-7956dfa4f7ae@t1g2000pra.googlegroups.com> Hi there, think %Subject says all. I am wondering if there is some tool to check dependencies within python programs. (something like jdepend for python ;-) Of course the dependencies are at runtime (dynamic) and not statically +dynamically (as in Java), but anyway it would be interesting to know of them (for better modularization e.g.) TIA, Berni. From stefan.behnel-n05pAM at web.de Sat Jan 19 08:34:57 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 19 Jan 2008 14:34:57 +0100 Subject: Excess whitespace in my soup In-Reply-To: References: <48eb8853-91b3-4c43-8014-a0c624e4c6e7@t1g2000pra.googlegroups.com> Message-ID: <4791FC81.5090004@web.de> John Machin wrote: > On Jan 19, 11:00 pm, Fredrik Lundh wrote: >> John Machin wrote: >>> I'm happy enough with reassembling the second item. The problem is in >>> reliably and correctly collapsing the whitespace in each of the above >> > fiveelements. The standard Python idiom of u' '.join(text.split()) >> > won't work because the text is Unicode and u'\xa0' is whitespace >> >>> and would be converted to a space. >> would this (or some variation of it) work? >> >> >>> re.sub("[ \n\r\t]+", " ", u"foo\n frab\xa0farn") >> u'foo frab\xa0farn' >> >> > > Yes, partially. Leading and trailing whitespace has to be removed > entirely, not replaced by one space. Sounds like adding a .strip() to me ... Stefan From ggpolo at gmail.com Thu Jan 10 09:08:34 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 10 Jan 2008 12:08:34 -0200 Subject: New Tk look (aka Ttk or Tile widgets) In-Reply-To: References: Message-ID: 2008/1/10, Robert Hicks : > Do I have to install something extra to use the new look? > > Robert > -- > http://mail.python.org/mailman/listinfo/python-list > Tk 8.5 -- -- Guilherme H. Polo Goncalves From yantao at telus.com Sun Jan 27 10:57:37 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 15:57:37 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: <13pode8n39n8ea8@corp.supernews.com> References: <13po55nc0q0s06@corp.supernews.com> <13pode8n39n8ea8@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13pode8n39n8ea8 at corp.supernews.com... > On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: > >> You didn't understand my question, but thanks any way. >> >> Yes, it is true that %s already support unicode, and I did not >> contradict that. But it counts the number of bytes instead of >> characters, and makes things like %-20s out of alignment. If you don't >> understand my assertion, please don't argue back and I am only >> interested in answers from those who are qualified. > > I understand your assertion. I think it is nonsense. this kind of reply only embarrase yourself > >>>> def test(): > ... print "12345678901234567890 +" > ... print "%-20s +" % "Plain ASCII" > ... print u"%-20s +" % u"Les mis?rables-\320\321\322" > ... >>>> test() > 12345678901234567890 + > Plain ASCII + > Les mis?rables-??? + > > > > > -- > Steven From mutawafayez at yahoo.com Sat Jan 12 11:36:04 2008 From: mutawafayez at yahoo.com (small giant) Date: Sat, 12 Jan 2008 08:36:04 -0800 (PST) Subject: what did the bible say about Mohammad Message-ID: <4123d276-f971-4658-a976-a147825b0d8e@v29g2000hsf.googlegroups.com> According to the Bible, God said to Moses, on whom be peace: I will raise up for them a prophet like you from among their brothers; I will put my words in his mouth, and he will tell them everything I command him. (The Holy Bible, New International Version, Deuteronomy chapter 18, verse 18). The prophet described in the above verse must have the following three characteristics: 1. He will be like Moses. 2. He will come from the brothers of the Israelites, i.e. the Ishmaelites. 3. God will put His words in the mouth of the prophet and he will declare what God commanded him. Let us see which prophet God was speaking of. 1. The prophet like Moses Some people feel that this prophecy refers to the prophet Jesus, on whom be peace. But, although Jesus (peace be upon him and all of God's prophets and messengers) was truly a prophet of God, he is not the prophet spoken of here. He was born miraculously, and finally God raised him up miraculously. On the other hand, Muhammad is more like Moses; both were born in a natural way and both died natural deaths. 2. From among the Ishmaelites Abraham had two sons, Ishmael and Isaac (Genesis, chapter 21). Ishmael became the grandfather of the Arab nation. And Isaac became the grandfather of Jewish nation. The prophet spoken of was to come not from among the Jews themselves, but from among their brothers, the Ishmaelites. Muhammad a descendant of Ishmael, is indeed that prophet. 3. God will put his words in his mouth 'Neither the content of the revelation, nor its form, were of Muhammad's devising. Both were given by the angel, and Muhammad's task was only to repeat what he heard.' (Word Religions from Ancient history to the Present, by Geoffrey Parrinder, p. 472). God sent the angel Gabriel to teach Muhammad the exact words that he should repeat to the people. The words are therefore not his own; they did not come from his own thoughts, but were put into his mouth by the angel. These are written down in the Qur'an word for word, exactly as they came from God. Now that we know that prophet we must listen to him, for, according to the Bible, God says: 'I will punish anyone who refuses to obey him' (Good News Bible, Deut. 18:19). Jesus (on whom be peace) In the Glorious Qur'an The Qur'an tells us many wonderful things about Jesus. As a result, believers in the Qur'an love Jesus, honor him and believe in him. In fact, no Muslim can be a Muslim unless he or she believes in Jesus, on whom be peace. The Qur'an says that Jesus was born of a virgin, that he spoke while he was still only a baby, that he healed the blind and the leper by God's leave and that he raised the dead by God's leave. What then is the significance of these miracles? First, the virgin birth. God demonstrates His power to create in every way. God created everyone we know from a man and a woman. But how about Adam, on whom be peace? God created him from neither a man nor a woman. And Eve from only a man, without a woman. And finally, to complete the picture, God created Jesus from a woman, without a man. What about the other miracles? These were to show that Jesus was not acting on his own behalf, but that he was backed by God. The Qur'an specifies that these miracles were performed by God's leave. This may be compared to the Book of Acts in the Bible, chapter 2, verse 22, where it says that the miracles were done by God to show that he approved of Jesus. Also, note that Jesus himself is recorded in the Gospel of John to have said: 'I can do nothing of my own authority' (5:30). The miracles, therefore, were done not by his own authority, but by God's authority. What did Jesus teach? The Qur'an tells us that Jesus came to teach the same basic message which was taught by previous prophets from God - that we must shun every false god and worship only the One True God. Jesus taught that he is the servant and messenger of the One True God, the God of Abraham. These Qur'anic teachings can be compared with the Bible (Mark 10:18; Matthew 26:39; John 14:28, 17:3, and 20:17) where Jesus teaches that the one he worshipped is the only true God. See also Matthew 12:18; Acts 3:13, and 4:27 where we find that his disciples knew him as 'Servant of God'. The Qur'an tells us that some of the Israelites rejected Jesus, and conspired to kill him, but God rescued Jesus and raised him to Himself. God will cause Jesus to descend again, at which time Jesus will confirm his true teachings and everyone will believe in him as he is and as the Qur'an teaches about him. Jesus is the Messiah. He is a word from God, and a spirit from Him. He is honored in this world and in the hereafter, and he is one of those brought nearest to God. Jesus was a man who spoke the truth which he heard from God. This can be compared with the Gospel According John where Jesus says to the Israelites: 'You are determined to kill me, a man who has told you the truth that I heard from God' (John 8:40). see this site www.sultan.org From inq1ltd at inqvista.com Thu Jan 31 10:43:01 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Thu, 31 Jan 2008 10:43:01 -0500 Subject: Fwd: Re: Problems installing Python on server In-Reply-To: <200801310946.50733.inq1ltd@inqvista.com> References: <200801310946.50733.inq1ltd@inqvista.com> Message-ID: <200801311043.02168.inq1ltd@inqvista.com> On Thursday 31 January 2008 09:46, jim-on-linux wrote: > > > Also be careful and setup all the > > > paths that is required for compiling > > > various Python modules etc. > > > > > > On Jan 29, 8:28 am, Yansky > > > > wrote: > > > > I asked my hosting company if they > > > > would upgrade Python on my server to > > > > the latest version. They responded > > > > with: > > > > > > > > "Sorry no. We tend to stick with > > > > what comes packaged with the unix > > > > distribution to ease maintenance > > > > issues. > > > > > > > > There is nothing stopping you from > > > > running your own version of python > > > > from within your own account. > > > > Download the source and compile it > > > > and install it into your own space. > > > > Adjust the fist line of your python > > > > scripts to reflect the location of > > > > YOUR python binary: > > > > > > > > #! /home/youraccount/yourlibs/python > > > > > > > > and you should be all set." > > > > Go to the ReadME file after you unpack > > python. > > Open and look for "Installing". > > Read the section, it explains how to > > install on the entire system and how to > > install locally. > > "Make altinstall" is what you are > > looking for. > > > > jim-on-linux > > http:\\www.inqvista.com > > > > > > The build instructions for Python > > > > are: To start building right away > > > > (on UNIX): type "./configure" in the > > > > current directory and when it > > > > finishes, type "make". This creates > > > > an executable "./python"; to install > > > > in usr/local, first do "su root" and > > > > then "make install". > > > > > > > > The problem is, I don't have root > > > > access to the server so I can't do > > > > the "make install". I have ubuntu on > > > > my computer, but from what I > > > > understand I can't compile it on > > > > that and upload it because the > > > > server runs Red Had and the > > > > ./configure would have made it > > > > incompatible right? > > > > > > > > So how can I build Python without > > > > root access? > > Will the "make install" make my Python the > default one? If I want to install some > Python modules, will I need to alter > their installation as well or will it see > my Python version as the right one to > install too? > > Cheers. From the Readme file enclose with Python; ------ " If you have a previous installation of Python that you don't want to replace yet, use make altinstall This installs the same set of files as "make install" except it doesn't create the hard link to "python" named "python" and it doesn't install the manual page at all. " ------ I installed python 2.5 using make altinstall by going to " /usr/local/lib " unpacking, then using make altinstall Folder 2.5 is created. To add modules, as I have added PIL to my system, I go to; " /usr/local/lib/python2.5/site-packages " where I installed PIL. installing a py module in the site-packages folder is where I would install any package unless otherwise directed. When upgrading you can go to the site directory and see what's in there, and what has to be added to a new upgrade. http:\\www.inqvista.com jim-on-linux From hniksic at xemacs.org Tue Jan 8 04:59:53 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 08 Jan 2008 10:59:53 +0100 Subject: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> <5ugulaF1hqn2cU1@mid.uni-berlin.de> <5ugv5dF1i0edtU1@mid.dfncis.de> Message-ID: <87fxx8mycm.fsf@mulj.homelinux.net> Robert Latest writes: > If 'slow' or some other program does buffered output, how come I can > see its output line-by-line in the shell? stdio uses different buffering strategies depending on the output type. When the output is a TTY, line buffering is used; when the output goes to a pipe or file, it is fully buffered. > In reality I want to call another program whose behavior I can't > influence (well, technically I could because it's open-source, but > let's assume it to be a black box for now). To test whether your black box buffers output to pipe, simply start it like this: $ ./slow | cat If you see lines one by one, you are in luck, and you can fix things on the Python level simply by avoiding buffering in popen. If not, you will need to resort to more advanced hackery (e.g. fixing stdio using LD_PRELOAD). From washakie at gmail.com Wed Jan 30 09:44:39 2008 From: washakie at gmail.com (washakie) Date: Wed, 30 Jan 2008 06:44:39 -0800 (PST) Subject: find nearest time in datetime list In-Reply-To: <47A0672F.3090702@timgolden.me.uk> References: <15180398.post@talk.nabble.com> <47A0672F.3090702@timgolden.me.uk> Message-ID: <15183205.post@talk.nabble.com> Thanks all! This is terrific, and a quick response... I have to go with the 2.4 version, but thanks to everyone... Tim Golden-4 wrote: > > washakie wrote: >> Hello, >> >> I have a list of datetime objects: DTlist, I have another single datetime >> object: dt, ... I need to find the nearest DTlist[i] to the dt .... is >> there a simple way to do this? There isn't necessarily an exact match... > > > import datetime > > dates = [datetime.date (2007, 1, (1+i)*2) for i in range (10)] > one_date = datetime.date (2007, 1, 7) > > print sorted (dates, key=lambda x: abs (x-one_date))[0] > > > > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/find-nearest-time-in-datetime-list-tp15180398p15183205.html Sent from the Python - python-list mailing list archive at Nabble.com. From dwblas at gmail.com Mon Jan 14 12:50:14 2008 From: dwblas at gmail.com (dwblas at gmail.com) Date: Mon, 14 Jan 2008 09:50:14 -0800 (PST) Subject: time.time or time.clock References: Message-ID: <87bab627-9fb4-4a39-9f44-08b8697384d2@i3g2000hsf.googlegroups.com> """ time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't high enough resolution on windows. Take a look at datetime. It is good to the micro-second on Linux and milli-second on Windows. """ import datetime begin_time=datetime.datetime.now() for j in range(100000): x = j+1 # wait a small amount of time print "Elapsed time =", datetime.datetime.now()-begin_time ## You can also access the individual time values print begin_time.second print begin_time.microsecond ## etc. From haraldarminmassa at gmail.com Tue Jan 22 09:14:41 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Tue, 22 Jan 2008 06:14:41 -0800 (PST) Subject: building psycopg2 on windows using mingw, "cannot find -lpq" References: Message-ID: <1095e286-cebe-4249-af42-8053a2e44417@d70g2000hsb.googlegroups.com> > I use psycopg2 all the time on windows. I use the binary installer > instead of source. Works great for me. > > -Tom Me2. Just in 7 out of 200 it does not work with the currently available binary installer, on some startups, so I decided to follow a recommendation out of the psycopg2 list to compile it from trunk :( Harald From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 9 07:19:55 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 09 Jan 2008 13:19:55 +0100 Subject: Learning Python via a little word frequency program In-Reply-To: References: Message-ID: <4784bbea$0$17616$426a74cc@news.free.fr> Andrew Savige a ?crit : > I'm learning Python by reading David Beazley's "Python Essential Reference" > book and writing a few toy programs. To get a feel for hashes and sorting, > I set myself this little problem today (not homework, BTW): > > Given a string containing a space-separated list of names: > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > > produce a frequency table of names, sorted descending by frequency. > then ascending by name. For the above data, the output should be: > > kevin : 3 > jock : 2 > andrew : 1 > bill : 1 > fred : 1 > freddy : 1 > > Here's my first attempt: > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > freq = {} > for name in names.split(): > freq[name] = 1 + freq.get(name, 0) > deco = zip([-x for x in freq.values()], freq.keys()) > deco.sort() > for v, k in deco: > print "%-10s: %d" % (k, -v) > > I'm interested to learn how more experienced Python folks would solve > this little problem. For a one-shot Q&D script: names = "freddy fred bill jock kevin andrew kevin kevin jock" freqs = [(- names.count(name), name) for name in set(names.split())] print "\n".join("%-10s : %s" % (n, -f) for f, n in sorted(freqs)) Now I might choose a very different solution for a more serious application, depending on detailed specs and intended use of the "frequency table". > Though I've read about the DSU Python sorting idiom, > I'm not sure I've strictly applied it above ... Perhaps not "strictly" since you don't really "undecorate", but that's another application of the same principle : provided the appropriate data structure, sort() (or sorted()) will do the right thing. > and the -x hack above to > achieve a descending sort feels a bit odd to me, though I couldn't think > of a better way to do it. The "other" way would be to pass a custom comparison callback to sort, which would be both slower and more complicated. Your solution is IMHO the right thing to do here. > I also have a few specific questions. Instead of: > > for name in names.split(): > freq[name] = 1 + freq.get(name, 0) > > I might try: > > for name in names.split(): > try: > freq[name] += 1 > except KeyError: > freq[name] = 1 or a couple other solutions, including a defaultdict (python >= 2.5). > Which is preferred? It's a FAQ - or it should be one. Globally: the second one tends to be faster when there's no exception (ie the key already exists), but slower when exceptions happen. So it mostly depends on what you expect your dataset to be. Now note that you don't necessarily need a dict here !-) > Ditto for: > > deco = zip([-x for x in freq.values()], freq.keys()) > > versus: > > deco = zip(map(operator.neg, freq.values()), freq.keys()) As far as I'm concerned, I'd favor the first solution here. Reads better IMHO > Finally, I might replace: > > for v, k in deco: > print "%-10s: %d" % (k, -v) > > with: > > print "\n".join("%-10s: %d" % (k, -v) for v, k in deco) That's what I'd do here too - but it depends on context (ie: for huge datasets and/or complex formating, i'd use a for loop). From yuri.feldman at gmail.com Thu Jan 17 07:14:38 2008 From: yuri.feldman at gmail.com (yuri.feldman at gmail.com) Date: Thu, 17 Jan 2008 04:14:38 -0800 (PST) Subject: Embedding Python - Freeing Python Objects Not Using Py_DECREF Message-ID: Hello, I'm embedding Python interpreter in a Win32 console application. I use C++. I would like to use the WinAPI LoadLibrary function to load the python dll at runtime (followed by GetProcAddress calls), so that I have to make no assumptions about the location of the dll. However I can't use the macro Py_DECREF if I load the dll this way. Is there a way to properly free python objects (specifically - dictionaries created by PyDict_New() and the object returned by PyRun_String()) not using Py_DECREF? Alternatively, is there a way to include the python header - to make the macro Py_DECREF available, but to be able to locate the python dll whenever python is installed? (The problem is that python may be installed anywhere, and the python dll does not always appear in system folders - sometimes it is in the python installation directory, thus it is unclear which targets to specify to the linker to search for the dll). I'd appreciate any help. Thanks in advance, From jr9445 at ATT.COM Thu Jan 24 13:24:32 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 24 Jan 2008 12:24:32 -0600 Subject: piping into a python script In-Reply-To: <200801241903.20082.donn.ingle@gmail.com> References: <668bb39a0801240845k70174c44xfb54d519f5c3ffe2@mail.gmail.com> <200801241903.20082.donn.ingle@gmail.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Donn > Sent: Thursday, January 24, 2008 12:03 PM > To: Micha? Bentkowski > Cc: python-list at python.org > Subject: Re: piping into a python script > > I have tested getopt and it strips the lone '-' out. I can get it from Try 'foo.py -- -'. The '--' normally tells the parser to stop parsing args. Ex: date > -foo.txt; rm -foo.txt; rm -- -foo.txt I think this will tell you if stdin is being piped in or not: import sys import os print os.isatty(sys.stdin.fileno()) D:\>type a.txt | python a.py False D:\>python a.py True Also if you're lazy, look at the StringIO class: if options.filelist is None and len(args) < 1: # read from stdin f = sys.stdin elif options.filelist is not None and len(args) < 1: # read filenames from file f = open(options.filelist, 'r') elif options.filelist is None and len(args) > 0: # filenames on command line f = StringIO.StringIO('\n'.join(args)) else: ## Thanks for playing. parser.print_help() exit(1) if f: for filename in f: > -- Segio Aragones (Groo the Wanderer Number 99) Ah yes, Groo. Ever wonder who would win if Groo and Forrest Gump fought each other? From mail at timgolden.me.uk Sun Jan 13 22:02:38 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 14 Jan 2008 03:02:38 +0000 Subject: How to get user home directory on Windows In-Reply-To: <478ab8a1$0$20930$e4fe514c@dreader19.news.xs4all.nl> References: <478ab8a1$0$20930$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <478AD0CE.4060406@timgolden.me.uk> Martin P. Hellwig wrote: > Giampaolo Rodola' wrote: >> Hi all, >> I'm trying to use the pywin32 extension to find out the user's home >> directory but currently I didn't find a solution yet. >> What I'd need to do is not getting the home directory of the currently >> logged in user but something like: >> >>>>> get_homedir("frank") >> "C:\home\users\frank" >>>>> get_homedir("josh") >> "C:\home\users\josh" >> >> Is there a way to do that? >> I tried to search through the Pywin32 documentation with no luck. >> In addition I'm not practiced with the Windows API at all. > > Well, windows, to my knowledge, uses the same base path for all profiles > (this is not true for the My Documents folder which can differ). So what > you could do is get the location from the ALLUSERPROFILE environment > variable, go one folder higher and iterate through that. > Ignoring the folders for the 'pseudo' users: 'All Users', 'Default > User', 'LocalService' and 'NetworkService'. The trouble with that is that any particular user's profile can be specifically overridden. I'm not attached to an AD network here, but I think a networked user's profile can be network based (whike a local user's won't be, say). And there are other ways to change the profile too, down to hacking the registry as described here: http://support.microsoft.com/kb/314843/#XSLTH3129121125120121120120 That said, it'll probably work for a lot of the people for a lot of the time. TJG From hinds.ja at gmail.com Thu Jan 3 10:55:17 2008 From: hinds.ja at gmail.com (hinds.ja at gmail.com) Date: Thu, 3 Jan 2008 07:55:17 -0800 (PST) Subject: Insert to a clob field using cx_Oracle via a stored procedure References: <87860f02-9c78-4248-8d30-c13c91a59f00@i29g2000prf.googlegroups.com> Message-ID: On Jan 2, 2:01?pm, hinds... at gmail.com wrote: > Hello, > > Does anyone have experience using cx_Oracle to call a stored procedure > that inserts to a clob field? ?We have done this successfully via > straight SQL, but we are at a loss on how to do the same insert using > a stored procedure call. ?Any assistance would be much appreciated. > Thanks. > > Jason Found a solution to this - see the following thread if you interested. http://forums.oracle.com/forums/thread.jspa?forumID=376&threadID=601700 From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 9 06:45:05 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 09 Jan 2008 12:45:05 +0100 Subject: How a smart editor could make "Postfix type declarations PEP3117" in Python3000 more readable In-Reply-To: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> References: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> Message-ID: <4784b3c0$0$18795$426a74cc@news.free.fr> aspineux a ?crit : > Hi > > I read the PEP 3117 about the new "Postfix type declarations" in > Python3000. > THIS PEP as been REJECTED ! Indeed - it's an april's fool joke !-) And BTW, no need to scream, we hear you pretty well. > But ... > > The notation in the PEP is very ugly ! This make python code more > difficult to read! > > Anyway when I switched to python (from C, C++, ..), I suffered a lot > of the > untyped python variables. > And I think this is a good idea to include > typing in python. The concept of "type" greatly differs between static typing and dynamic typing. FWIW, it also somewhat differs between declarative static type systems (C/C++/Java/etc) and inference-based static type systems (OCaml, Haskell etc). Anyway, Python is dynamically typed (FWIW, it's dynamic almost everywhere), and this is probably not going to change in a foreseeable future. So I guess you'd better learn to use dynamic typing instead of trying to write C++ in Python - or, if you just can't get used to dynamic typing, use another language. From kyosohma at gmail.com Fri Jan 4 16:05:46 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 4 Jan 2008 13:05:46 -0800 (PST) Subject: Tabnanny errors when Migrating Python 2.4 code to 2.5 References: <6d197192-0340-42f8-b764-cba91a92bb21@i3g2000hsf.googlegroups.com> Message-ID: On Jan 4, 2:06 pm, John Machin wrote: > On Jan 5, 3:56 am, kyoso... at gmail.com wrote: > > > Hi, > > > When Python 2.5 first came out, I eagerly downloaded it and > > immediately had issues with getting it to run my 2.4 code. So I just > > stuck to 2.4. However, I decided this week that I really should try to > > get 2.5 to work. Does anyone know why code that works perfectly for > > months in a 2.4 environment throws indentation errors in 2.5? > > No, not until you go to the bother of reproducing the problem with a > small file, tell us what platform you are on, how you are running this > code (IDLE, shell prompt, ...), how you installed Python 2.5 > (2.5.1?), ... I'm using Windows XP, using IDLE (which was mentioned already) and I downloaded the 2.5.1 exe/msi file from python.org to install it. I have yet to find a simple one which exhibits the issue to post. It seems to happen to my complex files, not the simple ones. Sorry to bother you. Mike From george.sakkis at gmail.com Fri Jan 18 12:50:40 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 18 Jan 2008 09:50:40 -0800 (PST) Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <54b11613-6b9c-4cb8-838c-d3e01699bf3d@e4g2000hsg.googlegroups.com> On Jan 18, 12:15 pm, David Sanders wrote: > Hi, > > I am processing large files of numerical data. Each line is either a > single (positive) integer, or a pair of positive integers, where the > second represents the number of times that the first number is > repeated in the data -- this is to avoid generating huge raw files, > since one particular number is often repeated in the data generation > step. > > My question is how to process such files efficiently to obtain a > frequency histogram of the data (how many times each number occurs in > the data, taking into account the repetitions). My current code is as > follows: > > ------------------- > #!/usr/bin/env python > # Counts the occurrences of integers in a file and makes a histogram > of them > # Allows for a second field which gives the number of counts of each > datum > > import sys > args = sys.argv > num_args = len(args) > > if num_args < 2: > print "Syntaxis: count.py archivo" > sys.exit(); > > name = args[1] > file = open(name, "r") > > hist = {} # dictionary for histogram > num = 0 > > for line in file: > data = line.split() > first = int(data[0]) > > if len(data) == 1: > count = 1 > else: > count = int(data[1]) # more than one repetition > > if first in hist: # add the information to the histogram > hist[first]+=count > else: > hist[first]=count > > num+=count > > keys = hist.keys() > keys.sort() > > print "# i fraction hist[i]" > for i in keys: > print i, float(hist[i])/num, hist[i] > --------------------- > > The data files are large (~100 million lines), and this code takes a > long time to run (compared to just doing wc -l, for example). > > Am I doing something very inefficient? (Any general comments on my > pythonic (or otherwise) style are also appreciated!) Is > "line.split()" efficient, for example? Without further information, I don't see anything particularly inefficient. What may help here is if you have any a priori knowledge about the data, specifically: - How often does a single number occur compared to a pair of numbers ? E.g. if a single number is much more common that a pair, you can avoid split() most of the times: try: first,count = int(line), 1 except ValueError: first,count = map(int,line.split()) Similarly if the pair is much more frequent than the single number, just invert the above so that the common case is in the 'try' block and the infrequent in 'except'. However if the two cases have similar frequency, or if you have no a priori knowledge, try/except will likely be slower. - What proportion of the first numbers is unique ? If it's small enough, a faster way to update the dict is: try: hist[first]+=count except KeyError: hist[first] = 1 > Is a dictionary the right way to do this? In any given file, there is > an upper bound on the data, so it seems to me that some kind of array > (numpy?) would be more efficient, but the upper bound changes in each > file. Yes, dict is the right data structure; since Python 2.5, collections.defaultdict is an alternative. numpy is good for processing numeric data once they are already in arrays, not for populating them. George From bronger at physik.rwth-aachen.de Mon Jan 28 02:04:05 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 28 Jan 2008 08:04:05 +0100 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> Message-ID: <87lk6a8m8q.fsf@physik.rwth-aachen.de> Hall?chen! Dustan writes: > On Jan 27, 12:41 pm, Torsten Bronger > wrote: > >> [...] >> >> Well, you save one or two lines per class. Not enough in my >> opinion. > > Are you referring to the alternate syntax or to the decorator? > Either way, you could be saving 4 or 5 or more lines, if you have > enough arguments. Mostly, I write them in one or two lines, e.g. def __init__(self, id, kind, person, feedname): self.id, self.kind, self.person = id, kind, person (Sometimes I break after the "=".) Still, I don't think that this at-most-once-per-class use case justifies a special syntax (whether within the current language or not) that everyone else has to learn, too. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From boblatest at yahoo.com Wed Jan 9 07:33:42 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 12:33:42 GMT Subject: How does unicode() work? Message-ID: <5ujt96F1i6h37U1@mid.dfncis.de> Here's a test snippet... import sys for k in sys.stdin: print '%s -> %s' % (k, k.decode('iso-8859-1')) ...but it barfs when actually fed with iso8859-1 characters. How is this done right? robert From kay.schluehr at gmx.net Wed Jan 30 02:53:21 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 29 Jan 2008 23:53:21 -0800 (PST) Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> <479e0225$0$36389$742ec2ed@news.sonic.net> <70c4064a-a65d-4fd5-b39c-38e6a3fb567b@i7g2000prf.googlegroups.com> <479fb907$0$25376$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Jan 30, 12:38 am, Wildemar Wildenburger wrote: > > Python has a JIT right no > > You mean in the Java-sense (outputting native machine code)? > > /W Sure. http://psyco.sourceforge.net/ From antroy at gmail.com Tue Jan 29 05:00:13 2008 From: antroy at gmail.com (Ant) Date: Tue, 29 Jan 2008 02:00:13 -0800 (PST) Subject: Python self-evaluating strings References: Message-ID: <20d655ca-0c5d-4f4a-b42c-89b47e00e0de@h11g2000prf.googlegroups.com> In the spirit of "Simple is better than complex." and totally bypassing the intention of quines (though not necessarily the definition): --- probably_not_a_real_quine.py ---- import sys for line in open(sys.argv[0]): print line, -------------------------------------- ;-) -- Ant. From nicola.musatti at gmail.com Fri Jan 4 04:35:25 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Fri, 4 Jan 2008 01:35:25 -0800 (PST) Subject: Who's to blame? References: <92dfc2fc-0677-43c0-b34f-4f240fa40205@e4g2000hsg.googlegroups.com> <255d32d0-43f5-4d34-a074-b87082dc6043@e23g2000prf.googlegroups.com> Message-ID: <2b076973-b132-4666-a163-b80bcbeaedfb@s8g2000prg.googlegroups.com> Hallo, Mike. First of all, thanks to both you and Rob for your answers. I now see that the wxPython group would have been a better place to post to, all the more so given the tight connection between the wxPython and wxWidgets projects, of which at first I wasn't aware. On Jan 3, 8:19 pm, kyoso... at gmail.com wrote: [...] > I've never created a modal dialog like this. Instead, I follow the > wxPython in Action book examples (most of the time), which would do a > yes/no dialog like this: > > > > dlg = wx.MessageDialog(None, 'Some Message', 'A Message Box', > wx.YES_NO | wx.QUESTION) > retCode = dlg.ShowModal() > if retCode == wx.ID_YES: > # do something > print 'yes' > else: > # do something else > print 'no' > dlg.Destroy() > > Actually my example started out as something like if wx.MessageBox(message="Some message", caption="Some caption", style=wx.YES|wx.NO) == wx.YES: pass I had to change it because the actual message can become very long, so I assembled a dialog with a scrollable text field. Maybe I'm expecting to much of wxStdDialogButtonSizer, but I still feel that given that both your method and mine above work straight away, it should provide the same behaviour with Yes/No buttons as with OK/Cancel ones. Cheers, Nicola Musatti From jeba.ride at gmail.com Tue Jan 15 23:09:37 2008 From: jeba.ride at gmail.com (Clement) Date: Tue, 15 Jan 2008 20:09:37 -0800 (PST) Subject: Asynchronous HTTP Message-ID: <6e33f161-1bba-437b-a3ca-e7bec80089ed@m34g2000hsb.googlegroups.com> Can i use asynchttp for http secure connection... If so plz how does it can be done. Is there any other library can do that that.... From nagle at animats.com Fri Jan 18 02:03:18 2008 From: nagle at animats.com (John Nagle) Date: Thu, 17 Jan 2008 23:03:18 -0800 Subject: Cannot catch _mysql_exceptions.OperationalError In-Reply-To: <5f435c88-ef42-4ca9-921a-675393824ccc@k39g2000hsf.googlegroups.com> References: <5f435c88-ef42-4ca9-921a-675393824ccc@k39g2000hsf.googlegroups.com> Message-ID: <47904de2$0$36326$742ec2ed@news.sonic.net> Bob wrote: > In our database code (we are using django v0.96) we wanted to catch > and handle MySQL OperationalErrors. We use both the Django models and > database connections. > > However, even though we confirmed that a > _mysql_exceptions.OperationalError are raised (particularly 1213 > deadlock), we cannot catch them with try/except. If you're using MySQLdb, it works fine: try: ... do database operations except MySQLdb.OperationalError, message: # handle trouble errorcode = message[0] # get MySQL error code if errorcode == kmysqlduplicateentry : # if dup on insert ... deal with duplicate entry If Django has a problem, you'll have to take that up with them. John Nagle From deets at nospam.web.de Thu Jan 3 08:07:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 14:07:27 +0100 Subject: reassign to builtin possible !? References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> Message-ID: <5u450fF1gldn9U2@mid.uni-berlin.de> Bernhard Merkle wrote: > Hi there, > > I am reading Learning Python 3e from Mark Lutz and just found out that > reassigning to builtins is possible. > What is the reason, why Python allows this ? IMO this is very risky > and can lead to hard to find errors. > (see also Learning Python 3e, Chapter 16, Page 315) > >>>> True > True >>>> False > False >>>> True = 1 >>>> True > 1 >>>> True = 0 >>>> True > 0 This hal always been possible. But it's not reassigning, it's shadowing - which is a totally different beast. Shadowing builtins is bad style, but lokal to your context. Which can get nasty of course, if you do the above on e.g. module level. But you can't alter the values for True/False globally with this. Diez From sergio.correia at gmail.com Fri Jan 18 20:38:24 2008 From: sergio.correia at gmail.com (Sergio Correia) Date: Fri, 18 Jan 2008 20:38:24 -0500 Subject: I don't understand what is happening in this threading code In-Reply-To: References: Message-ID: This is what's happening: 1) The chef thread releases the sema 2) While the chef thread is saying "Andiamo", decreasing "i", and ending the while loop, the waiter thread SERVES the dish and RUNS to reacquire the lock 3) Back in the main loop, chef.join() is run, and then the waiter's variable is changed. But it's already too late. The waiter is already locked. He'll wait and wait forever for another dish, which will never come. So you will have to kill him. All for a race condition. --- I've just read Carl's post (just b4 hitting submit). I agree with him, rewrite the logic. IMO, the objects should be the key, THEY are the ones that should be joined. You should run the chef and waiter as daemons, and just do something like orders.join() dishes.join() And when the chefs finishes with the orders and the waiter finishes serving them, the program ends. HTH, Sergio On Jan 18, 2008 7:43 PM, Matthew Wilson wrote: > In this code, I tried to kill my thread object by setting a variable on it > to False. > > Inside the run method of my thread object, it checks a different > variable. > > I've already rewritten this code to use semaphores, but I'm just curious > what is going on. > > Here's the code: > > import logging, threading, time > logging.basicConfig(level=logging.DEBUG, > format="%(threadName)s: %(message)s") > > class Waiter(threading.Thread): > def __init__(self, hot_food): > super(Waiter, self).__init__() > self.should_keep_running = True > self.hot_food = hot_food > > def run(self): > while self.should_keep_running: > logging.debug("Inside run, the id of should_keep_running is %s." > % id(self.should_keep_running)) > self.hot_food.acquire() > > def cook_food(hot_food): > i = 5 > while i >= 0: > logging.debug("I am cooking food...") > time.sleep(1) > hot_food.release() > logging.debug("Andiamo!") > i -= 1 > > def main(): > > hot_food = threading.Semaphore(value=0) > > chef = threading.Thread(name="chef", target=cook_food, args=(hot_food, )) > chef.start() > > w = Waiter(hot_food) > logging.debug("Initially, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > w.start() > logging.debug("After start, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > > # Wait for the chef to finish work. > chef.join() > > # Now try to kill off the waiter by setting a variable inside the waiter. > w.should_keep_running = False > logging.debug("Now, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > > if __name__ == "__main__": > main() > > And here's what I get when I execute it. I have to suspend the process > with CTRL=Z and then kill -9 it. > > $ python foo.py > MainThread: Initially, the id of w.should_keep_running is 135527852. > MainThread: After start, the id of w.should_keep_running is 135527852. > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > chef: I am cooking food... > Thread-1: Inside run, the id of should_keep_running is 135527852. > chef: Andiamo! > Thread-1: Inside run, the id of should_keep_running is 135527852. > MainThread: Now, the id of w.should_keep_running is 135527840. > > [1]+ Stopped python foo.py > > $ kill -9 %1 > > [1]+ Stopped python foo.py > > The memory address of should_keep_running seems to change when I set it > from True to False, and inside the run method, I keep checking the old > location. > > I am totally baffled what this means. > > Like I said earlier, I already rewrote this code to use semaphores, but > I just want to know what is going on here. > > Any explanation is welcome. > > TIA > > Matt > -- > http://mail.python.org/mailman/listinfo/python-list > From Matthew_WARREN at bnpparibas.com Mon Jan 28 05:36:34 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Mon, 28 Jan 2008 10:36:34 +0000 Subject: finding child cpu usage of a running child In-Reply-To: Message-ID: had to say, that subject conjoured up an interesting image in my head :) 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 michael at stroeder.com Tue Jan 29 04:10:01 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 29 Jan 2008 10:10:01 +0100 Subject: Encryption Recommendation In-Reply-To: <606aj3F1pa0tfU1@mid.uni-berlin.de> References: <6b40b773-8554-4e9c-838f-e6934212d16e@n20g2000hsh.googlegroups.com> <606aj3F1pa0tfU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > rogerrath2 at gmail.com wrote: > >> I'm still using Python 2.4. In my code, I want to encrypt a password >> and at another point decrypt it. What is the standard way of doing >> encryption in python? Is it the Pycrypto module? > > Usually, one doesn't store clear-text passwords. Instead, use a > hash-algorithm like md5 or crypt (the former is in the standard lib, don't > know of the other out of my head) and hash the password, and store that > hash. > > If a user enters the password, use the same algorithm, and compare the > resulting hashes with the stored one. And don't forget to add a salt so that same passwords do not have the same hash. But if the password checking is done with a challenge-response mechanism (e.g. HTTP-Digest Auth or SASL with DIGEST-MD5) it's required that the instance checking the password has the clear-text password available. So reversible encryption for storing passwords might be required. Ciao, Michael. From paul.hankin at gmail.com Fri Jan 25 04:44:57 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Fri, 25 Jan 2008 01:44:57 -0800 (PST) Subject: Which is more pythonic? References: <56518bb9-1d56-47c3-8112-6e0778832c12@v29g2000hsf.googlegroups.com> Message-ID: <7c2cc4fa-351a-4350-a20b-2f94b5a37c15@c23g2000hsa.googlegroups.com> benjamin.zimmerman at gmail.com wrote: > I have a goal function that returns the fitness of a given solution. I > need to wrap that function with a class or a function to keep track of > the best solution I encounter. Which of the following would best serve > my purpose and be the most pythonic? You could write a function that generates your trial solutions and use max. Eg: instead of using your Goal class: def f(score_function): goal = Goal(score_function) while there's more solutions: ... produce trial solution goal(trial_solution) return goal.best Write a solution generator... def all_solutions(): while there's more solutions: ... produce trial solution yield trial_solution ...and find the best using best = max(all_solutions(), key = score_function) This uses a builtin rather than either of the snippets in the original post, and it's also a much cleaner approach. -- Paul Hankin From rridge at caffeine.csclub.uwaterloo.ca Fri Jan 11 09:37:41 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 11 Jan 2008 09:37:41 -0500 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >fact 1: CPython compiles source code to byte-code. >fact 2: CPython executes this byte-code. >fact 3: Sun's JDK compiles source code to byte-code. >fact 4: Sun's JDK executes this byte-code. > >Care to prove me wrong on any of these points ? Don't bother: you can't. >So my first assertion that "CPython is compiled to byte-code, which is >then executed by a VM" is true, and since the same assertion also stands >for Java (ie: sun's JDK), then the "just like" qualifier is true too. >Period. No, the "just like" qualifier is false. Python doesn't compile "just like" Java, nor does it execute "just like" Java. The "byte-code" langauges are very different and they perform much differently. Java compiles slower but executes faster. Python's byte-code is ment to quickly generated on the fly to save having to reparse the source code. Java code is compiled using optimizations into a virtual machine languague ment to be executed as fast as possible on a wide range of processors. The similarities between the two are superficial, Python doesn't compile and execute code "just like" Java. Try all you want to try to reparse what you wrote in to a different meaning, it doesn't change the fact your intent was to mislead. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From mtobis at gmail.com Fri Jan 11 22:36:24 2008 From: mtobis at gmail.com (Michael Tobis) Date: Fri, 11 Jan 2008 19:36:24 -0800 (PST) Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> <13og1lgcespv6c2@corp.supernews.com> <13oga52q3f2gg1c@corp.supernews.com> Message-ID: On Jan 11, 8:40 pm, Steven D'Aprano wrote: > Read the OP's post again. His (her?) users aren't expected to create the > toolkit, merely to use it. To create good toolkits you need both a master > programmer and an expert in the field. It is an advantage if they are the > same person. But to use such a good toolkit, you shouldn't need to be a > master programmer. It appears we are in agreement, then. But that leaves me in a position where I can't understand your complaint. There's no reason I can see for the sort of compromise you ask for. Clean abstractions benefit from their cleanliness. Of course the users will have a lot to learn regardless, but that's the point. A user has to decide whether to take on a new tool. If that learning is about meaningless incantations (the way beginning programmers are currently taught to say "abracadabra public static void main") users will be less impressed with the advantage of the abstractions and be less likely to engage the new methods on offer. If the learning exposes new potential, that makes your tool more attractive. What's more, the next higher layer of abstraction will be easier to compose if the composer of that abstraction doesn't have to make the sort of compromise you suggest. Abstractions that stay out of the way until you need to expand on them is a big part of what Python is all about. It's not clear that this is the sort of application where cutting corners makes sense, so I don't see how your advice is justified. mt From eefacm at gmail.com Wed Jan 16 15:01:43 2008 From: eefacm at gmail.com (eefacm at gmail.com) Date: Wed, 16 Jan 2008 12:01:43 -0800 (PST) Subject: Perl Template Toolkit: Now in spicy new Python flavor References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> <13a75830-5416-4fe3-9460-018e1240e6e6@e32g2000prn.googlegroups.com> Message-ID: On Jan 15, 1:45 pm, George Sakkis wrote: > > eef... at gmail.com wrote: > > > I'd like to inform the Python community that the powerful and popular > > > Template Toolkit system, previously available only in its original > > > Perl implementation, is now also available in a beta Python > > > implementation: > > > >http://tt2.org/python/index.html > > > > I created this port both as a fun programming project, and for use in > > > environments where Perl is not available, for reasons technical, > > > cultural, or otherwise. The extensive Perl test suites have also been > > > ported, and most templates require no or very little modification. > How does it compare with other "mainstream" Python template engines > such as Cheetah, Mako, etc. ? I can't claim a comprehensive familiarity with Python template offerings, but all of the packages approved for use at my previous workplace left me cold. The most popular were ClearSilver and Django, and both felt horribly limiting compared to the Template Toolkit, which I became acquainted with when hacking on Bugzilla some years ago. Neither supports what I would consider very basic operations on the template data. Nothing like the following can be expressed in those packages: from pprint import PrettyPrinter from template import Template print Template().processString( "the list is [% a.pformat(b(c + d)) %]", { "a": PrettyPrinter(2, 40), "b": range, "c": 10, "d": 20 } ) Here we have a template that includes a method call, a function call, and simple addition. Neither Django nor ClearSilver can manage any of these three things. Both of those packages offer other features not found in the Template Toolkit; it was the relative impotence of the templating systems that drove me to attack the translation. > Unless I missed it, the documentation > covers the Perl version only. The online documentation, yes. All source-level documentation (from which the online documentation is largely drawn) has been converted into Python docstrings in the source code. They can be read by browsing the Subversion repository or by importing the code and using help(); eg: >>> import template.stash >>> help(template.stash) ... module docs ... >>> help(template.stash.Stash) ... class docs ... >>> help(template.stash.Stash.get) ... method docs ... From paul.hankin at gmail.com Mon Jan 14 08:03:23 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 14 Jan 2008 05:03:23 -0800 (PST) Subject: ucs2 or ucs4? References: Message-ID: <3430dce1-27da-471c-98c4-418170544c08@s12g2000prg.googlegroups.com> On Jan 14, 12:56 pm, Neal Becker wrote: > How do I tell if my python-2.5 is build with ucs2 or ucs4? See if unichr(0x10000) raises ValueError: if it does, you're ucs2. -- Paul Hankin From scrdhrt at gmail.com Fri Jan 18 05:25:06 2008 From: scrdhrt at gmail.com (Sacred Heart) Date: Fri, 18 Jan 2008 02:25:06 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <7xr6gguwiq.fsf@ruckus.brouhaha.com> Message-ID: <75a76c52-1b07-4b77-8ba9-2ca09db7b1e1@p69g2000hsa.googlegroups.com> On Jan 17, 7:39 pm, Paul Rubin wrote: > Sacred Heart writes: > > array1 = ['one','two','three','four'] > > array2 = ['a','b','c','d'] > > > I want to loop through array1 and add elements from array2 at the end, > > so it looks like this: > > > one a > > two b > > three c > > four c > > The "functional" style is to use the zip function that someone > described. The old-fashioned way is simply: > > n = len(array1) > for i in xrange(n): > print array1[i], array2[i] > > You can modify this in various ways if the lengths of the lists are > not equal. E.g. Thank you Paul, and everybody else contributing with answers of various complexity. Although a whole bunch of them was way too complex for my simple problem, but that's ok. I now know how to use map and zip, and also learned some tips and tricks. Thanks. All the best, SH From ggpolo at gmail.com Wed Jan 23 17:18:25 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jan 2008 20:18:25 -0200 Subject: Creating new types and invoking super In-Reply-To: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> References: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> Message-ID: 2008/1/23, Arnaud Delobelle : > On Jan 23, 8:55 pm, "Guilherme Polo" wrote: > > Hello, > > Hi > [...] > > First I tried this: > > > > def init(func): > > def _init(inst): > > super(inst.__class__, inst).__init__() > > func(inst) > > > > return _init > > > > class A(object): > > @init > > def __init__(self): pass > > This kind of approach can't work, you need to call super(A, obj). > super(type(obj), obj) is pointless, it defeats the whole purpose of > the mro! > Yeh, as shown in the next examples in the previous email. Using a decorator for that doesn't sound useful at all, was just trying something different ;) I will stick to the no-decorator option. > The only way I can think of would be to create a metaclass, but I > don't think it's worth it. super(A, obj).__init__() isn't that bad! > Metaclass doesn't apply here because metaclass is related to class-construction. This is related to instance initialization, and I'm creating the types as the user asks. > -- > Arnaud > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From ejensen at visi.com Thu Jan 10 15:47:07 2008 From: ejensen at visi.com (Ed Jensen) Date: Thu, 10 Jan 2008 20:47:07 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> Message-ID: <13od12b23hfv772@corp.supernews.com> Bruno Desthuilliers wrote: > I fail to see how the existence of JIT compilers in some Java VM changes > anything to the fact that both Java (by language specification) and > CPython use the byte-code/VM scheme. While your answer was technically correct, by omitting pertinent information, your answer lead readers to the wrong conclusion. The only question that remains is if you were being accidentally misleading or purposefully misleading. From robin at alldunn.com Thu Jan 24 12:58:09 2008 From: robin at alldunn.com (Robin Dunn) Date: Thu, 24 Jan 2008 09:58:09 -0800 Subject: [wxPython-users] Issue with docking wx.listctrl window In-Reply-To: References: Message-ID: <4798D1B1.7020908@alldunn.com> tarun wrote: > Hello All, > > I'm trying to create a Frame with AuiManager. The code is attached. > > *Problem:* > - I want 2 windows to be docked in the frame. One is a text control and > other is a list control. > - The text control gets docked, but on trying to dock the list control, > all the tabs dis-appear. > The tabs appear only when the list control window is kept floating. > > In the attached code the list control window is kept floating. This can > be docked > To see the issue with docking, comment line 33 and un-comment line 35 in > the attached file and then try to execute, the issue would be clearly > visible. On un-docking the window1, the tabs again appear.. > > *Please let me the solution to this ASAP* The main problem is that you are putting the listctrl on a panel, but you are telling AUI to manage the listctrl, not the panel. If I understand correctly then your other problems stem from that as well. Try passing self.log to AddPane, instead of self.log.list. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From princismo at gmail.com Mon Jan 21 23:33:30 2008 From: princismo at gmail.com (=?Big5?B?w0P4rw==?=) Date: Mon, 21 Jan 2008 20:33:30 -0800 (PST) Subject: How to solve "TypeError: list indices must be integers". References: <3f3ca8c6-b57c-43ff-bf80-11768e1a0f94@s8g2000prg.googlegroups.com> <9f38b518-20d5-4cc1-bf6d-0be6346d5f64@s27g2000prg.googlegroups.com> Message-ID: <225d984b-1187-467e-9a61-61aef697deeb@q77g2000hsh.googlegroups.com> On 1?22?, ??3?05?, John Machin wrote: > On Jan 22, 3:15 am, "??" wrote: > > > This is more details about my problem, which I running my py script > > for my project. Programming in pythoncard that we can develop a GUI > > based application easily. > > > I was assigned dialog.colorDialog(self) return value to a result > > object, but I suspect that result.color is the attribute of the result > > object that can assign to a string variable. > > The concepts " assigned to a object" > and " can be assigned to a variable" just don't > exist in Python. > > # Initially "name1" isn't bound to anything > name1 = 42 > # "name1" now refers to an int object whose value is 42 > name1 = 'abc' > # "name1" now refers to a str object whose value is 'abc' > name2 = name1 > # "name2" now refers to the same str object > > What is "dialog.colorDialog(self) return value"? What is "a result > object"? Show us the code! > > What is the connection between your last sentence above and the > "TypeError: list indices must be integers" problem? Show us the code! > > > > > There is a error prompt from python console "TypeError: list indices > > must be integers". > > Have any suggestion to solve this problem? > > Communication would be much easier if you show us the line of code > that causes the error message. > > Here are two simple examples of what can trigger that error message: > > >>> a_list = [1, 42, 666] > >>> not_an_integer = None > >>> a_list[not_an_integer] = 9876 > > Traceback (most recent call last): > File "", line 1, in > TypeError: list indices must be integers > > >>> a_name = a_list[not_an_integer] > > Traceback (most recent call last): > File "", line 1, in > TypeError: list indices must be integers > > Look for the pattern a_list[not_an_integer] in the statement that > triggers the exception. > > > > > When I print result.color, it is print out something like (255,0,0). > > Yes, that's most likely a tuple of (red, green, blue) values ... I'm > not astonished; are you? > > > How to covert result.color into a string? > > How? Use elementary Python functionality, after you've decided what > string representation you want. Examples: > > >>> color = (255, 128, 0) > >>> "red=%d green=%d blue=%d" % color > > 'red=255 green=128 blue=0'>>> '.someclass {background-color: #%02x%02x%02x; }' % color > > '.someclass {background-color: #ff8000; }' > > > > > How to convert a string to > > result.color type? > > Reverse the process. > > Again, what is the connection between "result.color" and the > "TypeError: list indices must be integers" problem? Many thanks, John Machin for your fast reply! Regards, Andreas From mgierdal at gmail.com Fri Jan 18 15:13:44 2008 From: mgierdal at gmail.com (mgierdal at gmail.com) Date: Fri, 18 Jan 2008 12:13:44 -0800 (PST) Subject: how to resolve Windows pathnames into cygwin ones References: <2ba97fb6-6bef-44aa-937b-2aa9582e4341@e4g2000hsg.googlegroups.com> <13p1m36m9htom5f@corp.supernews.com> <09ba7d26-d411-4bc5-9518-78a882882c66@q39g2000hsf.googlegroups.com> Message-ID: Well yes, I was hoping for a library function, but none provides it. Thanks for the code. Works nicely. On Jan 18, 12:12 pm, apatheticagnostic wrote: > Here we go then (are forward slashes valid in a filename in windows?) > def path_into_cygpath(path): > drive, destination = path.replace('\\','/').split(':') > return '/cygdrive/' + drive.lower() + destination From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 24 12:50:52 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 24 Jan 2008 18:50:52 +0100 Subject: Duplicating a variable In-Reply-To: References: Message-ID: <4798cfa2$0$31909$426a74cc@news.free.fr> hnessenospam at yahoo.com a ?crit : > I have run into a bit of a subtle problem. How do I go about > duplicating a variable (particularly a list of lists) in python. using the deepcopy function of the copy module. > I > was surprised when simple assignment didn't work. For example, let y = > [1,2,3] > >>>> x = y >>>> x[2] = 5 >>>> y > [1,2,5] Python only uses object references. It never copy anything unless explicitely asked for. From boblatest at yahoo.com Wed Jan 9 06:21:01 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 11:21:01 GMT Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> Message-ID: <5ujp0tF1ehvg2U1@mid.dfncis.de> Fredrik Lundh wrote: > keywords = filter(None, keywords) # get "true" items only Makes seinse. BTW, where can I find all methods of the built-in types? Section 3.6 only talks about strings and mentions the list append() method only in an example. Am I too stupid to read the manual, or is this an omission? robert From gagsl-py2 at yahoo.com.ar Fri Jan 25 17:03:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 Jan 2008 20:03:55 -0200 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> Message-ID: En Thu, 24 Jan 2008 11:57:49 -0200, Peter Schuller escribi?: > In this case my > problem is more related to the "file == module" and "directory == > module" semantics, since I want to break contents in a single module > out into several files. You already can do that, just import the public interfase of those several files onto the desired container module. See below for an example. >> Isn't org.lib.animal a package, reflected as a directory on disk? That's >> the same both for Java and Python. Monkey.py and Tiger.py would be >> modules >> inside that directory, just like Monkey.java and Tiger.java. Aren't the >> same thing? > > No, because in Java Monkey.java is a class. So we have class Monkey in > package org.lib.animal. In Python we would have class Monkey in module > org.lib.animal.monkey, which is redundant and does not reflect the > intended hierarchy. I have to either live with this, or put Monkey in > .../animal/__init__.py. Neither option is what I would want, ideally. You can also put, in animal/__init__.py: from monkey import Monkey and now you can refer to it as org.lib.animal.Monkey, but keep the implementation of Monkey class and all related stuff into .../animal/monkey.py -- Gabriel Genellina From jpeng at block.duxieweb.com Mon Jan 21 23:23:54 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Tue, 22 Jan 2008 12:23:54 +0800 Subject: read files In-Reply-To: References: Message-ID: <47956FDA.30009@block.duxieweb.com> Thank you. That gave so much solutions. And thanks all. Steven D'Aprano ??: > On Tue, 22 Jan 2008 11:00:53 +0800, J. Peng wrote: > >> first I know this is the correct method to read and print a file: >> >> fd = open("/etc/sysctl.conf") >> done=0 >> while not done: >> line = fd.readline() >> if line == '': >> done = 1 >> else: >> print line, >> >> fd.close() > > > The evolution of a Python program. > > # Solution 2: > > fd = open("/etc/sysctl.conf") > done = False > while not done: > line = fd.readline() > if line: > print line, > else: > done = True > fd.close() > > > > # Solution 3: > > fd = open("/etc/sysctl.conf") > while True: > line = fd.readline() > if line: > print line, > else: > break > fd.close() > > > # Solution 4: > > fd = open("/etc/sysctl.conf") > lines = fd.readlines() > for line in lines: > print line, > fd.close() > > > # Solution 5: > > fd = open("/etc/sysctl.conf", "r") > for line in fd.readlines(): > print line, > fd.close() > > > # Solution 6: > > for line in open("/etc/sysctl.conf").readlines(): > print line, > # garbage collector will close the file (eventually) > > > # Solution 7: > > fd = open("/etc/sysctl.conf", "r") > line = fd.readline() > while line: > print line, > line = fd.readline() > fd.close() > > > # Solution 8: > > fd = open("/etc/sysctl.conf", "r") > for line in fd: > print line, > fd.close() > > > # Solution 9: > > for line in open("/etc/sysctl.conf"): > print line, > > > # Solution 10: > # (the paranoid developer) > > try: > fd = open("/etc/sysctl.conf", "r") > except IOError, e: > log_error(e) # defined elsewhere > print "Can't open file, please try another." > else: > try: > for line in fd: > print line, > except Exception, e: > log_error(e) > print "Reading file was interrupted by an unexpected error." > try: > fd.close() > except IOError, e: > # Can't close a file??? That's BAD news. > log_error(e) > raise e > > > > From remco at gerlich.nl Sat Jan 19 07:12:57 2008 From: remco at gerlich.nl (Remco Gerlich) Date: Sat, 19 Jan 2008 13:12:57 +0100 Subject: Excess whitespace in my soup In-Reply-To: <48eb8853-91b3-4c43-8014-a0c624e4c6e7@t1g2000pra.googlegroups.com> References: <48eb8853-91b3-4c43-8014-a0c624e4c6e7@t1g2000pra.googlegroups.com> Message-ID: <7ae3ca10801190412w1648bd24xe9a1f4b85e6d1eb2@mail.gmail.com> Not sure if this is sufficient for what you need, but how about import re re.sub(u'[\s\xa0]+', ' ', s) That should replace all occurances of 1 or more whitespace or \xa0 characters, by a single space. Remco On Jan 19, 2008 12:38 PM, John Machin wrote: > I'm trying to recover the original data from some HTML written by a > well-known application. > > Here are three original data items, in Python repr() format, with > spaces changed to tildes for clarity: > > u'Saturday,~19~January~2008' > u'Line1\nLine2\nLine3' > u'foonly~frabjous\xa0farnarklingliness' > > Here is the HTML, with spaces changed to tildes, angle brackets > changed to square brackets, > omitting \r\n from the end of each line, and stripping a large number > of attributes from the [td] tags. > > ~~[td]Saturday,~19 > ~~January~2008[/td] > ~~[td]Line1[br] > ~~~~Line2[br] > ~~~~Line3[/td] > ~~[td]foonly > ~~frabjous farnarklingliness[/td] > > Here are the results of feeding it to ElementSoup: > > >>> import ElementSoup as ES > >>> elem = ES.parse('ws_soup1.htm') > >>> from pprint import pprint as pp > >>> pp([(e.tag, e.text, e.tail) for e in elem.getiterator()]) > [snip] > (u'td', u'Saturday, 19\n January 2008', u'\n'), > (u'td', u'Line1', u'\n'), > (u'br', None, u'\n Line2'), > (u'br', None, u'\n Line3'), > (u'td', u'foonly\n frabjous\xa0farnarklingliness', u'\n')] > > I'm happy enough with reassembling the second item. The problem is in > reliably and > correctly collapsing the whitespace in each of the above five > elements. The standard Python > idiom of u' '.join(text.split()) won't work because the text is > Unicode and u'\xa0' is whitespace > and would be converted to a space. > > Should whitespace collapsing be done earlier? Note that BeautifulSoup > leaves it as   -- ES does the conversion to \xa0 ... > > Does anyone know of an html_collapse_whitespace() for Python? Am I > missing something obvious? > > Thanks in advance, > John > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Mon Jan 21 12:31:33 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 21 Jan 2008 09:31:33 -0800 Subject: Is there a portable way to tell if data is available on a pipe? In-Reply-To: <47941112$0$36375$742ec2ed@news.sonic.net> References: <47941112$0$36375$742ec2ed@news.sonic.net> Message-ID: <13p9le6nu1u9l4d@corp.supernews.com> John Nagle wrote: > I need some way to find out if a pipe has data available for > a read without blocking if it does not. ... > I'd like to avoid having a thread to manage each pipe, but if I > have to, so be it. Well, without granting your wish, put a Queue.Queue "in front" of each pipe. The per-pipe thread reads a chunk, waiting if it has to, and then writes to the queue. To read from a pipe w/o waiting from one of these assemblies, you can use the get_nowait method on the associated queue. --Scott David Daniels Scott.Daniels at Acm.Org From thierry.volpiatto at gmail.com Sat Jan 19 15:41:59 2008 From: thierry.volpiatto at gmail.com (Thierry Volpiatto) Date: Sat, 19 Jan 2008 21:41:59 +0100 Subject: writing Python in Emacs In-Reply-To: (Terry Jones's message of "Sat, 19 Jan 2008 17:51:50 +0100") References: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> Message-ID: <87zlv14kfc.fsf@thievol.homelinux.org> I add just a note about ipython: if you use a version > 0.6.15 may be you will have a bad output on error like: == " ": instead of: if __name__ == "__main__": all the characters are missing. To avoid that, run in ipython: %upgrade -nolegacy uncomment in ~/.ipython/ipy_user_config.py: import ipy_defaults restart emacs and try a .py with some syntax errors. It should be ok now. Terry Jones writes: >>>>>> "Richard" == Richard Szopa writes: > > Richard> I am a devoted Emacs user and I write a lot in Python. > > Me too. > > Richard> I need the following features: > > Richard> 1) Tab completion, ideally Slime like. That is, when there's not > Richard> enough letters to unambiguously complete a symbol, I want it to > Richard> show a buffer (w/o taking the focus) w/ the possible > Richard> completions. In an ideal world, it would be able to complete > Richard> fo.ba to foo.bar. I imagine this would require quite tight > Richard> Emacs-Python integration. > > I know this is not what you want, but I use hippie expand (M-/) to cycle > through possible completions. It's not Python aware, but it is of some use. > > Richard> 2) Sending the toplevel definition (class or function) to the Python > Richard> buffer. > > I switched to IPython to have better interaction with a spawned Python. > > To use IPython you need to use the Python mode that is NOT the one from > (endorsed?) by the FSF. It gives you some completion (at least in the > *Python* buffer) and you can send pieces of the buffer to the python > process, via py-send-region (C-c |), py-execute-def-or-class (M-C-x), etc. > > Richard> 3) Hints on function/method arguments. IDLE has this done nearly > Richard> right, but the hints are a bit too intrusive for me. I would like to > Richard> see them in the minibuffer. > > I don't have this. > > Richard> 4) (optional) I would like to see the definition of a function > Richard> function or class by hitting M-. on its name. (I understand that > Richard> this may be impossible for methods, as Emacs would have to > Richard> automagically infer the type of the object). > > This is just an emacs tag file need. Have you googled for something like > emacs tags python? The issue of methods might be overcome by just moving > through tags with the same name. Yes, that requires _you_ to know when > you've hit the right thing. That's not optimal, but it's better than > nothing. Ideally you could send the definition to IPython, ask it for the > class info, and use that to jump to the right tag. > > Richard> I have tried a couple of times both python-modes (the one shipped w/ > Richard> Python and the one shipped w/ Emacs), pymacs and stuff like that... > Richard> And, as I said, never got it right. But, maybe I just cannot find the > Richard> way to configure it, and some configuration hints will be enough... > > If you have the time, please summarize your findings. The emacs/python > world has always seemed quite amorphous to me too. > > Terry > _______________________________________________ > help-gnu-emacs mailing list > help-gnu-emacs at gnu.org > http://lists.gnu.org/mailman/listinfo/help-gnu-emacs > -- A + Thierry Pub key: http://pgp.mit.edu From ivan.illarionov at gmail.com Wed Jan 30 21:52:43 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 30 Jan 2008 18:52:43 -0800 (PST) Subject: REALLY simple xml reader References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> Message-ID: >>> from xml.etree import ElementTree as et >>> from decimal import Decimal >>> >>> root = et.parse('file/with/your.xml') >>> debits = dict((debit.attrib['category'], Decimal(debit.find('amount').text)) for debit in root.findall('debit')) >>> >>> for cat, amount in debits.items(): ... print '%s: %s' % (cat, amount) ... food: 24.30 car: 909.56 medical: 188.20 savings: 25 withdrawal: 40 supplies: 10.58 clothes: 31.19 From george.sakkis at gmail.com Tue Jan 22 00:34:28 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 21 Jan 2008 21:34:28 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> Message-ID: <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> On Jan 22, 12:15 am, Paddy wrote: > On Jan 22, 3:20 am, Alan Isaac wrote:> I want to generate sequential pairs from a list. > <> > > What is the fastest way? (Ignore the import time.) > > 1) How fast is the method you have? > 2) How much faster does it need to be for your application? > 3) Are their any other bottlenecks in your application? > 4) Is this the routine whose smallest % speed-up would give the > largest overall speed up of your application? I believe the "what is the fastest way" question for such small well- defined tasks is worth asking on its own, regardless of whether it makes a difference in the application (or even if there is no application to begin with). Just because cpu cycles are cheap these days is not a good reason to be sloppy. Moreover, often the fastest pure Python version happens to be among the most elegant and concise, unlike other languages where optimization usually implies obfuscation. George From sathish.suray at gmail.com Sat Jan 26 08:30:57 2008 From: sathish.suray at gmail.com (sathish.suray at gmail.com) Date: Sat, 26 Jan 2008 05:30:57 -0800 (PST) Subject: nayanthara nake out Message-ID: nayanthara nake out namitha hot photos trisha bathing videos ____________________________ http://www.geocities.com/terfavet/ http://www.geocities.com/terfavet/ http://www.geocities.com/terfavet/ From george.sakkis at gmail.com Wed Jan 23 13:39:25 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 23 Jan 2008 10:39:25 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> Message-ID: On Jan 23, 4:37 am, Steven D'Aprano wrote: > On Tue, 22 Jan 2008 23:33:00 -0800, George Sakkis wrote: > > As I mentioned already, I consider the seeking of the most efficient > > solution a legitimate question, regardless of whether a "dumb" solution > > is fast enough for an application. Call it a "don't be sloppy" principle > > if you wish. > > Sure, by why do you limit "efficient" and "don't be sloppy" to mean > "write the fastest executing code you can, regardless of every other > trade-off"? I explicitly didn't limit sloppiness to inefficiency and mentioned it's a tradeoff: "... all else being equal or at least comparable (elegance, conciseness, readability, etc.). Of course it's a tradeoff; spending a week to save a few milliseconds on average is usually a waste for most applications, but being a lazy keyboard banger writing the first thing that pops into mind is not that good either." > But... do you write list.__len__() instead of len(list) to save a few > nanoseconds? No, of course not, it's not worth it, but that doesn't mean that being curious about what's faster and using timeit to find out is totally worthless. Another example: avoiding attribute lookups within a loop. I rarely write bar = foo.bar for i in big_list: bar(i) but it's valuable to know that it can make a difference when I really need it. Always writing the first thing that "just works" prevents one from even considering that there might be faster (or more elegant, more general, etc.) alternatives. George From deets at nospam.web.de Thu Jan 3 08:52:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 14:52:08 +0100 Subject: Treating a unicode string as latin-1 References: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Message-ID: <5u47k8F1gbcngU2@mid.uni-berlin.de> Simon Willison wrote: > Hello, > > I'm using ElementTree to parse an XML file which includes some data > encoded as cp1252, for example: > > Bob\x92s Breakfast > > If this was a regular bytestring, I would convert it to utf8 using the > following: > >>>> print 'Bob\x92s Breakfast'.decode('cp1252').encode('utf8') > Bob's Breakfast > > But ElementTree gives me back a unicode string, so I get the following > error: > >>>> print u'Bob\x92s Breakfast'.decode('cp1252').encode('utf8') > Traceback (most recent call last): > File "", line 1, in > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/encodings/cp1252.py", line 15, in decode > return codecs.charmap_decode(input,errors,decoding_table) > UnicodeEncodeError: 'ascii' codec can't encode character u'\x92' in > position 3: ordinal not in range(128) > > How can I tell Python "I know this says it's a unicode string, but I > need you to treat it like a bytestring"? I don't get your problem. You get a unicode-object. Which means that it got decoded by ET for you, as any XML-parser must do. So - why don't you get rid of that .decode('cp1252') and happily encode it to utf-8? Diez From steven.bethard at gmail.com Fri Jan 25 12:26:29 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 25 Jan 2008 10:26:29 -0700 Subject: find minimum associated values In-Reply-To: References: Message-ID: Alan Isaac wrote: > I have a small set of objects associated with a larger > set of values, and I want to map each object to its > minimum associated value. The solutions below work, > but I would like to see prettier solutions... > [snip] > > # arbitrary setup > keys = [Pass() for i in range(10)]*3 > vals = [random.random() for i in range(30)] > kv = zip(keys,vals) > random.shuffle(kv) > > #OBJECTIVE: > # find minimum val associated with each "key" in kv > [snip] > > print "method 3: defaultdict" > t=time.clock() > d = defaultdict(list) > for k,v in kv: > d[k].append(v) > for k in d: > d[k] = min(d[k]) > print time.clock()-t > print d This is definitely the approach I'd use. Seems "pretty" enough to me. ;-) STeVe From martin at v.loewis.de Tue Jan 1 16:28:03 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 01 Jan 2008 22:28:03 +0100 Subject: TK 8.5 In-Reply-To: <477A8345.5050303@codebykevin.com> References: <477A7066.9000402@v.loewis.de> <477A8345.5050303@codebykevin.com> Message-ID: <477AB063.4000606@v.loewis.de> >> Hence, there is no need to talk about this very much. That >> Python "supports" Tk 8.5 is too minor to mention - I think >> even Python 2.4 supports Tk 8.5. > > In terms of building and linking Python to Tk 8.5, this is certainly true. > > However, I think most people who ask about Python "supporting" Tk 8.5 > are probably asking how easily can the new features in Tk 8.5 be > accessed from Python, particularly the platform-specific themed widgets. I just found that there is also "middle ground": would most existing Tkinter applications work when Python was linked with Tk 8.5; in particular, would IDLE work? This is not the case for Python 2.5. Tk 8.5 changed the data types it returns from certain commands, affecting existing code. Likely, IDLE should work with Tk 8.5 in Python 2.6 and 3.0, but won't work for Python 2.5. > The answer to that question is, "At present, not very easily." There is > currently no support at all in lib-tk for themed widgets, for instance. > The external Tile.py module that I maintain at > http://tkinter.unpythonic.net/wiki/TileWrapper works well enough, but as > I am not the original author of this module, I cannot really offer it > for inclusion in the core Python distribution. As such, someone will > have to step up and write a new implememtation. That is of no concern for me whatsoever. Contributions are welcome. I know people are jumping up and down because of these themed widgets; the "I won't do anything actively" goes beyond that, though: even if existing widgets get new commands, or new widgets are added, then support for them in Tkinter is only added through user contributions. If "supports Tk 8.x" means "Tkinter has wrappers for all commands and options", then Tkinter has no support for any version of Tk, as a lot of commands remain unwrapped. Regards, Martin From grante at visi.com Thu Jan 24 15:28:50 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 24 Jan 2008 20:28:50 -0000 Subject: Ignore exceptions References: Message-ID: <13pht82n9il8k21@corp.supernews.com> On 2008-01-24, SMALLp wrote: > Hy. Hi. > Is there any way to make interrupter ignore exceptions. Nope. Either handle the exceptions or write code that doesn't generate exceptions. > I'm working on bigger project and i used to put try catch > blocks after writing and testing code You're getting unhandled exceptions after you've tested your code? I guess you need to do better testing. > what's boring and it's easy to make mistake. I remember of > something like that in C++ but I cant find anythin like that > for python. I should hope not. The Python language wouldn't _work_ if the VM ignored exceptions. Exceptions are used for all sorts of things besides errors (terminating a loop, exiting a program, etc.). If exceptions were ignored all sorts of things would stop working. -- Grant Edwards grante Yow! I'll show you MY at telex number if you show me visi.com YOURS ... From sturlamolden at yahoo.no Fri Jan 11 12:55:08 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 11 Jan 2008 09:55:08 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: On 10 Jan, 03:10, Steven D'Aprano wrote: > You are correct that optimizing Python is hard. However, in many cases, > the problem is not that Python is too slow, but the specific algorithm > chosen by the programmer is slow, e.g. no compiler optimization is going > to turn an O(n**2) algorithm into an O(1) algorithm. This is possibly the number one cause of 'slowness' complained about on mailing lists. > The Original Poster says it takes one or two seconds to process an > 800x600 GIF. That sounds believable: on my PC, it takes about five > seconds to loop over range(800*600) and do a tiny bit of processing. > Something like Psycho might speed that up a lot, possibly by an order of > magnitude or two. It seems the code he is referring to is doing k-means clustering on each frame. The clustering is done by from SciPy's cluster module, which is doing 'vector quantitization'. The algorithm is written in plain C. It is not Python that is slow. It is the amount of processing done on each frame. As the bottleneck is already in C, it cannot be done any faster without radically changing the algorithm and/or the hardware. From zentraders at gmail.com Wed Jan 9 15:18:42 2008 From: zentraders at gmail.com (Zentrader) Date: Wed, 9 Jan 2008 12:18:42 -0800 (PST) Subject: executing newgrp from python in current shell possible? References: Message-ID: <755e7fd2-5e4a-4a4b-b848-a5e4ca756087@l6g2000prm.googlegroups.com> On Jan 9, 5:56?am, Svenn Are Bjerkem wrote: >I have been looking for a way to execute this command > as a part of a script, but it seems that the changes are only valid in > the context of the script and when the script exits, the current shell > still have the original "users" group setting. I don't think you would want it any other way. Would you want a user to be able to change the group and have it remain permanently? Who's going to remember whether they were last in "A" or "B", and it opens up oportunities for the practical joker when you go to the restroom and leave the terminal on. Put the "change the group" code into a separate function in a separate file (with only you as the owner) and call it whenever you want to change groups. From toby at tobiah.org Wed Jan 16 15:14:02 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 16 Jan 2008 12:14:02 -0800 Subject: import from question In-Reply-To: <87tzleb2st.fsf@benfinney.id.au> References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> <478d04d4$0$26042$88260bb3@free.teranews.com> <87tzleb2st.fsf@benfinney.id.au> Message-ID: <478E658A.9070003@tobiah.org> Ben Finney wrote: > Tobiah writes: > >> This is a little surprising. So "from mod import *" really copies >> all of the scalars into new variables in the local namespace. > > No. Nothing is copied. All the objects (remembering that in Python, > *everything* is an object) created by the code in module 'mod' are > given names in the current namespace. Yeah, copied. Just as in: >>> a = 3 >>> b = a >>> a = 5 >>> b 3 >>> given b.py: ########################## thing = 0 ########################## and a.py: ########################## from b import * import b print thing print b.thing b.thing = 1 print b.thing print thing ########################### 0 0 1 0 -- Posted via a free Usenet account from http://www.teranews.com From wim at fixnum.org Tue Jan 22 17:55:02 2008 From: wim at fixnum.org (Wim Vander Schelden) Date: Tue, 22 Jan 2008 23:55:02 +0100 Subject: translating Python to Assembler In-Reply-To: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: Python modules and scripts are normally not even compiled, if they have been, its probably just the Python interpreter packaged with the scripts and resources. My advice is that if you want to learn Python, is that you just read a book about it or read only resources. Learning Python from assembler is kind of... strange. Not only are you skipping several generations of programming languages, spanned over a period of 40 years, but the approach to programming in Python is so fundamentally different from assembler programming that there is simply no reason to start looking at if from this perspective. I truly hope you enjoy the world of high end programming languages, but treat them as such. Looking at them in a low-level representation or for a low-level perspective doesn't bear much fruits. Kind regards, Wim On 1/22/08, over at thepond.com wrote: > > My expertise, if any, is in assembler. I'm trying to understand Python > scripts and modules by examining them after they have been > disassembled in a Windows environment. > > I'm wondering if a Python symbols file is available. In the Windows > environment, a symbol file normally has a PDB extension. It's a little > unfortunate that Python also uses PDB for its debugger. Google, for > whatever reason, wont accept queries with dots, hyphens, etc., in the > query line. For example a Google for "python.pdb" returns +python > +pdb, so I get a ridiculous number of returns referring to the python > debugger. I have mentioned this to Google several times, but I guess > logic isn't one of their strong points. :-) > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Jan 30 07:58:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jan 2008 04:58:27 -0800 (PST) Subject: HI all References: <1b6a8d39-8077-4d4e-b05f-1e0037472ed8@d4g2000prg.googlegroups.com> Message-ID: <054b4b69-a415-4e8a-8651-c3e3f93ad4d3@c4g2000hsg.googlegroups.com> On 30 ene, 09:26, tiwarishra... at gmail.com wrote: > I am shravan tiwari, i want to know that how i'll run any python > file(*.py) on command prompt r python GUI. > i tried this > > python test.py > > but i have got error, syntax error. so can i get the solution. This is the right way to run it. If you get a syntax error, it means that test.py is not correctly written. Fix the code and try again. -- Gabriel Genellina From stephan.diehl at gmx.net Mon Jan 21 12:38:16 2008 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Mon, 21 Jan 2008 18:38:16 +0100 Subject: Berlin (Germany) Python User Group is meeting on 23.1. Message-ID: The Berlin Python User Group is meeting on the 23.1. at newthinking store at 7pm. All details can be found at http://wiki.python.de/User_Group_Berlin. The Berlin Python User Group is planning to meet every two month to talk about Python. Most talking will be done in german, but I can assure you that english could be spoken as well, if the need arises... From nikbaer at gmail.com Mon Jan 28 21:03:09 2008 From: nikbaer at gmail.com (nik) Date: Mon, 28 Jan 2008 18:03:09 -0800 (PST) Subject: ISO with timezone Message-ID: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Hi, How does one express the time in ISO format with the timezone designator? what I want is YYYY-MM-DDThh:mm:ss.sTZD >From the documentation I see: >>> from datetime import tzinfo, timedelta, datetime >>> class TZ(tzinfo): ... def utcoffset(self, dt): return timedelta(minutes=-399) ... >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') '2002-12-25 00:00:00-06:39' and I've also figured out: >>>datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3] '2008-01-23T11:22:54.130' But can't figure out how to fit them together. Thank you, Nik From mwm at mired.org Fri Jan 11 11:51:17 2008 From: mwm at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 11:51:17 -0500 Subject: Magic function In-Reply-To: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> Message-ID: <20080111115117.134ad8be@mbook.mired.org> On Fri, 11 Jan 2008 08:29:18 -0800 (PST) dg.google.groups at thesamovar.net wrote: > Hi all, > > I'm part of a small team writing a Python package for a scientific > computing project. The idea is to make it easy to use for relatively > inexperienced programmers. As part of that aim, we're using what we're > calling 'magic functions', and I'm a little bit concerned that they > are dangerous code. I'm looking for advice on what the risks are (e.g. > possibility of introducing subtle bugs, code won't be compatible with > future versions of Python, etc.). > > Quick background: Part of the way our package works is that you create > a lot of objects, and then you create a new object which collects > together these objects and operates on them. We originally were > writing things like: > > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > bigobj = Bigobj(objects=[obj1,obj2]) > bigobj.run() > > This is fine, but we decided that for clarity of these programs, and > to make it easier for inexperienced programmers, we would like to be > able to write something like: > > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > run() > > The idea is that the run() function inspects the stack, and looks for > object which are instances of class Obj, creates a Bigobj with those > objects and calls its run() method. > > So, any comments on that approach? The basic idea is ok, but looking at the stack makes me a bit nervous. That makes the code complicated, and probably fragile in the face of changing python versions. The unittest module does much the same thing - you run unittest.main, and it runs all the tests in any TestCase subclass in your module (assuming you didn't do something to limit it). However, it does it by examining the module, not the stack. The real difference is that your "magic" classes have to be global to your module. On the other hand, it provides some nice tools to let you partition things, so you can easily run subsets of the classes from the command line. It's probably worth a look. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From arnodel at googlemail.com Mon Jan 21 12:11:55 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 21 Jan 2008 09:11:55 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: <3f9c0e91-c493-4a2d-8ef3-1a081602e8e8@q77g2000hsh.googlegroups.com> On Jan 21, 9:01?am, dg.google.gro... at thesamovar.net wrote: > Arnaud: I haven't had time to play with your solution yet - how quick > does it run? Ok I've done some quick timings, it's faster than I remembered it: numbers = [2, 4, 5, 8, 25] target = 758 Average time to find (1) best solution (in terms of length of repr): 0.0418s (2) first solution: 0.00421s (2.2GHz MacBook Pro, done with the timeit module) (1) involves working out all possible calculations with the 6 numbers. -- Arnaud From kyosohma at gmail.com Fri Jan 4 09:12:22 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 4 Jan 2008 06:12:22 -0800 (PST) Subject: Who's to blame? References: <92dfc2fc-0677-43c0-b34f-4f240fa40205@e4g2000hsg.googlegroups.com> <255d32d0-43f5-4d34-a074-b87082dc6043@e23g2000prf.googlegroups.com> <2b076973-b132-4666-a163-b80bcbeaedfb@s8g2000prg.googlegroups.com> Message-ID: <8749bb13-4f31-4cfc-8878-cc19bd417275@f10g2000hsf.googlegroups.com> On Jan 4, 3:35 am, Nicola Musatti wrote: > Hallo, Mike. > First of all, thanks to both you and Rob for your answers. I now see > that the wxPython group would have been a better place to post to, all > the more so given the tight connection between the wxPython and > wxWidgets projects, of which at first I wasn't aware. > > On Jan 3, 8:19 pm, kyoso... at gmail.com wrote: > [...] > > > > > I've never created a modal dialog like this. Instead, I follow the > > wxPython in Action book examples (most of the time), which would do a > > yes/no dialog like this: > > > > > > dlg = wx.MessageDialog(None, 'Some Message', 'A Message Box', > > wx.YES_NO | wx.QUESTION) > > retCode = dlg.ShowModal() > > if retCode == wx.ID_YES: > > # do something > > print 'yes' > > else: > > # do something else > > print 'no' > > dlg.Destroy() > > > > > Actually my example started out as something like > > if wx.MessageBox(message="Some message", caption="Some caption", > style=wx.YES|wx.NO) == wx.YES: > pass > > I had to change it because the actual message can become very long, so > I assembled a dialog with a scrollable text field. Maybe I'm expecting > to much of wxStdDialogButtonSizer, but I still feel that given that > both your method and mine above work straight away, it should provide > the same behaviour with Yes/No buttons as with OK/Cancel ones. > > Cheers, > Nicola Musatti Nicola, I have sub-classed wx.Dialog to do my own custom modal dialogs as well. You can use sizers and put whatever widgets you want onto it that way. Just make sure that when you create the Yes/No buttons, you give them the wx.ID_YES or wx.ID_NO ids, rather than -1 or wx.ID_ANY. yesBtn = wx.Button(parent, wx.ID_YES, 'Yes') noBtn = wx.Button(parent, wx.ID_NO, 'No') Mike From grante at visi.com Sat Jan 5 11:13:22 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 05 Jan 2008 16:13:22 -0000 Subject: Question on os.tempnam() vulnerability References: <13nt81gftkfa32d@corp.supernews.com> <13nv5m68qeknk1f@corp.supernews.com> <477FA9B5.9050609@v.loewis.de> Message-ID: <13nvb525r3m6m39@corp.supernews.com> On 2008-01-05, Martin v. L?wis wrote: >> I know. That's the point of my question: how do you do that >> under Windows? > > When you create a new process, you have the option to inherit > file handles to the new process. So the parent should open the > file, and then inherit the handle to the new process. That's an answer, though not for the question I asked. The program that's being run requires a that it be passed a filename on the command-line. I'm not writing the program that is to open the file. If I were, I'd just make it a python module and call it instead of running it in a separate process. > IOW, it's the same approach as on Unix. Not really. Under Unix you can safely create a temp file with a name that can be used to open the file. I asked about a way to do that under Windows as well. -- Grant Edwards grante Yow! ... I live in a at FUR-LINE FALLOUT SHELTER visi.com From nabble.dserodio at neverbox.com Thu Jan 10 13:24:59 2008 From: nabble.dserodio at neverbox.com (Daniel Serodio) Date: Thu, 10 Jan 2008 10:24:59 -0800 (PST) Subject: subprocess "handle is invalid" error In-Reply-To: <46266279.5050105@ctypes.org> References: <132cdrpqsmnvpa7@corp.supernews.com> <46266279.5050105@ctypes.org> Message-ID: <14740517.post@talk.nabble.com> Thomas Heller-2 wrote: > > Grant Edwards schrieb: > > [snip] > >> >> Traceback (most recent call last): >> File "surfedit.py", line 28, in ? >> File "Gnuplot\_Gnuplot.pyc", line 178, in __init__ >> File "Gnuplot\gp_win32.pyc", line 117, in __init__ >> File "subprocess.pyc", line 533, in __init__ >> File "subprocess.pyc", line 607, in _get_handles >> File "subprocess.pyc", line 634, in _make_inheritable >> WindowsError: [Errno 6] The handle is invalid >> >> How does one troubleshoot errors that happen three layers deep >> in the subprocess module? >> > > I think this is a subprocess bug. It is often attributed to py2exe > because > usually developers do never run the script in pythonW.exe instead of > python.exe, > and later build a *windows* program with py2exe (the *windows* program has > no > console, and that triggers the bug). > > [snip] > > I thought that this bug was fixed in Python2.5.1 (the release candidate), > but it seems it wasn't. The bug is at > http://sourceforge.net/tracker/index.php?func=detail&aid=1124861&group_id=5470&atid=105470 > > If all this is correct, I hope that someone adds a section to the py2exe > wiki; > and reopens the above bug report. > > Thomas > I've been bitten by this same bug in 2.5.1, and the bug you linked to (which is now @ http://bugs.python.org/issue1124861) is still marked as fixed. I've tried to reopen it but it seems only the reporter (or some "admin" user) is able to do it. -- View this message in context: http://www.nabble.com/subprocess-%22handle-is-invalid%22-error-tp10060967p14740517.html Sent from the Python - python-list mailing list archive at Nabble.com. From gherron at islandtraining.com Wed Jan 23 04:06:39 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 23 Jan 2008 01:06:39 -0800 Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? In-Reply-To: References: Message-ID: <4797039F.9080702@islandtraining.com> Kristian Domke wrote: > Hello to all > > I am trying to learn python at the moment studying an example program > (cftp.py from the twisted framework, if you want to know) > > There I found a line > > foo = (not f and 1) or 0 > > In this case f may be None or a string. > > If I am not wrong here, one could simply write > > foo = not f > > because if f = None: > > (not f) = true, > (true and 1) = true, > (true or 0) = true > > or if f = 'bar' > > (not f) = false > (false and 1) = false > (false or 0) = false > > So why bothering with the longer version? > Good catch! It's my guess that you've found a way to improve on a bit of carelessly written code. However there *is* a (subtle) difference between not f and (not f and 1) or 0 The first produces a boolean value, and the second produces an int value, but since one is a subclass of the other, you'd have to write quite perverse code care about the difference. Gary Herron > I hope, I made clear, what I want... > Quite. > CU > > Kristian > From donn.ingle at gmail.com Mon Jan 14 03:19:30 2008 From: donn.ingle at gmail.com (Donn) Date: Mon, 14 Jan 2008 10:19:30 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A77F0.4000502@v.loewis.de> References: <200801132048.08966.donn.ingle@gmail.com> <478A77F0.4000502@v.loewis.de> Message-ID: <200801141019.30792.donn.ingle@gmail.com> > Can you please type > paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] > f = open(paf, "r") I think I was getting a ghost error from another try somewhere higher up. You are correct, this does open the file - no matter what the locale is. I have decided to keep the test for a decode error because files created under different locales should not be written-to under the current one. I don't know if one can mix encodings in a single text file, but I don't have time to find out. It is getting messy with my test files created in differing locales, and my code changing so quickly. > See above. The encoding in codecs.open has no effect at all on > the file name; it only talks about the file content. Thanks, I suspected as much but it's a subtle thing. Best, \d -- "It is almost as if the human brain were specifically designed to misunderstand Darwinism, and to find it hard to believe.." -- Richard Dawkins Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From python.list at tim.thechases.com Wed Jan 9 12:49:36 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 09 Jan 2008 11:49:36 -0600 Subject: How to get memory size/usage of python object In-Reply-To: References: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> Message-ID: <47850930.8070309@tim.thechases.com> Sion Arrowsmith wrote: > Santiago Romero wrote: >> Is there a way to check the REAL size in memory of a python object? >> >> Something like >> >>> print sizeof(mylist) >> [ ... ] > > Would you care to precisely define "REAL size" first? Consider: > >>>> atuple = (1, 2) >>>> mylist = [(0, 0), atuple] > > Should sizeof(mylist) include sizeof(atuple) ? > >>>> del atuple > > What about now, when mylist has the only reference to the (1, 2) > object that also used to be referred to as atuple? or add to the mix >>> mylist = [(0,0), atuple] * 1000 where the same atuple is referenced 1000 times. And then if you >>> del atuple defining "sizeof()" becomes even more peculiar if you have a thousand things that "have" the same item that nothing else claims ownership of. Or, if you have this: >>> alist = [1,2,3] >>> mylist = ['a', 'b', alist] * 10 >>> s1 = sizeof(mylist) >>> alist.append(42) >>> s2 = sizeof(mylist) should s1==s2 ? -tkc From nanjundi at gmail.com Fri Jan 11 14:28:08 2008 From: nanjundi at gmail.com (Nanjundi) Date: Fri, 11 Jan 2008 11:28:08 -0800 (PST) Subject: split parameter line with quotes References: Message-ID: On Jan 11, 1:50 pm, teddyber wrote: > Hello, > > first i'm a newbie to python (but i searched the Internet i swear). > i'm looking for some way to split up a string into a list of pairs > 'key=value'. This code should be able to handle this particular > example string : > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > i know i can do that with some regexp (i'm currently trying to learn > that) but if there's some other way... > > thanks This is unconventional and using eval is not SAFE too. >>> s = 'qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,3des",maxbuf=1024,charset="utf-8",algorithm="md5-sess"' >>> d = eval(' dict(%s)' % s) >>> d.items() [('algorithm', 'md5-sess'), ('maxbuf', 1024), ('charset', 'utf-8'), ('cipher', 'rc4-40,rc4-56,rc4,des,3des'), ('qop', 'auth,auth-int,auth- conf')] >>> for k,v in d.iteritems(): print k, '=', v ... algorithm = md5-sess maxbuf = 1024 charset = utf-8 cipher = rc4-40,rc4-56,rc4,des,3des qop = auth,auth-int,auth-conf For safe eval, take a look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 -N From te_rem_ra_ove_an_forspam at consistent.org Thu Jan 31 20:47:36 2008 From: te_rem_ra_ove_an_forspam at consistent.org (Terran Melconian) Date: Thu, 31 Jan 2008 19:47:36 -0600 Subject: Naive idiom questions References: <60ev9jF1qdpctU1@mid.individual.net> Message-ID: On 2008-01-31, Bjoern Schliessmann wrote: > Did you measure such impact on your application? > Also see http://www.skymind.com/~ocrow/python_string/ I don't have a real application yet. That was, in fact, exactly the web page which informed me that the MutableString class was not implemented with mutable primitives. > Look at "lower level" HLLs. In C++, you'd have to use Well, in C++, I would use something like: string sa[5][5]; string has a default constructor, so I'll get a 5x5 array of empty strings. Alternatively, I could use boost::array if I wanted container semantics. If I needed something dynamically resizable, I could use: vector > vs(5); and then I could append elements to each one. If I wanted needed to resize them all to 5 immediately, I would have to loop: for (vector >::iterator i = vs.begin(); i != vs.end(); i++) i->resize(5); and that isn't particularly concise or elegant either, but the odds of needing them to start out at size 5 and *also* be resizable later are low for most applications. > Personally, I like list comprehensions much better. Perhaps the take-away lesson is that comprehensions should be seen as a very fundamental operation in Python, and I have the wrong idea by considering them advanced. From http Tue Jan 22 15:00:47 2008 From: http (Paul Rubin) Date: 22 Jan 2008 12:00:47 -0800 Subject: A global or module-level variable? References: <7637fd0b-961e-4730-abd8-96e85c907082@i72g2000hsd.googlegroups.com> Message-ID: <7xwsq1tyts.fsf@ruckus.brouhaha.com> Bret writes: > nextport=42000 > > def getNextPort(): > nextport += 1 > return nextport If you have to do it that way, use: def getNextPort(): global nextport nextport += 1 return nextport the global declaration stops the compiler from treating nextport as local and then trapping the increment as to an uninitialized variable. From rupert.thurner at gmail.com Sun Jan 20 06:40:39 2008 From: rupert.thurner at gmail.com (rupert.thurner) Date: Sun, 20 Jan 2008 03:40:39 -0800 (PST) Subject: finding memory leak in edgewall trac 0.11 References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> Message-ID: <0c6fc35d-91d2-4767-968d-e6eb56096eba@z17g2000hsg.googlegroups.com> On Jan 19, 10:31?pm, Christian Heimes wrote: > Jeroen Ruigrok van der Werven wrote: > > > Hi Christian, > > > -On [20080119 16:16], Christian Heimes (li... at cheimes.de) wrote: > >> I forgot one important point in my reply. The GC module contains some > >> useful methods for debugging. Check gc.garbage. It should be empty. > > > Yeah, we're messing around with that stuff as well as many other ways of > > trying to track issues, but it can really be looking for a needle in a > > haystack to be honest. > > There's so much output that, I guess, make sense only when you're semi-deep > > into the Python internals to even make heads or tails out of it. =\ > > And even third-party code is not helping much to reduce the clutter and > > provide insight. > > Under normal circumstances gc.garbage should be an empty list. In > general it's a bad sign if gc.garbage contains lots of objects. > > I found several potential leaks in trac: > > $ find -name \*.py | xargs grep __del__ > ./trac/versioncontrol/svn_fs.py: ? ?def __del__(self): > ./trac/versioncontrol/svn_fs.py: ? ?def __del__(self): > ./trac/db/pool.py: ? ?def __del__(self): > > $ find -name \*.py | xargs grep frame > ./trac/web/main.py: > [...] > ./trac/core.py: ? ? ? ?frame = sys._getframe(1) > ./trac/core.py: ? ? ? ?locals_ = frame.f_locals > > I recommend that you either replace __del__ with a weak reference > callback or to remove it. Referencing a frame, traceback or f_locals is > going to leak, too. You *must* explicitly del every frame and locals > variable. > > Christian many thanks! as the main change was replacing clearsilver with genshi, this means one could do the same thing with genshi, http://genshi.edgewall.org/? $ find -name \*.py | xargs grep frame ./genshi/filters/html.py: 'dir', 'disabled', 'enctype', 'for', 'frame', 'headers', 'height', ./genshi/input.py: _EMPTY_ELEMS = frozenset(['area', 'base', 'basefont', 'br', 'col', 'frame', ./genshi/output.py: 'http://www.w3.org/TR/html4/frameset.dtd' ./genshi/output.py: 'http://www.w3.org/TR/xhtml1/DTD/xhtml1- frameset.dtd' ./genshi/output.py: * "html-transitional" for the HTML 4.01 frameset DTD ./genshi/output.py: * "xhtml-frameset" for the XHTML 1.0 frameset DTD ./genshi/output.py: 'html-frameset': DocType.HTML_FRAMESET, ./genshi/output.py: 'xhtml-frameset': cls.XHTML_FRAMESET, ./genshi/output.py: _EMPTY_ELEMS = frozenset(['area', 'base', 'basefont', 'br', 'col', 'frame', ./genshi/template/base.py: _ctxt2dict = lambda ctxt: ctxt.frames[0] ./genshi/template/base.py: self.frames = deque([data]) ./genshi/template/base.py: self.pop = self.frames.popleft ./genshi/template/base.py: self.push = self.frames.appendleft ./genshi/template/base.py: return repr(list(self.frames)) ./genshi/template/base.py: for frame in self.frames: ./genshi/template/base.py: if key in frame: ./genshi/template/base.py: del frame[key] ./genshi/template/base.py: value, frame = self._find(key) ./genshi/template/base.py: if frame is None: ./genshi/template/base.py: self.frames[0][key] = value ./genshi/template/base.py: """Retrieve a given variable's value and the frame it was found in. ./genshi/template/base.py: for frame in self.frames: ./genshi/template/base.py: if key in frame: ./genshi/template/base.py: return frame[key], frame ./genshi/template/base.py: for frame in self.frames: ./genshi/template/base.py: if key in frame: ./genshi/template/base.py: return frame[key] ./genshi/template/base.py: for frame in self.frames: ./genshi/template/base.py: keys += [key for key in frame if key not in keys] ./genshi/template/directives.py: # Store the function reference in the bottom context frame so that it ./genshi/template/directives.py: ctxt.frames[-1][self.name] = function ./genshi/template/directives.py: frame = {} ./genshi/template/directives.py: ctxt.push(frame) ./genshi/template/tests/directives.py: frame = exc_traceback.tb_next ./genshi/template/tests/directives.py: frames = [] ./genshi/template/tests/directives.py: while frame.tb_next: ./genshi/template/tests/directives.py: frame = frame.tb_next ./genshi/template/tests/directives.py: frames.append(frame) ./genshi/template/tests/directives.py: frames[-1].tb_frame.f_code.co_name) ./genshi/template/tests/directives.py: frames[-1].tb_frame.f_code.co_filename) ./genshi/template/tests/directives.py: self.assertEqual(2, frames[-1].tb_lineno) ./genshi/template/tests/eval.py: frame = exc_traceback.tb_next ./genshi/template/tests/eval.py: frames = [] ./genshi/template/tests/eval.py: while frame.tb_next: ./genshi/template/tests/eval.py: frame = frame.tb_next ./genshi/template/tests/eval.py: frames.append(frame) ./genshi/template/tests/eval.py: frames[-3].tb_frame.f_code.co_name) ./genshi/template/tests/eval.py: frames[-3].tb_frame.f_code.co_filename) ./genshi/template/tests/eval.py: self.assertEqual(50, frames[-3].tb_lineno) ./genshi/template/tests/eval.py: frame = exc_traceback.tb_next ./genshi/template/tests/eval.py: while frame.tb_next: ./genshi/template/tests/eval.py: frame = frame.tb_next ./genshi/template/tests/eval.py: code = frame.tb_frame.f_code ./genshi/template/tests/eval.py: self.fail("never found the frame I was looking for") ./genshi/template/tests/eval.py: self.assertEqual(50, frame.tb_lineno) ./genshi/template/tests/eval.py: frame = exc_traceback.tb_next ./genshi/template/tests/eval.py: while frame.tb_next: ./genshi/template/tests/eval.py: frame = frame.tb_next ./genshi/template/tests/eval.py: code = frame.tb_frame.f_code ./genshi/template/tests/eval.py: self.fail("never found the frame I was looking for") ./genshi/template/tests/eval.py: self.assertEqual(50, frame.tb_lineno) rupert From jmgimeno at gmail.com Mon Jan 21 02:45:23 2008 From: jmgimeno at gmail.com (babui) Date: Sun, 20 Jan 2008 23:45:23 -0800 (PST) Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> Message-ID: <88dc9784-6d06-46cc-980e-0fe233912572@l32g2000hse.googlegroups.com> On 21 ene, 08:41, Santiago Romero wrote: > Hi ... > > I have the following DNS MX records info: > > domain.com > preference 10 host mx1.domain.com > preference 30 host anotherhost.domain.com > preference 20 host mx2.domain.com > And finally ... do you think there is a better python structure to > store this data and sort it in a more easy way? Why don't you use a list of tuples? L = [ (10, "mx1.domain.com"), (30, "anotherhost.domain.com", (20, "mx2.domain.com") ] and L.sort() sorts the list !!! Juan M. Gimeno > Thanks. From mfrancis at tcore.org Fri Jan 11 16:12:17 2008 From: mfrancis at tcore.org (Monica Francis) Date: Fri, 11 Jan 2008 13:12:17 -0800 Subject: Rapid desktop application development Message-ID: <404C1A9C83B11D41BEC3944A111FB28F62A3DD@tlcsmail.int-tlcssac.org> I am looking for Stephan Eilert who was an exchange student from Germany to the U.S. (Northern California) in the 1980's. Could you possibly be one in the same? Monica Erwin-Francis -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Sun Jan 27 08:02:38 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 27 Jan 2008 05:02:38 -0800 (PST) Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> <7xy7acsx2l.fsf@ruckus.brouhaha.com> <8ddebd68-43dc-4320-86e1-887aadff4af3@d70g2000hsb.googlegroups.com> <7xmyqs722t.fsf@ruckus.brouhaha.com> <13pnbp9l8lk1j8b@corp.supernews.com> Message-ID: On Jan 27, 11:32?am, Arnaud Delobelle wrote: [...] > > simple_posmax is more than 3x faster on my machine. ?It's not > surprising as even though the list is walked twice, it is all done in > C and no new objects have to be created. Then only non-C bit is when > the result of max(l) is fed to l.index(). Of course that's incorrect in general: if comparison functions between objects in l are python functions then some bytecode will be run and some new objects may be created. But in most cases I think it stands true. -- Arnaud From steven.bethard at gmail.com Mon Jan 28 10:45:54 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 28 Jan 2008 08:45:54 -0700 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > Sligthly improved (not for performance! but signature-preserving and > looks for default values) > > from functools import wraps > from inspect import getargspec > from itertools import izip, chain > > def autoassign(*names): > def decorator(f): > fargnames, _, _, fdefaults = getargspec(f) > defaults = [(n,v) for (n,v) > in izip(reversed(fargnames), reversed(fdefaults)) > if n in names] > @wraps(f) > def decorated(self, *args, **kwargs): > self.__dict__.update(defaults) > for name, arg in chain(izip(fargnames, args), > kwargs.iteritems()): > if name in names: > setattr(self, name, arg) > return f(self, *args, **kwargs) > return decorated > return decorator > > class Test(object): > @autoassign('foo', 'bar') > def __init__(self, foo, bar=3, baz=6): > print 'baz =', baz > > t = Test(1, 2, 6) > u = Test(foo=8) > > print t.foo # 1 > print t.bar # 2 > > print u.foo # 8 > print u.bar # 3 (default) You should definitely post this to the cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python STeVe From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 06:00:44 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 12:00:44 +0100 Subject: adding methods at runtime In-Reply-To: <940fcb28-764e-46ab-a627-aff513e009e1@j78g2000hsd.googlegroups.com> References: <940fcb28-764e-46ab-a627-aff513e009e1@j78g2000hsd.googlegroups.com> Message-ID: <47874c50$0$13390$426a34cc@news.free.fr> zslevi at gmail.com a ?crit : > Can I access the class attributes from a method added at runtime? Of course. > (My > experience says no.) So there's something wrong with your experience !-) > I experimented with the following code: > > > class myclass(object): > myattr = "myattr" > > instance = myclass() > def method(x): > print x > > instance.method = method As Marc pointed out, you're not adding a method but a function. What you want is: def method(self, x): print "x : %s - myattr : %s" % (x, self.myattr) import new instance.method = new.instancemethod(method, instance, myclass) Note that this is only needed for per-instance methods - if you want to add a new method for all instances, you just set the function as attribute of the class. The lookup mechanism will then invoke the descriptor protocol on the function object, which will return a method (FWIW, you have to do it manually on per-instance methods because the descriptor protocol is not invoked on instance attributes, only on class attributes). HTH From arnodel at googlemail.com Wed Jan 23 02:16:37 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 23:16:37 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> Message-ID: On Jan 22, 10:56?pm, dg.google.gro... at thesamovar.net wrote: > Arnaud and Terry, > > Great solutions both of you! Much nicer than mine. I particularly like > Arnaud's latest one based on folding because it's so neat and > conceptually simple. For me, it's the closest so far to my goal of the > most elegant solution. Thanks! It's a great little problem to think of and it helps bring more fun to this list. Sadly work takes over fun during the week, but I will try to improve it at the weekend. > So anyone got an answer to which set of numbers gives the most targets > from 100 onwards say (or from 0 onwards)? Is Python up to the task? I bet it is :) > A thought on that last one. Two ways to improve speed. First of all, > you don't need to rerun from scratch for each target Yes, I've been doing this by writing an 'action' (see my code) that takes note of all reached results. > Secondly, you > can try multiple different sets of numbers at the same time by passing > numpy arrays instead of single values (although you have to give up > the commutativity and division by zero optimisations). Have to think about this. -- Arnaud From cokofreedom at gmail.com Thu Jan 17 09:57:46 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 17 Jan 2008 06:57:46 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <478f699d$0$17578$426a74cc@news.free.fr> Message-ID: > > > Yes, small typo there. > > > Okey, so if my array1 is has 4 elements, and array2 has 6, it won't > > loop trough the last 2 in array2? How do I make it do that? > > > Please gentlemen: Python has no builtin type named 'array', so > s/array/list/g > > > Just pad your shortest list. I agree, but was merely showing how he would use the variables he had given. From nospam at invalid.com Wed Jan 9 23:45:34 2008 From: nospam at invalid.com (Jack) Date: Wed, 9 Jan 2008 20:45:34 -0800 Subject: Using a proxy with urllib2 Message-ID: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> I'm trying to use a proxy server with urllib2. So I have managed to get it to work by setting the environment variable: export HTTP_PROXY=127.0.0.1:8081 But I wanted to set it from the code. However, this does not set the proxy: httpproxy = '127.0.0.1:3129' proxy_support = urllib2.ProxyHandler({"http":"http://" + httpproxy}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) urllib2.install_opener(opener) I'm using it from a web.py URL handler file, not sure if it matters. I have another question though. It seems that using either of the methods above, the proxy will be global. What if I want to use a proxy with one site, but not with another site? Or even use a proxy for some URLs but not others? The proxy having to be global is really not convenient. Is there any way to do per-fetch proxy? From dg.google.groups at thesamovar.net Mon Jan 21 04:15:50 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Mon, 21 Jan 2008 01:15:50 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Message-ID: Decided I may as well post my other solution while I'm at it. The neat trick here is redefining the add, mul, etc. functions so that they raise exceptions for example if x>y then add(x,y) raises an exception which is handled by the search algorithm to mean don't continue that computation - this stops you from having to evaluate x+y AND y+x, etc. sub = lambda x,y:x-y def add(x,y): if x<=y: return x+y raise ValueError def mul(x,y): if x<=y or x==1 or y==1: return x*y raise ValueError def div(x,y): if not y or x%y or y==1: raise ValueError return x/y add.disp = '+' mul.disp = '*' sub.disp = '-' div.disp = '/' standard_ops = [ add, sub, mul, div ] def strexpression(e): if len(e)==3: return '('+strexpression(e[1])+e[0].disp+strexpression(e[2]) +')' elif len(e)==1: return str(e[0]) # I don't like this function, it's nice and short but is it clear # what it's doing just from looking at it? def expressions(sources,ops=standard_ops,minremsources=0): for i in range(len(sources)): yield ([sources[i]],sources[:i]+sources[i+1:],sources[i]) if len(sources)>=2+minremsources: for e1, rs1, v1 in expressions(sources,ops,minremsources+1): for e2, rs2, v2 in expressions(rs1,ops,minremsources): for o in ops: try: yield ([o,e1,e2],rs2,o(v1,v2)) except ValueError: pass def findfirsttarget(target,sources,ops=standard_ops): for e,s,v in expressions(sources,ops): if v==target: return strexpression(e) return None print findfirsttarget(923,[7,8,50,8,1,3]) gives: ((7*(((8*50)-1)/3))-8) Dan Goodman From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Jan 27 05:37:50 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 27 Jan 2008 11:37:50 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <60357uF1perd0U1@mid.individual.net> over at thepond.com wrote: > hehe...which part am I kidding about? The explanation was for > someone who thought python scripts were translated directly by the > processor. Who might this have been? Surely not Tim. > I have already disassembled a pyc file as a binary file. Have you? How's it look? > Maybe I was using the term assembler too broadly. A binary > compiled from an assembler source would look similar in parts to > what I disassembled. What is this supposed to mean? > That's not the point, however. I'm trying to say that a processor > cannot read a Python script, and since the Python interpreter as > stored on disk is essentially an assembler file, It isn't; it's an executable. > any Python script must be sooner or later be converted to > assembler form in order to be read by its own interpreter. This "assembler form" is commonly referred to as "Python byte code". > Whatever is typed in a Python script must be converted to binary > code. That, however, is true, though blurred. Regards, Bj?rn -- BOFH excuse #120: we just switched to FDDI. From martin at v.loewis.de Mon Jan 7 17:06:13 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Jan 2008 23:06:13 +0100 Subject: What is the encoding of __file__? In-Reply-To: <736ae822-54a9-4ee6-91fe-92c2c6eb43db@21g2000hsj.googlegroups.com> References: <736ae822-54a9-4ee6-91fe-92c2c6eb43db@21g2000hsj.googlegroups.com> Message-ID: <4782A255.8070604@v.loewis.de> > can someone quickly tell me what the encoding of __file__ is? I can't > find it in the documentation. > > BTW, I'm using Python 2.5.1 on WIndows XP and Vista. It's platform-specific - the same encoding that is used for file names (i.e. sys.getfilesystemencoding()). On Windows, it will be "mbcs", which in turn is installation-specific - on Western European/US installations, it's "windows-1252". Regards, Martin From mnordhoff at mattnordhoff.com Thu Jan 3 09:48:18 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 03 Jan 2008 09:48:18 -0500 Subject: problem with global var In-Reply-To: <3448388f0801030638sd285c7dh78b9ea9f7b911139@mail.gmail.com> References: <3448388f0801030638sd285c7dh78b9ea9f7b911139@mail.gmail.com> Message-ID: <477CF5B2.3020500@mattnordhoff.com> Bruno Ferreira wrote: > Hi, > > I wrote a very simple python program to generate a sorted list of > lines from a squid access log file. > > Here is a simplified version: > > ################################## > 1 logfile = open ("squid_access.log", "r") > 2 topsquid = [["0", "0", "0", "0", "0", "0", "0"]] > 3 > 4 def add_sorted (list): Don't call your variable "list". There's already the built-in type "list". > 5 for i in range(50): You should probably use xrange here. > 6 if int(list[4]) > int(topsquid[i][4]): > 7 topsquid.insert(i,list) > 8 break > 8 # Max len = 50 > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] I'd just use "[:50]", the 0 is implied. > 13 while True: > 14 logline = logfile.readline() > 15 linefields = logline.split() > 16 > 17 if logline != "": > 18 add_sorted (linefields) > 19 else: > 20 break for logline in logfile: if logline: linefields = logline.split() add_sorted(linefields) else: break > 22 for i in range (len(topsquid)): > 23 print topsquid[i][4] for i in topsquid: print i[4] (You probably want to use a name other than "i" then.) > #################################### > > When I execute the program _without_ the lines 10 and 11: > > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > > it runs perfectly. > > But if I execute the program _with_ those lines, this exception is thrown: > > bruno at ts:~$ python topsquid.py > Traceback (most recent call last): > File "topsquid.py", line 20, in > add_sorted (linefields) > File "topsquid.py", line 6, in add_sorted > if int(list[4]) > int(topsquid[i][4]): > UnboundLocalError: local variable 'topsquid' referenced before assignment > > > Note that now the error shown is not related with the lines 10 and 11, > but wiht a line prior to them. > > Any hints? Basically, you're trying to read the global variable "topsquid", and then you're trying to define a local variable "topsquid". Python doesn't like that. Declare it as global by adding "global topsquid" to the top of the function. -- From bignose+hates-spam at benfinney.id.au Wed Jan 9 18:17:46 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 10 Jan 2008 10:17:46 +1100 Subject: Conventions for dummy name (was: for loop without variable) References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de> Message-ID: <873at6k2qt.fsf_-_@benfinney.id.au> "Diez B. Roggisch" writes: > The underscore is used as "discarded" identifier. So maybe > > for _ in xrange(10): > ... The problem with the '_' name is that it is already well-known and long-used existing convention for an entirely unrelated purpose: in the 'gettext' i18n library, the '_' function to get the locally-translated version of a text string. Since the number of programs that need to use something like 'gettext' (and therefore use the '_' function) is likely only to increase, it seems foolish to set one's program up for a conflict with that established usage. I've seen 'dummy' used as a "don't care about this value" name in other Python code. That seems more readable, more explicit, and less likely to conflict with existing conventions. -- \ "It is forbidden to steal hotel towels. Please if you are not | `\ person to do such is please not to read notice." -- Hotel | _o__) sign, Kowloon, Hong Kong | Ben Finney From donn.ingle at gmail.com Thu Jan 24 12:03:19 2008 From: donn.ingle at gmail.com (Donn) Date: Thu, 24 Jan 2008 19:03:19 +0200 Subject: piping into a python script In-Reply-To: <668bb39a0801240845k70174c44xfb54d519f5c3ffe2@mail.gmail.com> References: <668bb39a0801240845k70174c44xfb54d519f5c3ffe2@mail.gmail.com> Message-ID: <200801241903.20082.donn.ingle@gmail.com> > wget -i - > it doesn't do anything, just waits for your input. Your applications > probably should behave the same. Okay, that works for me. > Paddy wrote: > > ls *.a | ./fui.py -f - *.b > It doesn't seem to me that -f parameter is necessary for your > application. Yes and no, I have another option that needs to take a variable number of args. > It should treat all the arguments as the filenames, > shouldn't it? And when one of the filenames is -, just try to read > stdin. I have tested getopt and it strips the lone '-' out. I can get it from sys.argv, but then I am really doing more parsing than I want to. It's a tricky job this. I think I will look in sys.argv, if I find a single dash the I will replace that element in the list with whatever comes from stdin. Then I'll pass all of it to getopt. Thanks for the help. \d -- When you allow legends to rule your life, your world is based on fiction -- Segio Aragones (Groo the Wanderer Number 99) Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From mwm-keyword-python.b4bdba at mired.org Sat Jan 12 14:59:39 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Sat, 12 Jan 2008 14:59:39 -0500 Subject: Import and execfile() In-Reply-To: References: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> Message-ID: <20080112145939.49f59e26@bhuda.mired.org> On Fri, 11 Jan 2008 20:55:07 -0800 (PST) George Sakkis wrote: > On Jan 11, 5:24 pm, Mike Meyer > wrote: > > On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis wrote: > > > I maintain a few configuration files in Python syntax (mainly nested > > > dicts of ints and strings) and use execfile() to read them back to > > > Python. This has been working great; it combines the convenience of > > > pickle with the readability of Python. So far each configuration is > > > contained in a single standalone file; different configurations are > > > completely separate files. > > You can make the syntax cleaner by using classes to hold the values > > instead of nested dicts, etc. That way you don't have to quote the > > names of the values: > > class Foo: > > bar = 1 > > baz = 2 > Actually I am using the dict() constructor instead of literals so it's > as clean as with classes; IMO for nested options it's cleaner than > nested classes: Yup, that does that. Wasn't available last time I did this, so... > > > I understand why this fails but I'm not sure how to tell execfile() to > > > set the path accordingly. Any ideas ? > > Manipulate sys.path yourself? > That's what Mitko suggested too, and indeed it works: > However this doesn't look very clean to me. Also it's not thread-safe; I don't know that there is a clean solutions. As for not being thread-safe, I'd suggest that you should have all your configuration information loaded *before* you start any threads. This makes shutting down in case you decide there's something wrong in it easier, and in some cases may prevent inadvertently doing things that shouldn't oughta be done. In the case where you config files are parsed by the python interpreter, this goes double because a busted config file could lead to exceptions, leaving your application in an unknown state. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From haag at lsu.edu Sat Jan 5 00:47:19 2008 From: haag at lsu.edu (Alaric Haag) Date: Fri, 04 Jan 2008 23:47:19 -0600 Subject: Information on PyGMT? References: Message-ID: In article , Jeroen Ruigrok van der Werven wrote: > -On [20080104 04:11], Alaric (haag at lsu.edu.invalid) wrote: > >Unfortunately, the only site (forge.nesc.ac.uk) that seems to offer the code > >(written by Magnus Hagdorn) is not responding. I don't know if that's a > >temporary condition or if that site is out of commission. > > > >Google isn't revealing much recent discussion either.... which is sad, as I > >would imagine this to be a valuable tool! > > I am not sure how appropriate > http://www.cdc.noaa.gov/people/jeffrey.s.whitaker/python/gmt/gmt-src/doc/html/ > public/gmt.gmt-module.html > might be? > > I cannot find Magnus' PyGMT-0.2 tarball anywhere, sorry. Many thanks! I was aware of that package, which seemed to be a less complete approach, but the good news is that the NESC site came back up! From ryszard.szopa at gmail.com Mon Jan 14 17:47:36 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Mon, 14 Jan 2008 14:47:36 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> Message-ID: <65cfbd40-6612-4bd5-aa5c-a1338da0f5a7@n20g2000hsh.googlegroups.com> On Jan 14, 1:53 pm, Michele Simionato wrote: > I really need to publish this one day or another, since these > questions > about super keeps coming out: > > http://www.phyast.pitt.edu/~micheles/python/super.html Thanks, Michele! Your essay was enlightening [2]. Specially if you take in account super's documentation is slightly outdated :). I also read Raymond Hettinger's article about descriptors (which you mention, but don't link to!) and decided to use them to reimplement methods that always call their superclass [1] method of the same name. Could you tell me what are the pros and cons of the two approaches (i.e. writing a decorator function and a decorator descriptor class)? The former gives slightly shorter code, while the second gives access to the original function and I somehow feel it is more... classy :) [code follows] Cheers, -- Richard [1] By which I mean the first class in their MRO. [2] I also found some other papers of yours about the "not for the faint of heart" corners of Python: MRO, metaclasses, class memoization, etc. and they were most enjoyable and interesting. def callingprevious1(fun): """Decorator to call a superclass' fun first. Decorator function approach. >>> class parent(object): ... def foo(self): ... print "I am foo of parent" ... >>> class child(parent): ... @callingprevious1 ... def foo(self): ... print "I am foo of child" ... >>> x = child() >>> x.foo() I am foo of parent I am foo of child >>> child.foo(x) I am foo of parent I am foo of child """ name = fun.__name__ def decorated(self, *args, **kwargs): try: super_object = super(self.__class__, self) getattr(super_object, name)(*args, **kwargs) except AttributeError: pass # if parent doesn't implement fun, we don't care # about it return fun(self, *args, **kwargs) # hopefully None decorated.__name__ = name return decorated class callingprevious(object): """ Decorator making the defined method call the method of the first superclass in mro at the beginning. Descriptor approach. >>> class parent(object): ... def foo(self): ... print "I am foo of parent" ... >>> class child(parent): ... @callingprevious ... def foo(self): ... print "I am foo of child" ... >>> x = child() >>> x.foo() I am foo of parent I am foo of child >>> child.foo(x) I am foo of parent I am foo of child """ def __init__(self, initval): self.name = initval.__name__ self.__combine_methods(initval) def __combine_methods(self, val): self.val = val def with_parent(obj, *args, **kwargs): try: parent_method = getattr(super(type(obj), obj), self.val.__name__) except AttributeError: pass else: parent_method(*args, **kwargs) return self.val(obj, *args, **kwargs) with_parent.__name__ = self.val.__name__ self.to_return = with_parent def __get__(self, obj, objtype): from types import MethodType # btw, is it anyhow better than just returning the function? return MethodType(self.to_return, obj, objtype) def __set__(self, obj, val): self.__combine_methods(val) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 28 15:27:15 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 28 Jan 2008 21:27:15 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> <6067h9F1otsbrU1@mid.individual.net> <13ps3djqrl4ap5b@corp.supernews.com> Message-ID: <606s53F1p4slrU1@mid.individual.net> Grant Edwards wrote: > No, it doesn't output corresponding machine code (that's what > some Java JIT implementations do, but I'm not aware of any > Python implementations that do that). The virtual machine > interpreter just does the action specified by the bytecode. By "outputs corresponding machine code" I meant "feeds corresponding machine code to the CPU" to make the analogy clearer. Which can mean a function call. Regards, Bj?rn -- BOFH excuse #325: Your processor does not develop enough heat. From paul at boddie.org.uk Fri Jan 11 08:38:38 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 11 Jan 2008 05:38:38 -0800 (PST) Subject: Detecting OS platform in Python References: Message-ID: <7441a2f9-e0b3-4686-b799-4c25e78ea94c@k2g2000hse.googlegroups.com> On 11 Jan, 04:14, Mike Meyer wrote: > On Thu, 10 Jan 2008 18:37:59 -0800 (PST) Devraj wrote: > > > My Python program needs reliably detect which Operating System its > > being run on, infact it even needs to know which distribution of say > > Linux its running on. The reason being its a GTK application that > > needs to adapt itself to be a Hildon application if run on devices > > like the N800. > > I don't think it can be done. For most Unix system, os.uname() will give > you the information you want: > > >>> os.uname() [...] > GNU/Linux distributions are collections of lots of people software, so > each has it's own way to state what "distribution" it is. I believe > there's some sort of standard - except not everybody follows it. So > you wind up using a series of heuristics to chase this information > down. On Red Hat distributions, there appears to be a file called /etc/ redhat-release containing the distribution name. I can't remember the Debian equivalent, but it may be /etc/debian_version or something like that. There's LSB-related stuff, too, but I'm not sure if any of that tells you about the distribution itself. [...] > I'm not a GTK programmer, and have never even heard of Hildon. Is > there some associated module you could try and import that doesn't > exist on the N800? I.e.: > > try: > import gtk > mygui = 'gtk' > except ImportError: > import Hildon > mygui = 'Hildon' > > or maybe something like: > > import gtk > mygui = 'gtk' if not hasattr(gtk, 'Hildon') else 'Hildon' There must be Hildon-related modules or features that one can import or test for, as Mike suggests. In the desktop module [1], I generally test various environment variables or the output of various programs in order to deduce which desktop environment is being used, but this is in software which isn't generally trying to display a graphical user interface. Just testing for the presence of a file or a program isn't usually enough because on systems where desktop environments co- exist, for example, the presence of a GNOME-related file or program doesn't mean that the user is actually using GNOME at that particular time. If you might be using Hildon and are actually displaying a GUI, however, attempting to get the resources you need should be enough to confirm whether you're running Hildon or not. Paul [1] http://www.python.org/pypi/desktop From jared.grubb at gmail.com Tue Jan 15 13:35:52 2008 From: jared.grubb at gmail.com (Jared Grubb) Date: Tue, 15 Jan 2008 10:35:52 -0800 Subject: Iterate through slots Message-ID: <925822270801151035x7975fdb6s972efc40ed4f6902@mail.gmail.com> How can I iterate through the slots of a class, including those it inherits from parent classes? class C(object): __slots__ = ['a'] class D(C): __slots__ = ['b'] >>> d = D() >>> d.__slots__ ['b'] >>> d.a = 1 # this works, so slots inherit properly >>> d.b = 2 >>> d.c = 3 # this doesnt work, like we expect Traceback (most recent call last): File "", line 1, in ? AttributeError: 'D' object has no attribute 'c' The reason I want to do this is that I want to have the following, and let all the children inherit the parent's __init__: class Parent(object): __slots__ = ['whatever'] def __init__(self, context=None, **kw): if context is None: context=getContext() for slot in SLOTITERATORHERE: # Resolve the slot's value, even for those things not specifically set in kw class Child1(Parent): __slots__ = ['for_me_only'] -------------- next part -------------- An HTML attachment was scrubbed... URL: From peng.kyo at gmail.com Wed Jan 16 22:40:59 2008 From: peng.kyo at gmail.com (J. Peng) Date: Thu, 17 Jan 2008 11:40:59 +0800 Subject: assigning values in python and perl In-Reply-To: <18c1e5f20801161934m69ff44edo1e35f5381f7d2928@mail.gmail.com> References: <18c1e5f20801161934m69ff44edo1e35f5381f7d2928@mail.gmail.com> Message-ID: <18c1e5f20801161940m4966b4dfod288fed0ae5eca46@mail.gmail.com> May I ask, python's pass-by-reference is passing the object's reference to functions, but perl, or C's pass-by-reference is passing the variable itself's reference to functions. So althought they're all called pass-by-reference,but will get different results.Is it? On Jan 17, 2008 11:34 AM, J. Peng wrote: > I just thought python's way of assigning value to a variable is really > different to other language like C,perl. :) > > Below two ways (python and perl) are called "pass by reference", but > they get different results. > Yes I'm reading 'Core python programming', I know what happened, but > just a little confused about it. > > $ cat t1.py > def test(x): > x = [4,5,6] > > a=[1,2,3] > test(a) > print a > > $ python t1.py > [1, 2, 3] > > $ cat t1.pl > sub test { > my $ref = shift; > @$ref = (4,5,6); > } > > my @a = (1,2,3); > test(\@a); > > print "@a"; > > $ perl t1.pl > 4 5 6 > From devnew at gmail.com Wed Jan 2 00:00:50 2008 From: devnew at gmail.com (devnew at gmail.com) Date: Tue, 1 Jan 2008 21:00:50 -0800 (PST) Subject: using Tix.FileSelectBox in python Message-ID: hi i was using Tix.FileSelectBox to select imagefiles from a directory..when i click on image and click my app's okbutton i can get the selected image name by self.selimgname=self.myfileselectbox.selection.cget("value") after this if i just select a folder and not an image and click ok then again the myfileselectbox.selection.cget("value") gives the previously selected image name. i would like to give an error msg asking the user if he doen't select an image..how can i do this? devnew From ptmcg at austin.rr.com Sun Jan 27 20:17:04 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 27 Jan 2008 17:17:04 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net><60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> Message-ID: <92e2e361-68f4-4cd2-b0d4-750e19a06faf@s19g2000prg.googlegroups.com> On Jan 27, 6:13?pm, "Terry Reedy" wrote: > > I think this version, with this name convention, is nice enough to possibly > go in the stdlib if there were an appropriate place for it. ?Not sure where > though. ?If there were a classtools module.... > > tjr +1 I thought at one time there was to be a "decorators" module in the stdlib for just this kind of useful item. At minimum, you could post this to the Python wiki at http://wiki.python.org/moin/PythonDecoratorLibrary. -- Paul From davidben at fmtc.com Wed Jan 16 15:01:32 2008 From: davidben at fmtc.com (DBenjamin) Date: Wed, 16 Jan 2008 12:01:32 -0800 (PST) Subject: Help wanted with GTK+ program References: Message-ID: <794b1708-2668-408e-8149-c52e1b0ff909@j78g2000hsd.googlegroups.com> On Jan 8, 5:49 pm, Hollabu... at gmail.com wrote: > I'm working on a simple GTK+ wrapper around the flash Pandora Radio > player (Pandora.com). > > It's very basic right now but I've got it almost working. > I'm using gtkmozembed to fetch and use the player and dbus to detect > multimedia keys. > The only problem I'm having is that the mozembed widget doesn't seem > to recognize the fake keypress event sent to it. > > CODE > > #!/usr/bin/env python > > import gtk > import gtkmozembed > import dbus > from dbus.mainloop.glib import DBusGMainLoop > > class Wrapper: > def __init__(self): > # Set-up the wrapper for the player > > self.win = gtk.Window() # Create a new GTK window called 'win' > > self.win.set_title("Pandora Player") # Set the title of the > window > self.win.set_icon_from_file('favicon.ico') # Set the window > icon to a web browser icon > self.win.set_position(gtk.WIN_POS_CENTER) # Position the > window in the centre of the screen > > self.win.connect("destroy", self.close_window) # Connect the > 'destroy' event to the 'CloseWindow' function, so that the app will > quit properly > > # Handle media keys under Gnome > DBusGMainLoop(set_as_default=True) > bus = dbus.Bus(dbus.Bus.TYPE_SESSION) > settings = bus.get_object('org.gnome.SettingsDaemon', '/org/ > gnome/SettingsDaemon') # Connect to gnome settings D-Bus > settings.connect_to_signal("MediaPlayerKeyPressed", > self.action) > > # Create the browser widget > gtkmozembed.set_profile_path("/tmp", "simple_browser_user") # > Set a temporary Mozilla profile (works around some bug) > self.mozbrowser = gtkmozembed.MozEmbed() # Create the browser > widget > > # Set-up the browser widget before we display it > self.win.add(self.mozbrowser) # Add the 'mozbrowser' widget to > the main window 'win' > self.mozbrowser.load_url("https://www.pandora.com:443/radio/ > tuner_8_2_0_2_pandora.swf") # Load Pandora > self.mozbrowser.set_size_request(640,540) # Size arrived at > after careful trial and error > self.mozbrowser.show() # Needed for correct size > > self.win.show_all() # Show the window > > def PlayPause(self, ): > event = gtk.gdk.Event(gtk.gdk.KEY_PRESS) > event.keyval = gtk.keysyms.space > event.time = 0 # assign current time > self.mozbrowser.grab_focus() > self.win.emit('key_press_event', event) > > def ThumbsDown(self): > event = gtk.gdk.Event(gtk.gdk.KEY_PRESS) > event.keyval = gtk.keysyms.minus > event.time = 0 # assign current time > self.mozbrowser.grabfocus() > self.win.emit('key_press_event', event) > > def ThumbsUp(self): > event = gtk.gdk.Event(gtk.gdk.KEY_PRESS) > event.keyval = gtk.keysyms.plus > event.time = 0 # assign current time > self.mozbrowser.grabfocus() > self.win.emit('key_press_event', event) > > def Skip(self): > event = gtk.gdk.Event(gtk.gdk.KEY_PRESS) > event.keyval = gtk.keysyms.Right > event.time = 0 # assign current time > self.mozbrowser.grabfocus() > self.win.emit('key_press_event', event) > > # Handles key presses > def action(self, *keys): > for key in keys: > if key == "Play": > self.PlayPause() > elif key == "Stop": > self.ThumbsUp() > elif key == "Previous": > self.ThumbsDown() > elif key == "Next": > self.Skip() > > def close_window(self, caller_widget): > """Close the window and exit the app""" > gtk.main_quit() # Close the app fully > > if __name__ == "__main__": > wrapper = Wrapper() > gtk.main() I was looking for something like you are writing and seen this post, maybe it would help you? http://rjoblog.wordpress.com/2007/12/19/pandora-4-all/ He is showing this url: https://www.pandora.com/radio/tuner_8_2_0_2_pandora.swf From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 25 08:05:09 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 25 Jan 2008 14:05:09 +0100 Subject: [OT] "just like Java" (was :Re: translating Python to Assembler) In-Reply-To: References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: <4799de28$0$12358$426a74cc@news.free.fr> Christian Heimes a ?crit : > Wim Vander Schelden wrote: >> Python modules and scripts are normally not even compiled, if they have >> been, >> its probably just the Python interpreter packaged with the scripts and >> resources. > > No, that is not correct. Python code is compiled to Python byte code and > execute inside a virtual machine just like Java or C#. I'm surprised you've not been flamed to death by now - last time I happened to write a pretty similar thing, I got a couple nut case accusing me of being a liar trying to spread FUD about Java vs Python respective VMs inner working, and even some usually sensible regulars jumping in to label my saying as "misleading"... From noemailplease0001 at gmail.com Tue Jan 29 14:51:04 2008 From: noemailplease0001 at gmail.com (noemailplease0001 at gmail.com) Date: Tue, 29 Jan 2008 11:51:04 -0800 (PST) Subject: breaking out of outer loops Message-ID: Any elegant way of breaking out of the outer for loop than below, I seem to have come across something, but it escapes me for i in outerLoop: for j in innerLoop: if condition: break else: continue break Thanks, K From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 23 08:02:39 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 23 Jan 2008 14:02:39 +0100 Subject: translating Python to Assembler References: <6ircp35hju5cb2iu9ip6rc7qjt9d585cde@4ax.com> Message-ID: <5vos7fF1nn9odU1@mid.individual.net> over at thepond.com wrote: > My expertise, if any, is in assembler. I'm trying to understand > Python scripts and modules by examining them after they have been > disassembled in a Windows environment. IMHO, that approach doesn't make sense to understand scripts or modules (except if you have some kind of super brain -- because Python is _very_ high level). It only does if you want to understand the Python compiler/interpreter you use. For compilers that output machine code directly this *may* make sense (but for more complex programs it will become very difficult). If you'd like to get a "low level" look into how things are done in Python, try the dis module. Using dis.dis, you can look at disassembled Python byte code. Regards, Bj?rn -- BOFH excuse #251: Processes running slowly due to weak power supply From hniksic at xemacs.org Sat Jan 26 22:25:12 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 27 Jan 2008 04:25:12 +0100 Subject: file write question References: <62b96f11-1a81-4be8-9dcb-348ee38ebe16@f10g2000hsf.googlegroups.com> Message-ID: <87myqsq7af.fsf@mulj.homelinux.net> "Robb Lane (SL name)" writes: > ... or just leave it till it's done? > I don't need to use the file contents until the script is done > (although it would be nice... just to check it while it's working), Use flush() to force the contents out at opportune times without closing and reopening the file object. From mr.cerutti at gmail.com Thu Jan 17 11:28:35 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 17 Jan 2008 11:28:35 -0500 Subject: Is this a bug, or is it me? In-Reply-To: References: <87myr4o3sg.fsf@mulj.homelinux.net> Message-ID: <51302a8c0801170828u1c5adad9j7170dc51c8a07a1d@mail.gmail.com> On Jan 17, 2008 11:08 AM, wrote: > On Jan 17, 4:59 pm, "Neil Cerutti" wrote: > > Generator expressions, unlike list comprehensions, have their own > > scope so that they don't "leak" names to the enclosing scope. The > > Python rule forbidding access to the locals of enclosing scopes is > > preventing the class names from working in the generator expression. > > Ah, that explains why my random suggestion worked but was not > helpful :) I feel like I am learning a lot today! Me, too. Especially about wrongly oversimplifying stuff that's complicated. My statement above isn't exactly right, since generator expressions usually *can* access stuff in the enclosing local scope. They wouldn't be very useful if they couldn't. -- Neil Cerutti From B.Ogryczak at addr.in.reply-to.invalid Sun Jan 20 10:42:16 2008 From: B.Ogryczak at addr.in.reply-to.invalid (Bart Ogryczak) Date: Sun, 20 Jan 2008 15:42:16 +0000 (UTC) Subject: too long float References: Message-ID: On 2008-01-18, citizen J. Peng testified: > hello, > > why this happened on my python? >>>> a=3.9 >>>> a > 3.8999999999999999 >>> a = 3.9 >>> print a 3.9 bart -- "PLEASE DO *NOT* EDIT or poldek will hate you." - packages.dir (PLD) http://candajon.azorragarse.info/ http://azorragarse.candajon.info/ From george.sakkis at gmail.com Mon Jan 7 13:21:55 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 7 Jan 2008 10:21:55 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Message-ID: On Jan 7, 9:27 am, Kay Schluehr wrote: > On Jan 7, 12:53 pm, Berco Beute wrote: > > > Cool! We knew it would happen one day :) > > What could be the reason? Python 3? Jython 2.2? Java's loss of > > sexiness? > > Python eats Perls lunch as a scripting language. Even better, it is not threatened by Ruby as many from the buzzword- ridden RoR crowd would like to believe. From dg.google.groups at thesamovar.net Tue Jan 22 17:56:23 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Tue, 22 Jan 2008 14:56:23 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> Message-ID: Arnaud and Terry, Great solutions both of you! Much nicer than mine. I particularly like Arnaud's latest one based on folding because it's so neat and conceptually simple. For me, it's the closest so far to my goal of the most elegant solution. So anyone got an answer to which set of numbers gives the most targets from 100 onwards say (or from 0 onwards)? Is Python up to the task? A thought on that last one. Two ways to improve speed. First of all, you don't need to rerun from scratch for each target. Secondly, you can try multiple different sets of numbers at the same time by passing numpy arrays instead of single values (although you have to give up the commutativity and division by zero optimisations). Dan Goodman From Scott.Daniels at Acm.Org Tue Jan 1 13:17:10 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 01 Jan 2008 10:17:10 -0800 Subject: Using mouse In-Reply-To: References: Message-ID: <13nl0ktmfgkgde5@corp.supernews.com> Lucas Prado Melo wrote: > I would like to control mouse events (i.e. I would like to "click" and > move mouse around by code). > How do I do this in python? A python doesn't have a mouse for long; it eats them up. It is your display and user I/O system that deals with mice, and so, inevitably, the answer to your question (and, indeed whether such a thing is even possible) depends on the OS and display packages you are using. --Scott David Daniels Scott.Daniels at Acm.Org From fcharlypillai at gmail.com Sat Jan 5 07:34:39 2008 From: fcharlypillai at gmail.com (cf29) Date: Sat, 5 Jan 2008 04:34:39 -0800 (PST) Subject: TextWrangler and new Python version (Mac) References: <4e34d25a-460b-40c2-96c0-60c98b5e0ab8@m34g2000hsf.googlegroups.com> Message-ID: <7b89b172-29de-4e0e-841d-bd818413a92c@l1g2000hsa.googlegroups.com> Thank you Jean, I could fix this problem. Creating the symbolic link wasn't really obvious though. They also say about the documentation: *Extract the documentation files, and place them in some suitable location, e.g. ~/Library/Python-Docs *Edit your "environment.plist" file, and create an environment variable PYTHONDOCS to the location of the folder which contains the Python documentation. Is that the html version of the Python documentation? Do you know more about this "environment.plist" file? Where is it supposed to be? I didn't find any. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 9 04:13:50 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 09 Jan 2008 10:13:50 +0100 Subject: Newbie question: Classes In-Reply-To: References: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com> Message-ID: <4784904f$0$18061$426a34cc@news.free.fr> Daniel Fetchinson a ?crit : nb: answering to the (unknown) OP: >> Basically, I have created a program using tkinter without using any class >> structure, simply creating widgets and functions (and finding ways around >> passing variables from function to function, using global variables etc). One of the points of OO is indeed to avoid excessive use of global state and "cargo" data. Now note that this can also be (at least partially) done using closures, callbacks, partial application, and other functional tricks. >> The program has become rather large ( lines?) I am trying to now put it into >> a class structure, because I hear it is easier to handle. It can make thing easier - from a maintainance/reusability POV at least - if you're at ease with OO design and programming. But getting OO right - specially when it comes to design - is not necessarily trivial neither, so don't think of it as a "silver bullet". >> So basically, I put all the stuff into a class, making the widgets in the >> "def __init__(self, root)" (root being my Tk() ) and then I have had to put >> a "self." in front of any instance of any variable or widget. Is this right? Probably not. >> it seems like nothing is any easier (except having variables locally). Is >> this right? Should I be creating more classes for different things or what? Probably, yes. You could try to identify small sets of functions dealing with a common (small) set of data, and regroup them into (small) classes, then think about how instances of these classes will work together. Also remember to separate the "logic" (data structures and rules about these data structures) from the "presentation" (the GUI code). The "logic" part should be usable independantly (with a CLI interface, a web interface, etc). My two cents... From terry at jon.es Tue Jan 8 21:34:07 2008 From: terry at jon.es (Terry Jones) Date: Wed, 9 Jan 2008 03:34:07 +0100 Subject: Open a List of Files In-Reply-To: Your message at 21:03:08 on Tuesday, 8 January 2008 References: <874pdomrrd.fsf@mulj.homelinux.net> Message-ID: <18308.12959.742868.758136@terry.local> Hi BJ > > Fredrik Lundh writes: > > Or in a dict: > > > > open_files = {} > > for fn in ['messages', 'recipients', 'viruses']: > > open_files[fn] = open(getfilename(fn), 'w') > > I decided that I was just trying to be "too smooth by 1/2" so I fell back > to ... > > messages = open(os.path.join(host_path,'messages.txt'), 'wb') > deliveries = open(os.path.join(host_path,'deliveries.txt'), 'wb') > actions = open(os.path.join(host_path,'actions.txt'), 'wb') > parts = open(os.path.join(host_path,'parts.txt'), 'wb') > recipients = open(os.path.join(host_path,'recipients.txt'), 'wb') > viruses = open(os.path.join(host_path,'viruses.txt'), 'wb') > esp_scores = open(os.path.join(host_path,'esp_scores.txt'), 'wb') I think you should revisit this decision. Something like Fredrik's code is the way to go. It has multiple advantages: - It's much shorter. - It's arguably easier to add/remove to/from. - It has less risk of error (much less repetition). - It allows your code to later take a string file tag and write to that file by looking up its file descriptor in the dict. - You can close all open files with a trivial loop. Also, if you start writing code like Fredrik's instead of like what you fell back on you'll make yourself a better programmer (in general, not just in Python). Terry From dstromberglists at gmail.com Thu Jan 17 15:26:07 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 17 Jan 2008 20:26:07 GMT Subject: bags? 2.5.x? References: <478bbae6$0$25383$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Mon, 14 Jan 2008 20:41:27 +0100, Wildemar Wildenburger wrote: > Dan Stromberg wrote: >> Is there a particular reason why bags didn't go into 2.5.x or 3000? >> >> I keep wanting something like them - especially bags with something >> akin to set union, intersection and difference. >> > How about this recepie > ? > > /W I'd found this with google, but thank you for making sure I was aware of it. The author of the bag class said that he was planning to submit bags for inclusion in 2.5 - is there a particular reason why they didn't go in? I keep finding a need for bags. In the past, I've done this sort of thing with dictionaries, but it's much nicer to have a bag class, and of course it's better to have it in the standard library than to slurp it into this, that and the other project. From NMBooker at googlemail.com Sun Jan 27 18:01:08 2008 From: NMBooker at googlemail.com (NMBooker) Date: Sun, 27 Jan 2008 15:01:08 -0800 (PST) Subject: Python System information References: <35d49700-9def-478e-8047-de548553e8c0@s8g2000prg.googlegroups.com> Message-ID: <655bcec0-1027-4fb6-a98d-2f5f4f600adf@z17g2000hsg.googlegroups.com> On Jan 27, 2:23 pm, Martin Saturka wrote: > > How can i get system information like CPU load and RAM usage in linux. > > What about 'pystatgrab'? > It provides good info, with a limitation - it does not have CPU info > for particular CPUs, it takes just the cumulative CPU info.http://www.i-scream.org/pystatgrab/http://packages.debian.org/statgrab > > M. Brilliant. Sorry about my misleading post I didn't know about statgrab. Thanks M. Nick Booker From sergio.correia at gmail.com Wed Jan 30 22:38:30 2008 From: sergio.correia at gmail.com (Sergio Correia) Date: Wed, 30 Jan 2008 22:38:30 -0500 Subject: Removing Pubic Hair Methods In-Reply-To: <87sl0en02e.fsf@benfinney.id.au> References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> <9275bfdb-8f07-4c63-abbf-40c136388bf3@i7g2000prf.googlegroups.com> <87sl0en02e.fsf@benfinney.id.au> Message-ID: So in this case it is REALLY better to ask for permission rather than forgiveness? On Jan 30, 2008 10:30 PM, Ben Finney wrote: > MRAB writes: > > > On Jan 31, 12:57 am, Asun Friere wrote: > > > Ouch!! If on the other hand 'females' is populated by instances of > > > (or merely includes instances of) class 'Human', I suggest you > > > test for female.consent somewhere in your code! > > > > > The Pythonic approach would be to try the action and catch a > > NoConsentException. > > You're making the classic Pythonista mistake: you behave as though > EAFP applies everywhere. I assure you, in the above situation, it does > not apply. > > -- > \ "He may look like an idiot and talk like an idiot but don't let | > `\ that fool you. He really is an idiot." ?Groucho Marx | > _o__) | > Ben Finney > -- > > http://mail.python.org/mailman/listinfo/python-list From ganeshborse at gmail.com Tue Jan 8 04:33:41 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Tue, 8 Jan 2008 01:33:41 -0800 (PST) Subject: Python modules - how to create & which are better Message-ID: <762240a7-ad30-47aa-a760-f1795b68915f@j20g2000hsi.googlegroups.com> I have embedded Python in my C++ application & creating Python function from the expression. I am then evaluating those Python compiled function (byte code) using PyObject_CallObject. I want to create a Python module which will have functions called by my user defined functions from the embedded Python interpreter. What will be best approach in this case? Should I be creating normal .py modules or .so modules (python extended with C code)? For me, most important is the executiong speed of the code in these modules. I want them to be fast, as those will be executed lot many times & in time bound fashion. Any suggestions on this? From BjornSteinarFjeldPettersen at gmail.com Sun Jan 27 04:07:38 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 27 Jan 2008 01:07:38 -0800 (PST) Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> Message-ID: On Jan 27, 9:58 am, o... at thepond.com wrote: > On Fri, 25 Jan 2008 17:44:07 -0800 (PST), ajaksu > wrote: > > > > >On Jan 25, 11:36 pm, ajaksu wrote: > >> On Jan 25, 11:10 pm, o... at thepond.com wrote: > >[...] > > >Gaah, is this what's going on? > > >ajaksu at Belkar:~$ cat error.txt > >This is not assembler... > > >ajaksu at Belkar:~$ ndisasm error.txt > >00000000 54 push sp > >00000001 686973 push word 0x7369 > >00000004 206973 and [bx+di+0x73],ch > >00000007 206E6F and [bp+0x6f],ch > >0000000A 7420 jz 0x2c > >0000000C 61 popa > >0000000D 7373 jnc 0x82 > >0000000F 656D gs insw > >00000011 626C65 bound bp,[si+0x65] > >00000014 722E jc 0x44 > >00000016 2E db 0x2E > >00000017 2E db 0x2E > >00000018 0A db 0x0A > > >:/ > > not sure what you're saying. Sure looks like assembler to me. Take the > '54 push sp'. The 54 is an assembler opcode for push and the sp is > the stack pointer, on which it is operating. go troll somewhere else (you obviously don't know anything about assembler and don't want to learn anything about Python). -- bjorn From thelanguageofcities at gmail.com Mon Jan 28 11:13:53 2008 From: thelanguageofcities at gmail.com (Max) Date: Mon, 28 Jan 2008 08:13:53 -0800 (PST) Subject: Python Genetic Algorithm References: <13pq880abaohbe4@corp.supernews.com> Message-ID: <327c3388-a2f2-425a-8d57-1cca68631457@j20g2000hsi.googlegroups.com> On Jan 27, 7:25 pm, Steven D'Aprano wrote: > Just pass the class itself. For example: > > # Define a class. > class Parrot(object): > pass > > x = "Parrot" # x is the NAME of the class > y = Parrot # y is the CLASS itself > z = Parrot() # z is an INSTANCE of the class > > You can use the class as a object, exactly the same as you can use a dict > or a string or a float or any other object. y() will create a new Parrot > instance exactly the same way that Parrot() would. > Okay, I'm getting into the thick of things, and I want to make sure I'm implementing this correctly. I have a module Individual.py which contains the abstract class Individual and the class BitString. My population __init__ takes chromosome as a parameter, and checks: if chromosome is not issubclass(Individual): raise Exception("Chromosome type must be a subclass of Individual.") Then it creates individuals as instances of chromosome (x = chromosome(params)). I'm pretty sure this is all right - what I'm wondering is, when actually creating a population, would I pass Individual.BitString as a parameter? That's what I have now. I have similar worries about my selection scheme. Right now I have the function rouletteWheel defined as a member of Population, so I pass the selector to my GA class as Population.rouletteWheel (making sure I have Population imported). I just want to ensure that this is correct. From bignose+hates-spam at benfinney.id.au Mon Jan 14 18:05:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 10:05:38 +1100 Subject: paging in python shell References: <31cb9b30-68f0-48ed-90f5-0e876fb08210@1g2000hsl.googlegroups.com> Message-ID: <87r6gkdn3x.fsf@benfinney.id.au> John Machin writes: > C:\junk>python demomore.py | more Your example uses the OS shell to invoke a pager on the output of the Python process. The OP was asking about paging *within* the Python shell. To my knowledge there's nothing in the default Python shell that enables what the OP is asking for. There are other Python shells, e.g. Idle, ipython, or a Python window inside Emacs, that may be better suited. -- \ "Compulsory unification of opinion achieves only the unanimity | `\ of the graveyard." -- Justice Roberts in 319 U.S. 624 (1943) | _o__) | Ben Finney From wicijowski at gmail.com Thu Jan 24 07:02:45 2008 From: wicijowski at gmail.com (janislaw) Date: Thu, 24 Jan 2008 04:02:45 -0800 (PST) Subject: Increment Variable Name References: Message-ID: <9e9714f6-24d8-46fe-908f-205d223574cd@p69g2000hsa.googlegroups.com> On Jan 23, 11:45?pm, David Brochu wrote: > This is probably really trivial but I'm stumped.... :-( > > Does anyone know how to increment a variable name? > > For example: > > I know the length of a list and I want to pass each element of a list ? > to a unique variable, thus I want to increment variable names. If the ? > list length = 4, i want to have the following variables: var1, var2, ? > var3, var4. > > Thanks Do you want to do this?: >>> locals() {'__builtins__': , '__name__': '__main__', 'pywin': , '__doc__': None} >>> locals()['var'+str(1)] = "spam" >>> locals() {'__builtins__': , '__name__': '__main__', 'var1': 'spam', 'pywin': , '__doc__': None} >>> var1 'spam' From stefan.behnel-n05pAM at web.de Wed Jan 23 11:08:59 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 17:08:59 +0100 Subject: Lxml on mac In-Reply-To: References: <47975B09.8090705@web.de> Message-ID: <4797669B.2040203@web.de> marcroy.olsen at gmail.com wrote: > On Jan 23, 4:19 pm, Stefan Behnel wrote: >> marcroy.ol... at gmail.com wrote: >>> What to one do if one what to use lxml(http://codespeak.net/lxml/ >>> index.html) on a mac? >> Have you tried installing up-to-date versions of libxml2/libxslt and running >> >> easy_install lxml >> >> ? > > No not yet. That was my nest step. > > But do anybody know if there is an easy way to use schema validation > in python(on a mac) ? You mean: easier than the above? Likely not many... Stefan From jens at aggergren.dk Tue Jan 29 08:58:54 2008 From: jens at aggergren.dk (Jens) Date: Tue, 29 Jan 2008 05:58:54 -0800 (PST) Subject: Terse Syntax through External Methods References: <5vu9gaF1no9i1U1@mid.uni-berlin.de> Message-ID: On Jan 25, 3:19 pm, "Diez B. Roggisch" wrote: > Jens schrieb: > > > > > Hello Everyone > > > I'm newbie to Zope and i have a few questions regarding external > > methods. What i wan't to do > > is provide a terse syntax for converting urls to special tracking > > urls: > > > > > > turns the provided url into something like > > >http://host/tracking?url=http%3A%2F%2Fmyurl%2F > > > in the output. > > > i've been trying to use a external procedure like this. > > > ## Script (Python) "track_link" > > ##bind container=container > > ##bind context=context > > ##bind namespace=_ > > ##bind script=script > > ##bind subpath=traverse_subpath > > ##parameters=self,url > > ##title=track link > > ## > > return "%s%s" % (self.tracking_prefix, url_quote(url)) > > > This doesn't work because because the method doesn't have access to > > the environment. Obviously I don't wan't to pass everything explicitly > > into the function as this would defeat the purpose of the exercise, > > namely to provide a terse syntax. > > > I have a background in other languages so I might be missing something > > conceptually with regard Zope and DTML.. Is there a better was of > > doing this, perhaps without using external methods? Currently im doing > > the following which isn't very elegant: > > > in content document > > > tracking>">link > > ... > > tracking: > > > > > Appreciate any input you might have on this- > > Is it really needed to use an external method for this, or isn't a > "normal" python script enough already? > > If it has to be an External method, you can't access such a context > AFAIK. But then you can create a python script that _has_ this context, > and passese it to the external method. Not the nicest solution, but > should work. > > Diez Like I said i'm a newbie. I though the deal with Zope was that i couldn't really do inline scripting (for security reasons) like in php but had to use these external methods. how does one go about creating a "normal" python script exactly and how do I invoke it's functionality? From noemailplease0001 at gmail.com Tue Jan 29 20:17:36 2008 From: noemailplease0001 at gmail.com (noemailplease0001 at gmail.com) Date: Tue, 29 Jan 2008 17:17:36 -0800 (PST) Subject: Appropriate use of Property() Message-ID: <72c9d910-f19a-407d-91cf-5599fa3e73b3@h11g2000prf.googlegroups.com> Property() can be used to rid ourselves of the extra effort of using two different methods (getAttrib() setAttrib()) for access of an attribute without giving direct access to the attribute, thus making it more elegant. So, the outsider using my module accesses the attribute with the syntax 'Object.attrib', but since this syntax looks as if he is accessing the attribute (rather than through a descrtiptor), should we subscribe to this syntax only when the attribute is both readable and writable? i.e., if I have an attribute which I strongly believe would always be only readable, should I go with the old style 'Object.getAttrib()'? Would like to know different perspectives. Thanks, K From xng at xs4all.nl Tue Jan 8 14:57:07 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Tue, 08 Jan 2008 20:57:07 +0100 Subject: Python or PowerShell ? In-Reply-To: <87hchodstr.fsf@physik.rwth-aachen.de> References: <87hchodstr.fsf@physik.rwth-aachen.de> Message-ID: <4783d594$0$8926$e4fe514c@dreader16.news.xs4all.nl> Torsten Bronger wrote: > Hall?chen! > > josepharmbruster at gmail.com writes: > >> I am all about using the right tool for the right purposes, [...] > > Which purpose? > >> I dug up one article from Google that talked about comparison but >> that was about it. >> >> http://www.simple-talk.com/sql/database-administration/comparing-python-and-powershell-dba-scripting-/ > > This comparison is about a very narrow field; additionally, it is a > field PowerShell was optimised for. > > Tsch?, > Torsten. > And adding to that, if you don't care about cross platform anyway, why even bother with python? I am sure that MS has tools that can do in a point and click kind of way all the things you might encounter. -- mph From sjmachin at lexicon.net Mon Jan 14 15:49:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 14 Jan 2008 12:49:02 -0800 (PST) Subject: paging in python shell References: Message-ID: <31cb9b30-68f0-48ed-90f5-0e876fb08210@1g2000hsl.googlegroups.com> On Jan 15, 7:35 am, "Alex K" wrote: > Hi Tim, > > Yes I mean piping the output into "more" for example. > Why don't you "suck it and see"??? E.g. C:\junk>copy con demomore.py for i in range(100): print 'line', i ^Z 1 file(s) copied. C:\junk>python demomore.py | more line 0 line 1 line 2 line 3 line 4 [snip] line 50 line 51 line 52 line 53 line 54 line 55 line 56 -- More -- From gagsl-py2 at yahoo.com.ar Wed Jan 2 00:14:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 02 Jan 2008 02:14:22 -0300 Subject: Newbie: Why doesn't this work References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> <13nldkj6ecl4j31@corp.supernews.com> Message-ID: En Wed, 02 Jan 2008 01:11:12 -0300, escribi?: > I am trying to experiment a little bit with new-style class and I am > confused why following example always returns 0 (zero). I was > expecting will return values from 0 to 9 and finaly > an Exception. > > class GenExample(object): > > def getInfo(self): > for no in range(10): > yield no > > myNo=property(getInfo) > > gen=GenExample() > print gen.myNo.next() > print gen.myNo.next() > . > . > print gen.myNo.next() Doing it this way, works as intended: py> gen=GenExample() py> myNo = gen.myNo py> print myNo.next() 0 py> print myNo.next() 1 ... py> print myNo.next() 9 py> print myNo.next() Traceback (most recent call last): File "", line 1, in StopIteration Why? I've seen you have read about the descriptor protocol. Methods are implemented as non-data descriptors. When you retrieve the "myNo" attribute from the "gen" instance, a bound method is created, combining the original getInfo function (stored into the class) with the gen instance. This is done *each* time the attribute is retrieved, and each time you get a different method object. That's why in your original example you always got 0: all methods are newly created ones, starting the iteration. (After the call finishes, as nobody holds any additional reference to it, the method object becomes a candidate to be garbage collected and eventually is deleted) Now it should be clear why my example above does work: I'm using always the *same* method object, previously saved into the "myNo" variable. This also explains a popular optimization technique: move attribute lookups out of a critical loop. That is, transforming this: for item in container: out.writerecord(item) into this: writerecord = out.writerecord for item in container: writerecord(item) Of course this should NOT be done blindly. -- Gabriel Genellina From arne.k.h at gmail.com Mon Jan 21 11:12:43 2008 From: arne.k.h at gmail.com (Arne) Date: Mon, 21 Jan 2008 08:12:43 -0800 (PST) Subject: Trouble writing to database: RSS-reader Message-ID: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> Hi! I try to make a rss-reader in python just for fun, and I'm almost finished. I don't have any syntax-errors, but when i run my program, nothing happends. This program is supposed to download a .xml-file, save the contents in a buffer-file(buffer.txt) and parse the file looking for start-tags. When it has found a start tag, it asumes that the content (between the start-tag and the end-tag) is on the same line, so then it removes the start-tag and the end-tag and saves the content and put it into a database. The problem is that i cant find the data in the database! If i watch my program while im running it, i can see that it sucsessfuly downloads the .xml-file from the web and saves it in the buffer. But I dont think that i save the data in the correct way, so it would be nice if someone had some time to help me. Full code: http://pastebin.com/m56487698 Saving to database: http://pastebin.com/m7ec69e1b Retrieving from database: http://pastebin.com/m714c3ef8 And yes, I know that there is rss-parseres already built, but this is only for learning. From google at mrabarnett.plus.com Tue Jan 22 15:45:05 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 22 Jan 2008 12:45:05 -0800 (PST) Subject: bags? 2.5.x? References: <478bbae6$0$25383$9b4e6d93@newsspool4.arcor-online.net> <437501ef-1b38-4e47-9106-c846a456dd49@c23g2000hsa.googlegroups.com> Message-ID: On Jan 21, 11:13 pm, Dan Stromberg wrote: > On Thu, 17 Jan 2008 18:18:53 -0800, Raymond Hettinger wrote: > >> >> I keep wanting something like them - especially bags with something > >> >> akin to set union, intersection and difference. > > >> > How about this recepie > >> > > >> The author of the bag class said that he was planning to submit bags > >> for inclusion in 2.5 - is there a particular reason why they didn't go > >> in? > > > Three reasons: > > > 1. b=collections.defaultdict(int) went a long way towards meeting the > > need to for a fast counter. > > > 2. It's still not clear what the best API would be. What should list(b) > > return for b.dict = {'a':3, 'b':0, 'c':-3}? Perhaps, [('a', 3), ('b', > > 0), ('c', -3)] or ['a', 'a', 'a'] > > or ['a'] > > or ['a', 'b', 'c'] > > or raise an Error for the negative entry. > > I'd suggest that .keys() return the unique list, and that list() return > the list of tuples. Then people can use list comprehensions or map() to > get what they really need. I think that a bag is a cross between a dict (but the values are always positive integers) and a set (but duplicates are permitted). I agree that .keys() should the unique list, but that .items() should return the tuples and list() should return the list of keys including duplicates. bag() should accept an iterable and count the duplicates. For example: >>> sentence = "the cat sat on the mat" >>> my_words = sentence.split() >>> print my_words ['the', 'cat', 'sat', 'on', 'the', 'mat'] >>> my_bag = bag(my_words) >>> print my_bag bag({'on': 1, 'the': 2, 'sat': 1, 'mat': 1, 'cat': 1}) my_list = list(my_bag) ['on', 'the', 'the', 'sat', 'mat', 'cat'] It should be easy to convert a bag to a dict and also a dict to a bag, raising ValueError if it sees a value that's not a non-negative integer (a value of zero just means "there isn't one of these in the bag"!). > > It might not be a bad thing to have an optional parameter on __init__ > that would allow the user to specify if they need negative counts or not; > so far, I've not needed them though. > > > 3. I'm still working on it and am not done yet. > > Decent reasons. :) > > Thanks! > > Here's a diff to bag.py that helped me. I'd like to think these meanings > are common, but not necessarily! > > $ diff -b /tmp/bag.py.original /usr/local/lib/bag.py > 18a19,58 > > > def _difference(lst): > > left = lst[0] > > right = lst[1] > > return max(left - right, 0) > > _difference = staticmethod(_difference) > > > def _relationship(self, other, operator): > > if isinstance(other, bag): > > self_keys = set(self._data.keys()) > > other_keys = set(other._data.keys()) > > union_keys = self_keys | other_keys > > #print 'union_keys is',union_keys > > result = bag() > > for element in list(union_keys): > > temp = operator([ self[element], other > [element] ]) > > #print 'operator is', operator > > #print 'temp is', temp > > result[element] += temp > > return result > > else: > > raise NotImplemented > > > def union(self, other): > > return self._relationship(other, sum) > > > __or__ = union > > > def intersection(self, other): > > return self._relationship(other, min) > > > __and__ = intersection > > > def maxunion(self, other): > > return self._relationship(other, max) > > > def difference(self, other): > > return self._relationship(other, self._difference) > > > __sub__ = difference From nagle at animats.com Thu Jan 24 14:56:48 2008 From: nagle at animats.com (John Nagle) Date: Thu, 24 Jan 2008 11:56:48 -0800 Subject: Sorting Large File (Code/Performance) In-Reply-To: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> Message-ID: <4798ec32$0$36333$742ec2ed@news.sonic.net> Ira.Kovac at gmail.com wrote: > Hello all, > > I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like > to sort based on first two characters. Given those numbers, the average number of characters per line is less than 2. Please check. John Nagle From cwitts at gmail.com Wed Jan 16 01:33:03 2008 From: cwitts at gmail.com (Chris) Date: Tue, 15 Jan 2008 22:33:03 -0800 (PST) Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> Message-ID: On Jan 16, 7:59 am, "J. Peng" wrote: > On Jan 16, 2008 1:45 PM, Dennis Lee Bieber wrote: > > > On Wed, 16 Jan 2008 11:09:09 +0800, "J. Peng" > > > alist = [] > > anint = 2 > > astr = "Touch me" > > > dummy(alist, anint, astr) > > > "dummy" can only modify the contents of the first argument -- the > > integer and string can not be mutated. > > Hi, > > How to modify the array passed to the function? I tried something like this: > > >>> a > [1, 2, 3] > >>> def mytest(x): > > ... x=[4,5,6] > ...>>> mytest(a) > >>> a > > [1, 2, 3] > > As you see, a was not modified. > Thanks! 'a' was not modified because you locally assigned a new object with 'x=[4,5,6]'. If you want the new list you created you will have to return it. You can see how you modify it if you were to use 'x.append()' or 'x.extend()' for eg. From steven.p.clark at gmail.com Thu Jan 10 17:02:53 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Thu, 10 Jan 2008 17:02:53 -0500 Subject: Newbie question on Classes In-Reply-To: References: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> Message-ID: <663744510801101402g14b77a71n12dd6694f0ed6ce5@mail.gmail.com> On Jan 10, 2008 4:54 PM, Fredrik Lundh wrote: > Adrian Wood wrote: > > > I can call man.state() and then woman.state() or Person.state(man) and > > Person.state(woman) to print the status of each. This takes time and > > space however, and becomes unmanageable if we start talking about a > > large number of objects, and unworkable if there is an unknown number. > > What I'm after is a way to call the status of every instance of Man, > > without knowing their exact names or number. > > > > I've gone through the relevant parts of the online docs, tried to find > > information elsewhere online, and looked for code samples, but the > > ionformation either isn't there, or just isn't clicking with me. I've > > tried tracking the names of each object in a list, and even creating > > each object within a list, but don't seem to be able to find the right > > syntax to make it all work. > > For a start, how about: > > class Person: > ... your class ... > > persons = [] > > man = Person() > persons.add(man) > > woman = Person() > persons.add(woman) > > for p in persons: > print p, p.state() > > Once you've gotten this to work, you can, if you want, look into moving > the list maintenance into the class itself (i.e. let the __init__ > function add the person to the list, and provide a destroy method that > removes it from the list). And once you've gotten that to work, you can > look at the "weakref" module for more elegant ways to handle > destruction. But one step at a time... > > > > -- > if you can keep all instances in a list, as Fredrik showed, it's easy. Otherwise you can do something like: class Person: people = [] def __init__(self, name): self.name = name Person.people.append(self) def print_state(self): print self.name some_folks = [Person('Bob'), Person('Mary')] other_guy = Person('Frank') for p in Person.people: p.print_state() This would keep the people from ever being garbage collected, but this may not be a problem for you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Wed Jan 30 04:22:18 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 30 Jan 2008 10:22:18 +0100 Subject: Unicode literals to latin-1 References: Message-ID: >>>>> (DR) wrote: >DR> How can I convert a string read from a database containing unicode literals, such as "Fr\u00f8ya" to the latin-1 equivalent, "Fr?ya"? >DR> I have tried variations around >DR> "Fr\u00f8ya".decode('latin-1') >DR> but to no avail. You have to use encode instead of decode, and the input string must be a unicode string. >>> print u"Fr\u00f8ya".encode('latin-1') Fr?ya >>> -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From paul at boddie.org.uk Fri Jan 11 12:52:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 11 Jan 2008 09:52:17 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <13od12b23hfv772@corp.supernews.com> Message-ID: <5b035c91-72eb-4d88-b19b-e89470865c5b@i7g2000prf.googlegroups.com> On 10 Jan, 21:47, Ed Jensen wrote: > Bruno Desthuilliers wrote: > > I fail to see how the existence of JIT compilers in some Java VM changes > > anything to the fact that both Java (by language specification) and > > CPython use the byte-code/VM scheme. > > While your answer was technically correct, by omitting pertinent > information, your answer lead readers to the wrong conclusion. Indeed. A perusal of the Java VM architecture documents plus any discussions around dynamic language support (and there's a discussion group about that very topic) reveal a number of differences between the CPython VM and Sun's Java VM. Moreover, despite claims about the Sun VM only being one of many, it holds a fairly similar position to that of the CPython VM in its own part of the computing world, with adoption only likely to increase now that it's open source. (And many new adopters were quite possibly using stuff like gcj previously which, as many will already know, is a native code compiler for Java.) These days, I seriously doubt that anyone uses the term "interpreted" to mean "parses the source text and works out what to do, over and over again as the program runs". Instead, I imagine that the term typically suggests the presence of a virtual processor doing what all processors do: interpret instructions. It's just that when native code is produced, we look away from the process of interpretation done by the hardware and consider it as the plain "on the metal" execution of the code. Sure, Sun's Java VM may not remove such a virtual processor entirely from the overall execution of a program, and the output of gcj may include the invocation of lots of moderately expensive library calls, but in contrast with CPython, some sequences of instructions will not ultimately be interpreted by the virtual machine at run-time. All this said, there are options other than CPython, and I imagine that they will become even more interesting to mainstream Python users over the next months and years. Paul From workitharder at gmail.com Sun Jan 6 17:23:50 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 6 Jan 2008 14:23:50 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> <617182dc-3ca1-4cf5-b1ca-1779dd8d6550@i3g2000hsf.googlegroups.com> Message-ID: On Jan 5, 5:36 pm, c... at mailinator.com wrote: > On Jan 5, 9:50 pm, Paul Hankin wrote: > > > > > On Jan 5, 5:12 pm, Paul Hankin wrote: > > > > On Jan 5, 4:14 pm, c... at mailinator.com wrote: > > > > > On Jan 5, 5:07 pm, c... at mailinator.com wrote: > > > > > > Hello, Paul and Arnaud. > > > > > While I think about your answers: do you think there is any way to > > > > > avoid shuffle? > > > > > It may take unnecessary long on a long list most of whose elements > > > > > have the property. > > > > You could generate a random shuffle of range(len(seq)) lazily, and use > > > that to iterate over your sequence. > > > > import random > > > import itertools > > > > def randxrange(n): > > > "Generate the numbers 0 to n-1 in a random order" > > > x = range(n) > > > for i in xrange(n): > > > r = random.randrange(n - i) > > > yield x[r] > > > x[r] = x[n - i - 1] > > > > def shuffled(seq): > > > "Generate the elements of seq in a random order" > > > return (seq[i] for i in randxrange(len(seq))) > > > > def pick_random(seq, prop): > > > return itertools.ifilter(prop, shuffled(seq)).next() > > > At the risk of filling this thread with my posts, here's a much > > simplified and faster version of this code that uses no extra storage. > > > import random > > > def pick_random(seq, prop): > > L = len(seq) > > for i in xrange(L): > > r = random.randrange(L - i) > > if prop(seq[r]): > > return seq[r] > > seq[r] = seq[L - i - 1] > > > -- > > Paul Hankin > > This one is good. Someone commented that you destroy the list, but > that can be fixed: > > def pick_random(seq, prop): > L = len(seq) > for i in xrange(L): > r = random.randrange(L - i) > if prop(seq[r]): > return seq[r] > seq[r], seq[L - i - 1]= seq[L - i - 1],seq[r] > > just pushing elements without the property to the end of the list > (list is mutated, true, but shuffle will do that too). In each > iteration of the for loop, there is only one random element, one check > of the property, and rebinding of elements without altering the lenght > of the list. This is optimal and has all the functionality. > > Two more comments: > for buzcor: deleting an element in the middle of a list is costly > for martin: that is certainly enough for me > > Thanks everybody! Just for fun, I profiled my answer versus the final answer over 300 seconds. I wrapped some parts of the functions in trivial functions so they would show up in the profiling. I found that my answer was 50% slower, but not because of the delete, but mostly the len() inside the loop, and the bool(seq) at the start of each loop. I was able to rewrite mine to only be 14 seconds slower (the time to make the copy at the beginning), but don't believe that's useful enough to post. ncalls tottime percall cumtime percall filename:lineno(function) 1516221 48.545 0.000 158.850 0.000 picked.py: 14(pick_random_bukzor) 3066421 19.359 0.000 53.815 0.000 picked.py:8(randrange2) 3066421 16.852 0.000 24.751 0.000 picked.py:9(len2) 1516221 14.712 0.000 14.712 0.000 picked.py:12(make_copy) 3066421 9.767 0.000 9.767 0.000 picked.py:10(notempty) 1550200 7.260 0.000 7.260 0.000 picked.py:7(delete) 1516221 31.574 0.000 104.384 0.000 picked.py: 27(pick_random) 3063737 19.556 0.000 54.617 0.000 picked.py:25(randrange3) 1516221 8.485 0.000 12.582 0.000 picked.py:26(len3) 1547516 5.611 0.000 5.611 0.000 picked.py: 24(do_transform) def delete(list, index): del list[index] def randrange2(X): return randrange(X) def len2(seq): return len(seq) def notempty(seq): if seq: return True def make_copy(l): return list(l) def pick_random_bukzor(seq, prop=bool): temp = make_copy(seq) while notempty(seq): i = randrange2(len2(temp)) if prop(temp[i]): return temp[i] else: delete(temp, i) def do_transform(seq, L, r, i): seq[r], seq[L - i - 1]= seq[L - i - 1],seq[r] def randrange3(X): return randrange(X) def len3(seq): return len(seq) def pick_random(seq, prop=bool): L = len3(seq) for i in xrange(L): r = randrange3(L - i) if prop(seq[r]): return seq[r] do_transform(seq, L, r, i) From paul at boddie.org.uk Wed Jan 30 07:19:12 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 30 Jan 2008 04:19:12 -0800 (PST) Subject: Trying to understand Python web-development References: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com> Message-ID: <2bb822db-0a33-4c47-bdd1-f4980a73fc00@m34g2000hsf.googlegroups.com> On 29 Jan, 18:11, walterbyrd wrote: > I don't know much php either, but running a php app seems straight > forward enough. I think that this (the ease of PHP application deployment) is one of the things that keeps Python framework developers up at night, regardless of whether the cause is technical (what processes or components are running) or social (that hosting providers install enough of the useful PHP stuff for people not to care about wanting to install more). > Python seems to always use some sort of development environment vs > production environment scheme. For development, you are supposed to > run a local browser and load 127.0.0.1:5000 - or something like that. > Then to run the same thing in a development environment, I have to > configure some files, or touch all the files, restart the web-server, > or something. Why is that? You can deploy Python Web applications using anything as simple as CGI (which only requires a single change to the Web server setup), right up to the full application server configuration. For a long time I've advocated the ability to be able to do this without having to switch frameworks and rewrite your code: that's what my WebStack package [1] is all about, and I guess that given the availability of the right adaptors and framework support, WSGI should let you do this as well. > Python also seems to require some sort of "long running processes" I > guess that the python interpretor has to running all of time. Not so: deploying anything as a CGI script/program means that the application code is only run when a request is made to the application. Lots of Python software can use this approach: MoinMoin, ViewVC, Trac... (All these things have, notably, implemented their own mechanisms for abstracting away the deployment technology, since they also work with things like mod_python. Another sad example of the community not coalescing around standards, although I think they're all looking into WSGI now.) > I am not really sure about what wsgi is supposed to accomplish. It's supposed to decouple the deployment technologies from the framework technologies, or at least that's what I'd use it for, and if all frameworks supported it, you'd supposedly be able to take, say, your Django application and run it on Zope 3, or your TurboGears application and run it on Twisted. Of course, you'd write your Django code differently from any Zope 3 code in your application, and the TurboGears code wouldn't look a lot like Twisted code, but that's another issue entirely. Paul [1] http://www.python.org/pypi/WebStack From lists at cheimes.de Wed Jan 9 16:15:35 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 09 Jan 2008 22:15:35 +0100 Subject: Python too slow? In-Reply-To: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: dongie.agnir at gmail.com wrote: > I'm pretty new to Python, and even newer to Image/Video processing, > and trying to get started on a project similar to GRL Vienna's laser > marker. I found some sample code here http://janto.blogspot.com/2006/01/motion-capture-in-python.html, > but after running the code with the included sample input file, it > seems quite slow (1-2 seconds from start to finish to do the 800 by > 600 gif image). Have you profiled your application? Do you know the bottle necks and the reason for the bottle necks? Is your application IO, memory or CPU bound? Have you considered rewriting the bottle necks in C? Christian From robert.kern at gmail.com Mon Jan 14 14:39:13 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 14 Jan 2008 13:39:13 -0600 Subject: help with slicing/replacing matrix sections. In-Reply-To: <478bb75f$0$5001$4c368faf@roadrunner.com> References: <478bb75f$0$5001$4c368faf@roadrunner.com> Message-ID: Erik Lind wrote: > I see a more complicated thread on a similar sounding question, but my > question is simpler, I hope. numpy questions are usually answered better on the numpy mailing list. http://www.scipy.org/Mailing_Lists > I have a large numpy matrix, initially created as: > > Mat = zeros((a,b), int) > > and a smaller array with other data > > Sub = [1,2,3,4,5],[6,7,8,9,0] > > I want to replace a section of Mat matrix with Sub matrix without having to > loop through each cell in each matrix individually. > > I thought index/slice assignments, should be able to do that, but I can only > get it to work (as per book examples) with simple arrays. Every syntax > combination I have tried gives one error or another, typically "can't > broadcast an object....", but intuitively it seems there should be a simple > solution. > > In short, how do I insert the data in the two (or any number of) rows in > Sub[0:2] into any part of Mat starting at Mat[x,y] without using "for" loops > ? In [11]: Sub = array([[1,2,3,4,5],[6,7,8,9,0]]) In [12]: Mat = zeros((10, 10), int) In [13]: Mat[5:5+2,4:4+5] = Sub In [14]: Mat Out[14]: array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 2, 3, 4, 5, 0], [0, 0, 0, 0, 6, 7, 8, 9, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) -- 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 afriere at yahoo.co.uk Wed Jan 23 02:54:00 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 22 Jan 2008 23:54:00 -0800 (PST) Subject: Removing objects References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> <27c8e3c8-3766-499c-9c62-82b03fa583d6@e23g2000prf.googlegroups.com> Message-ID: <430d47ec-1122-4016-b294-be20e0d4a0d9@s13g2000prd.googlegroups.com> On Jan 23, 6:16 pm, Asun Friere wrote: > >>> x.pop(x.index(c)) Umm, of course you would simply use x.remove(c) ... force of (bad) habit. %/ From pofuk at mzm.hr Thu Jan 3 18:26:33 2008 From: pofuk at mzm.hr (SMALLp) Date: Fri, 04 Jan 2008 00:26:33 +0100 Subject: py2exe command prompt whenr run Message-ID: HY! I'm using py2exe to port my applications on windows so user won't have to install python and other dependencies. Everything works file except when i run any of programs it star's command prompt before program starts. How can i avoid this to happen, and is there any other way of porting my applications on windows? Thanks! From aspineux at gmail.com Tue Jan 15 09:17:57 2008 From: aspineux at gmail.com (aspineux) Date: Tue, 15 Jan 2008 06:17:57 -0800 (PST) Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> Message-ID: On Jan 14, 8:07 pm, aspineux wrote: > On Jan 14, 7:49 pm, "Chris Mellon" wrote: > > > On Jan 14, 2008 12:39 PM, aspineux wrote: > > > > This append in both case > > > > dict(a=1).get('a', f()) > > > dict(a=1).setdefault('a', f()) > > > > This should be nice if f() was called only if required. > > > Think about the change to Python semantics that would be required for > > this to be true, and then use collections.defaultdict instead. > > Yes, I missed 'get' and 'setdefault' are functions :-) > Then why not some new semantic > > d.get('a', f()) --> d['a', f()] > d.setdefault('a', f()) --> d['a'=f()] > > Is is a good idea enough to change the python semantic ? > Or simply is it a good idea ? Thanks for all your answers. Anyway these notations are very compact, don't require the definition of a specific function, and work with old style/or already existing dictionary, dictionary you didn't created yourself. While the use of defaultdict require the definition of such a function and to control the creation of the dictionary. For me the best alternative that match the requirement above is the one provided by Paul Rubin. Regards. From mail at microcorp.co.za Tue Jan 15 10:07:32 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 15 Jan 2008 17:07:32 +0200 Subject: Interesting Thread Gotcha Message-ID: <000901c85788$74cfbfc0$03000080@hendrik> I thought I would share this nasty little gotcha with the group. Consider the following code fragment: print 'starting kbd thread' keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) print 'starting main loop' error = Mainloop(s,port_q,active_q_list) It produces, as output, the following: starting kbd thread we get here - a It does not print 'starting main loop', the Mainloop routine is never executed, and no exceptions are raised. Here is the offending routine that seems to capture the control: def kbd_driver(out_q,in_q): """ thread to look for keyboard input and to put it on the queue out_q also looks for replies on in_q and prints them """ kbdname = '/dev/stdin' kbd = open(kbdname,'r+',1) # Reading, line buffered unblock(kbd) # Call the magic to unblock keyboard print 'we get here - a' while True: try: d = kbd.readline() # see if any kbd input except: IOError try: msg=in_q.get(block=False) except Queue.Empty: time.sleep(0.1) continue print msg time.sleep(0.1) continue d = d.rstrip() # get rid of line feed out_q.put([d + '\r',in_q]) # add a carriage return and return q and send to port The unblock is a routine that unblocks a port using fcntl - it is not the problem. In case you don't believe me, here it is: def unblock(f): """Given file 'f', sets its unblock flag to true.""" fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) I will post the solution tomorrow when I read my mail, if no one has spotted it by then. - Hendrik From castironpi at gmail.com Sat Jan 12 13:55:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 10:55:05 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> <354c74f6-6e56-4e41-a686-56239aa4cea9@f47g2000hsd.googlegroups.com> <7x8x2uj3yb.fsf@ruckus.brouhaha.com> Message-ID: <0ad68aa8-735d-4cf0-b17a-d1f2be6af652@f47g2000hsd.googlegroups.com> On Jan 12, 12:26 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > 2) List is referenced by others; concurrent modifications may be going > > on; can not replace it. Can I make asynchronous modifications and > > merge the changes, SCM-style? > > Nothing else should have direct access to the list. Impossible to guarantee in Python. If you do, the reference to you does. From bperry.volatile at gmail.com Wed Jan 16 11:18:59 2008 From: bperry.volatile at gmail.com (Brandon Perry) Date: Wed, 16 Jan 2008 10:18:59 -0600 Subject: Unknown cause to error (new to python) In-Reply-To: <478e10bd$0$27280$426a34cc@news.free.fr> References: <478e10bd$0$27280$426a34cc@news.free.fr> Message-ID: <1200500339.6143.1.camel@bperry-laptop> Sorry, this is all I can get. :-( This isn't my webserver, so the only error logs I get are what they give me. I guess I will just have to keep working at it. Thanks for looking at it though, Brandon On Wed, 2008-01-16 at 15:12 +0100, Bruno Desthuilliers wrote: > Brandon Perry a ?crit : > > Hi, I am having to compile a standalone version of python for the web > > server I use (they don't allow access to /usr/bin/python). I posted > > earlier about a GLib error, but I have fixed that now. I am very close > > to getting this to work, but I am getting some weird errors. > > > > File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", > > line 41, in ? > > File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", line 71, in ? > > File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", line 4, in ? > > File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", line 4, in ? > > File "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", line 15, in ? > > Sorry but my crystal ball is broken. Please post the *whole* traceback. > From goon12 at gmail.com Sat Jan 12 14:07:04 2008 From: goon12 at gmail.com (Joe Riopel) Date: Sat, 12 Jan 2008 14:07:04 -0500 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** In-Reply-To: <47890e3e$0$26886$ecde5a14@news.coretel.net> References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> <4788de48$0$26887$ecde5a14@news.coretel.net> <47890e3e$0$26886$ecde5a14@news.coretel.net> Message-ID: <6a2ccd190801121107r7b728d09ve072909ba2863c04@mail.gmail.com> On Jan 12, 2008 2:00 PM, radiosrfun wrote: > Whether we agree on "tactics" or not - if it come to a battlefield with the > two of us - or any Americans there - we're still going to fight the same > enemy - not each other. This is a good resource for starting Python http://diveintopython.org/ From sjmachin at lexicon.net Fri Jan 4 17:28:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 4 Jan 2008 14:28:09 -0800 (PST) Subject: Tabnanny errors when Migrating Python 2.4 code to 2.5 References: <6d197192-0340-42f8-b764-cba91a92bb21@i3g2000hsf.googlegroups.com> Message-ID: <3e182358-9322-498a-822c-7a371c8b608f@e4g2000hsg.googlegroups.com> On Jan 5, 8:05 am, kyoso... at gmail.com wrote: > On Jan 4, 2:06 pm, John Machin wrote: > > > On Jan 5, 3:56 am, kyoso... at gmail.com wrote: > > > > Hi, > > > > When Python 2.5 first came out, I eagerly downloaded it and > > > immediately had issues with getting it to run my 2.4 code. So I just > > > stuck to 2.4. However, I decided this week that I really should try to > > > get 2.5 to work. Does anyone know why code that works perfectly for > > > months in a 2.4 environment throws indentation errors in 2.5? > > > No, not until you go to the bother of reproducing the problem with a > > small file, tell us what platform you are on, how you are running this > > code (IDLE, shell prompt, ...), how you installed Python 2.5 > > (2.5.1?), ... > > I'm using Windows XP, using IDLE (which was mentioned already) in the context of editing/displaying code, not executing it. Does the problem occur before or after you edit a file with IDLE? > and I > downloaded the 2.5.1 exe/msi file from python.org to install it. What you downloaded doesn't answer the question about how you installed it. Do you still have your 2.4 installation? > > I have yet to find a simple one which exhibits the issue to post. It > seems to happen to my complex files, not the simple ones. So chop up a complex file ... Have you inspected the failing files using a text editor that can display tabs and spaces (e.g. PythonWin, TextPad)? > > Sorry to bother you. You didn't bother me. You are bothering yourself by asking questions without enough information to get reasonable answers. From gordyt at gmail.com Wed Jan 9 15:46:10 2008 From: gordyt at gmail.com (gordyt) Date: Wed, 9 Jan 2008 12:46:10 -0800 (PST) Subject: ISO books of official Python docs References: fm38qu$6c7$1@reader2.panix.com Message-ID: <966c993a-2aa6-4724-852a-49d8da686675@k2g2000hse.googlegroups.com> Howdy kynnjo, > Is it possible to buy the official Python docs in book form? If > so, I'd very much appreciate the name(s) and author(s) of the > book(s). I haven't seen them in print form, but you can download PDF's from here: http://docs.python.org/download.html --gordy From DustanGroups at gmail.com Mon Jan 7 08:25:50 2008 From: DustanGroups at gmail.com (Dustan) Date: Mon, 7 Jan 2008 05:25:50 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <05595380-70b6-4e83-b15b-174af956c96c@j78g2000hsd.googlegroups.com> On Jan 7, 7:09 am, MartinRineh... at gmail.com wrote: > I'm a Java guy who's been doing Python for a month now and I'm > convinced that > > 1) a multi-paradigm language is inherently better than a mono-paradigm > language > > 2) Python writes like a talented figure skater skates. > > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is _______. > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > "grace" but I'm not sure I've done enough to choose. Here's a modest list: Masterly, tops, best obtainable, high-grade, very good, select, outstanding, exemplary, top-notch, boss, first-rate, crack, smashing, excelling, prime, skilled, crackerjack, sublime, super, terrific, peerless, notable, paramount, divine, premium, hand-picked, estimable, admirable, prize, choice, competent, desirable, attractive, foremost, to be desired, A-one, top-flight, dandy, incomparable, grade A, capital, great, dynamite, heavenly, unique, refined, matchless, high- quality, well-done, A-OK, blue-chip, frontline, sensational, highest, jim-dandy, splendid, extraordinary, exquisite, superlative, worthy, masterful, distinguished, magnificent, tiptop, accomplished, all right, first, first-class, fine, very fine, ace-high, exceptional, sharp, supreme, marvelous, transcendent, praiseworthy, custom-made, remarkable, world-class, invaluable, groovy, champion, rare, best, wonderful, superb, choicest, enticing, top, superfine, commendable, skillful, neat, striking, distinctive, priceless, sterling, superior, cool, classy, finest, hot, keen, above par. From mwm-keyword-python.b4bdba at mired.org Thu Jan 10 17:17:43 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 17:17:43 -0500 Subject: XML+Logs to Latex. XSLT? In-Reply-To: References: Message-ID: <20080110171743.5abc1e0b@bhuda.mired.org> On Thu, 10 Jan 2008 22:32:50 +0100 Fredrik Lundh wrote: > > Yes. For sure. I though XSLT was something like XML not other > > "language" and that Python will have any library that uses XSLT to do > > transformation... > XSLT is definitely a language (it's turing complete, after all), but > that there are of course several Python bindings to XSLT libraries; > here's one: XSLT is definitely something like XML - because an XSLT file is an XML file. But it represents a program, and hence is a programming language. It is unlike most other programming languages you will have encountered. XSLT may well be the most popular thing like XSLT, but Prolog is probably the language you've heard of that's closest to it. If you want to transform your XML into different-shaped XML or flat text, XSLT should be high on the list of tools to check out. > http://codespeak.net/lxml/ Very much recommended. > But please don't use SAX if you can avoid it; it's hard to work with, > and not very efficient. I'd recommend ElementTree, which is a light- > weight DOM library, that's part of the standard library: > http://effbot.org/zone/element-index.htm While I love the ElementTree API, the standard library implementation is missing tools that I find invaluable in working with XML. No schema support, for instance. The effort of maintaining a schema is repaid multiple times if you take advantage of it. If your application validates the XML on input, you *know* that when you translate a required attribute value to an the, the attribute will be there, and the it's value will repersent an int. And using a schema-aware editor is pretty much the only sane way for a human being to edit XML. The XPath implementation is also limited. Having written a little XSLT, not having pretty much all of XPath available for pulling values is painful. And of course, XSLT support, as there are things that XSLT is good for. Others I'm not so sure about. External entities seem to be unsupported by ElementTree. XInclude? More? > > Is this the way you will do it? > > As the author of ElementTree, I'm a bit biased, but I'd definitely do it > in Python ;-) Ditto - well, except I'm not the author of ElementTree. If all you want to do is read the XML into a tree of python strings, then the ElementTree implementation is an excellent API for doing so, and being in the standard library means you should already have it. If you want to leverage XML to make your job as easy as possible, then I'd recommend using the aforementioned lxml instead. It provides the same ElementTree API on top of the popular libxml2 and libxslt libraries (your Unix-like system probably comes with them pre-installed), and hence gives you access to all the XML tools they provide - like the ones I mentioned above. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From brett at python.org Mon Jan 28 20:20:09 2008 From: brett at python.org (Brett Cannon) Date: Mon, 28 Jan 2008 17:20:09 -0800 Subject: Announcing the Python core sprint at PyCon 2008 Message-ID: As has occurred since the inception of PyCon, there will be a sprint on the Python core at this year's conference! If you will be attending PyCon (or will be in Chicago during the dates of the sprints), attending the sprint is a great way to give back to Python. Working on Python itself tends to deepens one knowledge of the language and the standard library. Plus it is just plain fun getting to sit around some tables with fellow Python programmers for several days (the sprint will last four days, but you do not need to attend all four days to participate). The sprint is open to everyone of all skill levels. We can always use help with things from updating documentation to preparing for the next release of Python 3.0. On Sunday evening of the conference there will not only be a sprint intro session, but also a tutorial on how to develop for Python. Details will be covered from where to look in the code base for things to some best practices tips. If you are interested enough to want to sign up to attend, please go to http://wiki.python.org/moin/PyCon2008/SprintSignups/Python and add your name and email address. If you have questions you may email me. Please sign up for the sprint by the end of February as an email on what you need to do beforehand will be sent at that time based on the sprint sign-up page. And if you are not attending PyCon, we will most likely have several people in attendance on IRC, thus allowing even people not at PyCon to participate! -Brett Cannon Python core sprint coach, PyCon 2008 From steveo at syslang.net Fri Jan 4 17:55:33 2008 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 4 Jan 2008 17:55:33 -0500 (EST) Subject: Questions about subclassing an int Message-ID: class S(int): def __init__(self, value): self.value = value def addStr(self, str): self.doc = str s = S(44) s.addStr('Hello') print 's = ', s print 's.doc = ', s.doc class T(int): def __init__(self, value, str): self.value = value self.doc = str t = T(44, 'Goodbye') print 't = ', t print 't.doc = ', t.doc It works ok with S but it fails when I try to instantiate T with a syntax error. Why? Also, I don't understand why S works. If I change the name of value and use something else, the print of s still works by printing the integer value out. How does it know what value to use? Also, in S.__init__, should I be calling super(S, self).__init__(value) or is there a difference? And just for fun: class R(int): def __init__(self, value, doc): super(R, self).__init__(value) self.doc = doc r = R(66,'GGG') Traceback (most recent call last): File "", line 1, in ? TypeError: an integer is required Now it's no longer a syntax error but I don't see why it's different? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From terry at jon.es Wed Jan 23 10:45:30 2008 From: terry at jon.es (Terry Jones) Date: Wed, 23 Jan 2008 16:45:30 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 23:07:42 on Tuesday, 22 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> Message-ID: <18327.24858.376079.63735@jon.es> Hi Arnaud and Dan >>>>> "Arnaud" == Arnaud Delobelle writes: >> What was wrong with the very fast(?) code you sent earlier? Arnaud> I thought it was a bit convoluted, wanted to try something I Arnaud> thought had more potential. I think the problem with the second Arnaud> one is that I repeat the same 'fold' too many times. and later: Arnaud> Yes, I've been doing this by writing an 'action' (see my code) that Arnaud> takes note of all reached results. These are both comments about pruning, if I understand you. In the first you weren't pruning enough and in the second you're planning to prune more. I'm giving up thinking about this problem because I've realized that the pruning solution is fundamentally subjective. I.e., whether or not you consider two solutions to be the "same" depends on how hard you're willing to think about them (and argue that they're the same), or how smart you are. I have a new version that does some things nicely, but in trying to do efficient pruning, I've realized that you can't satisfy everyone. Some examples for the problem with target 253, numbers = 100, 9, 7, 6, 3, 1 Firstly, there are nice solutions that go way negative, like: 1 7 6 3 9 sub mul mul sub or 1 - 7 * 6 * (3 - 9) Here's a pruning example. Are these the "same"? 1 3 7 100 9 sub sub mul sub or 1 - 3 * (7 - 100 - 9) 1 3 7 9 100 sub add mul sub or 1 - 3 * (7 - 9 - 100) I think many people would argue that that's really the "same" and that one of the two should not appear in the output. The same goes for your earlier example for 406. It's 4 * 100 + 2 x 3, and 2 x 3 + 100 * 4, and so on. My latest program does all these prunings. But you can argue that you should push even further into eliminating things that are the same. You could probably make a pretty fast program that stores globally all the states it has passed through (what's on the stack, what numbers are yet to be used, what's the proposed op) and never does them again. But if you push that, you'll wind up saying that any two solutions that look like this: ....... 1 add e.g. 6 9 3 sub mul 7 mul 1 add or 6 * (9 - 3) * 7 + 1 7 6 mul 9 3 sub mul 1 add or 7 * 6 * (9 - 3) + 1 are the same. And if we go that far, then a really smart person might argue that this 100 7 sub 9 sub 3 mul 1 add or (100 - 7 - 9) * 3 + 1 is also the "same" (because all these solutions get to 252 and then add 1, so they're clearly the "same", right?): Once you've gone that far, you might even argue that on a particular problem of a particular difficulty (subjectively matching what your brain is capable of) all solutions that start out by pushing 1 onto the stack are actually the "same". And if you're even smarter than that, you might just look at any problem and say "Hey, that's easy! The answer is X" or "There's clearly no solution" because you'd immediately just see the answer (if any) and that all others were just obvious variants. E.g., if I said to you: "make 20 out of (20, 10, 10, 3)", I imagine you could immediately list the answer(s?) 20 = 20 20 = 10 + 10 20 = 20 + 10 - 10 20 = 20 - 10 + 10 etc., and explain that those are all really the same. You'd prune on the spot, and consider it obvious that the pruning was fully justified. But my 6-year-old son couldn't tell you that, and I doubt he'd agree with your prunings. OK, enough examples. I'm just trying to illustrate that the (difficult) problem of efficiently pruning doesn't have an objective solution. Pruning is subjective. OTOH, the decision problem "does this puzzle have any solutions or not (and if so, produce one)" does. That's why I'm going to stop working on this. My stack solution code is fun, but working on making it prune better is a black hole. And to make matters worse, the more I push it (i.e., the more advanced its prunings get), the less likely (some) people are to agree that its output is still correct. You can't win. If anyone wants the stack simulation code, send me an email. Terry From SSchukat at dspace.de Fri Jan 4 07:57:58 2008 From: SSchukat at dspace.de (Stefan Schukat) Date: Fri, 4 Jan 2008 13:57:58 +0100 Subject: pydepend (checking dependencies like jdepend) ? References: <1969e240-9e80-4df1-b085-7956dfa4f7ae@t1g2000pra.googlegroups.com> Message-ID: <3E7E58237D756A4D85E7A36CB8C953ED01E244@exchange2003.dspace.de> Hi, try to look at py2exe. This module scans all dependencies to pack them into one executable. Stefan -----Original Message----- From: python-list-bounces+sschukat=dspace.de at python.org [mailto:python-list-bounces+sschukat=dspace.de at python.org] On Behalf Of Bernhard Merkle Sent: Friday, January 04, 2008 1:14 PM To: python-list at python.org Subject: pydepend (checking dependencies like jdepend) ? Hi there, think %Subject says all. I am wondering if there is some tool to check dependencies within python programs. (something like jdepend for python ;-) Of course the dependencies are at runtime (dynamic) and not statically +dynamically (as in Java), but anyway it would be interesting to know of them (for better modularization e.g.) TIA, Berni. -- http://mail.python.org/mailman/listinfo/python-list From ganeshborse at gmail.com Wed Jan 30 02:38:46 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Tue, 29 Jan 2008 23:38:46 -0800 (PST) Subject: Replacing call to PyObject_CallObject with PyEval_CallFunction References: <5a99ab95-e225-4085-bce4-ea31da557d6d@j78g2000hsd.googlegroups.com> <740a5e65-64c3-45dc-95bf-691978fb4290@f47g2000hsd.googlegroups.com> Message-ID: <6e7b6586-ba2a-4e8b-8413-f7e666f6559e@s19g2000prg.googlegroups.com> On Jan 30, 1:58?pm, Gabriel Genellina wrote: > On 30 ene, 01:58, grbgooglefan wrote: > > > How do I pass the elements populated in struct variables of this > > vector dynamically to PyEval_CallFunction, in the fashion somewhat > > like below? > > PyEval_CallFunction(obj, "iii", vector[0].ioparam->nionum,vector[1].ioparam->nionum,vector[2].ioparam->nion?um); > > > PyEval_CallFunction(obj, "di", vector[0].ioparam->fionum,vector[1].ioparam->nionum); > > > PyEval_CallFunction(obj, "diiisis", vector[0].ioparam->fionum,vector[1].ioparam->nionum,vector[2].ioparam- > > >nionum,vector[3].ioparam->nionum,vector[4].ioparam- > > >ioString,vector[5].ioparam->nionum,vector[6].ioparam->ioString); > > I didn't know of PyEval_CallFunction until now, but aparently the > lines above are OK. Can't you use it that way? What's your problem? > > -- > Gabriel Genellina slowness of current code - vector is to parsed one by one & switch adds another time for checks. From paddy3118 at googlemail.com Fri Jan 25 02:51:52 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 23:51:52 -0800 (PST) Subject: Which is more pythonic? References: <56518bb9-1d56-47c3-8112-6e0778832c12@v29g2000hsf.googlegroups.com> Message-ID: <384a9c43-49e2-4feb-b21a-96f6b3a29a01@j78g2000hsd.googlegroups.com> On Jan 25, 5:14 am, "benjamin.zimmer... at gmail.com" wrote: > I have a goal function that returns the fitness of a given solution. I > need to wrap that function with a class or a function to keep track of > the best solution I encounter. Which of the following would best serve > my purpose and be the most pythonic? > > class Goal: > def __init__(self, goal): > self.goal = goal > self.best = None > self.best_score = None > > def __call__(self, solution): > score = self.goal(solution) > if self.best is None or score > self.best_score: > self.best_score = score > self.best = solution > return score > > def save_best_goal(goal): > def new_goal(solution): > score = goal(solution) > if new_goal.best is None or score > new_goal.best_score: > new_goal.best = solution > new_goal.best_score = score > return score > new_goal.best = new_goal.best_score = None > return new_goal > > -Ben You could also wrap the best score logic as a decorator applied to a function to save the best score as a function attribute. Whilst not class based, Python isn't solely an OO language. but if you know that extra capabilities are going to be needed you might favour the class based solution. - Paddy. From claird at lairds.us Tue Jan 1 20:04:55 2008 From: claird at lairds.us (Cameron Laird) Date: Wed, 2 Jan 2008 01:04:55 +0000 Subject: cloud computing (and python)? References: Message-ID: In article , Aaron Watters wrote: >So, in between skiing runs I noticed >a Business Week cover story on >"cloud computing". The article had >lots of interesting information in it like >about how somebody's mom used to >be an airline stewardess and the >interior decor of various office spaces. >It was a truly excellent piece of >journalism. > >However it gave me no idea what >"cloud computing" is and how it >could be used to solve a computational >problem. > >Could anyone on this list >which usually has highly informed >readers give me a clue at some >level of technical detail what cloud >computing is about and how it could >be used. Bonus points if you mention >Python in the response! > >An actual example would be great, >if it's not web scraping and searching. . . . Aaron, while I make time for a more pertinent response, might interest you. I owe you better examples, though. From stanc at al.com.au Fri Jan 18 00:28:42 2008 From: stanc at al.com.au (Astan Chee) Date: Fri, 18 Jan 2008 16:28:42 +1100 Subject: [python] How to detect a remote webpage is accessible? (in HTTP) In-Reply-To: References: Message-ID: <4790390A.7010406@al.com.au> How about: import socket, urllib2 timeout = 10 socket.setdefaulttimeout(timeout) try: auth_handler = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(auth_handler) #this used if we need authentication urllib2.install_opener(opener) req = urllib2.Request('http://website.com') f = urllib2.urlopen(req) notes= f.readlines() f.close() print "Everything is ok" except IOError, r: p = str(r) if re.search(r'urlopen error timed out',p): print "Web page timed out" You'll need to set up the timeout to whatever duration your website takes to load. Cheers Astan ?? wrote: > Howdy, all, > I want to use python to detect the accessibility of website. > Currently, I use urllib > to obtain the remote webpage, and see whether it fails. But the problem is that > the webpage may be very large; it takes too long time. Certainly, it > is no need to download > the entire page. Could you give me a good and fast solution? > Thank you. > -- > ShenLei > From lizm at rcsltd.co.uk Wed Jan 23 09:58:29 2008 From: lizm at rcsltd.co.uk (LizzyLiz) Date: Wed, 23 Jan 2008 06:58:29 -0800 (PST) Subject: csv to xls using python 2.1.3 References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> Message-ID: Perfect! Thanks :-) LizzyLiz From peng.kyo at gmail.com Thu Jan 17 01:07:02 2008 From: peng.kyo at gmail.com (J. Peng) Date: Thu, 17 Jan 2008 14:07:02 +0800 Subject: assigning values in python and perl In-Reply-To: <478EEF97.2070807@cheimes.de> References: <2d37f441-c01f-439b-9897-35b7e4dfa77b@h11g2000prf.googlegroups.com> <478EEF97.2070807@cheimes.de> Message-ID: <18c1e5f20801162207p18443838ma902c5bb740099a0@mail.gmail.com> On Jan 17, 2008 2:03 PM, Christian Heimes wrote: > George Sakkis wrote: > > Python's parameter passing is like passing a pointer in C/C++. > [snip] > > It's not (I repeat NOT) like passing a pointer in C. Please read > http://effbot.org/zone/call-by-object.htm > Yes I agree. Not the same at all. From rridge at caffeine.csclub.uwaterloo.ca Fri Jan 11 08:33:13 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 11 Jan 2008 08:33:13 -0500 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > And the reference implementation of Python (CPython) is not > interpreted, it's compiled to byte-code, which is then executed by a VM > (just like Java). Ross Ridge a ?crit : > Python's byte-code interpreter is not "just like" Java's virtual machine. Bruno Desthuilliers wrote: >of course it's not "just like" - different languages, different >byte-codes, different implementations. What is "just like" is the >byte-code/VM scheme. No the schemes aren't "just like" each other. They perform much differently. > Thought this was obvious to anyone able to parse a simple sentence. What's obvious is that you're lying. >> You're deliberately trying to mislead people into thinking Python performs >> similarily to Java. > >I don't know what you're smoking, but you should perhaps stop - because >this seems to drive you into parano?d delirium. This isn't the first time you've tried to mislead people into thinking Python's byte-code interpreter works just like Java's VM. Your over-zealous Python advocacy is benefiting no one. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From stefan.behnel-n05pAM at web.de Tue Jan 29 05:46:05 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 29 Jan 2008 11:46:05 +0100 Subject: Error in parsing XML for following test data In-Reply-To: References: Message-ID: <479F03ED.6080308@web.de> abhishek wrote: > I am having problem parsing following data set from XML. Please > provide hints on how to rectify this problem. > > I am using python2.4 version > > this is te test data that i am using -- > > """"""" > 1!!!!!!!!!!!!!!!11 > 2@@@@@@@@@@@@@@@22 > 3###############33 > 4$$$$$$$$$$$$$$$44 [...] How is this related to XML? Stefan From k_vinoj at yahoo.com Fri Jan 4 05:51:49 2008 From: k_vinoj at yahoo.com (vinoj davis) Date: Fri, 4 Jan 2008 16:21:49 +0530 (IST) Subject: how to connect to a remote machine using python........ Message-ID: <663493.85789.qm@web94609.mail.in2.yahoo.com> An HTML attachment was scrubbed... URL: From iclark at mail.ewu.edu Tue Jan 22 12:23:59 2008 From: iclark at mail.ewu.edu (Ian Clark) Date: Tue, 22 Jan 2008 17:23:59 +0000 (UTC) Subject: Curses and Threading References: <3924ad84-a513-4b25-b9af-cbd358f5d40a@i3g2000hsf.googlegroups.com> Message-ID: On 2008-01-22, Brett.Friermood at gmail.com wrote: >> In fact you have *two* threads: the main thread, and the one you create >> explicitly. > >> After you start the clock thread, the main thread continues executing, >> immediately entering the finally clause. >> If you want to wait for the other thread to finish, use the join() method. >> But I'm unsure if this is the right way to mix threads and curses. > > This is what the python documentation says: > > join([timeout]) > Wait until the thread terminates. This blocks the calling thread > until the thread whose join() method is called terminates. > > So according to this since I need to block the main thread until the > clock thread ends I would need the main thread to call > "cadtime().join()", correct? I'm not sure how to do this because I > don't have a class or anything for the main thread that I know of. I > tried putting that after cadtime().start() but that doesn't work. I > guess what I'm trying to say is how can I tell the main thread what to > do when it doesn't exist in my code? > > Thanks for the help > -Brett join() is a method on Thread objects. So you'll need a reference to the Thread you create, then call join() on that. thread = cadtime() thread.start() thread.join() Ian From loupgaroublond at gmail.com Fri Jan 4 10:07:44 2008 From: loupgaroublond at gmail.com (Yaakov Nemoy) Date: Fri, 4 Jan 2008 10:07:44 -0500 Subject: Memory Leaks and Heapy Message-ID: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> Hi list, Firstly, this is my first post here, so I hope I'm not breaking some unwritten etiquette rule about asking questions involving several different libraries. I'm trying to plug some memory leaks in a TurboGears program. We (the Fedora Project) have a few apps in Turbogears in infrastructure that all seem to be running into the same issues in a variety of configurations. Hopefully when I get to the cause of this in one app, Smolt, we can fix the others too. The app in question is Smolt, which uses TurboGears, SQLAlchemy with a MySQL backend, and simplejson for message passing between the server and client. Smolt takes voluntary hardware reports from its clients, and generally is configured to submit around the beginning of the month. Normally, our main data is cached by some separate processes that run short term, so we don't see any rapid memory growth, except for the beginning of each month, which makes isolating the problem to a few function calls fairly simple. To watch for memory growth, I simply have a client hammer the server with 1-3 threads submitting information simultaneously, 100 times, with a few deletion operations in between. To monitor for memory leaks, I'm using Heapy. To insert Heapy into the process, instead of calling 'start_server', a cherrypy method that does what you think it does and blocks, I'm using the module 'threading' to push it into a new thread. Using the process in heapy's documentation, I find that after running a single thread, there is about 1200 bytes of leaked memory. Despite this, the python process running the server has managed to grow from 16-18MB to something between 23-28MB each time I try this. After a second iteration, heapy shows 1168 bytes leaked. If heapy is correct, this means there are not many leaked objects in the python space. Running a larger example, say 100 threads, for a total of 10k submissions takes about an hour, and in the process, python baloons up to about 48MB. Still no signs of any missing objects. 48MB is not alot relatively speaking, but no amount of waiting seems to show python giving back that memory afterwards. On our production server, we have up to 200k machines all updating their information over a 3 day period, in which the server process manages to reach 600MB before we forcefully restart it. A couple of developers have mentioned that python might be fragmenting its memory space, and is unable to free up those pages. How can I go about testing for this, and are there any known problems like this? If not, what else can I do to look for leaks? -Yaakov From http Fri Jan 18 13:38:15 2008 From: http (Paul Rubin) Date: 18 Jan 2008 10:38:15 -0800 Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <7xlk6nou7c.fsf@ruckus.brouhaha.com> Tim Chase writes: > first = int(data[0]) > try: > count = int(data[1]) > except: > count = 0 By the time you're down to this kind of thing making a difference, it's probably more important to compile with pyrex or psyco. From ioscas at gmail.com Wed Jan 23 02:14:53 2008 From: ioscas at gmail.com (ioscas at gmail.com) Date: Tue, 22 Jan 2008 23:14:53 -0800 (PST) Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? Message-ID: Hi, I am looking for a HTML parser who can parse a given page into a DOM tree, and can reconstruct the exact original html sources. Strictly speaking, I should be allowed to retrieve the original sources at each internal nodes of the DOM tree. I have tried Beautiful Soup who is really nice when dealing with those god damned ill-formed documents, but it's a pity for me to find that this guy cannot retrieve original sources due to its great tidy job. Since Beautiful Soup, like most of the other HTML parsers in python, is a subclass of sgmllib.SGMLParser to some extent, I have investigated the source code of sgmllib.SGMLParser, see if there is anything I can do to tell Beautiful Soup where he can find every tag segment from HTML source, but this will be a time-consuming job. so... any ideas? cheers kai liu From sjmachin at lexicon.net Wed Jan 23 14:20:56 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 11:20:56 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <7x8x2g8isi.fsf@ruckus.brouhaha.com> Message-ID: <2b68cb79-220a-40db-9e6b-5b8ab9d41964@s13g2000prd.googlegroups.com> On Jan 24, 6:05 am, Paul Rubin wrote: > ryan k writes: > > Hello. I have a string like 'LNAME > > PASTA ZONE'. I want to create a list of those words and > > basically replace all the whitespace between them with one space so i > > could just do lala.split(). Thank you! > > import re > s = 'LNAME PASTA ZONE' > re.split('\s+', s) That is (a) excessive for the OP's problem as stated and (b) unlike str.split will cause him to cut you out of his will if his problem turns out to include leading/trailing whitespace: >>> lala = ' LNAME PASTA ZONE ' >>> import re >>> re.split(r'\s+', lala) ['', 'LNAME', 'PASTA', 'ZONE', ''] >>> lala.split() ['LNAME', 'PASTA', 'ZONE'] >>> From deets at nospam.web.de Wed Jan 23 18:27:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Jan 2008 00:27:44 +0100 Subject: Increment Variable Name In-Reply-To: References: Message-ID: <5vq0rjF1o724kU1@mid.uni-berlin.de> David Brochu schrieb: > This is probably really trivial but I'm stumped.... :-( > > Does anyone know how to increment a variable name? > > For example: > > I know the length of a list and I want to pass each element of a list to > a unique variable, thus I want to increment variable names. If the list > length = 4, i want to have the following variables: var1, var2, var3, var4. > Use a dictionary value_dict = {} for i, value in values: value_dict["var%i" % i] = value Diez From fredrik at pythonware.com Wed Jan 9 07:47:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 13:47:41 +0100 Subject: Collecting Rich Data Structures for students In-Reply-To: References: Message-ID: kirby.urner at gmail.com wrote: > Some have offered XML repositories, which I can well > understand, but in this case we're looking specifically for > legal Python modules (py files), although they don't have > to be Latin-1 (e.g. the sushi types file might not have a > lot of romanji). you can of course convert any XML file to legal Python code simply by prepending from xml.etree.ElementTree import XML data = XML(""" and appending """) and then using the ET API to navigate the data, but I guess that's not what you had in mind. From irmen.NOSPAM at xs4all.nl Thu Jan 17 19:24:57 2008 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 18 Jan 2008 01:24:57 +0100 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. In-Reply-To: References: <478FAC5A.50206@animats.com> Message-ID: <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> Christian Heimes wrote: > John Nagle wrote: >> It's possible to use "pickle" for interprocess communication over >> pipes, but it's not straightforward. > > IIRC the processing module uses pickle for IPC. Maybe you can get some > idea by reading its code? > > http://pypi.python.org/pypi/processing/0.40 > > Christian > So does Pyro: http://pyro.sourceforge.net/ However Pyro uses TCP-IP sockets for communication. It uses a small header that contains the size of the message and a few other things, and then the (binary by default) pickle stream. --irmen From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 28 12:19:06 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 28 Jan 2008 18:19:06 +0100 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: References: Message-ID: <479e0e88$0$1158$426a74cc@news.free.fr> Paddy a ?crit : (snip) > Is it not possible to write a function that queries its call stack > when run to find the name of all arguments and locals() of the level > above > so you could write: > > class test(object): > def __init__(self, x, y): > arg2inst() > > and automatically assign self.x=x; self.y=y ? Might be possible using the inspect module. But as far as I'm concerned, I'm not sure I really like the idea that much - no rationale here, just a feeling... From stefan.behnel-n05pAM at web.de Tue Jan 1 05:06:02 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 01 Jan 2008 11:06:02 +0100 Subject: ElementTree should parse string and file in the same way In-Reply-To: References: <4778A47B.9020201@web.de> Message-ID: <477A108A.20209@web.de> Peter Pei wrote: > To be preise [...] Preise the lord, not me. :) Happy New Year! Stefan From bearophileHUGS at lycos.com Tue Jan 15 04:53:24 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 15 Jan 2008 01:53:24 -0800 (PST) Subject: Data mapper - need to map an dictionary of values to a model References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com> Message-ID: <05398cdb-4c75-499b-bb52-d5de627a0906@j20g2000hsi.googlegroups.com> Luke: >What design patterns would you use here?< What about "generator (scanner) with parameters"? :-) Bye, bearophile From attn.steven.kuo at gmail.com Thu Jan 31 17:48:50 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 31 Jan 2008 14:48:50 -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> Message-ID: On Jan 31, 8:12 am, erikcw wrote: > Hi, > > I have a list of numbers each with a +/- margin of error. I need to > identify which ones overlab each other. > > For example: > 55 +/- 3 > 20 +/- 2 > 17 +/- 4 > 60 +/- 3 > > #base, max, min > list = [ > (55, 58, 52), > (20, 22, 18), > (17, 21, 13), > (60, 63, 57), > ] > > In this example the range of list[0] overlaps the range of list[3] AND > list[1] overlaps list[2] > > 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. > One way would be to use sets and check for intersection: for idx, s in enumerate(mysets): for next_idx, next_s in enumerate(mysets[idx+1:]): if s.intersection(next_s): print "mylist[%d] and mylist[%d] intersect" % ( idx, idx + next_idx + 1 ) -- Hope this helps, Steve From gandalf at shopzeus.com Fri Jan 11 08:57:11 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 11 Jan 2008 14:57:11 +0100 Subject: ftplib question (cannot open data connection) Message-ID: <478775B7.4040006@shopzeus.com> Hi All, I'm using a simple program that uploads a file on a remote ftp server. This is an example (not the whole program): def store(self,hostname,username,password,destdir,srcpath): self.ftp = ftplib.FTP(hostname) self.ftp.login(username,password) self.ftp.set_pasv(False) self.ftp.cwd(destdir) fobj = file(srcpath,"rb") destname = os.path.split(srcpath)[1] self.ftp.storbinary("STOR "+destname,fobj) The ftp server cannot use passive connections, and I can do nothing about that. Here is the problem: I can connect to this ftp server from my home computer, which is behind a NAT firewall. I can also connect to it from another computer, but I'm not able to upload any file. I tried to debug with a simple "ftp -v -d" command line program and apparently the problem is with the "EPRT" command: ftp> ls ---> EPRT |1|195.228.74.135|55749| 200 Port command successful. ---> LIST 425 Cannot open data connection. ftp> Well, the port number given by EPRT is bad - it is a closed port on this computer. I can open a small port range for this, but I would not like to open all ports and disable the firewall completely. Here are my questions: 1. How can I instruct ftplib to use specific ports for incoming connections? (For example, ports between 55000 and 56000). 2. How it is possible that the same program works from another computer that is behind a NAT firewall? Thanks, Laszlo From tinnews at isbd.co.uk Thu Jan 3 11:09:53 2008 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: 03 Jan 2008 16:09:53 GMT Subject: how to use bool References: Message-ID: <477d08d1$0$510$bed64819@news.gradwell.net> jimgardener at gmail.com wrote: > hi, i have some code where i set a bool type variable and if the value > is false i would like to return from the method with an error msg.. > being a beginner I wd like some help here > > class myclass: > ......... > def mymethod(self): > success=True > msg="all validation OK" > success=validateSthing() > if(success==False): > msg="sthing failed" > return (success,msg) > > dosomeprocessing() > ..... > success=validateSthingelse() > if(success==False): > msg="sthingelse failed" > return (success,msg) > domoreprocessing() > .... > return(success,msg) > > i would like to know if this way of doing this is OK..I have need of > many kinds of validations in this ..is there a better way of doing > this ? > With my philosophical programming hat on the first thing I'd say (as a fairly beginning python programmer) is "avoid multiple returns from a function/method if at all possible". They breed all sorts of problems and errors, in particular if there's any clearing up to do you have to do it in lots of places (or you forget it in some places). So:- def mymethod(self): msg="sthing failed" success=validateSthing() if success: dosomeprocessing() ..... success=validateSthingelse() if success: domoreprocessing() .... msg="all validation OK" return (success,msg) I've lost the different messages for different errors but you get the idea. "if success:" rather than "if (success==True)", more readable. For the opposite "if not success:". -- Chris Green From rw at smsnet.pl Mon Jan 28 09:26:05 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Mon, 28 Jan 2008 06:26:05 -0800 (PST) Subject: Set ulimit when using subprocess.Popen? References: Message-ID: Jarek Zgoda napisa?(a): > Rob Wolfe napisa?(a): > > > > Jarek Zgoda napisa?(a): > >> Hi, all, > >> > >> anybody has an idea on how to set ulimit (-v in my case, linux) for > >> process started using subprocess.Popen? > > > > What about: > > > > from subprocess import call > > call('ulimit -v 1000 && ulimit -v && ls', shell=True) > > subprocess.Popen('ulimit -v 1024; ls', shell=True) works perfect. > > Unfortunately, the nature of ulimit impacts deadly my application when > the limit is reached, so this knowledge is of no help in my case. ;) Use "ulimit -v unlimited" then. RW From stefan_ml at behnel.de Thu Jan 31 13:05:25 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 31 Jan 2008 19:05:25 +0100 Subject: REALLY simple xml reader In-Reply-To: <47A206D5.8020408@behnel.de> References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> <87tzkujeq6.fsf@benfinney.id.au> <13q3ri2707niqc6@corp.supernews.com> <47A206D5.8020408@behnel.de> Message-ID: <47A20DE5.3010407@behnel.de> Stefan Behnel wrote: > Steven D'Aprano wrote: >> 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. > [had a good laugh here] >> This is legal XML: >> >> """ >> Hello, world!""" >> >> and so is this: >> >> """ >> Hello, world!""" >> >> >> but not this: >> >> """ >> Hello, world!""" > > It's actually not that stupid. When you leave out the declaration, then the > XML is UTF-8 encoded (by spec), so normal ASCII whitespace doesn't matter. Sorry, strip the "ASCII" here. From the XML spec POV, your example """ Hello, world!""" is exactly equivalent to """ Hello, world!""" and whitespace between the declaration and the root element is allowed. It's just not allowed *before* the declaration, which in your case was left out, thus implying the default declaration. Stefan From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jan 15 14:22:22 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 15 Jan 2008 20:22:22 +0100 Subject: "env" parameter to "popen" won't accept Unicode on Windows -minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net><5v2cudF1k5a1oU1@mid.individual.net><478c551a$0$36354$742ec2ed@news.sonic.net> <5v3dq9F1k2577U1@mid.uni-berlin.de> Message-ID: <5v4ffeF1knst3U1@mid.individual.net> Brian Smith wrote: > popen() knows that it is running on Windows, and it knows what > encoding Windows needs for its environment (it's either UCS2 or > UTF-16 for most Windows APIs). At least when it receives a unicode > string, it has enough information to apply the conversion > automatically, and doing so saves the caller from having to figure > out what exact encoding is to be used. So you propose Python should employ a hidden automatism that automagically guesses the right encoding? Why not leave it explicitly/consistently and let the user decide? What will happen if a future Windows changes its encoding? Will we need another magic routine to tell it apart? Regards, Bj?rn -- BOFH excuse #353: Second-system effect. From steven.bethard at gmail.com Tue Jan 29 19:56:42 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 29 Jan 2008 17:56:42 -0700 Subject: breaking out of outer loops In-Reply-To: References: Message-ID: Jeremy Sanders wrote: > noemailplease0001 at gmail.com wrote: > >> Any elegant way of breaking out of the outer for loop than below, I >> seem to have come across something, but it escapes me >> >> for i in outerLoop: >> for j in innerLoop: >> if condition: >> break >> else: >> continue >> break > > Perhaps Python needs a "continue N" or a "break N" statement :-) > > for i in outerLoop: > for j in innerLoop: > if condition: > break 2 > > Seeing as we can't have a goto :-) Not true! You just have to import it: http://entrian.com/goto/ STeVe From ask at me Thu Jan 17 15:36:19 2008 From: ask at me (alf) Date: Thu, 17 Jan 2008 14:36:19 -0600 Subject: how django discovers changed sources In-Reply-To: References: <18udndZmKMfMNhLanZ2dnUVZ_rzinZ2d@comcast.com> <18udndFmKMfgMRLanZ2dnUVZ_rzinZ2d@comcast.com> Message-ID: Jeff wrote: > On Jan 17, 2:51 pm, "Guilherme Polo" wrote: >> 2008/1/17, alf :> Jeff wrote: >>>> That is the behavior of the development server. When you are writing >>>> your application, you don't want to have to manually restart the >>>> server every time you change a file. On apache it obviously doesn't >>>> do that. >>> thx for clarification, but still I am curious how it is done under the >>> hood. it really impressed me ... >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> It checks if modification time on registered files have changed since last check >> >> -- >> -- Guilherme H. Polo Goncalves > > django.utils.autoreload provides the functionality. thx for the reference, Andy From davidtweet at gmail.com Sat Jan 19 18:02:00 2008 From: davidtweet at gmail.com (David Tweet) Date: Sat, 19 Jan 2008 15:02:00 -0800 Subject: Default attribute values pattern In-Reply-To: References: Message-ID: <3fd0162e0801191502k57fb81f6q472e9b077a585ccd@mail.gmail.com> Hello, Seems to me that setattrs sort of assumes that you want to have all your initialization arguments set as attributes of the same name. I would think you'd sometimes want to be able to process the extra arguments inside of each __init__, assign them to attributes with different names, etc. My approach would be to treat each __init__ as a wrapping function, grabbing the items it needs out of the keyword dictionary and then calling the next __init__. Curious to hear other approaches though: def Grab(argdict, key, default): """Like argdict.get(key, default), but also deletes key from argdict.""" if key in argdict: retval = argdict["key"] del(argdict[key]) else: retval = default return retval class Base(object): def __init__(self, x=0, y=None): print "in Base init" self.x = x self.y = y class Derived1(Base): def __init__(self, **kwargs): print "in Derived1 init" self.z = Grab(kwargs, "z", None) super(Derived1, self).__init__(**kwargs) class Derived2(Derived1): def __init__(self, **kwargs): print "in Derived2 init" self.a = Grab(kwargs, "a", 0) self.b = Grab(kwargs, "b", False) super(Derived2, self).__init__(**kwargs) print self.__dict__ newthing = Derived2(x=234, y="blah", a=55555) On Jan 19, 2008 10:14 AM, George Sakkis wrote: > A situation that often comes up is having to initialize several > instance attributes that accept a default value. For a single class, > passing the default values in __init__ is fine: > > class Base(object): > def __init__(self, x=0, y=None): > self.x = x > self.y = y > > For inherited classes that need to override __init__ while keeping a > compatible interface though, the default values have to be repeated: > > class Derived(Base): > def __init__(self, x=0, y=None, z=''): > super(Derived,self).__init__(self,x,y) > self.z = '' > > For just two attributes and two classes that's maybe not too bad but > for many attributes and/or derived classes that may span multiple > modules, that doesn't seem to scale from a maintenance point of view, > especially if the defaults change over time. > > A pattern I've been using lately instead is store the defaults in > class attributes and let __init__ accept keyword arguments: > > class Base(object): > > x = 0 > y = None > > def __init__(self, **kwds): > setattrs(self, kwds) > > where setattrs is: > > def setattrs(self, attrvals, strict=True): > if strict: > # raise AttributeError if some attr doesn't exist already > for attr in attrvals.iterkeys(): > getattr(self,attr) > for attr,val in attrvals.iteritems(): > setattr(self, attr, val) > > This way, only the new and overriden default attributes have to > repeated in derived classes: > > class Derived(Base): > > x = 1 > z = '' > > def __init__(self, **kwds): > super(Derived,self).__init__(**kwds) > print 'In Derived.__init__' > > > Is this a good way of doing it ? Is there a better pattern ? > > George > -- > http://mail.python.org/mailman/listinfo/python-list > -- -David From ggpolo at gmail.com Mon Jan 7 09:33:55 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 12:33:55 -0200 Subject: introspection question In-Reply-To: References: Message-ID: 2008/1/7, Alex K : > Hi Guys, > > What would be the simplest way of enumerating all methods and members > (including inherited) of a given object? Thank you. > > Alex > -- > http://mail.python.org/mailman/listinfo/python-list > import inspect inspect.getmembers(yourobject) -- -- Guilherme H. Polo Goncalves From steve at REMOVE-THIS-cybersource.com.au Wed Jan 30 20:08:42 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 31 Jan 2008 01:08:42 -0000 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! References: Message-ID: <13q27sqncv487a9@corp.supernews.com> On Wed, 30 Jan 2008 19:40:24 -0500, Blubaugh, David A. wrote: > I do not understand why no one has answered the following question: > > Has anybody worked with Gene Expression Programming???? Yes, people have worked with Gene Expression Programming. I don't know who. I don't know where. But I'm sure that there have been people who have worked with it. -- Steven From http Mon Jan 21 18:08:30 2008 From: http (Paul Rubin) Date: 21 Jan 2008 15:08:30 -0800 Subject: Transforming ascii file (pseduo database) into proper database References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> <051e9305-6f9a-4d95-91cb-641c04b97b79@e10g2000prf.googlegroups.com> Message-ID: <7x4pd63hg1.fsf@ruckus.brouhaha.com> "p." writes: > So as an exercise, lets assume 800MB file, each line of data taking up > roughly 150B (guesstimate - based on examination of sample data)...so > roughly 5.3 million unique IDs. I still don't understand what the problem is. Are you familiar with the concept of external sorting? What OS are you using? If you're using a Un*x-like system, the built-in sort command should do what you need. "Internal" sorting means reading a file into memory and sorting it in memory with something like the .sort() function. External sorting is what you do when the file won't fit in memory. Basically you read sequential chunks of the file where each chunk fits in memory, sort each chunk internally and write it to a temporary disk file, then merge all the disk files. You can sort inputs of basically unlimited size this way. The unix sort command knows how to do this. It's often a good exercise with this type of problem, to ask yourself how an old-time mainframe programmer would have done it. A "big" computer of the 1960's might have had 128 kbytes of memory and a few MB of disk, but a bunch of magtape drives that held a few dozen MB each. With computers like that, they managed to process the phone bills for millions of people. The methods that they used are still relevant with today's much bigger and faster computers. If you watch old movies that tried to get a high tech look by showing computer machine rooms with pulsating tape drives, external sorting is what those computers spent most of their time doing. Finally, 800MB isn't all that big a file by today's standards. Memory for desktop computers costs around 25 dollars per gigabyte so having 8GB of ram on your desk to crunch those 800MB files with is not at all unreasonable. From boblatest at yahoo.com Tue Jan 8 04:20:16 2008 From: boblatest at yahoo.com (Robert Latest) Date: 8 Jan 2008 09:20:16 GMT Subject: popen question Message-ID: <5ugtigF1ia3o4U5@mid.dfncis.de> Hello, look at this function: -------------- def test(): child = os.popen('./slow') for line in child: print line ------------- The program "slow" just writes the numbers 0 through 9 on stdout, one line a second, and then quits. I would have expected the python program to spit out a numbers one by one, instead I see nothing for 10 seconds and then the whole output all at once. How can I get and process the pipe's output at the pace it is generated? Thanks, robert From deets at nospam.web.de Wed Jan 23 18:14:49 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Jan 2008 00:14:49 +0100 Subject: creating .pyo with make In-Reply-To: <4797c8d7$0$16956$426a74cc@news.free.fr> References: <4797c5d7$0$20781$426a34cc@news.free.fr> <4797c8d7$0$16956$426a74cc@news.free.fr> Message-ID: <5vq03cF1mod1jU1@mid.uni-berlin.de> Yann Leboulanger schrieb: > Yann Leboulanger wrote: >> Hi, >> >> I use autoconf / automake to manage my python project, and I'l like >> make / make install to create / install .pyo files instead of .py files. >> >> Is there something I should add to my Makefile.am files to do that? Or >> should I do all that myself with py_compile module? >> >> Are there some examples somewhere with autotools? >> >> Thanks for your help > > Hehe replying to myself. It seems I just have to replace > project_DATA = $(srcdir)/*.py > by > project_PYTHON = $(srcdir)/*.py > > Then when I do make install, it installs .py, .pyc and .pyo. > Would it be possible to install only .pyo? Is it a good idea? There might be the occasional code that relies on doc-strings to work - seldomly, but possible. Which are obmitted by .pyo, but not of pyc. Apart from that, having only pyc-files (or pyo for that matter) sucks. Just today I had to delve into a ZOPE-application, setting breakpoints and getting things done. It would have been impossible or at least much more inconvenient to debug if I hadn't had the sources available (and put at a place where they actually get invoked from the interpreter, not lying around unrelated) Diez From alnilam at gmail.com Tue Jan 22 16:20:32 2008 From: alnilam at gmail.com (Alnilam) Date: Tue, 22 Jan 2008 13:20:32 -0800 (PST) Subject: HTML parsing confusion References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> <50269e4a-af44-4d73-b6cb-c42af6b5164d@e10g2000prf.googlegroups.com> <5vmkiiF1nadr7U1@mid.uni-berlin.de> Message-ID: On Jan 22, 11:39?am, "Diez B. Roggisch" wrote: > Alnilam wrote: > > On Jan 22, 8:44 am, Alnilam wrote: > >> > Pardon me, but the standard issue Python 2.n (for n in range(5, 2, > >> > -1)) doesn't have an xml.dom.ext ... you must have the mega-monstrous > >> > 200-modules PyXML package installed. And you don't want the 75Kb > >> > BeautifulSoup? > > >> I wasn't aware that I had PyXML installed, and can't find a reference > >> to having it installed in pydocs. ... > > > Ugh. Found it. Sorry about that, but I still don't understand why > > there isn't a simple way to do this without using PyXML, BeautifulSoup > > or libxml2dom. What's the point in having sgmllib, htmllib, > > HTMLParser, and formatter all built in if I have to use use someone > > else's modules to write a couple of lines of code that achieve the > > simple thing I want. I get the feeling that this would be easier if I > > just broke down and wrote a couple of regular expressions, but it > > hardly seems a 'pythonic' way of going about things. > > This is simply a gross misunderstanding of what BeautifulSoup or lxml > accomplish. Dealing with mal-formatted HTML whilst trying to make _some_ > sense is by no means trivial. And just because you can come up with a few > lines of code using rexes that work for your current use-case doesn't mean > that they serve as general html-fixing-routine. Or do you think the rather > long history and 75Kb of code for BS are because it's creator wasn't aware > of rexes? > > And it also makes no sense stuffing everything remotely useful into the > standard lib. This would force to align development and release cycles, > resulting in much less features and stability as it can be wished. > > And to be honest: I fail to see where your problem is. BeatifulSoup is a > single Python file. So whatever you carry with you from machine to machine, > if it's capable of holding a file of your own code, you can simply put > BeautifulSoup beside it - even if it was a floppy ?disk. > > Diez I am, by no means, trying to trivialize the work that goes into creating the numerous modules out there. However as a relatively novice programmer trying to figure out something, the fact that these modules are pushed on people with such zealous devotion that you take offense at my desire to not use them gives me a bit of pause. I use non-included modules for tasks that require them, when the capability to do something clearly can't be done easily another way (eg. MySQLdb). I am sure that there will be plenty of times where I will use BeautifulSoup. In this instance, however, I was trying to solve a specific problem which I attempted to lay out clearly from the outset. I was asking this community if there was a simple way to use only the tools included with Python to parse a bit of html. If the answer is no, that's fine. Confusing, but fine. If the answer is yes, great. I look forward to learning from someone's example. If you don't have an answer, or a positive contribution, then please don't interject your angst into this thread. From http Thu Jan 24 19:14:40 2008 From: http (Paul Rubin) Date: 24 Jan 2008 16:14:40 -0800 Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <4799285d$0$36346$742ec2ed@news.sonic.net> Message-ID: <7x3asmep73.fsf@ruckus.brouhaha.com> John Nagle writes: > - Get enough memory to do the sort with an in-memory sort, like > UNIX "sort" or Python's "sort" function. Unix sort does external sorting when needed. From sergio.correia at gmail.com Wed Jan 30 19:54:11 2008 From: sergio.correia at gmail.com (Sergio Correia) Date: Wed, 30 Jan 2008 19:54:11 -0500 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> Message-ID: is this some kind of joke? if you get no answers, then the answer is no On Jan 30, 2008 7:40 PM, Blubaugh, David A. wrote: > I do not understand why no one has answered the following question: > > Has anybody worked with Gene Expression Programming???? > > > 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: Wednesday, January 30, 2008 6:10 PM > To: python-list at python.org > Subject: Python-list Digest, Vol 52, Issue 437 > > 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. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From skip at pobox.com Tue Jan 15 10:10:38 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 15 Jan 2008 09:10:38 -0600 Subject: Why this apparent assymetry in set operations? Message-ID: <18316.52462.481389.962217@montanaro.dyndns.org> I've noticed that I can update() a set with a list but I can't extend a set with a list using the |= assignment operator. >>> s = set() >>> s.update([1,2,3]) >>> s set([1, 2, 3]) >>> s |= [4,5,6] Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for |=: 'set' and 'list' >>> s |= set([4,5,6]) >>> s set([1, 2, 3, 4, 5, 6]) Why is that? Doesn't the |= operator essentially map to an update() call? Skip From Scott.Daniels at Acm.Org Tue Jan 1 16:34:48 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 01 Jan 2008 13:34:48 -0800 Subject: confusion about package/module imports In-Reply-To: References: Message-ID: <13nlc7fecs63099@corp.supernews.com> Jugdish wrote: > Why doesn't the following work? > ... [well boiled-down code skipped] >>>> setenv PYTHONPATH $HOME:$PYTHONPATH >>>> python $HOME/pkg/subpkg/b.py > Traceback (most recent call last): > File "pkg/subpkg/b.py", line 1, in ? > import pkg.subpkg.a > File "$HOME/pkg/subpkg/__init__.py", line 2, in ? > import b > File "$HOME/pkg/subpkg/b.py", line 2, in ? > class B(pkg.subpkg.a.A): > AttributeError: 'module' object has no attribute 'subpkg' OK, here's a trick for finding import problems: python -v (shows all imports) And for this case: sprinkle prints to find out what is happening. so, add "print __name, __file__" to the top of each file where you wonder what is going on. I later added prints in pkg/subpkg/__init__.py to make the steps clear. You'll see that b is executed (making module __main__), it imports pkg.subpkg.a, which is accomplished by importing pkg (successfully), then by importing pkg.subpkg which imports pkg.subpkg.a (successfully) and then imports pkg.subpkg.b which then attempts to import pkg.subpkg.a At that point, only the module pkg and what should eventually become pkg.subpkg.a have been successfully imported. pkg.subpkg had not yet been imported. If you remove the "import b" from subpkg's __init__, you will find your problems going away. Alternatively, you can remove the import a / import b from subpkg and add import subpkg.a, subpkg.b to pkg's __init__. Essentially, you need pkg.subpkg fully imported before you import pkg.subpkg.b Of course, in most of these cases you will have imported the code for b twice, once as a main program, and once as a module in the hierarchy, which is probably your actual problem (and why I use "print __name__, __file__"). --Scott David Daniels Scott.Daniels at Acm.Org From jzgoda at o2.usun.pl Fri Jan 18 05:03:54 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 18 Jan 2008 11:03:54 +0100 Subject: [python] How to detect a remote webpage is accessible? (in HTTP) In-Reply-To: References: Message-ID: ?? napisa?(a): > Howdy, all, > I want to use python to detect the accessibility of website. > Currently, I use urllib > to obtain the remote webpage, and see whether it fails. But the problem is that > the webpage may be very large; it takes too long time. Certainly, it > is no need to download > the entire page. Could you give me a good and fast solution? > Thank you. Issue HTTP HEAD request. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From bj_666 at gmx.net Wed Jan 2 06:29:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Jan 2008 11:29:35 GMT Subject: wxpython application ( problem ? ) References: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> Message-ID: <5u1asvF1fgr5bU2@mid.uni-berlin.de> On Wed, 02 Jan 2008 03:24:56 -0800, vedrandekovic wrote: > Here is sample of my simple script with wxpython and modules: > subprocess,threading, directpython....... Are you accessing the GUI from threads? Ciao, Marc 'BlackJack' Rintsch From http Mon Jan 21 03:34:46 2008 From: http (Paul Rubin) Date: 21 Jan 2008 00:34:46 -0800 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <80e1aed1-1d75-4409-bbc3-d48f9c3656ab@e6g2000prf.googlegroups.com> Message-ID: <7x8x2jh909.fsf@ruckus.brouhaha.com> Arnaud Delobelle writes: > Update: 2, 4, 5, 8, 9, 25 can reach any target between 100 and 999. Are you sure? What expression do you get for target = 758? From fredrik at pythonware.com Wed Jan 9 02:51:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 08:51:06 +0100 Subject: Open a List of Files In-Reply-To: <18308.12959.742868.758136@terry.local> References: <874pdomrrd.fsf@mulj.homelinux.net> <18308.12959.742868.758136@terry.local> Message-ID: Terry Jones wrote: > I think you should revisit this decision. Something like Fredrik's code is > the way to go. He used my suggestion, just for a few more files than he had in his original post. Seriously, for a limited number of files, the dictionary approach is mostly pointless; you end up replacing foo = open("foo") foo.write(...) with somedict["foo"] = open("foo") somedict["foo"].write(...) which, frankly, sucks in a whole lot of ways. > It has multiple advantages: > > - It's much shorter. For a small number of files, it isn't, really. > - It's arguably easier to add/remove to/from. Only if you're not using the files you're opening; as soon you try to do something with them, it's more work. > - It has less risk of error (much less repetition). No, it hasn't. There's more to type when using the files, and you have *two* things you can misspell; that is, you're replacing a NameError with either a NameError or a KeyError. > - It allows your code to later take a string file tag and > write to that file by looking up its file descriptor in the dict. Instead of allowing your code to take a file object and write to that file by writing to that file object? > - You can close all open files with a trivial loop. Ok, this is actually an advantage. Not that you need to do that very often, since Python does it for you. And if you find yourself needing to do this a lot, you can of course stuff all the output files in a list but *still* use the variables to refer to the file when writing to them. ::: There is one case where a dictionary of files makes perfect sense, of course, and that's when you can associate the file with some *other* value that you're *already* using. (Say, a user name or a machine name or a severity level or something like that.) But inventing your own string tags to use instead of variables is just plain bad design. From electronixtar at gmail.com Wed Jan 2 07:38:09 2008 From: electronixtar at gmail.com (est) Date: Wed, 2 Jan 2008 04:38:09 -0800 (PST) Subject: dbus-python for windows Message-ID: <194e7fee-728a-48eb-9f51-1e272ecca838@j20g2000hsi.googlegroups.com> Hi all I am trying to port Scribes to Windows, but I could not find a package named dbus-python for windows. There is a windbus but it not for Python, so how could I install dbus module for Windows Python 2.5 ? ps Is there anyone trying to port Scribes to Windows? From spaceoutlet at gmail.com Wed Jan 9 07:47:18 2008 From: spaceoutlet at gmail.com (Alex K) Date: Wed, 9 Jan 2008 13:47:18 +0100 Subject: PIL question Message-ID: Hello, Would anyone know how to generate thumbnails with rounded corners using PIL? I'm also considering imagemagick if PIL turns out not to be appropriate for the task. Thank you so much, Alex From mark.e.tolonen at mailinator.com Sat Jan 26 12:34:27 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Sat, 26 Jan 2008 09:34:27 -0800 Subject: Beginner String formatting question References: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> Message-ID: wrote in message news:68769e37-7787-414f-abd3-a447341e9f7d at v17g2000hsa.googlegroups.com... > Hi all, > > I am trying to write a simple program that will accept an integral > "time" input in the HHMMSS format and output a "HH:MM:SS" form. My > code is as follows: > ======================== > import string > > def FormatTime(time): > '''Converts an HHMMSS string to HH:MM:SS format.''' > > timeString = str(time) #converts the num to string > > hours = [timeString[0], timeString[1]] > minutes = [timeString[2], timeString[3]] > seconds = [timeString[4], timeString[5]] > > Ftime = "%s:%s:%s",(hours,minutes,seconds) > clock = Ftime.join() > > return clock > =========================== > > when I run it from IDLE, I get this: > >>>> Format.FormatTime(time) > ['1', '1', ':', '2', '2', ':', '3', '3'] > ['1', '1', ':', '2', '2', ':', '3', '3'] > > My questions- > 1) Why is this function printing out twice? > 2)It may be a formatting issue, but I want to have the output as > "HH:MM:SS", rather than having it broken out into each cell. I > thought the 'join' command would do this, but I must not be using it > properly/understanding something. > 3)as a side note, I've noticed that the parameter "time" passed in > must be passed in as a string, otherwise I receive an error that > "time" is unsubscriptable. Am I unable to pass in an int and then > convert it to a string within the function with str()? > > I've been at this for a while, so I may not be able to see the forest > through the trees at this point. I'd greatly appreciate any > suggestions or instruction on these mistakes. > > Best, > > Jimmy Your code as displayed above doesn't work. >>> Format.FormatTime(112233) Traceback (most recent call last): File "", line 1, in File "Format.py", line 13, in FormatTime clock = Ftime.join() AttributeError: 'tuple' object has no attribute 'join' >>> Format.FormatTime('112233') Traceback (most recent call last): File "", line 1, in File "Format.py", line 13, in FormatTime clock = Ftime.join() AttributeError: 'tuple' object has no attribute 'join' Make sure to copy/paste the exact working code. Look at the 'time' and 'datetime' modules and the functions and methods 'strftime' and 'strptime' for displaying and parsing times. --Mark From steve at REMOVE-THIS-cybersource.com.au Sat Jan 5 00:24:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 05 Jan 2008 05:24:19 -0000 Subject: How a smart editor could make "Postfix type declarations PEP3117" in Python3000 more readable References: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> Message-ID: <13nu54396vganbc@corp.supernews.com> On Fri, 04 Jan 2008 19:39:13 -0800, aspineux wrote: > Hi > > I read the PEP 3117 about the new "Postfix type declarations" in > Python3000. > THIS PEP as been REJECTED ! But ... > > The notation in the PEP is very ugly ! This make python code more > difficult to read! Please look at the date on the PEP: http://www.python.org/dev/peps/pep-3117/ -- Steven From kyosohma at gmail.com Tue Jan 15 15:36:58 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 15 Jan 2008 12:36:58 -0800 (PST) Subject: A question about event handlers with wxPython References: <478c3bb2$0$5150$4c368faf@roadrunner.com> <2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com> <478ccbc3$0$11000$4c368faf@roadrunner.com> <478d15b4$0$18437$4c368faf@roadrunner.com> Message-ID: <0571a7cd-f7f6-44b4-a4d5-e427de93590a@c4g2000hsg.googlegroups.com> On Jan 15, 2:20 pm, "Erik Lind" wrote: > That all looks cool. I will experiment more. I'm a bit slow on this as only > two weeks old so far. > > Thanks for the patience No problem. I'm pretty slow with some toolkits too...such as SQLAlchemy. Ugh. Mike From stef.mientki at gmail.com Tue Jan 22 16:35:45 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 22 Jan 2008 22:35:45 +0100 Subject: get the size of a dynamically changing file fast ? In-Reply-To: <198fd91f-912b-4f56-a840-af96225125a7@c23g2000hsa.googlegroups.com> References: <198fd91f-912b-4f56-a840-af96225125a7@c23g2000hsa.googlegroups.com> Message-ID: <479661B1.8010005@gmail.com> Mike Driscoll wrote: > On Jan 17, 3:56 pm, Stef Mientki wrote: > >> hello, >> >> I've a program (not written in Python) that generates a few thousands >> bytes per second, >> these files are dumped in 2 buffers (files), at in interval time of 50 msec, >> the files can be read by another program, to do further processing. >> >> A program written in VB or delphi can handle the data in the 2 buffers >> perfectly. >> Sometimes Python is also able to process the data correctly, >> but often it can't :-( >> >> I keep one of the files open en test the size of the open datafile each >> 50 msec. >> I have tried >> os.stat ( ....) [ ST_SIZE] >> os.path.getsize ( ... ) >> but they both have the same behaviour, sometimes it works, and the data >> is collected each 50 .. 100 msec, >> sometimes 1 .. 1.5 seconds is needed to detect a change in filesize. >> >> I'm using python 2.4 on winXP. >> >> Is there a solution for this problem ? >> >> thanks, >> Stef Mientki >> > > Tim Golden has a method to watch for changes in a directory on his > website: > > http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html > > This old post also mentions something similar: > > http://mail.python.org/pipermail/python-list/2007-October/463065.html > > And here's a cookbook recipe that claims to do it as well using > decorators: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/426620 > > Hopefully that will get you going. > > Mike > thanks Mike, sorry for the late reaction. I've it working perfect now. After all, os.stat works perfectly well, the problem was in the program that generated the file with increasing size, by truncating it after each block write, it apperently garantees that the file is flushed to disk and all problems are solved. cheers, Stef Mientki From t.rectenwald at gmail.com Thu Jan 3 20:25:18 2008 From: t.rectenwald at gmail.com (t_rectenwald) Date: Thu, 3 Jan 2008 17:25:18 -0800 (PST) Subject: Cursors in a Loop References: <3da337d8-2de0-4fdb-8c38-2f6fcd8348ac@i72g2000hsd.googlegroups.com> Message-ID: On Jan 3, 7:47?pm, t_rectenwald wrote: > I have a python script that uses the cx_Oracle module. ?I have a list > of values that I iterate through via a for loop and then insert into > the database. ?This works okay, but I'm not sure whether I can use one > cursor for all inserts, and define it outside of the loop, or > instantiate and close the cursor within the loop itself. ?For example, > I have: > > for i in hostlist: > ? ? cursor = connection.cursor() > ? ? sql= "insert into as_siebel_hosts_temp values('%s')" % (i) > ? ? cursor.execute(sql) > ? ? cursor.close() > > And I've also tried: > > cursor = connection.cursor() > for i in hostlist: > ? ? sql= "insert into as_siebel_hosts_temp values('%s')" % (i) > ? ? cursor.execute(sql) > cursor.close() > > Both work fine, and execute in the same amount of time. ?I'm just > trying to understand what is the "correct" approach to use. > > Thanks, > Tom I think I have this one figured out. The answer would be the second option, i.e. keep the cursor instantion and close outside of the loop. I wasn't aware that one cursor could be used for multiple executes. Regards, Tom From steve at holdenweb.com Thu Jan 31 09:10:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 09:10:50 -0500 Subject: REALLY simple xml reader In-Reply-To: <87tzkujeq6.fsf@benfinney.id.au> References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> <87tzkujeq6.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Steve Holden writes: > >> Diez B. Roggisch wrote: >>> Ricardo Ar?oz schrieb: >>>> doc = """ >>>> >>> It's not allowed to have a newline before the >>> >>> Put it on the line above, and things will work. >>> >> If you don't think that looks pretty enough just escape the first >> newline in the string constant to have the parser ignore it: > > 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. > >> doc = """\ >> > > This is fine. > Sure. The only difference in "prettiness" I was referring to was the difference betwee doc = """ ... and doc = """\ ... In other words, Python source-code prettiness. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From nonamehuang at yahoo.com.cn Sat Jan 5 08:55:22 2008 From: nonamehuang at yahoo.com.cn (nonamehuang at yahoo.com.cn) Date: Sat, 5 Jan 2008 05:55:22 -0800 (PST) Subject: Welcome to my webside that provides help in English Study for Chinese.. Message-ID: <9fcfae8c-4485-4df1-b10f-52a2e257a767@s12g2000prg.googlegroups.com> The address is http://englearn.zhan.cn.yahoo.com And I need your advice. Well, maybe your help. You see. aha! From travis.jensen at gmail.com Fri Jan 25 00:54:58 2008 From: travis.jensen at gmail.com (Travis Jensen) Date: Thu, 24 Jan 2008 22:54:58 -0700 Subject: Which is more pythonic? In-Reply-To: <56518bb9-1d56-47c3-8112-6e0778832c12@v29g2000hsf.googlegroups.com> References: <56518bb9-1d56-47c3-8112-6e0778832c12@v29g2000hsf.googlegroups.com> Message-ID: <6480447F-1496-430A-A9A6-555358EBCA97@gmail.com> Well, regardless of being "pythonic" or not, the first is far more understandable and therefore more maintainable. Objects were invented to handle holding state; using a function to hold state is, in my opinion, doing a language-based cheat. :) tj On Jan 24, 2008, at 10:14 PM, benjamin.zimmerman at gmail.com wrote: > I have a goal function that returns the fitness of a given solution. I > need to wrap that function with a class or a function to keep track of > the best solution I encounter. Which of the following would best serve > my purpose and be the most pythonic? > > class Goal: > def __init__(self, goal): > self.goal = goal > self.best = None > self.best_score = None > > def __call__(self, solution): > score = self.goal(solution) > if self.best is None or score > self.best_score: > self.best_score = score > self.best = solution > return score > > def save_best_goal(goal): > def new_goal(solution): > score = goal(solution) > if new_goal.best is None or score > new_goal.best_score: > new_goal.best = solution > new_goal.best_score = score > return score > new_goal.best = new_goal.best_score = None > return new_goal > > -Ben > -- > http://mail.python.org/mailman/listinfo/python-list Travis Jensen travis.jensen at gmail.com http://softwaremaven.innerbrane.com/ You should read my blog; it is more interesting than my signature. From lists at cheimes.de Sat Jan 19 16:31:38 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 19 Jan 2008 22:31:38 +0100 Subject: finding memory leak in edgewall trac 0.11 In-Reply-To: <20080119202909.GY61556@nexus.in-nomine.org> References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> Message-ID: <47926C3A.5060000@cheimes.de> Jeroen Ruigrok van der Werven wrote: > Hi Christian, > > -On [20080119 16:16], Christian Heimes (lists at cheimes.de) wrote: >> I forgot one important point in my reply. The GC module contains some >> useful methods for debugging. Check gc.garbage. It should be empty. > > Yeah, we're messing around with that stuff as well as many other ways of > trying to track issues, but it can really be looking for a needle in a > haystack to be honest. > There's so much output that, I guess, make sense only when you're semi-deep > into the Python internals to even make heads or tails out of it. =\ > And even third-party code is not helping much to reduce the clutter and > provide insight. Under normal circumstances gc.garbage should be an empty list. In general it's a bad sign if gc.garbage contains lots of objects. I found several potential leaks in trac: $ find -name \*.py | xargs grep __del__ ./trac/versioncontrol/svn_fs.py: def __del__(self): ./trac/versioncontrol/svn_fs.py: def __del__(self): ./trac/db/pool.py: def __del__(self): $ find -name \*.py | xargs grep frame ./trac/web/main.py: [...] ./trac/core.py: frame = sys._getframe(1) ./trac/core.py: locals_ = frame.f_locals I recommend that you either replace __del__ with a weak reference callback or to remove it. Referencing a frame, traceback or f_locals is going to leak, too. You *must* explicitly del every frame and locals variable. Christian From stanc at al.com.au Wed Jan 30 22:01:30 2008 From: stanc at al.com.au (Astan Chee) Date: Thu, 31 Jan 2008 14:01:30 +1100 Subject: small problem with re.sub Message-ID: <47A13A0A.3010607@al.com.au> Hi, I have a html text stored as a string. Now I want to go through this string and find all 6 digit numbers and make links from them. Im using re.sub and for some reason its not picking up the previously matched condition. Am I doing something wrong? This is what my code looks like: htmlStr = re.sub('(?P\d{6})','(?P=id)',htmlStr) It seems that it replaces it alright, but it replaces it literally. Am I not escaping certain characters? Thanks again for the help. Cheers Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. From bignose+hates-spam at benfinney.id.au Wed Jan 23 16:32:14 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 24 Jan 2008 08:32:14 +1100 Subject: Module/package hierarchy and its separation from file structure References: Message-ID: <874pd49qjl.fsf@benfinney.id.au> Peter Schuller writes: > Let me just shoot down one possible suggestion right away, to show > you what I am trying to accomplish: > > I do *not* want to simply break out X into org.lib.animal.x, and > have org.lib.animal import org.lib.animal.x.X as X. Nevertheless, that seems the best (indeed, the Pythonic) solution to your problem as stated. Rather than just shooting it down, we'll have to know more about ehat actual problem you're trying to solve to understand why this solution doesn't fit. > While this naively solves the problem of being able to refer to X as > org.lib.animal.X, the solution is anything but consistent because > the *identity* of X is still org.lib.animal.x.X. The term "identity" in Python means something separate from this concept; you seem to mean "the name of X". > Examples of way this breaks things: > > * X().__class__.__name__ gives unexpected results. Who is expecting them otherwise, and why is that a problem? > * Automatically generated documentation will document using the > "real" package name. Here I lose all track of what problem you're trying to solve. You want the documentation to say exactly where the class "is" (by name), but you don't want the class to actually be defined at that location? I can't make sense of that, so probably I don't understand the requirement. -- \ "If it ain't bust don't fix it is a very sound principle and | `\ remains so despite the fact that I have slavishly ignored it | _o__) all my life." ?Douglas Adams | Ben Finney From JO3chiang at gmail.com Tue Jan 8 02:01:35 2008 From: JO3chiang at gmail.com (jo3c) Date: Mon, 7 Jan 2008 23:01:35 -0800 (PST) Subject: use fileinput to read a specific line References: <6f2db44c-2641-47cb-ab24-4177ccc96d6e@m77g2000hsc.googlegroups.com> <13o637afk4mql0c@corp.supernews.com> <44c28069-12bf-43c2-96f6-06b4c3923188@41g2000hsy.googlegroups.com> Message-ID: <84b55d6a-2bda-442a-8336-3175eb34ba45@i7g2000prf.googlegroups.com> On Jan 8, 2:08 pm, "Russ P." wrote: > > Given that the OP is talking 2000 files to be processed, I think I'd > > recommend explicit open() and close() calls to avoid having lots of I/O > > structures floating around... > > Good point. I didn't think of that. It could also be done as follows: > > for fileN in files: > > lnum = 0 # line number > input = file(fileN) > > for line in input: > lnum += 1 > if lnum >= 4: break > > input.close() > > # do something with "line" > > Six of one or half a dozen of the other, I suppose. this is what i did using glob import glob for files in glob.glob('/*.txt'): x = open(files) x.readline() x.readline() x.readline() y = x.readline() # do something with y x.close() From spaceoutlet at gmail.com Sat Jan 12 04:45:35 2008 From: spaceoutlet at gmail.com (Alex K) Date: Sat, 12 Jan 2008 10:45:35 +0100 Subject: paging in python shell Message-ID: Hello, Does anyone know if the python shell supports paging or if I should look into iPython? Thank you so much. Alex From peter.schuller at infidyne.com Tue Jan 29 07:51:58 2008 From: peter.schuller at infidyne.com (Peter Schuller) Date: Tue, 29 Jan 2008 06:51:58 -0600 Subject: Module/package hierarchy and its separation from file structure References: <04ab182a-5ecd-4d1b-89c5-ac321048f6f1@x69g2000hsx.googlegroups.com> Message-ID: > You can reassign the class's module: > > from org.lib.animal.monkey import Monkey > Monkey.__module__ = 'org.lib.animal' > > > (Which, I must admit, is not a bad idea in some cases.) Is there a sense whether this is truly a supported way of doing this, in terms of not running into various unintended side-effects? One example would be sys.modules that I mentioned in the previous post. Another, possibly related, might be interaction with the import keyword and its implementation. I will probably have to read up more on the semantics of __import__ and related machinery. -- / Peter Schuller PGP userID: 0xE9758B7D or 'Peter Schuller ' Key retrieval: Send an E-Mail to getpgpkey at scode.org E-Mail: peter.schuller at infidyne.com Web: http://www.scode.org From boblatest at yahoo.com Wed Jan 9 15:02:20 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 20:02:20 GMT Subject: How does unicode() work? References: <5ujt96F1i6h37U1@mid.dfncis.de> <1199888091.3474.9.camel@dot.uniqsys.com> Message-ID: <5uknicF1il028U2@mid.uni-berlin.de> John Machin wrote: > When mixing unicode strings with byte strings, Python attempts to > decode the str object to unicode, not encode the unicode object to > str. Thanks for the explanation. Of course I didn't want to mix Unicode and Latin in one string, my snippet just tried to illustrate the point. I'm new to Python -- I came from C, and C gives a rat's ass about encoding. It just dumps bytes and that's that. robert From jorgen.maillist at gmail.com Sat Jan 12 06:02:20 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Sat, 12 Jan 2008 12:02:20 +0100 Subject: where do my python files go in linux? Message-ID: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> Hi All, I am trying to make a debian package. I am following the tutorial by Horst Jens (http://showmedo.com/videos/video?name=linuxJensMakingDeb&fromSeriesID=37) and it is very informative. However one thing my app has and his doesn't, is multiple python files which need to be executed. For example {dir}/app app.py app.py calls a lot of modules in {dir}/app. Horst says the python file goes in /usr/bin/app.py which is ok with me, but I have multiple python files, and I decided to use an app.sh script to call my python files. In the /usr/bin I do not see subdirs so I assume that is not really desirable. Question 1. Where do I put the bulk of python scripts in a normal linux environment? Question 2. Should I use *.pyc rather then *.py files to speed up executing as the user cannot write to /usr/bin or any other dir in the system and everytime my app runs it will recompile it Thanks for any advice or maybe a good tutorial how to set up files in a linux environment With regards, - Jorgen From fredrik at pythonware.com Sat Jan 12 16:50:10 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Jan 2008 22:50:10 +0100 Subject: sqlite3 is it in the python default distro? In-Reply-To: References: Message-ID: Martin Marcher wrote: > I can see that sqlite is in the standard lib documentation: > http://docs.python.org/lib/module-sqlite3.html > > however debian and ubuntu (and gentoo according to the packages info) seem > _not_ to include it. http://packages.debian.org/python-sqlite From attn.steven.kuo at gmail.com Tue Jan 29 12:23:16 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Tue, 29 Jan 2008 09:23:16 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: Message-ID: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> On Jan 29, 8:34 am, William McBrine wrote: > Look at this -- from Python 2.5.1: > > >>> a = [1, 2, 3, 4, 5] > >>> for x in a: > > ... if x == 3: > ... a.remove(x) > ... print x > ... > 1 > 2 > 3 > 5 > > >>> a > [1, 2, 4, 5] > > Sure, the resulting list is correct. But 4 is never printed during the > loop! > (snipped) If you're going to delete elements from a list while iterating over it, then do it in reverse order: >>> a = [ 98, 99, 100 ] >>> last_idx = len(a) - 1 >>> for i, x in enumerate(a[::-1]): ... if x == 99: del(a[last_idx - i]) ... print x ... 100 99 98 >>> a [98, 100] -- Hope this helps, Steven From sjmachin at lexicon.net Wed Jan 9 15:01:30 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 9 Jan 2008 12:01:30 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> <962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.googlegroups.com> Message-ID: On Jan 10, 6:52 am, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of Fredrik Lundh > > Sent: Wednesday, January 09, 2008 2:39 PM > > To: python-l... at python.org > > Subject: Re: problem of converting a list to dict > > > Louis.Soni... at gmail.com wrote: > > > >> to see what's going on on your machine, try printing "a" after the > > >> split, but before you use it to populate the dictionary. > > > > 'print a' works > > > so what does it tell you? > > A bigger hint: > a=i.split('=') > print "'%s' splits into " % (i), a consider: (1) using %r instead of '%s' (2) omitting the redundant space after 'into' (3) losing the redundant () around i > assert len(a) == 2 > mydict[a[0]]=a[1] From wuhrrr at gmail.com Thu Jan 17 02:48:51 2008 From: wuhrrr at gmail.com (Hai Vu) Date: Wed, 16 Jan 2008 23:48:51 -0800 (PST) Subject: Parsing links within a html file. References: Message-ID: <34a13767-43de-46d0-9691-d3d267208bd9@s13g2000prd.googlegroups.com> On Jan 14, 9:59 am, Shriphani wrote: > Hello, > I have a html file over here by the name guide_ind.html and it > contains links to other html files like guides.html#outline . How do I > point BeautifulSoup (I want to use this module) to > guides.html#outline ? > Thanks > Shriphani P. Try Mark Pilgrim's excellent example at: http://www.diveintopython.org/http_web_services/index.html >From the above link, you can retrieve openanything.py which I use in my example: # list_url.py # created by Hai Vu on 1/16/2008 from openanything import fetch from sgmllib import SGMLParser class RetrieveURLs(SGMLParser): def reset(self): SGMLParser.reset(self) self.urls = [] def start_a(self, attributes): url = [v for k, v in attributes if k.lower() == 'href'] self.urls.extend(url) print '\t%s' % (url) # -------------------------------------------------------------------------------------------------------------- # main def main(): site = 'http://www.google.com' result = fetch(site) if result['status'] == 200: # Extracts a list of URLs off the top page parser = RetrieveURLs() parser.feed(result['data']) parser.close() # Display the URLs we just retrieved print '\nURL retrieved from %s' % (site) print '\t' + '\n\t'.join(parser.urls) else: print 'Error (%d) retrieving %s' % (result['status'], site) if __name__ == '__main__': main() From hniksic at xemacs.org Fri Jan 11 18:23:45 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 12 Jan 2008 00:23:45 +0100 Subject: Newbie Q: modifying SQL statements References: <20080111013206.GA18259@neptune.faber.nom> <20080110225352.2c112555@bhuda.mired.org> Message-ID: <87d4s8ndz2.fsf@mulj.homelinux.net> "Faber J. Fedor" writes: > On 10/01/08 22:53 -0500, Mike Meyer wrote: >> Personally, I think it would be more pythonic to not try and use two >> different APIs to walk the list of jobs (... One Way To Do it): >> >> def __call__(self, where=None): >> q = "select * from %s" % (self.name,) + ("" if not where else (" where %s" % where)) > > Does this '("" if not where...' syntax actually work? http://docs.python.org/whatsnew/pep-308.html From Russ.Paielli at gmail.com Mon Jan 28 02:56:16 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 23:56:16 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> <87lk6a8m8q.fsf@physik.rwth-aachen.de> <13pr24chv832660@corp.supernews.com> Message-ID: <00eb8dc1-6fd8-4090-8d0b-4e586d6e260d@s12g2000prg.googlegroups.com> On Jan 27, 11:47 pm, Steven D'Aprano wrote: > On Mon, 28 Jan 2008 08:04:05 +0100, Torsten Bronger wrote: > >> Are you referring to the alternate syntax or to the decorator? Either > >> way, you could be saving 4 or 5 or more lines, if you have enough > >> arguments. > > > Mostly, I write them in one or two lines, e.g. > > > def __init__(self, id, kind, person, feedname): > > self.id, self.kind, self.person = id, kind, person > > It's not the number of lines that is important, but the amount of > redundant code, and the amount of redundant code is identical whether you > write it in one line or three. > > The problem is that instance initialization frequently and regularly > breaks the principle "Don't Repeat Yourself". Whether you initialize your > code like this: > > self.id = id > self.kind = kind > self.person person > > or like this: > > self.id = id; self.kind = kind; self.person = person > > or like this: > > self.id, self.kind, self.person = id, kind, person > > you are repeating yourself. > > Unfortunately, without syntactical support, I don't think there is any > easy way to tell the compiler which arguments to auto-initialize and > which to skip. And Guido rightly is reluctant to create special syntax > for special cases, and something which happens only in __init__ (and > maybe __new__?) is certainly a special case. > > That leaves a decorator solution, married with a convention for names. > > Here's a thought... why assume that the convention is a prefix? What > about a suffix? > > @autoassign > def __init__(self, spam_, ham_, eggs): > pass > > A trailing underscore doesn't conflict with the conventions for leading > underscores. The only conflict is with the convention that if you want a > name that looks like a reserved word you put an underscore after it. > Since Python has very few reserved words, and they rarely make good > argument names, there should be far fewer conflicts with an underscore > suffix rather than a prefix. > > I'd still prefer compiler support, preferably with a leading & as syntax. > Since all the work would happen at compile time, it wouldn't effect the > runtime speed, and it wouldn't lead to any confusion with function > signatures. The class you get would be exactly the same as if you had > done the attribute initialization by hand, except the compiler did it. > > That's the ideal solution, but failing that, a decorator solution with a > trailing _ gets my vote. > > -- > Steven The problem with a trailing underscore is that it creates another valid name, so if someone used the name foo_, it would conflict with your convention. You need a character that is not part of a valid Python identifier or operator, such as &, $, %, @, !, ~, or ^. From larry.bates at websafe.com Fri Jan 25 11:27:06 2008 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 25 Jan 2008 10:27:06 -0600 Subject: is possible to get order of keyword parameters ? In-Reply-To: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> Message-ID: Keyword arguments are normally treaded as "order independent". Why do you think you need to find the order? What problem do you wish to solve? -Larry rndblnch wrote: > (sorry, draft message gone to fast) > > i.e. is it possible to write such a function: > > def f(**kwargs): > > return result > > such as : > f(x=12, y=24) == ['x', 'y'] > f(y=24, x=12) == ['y', 'x'] > > what i need is to get the order of the keyword parameters inside the > function. > any hints ? > > thanks, > > renaud From bladedpenguin at gmail.com Sat Jan 26 00:30:25 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 21:30:25 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> <45a8d4a7-d24d-461e-9783-59a7d697a041@q77g2000hsh.googlegroups.com> <499aaee4-7e8f-47fb-bedd-7db548b92a5c@i29g2000prf.googlegroups.com> Message-ID: <9ceb64c0-7c92-47c3-910d-a3b29221aaa1@k39g2000hsf.googlegroups.com> On Jan 25, 10:25 pm, petr.jakes.... at gmail.com wrote: > > I agree that SDL is probably the best choice but for the sake of > > completeness, Gtk can (at least in theory - I've never tried it) be > > built against directfb and run without X. > > from the Pygame Introduction: Pygame is a Python extension library > that wraps the SDL library and it's helpers. So you mean, Pygame can > run without X? > > BTW I have nothing against X, I just have not experiences on the GUI > field, so my feeling was it can run faster without X on the 500MHz AMD > Geode CPU. > > Petr The problem is not with x: you should be able to run x just fine with only 133MHZ and a few megs of ram. The performance issues on such a machine come from things like kde and gnome. use one of the simpler window managers. From timr at probo.com Thu Jan 10 01:49:43 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 10 Jan 2008 06:49:43 GMT Subject: Tracking colors References: Message-ID: <2ofbo3pu87j82uib3h25dhs0827elaei23@4ax.com> dongie.agnir at gmail.com wrote: > >I'm just getting started with Python, and I want to do a bit of color >tracking using VideoCapture. However, I've never worked with video or >images, so I'm a little at a loss. How would I use VideoCapture to >track a specified color, and its coordinates? There's really no easy way to do this. You'll have to convert the image to an array of pixels, then search through them to find a block of the color you're interested in. Remember that camera sensors are real-world devices, so the actual pixel values vary slightly from frame to frame. You'll have to look for a range. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From eieimemiv at gmail.com Tue Jan 1 07:13:07 2008 From: eieimemiv at gmail.com (eieimemiv at gmail.com) Date: Tue, 1 Jan 2008 12:13:07 +0000 (UTC) Subject: M-I,5`Persecution ` B ernard Levin expre sses hi s vie ws Message-ID: The article of which part. is reproduced below was penned by Bernard Levin for the. Features section of the Times on 21 September 1991. To my mind, it described the situation at the time and in particular a recent. meeting with a friend, during which I for the first time admitted to someone. other than my GP that I had. been subjected to a conspiracy of harassment over the previous year. and a half. >There is a madman running loose about. London, called David Campbell; I have >no reason to believe. that he is violent, but he should certainly be >approached with caution. You may. know him by the curious glitter in his >eyes and a persistent. trembling of his hands; if that does not suffice, you >will find him attempting to thrust no fewer than 48 books. into your arms, >all hardbacks, with a promise that, if you should return to the. same >meeting-place next year, he will heave. another 80 at you. > >If, by now, the police have arrived and are keeping a close watch on. him, >you may. feel sufficiently emboldened to examine the books. The jackets are >a. model of uncluttered typography, elegantly and simply laid out; there is >an unobtrusive colophon of. a rising sun, probably not picked at random. >Gaining confidence - the lunatic is smiling by now, and. the policemen, who >know about such things, have. significantly removed their helmets - you >could do. worse than take the jacket off the first book in the pile. The >only. word possible to describe the binding is sumptuous; real cloth in a >glorious shade of dark green, with the title and author in black. and gold >on. the spine. > >Look at it more closely; your eyes do not deceive you - it truly does. have >real top-bands and tail-bands, in yellow,. and, for good measure, a silk >marker ribbon in a lighter green. The. paper is cream-wove and acid-free, >and the book is sewn,. not glued. > >Throughout the encounter, I. should have mentioned, our loony has been >chattering away, although what he. is trying to say is almost impossible to >understand; after a time, however, he becomes sufficiently coherent to. make >clear that he. is trying to sell the books to you. Well, now, such quality >in. bookmaking today can only be for collectors' limited editions at a >fearsome price -. #30, #40, #50? > >No, no, he. says, the glitter more powerful than ever and the trembling of >his hands rapidly. spreading throughout his entire body; no, no - the books >are priced variously at. #7, #8 or #9, with the top price #12. > >At this, the policemen understandably put their helmets. back on; one of >them draws his truncheon and the. other can be heard summoning >reinforcements on his walkie-talkie. The madman. bursts into tears, and >swears it is all. true. > >And. it is. > >David Campbell has. acquired the entire rights to the whole of the >Everyman's. Library, which died a lingering and shameful death a decade or >so ago, and he proposes to start it. all over again - 48 volumes this >September. and 80 more next year, in editions I have described, at the >prices specified.. He proposes to launch his amazing venture simultaneously >in Britain and the. United States, with the massive firepower of Random >Century at his back in this country, and the dashing cavalry of. Knopf >across the water, and no. one who loves literature and courage will forbear >to. cheer. At the time this article was written I had believed for. some time that columnists in the Times and. other journalists had been making references to my situation. Nothing. unusual about this you may think, plenty of people have the same sort of ideas. and obviously the papers aren't writing about them, so why should my beliefs not be as false. as those of others? What makes this article. so extraordinary is that three or four days immediately preceding its publication, I had a meeting with. a friend, during the course of. which we discussed the media persecution, and in particular that by Times columnists. It seemed to. me, reading the article by Levin in Saturday?s. paper, that he was describing in some detail his "artist?s impression" of that. meeting. Most telling are the final sentences, when. he writes, "The madman bursts into tears, and swears it is all true. And it is." Although I did not "burst into tears" (he. seems to be using a bit of. poetic licence and exaggerating) I did try hard to convince my friend that it was all true; and. I am able to concur with Mr Levin, because, of. course, it is. At the beginning of the piece Levin reveals a. fear of being attacked by the "irrational" subject of his. story, saying "I have no reason to believe that he is violent, but. he should certainly be approached with caution". This goes back. to the xenophobic propaganda of "defence" against a "threat" which was seen at the very beginning of the harassment. The impression. of a "madman running loose" who needs to be controlled through. an agency which assigns to itself the mantle. of the "police" is also one which had been expressed. elsewhere. In the. final paragraph of this extract, his reference to Everyman?s Library as having "died a lingering and shameful death a decade or. so ago" shows clearly what sort of conclusion. they wish to their campaign. They want a permanent solution,. and as they are prevented from achieving that solution directly, they waste significant resources on. methods which have been repeatedly shown to be. ineffective for such a purpose. 5203 From Russ.Paielli at gmail.com Sun Jan 27 21:08:25 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 18:08:25 -0800 (PST) Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> Message-ID: <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> On Jan 27, 5:03 pm, Paddy > If static typing is optional then a program written in a dynamic > language that passes such an automated static analysis of source code > would have to be a simple program written in a simplistic way, and > also in a static style. Yes, but for safety-critical software you usually want the simplest possible solution. The last think you want is an unnecessarily "fancy" design. Unless there is a darn good reason to write a "non-static" program, you just don't do it. You might want to check into what the FAA allows in "flight-critical" code, for example. I am certainly not an expert in that area, but I've had a passing exposure to it. My understanding is that every possible branch of the code must be fully and meticulously analyzed and verified. Hence, the dynamic dispatching of ordinary object-oriented code is either prohibited or severely frowned upon. > Having used such formal tools on hardware designs that are expressed > using statically typed languages such as Verilog and VHDL, we don't > have the problem of throwing away run time typing, but we do get other > capacity problems with formal proofs that mean only parts of a design > can be formally prooved, or we can proof that an assertion holds only > as far as the engine has resources to expand the assertion. > We tend to find a lot of bugs in near complete designs by the random > generation of test cases and the automatic checking of results. In > effect, two (or more) programs are created by different people and > usually in different languages. One is written in say Verilog and can > be used to create a chip, another is written by the Verification group > in a 'higher level language' (in terms of chip testing), a tunable > randomized test generator then generates plausible test streams that > the Verification model validates. The test stream is applied to the > Verilog model and the Verilogs responses checked against the > Verification models output and any discrepancy flagged. Coverage > metrics (line coverage , statement coverage, expression coverage ...), > are gathered to indicate how well the design/program is being > exercised. > > I would rather advocate such random test generation methods as being > more appropriate for testing software in safety critical systems when > the programming language is dynamic. Random test generation methods can go a long way, and they certainly have their place, but I don't think they are a panacea. Coming up with a random set of cases that flush out every possible bug is usually very difficult if not impossible. That was the point of the quote in my original post. From jyoung79 at kc.rr.com Tue Jan 22 14:58:19 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Tue, 22 Jan 2008 13:58:19 -0600 Subject: question Message-ID: <6760762.631391201031899339.JavaMail.root@hrndva-web18-z01> I'm still learning Python and was wanting to get some thoughts on this. I apologize if this sounds ridiculous... I'm mainly asking it to gain some knowledge of what works better. The main question I have is if I had a lot of lists to choose from, what's the best way to write the code so I'm not wasting a lot of memory? I've attempted to list a few examples below to hopefully be a little clearer about my question. Lets say I was going to be pulling different data, depending on what the user entered. I was thinking I could create a function which contained various functions inside: def albumInfo(theBand): def Rush(): return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] def Enchant(): return ['A Blueprint of the World', 'Wounded', 'Time Lost'] ... The only problem with the code above though is that I don't know how to call it, especially since if the user is entering a string, how would I convert that string into a function name? For example, if the user entered 'Rush', how would I call the appropriate function --> albumInfo(Rush()) But if I could somehow make that code work, is it a good way to do it? I'm assuming if the user entered 'Rush' that only the list in the Rush() function would be stored, ignoring the other functions inside the albumInfo() function? I then thought maybe just using a simple if/else statement might work like so: def albumInfo(theBand): if theBand == 'Rush': return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] elif theBand == 'Enchant': return ['A Blueprint of the World', 'Wounded', 'Time Lost'] ... Does anyone think this would be more efficient? I'm not familiar with how 'classes' work yet (still reading through my 'Core Python' book) but was curious if using a 'class' would be better suited for something like this? Since the user could possibly choose from 100 or more choices, I'd like to come up with something that's efficient as well as easy to read in the code. If anyone has time I'd love to hear your thoughts. Thanks. Jay From eproust at gmail.com Mon Jan 21 05:05:11 2008 From: eproust at gmail.com (pythonewbie) Date: Mon, 21 Jan 2008 02:05:11 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <5vi1r8F1mjs0rU1@mid.uni-berlin.de> <5360e13d-215d-4d3e-9930-daa6cddd996a@f10g2000hsf.googlegroups.com> <5vj79dF1m2nmlU1@mid.uni-berlin.de> Message-ID: <2ba5fe9b-4a57-4147-bc18-22213b002297@d4g2000prg.googlegroups.com> On 21 jan, 10:34, "Diez B. Roggisch" wrote: > pythonewbie > > > > > Because the solution using distutils.sysconfig.get_python_lib() is > > very smart ! > > Depending on your goal. You said > > """ > My goal is to verify if an/several extension(s) are installed and to > automatically install the missing ones on Linux or Win32. > """ > > This goal can't be reached with only the site-packages - because I can > install packages somewhere else (matter of factly, this happens on debian > for example, they've split the install-dirs and created a bunch of dirs > under /usr/share) > > So having a method that gives you the installation root doesn't help much > here. > > Diez To John Machin, >>> sys.path ['', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/ python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/ python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/ usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/ Numeric', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/ python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0', '/usr/lib/python2.5/site- packages/wx-2.8-gtk2-unicode'] From python.list at tim.thechases.com Sun Jan 27 23:30:45 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 27 Jan 2008 22:30:45 -0600 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <479D5A75.5040704@tim.thechases.com> > This is neat. :) Could that maybe be extended to only assign selected > args to the instance and let others pass unchanged. So that, for instance: > > @autoassign("foo", "bar") > def __init__(self, foo, bar, baz): > super(baz) I've seen some folks import inspect/functools, but from my testing, the __init__ method in question has a .func_code object that already has the varnames in it. However, as you suggest, a version below allows for named defaults, and letting others go un-defaulted. I'm not sure about naming conventions for class-style decorators--start with a cap, like a class should ("AutoAssign") or because it behaves like a function, use "auto_assign", or any of a number of other variants. Anyways... class auto_assign(object): def __init__(self, *varnames): self.args = set(varnames) def __call__(self, fn): autoassign = self def wrapper(self, *args, **kwargs): for argname, argvalue in zip( fn.func_code.co_varnames[1:], args): if argname in autoassign.args: setattr(self, argname, argvalue) for argname in autoassign.args: if argname in kwargs: setattr(self, argname, kwargs[argname]) fn(self, *args, **kwargs) return wrapper class Foo(object): @auto_assign('foo', 'baz', 'fred') def __init__(self, foo, bar, baz, *args, **kwargs): pass f = Foo('hello', 42, 3.14, fred='wilma', barney='betty') try: print f.foo except AttributeError: print "Could not print f.foo" try: print f.bar except AttributeError: print "Could not print f.bar" try: print f.baz except AttributeError: print "Could not print f.baz" try: print f.fred except AttributeError: print "Could not print f.fred" try: print f.barney except AttributeError: print "Could not print f.barney" -tkc From Dom.Rout at gmail.com Tue Jan 8 14:51:21 2008 From: Dom.Rout at gmail.com (Dom Rout) Date: Tue, 8 Jan 2008 11:51:21 -0800 (PST) Subject: Peer To Peer File Sharing... Message-ID: <652595fc-071c-410e-b2fc-59c16495bc00@s8g2000prg.googlegroups.com> Hello. Well, this is my first post on any USENET group anywhere, so I hope I get it right. Basically, I just want to get some opinions on a plan of mine for a new project. I want to produce a small, peer to peer, file sharing network for the use of myself and some of my friends. The purpose of this is basically to allow us to share files conveniently without relying on technology such as Windows Live Messenger (Yuck). I have a VPS which I would like to dedicate to the task of acting as a tracker, so I can run a server application written in python on it. I will also write the first client in python, although I may go for a different language for the client in the final version, for performance. For now, Python is perfect because of the ease of use that it offers and the fact that I already know a bit about socket programming using it. Also concerning architecture, I will also have a number of peers that connect to the tracker and also to other peers, via an IP address provided by the server, as necessary to download the files. The files themselves should be split up into "Chunks" of fixed length, which will be given an index and tracked by the server. The server should know which clients have which chunks of a file, and when a client needs to download a file the server should look for other clients that have chunks from that file and give the IP address to the client, which should then for a connection to this peer and download the parts of the file that are available. When managing the chunks of a file, I will need to use a mutex to allow reading and writing of them. I should provide a getter and setter method in each file to allow chunks to be placed into it more conveniently. The getter and setter should both use mutex's to allow multiple threads of uploads and downloads at the same time. I will need to implement a username and password system, to restrict the users of the system to people that I trust. To uniquely identify a file, I would like to use a file path. There should be a theoretical directory that contains all shared files, although the client should be given the option of which files from the directory to download. This directory should look like: "Global/" "Global/Images/" "Global/Music/" "Users//" It would be nice if it was possible to subscribe to certain directories, and download new files from them as need be. Well, these are my ideas so far. Is anything drastically obviously wrong, and can anyone suggest to me any best practices when implementing this sort of design? Thanks, Dominic Rout. From lists at cheimes.de Sun Jan 20 06:20:32 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 20 Jan 2008 12:20:32 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt In-Reply-To: References: Message-ID: pythonewbie wrote: > I am stucked on creating a function to get the Python install > directory (and site-packages directory) with a 100% reliable method... Only one method is 100% reliable: try: import yourextension except ImportError: available = False else: available = True Christian From sjmachin at lexicon.net Tue Jan 8 06:31:05 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 8 Jan 2008 03:31:05 -0800 (PST) Subject: Open a List of Files References: Message-ID: <5c89f461-1c29-404c-bfe3-4572311c717f@d70g2000hsb.googlegroups.com> On Jan 8, 10:03 pm, Fredrik Lundh wrote: > BJ Swope wrote: > > given a list such as > > > ['messages', 'recipients', 'viruses'] > > > how would I iterate over the list and use the values as variables and > > open the variable names a files? > > > I tried > > > for outfile in ['messages', 'recipients', 'viruses']: > > filename = os.path.join(Host_Path, outfile) > > outfile = open(filename, 'w') > > > But it's not working. > > the code looks ok. please define "not working". > To me, it looks bad. He's rebinding "outfile" inside the loop, which is not good style, makes the reader slow down, back up, read the code again ... however this doesn't stop this small code fragment from opening the 3 files for write access -- assuming an import, and suitable contents for "Host_Path". From Scott.Daniels at Acm.Org Thu Jan 10 00:28:15 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 09 Jan 2008 21:28:15 -0800 Subject: Structure of packages In-Reply-To: References: Message-ID: <13obaunlh9pl94@corp.supernews.com> Ben Fisher wrote: > I am trying to learn the best way to do intra-package references. My > package looks like this: ... > I had thought that "from PackageName.b import *" would work.... In an attempt to hand oyu a net, rather than an answer: Try using command line: python -v whatever.py You can see all the imports that are done and in what order. Also realize that import a file executes it, so you can sprinkle prints at points where you are confused. --Scott David Daniels Scott.Daniels at Acm.Org From mimvev at gmail.com Tue Jan 1 03:52:51 2008 From: mimvev at gmail.com (mimvev at gmail.com) Date: Tue, 1 Jan 2008 08:52:51 +0000 (UTC) Subject: M-I,5`Persecu tion ` buggi ng an d counter-surveillan ce Message-ID: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -= MI5: bugging. and counter-surveillance -= -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- PO: >Did. you ever look for the bugs in your house ? If not, why not ? I mean if PO: >I thought that was happening. to me, I'd search the place from top to bottom, PO: >I mean. I live there I would know if anything was out of place. If I was PO: >really suspicious, I would call in one of those bug detection. teams which PO: >have those machines that pick up the transmitted radio. waves. This PO:. >reminds me of BUGS, that new programme on BBC1 on That's exactly what we did. We went to. a competent, professional detective agency in London, paid them over 400 quid to debug our house.. They used scanner devices which go to over 1. GHz and would pick up any nearby transmitter in that range, they also checked. the phones and found nothing... but if the tap was at the exchange, then. they wouldn't find anything,. would they? CS: >Doesn't this suggest. to you that there are, in fact, no bugs to be found? You can assume that they've done this sort of. thing to other people in more "serious" cases, where they would know the targets. would suspect the presence of electronic. surveillance. So they will have developed techniques and devices which are not readily detectable either by. visual inspection or by. electronic means. What those techniques might be, I couldn't guess. In this case,. the existence of bugging devices was clear from the beginning, and they "rubbed it in" with what was said by. the boy on the coach. It was almost. as if they wanted counter-surveillance people to be called in, who they knew. would fail to detect the bugging devices, causing loss of credibility to the other things I would have. to say relating to the harassment. I did all the things someone in my situation would do to try. to find the bugs. In addition to calling in professional help using. electronic counter-surveillance, I made a close. visual inspection of electrical equipment, plus any points where audio or video. surveillance devices might have been concealed. Of course, I found nothing.. Normal surveillance "mini-cameras" are quite noticeable. and require visible supporting circuitry. It seems to me the best place to. put a small video surveillance device. would be additional to a piece of electronic equipment such as a TV or video. It would be necessary to physically break in to a property. to fit such a. device. 2773 From gowricp at gmail.com Fri Jan 11 19:13:07 2008 From: gowricp at gmail.com (Gowri) Date: Fri, 11 Jan 2008 16:13:07 -0800 (PST) Subject: converting JSON to string Message-ID: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> Hello, I actually have two questions: 1. Are there any libraries which convert XML to JSON? 2. I am currently doing the above using the DOM parser and creating a JSON array for node in doc.getElementsByTagName("book"): isbn = node.getAttribute("isbn") titleNode = (node.getElementsByTagName("title") [0]).childNodes[0] title = titleNode.data primarykeys.append({'isbn': isbn, 'title': title}) return primarykeys I want to send primarykeys as a response to my client. i use mod_python and apache. The problem is, I have not been able to figure out how to convert my JSON output to a string. Could someone please help me? Thanks in advance From jzgoda at o2.usun.pl Tue Jan 15 05:42:38 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 15 Jan 2008 11:42:38 +0100 Subject: MySQL-python-1.2.2 install with no mysql In-Reply-To: References: Message-ID: washakie napisa?(a): > I need to install the MySQL-python-1.2.2 connector in order to access a db > on another machine. In the install it asks for the location of the > mysql_config file, and if I leave it as the default I get: > > [root at lars MySQL-python-1.2.2]# python setup.py build > sh: mysql_config: command not found > Traceback (most recent call last): > File "setup.py", line 16, in ? > metadata, options = get_config() > File "/opt/MySQL-python-1.2.2/setup_posix.py", line 43, in get_config > libs = mysql_config("libs_r") > File "/opt/MySQL-python-1.2.2/setup_posix.py", line 24, in mysql_config > raise EnvironmentError, "%s not found" % mysql_config.path > EnvironmentError: mysql_config not found > [root at lars MySQL-python-1.2.2]# > > How can I install MySQL-python-1.2.2 without installing MySQL??? In short: without installing client libraries you cann't. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 29 12:05:59 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 29 Jan 2008 18:05:59 +0100 Subject: Python noob SOS (any [former?] Perlheads out there?) In-Reply-To: References: Message-ID: <479f5cf0$0$19801$426a74cc@news.free.fr> kj a ?crit : > For many months now I've been trying to learn Python, but I guess > I'm too old a dog trying to learn new tricks... For better or > worse, I'm so used to Perl when it comes to scripting, that I'm > just having a very hard time getting a hang of "The Python Way." > (snip) > > I'd written a Perl module to facilitate the writing of scripts. > It contained all my boilerplate code for parsing and validating > command-line options, generating of accessor functions for these > options, printing of the help message and of the full documentation, > testing, etc. > > Of course, for Python now I don't have any of this, so I must write > it all from scratch, Hem... What about the optparse module ? (nb: it's in the standard lib). From aisaac at american.edu Fri Jan 25 17:28:51 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 25 Jan 2008 22:28:51 GMT Subject: find minimum associated values In-Reply-To: <7xd4rpznl0.fsf@ruckus.brouhaha.com> References: <7xd4rpznl0.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > How about something like: > > kv_sorted = sorted(kv, key=lambda x: (id(x[0]), x[1])) You mean like this? #sort by id and then value kv_sorted = sorted(kv, key=lambda x: (id(x[0]),x[1])) #groupby: first element in each group is object and its min value d =dict( g.next() for k,g in groupby( kv_sorted, key=lambda x: x[0] ) ) Yes, that appears to be fastest and is pretty easy to read. Thanks, Alan From bignose+hates-spam at benfinney.id.au Sat Jan 26 18:47:52 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 27 Jan 2008 10:47:52 +1100 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> <87k5lx5v19.fsf@benfinney.id.au> <22c3fd21-2fe3-4893-89f4-b23e1703d083@y5g2000hsf.googlegroups.com> Message-ID: <877ihw5etz.fsf@benfinney.id.au> Carl Banks writes: > On Jan 25, 6:45 pm, Ben Finney > wrote: > > "Gabriel Genellina" writes: > > > You can also put, in animal/__init__.py: > > > from monkey import Monkey > > > and now you can refer to it as org.lib.animal.Monkey, but keep the > > > implementation of Monkey class and all related stuff into > > > .../animal/monkey.py > > > > This (as far as I can understand) is exactly the solution the > > original poster desired to "shoot down", for reasons I still don't > > understand. > > The solution is to modify the class's __module__ attribute as well as > importing it, as I've already pointed out: > > from org.lib.animal.monkey import Monkey > Monkey.__module__ = 'org.lib.animal' Thanks, that makes it clear. > This should be enough to satisfy the OP's requirements, at least for > classes, without softening the one-to-one module-to-file > relationship, or using "hacks". > > In fact, I'd say this is good practice. I've not seen that before, but it seems an elegant way to address what the OP is asking for. -- \ "Madness is rare in individuals, but in groups, parties, | `\ nations and ages it is the rule." -- Friedrich Nietzsche | _o__) | Ben Finney From python at rcn.com Thu Jan 17 03:49:54 2008 From: python at rcn.com (Raymond Hettinger) Date: Thu, 17 Jan 2008 00:49:54 -0800 (PST) Subject: Replace stop words (remove words from a string) References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> Message-ID: On Jan 17, 12:25?am, BerlinBrown wrote: > if I have an array of "stop" words, and I want to replace those values > with something else; > mystr = > kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsld?fsd; > if I have an array stop_list = [ "[BAD]", "[BAD2]" ] > I want to replace the values in that list with a zero length string. Regular expressions should do the trick. Try this: >>> mystr = 'kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsld?fsd;' >>> stoplist = ["[BAD]", "[BAD2]"] >>> import re >>> stoppattern = '|'.join(map(re.escape, stoplist)) >>> re.sub(stoppattern, '', mystr) 'kljsldkfjksjdfjsdjflkdjslkfKkjkkkkjkkjkLSKJFKSFJKSJF;Lkjsld\xadfsd;' Raymond From rrasss at gmail.com Tue Jan 1 22:55:45 2008 From: rrasss at gmail.com (Rick) Date: Tue, 1 Jan 2008 21:55:45 -0600 Subject: Simple server using asyncore/asynchat Message-ID: <414fb3c30801011955t2ea6be7ch72f6f7a7652dea12@mail.gmail.com> Hey folks. I'm trying to create a (fairly) simple server that listens for connections and when it receives one sends a message to the client and then waits for a response (and would continue to do that). My problem is, every time my client connects, the server doesn't send the text and then immediately closes the connection with the client, but DOES print that the client was connected. Anyone know why? Here's my code: # conn.py import socket import asyncore import asynchat import string host = 'localhost' #socket.gethostname () port = 8017 buf = 1024 class ConnChannel (asynchat.async_chat): def __init__(self, conn): self.conn = conn def handle_connect(): self.send(self.conn, "Hello, Welcome to BasicMUD.\r\n") # it doesn't do thise self.numberclients = self.numberclients + 1 # or this self.send(self.conn, "There are " + self.numberclients + " players online.") # or this print "Client connected!" # it prints this def handle_read(self): print self.recv(8192) def handle_write(self): print "sending" class ConnTube (asyncore.dispatcher): def __init__(self, hostd, portd): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM ) self.bind ( ( hostd , portd ) ) self.listen ( 5 ) self.numberclients = 0 def handle_accept(self): channel, addr = self.accept() ConnChannel(channel) connTube = ConnTube(host, port) asyncore.loop() Thanks everyone! Rick -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Tue Jan 1 06:28:29 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 01 Jan 2008 12:28:29 +0100 Subject: pdf library. References: <133097f4-de83-4e13-93f1-1404213333a4@l6g2000prm.googlegroups.com> Message-ID: >>>>> Shriphani (S) wrote: >S> I tried pyPdf for this and decided to get the pagelinks. The trouble >S> is that I don't know how to determine whether a particular page is the >S> first page of a chapter. Can someone tell me how to do this ? AFAIK PDF doesn't have the concept of "Chapter". If the document has an outline, you could try to use the first level of that hierarchy as the chapter starting points. But you don't have a guarantee that they really are chapters. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From kyosohma at gmail.com Wed Jan 23 10:49:14 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 23 Jan 2008 07:49:14 -0800 (PST) Subject: Processing XML that's embedded in HTML References: <6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> <47972624.2050002@web.de> Message-ID: <58d2add2-147e-435e-9214-278689321feb@z17g2000hsg.googlegroups.com> John and Stefan, On Jan 23, 5:33 am, Stefan Behnel wrote: > Hi, > > Mike Driscoll wrote: > > I got lxml to create a tree by doing the following: > > > from lxml import etree > > from StringIO import StringIO > > > parser = etree.HTMLParser() > > tree = etree.parse(filename, parser) > > xml_string = etree.tostring(tree) > > context = etree.iterparse(StringIO(xml_string)) > > No idea why you need the two steps here. lxml 2.0 supports parsing HTML in > iterparse() directly when you pass the boolean "html" keyword. I don't know why I have 2 steps either, now that I look at it. However, I don't do enough XML parsing to get real familiar with the ins and outs of Python parsing either, so it's mainly just my inexperience. And I also got lost in the lxml tutorials... > > > However, when I iterate over the contents of "context", I can't figure > > out how to nab the row's contents: > > > for action, elem in context: > > if action == 'end' and elem.tag == 'relationship': > > # do something...but what!? > > # this if statement probably isn't even right > > I would really encourage you to use the normal parser here instead of iterparse(). > > from lxml import etree > parser = etree.HTMLParser() > > # parse the HTML/XML melange > tree = etree.parse(filename, parser) > > # if you want, you can construct a pure XML document > row_root = etree.Element("newroot") > for row in tree.iterfind("//Row"): > row_root.append(row) > > In your specific case, I'd encourage using lxml.objectify: > > http://codespeak.net/lxml/dev/objectify.html > > It will allow you to do this (untested): > > from lxml import etree, objectify > parser = etree.HTMLParser() > lookup = objectify.ObjectifyElementClassLookup() > parser.setElementClassLookup(lookup) > > tree = etree.parse(filename, parser) > > for row in tree.iterfind("//Row"): > print row.relationship, row.StartDate, row.Priority * 2.7 > > Stefan I'll give your ideas a go and also see if what the others posted will be cleaner or faster. Thank you all. Mike From george.sakkis at gmail.com Mon Jan 21 00:41:39 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 20 Jan 2008 21:41:39 -0800 (PST) Subject: object scope References: <13p8803q11tm32d@corp.supernews.com> Message-ID: On Jan 21, 12:16 am, "J. Peng" wrote: > Dennis Lee Bieber ??: > > > The scope of "name" is the entire function; lacking a "global name" > > statement, AND being on the left side of an assignment, it is a function > > local name. > > Thank you. Does python have so-called 'block scope' object? No, it doesn't; in most cases that you may care, a name's scope is either local or global*. > or if you can,please show me the doc for python's object scope. http://www.network-theory.co.uk/docs/pytut/PythonScopesandNameSpaces.html George * There is also class scope and lexical closures but most likely you don't have to worry about them for now. From serilanimi at gmail.com Fri Jan 11 15:01:16 2008 From: serilanimi at gmail.com (serilanimi at gmail.com) Date: Fri, 11 Jan 2008 12:01:16 -0800 (PST) Subject: opensg or openscenegraph References: <40zfj.33787$lD6.31634@newssvr27.news.prodigy.net> Message-ID: <88ef87d8-d63b-4a7e-96db-07bc2a7a1fc9@s19g2000prg.googlegroups.com> On Jan 4, 3:08?pm, yomgui wrote: > Hi, > > I need to use a scengraph for my python/opengl application > but I have trouble finding out which one I should use. > > opensg or openscenegraph (OSG) ? > > I suppose the quality of the python bindings will make the decision. > > any advice ? > > thanks > > yomgui Hi yomgui, I am considering either of these as well for writing a simulation game. The Python Bindings I have found to date are: For OpenSG: https://realityforge.vrsource.org/trac/pyopensg For OSG (there seems to be several variations of these): http://code.astraw.com/projects/pyosg I suppose you could also use something like Py++ to create your own. I too, am having a hard time deciding. I was leaning towards OpenSceneGraph because it seems to be better supported. If you make a decision, please let me know which one you decided on and your reasons. Regards, serilanimi From http Thu Jan 31 17:15:58 2008 From: http (Paul Rubin) Date: 31 Jan 2008 14:15:58 -0800 Subject: Naive idiom questions References: Message-ID: <7x4pctmyjl.fsf@ruckus.brouhaha.com> Terran Melconian writes: > I want to be able to accumulate a string with +=, not by going > through an intermediate list and then doing ''.join(), because I > think the latter is ugly. There are also times when I'd like to use > the string as a modifiable buffer. See the StringIO, cStringIO, and array modules. > l=[[None]*5 for i in range(5)] This is the usual way. > * Is there a way to get headings in docstrings? I think this is normally not done. From kyosohma at gmail.com Tue Jan 22 16:41:35 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 22 Jan 2008 13:41:35 -0800 (PST) Subject: get the size of a dynamically changing file fast ? References: <198fd91f-912b-4f56-a840-af96225125a7@c23g2000hsa.googlegroups.com> Message-ID: <197576d1-ab36-45f2-9648-3cfab6d3a814@j20g2000hsi.googlegroups.com> On Jan 22, 3:35 pm, Stef Mientki wrote: > Mike Driscoll wrote: > > On Jan 17, 3:56 pm, Stef Mientki wrote: > > >> hello, > > >> I've a program (not written in Python) that generates a few thousands > >> bytes per second, > >> these files are dumped in 2 buffers (files), at in interval time of 50 msec, > >> the files can be read by another program, to do further processing. > > >> A program written in VB or delphi can handle the data in the 2 buffers > >> perfectly. > >> Sometimes Python is also able to process the data correctly, > >> but often it can't :-( > > >> I keep one of the files open en test the size of the open datafile each > >> 50 msec. > >> I have tried > >> os.stat ( ....) [ ST_SIZE] > >> os.path.getsize ( ... ) > >> but they both have the same behaviour, sometimes it works, and the data > >> is collected each 50 .. 100 msec, > >> sometimes 1 .. 1.5 seconds is needed to detect a change in filesize. > > >> I'm using python 2.4 on winXP. > > >> Is there a solution for this problem ? > > >> thanks, > >> Stef Mientki > > > Tim Golden has a method to watch for changes in a directory on his > > website: > > >http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_fo... > > > This old post also mentions something similar: > > >http://mail.python.org/pipermail/python-list/2007-October/463065.html > > > And here's a cookbook recipe that claims to do it as well using > > decorators: > > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/426620 > > > Hopefully that will get you going. > > > Mike > > thanks Mike, > sorry for the late reaction. > I've it working perfect now. > After all, os.stat works perfectly well, > the problem was in the program that generated the file with increasing > size, > by truncating it after each block write, it apperently garantees that > the file is flushed to disk and all problems are solved. > > cheers, > Stef Mientki I almost asked if you were making sure you had flushed the data to the file...oh well. Mike From lasses_weil at klapptsowieso.net Tue Jan 29 18:38:47 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Wed, 30 Jan 2008 00:38:47 +0100 Subject: optional static typing for Python In-Reply-To: <70c4064a-a65d-4fd5-b39c-38e6a3fb567b@i7g2000prf.googlegroups.com> References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> <479e0225$0$36389$742ec2ed@news.sonic.net> <70c4064a-a65d-4fd5-b39c-38e6a3fb567b@i7g2000prf.googlegroups.com> Message-ID: <479fb907$0$25376$9b4e6d93@newsspool4.arcor-online.net> > Python has a JIT right no > You mean in the Java-sense (outputting native machine code)? /W From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Jan 5 05:53:07 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 05 Jan 2008 11:53:07 +0100 Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> Message-ID: <5u95sjF1etf0nU1@mid.individual.net> MartinRinehart at gmail.com wrote: > Jeroen Ruigrok van der Werven wrote: >> self.startLoc = start >> self.stopLoc = stop > > Thanks! Of course it should. Old Java habits die slowly. That's not really a Java habit. In Java and C++, personally I like to write this.startLoc = start this.stopLoc = stop It makes much clearer what a field and what a "normal" variable is in those languages. Regards, Bj?rn -- BOFH excuse #294: PCMCIA slave driver From NikitaTheSpider at gmail.com Fri Jan 11 11:23:47 2008 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Fri, 11 Jan 2008 11:23:47 -0500 Subject: Detecting OS platform in Python References: Message-ID: In article , Mike Meyer wrote: > On Thu, 10 Jan 2008 18:37:59 -0800 (PST) Devraj wrote: > > > Hi everyone, > > > > My Python program needs reliably detect which Operating System its > > being run on, infact it even needs to know which distribution of say > > Linux its running on. The reason being its a GTK application that > > needs to adapt itself to be a Hildon application if run on devices > > like the N800. > > I don't think it can be done. [...] > ...trying to figure out what features you have > available by guessing based on the platform type is generally the > wrong way to approach this kind of problem - only in part because you > wind up reduced to a series of heuristics to figure out the > platform. And once you've done that, you could wind up being wrong. > > Generally, you're better of probing the platform to find out if it has > the facilities you're looking for. For python, that generally means > trying to import the modules you need, and catching failures; or > possibly looking for attributes on modules if they adopt to the > environment around them. Much agreed. I just went through this with my SHM module. Compilation was failing because of a variation in ipc_perm in ipc.h on various platforms. I didn't feel confident at all that I could compile a list of all of the variations let alone keep it accurate and updated. The clincher was when I found that OS X >= 10.4 has two flavors of ipc_perm and which gets used depends on a compile flag, so identifying the OS would not have been useful in that case. OP, I don't know what a Hildon or N800 is, but is it possible that the same OS fingerprint could show up on different devices? If so then you're really out of luck. I think you'll be much better off if you focus less on the OS and more on the features it offers. Good luck -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From paddy3118 at googlemail.com Sun Jan 20 23:16:18 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 20 Jan 2008 20:16:18 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: On Jan 21, 3:15 am, Albert Hopkins wrote: > This issue may have been referred to in > but I didn't > entirely understand the explanation. Basically I have this: > > >>> a = float(6) > >>> b = float('nan') > >>> min(a, b) > 6.0 > >>> min(b, a) > nan > >>> max(a, b) > 6.0 > >>> max(b, a) > nan > > Before I did not know what to expect, but I certainly didn't expect > this. So my question is what is the min/max of a number and NaN or is it > not defined (for which I would have expected either an exception to be > raised or NaN returned in each case). > > As a corrollary would I be able to rely on the above behavior or is it > subject to change (to fix a bug in min/max perhaps :-)? I am definitely NOT a floating point expert, but I did find this: http://en.wikipedia.org/wiki/IEEE_754r#min_and_max P.S. What platform /Compiler are you using for Python? - Paddy. From cwitts at gmail.com Fri Jan 18 01:13:18 2008 From: cwitts at gmail.com (Chris) Date: Thu, 17 Jan 2008 22:13:18 -0800 (PST) Subject: too long float References: Message-ID: <4fe99e03-4ffd-4b1a-b9cc-5df8a11feed4@i29g2000prf.googlegroups.com> On Jan 18, 7:55 am, "J. Peng" wrote: > hello, > > why this happened on my python? > > >>> a=3.9 > >>> a > > 3.8999999999999999 > > I wanted 3.9 but got 3.89................ > How to avoid it? thanks. > > this is my python version: > > >>> sys.version > > '2.3.4 (#1, Feb 6 2006, 10:38:46) \n[GCC 3.4.5 20051201 (Red Hat 3.4.5-2)]' >>> 3.9 3.8999999999999999 >>> 3.9 == 3.8999999999999999 True http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm From Lie.1296 at gmail.com Sat Jan 5 05:27:03 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 5 Jan 2008 02:27:03 -0800 (PST) Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <13nn9k48n7ohr95@corp.supernews.com> <69337707-ff18-4b39-af0a-78cf0a14b667@1g2000hsl.googlegroups.com> Message-ID: > I mean, really, I've been using web-mail and various varieties of > remote > storage for over a decade. ?What is *new* about the concept? ?(I see > some > hints above, but it's mixed in with a lot of other stuff...) In essence, you're correct, this concept of cloud computing actually have existed for some time, but there is a difference between the "classic" cloud computing and "new" cloud computing. The classic cloud computing is rather limited emails, bbs, newsgroup, etc while the new cloud computing also refers to the newly available scope such as word processing, image processing, and even video editing. In essence they're the same, you store your files on their server, and you used a webbased tools to access your file, but nowadays people wouldn't consider the classic cloud computing a cloud computing anymore, as they've become too "normal". It's not a completely meaningless marketing buzz phrase, the concept has existed for some time, but the word is new. Another way to look at this is: "classic" cloud computing are cloud computing that is done because it can't be done the other way (what use is an email address if you could only receive emails if your desktop is always on, what use is a newsgroup if people could only post if they are physically in front of the computer hosting the newsgroup). While the "new" cloud computing refers to applications that previously exist as desktop applications, but now ported to become web-based applications, meaning the application could be usable without the "cloud", but some features like universal availability could not be used. From fredrik at pythonware.com Thu Jan 10 16:13:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 22:13:27 +0100 Subject: Python too slow? In-Reply-To: <13od12b23hfv772@corp.supernews.com> References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <13od12b23hfv772@corp.supernews.com> Message-ID: Ed Jensen wrote: > The only question that remains is if you were being accidentally > misleading or purposefully misleading. oh, please. it was perfectly clear for anyone with the slightest clue what Bruno was talking about (especially if they'd read the post he was replying to), so the only question that remains is why you didn't understand it. From r.grimm at science-computing.de Mon Jan 7 02:33:15 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Sun, 6 Jan 2008 23:33:15 -0800 (PST) Subject: python interfaces References: <96b70141-f872-413a-a433-08b217cecb27@e4g2000hsg.googlegroups.com> Message-ID: On Jan 6, 11:01 am, Fredrik Lundh wrote: > r.gr... at science-computing.de wrote: > > Interfaces are a extremly smart Design Principle in static typed > > languages like Java and C++. > > that's somewhat questionable in itself, and even more questionable as an > argument for interfaces in Python. > > I'd recommend anyone who thinks that they cannot program without formal > interfaces to try using Python as Python for a while, before they try > using it as something else. you might be surprised over how easy it is > to build robust stuff without having to add lots of extra constraints to > your code. > > Hallo, I argued, that Interface and multiple inheritance are different things and especially, that Interfaces are very useful in staticially typed languages. In such languages like Java and C++ you need a formalismen to guide the user. You may call it extension point, pure virtual function or abstract methode. Sorry for the misunderstanding, I argued for Interface in heavyweight static typed languages and nor for lightweight dynamic typed languages like python. They aren't pointless and a hack. Greetings Rainer From mail at timgolden.me.uk Thu Jan 24 06:20:31 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jan 2008 11:20:31 +0000 Subject: wxpython In-Reply-To: <0d5fbbaf-aff3-46eb-a8ff-ef0247262fcc@i29g2000prf.googlegroups.com> References: <77cc3d61-5dd0-4878-b436-b6d07e40de4d@i7g2000prf.googlegroups.com> <0d5fbbaf-aff3-46eb-a8ff-ef0247262fcc@i29g2000prf.googlegroups.com> Message-ID: <4798747F.9090005@timgolden.me.uk> [Tim Golden] >> wxPython is trying to interpret your byte stream as a Unicode >> text stream encoded as cp1252. But it's not, so it gives up >> in a heap. One solution is to pass the repr of file_content. >> Another solution is for you to prefilter the text, replacing >> non-printables by their hex value or by some marker. Not much >> in it, really. >> >> >> import random >> file_content = "".join ( >> chr (random.randint (0, 255)) for i in range (1000) >> ) >> munged_text = "".join ( >> c if 32 <= ord (c) <= 126 else hex (ord (c)) for c in file_content >> ) >> >> print repr (file_content) >> print munged_text >> >> >> TJG [joe jacob] > If I open an exe file in notepad, I can see some junk characters. I'm > trying to develop a program like an editor which can encrypt a file > opened by it. I need to open files like exe or jpeg etc in the editor > and after encryption the encrypted data should be displayed in the > editor. I developed the editor but when I tried to open an windows exe > file in it I am getting the above mentioned error as the characters > contained in it are non unicode. Hi, Joe. I've copied this back to the list (and I encourage you to do the same when replying) since the more people see the issue, the more chances you've got of a useful answer! To try to address what you're saying here: notepad.exe makes some choice or other when confronted by the byte stream in a file which you open. I don't know what that choice is, or how it tries to cope with encoded unicode text, but whatever it does by the choice of its developers. The "some junk characters" are one of several possible representations of the not-ordinary-characters which your file contains. If you're writing your own editor or file display, you have to make similar choices, which includes understanding what possibilities are offered by the toolset you're employing -- in this case, wxPython. The wxPython wx.TextCtrl expects to be fed with Unicode text. If you pass it a string instead, it tries to decode it according to the system's default encoding, here cp1252. If it can't, it doesn't display "junk characters": it just gives an error. If you want junk characters, then you'll either have to explicitly pass in the characters you want displayed or do the kind of thing I suggested above to indicate their hex value, or find another control (or an option of the wx.TextCtrl) which will attempt to do the work for you when displaying raw bytes. I'm afraid I'm not a wxPython expert so maybe someone else has suggestions. But the most important thing is that you understand what's happening here and why you can't just say "I want it to do what Notepad does". TJG From pavlovevidence at gmail.com Thu Jan 31 20:51:49 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 31 Jan 2008 17:51:49 -0800 (PST) Subject: Naive idiom questions References: Message-ID: On Jan 31, 4:30 pm, Terran Melconian wrote: > * Why are there no real mutable strings available? > > I found MutableString in UserString, but further research indicates > that it is horribly inefficient and actually just wraps immutable > strings for the implementation. > > I want to be able to accumulate a string with +=, not by going > through an intermediate list and then doing ''.join(), because I > think the latter is ugly. If it's just the weird spelling, you can always write str.join("",acc) > There are also times when I'd like to use > the string as a modifiable buffer. array module has already been mentioned. You can also use an mmap (pass it a file handle of -1 I believe to get an anonymous buffer), or even a numpy array of type character if you're feeling frisky. Python 3.0 is scheduled to have a mutable buffer type. (BTW, originally there was going to be a mutable bytes type, but this proved to cause many inconveniences so bytes is now an immutable, and buffer is a now a lessened version of what bytes would have been.) > Is the python idiom that this is actually the Right Thing for > reasons I'm not seeing? Is there a fundamental reason it would be > hard to implement a mutable string in cpython? It might seem a little weird for someone coming from Perl, but Python isn't the sort of language that implements every possible feature that isn't "fundamentally hard". Python carefully considers the benefits and drawbacks of adding something, and if there is too much drawback it won't be added, no matter how obvious or basic it seems. In practice, very few string operations really need the benefit of mutability. (How large are most strings, really?) OTOH, the drawbacks of mutability are severe: once you allow string buffer data to change, then the language has to take defensive steps in case string values are mutated. Strings could no longer be keys for dicts, for instance, which would be unfortunate since that's how Python looks up global variables and attributes. Python wisely made the built-in string type immutable--saving all kinds of grief for the most typical usages--while providing modules such as cStringIO, array, and mmap to handle the special cases where you really need a mutable type. > * What's the best way to initialize a list of lists? > > I keep wanting to do this: > > l=[[None]*5]*5 > > as do many other Python novices, but of course it quickly becomes > apparent why this is a bad idea as soon as one modifies a value. > The best I've found is: > > l=[[None]*5 for i in range(5)] > > I don't particularly like it, though. It bothers me to have to > explain list comprehensions, which are a moderately advanced feature > conceptually, just to initialize an array. We could get around this > if we had a defaultlist, but we don't. Is there a more elegant > solution here? No. Since 2D arrays aren't commonplace, since listcomps work passably here, and since there's a popular thrid-party library (numpy) that handles multidimensional arrays, it's unlikely that Python would add any means to do this more elegantly. You can put it in a function and forget about how it's implemented if you don't like the listcomps. def create_empty_2d_list(rows,cols): return [[None]*cols for i in xrange(rows)] > * Is there a way to get headings in docstrings? > > I want to create my own sections, like "OVERVIEW", "EXAMPLES", > "AUTHORS", "BUGS", etc. I can't figure out any way to do this. In > perldoc, I can easily use =head1, but I can't figure out the Python > equivalent. At first I thought I could use (re)structuredtext, but > then it became apparent that pydoc(1) does not parse any of this > markup. Am I missing something, or is it just not possible to > achieve this effect other than by writing separate, independent > manpages? Not a big expert on docstrings (they seem so superfluous...) but perhaps there are third-party packages that let you specify meta- documentation with function decorators. For example: @overview("Blah blah blah") @authors("So and so") def some_function(): pass Try looking on PyPI (cheeseshop.python.org). Python's in-code documentation is pretty basic; I think Python is happy to outsource more elaborate schemes to third party packages. Carl Banks From kyosohma at gmail.com Thu Jan 3 14:07:11 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 3 Jan 2008 11:07:11 -0800 (PST) Subject: PyOpenGL, wxPython weird behaviour References: <71ae5a6b-31e9-41e9-a39e-919138dc4a03@l6g2000prm.googlegroups.com> Message-ID: On Jan 3, 11:50 am, Adeola Bannis wrote: > Hi everyone, > > I'm doing a project using wxPython and pyopengl, and I seem to have a > problem rendering textures. This is code that worked before my hard > drive had a meltdown, but not since I re-installed everything. > > I've determined the problem is in the OpenGL part of my program. I do > some calculations to generate a 2D numpy array that holds the image > data, and pylab.imshow() shows me the image as it is meant to be. I > used the same algorithm in Octave and MATLAB, and all are giving me > the right picture. > > However, using pyOpenGL and the numpyhandler functions (http://cours- > info.iut-bm.univ-fcomte.fr/docs/python/OpenGL/ > OpenGL.arrays.numpymodule.NumpyHandler-class.html) doesn't seem to > work. I get a garbled screen pocked with black pixels. I am including > my openGL code below. What am I doing wrong? > > And yes, I did make the dtype of my array 'float32'. > > -------code snippets------ > > import wx > from wx.glcanvas import GLCanvas > > from OpenGL.GLU import * > from OpenGL.GL import * > from OpenGL.arrays.numpymodule import NumpyHandler > > PC = 1 > RI = 0 > > class myGLCanvas(GLCanvas): > def __init__(self, parent): > GLCanvas.__init__(self, parent,-1) > wx.EVT_PAINT(self, self.OnPaint) > self.init = 0 > self.mode = -1 > # making a texture for the range image > self.texture = glGenTextures(1) > # making a spot for the point cloud points > self.cloud = None > return > > def OnPaint(self,event): > dc = wx.PaintDC(self) > self.SetCurrent() > if not self.init: > self.InitGL() > self.init = 1 > self.OnDraw() > return > > def OnDraw(self): > glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) > if self.mode == RI: > self.drawRange() > elif self.mode == PC: > self.drawCloud() > > def InitGL(self): > glClearColor(0.0, 0.0, 0.0, 0.0); > glClearDepth(1.0) > glEnable(GL_DEPTH_TEST) > glDepthFunc(GL_LEQUAL) > glClear(GL_COLOR_BUFFER_BIT) > > glPixelStorei(GL_UNPACK_ALIGNMENT, 1) > glPixelStorei(GL_PACK_ALIGNMENT, 1) > > #NTSC colour scales... > glPixelTransferf(GL_RED_SCALE, 0.299); > glPixelTransferf(GL_GREEN_SCALE, 0.587); > glPixelTransferf(GL_BLUE_SCALE, 0.114); > > glMatrixMode(GL_PROJECTION) > glLoadIdentity() > glOrtho(0.0,1.0,0,1.0,-1.0,1.0) > glMatrixMode(GL_MODELVIEW) > glLoadIdentity() > > return > > def rangeImage(self, image): > > glBindTexture(GL_TEXTURE_2D, self.texture) > glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) > > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, > GL_LINEAR) > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) > glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) > > # flatten it into a list so the OpenGL calls work > n = NumpyHandler() > fI = image.flatten() > flatImage = n.dataPointer(n.contiguous(fI)) > > print n.contiguous(fI) > > gluBuild2DMipmaps(GL_TEXTURE_2D, 1, image.shape[0]+1, > image.shape[1]+1, > GL_LUMINANCE, GL_FLOAT, flatImage) > self.mode = RI > self.OnDraw() > > def drawRange(self): > ''' Controls the actual drawing of the range image''' > > glMatrixMode(GL_MODELVIEW) > glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) > > glColor3f(1.0,1.0,1.0) > glEnable(GL_TEXTURE_2D) > glBindTexture(GL_TEXTURE_2D, self.texture) > glBegin(GL_TRIANGLE_FAN) > glTexCoord2d(1,1); glVertex3f(0.0, 0.0, 0.0) > glTexCoord2d(1,0); glVertex3f(0.0, 1.0, 0.0) > glTexCoord2d(0,0); glVertex3f(1.0, 1.0, 0.0) > glTexCoord2d(0,1); glVertex3f(1.0, 0.0, 0.0) > glEnd() > self.SwapBuffers() > > --------end snippet----------- I've never messed with pyOpenGL, but it seems that they have their own user's group, which would probably be better at answering your question: http://sourceforge.net/mail/?group_id=5988 Of course, it could be that you upgraded your wxPython to the latest version and as I recall, they were discussing some subtle differences in DCs, blitting, paint events and other things that I just don't understand at this point in my "Pythoneering". You might ask them at their group, which is usually very helpful: wxPython.org Mike From steven.bethard at gmail.com Fri Jan 25 15:06:07 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 25 Jan 2008 13:06:07 -0700 Subject: is possible to get order of keyword parameters ? In-Reply-To: References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> <5b6e2bc6-8136-4e3a-8bf2-bb6d689d6110@s8g2000prg.googlegroups.com> Message-ID: Steven Bethard wrote: > rndblnch wrote: >> my goal is to implement a kind of named tuple. >> idealy, it should behave like this: >> p = Point(x=12, y=13) >> print p.x, p.y >> but what requires to keep track of the order is the unpacking: >> x, y = p >> i can't figure out how to produce an iterable that returns the values >> in the right order. >> relying on a "natural" order of the key names is not possible: x, and >> y are alphabetically sorted but the following example should also >> work: >> size = Point(width=23, height=45) >> w, h = size > > There are a couple of recipes for named tuples: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261 > > The latter of these will be in Python 2.6. Using that recipe, and your > example, you would write:: > > Point = namedtuple('Point', 'x y') > p = Point(x=12, y=13) > x, y = p > > Point = namedtuple('Point', 'width', 'height') Sorry, typo here. This should have read Point = namedtuple('Point', 'width height') > size = Point(width=23, height=45) > w, h = size STeVe From goon12 at gmail.com Sat Jan 12 14:43:14 2008 From: goon12 at gmail.com (Joe Riopel) Date: Sat, 12 Jan 2008 14:43:14 -0500 Subject: where do my python files go in linux? In-Reply-To: <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> <20080112113759.GJ75977@nexus.in-nomine.org> <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> Message-ID: <6a2ccd190801121143m54e4209dh9cd778bbf4e0c65f@mail.gmail.com> On Jan 12, 2008 10:13 AM, Jorgen Bodde wrote: > I thought about that too. I just wonder why /usr/local/bin is always > empty and every .deb I install from a source (if it's from Ubuntu or > not) installs files in /usr/bin .. So I looked further and noticed > that most python files do reside in /usr/share/{appname} This link might explain why your /usr/local/bin is empty: http://www.pathname.com/fhs/pub/fhs-2.3.html#THEUSRHIERARCHY From konrad.hinsen at laposte.net Tue Jan 1 15:06:18 2008 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Tue, 1 Jan 2008 21:06:18 +0100 Subject: parallel processing in standard library Message-ID: <38B8E51E-E56F-4C01-A13E-E9BB939E2398@laposte.net> Emin.shopper Martinian.shopper wrote: > Is there any hope of a parallel processing toolkit being > incorporated into the python standard library? I've seen a wide > variety of toolkits each with various features and limitations. > Unfortunately, each has its own API. For coarse-grained > parallelism, I suspect I'd be pretty happy with many of the > existing toolkits, but if I'm going to pick one API to learn and > program to, I'd rather pick one that I'm confident is going to be > supported for a while. I don't think that parallel computing is mature enough to allow the standardization of APIs, except within a given and well specified parallel computing model such as message passing. The Python Wiki has an impressive list of parallel processing options for Python (see http://wiki.python.org/moin/ParallelProcessing). With the exception of the various MPI interfaces, I don't think that any two of them are based on the same parallel computing model. I don't expect this situation to change any time soon, as parallel computing is still very much experimental. Whereas sequential computing has well-tested software engineering techniques, reliable libraries that can be combined into programs, and ever improving testing techniques, none of these exist for parallel computing. For an overview of parallel computing models and for a more detailed description of one of them as implemented in Python, please see my recent article in "Computing in Science and Engineering": http://www.computer.org/portal/site/cise/index.jsp? pageID=cise_level1&path=cise/2007/n6&file=sci.xml&xsl=article.xsl Konrad. From reed at reedobrien.com Tue Jan 8 21:02:24 2008 From: reed at reedobrien.com (Reed O'Brien) Date: Tue, 8 Jan 2008 21:02:24 -0500 Subject: [Tutor] Spaces and tabs messing up code In-Reply-To: <20080109004941.GA25990@ayn.mi.celestial.com> References: <20080109004941.GA25990@ayn.mi.celestial.com> Message-ID: <8863C706-200A-41CE-AAE9-739C7328C9E8@reedobrien.com> On Jan 8, 2008, at 7:49 PM, Bill Campbell wrote: > On Tue, Jan 08, 2008, mobiledreamers at gmail.com wrote: >> >> my friend uses vim Small editors for small minds;) >> >> and i use xemacs >> >> so our shared python code is a mix of tabs and spaces and it is >> hard >> for him to edit it in vim >> >> any idea on how to make it clean >> >> convert it all to 4 spaces? > > Do that, and in his ~/.vimrc file, add a line ``set expandtab'' Tell him to use emacs. > > (Friends don't let friends use emacs :-). > > Bill > -- > INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC > URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way > FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) > 236-1676 > > Giving money and power to government is like giving whiskey and car > keys to > teenage boys -- P.J. O'Rourke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From asmodai at in-nomine.org Sat Jan 5 05:37:51 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 5 Jan 2008 11:37:51 +0100 Subject: Basic inheritance question In-Reply-To: References: Message-ID: <20080105103751.GU82115@nexus.in-nomine.org> -On [20080105 11:36], MartinRinehart at gmail.com (MartinRinehart at gmail.com) wrote: >class code: > def __init__( self, start, stop ): > startLoc = start > stopLoc = stop Shouldn't this be: self.startLoc = start self.stopLoc = stop ? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Open your Heart and push the limits... From arnodel at googlemail.com Wed Jan 23 14:18:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 11:18:10 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <90cfc1f7-8792-4e28-9466-6a1bf77c87c5@q77g2000hsh.googlegroups.com> Message-ID: <34616e6a-3cd7-47c6-9fb5-885f527b80af@f47g2000hsd.googlegroups.com> On Jan 23, 7:06?pm, George Sakkis wrote: > The OP wanted an answer to a simple question, not a lecture on good > software engineering principles. I wholeheartedly agree. -- Arnaud From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jan 11 15:24:54 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 11 Jan 2008 21:24:54 +0100 Subject: Help needed References: <9f5efc14-0101-45f4-a896-0811b60f1709@l32g2000hse.googlegroups.com> Message-ID: <5uq1kmF1jge26U1@mid.individual.net> Devraj wrote: > Sorry to diverge from the topic, but is there a reason you need to > develop something like again? It's obvious, isn't it? > On Jan 11, 1:15 pm, tijo wrote: >> I dont know how to check the rest like how many bytes send or how >> much time taken since this is part of my course work could >> someone please help me thanks in advance. Homework. Regards, Bj?rn -- BOFH excuse #183: filesystem not big enough for Jumbo Kernel Patch From edreamleo at charter.net Sun Jan 27 13:27:21 2008 From: edreamleo at charter.net (Edward K Ream) Date: Sun, 27 Jan 2008 12:27:21 -0600 Subject: ANN: Leo 4.4.6 final released Message-ID: Leo 4.4.6 final is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo 4.4.6 fixes several recently reported bugs, all minor. Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.6: ---------------------------- - Fixes all known bugs. - Added @auto importers for javascript and xml files. - Added find-next-clone and toggle-sparse-move commands. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From martin at v.loewis.de Mon Jan 14 18:23:23 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 15 Jan 2008 00:23:23 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801150055.07699.donn.ingle@gmail.com> References: <200801141802.56353.donn.ingle@gmail.com> <478BD8AC.6050404@v.loewis.de> <200801150055.07699.donn.ingle@gmail.com> Message-ID: <478BEEEB.4020207@v.loewis.de> > Ah. Can one call it after the full call has been done: > locale.setlocale(locale.LC_ALL,'') > locale.setlocale(locale.LC_ALL) > Without any issues? If you pass LC_ALL, then some systems will give you funny results (semicolon-separated enumerations of all the categoryies). Instead, pick a specific category, e.g. LC_CTYPE. >>> I need that two-letter code that's hidden in a >>> typical locale like en_ZA.utf8 -- I want that 'en' part. > Okay, I need it because I have a tree of dirs: en, it, fr and so on for the > help files -- it's to help build a path to the right html file for the > language being supported. Ok - taking the first two letters should then be fine, assuming all your directories have two-letter codes. >> Not sure why you want that. Notice that the locale name is fairly system >> specific, in particular on non-POSIX systems. It may be >> "English_SouthAfrica" on some systems. > Wow, another thing I had no idea about. So far all I've seen are the > xx_yy.utf8 shaped ones. > > I will have some trouble then, with the help system. If you have "unknown" systems, you can try to use locale.normalize. This has a hard-coded database which tries to deal with some different spellings. For "English", it will give you en_EN.ISO8859-1. OTOH, if your software only works on POSIX systems, anyway, I think it is a fair assumption that they use two-letter codes for the languages (the full language name is only used on Windows, AFAIK). Notice that xx_yy.utf8 definitely is *not* the only syntactical form. utf8 is spelled in various ways (lower and upper case, with and without dash), and there may be other encodings (see the en_EN example above), or no encoding at all in the locale name, and their may be "modifiers": aa_ER at saaho (saaho dialect in Eritrea) be_BY at latin (as opposed to the Cyrillic be_BY locale) likewise for sr_RS de_DE at euro (as opposed to the D-Mark locale); likewise for other members of the Euro zone ca_ES.UTF-8 at valencia (Valencian - Southern Catalan) (no real difference to ca_ES at euro, but differences in message translations) gez_ER at abegede (Ge'ez language in Eritrea with Abegede collation) tt_RU at iqtelif.UTF-8 (Tatar language written in IQTElif alphabet) uz_UZ at cyrillic (as opposed to latin uz_UZ) There used to be a @bokmal modifier for Norwegian (as opposed to the Nynorsk grammar), but they have separate language codes now (nb vs. nn). Regards, Martin Regards, Martin From fredrik at pythonware.com Sat Jan 12 14:33:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Jan 2008 20:33:50 +0100 Subject: Simple List division problem In-Reply-To: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> Message-ID: marcstuart wrote: > How do I divide a list into a set group of sublist's- if the list is > not evenly dividable ? consider this example: > > x = [1,2,3,4,5,6,7,8,9,10] > y = 3 # number of lists I want to break x into > z = y/x > > what I would like to get is 3 sublists > > print z[0] = [1,2,3] > print z[2] = [4,5,6] > print z[3] = [7,8,9,10] > > obviously not even, one list will have 4 elements, the other 2 will > have 3., here's one way to do it: # chop it up n = len(x) / y z = [x[i:i+n] for i in xrange(0, len(x), n)] # if the last piece is too short, add it to one before it if len(z[-1]) < n and len(z) > 1: z[-2].extend(z.pop(-1)) From martin at marcher.name Wed Jan 23 06:23:15 2008 From: martin at marcher.name (Martin Marcher) Date: Wed, 23 Jan 2008 12:23:15 +0100 Subject: UDP Client/Server References: Message-ID: Guilherme Polo wrote: >> >>> class FooRequestHandler(BaseRequestHandler): >> ... def handle(self): >> ... data, addr_info = self.request[1].recvfrom(65534) > > Your FooReceiveServer subclasses UDPServer, it already handled the > recvfrom for you, so, this is wrong. > hmm then why do I receive every second request, shouldn't then no data at all come up? Also the next thing that would be a problem would be if I do data = self.request[0] I do get the data but where would I get the info from to which endpoint I need to send the answer? martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From rzantow at gmail.com Sat Jan 26 11:22:24 2008 From: rzantow at gmail.com (rzed) Date: Sat, 26 Jan 2008 16:22:24 +0000 Subject: Doesn't know what it wants References: <0104616d-87be-4250-b3ef-7a77ac39664a@u10g2000prn.googlegroups.com> Message-ID: Tim Rau wrote in news:0104616d-87be-4250-b3ef- 7a77ac39664a at u10g2000prn.googlegroups. com: > On Jan 26, 1:41 am, John Machin wrote: >> On Jan 26, 4:20 pm, Tim Rau wrote: >> >> >> >> > Traceback (most recent call last): >> > File "C:\Documents and Settings\Owner\My Documents\NIm's >> > code\sandbox >> > \sandbox.py", line 242, in >> > player = ship() >> > File "C:\Documents and Settings\Owner\My Documents\NIm's >> > code\sandbox >> > \sandbox.py", line 121, in __init__ >> > self.phyInit() >> > File "C:\Documents and Settings\Owner\My Documents\NIm's >> > code\sandbox >> > \sandbox.py", line 147, in phyInit >> > moi = cp.cpMomentForCircle(self.mass, .2, 0, >> > vec2d((0,0))) >> > ArgumentError: argument 4: : >> > expected vec2d instance instead of vec2d >> >> > As far as I can tell, It's getting a vec2d, and it wants a >> > vec2d. I't seems like it doesn't know what it wants, but I >> > thought only teenagers did that, no programming languages. >> >> It possibly means that it is expecting an instance of a class >> whose name is "vec2d" but you have given it an instance of >> some *other* class whose name just happens to be "vec2d". >> >> > clearly, Im missing something. >> >> Yes, some information: >> 1. what is vec2d, class or function? >> 2. what do you believe vec2d((0, 0)) should return? >> 3. what is this belief based on? >> 4. what has it actually returned this time? >> 5. what do you believe that cp.cpMomentForCircle expects as >> argument 4? >> 6. what is this belief based on? >> >> The ArgumentError exception is raised by ctypes "when a foreign >> function call cannot convert one of the passed arguments". >> Based on guessin'n'googlin' the cp thing is a set of Python >> bindings to a library written in C++ ... have you considered >> asking the author of the bindings? > > 1. vec2d is a class, designed to hold and manipulte 2d vectors > 2. it should return a vector with x=0 and y=0 > 3. That's what it's done before. > 4. trying it in the interpreter seems to show that it returns a > vec2d with zero length. as it should. > 5.cp.cpMomentForCircle seems to expect a vec2d. I'm baseing that > on a functioning demo that uses the exact same line. > > I guess that the vec2d I've got is not the one it wants. How do > I tell the difference? I'll go look at all the imports. > Are you passing the class or an instance of the class? I'd bet the former, but it should be the latter. -- rzed From fredrik at pythonware.com Mon Jan 7 03:06:21 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 09:06:21 +0100 Subject: whats wrong with this In-Reply-To: <869955.87550.qm@web45515.mail.sp1.yahoo.com> References: <869955.87550.qm@web45515.mail.sp1.yahoo.com> Message-ID: mpho raborife wrote: > I'm trying to rum gmmtrain within my pthon program like this: > > Input -l List -t inittype -e traintype > -m mixture -d dimension -v vfloor -n number -p percent -r results -c cycle) > > But i keep on getting an error. it helps if you include the actual error message in your post, so we don't have to guess. the line you quoted should give you a "SyntaxError: invalid syntax" message; the "os.system" call takes a Python string object, so the correct syntax is: os.system("gmmtrain -o output -i /etc.../") if that doesn't help, please post the *entire* traceback; also see: http://effbot.org/pyfaq/tutor-i-need-help-im-getting-an-error-in-my-program-what-should-i-do.htm From python-url at phaseit.net Mon Jan 21 11:20:54 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 21 Jan 2008 16:20:54 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jan 21) Message-ID: QOTW: "I'd say Java was never sexy, but dressed up in expensive lingerie by marketing maniacs..." - Diez B. Roggisch http://groups.google.com/group/comp.lang.python/msg/ae0463c921077f7f "I must say that the richness that list comprehensions, generators and iterators have brought to Python are well nigh immeasurable." - Uche Ogbuji Four newbie questions: * What are __new__ and __init__?: http://groups.google.com/group/comp.lang.python/browse_thread/thread/3fcb1673e25cdfe8/ * call-by-object and assignment explained (two threads): http://groups.google.com/group/comp.lang.python/browse_thread/thread/6acd8387adbbb7f2/ http://groups.google.com/group/comp.lang.python/browse_thread/thread/f113debd4032c712/ * Why the name "list" is used instead of "array"? http://groups.google.com/group/comp.lang.python/browse_thread/thread/d95bae7bd6c73670/ * Useful comments about a simple program: counting repeated numbers from a file: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b3ded6d0f494d06/ A short explanation about Unicode and encodings, by Martin L?wis: http://groups.google.com/group/comp.lang.python/browse_thread/thread/983f2f84f1f70320/ Computing all combinations from multiple lists - several alternatives discussed: http://groups.google.com/group/comp.lang.python/browse_thread/thread/998a10a65128c96e/ APyB[1], the Brazilian Python Association, proudly announces that the upcoming International Free Software Forum[2], one of the biggest FLOSS events in the world, with more than 5 thousand participants in 2007, will have a dedicated Python track this year, with 14 talks[3] related to Python and 3 training sessions: [1] http://associacao.pythonbrasil.org/ [2] http://fisl.softwarelivre.org/ [3] http://www.pythonbrasil.com.br/moin.cgi/PropostasFISL9 Pairing two lists: from simple to rather complex answers: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9fe4347ae4f0b4ac/ Tips to find memory leaks: http://groups.google.com/group/comp.lang.python/browse_thread/thread/7249eee28515bb92/ Python playes games, and more: http://www.mechanicalcat.net/richard/log/Python/pyglet_1_0_is_out Arguments in a function call are evaluated before checking its number - a missing comma is very significant! http://groups.google.com/group/comp.lang.python/browse_thread/thread/1fa85946f0947023/ Django is available for Jython, if you use the right branches: http://jython.svn.sourceforge.net/viewvc/jython/ Much the same is true for TurboGears ... ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From workitharder at gmail.com Fri Jan 4 12:29:50 2008 From: workitharder at gmail.com (bukzor) Date: Fri, 4 Jan 2008 09:29:50 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: On Jan 4, 9:08 am, Sion Arrowsmith wrote: > Hrvoje Niksic wrote: > > >BTW if you're using C++, why not simply use std::set? > > Because ... how to be polite about this? No, I can't. std::set is > crap. The implementation is a sorted sequence -- if you're lucky, > this is a heap or a C array, and you've got O(log n) performance. > But the real killer is that requirement for a std::set is that > T::operator< exists. Which means, for instance, that you can't > have a set of complex numbers.... > > -- > \S -- si... 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 Why cant you implement < for complex numbers? Maybe I'm being naive, but isn't this the normal definition? a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) How do you implement a set without sorting? Are you expecting better than O(log n)? --Buck From basilisk96 at gmail.com Wed Jan 9 22:17:21 2008 From: basilisk96 at gmail.com (Basilisk96) Date: Wed, 9 Jan 2008 19:17:21 -0800 (PST) Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> Message-ID: <0a00b023-5cd0-41c3-82f8-96910cf0f515@d70g2000hsb.googlegroups.com> On Jan 9, 9:49 pm, erik gartz wrote: > The loop performs some actions with web services. The particular > iteration I'm on isn't important to me. It is only important that I > attempt the web services that number of times. If I succeed I > obviously break out of the loop and the containing function (the > function which has the loop in it) returns True. If all attempts fail > the containing loop returns False. Do you think you could apply something like this: def foo():print "fetching foo..." actions = (foo,)*5 for f in actions: f() fetching foo... fetching foo... fetching foo... fetching foo... fetching foo... ..but not knowing your specific implementation, I may be off the wall here. Cheers, -Basilisk96 From fredrik at pythonware.com Mon Jan 7 17:47:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 23:47:51 +0100 Subject: Open source English dictionary to use programmatically w/ python In-Reply-To: References: Message-ID: dgoldsmith_89 wrote: > Can anyone point me to a downloadable open source English dictionary > suitable for programmatic use with python: I'm programming a puzzle > generator, and I need to be able to generate more or less complete > lists of English words, alphabetized. Thanks! DG here's one: http://www.dcs.shef.ac.uk/research/ilash/Moby/ From http Sat Jan 12 15:25:50 2008 From: http (Paul Rubin) Date: 12 Jan 2008 12:25:50 -0800 Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> Message-ID: <7xprw6g59t.fsf@ruckus.brouhaha.com> marcstuart writes: > what I would like to get is 3 sublists > > print z[0] = [1,2,3] > print z[2] = [4,5,6] > print z[3] = [7,8,9,10] Are you SURE you want that? In almost every situation I've seen, print z[0] = [1,2,3] print z[2] = [4,5,6] print z[3] = [7,8,9] print z[4] = [10] is preferable. From Matthew_WARREN at bnpparibas.com Wed Jan 23 12:46:17 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Wed, 23 Jan 2008 17:46:17 +0000 Subject: pairs from a list In-Reply-To: Message-ID: I'm just fiddling with this, am no great expert, but I added def pairs5(x): o=[] for n in zip(x[::2],x[1:2]): o.append(n) return o I dont know if that breaks any constraints placed on the problem, but I get the following output 0.07158942896 0.266009705575 0.21342143313 0.0537146193457 0.0107680502972 does that make it faster than pairs(4) or am I breaking some constraints on the problem? Matt. Internet aisaac at american.edu To python-list Sent by: cc python-list-bounces+matthew.warren=uk.bnpparibas.com@ python.org Subject Re: pairs from a list 22/01/2008 18:09 Arnaud Delobelle wrote: > pairs4 wins. Oops. I see a smaller difference, but yes, pairs4 wins. Alan Isaac import time from itertools import islice, izip x = range(500001) def pairs1(x): return izip(islice(x,0,None,2),islice(x,1,None,2)) def pairs2(x): xiter = iter(x) while True: yield xiter.next(), xiter.next() def pairs3(x): for i in range( len(x)//2 ): yield x[2*i], x[2*i+1], def pairs4(x): xiter = iter(x) return izip(xiter,xiter) t = time.clock() for x1, x2 in pairs1(x): pass t1 = time.clock() - t t = time.clock() for x1, x2 in pairs2(x): pass t2 = time.clock() - t t = time.clock() for x1, x2 in pairs3(x): pass t3 = time.clock() - t t = time.clock() for x1, x2 in pairs4(x): pass t4 = time.clock() - t print t1, t2, t3, t4 Output: 0.317524154606 1.13436847421 1.07100930426 0.262926712753 -- 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 deets at nospam.web.de Mon Jan 21 04:34:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Jan 2008 10:34:37 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <5vi1r8F1mjs0rU1@mid.uni-berlin.de> <5360e13d-215d-4d3e-9930-daa6cddd996a@f10g2000hsf.googlegroups.com> Message-ID: <5vj79dF1m2nmlU1@mid.uni-berlin.de> pythonewbie > > Because the solution using distutils.sysconfig.get_python_lib() is > very smart ! Depending on your goal. You said """ My goal is to verify if an/several extension(s) are installed and to automatically install the missing ones on Linux or Win32. """ This goal can't be reached with only the site-packages - because I can install packages somewhere else (matter of factly, this happens on debian for example, they've split the install-dirs and created a bunch of dirs under /usr/share) So having a method that gives you the installation root doesn't help much here. Diez From http Wed Jan 30 08:20:49 2008 From: http (Paul Rubin) Date: 30 Jan 2008 05:20:49 -0800 Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> Message-ID: <7xwsprxxe6.fsf@ruckus.brouhaha.com> "Neil Cerutti" writes: > Or one can put on his bellbottoms, horn-rimmed glasses, and wear a mullet: > > i = 0 > while i < len(a): > if a[i] == 99: > del a[i] > else: > i += 1 Quadratic time!! Yowch!! Back to the future: def rocket_science(xs): for x in xs: if x != 99: yield x a[:] = list(rocket_science(a)) ;-) From sromero at gmail.com Fri Jan 11 08:06:21 2008 From: sromero at gmail.com (Santiago Romero) Date: Fri, 11 Jan 2008 05:06:21 -0800 (PST) Subject: Converting a bidimensional list in a bidimensional array References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> <005679e9-c355-4e0a-872c-e0dae3181fd0@x69g2000hsx.googlegroups.com> Message-ID: <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> > > - Speed Performance: Do you think that changing from list to Array() > > would improve speed? I'm going to do lots of tilemap[y][x] checks (I > > mean, player jumping around the screen, checking if it's falling over > > a non-zero tile, and so). > First of all: if you have enough memory to use a python list, then I > suggest you to use a list. > > Often python lists are faster than array.array (maybe because python > lists actually contain pyobjects). My problem is that, in my game, each screen is 30x20, and I have about 100 screens, so my tilemap contains 32*20*100 = 60000 python objects (integers). If each integer-python-object takes 16 bytes, this makes 60000 * 16 = almost 1MB of memory just for the tilemaps... Using array of type H (16 bits per item = 2 bytes), my maps take just 60000*2 = 120KB of memory. After that, I just will access tilemap data for reading (i.e. value = tilemap.GetTile(x,y)) ... Do you think I should still go with lists instead of an H-type array? From terry at jon.es Wed Jan 23 16:55:56 2008 From: terry at jon.es (Terry Jones) Date: Wed, 23 Jan 2008 22:55:56 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 13:23:46 on Wednesday, 23 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> <127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com> <457550e3-f5e1-4fad-b553-c3e5e400dbb1@u10g2000prn.googlegroups.com> Message-ID: <18327.47084.736074.304302@jon.es> >>>>> "Arnaud" == Arnaud Delobelle writes: >> >> Ha - you can't have it both ways Arnaud! You don't want the computation to >> go negative... doesn't that (and my "proof") have something to do with the >> inverse nature of add and sub? :-) Arnaud> I think I can have it both ways, here's why: the "big then small" Arnaud> and "no negatives" rules are applied indiscriminately by the Arnaud> algorithm: it doesn't need to know about the history of operations Arnaud> in order to make a decision depending on their nature. OTOH, Arnaud> identifying (a + b) - c and a + (b - c) for example, requires Arnaud> inspection of the stack/tree/ calculation history. It is an Arnaud> *informed* decision made by the algorithm But this is having it both ways too :-) The reason the algorithm can do it indiscriminately is because *you* know that it always applies, and *you* figure out and implement the algorithm that way. The algorithm doesn't have a mind of its own, after all. BTW, there are some very important issues here. One is about representation (thinking about representation is one of my pet vices). When you try to solve some real-world problem with a computer, you must choose a representation. What many people seem to fail to recognize is that in so doing you've already begun to solve the problem. If you pick a better representation, your algorithm can potentially be much dumber and still be hugely faster than a brilliant algorithm on a terrible representation. In maintaining an A > B invariant in operations A + B and A * B, you're using insight into the problem to influence representation. With that better representation, your algorithm doesn't have to do so much work. I wrote some more about this a while ago at http://www.fluidinfo.com/terry/2007/03/19/why-data-information-representation-is-the-key-to-the-coming-semantic-web/ Arnaud> Note that disallowing 0 and disallowing x - x are equivalent, as Arnaud> the only way to get your first 0 is by doing x - x. That depends. I allow negative numbers in the input, and also 0 (I just don't let you use it :-)) Arnaud> Thanks for the discussion, it's made me realise more clearly what I Arnaud> was doing. Me too! Thanks. Terry From revuesbio at gmail.com Fri Jan 18 09:21:27 2008 From: revuesbio at gmail.com (revuesbio) Date: Fri, 18 Jan 2008 06:21:27 -0800 (PST) Subject: MySQLdb and compatibility with vista 64 bits References: <3bb34edc-2c2c-4ff5-8042-dc94c7fadc4f@s19g2000prg.googlegroups.com> Message-ID: <7c69d9b4-313e-4130-83ec-6cbb40d04efe@y5g2000hsf.googlegroups.com> On 5 jan, 20:00, revuesbio wrote: > Hello, > I try to installmysqldbon windows vista 64bits but there is a > failure when i try to importmysqldbin python 2.5 : > "DLL load failed with error code 193" > > Is there a solution to this problem ? > Thank you is there another solution to interact mysql and python with vista x64 ? From pavlovevidence at gmail.com Sat Jan 5 16:15:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 5 Jan 2008 16:15:16 -0500 Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> Message-ID: <41solf.jf2.ln@127.0.0.1> On Sat, 05 Jan 2008 08:14:46 -0800, caca wrote: > On Jan 5, 5:07 pm, c... at mailinator.com wrote: >> Hello, Paul and Arnaud. >> While I think about your answers: do you think there is any way to >> avoid shuffle? >> It may take unnecessary long on a long list most of whose elements have >> the property. > > Umm... > You provide nice answers in the case many elements are picked from the > same list. > Any ideas for the case when the picker is called many times on a > program, but never twice with the same list? ISTM the best thing would be to reimplement the shuffle algorithm, but to stop shuffling as soon as you get a hit. The drawback is that it's a destructive operation, but that doesn't sound like it's an issue for you. Here's something for starters: def random_element_with_property(x,test_property_func): for i in xrange(len(x)-1): j = random.randrange(i+1,len(x)) tmp = x[j] if test_property_func(tmp): return tmp x[j] = x[i] x[i] = tmp return None Then, for example, use it like this: def odd(i): return i&1 e = random_element_with_property(range(20),odd) Carl Banks From bearophileHUGS at lycos.com Tue Jan 15 11:32:54 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 15 Jan 2008 08:32:54 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> <478c868a$0$7040$426a34cc@news.free.fr> <5c0a472a-5ed6-4b34-9685-42f9a0a4145e@k39g2000hsf.googlegroups.com> Message-ID: cokofree... at gmail.com: > A lecturer gave me the perfect answer to the question of speed. > "You have two choices when it comes to programming. Fast code, or fast > coders." I don't believe that anymore, ShedSkin compiles slowly and it has limitations still, but it shows that it's possible to create a language with simple short syntax and high running speed at the same time. Bye, bearophile From arkanes at gmail.com Fri Jan 11 14:06:02 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 11 Jan 2008 13:06:02 -0600 Subject: Strange problem: MySQL and python logging using two separate cursors In-Reply-To: <13oa2dqgt7c0oac@corp.supernews.com> References: <13oa2dqgt7c0oac@corp.supernews.com> Message-ID: <4866bea60801111106q5a3b888le734c5b1bd2d1278@mail.gmail.com> On Jan 9, 2008 11:52 AM, Dennis Lee Bieber wrote: > On Wed, 9 Jan 2008 10:11:09 +0100, Frank Aune > declaimed the following in comp.lang.python: > > > The only clue I have so far, is that the cursor in task 1 seems to be unable > > to "register" any new entries in the log table produced by task 2 as soon as > > task 1 perform an SQL query of some kind. > > > How often do you issue a commit? For some DB-API adapters (I forget > which database -- think it was SQLite) a select query does not complete > until the last data has been fetched from it -- meaning the transaction > (the DB-API spec is that auto-commit is OFF) is still open and "other > transaction changes" will not be seen. {I do find it perplexing that > transactions are started by cursor actions, but committed by the > connection!} > > > Im contemplating using the same cursor for task 1 and 2, but I think keeping > > them separate is a better design - if it only worked :) > > > I'd probably suggest using a separate connection and cursor -- with > liberal usage of conn.commit() to ensure that transaction "views" are > flushed/refreshed. The MySql api doesn't have a concept of a cursor, only connections. If you want truly separate cursors in MySql you need to use individual connections. From donn.ingle at gmail.com Sun Jan 13 13:48:08 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 20:48:08 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A4F8A.5010108@v.loewis.de> References: <200801131928.54459.donn.ingle@gmail.com> <478A4F8A.5010108@v.loewis.de> Message-ID: <200801132048.08966.donn.ingle@gmail.com> Well, that didn't take me long... Can you help with this situation? I have a file named "M?gul.pog" in this directory: /home/donn/.fontypython/ I set my LANG=C Now, I want to open that file from Python, and I create a path with os.path.join() and an os.listdir() which results in this byte string: paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] I *think* that the situation is impossible because the system cannot resolve the correct filename (due the locale being ANSI and the filename being other) but I am not 100% sure. So, I have been trying combinations of open: 1. f = codecs.open( paf, "r", "utf8" ) I had hopes for this one. 2. f = codecs.open( paf, "r", locale.getpreferredencoding()) 3. f = open( paf, "r") But none will open it - all get a UnicodeDecodeError. This aligns with my suspicions, but I wanted to bounce it off you to be sure. It does not really mesh with our previous words about opening all files as bytestrings, and admits failure to open this file. Also, this codecs.open(filename, "r", ) function: 1. Does it imply that the filename will be opened (with the name as it's type : i.e. bytestring or unicode ) and written *into* as 2. Imply that filename will be encoded via and written into as It's fuzzy, how is the filename handled? \d -- He has Van Gogh's ear for music. -- Billy Wilder Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From pavlovevidence at gmail.com Wed Jan 9 22:44:53 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 9 Jan 2008 22:44:53 -0500 Subject: for loop without variable References: Message-ID: On Wed, 09 Jan 2008 14:25:36 -0800, erik gartz wrote: > Hi. I'd like to be able to write a loop such as: for i in range(10): > pass > but without the i variable. The reason for this is I'm using pylint and > it complains about the unused variable i. I can achieve the above with > more lines of code like: > i = 0 > while (i != 10): > i += 1 > Is there a concise way to accomplish this without adding extra lines of > codes? Thanks in advance for your help. IIRC, in pylint you can turn off checking for a particular symbol. I had to edit a .pylintrc file (location may vary on Windows) and there was a declaration in the file that listed symbols to ignore. Last time I bothered running it, I added "id" to that list, since I use it often (bad habit) and almost never use the builtin id, but still wanted shadowing warnings for other symbols. Carl Banks From deets at nospam.web.de Tue Jan 15 16:49:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 Jan 2008 22:49:53 +0100 Subject: searching an XML doc In-Reply-To: <327368a7-694f-4f30-8f76-db0569ed4a5c@k2g2000hse.googlegroups.com> References: <327368a7-694f-4f30-8f76-db0569ed4a5c@k2g2000hse.googlegroups.com> Message-ID: <5v4o44F1l2oshU1@mid.uni-berlin.de> Gowri schrieb: > Hello, > > I've been reading about ElementTreee and ElementPath so I could use > them to find the right elements in the DOM. Unfortunately neither of > these seem to offer XPath like capabilities where I can find elements > based on tag, attribute values etc. Are there any libraries which can > give me XPath like functionality? lxml does that. Diez From cameronwong88 at gmail.com Fri Jan 4 14:56:11 2008 From: cameronwong88 at gmail.com (cameronwong88 at gmail.com) Date: Fri, 4 Jan 2008 11:56:11 -0800 (PST) Subject: Question on os.tempnam() vulnerability Message-ID: Hello, Does any one know what kind of security risk these message are suggesting? >>> f = os.tempnam() __main__:1: RuntimeWarning: tempnam is a potential security risk to your program >>> f '/tmp/filed4cJNX' >>> g = os.tmpnam() __main__:1: RuntimeWarning: tmpnam is a potential security risk to your program >>> g '/tmp/fileENAuNw' Thanks, ~cw From oweston at earthlink.net Thu Jan 3 09:45:56 2008 From: oweston at earthlink.net (wes) Date: Thu, 03 Jan 2008 06:45:56 -0800 Subject: problem with global var In-Reply-To: References: Message-ID: <13npt8kotgm0964@corp.supernews.com> Bruno Ferreira wrote: > Hi, > > I wrote a very simple python program to generate a sorted list of > lines from a squid access log file. > > Here is a simplified version: > > ################################## > 1 logfile = open ("squid_access.log", "r") > 2 topsquid = [["0", "0", "0", "0", "0", "0", "0"]] > 3 > 4 def add_sorted (list): global topsquid > 5 for i in range(50): > 6 if int(list[4]) > int(topsquid[i][4]): > 7 topsquid.insert(i,list) > 8 break > 8 # Max len = 50 > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > 12 > 13 while True: > 14 logline = logfile.readline() > 15 linefields = logline.split() > 16 > 17 if logline != "": > 18 add_sorted (linefields) > 19 else: > 20 break > 21 > 22 for i in range (len(topsquid)): > 23 print topsquid[i][4] > #################################### > > When I execute the program _without_ the lines 10 and 11: > > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > > it runs perfectly. > > But if I execute the program _with_ those lines, this exception is thrown: > > bruno at ts:~$ python topsquid.py > Traceback (most recent call last): > File "topsquid.py", line 20, in > add_sorted (linefields) > File "topsquid.py", line 6, in add_sorted > if int(list[4]) > int(topsquid[i][4]): > UnboundLocalError: local variable 'topsquid' referenced before assignment > > > Note that now the error shown is not related with the lines 10 and 11, > but wiht a line prior to them. > > Any hints? > Try line 4 add. From pavlovevidence at gmail.com Sat Jan 12 14:16:38 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 12 Jan 2008 14:16:38 -0500 Subject: where do my python files go in linux? References: Message-ID: On Sat, 12 Jan 2008 12:02:20 +0100, Jorgen Bodde wrote: > I am trying to make a debian package. I am following the tutorial by > Horst Jens > (http://showmedo.com/videos/video? name=linuxJensMakingDeb&fromSeriesID=37) > and it is very informative. However one thing my app has and his > doesn't, is multiple python files which need to be executed. For example > > {dir}/app > app.py > > app.py calls a lot of modules in {dir}/app. Horst says the python file > goes in /usr/bin/app.py which is ok with me, but I have multiple python > files, and I decided to use an app.sh script to call my python files. In > the /usr/bin I do not see subdirs so I assume that is not really > desirable. > > Question 1. Where do I put the bulk of python scripts in a normal linux > environment? > Question 2. Should I use *.pyc rather then *.py files to speed up > executing as the user cannot write to /usr/bin or any other dir in the > system and everytime my app runs it will recompile it > > Thanks for any advice or maybe a good tutorial how to set up files in a > linux environment On a Debian system: I would put app.py in /usr/local/bin. I would create the directory /usr/local/lib/app, and put all other *.py and *.pyc files there. At the top of app.py, I'd add the following line so that I could import files directly from /usr/local/lib/app: sys.path.insert(0,'/usr/local/lib/app') Alternatively, using your app.sh approach, I'd put app.sh in /usr/local/bin/, and all *.py and *.pyc files in /usr/local/lib/app. I'd invoke Python something like this: PYTHONPATH=/usr/local/lib/app:$PYTHONPATH python -m app (The -m switch searches the Python path for a module to run.) If it's more of a library than an application (maybe there is a command line script, but users could want to import the modules directly), then I'd stick all the modules in /usr/local/lib/python2.x/site-packages, and the command line scripts in /usr/local/bin. Yes, install the *.pyc files. I recommend putting *.py files there as well, so users can refer to it if there are any problems, but you don't have to. The Python module compileall is your friend here. Carl Banks From sjmachin at lexicon.net Wed Jan 23 14:10:16 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 11:10:16 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> Message-ID: On Jan 24, 5:50 am, ryan k wrote: > Hello. I have a string like 'LNAME > PASTA ZONE'. I want to create a list of those words and > basically replace all the whitespace between them with one space so i > could just do lala.split(). Thank you! > > Ryan Kaskel So when you go to the Python interactive prompt and type firstly lala = 'LNAME PASTA ZONE' and then lala.split() what do you see, and what more do you need to meet your requirements? From rrr at ronadam.com Sun Jan 13 23:02:39 2008 From: rrr at ronadam.com (Ron Adam) Date: Sun, 13 Jan 2008 22:02:39 -0600 Subject: time.time or time.clock In-Reply-To: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> References: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> Message-ID: <478ADEDF.2070306@ronadam.com> John Machin wrote: > On Jan 14, 7:05 am, Ron Adam wrote: >> I'm having some cross platform issues with timing loops. It seems >> time.time is better for some computers/platforms and time.clock others, but > > Care to explain why it seems so? > >> it's not always clear which, so I came up with the following to try to >> determine which. >> >> import time >> >> # Determine if time.time is better than time.clock >> # The one with better resolution should be lower. >> if time.clock() - time.clock() < time.time() - time.time(): >> clock = time.clock >> else: >> clock = time.time >> >> Will this work most of the time, or is there something better? >> > > Manual: > """ > clock( ) > > On Unix, return the current processor time as a floating point number > expressed in seconds. The precision, and in fact the very definition > of the meaning of ``processor time'', depends on that of the C > function of the same name, but in any case, this is the function to > use for benchmarking Python or timing algorithms. > > On Windows, this function returns wall-clock seconds elapsed since the > first call to this function, as a floating point number, based on the > Win32 function QueryPerformanceCounter(). The resolution is typically > better than one microsecond. > [snip] > > time( ) > > Return the time as a floating point number expressed in seconds since > the epoch, in UTC. Note that even though the time is always returned > as a floating point number, not all systems provide time with a better > precision than 1 second. While this function normally returns non- > decreasing values, it can return a lower value than a previous call if > the system clock has been set back between the two calls. > """ > > AFAICT that was enough indication for most people to use time.clock on > all platforms ... before the introduction of the timeit module; have > you considered it? I use it to time a Visual Python loop which controls frame rate updates and set volocities according to time between frames, rather than frame count. The time between frames depends both on the desired frame rate, and the background load on the computer, so it isn't constant. time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't high enough resolution on windows. I do use timeit for bench marking, but haven't tried using in a situation like this. > It looks like your method is right sometimes by accident. func() - > func() will give a negative answer with a high resolution timer and a > meaningless answer with a low resolution timer, where "high" and "low" > are relative to the time taken for the function call, so you will pick > the high resolution one most of the time because the meaningless > answer is ZERO (no tick, no change). Some small fraction of the time > the low resolution timer will have a tick between the two calls and > you will get the wrong answer (-big < -small). If the difference is between two high resolution timers then it will be good enough. I think the time between two consectutive func() calls is probably low enough to rule out low resolution timers. In the case of two > "low" resolution timers, both will give a meaningless answer and you > will choose arbitrarily. In the case of two low resolution timers, it will use time.time. In this case I probably need to raise an exception. My program won't work correctly with a low resolution timer. Thanks for the feed back, I will try to find something more dependable. Ron From stephane at harobed.org Thu Jan 10 06:02:42 2008 From: stephane at harobed.org (=?iso-8859-1?q?KLEIN_St=E9phane?=) Date: Thu, 10 Jan 2008 11:02:42 +0000 (UTC) Subject: Do you know mirror repository of PyUMLGraph, what do you thinks about this tools ? Message-ID: Hi, I've looked http://www.umlgraph.org/ tools. I think it's great to generate UML Diagram from source code and comment's. I read there are "Python version" of this tools : PyUMLGraph (http://pypi.python.org/pypi/ PyUMLGraph/0.1.10). Unfortunately, repository of this tools is down :( My questions : * do you know a mirror repository of this tools ? * have you used this tools ? What do you thinks about ? I thinks this can be a great tools in agility programming context. Thanks for your informations Stephane From python.list at tim.thechases.com Wed Jan 9 09:40:33 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 09 Jan 2008 08:40:33 -0600 Subject: Open a List of Files In-Reply-To: <18308.56071.859777.102224@terry.local> References: <874pdomrrd.fsf@mulj.homelinux.net> <18308.12959.742868.758136@terry.local> <18308.56071.859777.102224@terry.local> Message-ID: <4784DCE1.3090602@tim.thechases.com> > You don't need "for fn in open_files.keys():", you can just use "for fn in > open_files:", but simpler than that is to just use the dictionary values: > > for fn in open_files.values(): > fn.close() This can also work for standard variable names: for f in (messages, deliveries, actions, parts, recipients, viruses, esp_scores): f.close() -tkc From PrinceOfDataMining at gmail.com Thu Jan 17 16:18:41 2008 From: PrinceOfDataMining at gmail.com (Samuel) Date: Thu, 17 Jan 2008 13:18:41 -0800 (PST) Subject: ANN:proxysocket(socks4,socks5)v0.1 Message-ID: <7228288b-cb34-40ba-8483-a2dc57115511@d21g2000prf.googlegroups.com> http://code.google.com/p/proxysocket/downloads/list From haraldarminmassa at gmail.com Wed Jan 23 07:28:54 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Wed, 23 Jan 2008 04:28:54 -0800 (PST) Subject: translating Python to Assembler...sorry if this is duplicated...it's unintentional References: Message-ID: <57c1047c-1646-458c-b20a-76b06991837f@h11g2000prf.googlegroups.com> > My expertise, if any, is in assembler. I'm trying to understand Python > scripts and modules by examining them after they have been > disassembled in a Windows environment. Maybe you could also profit from diassembling Pythons bytecode into MNEmonics of the Python Virtual Machine ? http://docs.python.org/lib/module-dis.html Because "disassembling python scripts" with any other disassembler will not likely lead to something usefull: a) the .pyc and pyo files are in Python Bytecode, that is "assembler for the Python Virtual Machine Processor", disassemble with the mentioned module b) python2x.dll is in i386-Assembler, but contains the virtual machine. Understanding that will you will learn a lot of great programming concepts from some of the most brilliant minds on this planet; but will give you no hint to understand Python scripts, as they are running on top of that VM. Like disassembling the Hybrid Power Drive of a Lexus GS450h will teach you nothing about navigating from Berlin to Paris. Best wishes, Harald From deets at nospam.web.de Sun Jan 20 14:59:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 20 Jan 2008 20:59:33 +0100 Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt In-Reply-To: References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> Message-ID: <5vhnheF1meri9U1@mid.uni-berlin.de> pythonewbie schrieb: > On 20 jan, 19:50, "Diez B. Roggisch" wrote: >> pythonewbie schrieb: >> >> >> >>> On 20 jan, 12:20, Christian Heimes wrote: >>>> pythonewbie wrote: >>>>> I am stucked on creating a function to get the Python install >>>>> directory (and site-packages directory) with a 100% reliable method... >>>> Only one method is 100% reliable: >>>> try: >>>> import yourextension >>>> except ImportError: >>>> available = False >>>> else: >>>> available = True >>>> Christian >>> Hi Christian, >>> OK thanks, interesting to detect if an extension is available or not. >>> But for different reasons I also want to get the absolute path of >>> Python install directory (not only the executable under Linux) and >>> site-packages directory. >>> How could I proceed ? >> Maybe sys.path is a starter? >> >> Diez > > Yes, it is, but my problem is that I am not sure to find the > information I need at the same position of the list generated by > sys.path. > > I explain, for Win32, I find install directory using sys.path[6] and > site-package directory using sys.path[7], for Linux I find install > directory using sys.path[2] and site-package directory using > sys.path[6]. > > For my tests, I have used XP Pro and Ubuntu Gutsy. > > I am not sure to find these information at the same position in the > sys.path list using Win9x, Win2k, Ubuntu Dapper, Redhat FC6, FreeBSD > and using Python v2.1 2.2 2.3 etc ? > > This why I'm asking experienced programmers of this usenet group for > advices. Sorry, I missed your first post. However, I don't see what your problem actually is. If you want to look for any extension, you need to consider whatever can be seen in the sys.path. So what do you care about the order of them? Diez From lefevrol at yahoo.com Mon Jan 28 14:29:52 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Mon, 28 Jan 2008 20:29:52 +0100 Subject: read and readline hanging In-Reply-To: <605nnmF1oc8dvU2@mid.uni-berlin.de> References: <5vuv9iF1o6ambU2@mid.uni-berlin.de> <605nnmF1oc8dvU2@mid.uni-berlin.de> Message-ID: > The buffering behavior at the interactive prompt is very often different > from connections via pipes. I hadn't thought of that. I will ask on the Octave list. Thanks, -- O.L. From JO3chiang at gmail.com Tue Jan 1 21:32:30 2008 From: JO3chiang at gmail.com (jo3c) Date: Tue, 1 Jan 2008 18:32:30 -0800 (PST) Subject: parse text files in a directory? Message-ID: hi everybody im a newbie in python, i have a question how do u parse a bunch of text files in a directory? directory: /dir files: H20080101.txt , H20080102.txt,H20080103.txt,H20080104.txt,H20080105.txt etc...... i already got a python script to read and insert a single text files into a postgres db. is there anyway i can do it in a batch, cause i got like 2000 txt files. thanks in advance joe From http Thu Jan 31 17:09:20 2008 From: http (Paul Rubin) Date: 31 Jan 2008 14:09:20 -0800 Subject: char string 2 hex string References: Message-ID: <7xfxwd3awf.fsf@ruckus.brouhaha.com> Antonio Chay writes: > "AAA" should be "414141" 'AAA'.encode('hex') From google at mrabarnett.plus.com Sun Jan 27 20:28:33 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 27 Jan 2008 17:28:33 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> <479d1616$0$9100$9b4e6d93@newsspool2.arcor-online.net> <13pqabbsrvkgn6f@corp.supernews.com> Message-ID: On Jan 28, 1:01 am, Steven D'Aprano wrote: > On Mon, 28 Jan 2008 00:39:02 +0100, Wildemar Wildenburger wrote: > > Dustan wrote: > >>> Well, you save one or two lines per class. Not enough in my opinion. > > >> Are you referring to the alternate syntax or to the decorator? Either > >> way, you could be saving 4 or 5 or more lines, if you have enough > >> arguments. > > > OK, but then again, every decent IDE should give you the tools to write > > an automation for that. Not that I don't like the idea of > > auto-assignment, but, you know ... > > You know, not everybody uses a "decent IDE", by choice or necessity, and > even if they did, having what is essentially a macro to type for you > doesn't solve the essential problem that you're writing the same thing > THREE TIMES instead of once. And then you have to keep it all in sync > through who knows how many code revisions and refactorings. > > class Parrot(object): # after many revisions... > def __init__(self, genus, species, variety, name, age, colours, > wingspan, beaksize, healthstate, language, vocabulary): > self.wingspan = wingspan > self.beaksize = beaksize > self.name = name > self.age = age > self.binomial_name = (genus, species) > self.breed = variety > self.colour = colour > self.language = language > self.state = get_state(healthstate) > self.words = vocabulary > self.colors = colours > > What IDE will spot the error(s) in the above? > > Here's another version, assuming syntax support for auto-assignment for > names starting with an ampersand: > > class Parrot(object): # after many revisions... > def __init__(self, genus, species, variety, &name, &age, &colours, > &wingspan, &beaksize, healthstate, &language, vocabulary): > self.binomial_name = (genus, species) > self.breed = variety > self.state = get_state(healthstate) > self.words = vocabulary > > See how much easier it is to keep the attributes synced with the > arguments? Don't Repeat Yourself in action. > > I think the biggest minus on this proposal is that it creates new syntax > that is only meaningful in the __init__ method of a class. "Special cases > aren't special enough to break the rules." I'd vote for it, but > conditionally. What should this do? > > def foo(x, y, &z): > pass > > Create foo.z perhaps? > Well, if: def __init__(self, &foo): pass does: def __init__(self, foo): self.foo = foo then: def foo(x, y, &z): pass does: def foo(x, y, &z): x.z = z Don't think that's useful, though... From steve at REMOVE-THIS-cybersource.com.au Thu Jan 24 16:27:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 24 Jan 2008 21:27:50 -0000 Subject: object vs class oriented -- xotcl References: Message-ID: <13pi0mmk525f325@corp.supernews.com> On Thu, 24 Jan 2008 12:35:44 -0800, William Pursell wrote: > Basically, you can > instantiate an object A of class Foo, and later change A to be an object > of class Bar. Does Python support this type of flexibility? As I > stated above, I've been away from Python for awhile now, and am a bit > rusty, but it seems that slots or "new style" objects might provide > this type of behavior. If you think slots are a candidate for this functionality, I think you have misunderstood what slots actually are. Slots don't define what class the object has, they are a memory optimization for when you need vast numbers of instances and don't need arbitrary attributes. > The ability to have an object change class is > certainly (to me) a novel idea. Can I do it in Python? Yes, mostly. Example: >>> class Spam(object): ... def whatami(self): ... return "I am a delicious and tasty processed meat product" ... >>> class Parrot(object): ... def whatami(self): ... return "I am a colourful bird with a large vocabulary" ... >>> >>> s = Spam() >>> s.whatami() 'I am a delicious and tasty processed meat product' >>> s.__class__ = Parrot >>> s.whatami() 'I am a colourful bird with a large vocabulary' If you actually play around with this, you'll soon find the limitations. For instance: >>> s.__class__ = int Traceback (most recent call last): File "", line 1, in TypeError: __class__ assignment: only for heap types -- Steven From peng.kyo at gmail.com Thu Jan 17 22:23:18 2008 From: peng.kyo at gmail.com (J. Peng) Date: Fri, 18 Jan 2008 11:23:18 +0800 Subject: array and list Message-ID: <18c1e5f20801171923q73e7830dj85b80d086ccbbb8f@mail.gmail.com> what's the difference between an array and a list in python? I see list has all features of array in C or perl. so please tell me.thanks. From pablo at decode.com.ar Wed Jan 23 18:05:01 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Wed, 23 Jan 2008 21:05:01 -0200 Subject: Increment Variable Name In-Reply-To: <56455F14-760D-4FE0-863B-949F863AD083@gmail.com> References: <56455F14-760D-4FE0-863B-949F863AD083@gmail.com> Message-ID: <4797C81D.4070105@decode.com.ar> Hi David, David Brochu wrote: > I know the length of a list and I want to pass each element of a list > to a unique variable, thus I want to increment variable names. If the > list length = 4, i want to have the following variables: var1, var2, > var3, var4. yuck... no, believe me, you probably don't want to do that. Why don't you tell us what you are actually trying to achieve instead? (I mean, the problem, not the solution) if you are REALLY sure that you want is what you asked: >>> for var in enumerate(['welcome', 'to', 'php']): ... exec "var%s=%r"% var ... >>> vars() {'var1': 'to', 'var0': 'welcome', 'var2': 'php', '__builtins__': , 'var': (2, 'php'), '__name__': '__main__', '__doc__': None} (I'm assuming that you have builtin objects in your list) This is completely unsafe and error prone. IOW horrible. HTH, Pablo From Frank.Aune at broadpark.no Tue Jan 22 07:18:03 2008 From: Frank.Aune at broadpark.no (Frank Aune) Date: Tue, 22 Jan 2008 13:18:03 +0100 Subject: MySQLdb and DictCursor Message-ID: <200801221318.03990.Frank.Aune@broadpark.no> Hi, Im using a MySQLdb connection with a DictCursor, and to me it seems the wrapping to dictionaries only prepend column names when there is an actual conflict in the keywords. I would like the cursor to always prepend table names no matter what. Is this possible? Thanks, -Frank From musiccomposition at gmail.com Mon Jan 14 22:26:35 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 14 Jan 2008 19:26:35 -0800 (PST) Subject: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net> Message-ID: <57518348-4d34-404c-8ec2-f97ac407510b@f47g2000hsd.googlegroups.com> On Jan 14, 6:26 pm, John Nagle wrote: > I passed a dict for the "env" variable to Popen with Unicode strings > for the dictionary values. > > Got: > > File "D:\Python24\lib\subprocess.py", line 706, in _execute_child > TypeError: environment can only contain strings > > It turns out that the strings in the "env" parameter have to be ASCII, > not Unicode, even though Windows fully supports Unicode in CreateProcess. > > John Nagle From danb_83 at yahoo.com Sun Jan 6 18:59:51 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 6 Jan 2008 15:59:51 -0800 (PST) Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <5u95sjF1etf0nU1@mid.individual.net> Message-ID: <42aeef02-a0a9-4e29-9a5d-7a0785997666@v67g2000hse.googlegroups.com> On Jan 5, 4:53 am, Bjoern Schliessmann wrote: > MartinRineh... at gmail.com wrote: > > Jeroen Ruigrok van der Werven wrote: > >> self.startLoc = start > >> self.stopLoc = stop > > > Thanks! Of course it should. Old Java habits die slowly. > > That's not really a Java habit. In Java and C++, personally I like > to write > > this.startLoc = start > this.stopLoc = stop > > It makes much clearer what a field and what a "normal" variable is > in those languages. My employer has us use the "m_" convention. I wonder why Bjarne made "this->" optional in the first place. From eddie at holyrood.ed.ac.uk Thu Jan 31 06:01:18 2008 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 31 Jan 2008 11:01:18 +0000 (UTC) Subject: Online Debugging References: Message-ID: Yansky writes: >I'm trying to debug a script on my server and it's taking forever >using print to find the error. I've tried to use the debugging >examples on this page http://webpython.codepoint.net/debugging but >they don't seem to be working for me. >Is there an easier/better way to debug online scripts? I was hoping >there might be something similar to php where it gives some error info >and the line code. One simple method might be something along these lines: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215 which I came across yesterday. Eddie From paddy3118 at googlemail.com Fri Jan 11 11:00:28 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 11 Jan 2008 08:00:28 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <41548a0d-eb74-4cd5-94b7-0ca11e691204@f3g2000hsg.googlegroups.com> <1199925201.586849@www.vif.com> <13oe3ijtbad01e4@corp.supernews.com> <05193522-df52-47d1-b9a0-b9e903b75222@k39g2000hsf.googlegroups.com> Message-ID: On Jan 11, 9:31 am, cokofree... at gmail.com wrote: > evenOrOdd = True > s1, s2 = "hi_cat_bye_dog_foo_bar_red", "" > > for i in s1: > if i == '_': > s2 += ':' if evenOrOdd else ',' > evenOrOdd = not evenOrOdd > else: > s2 += i > > print s2 > > Presently I cannot work out how to use .join instead of += ... Do s2 = [] then later: s2.append(i) and at the end: print ''.join(s2) - Paddy. > While I realise this is producing a new string (and I believe += > rebuilds it a lot?) how much slower > is this going to be over the others? From aaron.watters at gmail.com Tue Jan 1 16:26:13 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 1 Jan 2008 13:26:13 -0800 (PST) Subject: cloud computing (and python)? Message-ID: So, in between skiing runs I noticed a Business Week cover story on "cloud computing". The article had lots of interesting information in it like about how somebody's mom used to be an airline stewardess and the interior decor of various office spaces. It was a truly excellent piece of journalism. However it gave me no idea what "cloud computing" is and how it could be used to solve a computational problem. Could anyone on this list which usually has highly informed readers give me a clue at some level of technical detail what cloud computing is about and how it could be used. Bonus points if you mention Python in the response! An actual example would be great, if it's not web scraping and searching. - Aaron Watters == http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=snow From brkict at gmail.com Mon Jan 21 14:52:16 2008 From: brkict at gmail.com (glomde) Date: Mon, 21 Jan 2008 11:52:16 -0800 (PST) Subject: is it possible to set namespace to an object. References: <27529efd-b8d8-4a8e-b72d-379a607366b7@i7g2000prf.googlegroups.com> <4794dd6c$0$27198$9b4e6d93@newsspool1.arcor-online.net> <62e9433b-4f04-4020-b1e6-581496ba3f3e@s19g2000prg.googlegroups.com> <9b656006-3b97-4ee8-b992-ff06b970904b@q77g2000hsh.googlegroups.com> Message-ID: <6e6d0820-d7e1-4042-a75d-c193d133970b@u10g2000prn.googlegroups.com> On 21 Jan, 20:16, George Sakkis wrote: > On Jan 21, 1:56 pm, glomde wrote: > > > > > On 21 Jan, 18:59, Wildemar Wildenburger > > > wrote: > > > glomde wrote: > > > > Hi, > > > > > is it somehow possible to set the current namespace so that is in an > > > > object. > > > > [snip] > > > > set namespace testObj > > > > Name = "Test" > > > > > Name would set testObj.Name to "Test". > > > > > [snip] > > > > > Is the above possible? > > > > Don't know, sorry. But let me ask you this: Why do you want to do this? > > > Maybe there is another way to solve the problem that you want to solve. > > > The reason is that I do not want to repeat myself. It is to set up XML > > type like > > trees and I would like to be able to do something like. > > > with ElemA(): > > Name = "Top" > > Description "Blahaha..." > > with ElemB(): > > Name = "ChildA" > > Description "Blahaha..." > > .... > > > This would be the instead of. > > with ElemA() as node: > > node.Name = "Top" > > node.Description "Blahaha..." > > with ElemB() as node: > > node.Name = "ChildA" > > node.Description "Blahaha..." > > .... > > > So to save typing and have something that I think looks nicer. > > ... and more confusing for anyone reading the code (including you > after a few weeks/months). If you want to save a few keystrokes, you > may use 'n' instead of 'node' or use an editor with easy auto > completion. > > By the way, is there any particular reason for generating the XML > programmatically like this ? Why not have a separate template and use > one of the dozen template engines to populate it ? > > George I am not using it for XML generation. It was only an example. But the reason for using it programmatically is that you mix power of python with templating. Using for loops and so on. XIST(www.livinglogic.de) is doing something similar. But I would like the namespace thing. The above was only an example. And yes it might be confusing if you read the code. But I still want to do it, the question is it possible? From r.grimm at science-computing.de Sat Jan 5 05:06:21 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Sat, 5 Jan 2008 02:06:21 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: On Jan 4, 6:08 pm, Sion Arrowsmith wrote: > Hrvoje Niksic wrote: > > >BTW if you're using C++, why not simply use std::set? > > Because ... how to be polite about this? No, I can't. std::set is > crap. The implementation is a sorted sequence -- if you're lucky, > this is a heap or a C array, and you've got O(log n) performance. > But the real killer is that requirement for a std::set is that > T::operator< exists. Which means, for instance, that you can't > have a set of complex numbers.... > > -- Hallo and Sorry for being OT. As Arnaud pointed out, you must only overload the < Operator for the requested type. Something like bool operator < ( const Type& fir, const Type& sec ).... similar to python with __lt__ . The rest of magic will be done by the compiler/interpreter. Assoziative Arrays (set,map,multi_set,multi_map) in the classical STL are implemented as binary trees. Therefore the keys must be comparable and the access time is O(log n ). To get a dictionary with O(1), the most STL implementation support a extension called hash_set. The new standard TR1 support unsorted_set ... . You can download it from www.boost.org. Newer gcc runtimes also including the new subnamespace tr1. There is no need to implement set in c++ to get O(1). Greetings Rainer From meesters at uni-mainz.de Mon Jan 28 10:10:10 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Mon, 28 Jan 2008 16:10:10 +0100 Subject: extending Python - passing nested lists Message-ID: Hi, I would like to write a C-extension function for an application of mine. For this I need to pass a nested list (like: [[a, b, c], [d, e, f], ...], where all letters are floats) to the C-function. Now, with the code I have the compiler is complaining: "subscripted value is neither array nor pointer". Can somebody tell me what's wrong? Here a code snippet to reproduce this problem: static PyObject *_foo(PyObject *self, PyObject *args) { int i; long lenght; float ax, ay, az; PyObject *dummy_list; if (!PyArg_ParseTuple(args, "O", &dummy_list)) return NULL; dummy_list = PySequence_Fast(dummy_list, "argument must be iterable"); lenght = PyObject_Length(dummy_list); for (i=0; i < lenght; i++) { // part which does not work: ax = dummy_list[i][0]; ay = dummy_list[i][1]; az = dummy_list[i][2]; } return 0; } TIA Christian From ryszard.szopa at gmail.com Tue Jan 15 15:54:11 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Tue, 15 Jan 2008 12:54:11 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> <478D044D.1040406@skynet.be> Message-ID: <87846c00-1f44-4362-add1-54e5cfc094e9@u10g2000prn.googlegroups.com> On Jan 15, 8:06 pm, Helmut Jarausch wrote: > Unfortunately the links [2], [3] and [4] are not given, Luckily, there's Google :) [2] Article about MRO: http://www.python.org/download/releases/2.3/mro/ [3] Descriptor HowTo: http://users.rcn.com/python/download/Descriptor.htm [4] Articles about metaclasses (second one relevant to super): * http://www.ibm.com/developerworks/linux/library/l-pymeta.html, * http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/?S_TACT=105AGX03&S_CMP=ART, * http://www.ibm.com/developerworks/linux/library/l-pymeta3.html?S_TACT=105AGX03&S_CMP=ART Of course, it would be very nice if the article was updated to include the links. HTH, -- Richard From deets at nospam.web.de Tue Jan 15 04:47:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 Jan 2008 10:47:53 +0100 Subject: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net> <5v2cudF1k5a1oU1@mid.individual.net> <478c551a$0$36354$742ec2ed@news.sonic.net> Message-ID: <5v3dq9F1k2577U1@mid.uni-berlin.de> John Nagle wrote: > Benjamin wrote: >> On Jan 14, 6:26 pm, Bjoern Schliessmann > mail-0306.20.chr0n... at spamgourmet.com> wrote: >>> John Nagle wrote: >>>> It turns out that the strings in the "env" parameter have to be >>>> ASCII, not Unicode, even though Windows fully supports Unicode in >>>> CreateProcess. That's of course nonsense, they don't need to be ascii, they need to be byte-strings in whatever encoding you like. >>> Are you sure it supports Unicode, not UTF8 or UTF16? Probably using >>> something like u"thestring".encode("utf16") will help. >> Otherwise: bugs.python.org John's understanding of the differences between unicode and it's encodings is a bit blurry, to say the least. > Whatever translation is necessary should be done in "popen", which > has cases for Windows and POSIX. "popen" is supposed to be cross-platform > to the extent possible. I think it's just something that didn't get fixed > when Unicode support went in. Sure thing, python will just magically convert unicode to the encoding the program YOU invoke will expect. Right after we introduced the solve_my_problem() built-in-function. Any other wishes? If I write this simple program ------ test.py ------- import os import sys ENCODDINGS = ['utf-8', 'latin1'] os.env["MY_VARIABLE"].encode(ENCODINGS[int(sys.argv[1])]) ------ test.py ------- how's python supposed to know that suprocess.call("python test.py 0", env=dict(MY_VARIABLE=u'foo')) needs to be UTF-8? Diez From aahz at pythoncraft.com Wed Jan 2 23:29:57 2008 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2008 20:29:57 -0800 Subject: Two candies References: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com> Message-ID: In article <78662711-83fe-47ae-9dfa-d55d710bcdac at i3g2000hsf.googlegroups.com>, wrote: > >2) When I use MatchObjects I have to look at the docs to remember the >difference between group() and groups() etc. So I suggest to add a >__getitem__ method to MatchObject, so this: > >mo[3] > >Equals to: > >mo.group(3) Patches are wonderful, but if not, please post this RFE to the bug tracker. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From lasses_weil at klapptsowieso.net Wed Jan 30 09:18:32 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Wed, 30 Jan 2008 15:18:32 +0100 Subject: optional static typing for Python In-Reply-To: References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> <479e0225$0$36389$742ec2ed@news.sonic.net> <70c4064a-a65d-4fd5-b39c-38e6a3fb567b@i7g2000prf.googlegroups.com> <479fb907$0$25376$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <47a08738$0$9108$9b4e6d93@newsspool2.arcor-online.net> Kay Schluehr wrote: > On Jan 30, 12:38 am, Wildemar Wildenburger > wrote: >>> Python has a JIT right no >> You mean in the Java-sense (outputting native machine code)? >> >> /W > > Sure. > > http://psyco.sourceforge.net/ > Oh, switcheroo! :) /W From theller at ctypes.org Tue Jan 22 08:42:43 2008 From: theller at ctypes.org (Thomas Heller) Date: Tue, 22 Jan 2008 14:42:43 +0100 Subject: ctypes CDLL - which paths are searched? In-Reply-To: <4795E88F.7050406@igpm.rwth-aachen.de> References: <4794d573$0$2980$ba620e4c@news.skynet.be> <4795E88F.7050406@igpm.rwth-aachen.de> Message-ID: Helmut Jarausch schrieb: > Thomas Heller wrote: >> Helmut Jarausch schrieb: >>> Hi, >>> >>> how can I specify the paths to be searched for a dynamic library >>> to be loaded by ctypes' CDLL class on a Linux system. >>> >>> Do I have to set os.environment['LD_LIBRARY_PATH'] ? >>> >> >> ctypes passes the argument given to CDLL(path) straight to >> the dlopen(3) call, so your system documentation should tell you. >> > > Thanks, > > but then it's difficult to use CDLL. Setting > os.environ['LD_LIBRARY_PATH'] within the script which > calls CDLL is too late. > What other methods are possible rather than put an explicit > export LD_LIBRARY_PATH=... > before running the script, if I don't want to put the dynamic > library into a standard system library. I guess you can also use an absolute pathname (but the dlopen(3) manpage should tell you more. I'm not too familiar with linux). Thomas From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 21 13:19:59 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 19:19:59 +0100 Subject: Default attribute values pattern In-Reply-To: <41f8394c-342c-42dc-9bf2-a737b572aff9@c4g2000hsg.googlegroups.com> References: <4794697f$0$16980$426a74cc@news.free.fr> <41f8394c-342c-42dc-9bf2-a737b572aff9@c4g2000hsg.googlegroups.com> Message-ID: <4794e206$0$4429$426a74cc@news.free.fr> cokofreedom at gmail.com a ?crit : >> Grab(argdict, key, default) is argdict.pop(key, default) > > "pop() raises a KeyError when no default value is given and the key is > not found." Then use it with a default value !-) >> def grab(kw, key, default=None): >> try: >> return kw.pop(key) >> except KeyError: >> return default > > So Bruno's technique seems to me to be the correct one as it catches > the KeyError. Note that I cancelled the message (too bad, doesn't work everywhere). I totally agree with Arnaud on this, and should sometimes re-read the doc for stuff I use so often I think I know them. From gagsl-py2 at yahoo.com.ar Wed Jan 23 16:14:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 19:14:00 -0200 Subject: HTML parsing confusion References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> <50269e4a-af44-4d73-b6cb-c42af6b5164d@e10g2000prf.googlegroups.com> <5vmkiiF1nadr7U1@mid.uni-berlin.de> <38176c81-a9b1-40dc-8bbe-25c5b3f4a75a@p69g2000hsa.googlegroups.com> Message-ID: En Wed, 23 Jan 2008 10:40:14 -0200, Alnilam escribi?: > Skipping past html validation, and html to xhtml 'cleaning', and > instead starting with the assumption that I have files that are valid > XHTML, can anyone give me a good example of how I would use _ htmllib, > HTMLParser, or ElementTree _ to parse out the text of one specific > childNode, similar to the examples that I provided above using regex? The diveintopython page is not valid XHTML (but it's valid HTML). Assuming it's property converted: py> from cStringIO import StringIO py> import xml.etree.ElementTree as ET py> tree = ET.parse(StringIO(page)) py> elem = tree.findall('//p')[4] py> py> # from the online ElementTree docs py> http://www.effbot.org/zone/element-bits-and-pieces.htm ... def gettext(elem): ... text = elem.text or "" ... for e in elem: ... text += gettext(e) ... if e.tail: ... text += e.tail ... return text ... py> print gettext(elem) The complete text is available online. You can read the revision history to see what's new. Updated 20 May 2004 -- Gabriel Genellina From ram.rachum at gmail.com Wed Jan 23 09:10:07 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Wed, 23 Jan 2008 06:10:07 -0800 (PST) Subject: A GUI framework for running simulations Message-ID: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com> Hello! I am currently working on writing a simulation engine for special relativity physics. I'm writing it in Python, of course. I'm doing fine with the engine, but I want a GUI framework in which I could use it conveniently, and test different setups on it. I'm not so strong with GUI programming. I looked at Tkinter, I looked at WxPython, I looked at PythonCard. It all looks pretty daunting. My question is, does there exist a GUI package that is intended specifically for simulations? I saw a program called Golly, which is a simulation for Conway's Game of Life. Its GUI had most of the features I needed. For example, you can load a setup, there are "play" and "stop" buttons, you can change a setup and save it, etc. So does anyone know of a general GUI framework for running simulations? From marekjed at pobox.INVALID.com Mon Jan 28 06:48:57 2008 From: marekjed at pobox.INVALID.com (marek jedlinski) Date: Mon, 28 Jan 2008 12:48:57 +0100 Subject: Can xml.sax NOT process the DTD? Message-ID: I'm using xml.sax to extract certain content from xml files. (Background: my job is software localization; these are bilingual xml files, from which I need to extract translated text, e.g. for spellchecking). It works fine, unless a particular file has a doctype directive that specifies a DTD. The parser then bails out, because the dtd is not available (IOError, file not found). Since I don't have the DTDs, I need to tell the SAX parser to ignore the doctype directive. Is this possible, please? I've noticed that I can eliminate the error if I create 0-byte dtd files and put them where the parser expects to find them, but this is a little tedious, since there are plenty of different DTDs expected at different locations. Or is there another SAX parser for Python I could use instead? Kind thanks for any suggestions, .marek -- No ads, no nags freeware: http://www.tranglos.com From walterbyrd at iname.com Wed Jan 30 15:27:16 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 30 Jan 2008 12:27:16 -0800 (PST) Subject: Trying to understand Python web-development References: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com> <2bb822db-0a33-4c47-bdd1-f4980a73fc00@m34g2000hsf.googlegroups.com> Message-ID: <85a24948-9e59-4b74-95e8-6d9c75e9bff7@e23g2000prf.googlegroups.com> Thanks for all that posts. This thread has been helpful. I have seen a lot of posts about the importance of decoupling the deployment technologies from the framework technologies. This is how I have done that in PHP. I develop on my home box. When I get something working the way I want, I ftp those files to the remote server. To me, that seems to make more sense that trying to run two different web servers on the same system. My PHP system involves no monkeying with special config files, or running special servers to couple the different environments, or setting special ports, or paths. For PHP development, I don't even need ssh access. > I think that this (the ease of PHP application deployment) is one of the things that keeps Python framework developers up at night I think you may have something there. For $10 a year I can get an account at dollar-hosting.net, copy some php files there, and that's all there to it. I have been beating my brains out trying to get anything working with a python framework, and I have not been able to do it. I even bought VPS hosting just for the sake of python development. But, I still can not seem to make the quantum leap of getting something that works locally, to work remotely. BTW: with the VPS hosting, I had to install and configure my own web-hosting and PHP, including setting up lighttpd with fastcgi and php modules - and I still found that much easier than getting anything to work with python. From rick.arnett at gmail.com Mon Jan 28 11:15:01 2008 From: rick.arnett at gmail.com (the_ricka) Date: Mon, 28 Jan 2008 08:15:01 -0800 (PST) Subject: SMTP Sending Mail Problem Message-ID: <9b00a5f5-277d-4d23-be82-60c2aafc4227@c23g2000hsa.googlegroups.com> Hi all, I'm fairly new to python, but very excited about it's potential. I'm trying to write a simple program that will accept input from a command line and send email. The parameters I used on the command line are for From address, To addresses, Subject and Body. For the body, I thought it would be better to read the input from a file so I could allow someone to nicely format the body with newlines in a text editor and just read it into a string and send it. However, whenever I try to read more than one line from the file, the email is not being delivered. The only reason I know this is because I tried just reading in the first line of the text file, and the email sent fine. Right now I believe this must have something to do with new line characters at the end of each line, but it doesn't quite make sense to me why this is a problem, as I have also used the same script and just created a string in it with multiple lines (\r\n) and sent it and the email sends fine. To complicate the issue further, I have turned used the set_debuglevel method so I can see the output from the SMTP server, and it appears that the message was Queued for mail delivery. The SMTP server we are using is Exchange if that matters. I have listed the code below, along with output from the SMTP server. Any help would be much appreciated. (Note, I don't typically read in the file with a range(n) iterator, but that is how I have noticed that I can send only one line, but not send multiple lines. As soon as I change the range value to 1, the email will successfully send the first line of the text file). import sys,smtplib if len(sys.argv) != 5: print """ Usage: sendmail FROM RECIPIENTS SUBJECT BODY RECIPIENTS should be a semicolon delimited list of email addresses. BODY should be a file where the message to send is stored Use double quotes to surround the SUBJECT element if it is more than one word """ exit() fromaddr = sys.argv[1] toaddrs = sys.argv[2].split(";") subject = sys.argv[3] body = "" print toaddrs print type(toaddrs) try: infile = open(sys.argv[4], 'r') for i in range(4): body = body + infile.readline() except IOError: print "Can't open the given file, please try again" exit() headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs), subject) msg = headers + body server = smtplib.SMTP('##############') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() Output: send: 'ehlo hplaptopr.############.com\r\n' reply: '250-################.com Hello [10.#.#.#]\r\n' reply: '250-SIZE 20971520\r\n' reply: '250-DSN\r\n' reply: '250-VRFY\r\n' reply: '250-AUTH GSSAPI NTLM LOGIN\r\n' reply: '250-AUTH=LOGIN\r\n' reply: '250 OK\r\n' reply: retcode (250); Msg: ################.com Hello [10.#.#.#] SIZE 20971520 DSN VRFY AUTH GSSAPI NTLM LOGIN AUTH=LOGIN OK send: 'mail FROM:<######@######.com> size=116\r\n' reply: '250 2.1.0 #######@######.com....Sender OK\r\n' reply: retcode (250); Msg: 2.1.0 ######@######.com....Sender OK send: 'rcpt TO:<######@######.com>\r\n' reply: '250 2.1.5 ######@######.com \r\n' reply: retcode (250); Msg: 2.1.5 #######@######.com send: 'data\r\n' reply: '354 Start mail input; end with .\r\n' reply: retcode (354); Msg: Start mail input; end with . data: (354, 'Start mail input; end with .') send: 'From: #######@######.com\r\nTo: ######@######.com\r\nSubject: Test1\r\n\ r\nThis is from the file\r\nThis concludes our test\r\n\r\n\r\n.\r\n' reply: '250 2.6.0 <############@###############.com> Qu eued mail for delivery\r\n' reply: retcode (250); Msg: 2.6.0 <##########@n#########.com> Queued mail for delivery data: (250, '2.6.0 <########@################.com> Q ueued mail for delivery') send: 'quit\r\n' reply: '221 2.0.0 ################.com Service closing transmission cha nnel\r\n' reply: retcode (221); Msg: 2.0.0 #################.com Service closing t ransmission channel From deets at nospam.web.de Sun Jan 27 12:50:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jan 2008 18:50:06 +0100 Subject: REALLY simple xml reader In-Reply-To: References: Message-ID: <603uikF1npdtkU1@mid.uni-berlin.de> Simon Pickles schrieb: > Hi > > Can anyone suggest a really simple XML reader for python? I just want to > be able to do something like this: > > xmlDoc = xml.open("file.xml") > element = xmlDoc.GetElement("foo/bar") > > ... to read the value of: > > > 42 > Since python2.5, the ElementTree module is available in the standard lib. Before 2.5, you can of course install it. Your code then would look like this: import xml.etree.ElementTree as et doc = """ 42 """ root = et.fromstring(doc) for bar in root.findall("bar"): print bar.text Diez From peterbe at gmail.com Wed Jan 16 19:13:41 2008 From: peterbe at gmail.com (Peter Bengtsson) Date: Wed, 16 Jan 2008 16:13:41 -0800 (PST) Subject: ElementTree and namespaces in the header only References: <2c769fe0-8add-4aa1-9657-b8ee5f76cb91@k39g2000hsf.googlegroups.com> Message-ID: <078052fc-ca12-4528-9113-5add7979c446@1g2000hsl.googlegroups.com> On Jan 15, 5:22 pm, Fredrik Lundh wrote: > Peter Bengtsson wrote: > > root = Element('feed', xmlns='http://www.w3.org/2005/Atom') > > root.set('xmlns:se', NS_URL) > > entry = SubElement(root, 'entry') > > SubElement(root, 'title').text = 'Title' > > SubElement(entry, SEN('category')).text = 'Category' > > But surely the xmlns:se attribute on the tag is > > excessive since the namespace (by the URI) is already defined in the > > tag. How do I set non-default namespace tags in elements > > without the automatic xmlns:se attribute repeated each time? > > ET 1.2's standard serializer doesn't take explicitly setnamespacesinto > account. If you want full control over namespace generation, you have > to do it yourself: > > http://effbot.org/zone/element-namespaces.htm#explicitly-setting-name... > > ET 1.3 provides a default_namespace option for this specific case (but > you still have to use universal names for everything that should go into > the default namespace). > > That's perfect Fredrik. Exactly what I was looking for. From arnodel at googlemail.com Thu Jan 24 02:27:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 23:27:17 -0800 (PST) Subject: Creating new types and invoking super References: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> <9eeb9667-f362-4ce2-971a-42ef639c8f86@c4g2000hsg.googlegroups.com> Message-ID: <185eb303-f233-4fcc-a45b-f2680618bb11@z17g2000hsg.googlegroups.com> On Jan 24, 7:19?am, Arnaud Delobelle wrote: Oops again > > Change this line to: > ? ? ? ? ? ? ? getattr(super.cls, obj), self.f.__name__)() I mean getattr(super(self.cls, obj), self.f.__name__)() -- Arnaud From matiassurdi at gmail.com Thu Jan 10 10:11:42 2008 From: matiassurdi at gmail.com (Matias Surdi) Date: Thu, 10 Jan 2008 16:11:42 +0100 Subject: importing module conflict In-Reply-To: <8763y1izrj.fsf@benfinney.id.au> References: <8763y1izrj.fsf@benfinney.id.au> Message-ID: Ben Finney escribi?: > Matias Surdi writes: > >> Suppose I've a module named "urllib" and from it I need to import >> the urllib module from the python standart library. > > What you want is the "absolute import" behaviour, described in PEP 328 > and implemented in > Python 2.5 . > Thanks a lot. That was exactly what I was looking for.Excellent. From dima.hristov at gmail.com Mon Jan 21 07:56:29 2008 From: dima.hristov at gmail.com (DHR) Date: Mon, 21 Jan 2008 04:56:29 -0800 (PST) Subject: Q: paramiko/SSH/ how to get a remote host_key References: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> Message-ID: I am connecting from a WindowsXP SP2 machine. When using Putty as an SSH client, if you connect for the first time then you get somethign like this: ''' The server's host key is not cached in the registry. You have no guarantee that the server is the computer you think it is. The server's rsa2 key fingerprint is: ssh-rsa 1024 7b:e5:6f:a7:f4:f9:81:62:5c:e3:1f:bf:8b:57:6c:5a If you trust this host, hit Yes to add the key to PuTTY's cache and carry on connecting. If you want to carry on connecting just once, without adding the key to the cache, hit No. If you do not trust this host, hit Cancel to abandon the connection. ''' If I get it correctly, Putty is using such a command to recieve the host_key the first time it connects to a remote SSH server. Then it stores it into the registry. The question is how can I do it from Python? Guilherme Polo wrote: > 2008/1/21, DHR : > > I'm trying to run the simpliest example form paramiko readme(Homepage: > > http://www.lag.net/paramiko/), and > > cannot find out how to get the remote SSH server host_key. > > > > > > This is the code. It is supposed to connect to a remote SSH host and > > execute an 'ls' command: > > > > import paramiko, base64 > > > > key = paramiko.RSAKey(data=base64.decodestring('AAA...')) > > client = paramiko.SSHClient() > > client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key) > > client.connect('227.112.168.273', username='uname', password='pass') > > stdin, stdout, stderr = client.exec_command('ls') > > for line in stdout: > > print '... ' + line.strip('\n') > > > > client.close() > > > > Now, if I understand it correctly I need to get somehow the host_key > > from the server and > > write it insted of the 'AAA...' thing. Is there a command to get the > > host_key from a remote SSH > > server? > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > You need a key to connect to that server, so you should want this: > > keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) > > Then keys[hostname] should contain a RSAKey object that you are looking for > > > -- > -- Guilherme H. Polo Goncalves From rndblnch at gmail.com Fri Jan 25 08:49:40 2008 From: rndblnch at gmail.com (rndblnch) Date: Fri, 25 Jan 2008 05:49:40 -0800 (PST) Subject: is possible to get order of keyword parameters ? Message-ID: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> (sorry, draft message gone to fast) i.e. is it possible to write such a function: def f(**kwargs): return result such as : f(x=12, y=24) == ['x', 'y'] f(y=24, x=12) == ['y', 'x'] what i need is to get the order of the keyword parameters inside the function. any hints ? thanks, renaud From roy at panix.com Sun Jan 27 20:41:59 2008 From: roy at panix.com (Roy Smith) Date: Sun, 27 Jan 2008 20:41:59 -0500 Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: In article , ajaksu wrote: > On Jan 27, 10:32 pm, Paddy wrote: > > I would value the opinion of fellow Pythoneers who have also > > contributed to Wikipedia, on the issue of "Is Python Standardized". > > Specifically in the context of this table: > > http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Gene... > > (Comparison of programming languages) > > And this entry in the talk page > > http://en.wikipedia.org/wiki/Talk:Comparison_of_programming_languages... > > (Talk:Comparison of programming languages#Standardized Python?) > > > > - Thanks. > > Hmmm. Seems to me that "Is X Standardized" in the given context means > having a formal, published standard issued by some Standards > organization. That's exactly what it means. For example, if I'm buying a C++ compiler, I can specify in the contract, "Must comply with ISO 14882", and everybody will know what I'm talking about. On the other side of the fence, if I'm a free-lance C++ developer, I can specify to my customers that the code I write will work properly when compiled with a compiler that meets ISO 14882. Whether such a compiler actually exists, is besides the point :-) Python has no such standard. Sure, there's the stuff on docs.python.org, but it's kind of hard to write a contract which says, "Must comply with the stuff on docs.python.org", and have it be meaningful in a legal sense. So, I think the "No" in the "Standardized?" column for python is exactly right. That's not to say you can't have something good which isn't standardized. Sometimes standards committees even go off into left field and field break stuff in the process of standardizing it. Some things have so many different standards (i.e. the pletora of unix standards), it's almost worthless to say it's standardized. But, as it stands, the Wikipedia article is correct. From wdraxinger at darkstargames.de Sat Jan 19 18:19:24 2008 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sun, 20 Jan 2008 00:19:24 +0100 Subject: HTTP POST uploading large files Message-ID: I'm thinking about writing a script to upload videos to sites like YouTube or Google Video, which is usually done by a HTTP POST. The problem is, that videos, by nature are rather big files, however urllib2 wants it's Request objects being prepared beforehand, which would mean to first load the whole file to memory. I looked into pycURL, knowing that cURL can POST send files directily from the file system, however pycURL doesn't expose the neccesary functions yet. Am I just blind for some urllib2/httplib feature, or some other library? Or do I really have to fiddle around with sockets myself (I hope not...). Thanks in advance Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From icarr at compx.com Wed Jan 2 14:11:07 2008 From: icarr at compx.com (Israel Carr) Date: Wed, 2 Jan 2008 14:11:07 -0500 Subject: database query - logic question Message-ID: <6A85AD3923D6C348AF108B4A8F459EA201BEFD3B@CIXMX1.compxnet.com> Thanks for anyone who takes the time to read this. If I posted to the wrong list, I apologize and you can disregard. I need help with a script to pull data from a postgres database. I'm ok with the database connection just not sure how to parse the data to get the results I need. I'm running Python 2.4.4. For what it's worth, once I can get my logic correct I'll be publishing the reports mentioned below via zope for web clients. Here is a small sample of the records in the table: name date time status machine1 01/01/2008 13:00:00 system ok machine1 01/01/2008 13:05:00 system ok machine1 01/01/2008 13:10:00 status1 machine1 01/01/2008 13:10:30 status1 machine1 01/01/2008 13:11:00 system ok machine1 01/01/2008 13:16:30 status2 machine1 01/01/2008 13:17:00 status2 machine1 01/01/2008 13:17:30 status2 machine1 01/01/2008 13:18:00 status2 machine1 01/01/2008 13:18:30 status2 machine1 01/01/2008 13:19:00 system ok machine1 01/01/2008 13:24:00 status2 machine1 01/01/2008 13:24:30 status2 machine1 01/01/2008 13:25:00 system ok I need to report from this data. The detail report needs to be something like: machine1 01/01/2008 13:10:00 status1 00:01:30 machine1 01/01/2008 13:16:30 status2 00:02:30 machine1 01/01/2008 13:24:00 status2 00:01:00 and the summary needs to be machine1 01/01/2008 total 'status1' time = 00:01:30 machine1 01/01/2008 total 'status2' time = 00:03:30 _____ machine1 01/01/2008 total 'non-OK' time = 00:05:00 #this is the sum of status1 and status2 times The 'machine1' system is periodically checked and the system status is written to the database table with the machinename/date/time/status. Everything that isn't a 'system ok' status is bad. For me to determine the amount of time a machine was in a bad status I'm taking the first time a machine has a 'system ok' status after a bad status and subtracting from that time the time that a machine first went into that bad status. From my table above: machine1 went into 'status2' status at 13:16:30 and came out of 'status2' to a 'system ok' status at 13:19:00. So the downtime would be 13:19:00 - 13:16:30 = 00:02:30 I'm not sure how to query when a 'bad' status is found to find the next 'good' status and calculate based on the times. Essentially, I need help creating the reports mentioned above. Your questions may also help clarify my fuzzy description. Thanks for any help. Reply with questions. Israel From bdesth.quelquechose at free.quelquepart.fr Mon Jan 7 15:08:07 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 07 Jan 2008 21:08:07 +0100 Subject: TIOBE declares Python as programming language of 2007! In-Reply-To: <5uempsF1gt5cbU1@mid.uni-berlin.de> References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> <5uempsF1gt5cbU1@mid.uni-berlin.de> Message-ID: <478286a2$0$23176$426a74cc@news.free.fr> Diez B. Roggisch a ?crit : > Berco Beute schrieb: > >> Cool! We knew it would happen one day :) >> What could be the reason? Python 3? Jython 2.2? Java's loss of >> sexiness? > > > I'd say Java was never sexy, but dressed up in expensive lingerie by > marketing maniacs... +2 QOTW > Diez From richie at entrian.com Fri Jan 4 04:34:48 2008 From: richie at entrian.com (Richie Hindle) Date: Fri, 04 Jan 2008 09:34:48 +0000 Subject: urllib2 disable proxy In-Reply-To: <200801022303.53722.jimis@gmx.net> References: <200801022303.53722.jimis@gmx.net> Message-ID: Hi Dimitris, > I've been looking for a way to explicitly disable the use of proxies with > urllib2, no matter what the environment dictates. Unfortunately I can't find > a way [...] Would changing the environment work? Like this: >>> del os.environ['http_proxy'] >>> do_stuff_with_urllib2() -- Richie Hindle richie at entrian.com From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 22 04:23:32 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 22 Jan 2008 10:23:32 +0100 Subject: Trouble writing to database: RSS-reader In-Reply-To: <92b8934d-7b8b-4ca0-bcdd-1b4cd4853f1f@p69g2000hsa.googlegroups.com> References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> <4794e0f9$0$4429$426a74cc@news.free.fr> <739742b0-7d3d-4039-b793-ccefae4be721@1g2000hsl.googlegroups.com> <47951982$0$2681$426a74cc@news.free.fr> <92b8934d-7b8b-4ca0-bcdd-1b4cd4853f1f@p69g2000hsa.googlegroups.com> Message-ID: <4795b5c8$0$20146$426a74cc@news.free.fr> MRAB a ?crit : > On Jan 21, 9:15 pm, Bruno Desthuilliers > wrote: >> Arne a ?crit : (snip) >>> So, I shouldn't use this techinicke (probably wrong spelled) >> May I suggest "technic" ?-) > > That should be "technique"; just ask a Francophone! :-) My bad :( From nick at craig-wood.com Thu Jan 24 04:30:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 24 Jan 2008 03:30:05 -0600 Subject: A GUI framework for running simulations References: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com> Message-ID: Martin Manns wrote: > If you want to keep things simple, pygame could be an alternative for > visualizing simulations and setting parameters even though it does not > provide all these fancy widgets around. I'd second that. pygame will give you a window you can draw on which you can plot the result of your simulation. You can draw a few buttons (like play and stop) and detect clicks in them very easily. If you want loads of parameters then you'll either need to reach for a GUI toolkit or roll your own menuing system for pygame (which isn't that hard). -- Nick Craig-Wood -- http://www.craig-wood.com/nick From robin at NOSPAMreportlab.com Sun Jan 20 14:18:34 2008 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sun, 20 Jan 2008 19:18:34 +0000 Subject: bitmap problem In-Reply-To: <47935374.3010203@jessikat.plus.net> References: <47935374.3010203@jessikat.plus.net> Message-ID: <47939E8A.8080207@jessikat.plus.net> Robin Becker wrote: > I'm having trouble with defining a completely transparent bitmap > for use as a stipple in a canvas > > ....... after a bit of searching I find that stipples cannot be created with the tk image command; for non-standard stipples you need to use a file. -- Robin Becker From bronger at physik.rwth-aachen.de Tue Jan 15 16:01:59 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 15 Jan 2008 22:01:59 +0100 Subject: ElementTree and namespaces in the header only References: <2c769fe0-8add-4aa1-9657-b8ee5f76cb91@k39g2000hsf.googlegroups.com> Message-ID: <87sl0y7qgo.fsf@physik.rwth-aachen.de> Hall?chen! Fredrik Lundh writes: > Peter Bengtsson wrote: > >> root = Element('feed', xmlns='http://www.w3.org/2005/Atom') >> root.set('xmlns:se', NS_URL) >> entry = SubElement(root, 'entry') >> SubElement(root, 'title').text = 'Title' >> SubElement(entry, SEN('category')).text = 'Category' > >> But surely the xmlns:se attribute on the tag is >> excessive since the namespace (by the URI) is already defined in the >> tag. How do I set non-default namespace tags in elements >> without the automatic xmlns:se attribute repeated each time? > > ET 1.2's standard serializer doesn't take explicitly set namespaces > into account. If you want full control over namespace generation, > you have to do it yourself: > > http://effbot.org/zone/element-namespaces.htm#explicitly-setting-namespace-attributes > > ET 1.3 provides a default_namespace option for this specific case > (but you still have to use universal names for everything that > should go into the default namespace). I've worked with Saxon for a couple of years, and it tries to generate the "minimal" (well, sort of) XML file possible: It uses the prefixes given in the source XSLT file rather than generating something, and detects implicitly set namespaces, thus avoiding spitting them out again. Wouldn't this be an option for ET, too? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From paul.hankin at gmail.com Tue Jan 22 17:33:43 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 22 Jan 2008 14:33:43 -0800 (PST) Subject: difflib confusion References: Message-ID: <07ba2b13-31ff-4ba9-8f6f-2fd1e11dcd59@d70g2000hsb.googlegroups.com> On Jan 22, 6:57?pm, "krishnakant Mane" wrote: > hello all, > I have a bit of a confusing question. > firstly I wanted a library which can do an svn like diff with two files. > let's say I have file1 and file2 where file2 contains some thing which > file1 does not have. ?now if I do readlines() on both the files, I > have a list of all the lines. > I now want to do a diff and find out which word is added or deleted or changed. > and that too on which character, if not at least want to know the word > that has the change. > any ideas please? Have a look at difflib in the standard library. -- Paul Hankin From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 18:21:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 11 Jan 2008 23:21:48 -0000 Subject: python recursive function References: <01c6fa55-3836-4d92-aaf4-02fec7fa529c@l6g2000prm.googlegroups.com> Message-ID: <13ofugcsm9msa6f@corp.supernews.com> On Fri, 11 Jan 2008 06:30:04 -0600, Nick Craig-Wood wrote: > HYRY wrote: >> def bears (n): >> if n==42: >> return True ... >> return False > > Almost but you missed a case... Why are you people doing the OP's homework for him? And then DEBUGGING it as well? Haven't you got something better to do than to help create a new generation of incompetent, under-educated programmers? -- Steven From george.sakkis at gmail.com Tue Jan 15 16:45:59 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 15 Jan 2008 13:45:59 -0800 (PST) Subject: Perl Template Toolkit: Now in spicy new Python flavor References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> Message-ID: <13a75830-5416-4fe3-9460-018e1240e6e6@e32g2000prn.googlegroups.com> On Jan 15, 3:15 pm, Joshua Kugler wrote: > eef... at gmail.com wrote: > > I'd like to inform the Python community that the powerful and popular > > Template Toolkit system, previously available only in its original > > Perl implementation, is now also available in a beta Python > > implementation: > > >http://tt2.org/python/index.html > > > I created this port both as a fun programming project, and for use in > > environments where Perl is not available, for reasons technical, > > cultural, or otherwise. The extensive Perl test suites have also been > > ported, and most templates require no or very little modification. > > I must say...wow. That would have saved me some time and hassle about a > year ago, but of course, I wouldn't have fell in love with pure XML > templates either. :) As someone who has used Template Toolkit quite a bit, > I must say that is is quite cool. Congrats on a job well done! > > j How does it compare with other "mainstream" Python template engines such as Cheetah, Mako, etc. ? Unless I missed it, the documentation covers the Perl version only. George From mraborife at yahoo.com Mon Jan 7 08:57:17 2008 From: mraborife at yahoo.com (mpho raborife) Date: Mon, 7 Jan 2008 05:57:17 -0800 (PST) Subject: python syntax Message-ID: <606127.72912.qm@web45504.mail.sp1.yahoo.com> I need help with the following: os.system("gmmscore"+"-i" + Input + "-l" + List + "-t" + str(modeltype) + "-m" + str(mixture) + "-d" + str(dimension) + "-v" + str(vfloor) + "-n" + str(number) + "-r" + results) --------------------------------- Never miss a thing. Make Yahoo your homepage. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Sat Jan 19 02:02:42 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 19 Jan 2008 07:02:42 +0000 Subject: What is a shortcut to the Default home directory in Windows In-Reply-To: References: <1f85750e-a85a-4bb5-8f20-cbb5939f89a3@p69g2000hsa.googlegroups.com> <1fddf38d-e6a2-416f-a8f8-020560970ab5@z17g2000hsg.googlegroups.com> Message-ID: <4791A092.7090704@timgolden.me.uk> Christian Heimes wrote: > Mike Driscoll wrote: >> I personally use Tim Golden's excellent win32 API wrapper, the >> winshell script. You can find it here: >> >> http://timgolden.me.uk/python/winshell.html > > Yeah. Tim's winshell is fine but it's not using the official win32 api. Umm... Is it not? The only thing I'm aware of doing is retaining backwards compat. by using SHGetPathFromIDList on the SHGetSpecialFolderLocation because I was writing against Win9x at the time. Or are you saying something else? (Admit I haven't checked all the docs since I wrote it to see what's been "deprecated" this week). TJG From bernhard.merkle at googlemail.com Fri Jan 4 08:24:40 2008 From: bernhard.merkle at googlemail.com (Bernhard Merkle) Date: Fri, 4 Jan 2008 05:24:40 -0800 (PST) Subject: pydepend (checking dependencies like jdepend) ? References: <1969e240-9e80-4df1-b085-7956dfa4f7ae@t1g2000pra.googlegroups.com> Message-ID: <71a1c5ae-2051-44ff-998e-a342fa88ffab@e25g2000prg.googlegroups.com> On Jan 4, 1:57 pm, "Stefan Schukat" wrote: > Hi, > > try to look at py2exe. This module scans all dependencies to pack them > into one executable. my intention is to _know_ (or display or list or whatever) the dependencies. (see also my original posting). The aim is to control and have a view on modularization and e.g. avoid unnecessary bidirectional dependencies etc. does py2.exe display such information ? Berni. From fredrik at pythonware.com Thu Jan 3 03:44:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 09:44:30 +0100 Subject: shelve and nested dictionaries In-Reply-To: References: Message-ID: Matthew Schibler wrote: > I'm a newbie to Python, with some experience using perl (where I used > nested arrays and hashes extensively). I am building a script in > python for a MUD I play, and I want to use the shelve module to store > persistent information between script executions. The following code > does not work for me, > > import shelve, sys, os, string > db = shelve.open(os.path.abspath(os.path.dirname(sys.argv[0])) + '/' + > 'sandbox.dat', 'c') > db['JustSomeVariable'] = 'apple' > db['subdb'] = {} > db['subdb']['anotherdict'] = {} > db['subdb']['anotherdict']['bleh'] = 'hello world' > db.close() > > of course, that's just a working example but it illustrates the > problem i'm having. I think shelve objects act like dictionaries in a > way, at least they seem to have dictionary keys beneath them. the shelve module only tracks changes to the shelf itself (i.e. db[key]), not changes to to mutable objects stored in the shelve). to change a mutable object, you have to fetch it, modify it, and then write it back: value = db[key] ... update value ... db[key] = value in Python 2.3 and later, the shelve can help you with this, to some extent; from the help page: To avoid the problem with mutable entries, you may pass the keyword argument writeback=True in the call to shelve.open. When you use: d = shelve.open(filename, writeback=True) then d keeps a cache of all entries you access, and writes them all back to the persistent mapping when you call d.close(). This ensures that such usage as d[key].append(anitem) works as intended. However, using keyword argument writeback=True may consume vast amount of memory for the cache, and it may make d.close() very slow, if you access many of d's entries after opening it in this way: d has no way to check which of the entries you access are mutable and/or which ones you actually mutate, so it must cache, and write back at close, all of the entries that you access. You can call d.sync() to write back all the entries in the cache, and empty the cache (d.sync() also synchronizes the persistent dictionary on disk, if feasible). From paul.hankin at gmail.com Wed Jan 9 08:22:55 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 9 Jan 2008 05:22:55 -0800 (PST) Subject: flatten sequences in a dictionary References: Message-ID: On Jan 9, 1:16 pm, ajcpp... at gmail.com wrote: > Hi > > I wondering if someone could give me a pointer. I have a dictionary > with the following structure: > > testDict = dict(foo=((1,2,3),(1,4,3)), bar=((3,2,1),(9,8,7,)), > mumble=((1,2,3),)) > > I am trying to create a list of the the 3 element tuples using > itertools (just for a bit of fun). I'm trying this: > > list(itertools.chain(testDict.itervalues()) Close! Try: list(itertools.chain(*testDict.itervalues()) -- Paul Hankin From MartinRinehart at gmail.com Fri Jan 25 13:14:27 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Fri, 25 Jan 2008 10:14:27 -0800 (PST) Subject: Operator overloading Message-ID: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com> If it were my choice, the plus sign would do this: def itemadd( i1, i2 ): if ( type(i1) == str ) or ( type(i2) == str ): return str(i1) + str(i2) else: return i1 + i2 I'd like to redefine it so it works my way but operator overloading seems strictly confined to classes I create. Is there a way? Or do I just have to grump, "Even a kludge like Perl ..."? From kyosohma at gmail.com Wed Jan 2 09:25:07 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 2 Jan 2008 06:25:07 -0800 (PST) Subject: wxpython application ( problem ? ) References: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> Message-ID: <1d8d6374-fbd0-4292-a5d3-82e8791bd9a3@e6g2000prf.googlegroups.com> On Jan 2, 5:24 am, vedrandeko... at gmail.com wrote: > Hello, > > Here is sample of my simple script with wxpython and modules: > subprocess,threading, directpython....... > > Code sample: > > import wx > import wx.aui > app=wx.App() > frame=wx.Frame(None,title="New project") > > #There is also part with wx.aui > > frame.Show() > app.MainLoop() > > After a few minutes wx application does destroy. Any ides why? I highly recommend reading this wxPython wiki entry about using threads in wxPython: http://wiki.wxpython.org/LongRunningTasks I've found it quite helpful in my own programming. Mike From gagsl-py2 at yahoo.com.ar Mon Jan 21 14:38:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 17:38:10 -0200 Subject: Bug in __init__? References: <88580064-3590-471e-8036-a631dd5a38b4@i3g2000hsf.googlegroups.com> <50ed76e4-f865-4821-935f-310c96b0ecb9@e23g2000prf.googlegroups.com> Message-ID: En Mon, 21 Jan 2008 05:59:38 -0200, escribi?: > Is there no way of adding a possible warning message (that obviously > could be turned off) to warn users of possible problems linked to > using mutable types as parameters? > > Seems to me this could save users a few minutes/hours of headaches and > headscratching. (The biggest issue affecting new programmers these > days!) Most objects are mutable, such warning would happen so often that would become useless. The only immutable objects are numbers, strings, tuples, None and a few esoteric types; all other instances, including instances of all user defined classes, are mutable unless explicitely their attributes are read-only. -- Gabriel Genellina From pnemeth at fit.edu Wed Jan 30 12:16:08 2008 From: pnemeth at fit.edu (Peter Nemeth) Date: Wed, 30 Jan 2008 12:16:08 -0500 (EST) Subject: event handling Message-ID: Hi , I am working on a stellar spectral analysis pipeline in Python. My OS is Suse 10.0, and i use Python 2.5 . I have found difficulties with keyboard event handling. My code communicates with the user through an xterm window and shows graphs in a Gnuplot window. At a certain point i start an infinite loop in order to select multiple spectral regions by mouse-clicks over the Gnuplot graph. I would like to terminate this loop by a single keystroke, but i can not get it done. I use 'thread' to run this process in the background waiting for a keystroke. I don't want to use tkinter, widgets or pygame because those require a popup surface to work in and i already have the gnuplot window. I tried a C like getch() function, but that pauses the code waiting for key press instead of scanning the event queue. Is there any other means for general event handling in Python? Any help would be greatly appreciated. Sincerely, Peter From bignose+hates-spam at benfinney.id.au Thu Jan 31 08:40:01 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 01 Feb 2008 00:40:01 +1100 Subject: REALLY simple xml reader References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> Message-ID: <87tzkujeq6.fsf@benfinney.id.au> Steve Holden writes: > Diez B. Roggisch wrote: > > Ricardo Ar?oz schrieb: > >> doc = """ > >> > > > > It's not allowed to have a newline before the > > > > Put it on the line above, and things will work. > > > If you don't think that looks pretty enough just escape the first > newline in the string constant to have the parser ignore it: 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. > doc = """\ > This is fine. -- \ "True greatness is measured by how much freedom you give to | `\ others, not by how much you can coerce others to do what you | _o__) want." ?Larry Wall | Ben Finney From bsneddon at yahoo.com Wed Jan 9 15:28:39 2008 From: bsneddon at yahoo.com (bsneddon) Date: Wed, 9 Jan 2008 12:28:39 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> Message-ID: <49d262c8-492c-4f68-a145-27e84d3f7694@q39g2000hsf.googlegroups.com> On Jan 9, 3:12 pm, Tim Chase wrote: > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] > > > I'd like to remove the first and the last item as they are irrevalent, > > and convert it to the dict: > > {'tom':'boss','mike':'manager','paul':'employee'} > > > I tried this but it didn't work: > > > mydict={} > > for i in mylist[1:-1]: > > a=i.split('=') # this will disect each item of mylist into a 2-item > > list > > mydict[a[0]]=a[1] > > > and I got this: > > File "srch", line 19, in > > grab("a/tags1") > > File "srch", line 15, in grab > > mydict[mylist[0]]=mylist[1] > > IndexError: list index out of range > > This can be rewritten a little more safely like > > mydict = dict(pair.split('=',1) > for pair in mylist > if '=' in pair) > > Some of John Machin's caveats still apply: > (2) a[0] is empty or not what you expect (a person's name) > (3) a[1] is empty or not what you expect (a job title) > (consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = ' > boss') > (4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...] > > to which I'd add > > (5) what happens if you have more than one equals-sign in your > item? ("bob=robert=manager" or "bob=manager=big-cheese") > > #2 and #3 can be ameliorated a bit by > > import string > mydict = dict( > map(string.strip,pair.split('=',1)) > for pair in mylist > if '=' in pair) > > which at least whacks whitespace off either end of your keys and > values. #4 and #5 require a clearer definition of the problem. > > -tkc This seemed to work for me if you are using 2.4 or greater and like list comprehension. >>> dict([ tuple(a.split("=")) for a in mylist[1:-1]]) {'mike': 'manager', 'paul': 'employee', 'tom': 'boss'} should be faster than looping From benedict.verheyen at gmail.com Mon Jan 28 09:24:19 2008 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Mon, 28 Jan 2008 15:24:19 +0100 Subject: starting programs from python script on windows In-Reply-To: <479DB03A.9060801@timgolden.me.uk> References: <479DB03A.9060801@timgolden.me.uk> Message-ID: Tim Golden schreef: > OK. You've got a few misunderstandings in there. Nothing too major, > but it's worth sorting them out. > > 1) If you just want to kick off a program and that's it, say as part of > some kind of startup process, then you can just use the subprocess.call > convenience function. The business with stdout=PIPE is for communicating > with (usually console-based) programs which read and write to the > console. > > 2) The optional PYTHONPATH env var is used *internally* to Python as > one way of determining the path to search for Python modules *after > you've got Python running*. To run Python itself, you either need > to ensure the python.exe is already in the standard PATH env var, > or look for it in its conventional place: c:\python25\python.exe. > (Or make some other arrangement according to local convention etc.) > > There was a thread here recently about using Python as part of a > login script -- which is what I think you're doing here. I think, > because of the uncertain interaction between the Workstation in > effect when you're logging in as opposed to the Workstation which > owns the user's desktop, you might do better to have some technique > for adding to the [Startup] entry on the Start Menu if all you want > to do is to start programs. > > All that said, here's some sample code which just kicks off a > batch of programs. Note that I'm use os.startfile because that > will use ShellExecute which honours app path shortcuts, making > common things like MS Office apps much easier. You could > equivalently use subprocess.call but then you either have > to hardcode application paths or use FindExectable against an > arbitrary associated doc to find the right place. > > > import os > > programs = [ > "outlook.exe", > "cmd.exe", > "winword.exe", > "c:/temp/helpfile.pdf" > ] > for program in programs: > os.startfile (program) > > > > The last entry -- helpfile.pdf -- is to illustrate that os.startfile > can "start" documents as well as executable programs. > > TJG Tim, that seems to work ok. I will do some more testing but it looks good, Thanks! Benedict From paul.hankin at gmail.com Sat Jan 5 15:50:43 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 5 Jan 2008 12:50:43 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> Message-ID: <617182dc-3ca1-4cf5-b1ca-1779dd8d6550@i3g2000hsf.googlegroups.com> On Jan 5, 5:12?pm, Paul Hankin wrote: > On Jan 5, 4:14?pm, c... at mailinator.com wrote: > > > On Jan 5, 5:07 pm, c... at mailinator.com wrote: > > > > Hello, Paul and Arnaud. > > > While I think about your answers: do you think there is any way to > > > avoid shuffle? > > > It may take unnecessary long on a long list most of whose elements > > > have the property. > > You could generate a random shuffle of range(len(seq)) lazily, and use > that to iterate over your sequence. > > import random > import itertools > > def randxrange(n): > ? ? "Generate the numbers 0 to n-1 in a random order" > ? ? x = range(n) > ? ? for i in xrange(n): > ? ? ? ? r = random.randrange(n - i) > ? ? ? ? yield x[r] > ? ? ? ? x[r] = x[n - i - 1] > > def shuffled(seq): > ? ? "Generate the elements of seq in a random order" > ? ? return (seq[i] for i in randxrange(len(seq))) > > def pick_random(seq, prop): > ? ? return itertools.ifilter(prop, shuffled(seq)).next() At the risk of filling this thread with my posts, here's a much simplified and faster version of this code that uses no extra storage. import random def pick_random(seq, prop): L = len(seq) for i in xrange(L): r = random.randrange(L - i) if prop(seq[r]): return seq[r] seq[r] = seq[L - i - 1] -- Paul Hankin From fitzpatrick.dominic at googlemail.com Fri Jan 11 09:46:51 2008 From: fitzpatrick.dominic at googlemail.com (Fidtz) Date: Fri, 11 Jan 2008 06:46:51 -0800 (PST) Subject: python recursive function References: Message-ID: On 11 Jan, 08:30, Tom_chicollegeboy wrote: > here is what I have to do: > > This question involves a game with teddy bears. The game starts when I > give you some bears. You then start giving me back some bears, but you > must follow these rules (where n is the number of bears that you > have): > > If n is even, then you may give back exactly n/2 bears. (Hint: To test > whether n is even, use the expression ((n % 2) == 0).) > If n is divisible by 3 or 4, then you may multiply the last two digits > of n and give back this many bears. (By the way, the last digit of n > is n%10, and the next-to-last digit is (n%100)/10; this rule may not > be used if either of the last two digits is 0.) > > If n is divisible by 5, then you may give back exactly 42 bears. > The goal of the game for you is to end up with EXACTLY 42 bears. > > For example, suppose that you start with 250 bears. Then you could > make these moves: > > Start with 250 bears. > Since 250 is divisible by 5, you may return 42 of the bears, leaving > you with 208 bears. > Since 208 is even, you may return half of the bears, leaving you with > 104 bears. > Since 104 is even, you may return half of the bears, leaving you with > 52 bears. > Since 52 is divisible by 4, you may multiply the last two digits > (resulting in 10) and return these 10 bears. This leaves you with 42 > bears. > You have reached the goal! > Now, you are to write a program that, if I give you n bears, returns > true if it is at all possible for you to win the game. Your program > must use recursion to check all possible ways in which you can apply > the rules. > > Usage: > > >>> bears(42) > True > >>> bears(250) > True > >>> bears(50) > False > >>> bears(84) > True > >>> bears(41) > > False > > As you see my program must use recursion. > > I came up with this idea but I am not sure if its right or are there > any minor errors that I can easily fix: > > def bears (n): > if n==42: > return True > if n%5==0: > bears(n-42) > if n%2==0: > bears(n/2) > if n%3==0 or n%4==0: > one = (n%10) > two = ((n%100)/10) > if one!=0 and two!=0: > bears(n-(one*two)) > return False > > If a game hits 42 it should return True, otherwise False. If program > never hits 42 and return True, then it returns False. I figured out > base case, but I still get False when I enter bears(250). Any help > would be very appreciated! May != Must and Could != Should From paul.hankin at gmail.com Sat Jan 5 12:12:52 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 5 Jan 2008 09:12:52 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> Message-ID: On Jan 5, 4:14?pm, c... at mailinator.com wrote: > On Jan 5, 5:07 pm, c... at mailinator.com wrote: > > > Hello, Paul and Arnaud. > > While I think about your answers: do you think there is any way to > > avoid shuffle? > > It may take unnecessary long on a long list most of whose elements > > have the property. You could generate a random shuffle of range(len(seq)) lazily, and use that to iterate over your sequence. import random import itertools def randxrange(n): "Generate the numbers 0 to n-1 in a random order" x = range(n) for i in xrange(n): r = random.randrange(n - i) yield x[r] x[r] = x[n - i - 1] def shuffled(seq): "Generate the elements of seq in a random order" return (seq[i] for i in randxrange(len(seq))) def pick_random(seq, prop): return itertools.ifilter(prop, shuffled(seq)).next() -- Paul Hankin From sjmachin at lexicon.net Sat Jan 26 01:41:32 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 22:41:32 -0800 (PST) Subject: Doesn't know what it wants References: Message-ID: On Jan 26, 4:20 pm, Tim Rau wrote: > Traceback (most recent call last): > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > \sandbox.py", line 242, in > player = ship() > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > \sandbox.py", line 121, in __init__ > self.phyInit() > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > \sandbox.py", line 147, in phyInit > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) > ArgumentError: argument 4: : expected > vec2d instance instead of vec2d > > As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't > seems like it doesn't know what it wants, but I thought only teenagers > did that, no programming languages. It possibly means that it is expecting an instance of a class whose name is "vec2d" but you have given it an instance of some *other* class whose name just happens to be "vec2d". > clearly, Im missing something. Yes, some information: 1. what is vec2d, class or function? 2. what do you believe vec2d((0, 0)) should return? 3. what is this belief based on? 4. what has it actually returned this time? 5. what do you believe that cp.cpMomentForCircle expects as argument 4? 6. what is this belief based on? The ArgumentError exception is raised by ctypes "when a foreign function call cannot convert one of the passed arguments". Based on guessin'n'googlin' the cp thing is a set of Python bindings to a library written in C++ ... have you considered asking the author of the bindings? From steve at REMOVE-THIS-cybersource.com.au Wed Jan 23 16:48:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 21:48:19 -0000 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> Message-ID: <13pfdh31k2bp8eb@corp.supernews.com> On Wed, 23 Jan 2008 10:39:25 -0800, George Sakkis wrote: > On Jan 23, 4:37 am, Steven D'Aprano > wrote: >> On Tue, 22 Jan 2008 23:33:00 -0800, George Sakkis wrote: >> > As I mentioned already, I consider the seeking of the most efficient >> > solution a legitimate question, regardless of whether a "dumb" >> > solution is fast enough for an application. Call it a "don't be >> > sloppy" principle if you wish. >> >> Sure, by why do you limit "efficient" and "don't be sloppy" to mean >> "write the fastest executing code you can, regardless of every other >> trade-off"? > > I explicitly didn't limit sloppiness to inefficiency and mentioned it's > a tradeoff: Of course you did, and I was being sloppy. The "you" was meant more as a generic you than you yourself. Sorry for the confusion. As for your other points, I think we're actually very much in agreement, except for your tolerance of random posters asking what I believe is an incoherent question: "what's the fastest way to do ...?". It seems to me you're willing to give them the benefit of the doubt that they've done their profiling and considered their trade-offs, or at the very worst are asking from purely intellectual curiosity. Call me cynical if you like, but I think that in the absence of any direct evidence supporting those things, the most likely possibility is the opposite. -- Steven From stefan.behnel-n05pAM at web.de Wed Jan 23 06:03:27 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 12:03:27 +0100 Subject: Problem with processing XML In-Reply-To: References: <13pbudgks88rcf3@corp.supernews.com> Message-ID: <47971EFF.8070701@web.de> Hi, Paul Boddie wrote: > People will, of course, tell you that you shouldn't use a DOM for > anything and that the "consensus" is to use ElementTree or lxml (see > above), but I can't help feeling that this has a damaging effect on > the XML situation for Python: some newcomers would actually benefit > from the traditional APIs, may already be familiar with them from > other contexts, and may consider Python lacking if the support for > them is in apparent decay. It requires a degree of motivation to > actually attempt to maintain software providing such APIs (which was > my solution to the problem), but if someone isn't totally bound to > Python then they might easily start looking at other languages and > tools in order to get the job done. I had a discussion with Java people lately and they were all for Ruby, Groovy and similar languages, "because they have curly braces and are easy to learn when you know Java". My take on that is: Python is easy to learn, full-stop. It's the same for DOM: when you know DOM from (usually) the Java world, having a DOM-API in Python keeps you from having to learn too many new things. But when you get your nose kicked into ElementTree, having to learn new things will actually help you in understanding that what you knew before did not support your way of thinking. http://www.python.org/about/success/esr/ So, there is a learning curve, but it's much shorter than what you already invested to learn 'the wrong thing'. It's what people on this list tend to call their "unlearning curve". Stefan From martin at v.loewis.de Wed Jan 16 14:54:27 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 16 Jan 2008 20:54:27 +0100 Subject: Creating unique combinations from lists In-Reply-To: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> Message-ID: <478E60F3.5000509@v.loewis.de> > I could do nested for ... in loops, but was looking for a Pythonic way > to do this. Ideas? I find nested for loops very Pythonic. Explicit is better than implicit, and simple is better than complex. Regards, Martin From jarausch at skynet.be Tue Jan 15 14:06:53 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 15 Jan 2008 20:06:53 +0100 Subject: super, decorators and gettattribute In-Reply-To: <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> Message-ID: <478D044D.1040406@skynet.be> Michele Simionato wrote: > I really need to publish this one day or another, since these > questions > about super keeps coming out: > > http://www.phyast.pitt.edu/~micheles/python/super.html Unfortunately the links [2], [3] and [4] are not given, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From shore.cloud at gmail.com Sun Jan 27 11:21:20 2008 From: shore.cloud at gmail.com (Mr Shore) Date: Mon, 28 Jan 2008 00:21:20 +0800 Subject: is it a bug? Message-ID: import threading import time class timer(threading.Thread): def __init__(self,no,interval): threading.Thread.__init__(self) self.no=no self.interval=interval def run(self): while True: print 'Thread Object (%d), Time:%s'%(self.no,time.ctime()) time.sleep(self.interval) def test(): threadone=timer(1,1) threadtwo=timer(2,3) threadone.start() threadtwo.start() print 'main thread' if __name__=='__main__': test() when I run the above programme,an error comes out but ignored Exception exceptions.AttributeError: '_shutdown' in ignored -------------- next part -------------- An HTML attachment was scrubbed... URL: From cthedot at gmail.com Tue Jan 8 15:24:46 2008 From: cthedot at gmail.com (Christof Hoeke) Date: Tue, 08 Jan 2008 21:24:46 +0100 Subject: Javascript parser Message-ID: hello, is there any Javascript (not just JSON) parser for Python? I saw http://wwwsearch.sourceforge.net/python-spidermonkey/ which seems to be from 2003 and unmaintained and seems to be quite complicated to get to work anyway :( Using Rhino from Jython is not really an option as I'd like to work in (C)Python only. thanks for any hint Christof From hanke at brailcom.org Wed Jan 23 08:30:22 2008 From: hanke at brailcom.org (Hynek Hanke) Date: Wed, 23 Jan 2008 14:30:22 +0100 Subject: pythonic backtrace with gdb Message-ID: <4797416E.3020005@brailcom.org> Hello, please, I'm trying to obtain a pythonic backtrace via gdb to be able to debug deadlock situations in a multi-threaded program by attaching to the running process. I'm running the program under python2.4-dbg, When I try to load the .gdbinit script obtained at http://wiki.python.org/moin/DebuggingWithGdb , gdb crashes however with the following error (full session listing): (gdb) attach 10753 Attaching to program: /usr/bin/python, process 10753 warning: no loadable sections found in added symbol-file system-supplied DSO at 0x7fff575fd000 0x00002b33537177fb in ?? () from /lib64/ld-linux-x86-64.so.2 (gdb) pystack /tmp/buildd/gdb-6.6.dfsg.90.20070912/gdb/regcache.c:164: internal-error: register_type: Assertion `regnum >= 0 && regnum < descr->nr_cooked_registers' failed. A problem internal to GDB has been detected, further debugging may prove unreliable. Quit this debugging session? (y or n) [answered Y; input not from terminal] /tmp/buildd/gdb-6.6.dfsg.90.20070912/gdb/regcache.c:164: internal-error: register_type: Assertion `regnum >= 0 && regnum < descr->nr_cooked_registers' failed. A problem internal to GDB has been detected, further debugging may prove unreliable. Create a core file of GDB? (y or n) [answered Y; input not from terminal] Ne?sp??n? ukon?en (SIGABRT) I've also tried to use the backtrace script here http://mashebali.com/?Python_GDB_macros:The_Macros:Backtrace But I get a different error: (gdb) pbt Invalid type combination in ordering comparison. I'm using GDB version 6.6.90. Could you please suggest what can I do to be able to get the backtrace? Thank you, Hynek Hanke From mr.cerutti at gmail.com Fri Jan 4 15:47:11 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 4 Jan 2008 15:47:11 -0500 Subject: fastest method to choose a random element In-Reply-To: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> Message-ID: <51302a8c0801041247jc9a6c8ej10e346b8357bacdc@mail.gmail.com> On Jan 4, 2008 2:55 PM, wrote: > Hello, > This is a question for the best method (in terms of performance > only) to choose a random element from a list among those that satisfy > a certain property. I would automatically use random.choice(filter(pred_func, a_list)). You just have to catch the possible IndexError. This is the setting: I need to pick from a list a random element > that satisfies a given property. All or none of the elements may have > the property. Most of the time, many of the elements will satisfy the > property, and the property is a bit expensive to evaluate. Chance of > having the property are uniform among elements. > > A simple approach is: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > > Returns None if no element has the property > ''' > random.shuffle(a_list) > for i in a_list: > if property(i): return i I'm pretty sure you don't want to use a destructive random_pick function. You'll have to shuffle a copy instead to avoid that problem. > > but that requires to shuffle the list every time. > > A second approach, that works if we know that at least one element of > the list has the property, is: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > > Loops forever if no element has the property > ''' > while 1: > i=random.choice(a_list) > if property(i): return i > > which is more efficient (on average) if many elements of the list have > the property and less efficient if only few elements of the list has > the property (and goes crazy if no element has the property) That's awful. Here's another linear time idea, returning the nearest element that satisfies the predicate. offset = random.randrange(len(a_list)) for n in xrange(len(a_list)): ix = (offset + n) % len(a_list) if predicate(a_list[ix]): return a_list[ix] raise ValueError('no element has the property') The possible problem is that large strings of elements in a row that don't match the predicate greatly increase the odds of getting the following element that *does* match the predicate. Worst case is two predicate matched elements in a row, surrounded by a bunch of non-matched elements. > Yet another one: > > import random > def random_pick(a_list,property): > '''Returns a random element from a list that has the property > ''' > b_list=[x for x in a_list if property(x)] > try: > return random.choice(b_list) > finally: return None > > but this one checks the property on all the elements, which is no > good. Is it really expensive to check the property? That would mitigate against the filter solution and for the other one I posted. This seems to be a case of trying to solve a data problem functionally. It'd be better to store your data differently if this will be a frequent operation and you simply can't afford to call the predicate on all the elements. Incidentally, try not to shadow builtin names like 'property'. -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Thu Jan 3 18:14:29 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 3 Jan 2008 15:14:29 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: Message-ID: <066ade7e-fd6f-45e0-878a-3eacd90efdde@u10g2000prn.googlegroups.com> On Jan 4, 9:56 am, "Reedick, Andrew" wrote: > As a Perl monkey in the process of learning Python, I just stepped on > the "'1' (string) is not the same as 1 (integer) in regards to keys for > dictionaries/hashes" landmine. Congratulations. You have just stepped off the "'1' (string) is the same as 1 (integer) in regards to several purposes" landmine. Welcome to the awk-free world :-) > Is there a good way to ensure that > numbers represented as strings or ints do not get mixed up as keys? > > Example of the problem: > >>> h2 = { 1 : ''} > >>> print h2.has_key(1) > True > >>> print h2.has_key('1') > False > > The problem occurred because a method used to generate keys was > returning a string instead of a number without an explicit conversion > taking place. And since I was using hash.get(i, default_value) to avoid > having to pair every key lookup with a hash.has_key(), no exception was > thrown when the key wasn't found. has_key is a has_been ... use "key in dict" instead of "dict.has_key(key)" > It's fugly to wrap every key reference in str(), ex: > foo[str(some_func(i))]. Fugliness is in the eye of the beholder. From python.list at tim.thechases.com Mon Jan 28 11:23:14 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 28 Jan 2008 10:23:14 -0600 Subject: Encryption Recommendation In-Reply-To: <606aj3F1pa0tfU1@mid.uni-berlin.de> References: <6b40b773-8554-4e9c-838f-e6934212d16e@n20g2000hsh.googlegroups.com> <606aj3F1pa0tfU1@mid.uni-berlin.de> Message-ID: <479E0172.6030903@tim.thechases.com> > Usually, one doesn't store clear-text passwords. Instead, use a > hash-algorithm like md5 or crypt (the former is in the standard lib, don't > know of the other out of my head) and hash the password, and store that > hash. Python offers md5, and SHA modules built-in. (yay, python!) http://docs.python.org/lib/module-md5.html http://docs.python.org/lib/module-sha.html It does also offer access to the crypt() function on Unix-like OS'es but not Win32: http://docs.python.org/lib/module-crypt.html but it's based on DES which is no longer considered particularly secure. From what I've seen, even MD5 is being phased out in favor of SHA. > If a user enters the password, use the same algorithm, and compare the > resulting hashes with the stored one. Generally one adds a "salt" to the mix, a random piece of data that's stored with the password, so that if two users use the same password, the salt makes them the appear like different passwords: import sha import string from random import choice SALT_CHAR_COUNT = 5 salt_chars = string.letters + string.numbers + string.punctuation def is_valid(username, password): correct_hash, salt = get_hash_and_salt(username) test_hash = sha.new(salt + password).hexdigest() return test_hash == correct_hash def set_password(username, password): salt = ''.join([random.choice(salt_chars) for _ in xrange(SALT_CHAR_COUNT)]) hash = sha.new(salt + password) save_user(username, salt, hash) Implementing get_hash_and_salt() and save_user() (and perhaps tweaking the desired set of salt_chars) are left as an exercise to the reader, using whatever persistent storage mechanism suits. -tkc From asmodai at in-nomine.org Wed Jan 2 07:44:08 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 2 Jan 2008 13:44:08 +0100 Subject: dbus-python for windows In-Reply-To: <194e7fee-728a-48eb-9f51-1e272ecca838@j20g2000hsi.googlegroups.com> References: <194e7fee-728a-48eb-9f51-1e272ecca838@j20g2000hsi.googlegroups.com> Message-ID: <20080102124408.GD67953@nexus.in-nomine.org> -On [20080102 13:41], est (electronixtar at gmail.com) wrote: >I am trying to port Scribes to Windows, but I could not find a package >named dbus-python for windows. There is a windbus sourceforge.net/projects/windbus/> but it not for Python, so how could >I install dbus module for Windows Python 2.5 ? Well, I assume using the source from http://dbus.freedesktop.org/releases/dbus-python/ and trying to build it fails on Windows? (I readily admit I have little clue how much of dbus is platform-specific.) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Resolve to find thyself; and to know that he who finds himself, loses his misery... From gagsl-py2 at yahoo.com.ar Wed Jan 30 21:22:37 2008 From: gagsl-py2 at yahoo.com.ar (gagsl-py2 at yahoo.com.ar) Date: Wed, 30 Jan 2008 23:22:37 -0300 (ART) Subject: Python UML Metamodel In-Reply-To: <754577.12877.qm@web90503.mail.mud.yahoo.com> Message-ID: <40690.87155.qm@web32813.mail.mud.yahoo.com> --- sccs cscs escribi?: > Gabriel Genellina a ?crit : > En Tue, 29 Jan 2008 21:25:26 -0200, sccs cscs > escribi?: > > > I find an OPEN SOURCE tool > (http://bouml.free.fr/) that Recently > > generates Python code from UML model. > > Does it keep the model synchronized when you modify > the Python code? > > =>No, not for the moment because the Python code > generator is brand new, but the tool's author and > i are specifying the reverse tool for a next > version. I do not have found another Open Source > Tool that generates Python code from UML better like > that. Ok, that's important. If the model cannot reflect changes in the code it becomes less and less useful. > > I like to model the Python language metamodel > himself, with it, e.g the > > model of the language: I need that to better > understand the language > > constraint of the language. > > [...] > > -a class "class" has 0..n attributes and 0..n > method > > Just attributes. Methods are created on-the-fly when > the corresponding > function attribute is retrieved from the instance. > And remember that instances are not restricted to > what their class define. > You can add or remove any attribute (even methods!) > to any instance of a > user-defined class at any time. (This doesn't apply > to most builtin types, > but *does* apply if you inherit from it) > > > =>You're Right but I will also model that dynamic > aspect . However i think it is possible and the > relevant to make a static metamodel of Python, as > if there was no possibility of changing dynamic an > instance. But Python *is* a dynamic language. You have to capture that into the model somehow. > A lot of person do not understand nothing > to Python on many aspects, because there is no > graphical representation of the relation of concepts > : may a module have more than on class definition ? > a mix of class and global fonction? etc... A graphical representation may be useful, but it must be acurate too - else people may incorrectly deduce that something can't be done because it's not expressed in the graph. > > Does anyone know a document that describes it > already, because I think > > it is complicated to find this information in the > documentation of > > Python. > > See section 2 "Data Model" and section 3 "Execution > Model" in the Python > Language Reference http://docs.python.org/ref/ > > => > Thank you, it's pretty standard but somewhat > indigestible. However, by studying line by line, I > would have to be filled into a UML model Yes, sure, it's hard to follow. As the subtitle says, it's "for language lawyers" :) > > - a class "method" can contains nested "method", > but what is the way to > > get a list of internal methods, without use ? Can > i just write: > > "myNestedMethodList = method.nestedMethodList" > > Are you talking about nested functions? > => Yes > > You can't enumerate them from outside the container > function: Python is a > dynamic language, those inner functions are created > when the def statement > is *executed*. If you have an if statement around > the def, the function > may not even exist. > > => OK, it is diffcult to model: but possible: for > example, by using a composition (a method may have > 0..n inner function). The dynamic aspect may be > described into a UML note or constraints for example Anyway it doesn't look right. Inner functions are not attributes of the enclosing one, like local variables are not attributes of the enclosing function. -- Gabriel Genellina Los referentes m?s importantes en compra/ venta de autos se juntaron: Demotores y Yahoo! Ahora comprar o vender tu auto es m?s f?cil. Vist? ar.autos.yahoo.com/ From jarausch at skynet.be Tue Jan 15 14:00:36 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 15 Jan 2008 20:00:36 +0100 Subject: Benchmark [was Re: common problem - elegant solution sought] In-Reply-To: <7xbq7ngdge.fsf@ruckus.brouhaha.com> References: <5v3gg1F1kkla5U1@mid.dfncis.de> <478ccc9e$0$29264$ba620e4c@news.skynet.be> <7xbq7ngdge.fsf@ruckus.brouhaha.com> Message-ID: <478d02d4$0$22319$ba620e4c@news.skynet.be> Paul Rubin wrote: > Helmut Jarausch writes: >> def del_by_key(L,key) : >> for pos, (k,d) in enumerate(L): >> if k == key : >> del L[pos] >> break > > This looks very dangerous, mutating L while iterating over it. No, as Bruno Desthuilliers has pointed out, because one breaks out of the loop immediately. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From duncan.booth at invalid.invalid Wed Jan 9 10:53:49 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jan 2008 15:53:49 GMT Subject: stupid/style/list question References: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Duncan Booth: >> I tried to measure this with timeit, and it looks like the 'del' is >> actually quite a bit faster (which I find suprising). > > Yes, it was usually faster in my benchmarks too. Something similar is > true for dicts too. I think such timings are influenced a lot by the > garbage collector. > That may come into it, but I made the obvious change I mentioned (to avoid dereferncing a pointer every time through the loop) and got about an 8% speed-up on my test. I don't think that explains all of the speed difference though, so the garbage collector may come into it too: I'll see if I can do some more experimentation before submitting a patch. From kay.schluehr at gmx.net Sun Jan 6 02:20:55 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 5 Jan 2008 23:20:55 -0800 (PST) Subject: How a smart editor could make "Postfix type declarations PEP3117" in Python3000 more readable References: <4469647b-6eb1-498d-a9b4-ca7ce5870b56@p69g2000hsa.googlegroups.com> <477F1EAF.4070105@animats.com> Message-ID: <01c42c8e-baf2-43eb-9e87-ee4e5c0e34d6@v67g2000hse.googlegroups.com> On Jan 5, 7:07 am, John Nagle wrote: > Python doesn't really need explicit type declarations. > They're not needed for correctness, and they're not needed for > performance. Take a look at Shed Skin, which is able to hard-compile Python > using type inference without explicit type declarations. ShedSkin is not Python. From rridge at caffeine.csclub.uwaterloo.ca Sun Jan 27 10:04:06 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Sun, 27 Jan 2008 10:04:06 -0500 Subject: Using a dict as if it were a module namespace References: <13podkpqqvef674@corp.supernews.com> Message-ID: Steven D'Aprano writes: >(1) Import the test and grab the values needed from it: > > setup = """from __main__ import myfunc, test >x, y = test['x'], test['y']""" > > >I don't like this one. It doesn't seem very elegant to me, and it gets >unwieldy as the complexity increases. Every item I need from test has to >be named twice, violating the principle Don't Repeat Yourself. If the >tests change, the setup string has to be explicitly changed also. I think this is the way to go as it follows the principle of "say what you mean." You can however simplify it, and repeat yourself less, by using the extended call syntax: expr = "myfunc(**test)" setup = """from __main__ import myfunc, test""" ... >I don't like this one. It looks hackish, and I worry about conflicts and >side-effects. If it works (and I haven't tested it) it relies on an >implementation detail of timeit.Timer.__init__, namely the line >"exec code in globals(), ns". Worst of all, it pollutes or even mangles >the global namespace of the calling code, not the code being tested. It wouldn't work because the timeit module's "globals" are different from the __main__ module's globals. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From castironpi at gmail.com Sat Jan 12 09:04:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 06:04:19 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> Message-ID: On Jan 11, 5:26 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > 1. Put a single thread in charge of the list, and communicate with it > by message passing through Queues. To get X out of the list, you'd > send the mutator thread a message asking for removal. The mutator > thread would loop reading and processing messages from the queue, > blocking when no requests are pending. This is sort of the preferred > Python style and is pretty simple to get correct, but if there are > many such objects you can end up with more threads than you really > want. I've heard this called 'fire and forget'. You can insure that mutations are honored one-at-a-time and in the order received. How do you make a -read- operation; wait for queued mutations, that is lock for a turn on the queue? Can you optionally read whatever the state is, regardless of what's happened in the meantime? Thing is, one thread needs its -own- preceding operations completed before a reading operation. From mario at ruggier.org Wed Jan 2 03:45:15 2008 From: mario at ruggier.org (mario) Date: Wed, 2 Jan 2008 00:45:15 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> Message-ID: <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> On Jan 2, 9:30 am, "Martin v. L?wis" wrote: > Use "mbcs" in the second call, not "mcbs". Ooops, sorry about that, when i switched to test it in the interpreter I mistyped "mbcs" with "mcbs". But remark I did it consistently ;-) I.e. it was still teh same encoding, even if maybe non-existant.. ? If I try again using "mbcs" consistently, I still get the same error: $ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> unicode('', 'mbcs') u'' >>> unicode('', 'mbcs').encode('mbcs') Traceback (most recent call last): File "", line 1, in LookupError: unknown encoding: mbcs >>> mario From rridge at caffeine.csclub.uwaterloo.ca Wed Jan 23 09:57:36 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 23 Jan 2008 09:57:36 -0500 Subject: subprocess and & (ampersand) References: Message-ID: Tim Golden wrote: >but this doesn't: > > >"c:\Program Files\Mozilla Firefox\firefox.exe" "%*" > > > >import subprocess > >cmd = [ >r"c:\temp\firefox.bat", >"http://local.goodtoread.org/search?word=tim&cached=0" >] >subprocess.Popen (cmd) > > You need to use double quotes both in the .BAT file and in the string you pass to subprocess.Popen(). Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From mail at microcorp.co.za Wed Jan 16 02:10:36 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 16 Jan 2008 09:10:36 +0200 Subject: Interesting Thread Gotcha References: Message-ID: <00c701c85810$95d8e600$03000080@hendrik> "Dan" wrote: > >>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) > > Needs to be > >>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) > > Commas are important! > > -Dan Absolutely! - well spotted! As the first correct respondent, you win the freedom to spend a week in Naboomspruit at your own expense. It would have been nice, however, to have gotten something like: TypeError - This routine needs a tuple. instead of the silent in line calling of the routine in question, while failing actually to start a new thread. It seems to act no different from plain old: kbd_driver (port_q,kbd_q) Is it worth the trouble of learning how to submit a bug report? - Hendrik From arkanes at gmail.com Thu Jan 24 12:26:59 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 24 Jan 2008 11:26:59 -0600 Subject: translating Python to Assembler In-Reply-To: <5vroakF1o4jkvU1@mid.individual.net> References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <5vroakF1o4jkvU1@mid.individual.net> Message-ID: <4866bea60801240926t3db87f4fsaff6f725064fa5ab@mail.gmail.com> On Jan 24, 2008 9:14 AM, Bjoern Schliessmann wrote: > Tim Roberts wrote: > > Bjoern Schliessmann > > >> So, how do processors execute Python scripts? :) > > > > Is that a rhetorical question? > > A little bit. > > > Grant is quite correct; Python scripts (in the canonical CPython) > > are NOT compiled into assembly language. Scripts are compiled to > > an intermediate language. Processors execute Python scripts when > > the interpreter, written in a high-level language and compiled to > > assembly, interprets the intermediate language created by the > > Python "compiler". > > So in the end, the program defined in the Python script _is_ > compiled to the CPU's language. But never mind, it depends on how > you define "compile" in the end. > This is true if and only if you would agree that Powerpoint presentations, Word documents, and PNG images are likewise compiled to machine code. From arnodel at googlemail.com Wed Jan 30 06:57:50 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 30 Jan 2008 03:57:50 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> Message-ID: <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> On Jan 29, 10:59?pm, Paul Hankin wrote: > If I really had to modify it in place (and the condition wasn't really > x == 99), how about: > bad_indices = [i for i, x in enumerate(a) if x == 99] > for bad_index in reversed(bad_indices): > ? ? del a[bad_index] Or one could use the trick of counting from the right (untested): n = len(a) for i, x in enumerate(a): if x == 99: del a[i-n] -- Arnaud From pofuk at mzm.hr Wed Jan 23 10:25:38 2008 From: pofuk at mzm.hr (SMALLp) Date: Wed, 23 Jan 2008 16:25:38 +0100 Subject: Python printing! Message-ID: Hy. How to use printer in python. I goggled little i I found only some win32 package which doesn't look processing for cross platform application. (I'm using USB printer and I tried to f=open("dev/...") usb port but i couldn't fond where printer is! Tnx! SMALLp From pupeno at pupeno.com Sat Jan 26 09:10:03 2008 From: pupeno at pupeno.com (=?UTF-8?B?Si4gUGFibG8gRmVybsOhbmRleg==?=) Date: Sat, 26 Jan 2008 14:10:03 +0000 Subject: Replacing a package with another Message-ID: Hello, Is it possible to replace one package with another at runtime, that is, I have package a.blah which I want instead of b.blah, so I can "inject" functionality in an existing package? Thanks. -- J. Pablo Fern?ndez (http://pupeno.com) From dg.google.groups at thesamovar.net Mon Jan 14 13:47:42 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Mon, 14 Jan 2008 10:47:42 -0800 (PST) Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> <1ec2c39c-ce88-4e4b-bab8-7bfcee8c6d10@s13g2000prd.googlegroups.com> Message-ID: Hi R?diger, Thanks for your message. I liked your approach and I've been trying something along exactly these sorts of lines, but I have a few problems and queries. The first problem is that the id of the frame object can be re-used, so for example this code (where I haven't defined InstanceTracker and getInstances, but they are very closely based on the ideas in your message): class A(InstanceTracker): gval = 0 def __init__(self): self.value = A.gval # each time you make a new object, give A.gval += 1 # it a value one larger def __repr__(self): return str(self.value) def f2(): a = A() # objects 0 and 2 return getInstances(A) def f3(): a = A() # object 1 return f2() inst2 = f2() inst3 = f3() print inst2 print inst3 The output is: [0] [0, 2] The A-variable with value 0 is not being garbage collected because it's saved in the variable inst2, but it's also being returned by the second call to getInstances because the frame of f2 is the same each time (which makes sense, but may be implementation specific?). The same problem doesn't exist when you use the stack searching method because from f2's point of view, the only bound instance of A is the one in that particular call of f2. If you had at the end instead of the inst2, inst3 stuff: print f2() print f3() The output is: [0] [2] Again, I guess this because A with value 0 is being garbage collected between print f2() and print f3(), but again I think this is implementation specific? You don't have a guarantee that this object will be garbage collected straight away do you? So my concern here is that this approach is actually less safe than the stack based approach because it depends on implementation specific details in a non-straightforward way. That said, I very much like the fact that this approach works if I write: a = [A()] a = [[A()]] etc. To achieve the same thing with the stack based approach you have to search through all containers to (perhaps arbitrary) depth. I also have another problem which is that I have a function decorator which returns a callable object (a class instance not a function). Unfortunately, the frame in which the callable object is created is the frame of the decorator, not the place where the definition is. I've written something to get round this, but it seems like a bit of a hack. Can anyone suggest an approach that combines the best of both worlds, the instance tracking approach and the stack searching approach? Or do I need to just make a tradeoff here? Thanks again for all your help everyone, Dan Goodman From nma at 12000.org Mon Jan 21 21:36:34 2008 From: nma at 12000.org (Nasser Abbasi) Date: Mon, 21 Jan 2008 18:36:34 -0800 Subject: newbie question: On installation of additional packages to Python Message-ID: hello; I have not used Python before directly, but I am interested in trying it. I've read some good things about it. ( I am mainly interested in trying it for some scientific applications and simulation.) I am running on windowz. I have downloaded and installed 2.5.1 Python. my question is on installing additional packages. What is the easiest way to do that? I read about python 'eggs' (like jar files for Java), and easyInstall script, and such. Is there some automated way to install Python packages? a manual/document I could read that describes step by step how to do that? Browsing the documentation, there does not seem to be something specific there (other than saying download this tar file and install it). I like how one can install additional packages in 'R' . In 'R' one can do all that from the user interface for R by a pull-down menu, then one selects a mirror site, then one can see all the packages available, then select the package to download, and the rest is done automatically. (The package is downloaded, installed, etc...) Anything like that exists for Python? Btw, I have VM running on windowz, and so I can run Python on Ubuntu linux on that VM, would be easier to install additional Python packages there, may be using that nice GUI based Ubuntu package manager to do that? thanks, Nasser From lasses_weil at klapptsowieso.net Mon Jan 21 12:59:05 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 21 Jan 2008 18:59:05 +0100 Subject: is it possible to set namespace to an object. In-Reply-To: <27529efd-b8d8-4a8e-b72d-379a607366b7@i7g2000prf.googlegroups.com> References: <27529efd-b8d8-4a8e-b72d-379a607366b7@i7g2000prf.googlegroups.com> Message-ID: <4794dd6c$0$27198$9b4e6d93@newsspool1.arcor-online.net> glomde wrote: > Hi, > > is it somehow possible to set the current namespace so that is in an > object. > [snip] > set namespace testObj > Name = "Test" > > Name would set testObj.Name to "Test". > > [snip] > > Is the above possible? > Don't know, sorry. But let me ask you this: Why do you want to do this? Maybe there is another way to solve the problem that you want to solve. /W From kirby.urner at gmail.com Thu Jan 10 13:38:30 2008 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: Thu, 10 Jan 2008 10:38:30 -0800 (PST) Subject: What is "lambda x=x : ... " ? References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com> Message-ID: You're talking about syntax from the bad old days when the scope rules were different. If not too archeological for your tastes, download and boot a 1.5 and see what happens. Less empirically, here're some key references: http://www.python.org/doc/2.2.3/whatsnew/node9.html http://www.python.org/dev/peps/pep-0227/ The change came in 2.2 with from __future__ support in 2.1. Kirby 4D On Jan 10, 11:25 am, "zsl... at gmail.com" wrote: > I'm reading this page:http://www.ps.uni-sb.de/~duchier/python/continuations.html > and I've found a strange usage of lambda: > > #################### > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ################### > > What does "y=y" and "c=c" mean in the lambda function? > I thought it bounds the outer variables, so I experimented a little > bit: > > ################# > x = 3 > y = lambda x=x : x+10 > > print y(2) > ################## > > It prints 12, so it doesn't bind the variable in the outer scope. From bakermi at cbc.ca Fri Jan 18 15:40:52 2008 From: bakermi at cbc.ca (bakermi at cbc.ca) Date: Fri, 18 Jan 2008 12:40:52 -0800 (PST) Subject: IRC bot threading dilemma Message-ID: Hello, I have coded an IRC bot in Python. Each inbound packet is parsed, and once the bot decides whether it is a command directed at the bot or not, it will either discard the packet or make a function call to an access control checker function. If the invoking user is found to have sufficient access to run this command, another function call is made. This function call depends on what command the user in question has invoked. Try to imagine making one of these functions send out a WHOIS query to the server, and wait for the burst of WHOIS-response packets from it. How would this function wait? Yes, I know, I am going to have to create another thread to loop while it waits for this reply packet. The problem is, I can't simply tell my command function to loop until the "waiter thread" raises a flag to say that it has received the packet. During this looping time, program flow would be stuck here, thus preventing the bot from replying to any vital duties such as "pingponging" (server verifies that you are still there by sending "PING" and expects a "PONG" in return.) For this reason I was thinking: do you think I should run a new thread whenever a new command is invoked by a user? And have the thread delete itself when it's completed execution? This way the bot would *always* be free to do its duties. Any help is much appreciated. M. Baker From mwm at mired.org Fri Jan 11 11:17:00 2008 From: mwm at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 11:17:00 -0500 Subject: Learning Python via a little word frequency program In-Reply-To: <7x63y0ins2.fsf@ruckus.brouhaha.com> References: <205c99df-2550-47b0-9c82-020b99ed3122@l1g2000hsa.googlegroups.com> <7x63y0ins2.fsf@ruckus.brouhaha.com> Message-ID: <20080111111700.01febeee@mbook.mired.org> On 11 Jan 2008 03:50:53 -0800 Paul Rubin <"http://phr.cx"@NOSPAM.invalid> wrote: > rent writes: > > keys = freq.keys() > > keys.sort(key = freq.get, reverse = True) > > for k in keys: > > print "%-10s: %d" % (k, freq[k]) > > I prefer (untested): > > def snd((x,y)): return y # I wish this was built-in What's wrong with operator.itemgetter? > sorted_freq = sorted(freq.iteritems(), key=snd, reverse=True) (still untested) from operator import itemgetter sorted_freq = sorted(freq.iteritems(), key=itemgetter(2), reverse=True) http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From gagsl-py2 at yahoo.com.ar Sun Jan 27 12:45:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 15:45:24 -0200 Subject: Exceptions on delete in pysqlite References: <479a7b0c$0$9119$9b4e6d93@newsspool2.arcor-online.net> Message-ID: En Fri, 25 Jan 2008 22:12:57 -0200, Wildemar Wildenburger escribi?: > Using pysqlite, I'd like to check if some dataset that I removed has > been in the database at all. Ideally I'd like pysqlite to raise an > Exception if deleting does nothing. Is that possible? I don't think so. It isn't an error, like a SELECT which returns an empty set isn't an error either. > Codewise, I'd like the following, but without me checking for and > raising the exception myself: > > cur = con.execute("""DELETE FROM SomeTable WHERE id=? AND name=?""", > (ID, NAME)) > if cur.rowcount == 0: > raise Exception Write a function to do that. -- Gabriel Genellina From mr.cerutti at gmail.com Thu Jan 17 10:28:50 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 17 Jan 2008 10:28:50 -0500 Subject: Is this a bug, or is it me? In-Reply-To: <51302a8c0801170723p35097f2avcb1b19964ef28dd9@mail.gmail.com> References: <51302a8c0801170723p35097f2avcb1b19964ef28dd9@mail.gmail.com> Message-ID: <51302a8c0801170728w76904efua3742e4d313e83c9@mail.gmail.com> On Jan 17, 2008 10:23 AM, Neil Cerutti wrote: > You cannot access a class's class variables in it's class-statement > scope, since the name of the type is not bound until after the class > statement is completed. Arrgh! I hate making the "its" error. But I wanted to add that this property of Python's class statement bothers me only when I think it would be good to use class variables as default method argument values. Luckily, I don't think very often. ;) -- Neil Cerutti From kw at codebykevin.com Thu Jan 10 10:42:21 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 10 Jan 2008 10:42:21 -0500 Subject: Problem with Tkinter.PhotoImage In-Reply-To: References: Message-ID: <47863CDD.9060200@codebykevin.com> C?dric Lucantis wrote: > Hi, > > I can only load gif images with Tkinter.PhotoImage and none with BitmapImage. > I tried png, jpg, bmp and xpm and always got this errors : > That's because Tk only supports the gif format natively. You need to install an additional photo library to support additional images (Tk has an Img extension, and Python Image Library is also very good). -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bs866806 at 163.com Thu Jan 3 01:53:01 2008 From: bs866806 at 163.com (bs866806 at 163.com) Date: Wed, 2 Jan 2008 22:53:01 -0800 (PST) Subject: How To Yell At Employees Message-ID: Dallas, TX - Madmanager.com, officially launches its web based management advice site, featuring expert management help on topics such as "How To Yell At Employees?" Solutions cost as little as $1.00 and feature results oriented answers to tough management questions. Situations madmanager can help with are "How to motivate a losing team?" "How to improve lagging sales?" "How to get rude employees to provide excellent customer service?" There are no canned responses and each problem is responded to with a solution tailored to the manager's unique situation. Founder Darryl Gee, a.k.a the madmanager has 18 years of sales and management experience. Sales trainer, Operations Manager, Store Manager and District Leader are titles he has held. He started madmanager.com to provide low cost, instant access to expert management advice. Easily accessed from any PC, the site is home to dozens of management articles, links and a management message board. Advice is offered privately, anonymously and judgement free. Any manager, any where in the world can access madmanager.com. The basic service, 1 solution for $4.99 or 3 for $8.99, is delivered via a simple click and submit form. The more advanced, high value $21 monthly subscription, is 21 questions, with 21 solutions, administered via a simple message board. It's just $1 per question. The site is targeted to assistant managers, new managers, sales managers and retailers who want to achieve phenomenal results such as, consistent sales increases, exceptional profit growth, and stellar customer service. Users will work closely with madmanager to develop goals, business strategies and sales tactics - for as little as $1. Add madmanager to the list of things you can get for $1.00 - A hamburger, a Sunday paper, a song for your ipod ... and now management advice. Managers and Business Owners who wish to use the service, access featured articles and access the free forums can visit Madmadmanger.com. Madmadmanger.com is a Dallas, TX based sole proprietorship, founded by Darryl Gee. You can find management related articles written by Darryl Gee at this link http://isnare.com/?s=author&a=Darryl+Gee CONTACT: Darryl Gee 2828 LaClede Ave. Suite 188 Dallas, TX 75204 dagee at madmanager.com (214) 764-6972 http://cncarrental.cn/html/Death/20060925/9596.html From marek.rocki at wp.pl Mon Jan 28 12:43:43 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Mon, 28 Jan 2008 09:43:43 -0800 (PST) Subject: validate string is valid maths References: Message-ID: <2ac8fb9c-2e6b-4967-a641-7f6addc5f97c@v29g2000hsf.googlegroups.com> I decided to play with it a little bit, but take a different approach than Steven. This seems actually one of the problems where regexp might be a good solution. import re re_signednumber = r'([-+]?\d+)' re_expression = '%s(?:([-+/*])[-+/*]*?%s)*' % (re_signednumber, re_signednumber) for test_case in ('3++++++8', '3++--*-9', '3++*/-9', '45--/**/+7', '55/-**+-6**'): print re.match(re_expression, test_case).groups() Now you have two problems ;-) One question: you write "in cases where multiple symbols conflict in meaning (as '3++--*-9' the earliest valid symbols in the sequence should be preserved". Aren't '++' the earliest valid symbols (operation and sign)? It seems, instead, that in your test cases the sign is always immediately preceding the number. My regexp accommodates for that. Regards, Marek From svenn.bjerkem at googlemail.com Sat Jan 12 09:19:46 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Sat, 12 Jan 2008 06:19:46 -0800 (PST) Subject: executing newgrp from python in current shell possible? References: <755e7fd2-5e4a-4a4b-b848-a5e4ca756087@l6g2000prm.googlegroups.com> Message-ID: On Jan 9, 9:18 pm, Zentrader wrote: > On Jan 9, 5:56 am, Svenn Are Bjerkem > wrote: > > >I have been looking for a way to execute this command > > as a part of a script, but it seems that the changes are only valid in > > the context of the script and when the script exits, the current shell > > still have the original "users" group setting. > > I don't think you would want it any other way. Would you want a user > to be able to change the group and have it remain permanently? Who's > going to remember whether they were last in "A" or "B", and it opens > up oportunities for the practical joker when you go to the restroom > and leave the terminal on. Put the "change the group" code into a > separate function in a separate file (with only you as the owner) and > call it whenever you want to change groups. I am trying to create a script that make it easy for users in a design team to create files that belong to the same group, but retain the users uid. In order to make it visible that the user is creating files with a different gid, the script will change the prompt to indicate so. In a tcl solution I have now, the users home is changed to the design area as some tools are reading and writing setup files into $HOME. I have not found a way to change the gid in tcl so I turned to python in hope that this scripting language could do so. The tcl solution spawns a new tcsh after setting several environment variables and works quite well except for not being able to change gid. And it is also a wish from my side to port this script to python. Is your suggestion to put "newgrp design" into a new file and then exec this file in my python script? What happens to the group id of the shell that called the python script in this case? I would try to avoid spawning a new tcsh as this make execution of tools on a remote computer difficult as the handover of command line arguments does not seem to be handed over to the newly spawned shell. I may be understanding something wrongly here. -- Svenn From jairtrejo at yahoo.com.mx Wed Jan 2 14:19:57 2008 From: jairtrejo at yahoo.com.mx (Jair Trejo) Date: Wed, 2 Jan 2008 13:19:57 -0600 (CST) Subject: PyCairo, PIL and StringIO In-Reply-To: Message-ID: <782391.65282.qm@web52202.mail.re2.yahoo.com> > > De: Fredrik Lundh > A: python-list at python.org > Fecha: Wed, 02 Jan 2008 15:39:11 +0100 > Asunto: Re: PyCairo, PIL and StringIO > > Jair Trejo wrote: > > > I'm doing some image processing in PIL, and I want > to > > display the results in a GTK window using PyCairo, > so > > I create a Cairo image surface from the PIL Image > like > > this: > > data > > mfile = StringIO.StringIO() > > final.save(mfile, format="PNG") > > ima = > > cairo.ImageSurface.create_from_png(mfile) > > mfile.close() > > return ima > > > > Where final is a PIL image. The problem is, I get > a > > IOError: error while reading from Input Stream. > > > > ?Any idea of why is this happening? > > "save" leaves the file pointer at an undefined > position (usually at the > end), so my guess is that you have to rewind the > file before you pass it > to the next function: > > final.save(mfile, format="PNG") > mfile.seek(0) # rewind > > also note that compressing and decompressing will > introduce unnecessary > overhead; chances are that you might get a lot > better performance if you > just shuffle the raw pixels. I haven't used PyCairo > myself, but from a > quick look at the ImageSurface documentation, > something like this should > work (untested): > > if final.mode != "RGB": > final = final.convert("RGB") > w, h = final.size > data = final.tostring() # get packed RGB buffer > ima = cairo.ImageSurface.create(data, > FORMAT_RGB24, w, h, w*3) > > (tweak as necessary) > > Thank, you, it worked! I tried rewinding the file, and it worked OK. But you were right about performance issues, so I tweaked your code and left it as: from array import array ... w,h = final.size data=array('c') data.fromstring(final.tostring()) ima=cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32,w,h,w*4) return ima Which is around 10 times faster. The problem is, it swaps the R and B bands. I could probably write my own Image.tostring(), but i found it more convenient to swap the channels before processing, and it worked just fine. ____________________________________________________________________________________ ?Capacidad ilimitada de almacenamiento en tu correo! No te preocupes m?s por el espacio de tu cuenta con Correo Yahoo!: http://correo.yahoo.com.mx/ From mfefe at gmail.com Tue Jan 1 07:56:47 2008 From: mfefe at gmail.com (mfefe at gmail.com) Date: Tue, 1 Jan 2008 12:56:47 +0000 (UTC) Subject: M I-5'Per secution Be rnard Levi n ex presses hi s views Message-ID: The article of which part is reproduced below. was penned by Bernard Levin for the Features section of the Times on 21 September 1991. To my. mind, it described the situation at the time. and in particular a recent meeting with a friend,. during which I for the first time admitted to someone other than my GP that I had been subjected to a conspiracy of. harassment over the previous. year and a half. >There is a madman running loose about London, called David. Campbell; I have >no reason to believe that he is. violent, but he should certainly be >approached with caution. You. may know him by the curious glitter in his >eyes and a. persistent trembling of his hands; if that does not suffice, you >will find. him attempting to thrust no fewer than 48 books into your arms, >all hardbacks, with a promise that, if. you should return to the same >meeting-place next. year, he will heave another 80 at you. > >If, by now, the police have arrived and are keeping a close watch. on him, >you may feel. sufficiently emboldened to examine the books. The jackets are >a model of uncluttered typography,. elegantly and simply laid out; there is >an unobtrusive colophon of. a rising sun, probably not picked at random. >Gaining confidence - the lunatic is smiling by now,. and the policemen, who >know about such things, have significantly. removed their helmets - you >could do worse than take the jacket off the first book in the. pile. The >only word possible to describe the binding is sumptuous; real cloth in. a >glorious shade of dark green,. with the title and author in black and gold >on the. spine. > >Look at it more closely; your eyes do not deceive. you - it truly does have >real top-bands and tail-bands,. in yellow, and, for good measure, a silk >marker ribbon in a lighter green. The paper is cream-wove and. acid-free, >and the book is. sewn, not glued. > >Throughout the encounter, I should have mentioned,. our loony has been >chattering away, although what he is trying to. say is almost impossible to >understand;. after a time, however, he becomes sufficiently coherent to make >clear that he is trying to sell the books to you. Well,. now, such quality >in bookmaking today can only be for collectors' limited editions at. a >fearsome price - #30, #40,. #50? > >No, no, he says, the glitter more powerful than ever. and the trembling of >his hands rapidly spreading throughout his. entire body; no, no - the books >are priced variously. at #7, #8 or #9, with the top price #12. > >At this, the policemen understandably put their helmets back on; one. of >them draws his truncheon and the other can be. heard summoning >reinforcements on. his walkie-talkie. The madman bursts into tears, and >swears it is. all true. > >And it. is. > >David Campbell has acquired the entire rights to the whole. of the >Everyman's Library, which. died a lingering and shameful death a decade or >so ago, and he proposes to start it all over again. - 48 volumes this >September and 80 more next year, in editions I have described, at. the >prices. specified. He proposes to launch his amazing venture simultaneously >in Britain and. the United States, with the massive firepower of Random >Century at his back in this country,. and the dashing cavalry of Knopf >across the water, and no one who loves. literature and courage will forbear >to. cheer. At the time this article was written I had. believed for some time that columnists in the Times. and other journalists had been making references to my situation. Nothing unusual about this you may think,. plenty of people have the same sort of. ideas and obviously the papers aren't writing about them, so why should my beliefs not be as false as those. of others? What makes this article so extraordinary is that three or. four days immediately preceding. its publication, I had a meeting with a friend, during the course of which. we discussed the media persecution, and in particular that by Times. columnists. It seemed to me, reading the article by Levin in Saturday?s paper, that he. was describing in some detail his "artist?s impression" of that meeting. Most telling are. the final sentences, when he writes, "The madman bursts into tears,. and swears it is all true. And it is." Although I did not "burst into tears". (he seems to be using a bit of poetic licence and exaggerating). I did try hard to convince my friend that it was all true;. and I am able to concur with Mr Levin, because,. of course, it is. At the beginning of. the piece Levin reveals a fear of being attacked by the "irrational" subject of his story, saying "I have no reason to. believe that he is. violent, but he should certainly be approached with caution". This goes back to the xenophobic. propaganda of "defence" against a "threat" which was seen at the very beginning. of the harassment. The impression of a "madman running loose" who needs to be. controlled through an agency which assigns to itself the mantle of. the "police" is also one which had been expressed. elsewhere. In. the final paragraph of this extract, his reference to Everyman?s Library as. having "died a lingering and shameful death a decade or so ago" shows clearly what sort of. conclusion they wish to their campaign. They want a permanent solution, and as they are prevented from achieving. that solution directly, they waste. significant resources on methods which have been repeatedly shown to be ineffective for such. a purpose. 343 From george.sakkis at gmail.com Sat Jan 26 02:48:24 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 25 Jan 2008 23:48:24 -0800 (PST) Subject: Pickling dynamically generated classes Message-ID: <17d87139-dff6-4182-a7bb-c243ba5f43c4@d21g2000prf.googlegroups.com> The Fine Manual mentions that pickle works for classes that are defined at the top level of a module. Is there a way to extend this behavior so that I can pickle and unpickle instances of dynamically generated classes ? Longer version: I have a function RecordTypeFactory(fields, ...) that dynamically generates and caches a record-like class based on the passed fields and other info (or returns the cached class if it has been created before). Although I am able to pickle instances of the various generated classes (records) by writing the gen. class in globals(), I cannot unpickle them from a different process unless RecordTypeFactory is called with the same arguments so that "the same" class is generated in the other process as well. Essentially what I'm missing is a hook to call RecordTypeFactory with the same fields when an instance of the gen. class is to be unpickled. George From sjmcarter at gmail.com Tue Jan 15 14:29:58 2008 From: sjmcarter at gmail.com (SJ Carter) Date: Tue, 15 Jan 2008 11:29:58 -0800 (PST) Subject: Perl Template Toolkit: Now in spicy new Python flavor References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> Message-ID: Congrats. This will no doubt prove valuable to any Python programmer. From cjw at sympatico.ca Tue Jan 15 10:54:10 2008 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 15 Jan 2008 10:54:10 -0500 Subject: Why this apparent assymetry in set operations? In-Reply-To: <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: Neil Cerutti wrote: > On Jan 15, 2008 10:10 AM, wrote: >> I've noticed that I can update() a set with a list but I can't extend a set >> with a list using the |= assignment operator. >> >> >>> s = set() >> >>> s.update([1,2,3]) >> >>> s >> set([1, 2, 3]) >> >>> s |= [4,5,6] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: unsupported operand type(s) for |=: 'set' and 'list' >> >>> s |= set([4,5,6]) >> >>> s >> set([1, 2, 3, 4, 5, 6]) >> >> Why is that? Doesn't the |= operator essentially map to an update() call? > > No, according to 3.7 Set Types, s | t maps to s.union(t). > If the RHS is a set then it works OK: *** Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32. *** >>> import sets >>> s1= sets.Set([2, 4, 5]) Set([2, 4, 5]) >>> s1= sets.Set([2, 4, 5]) >>> s2= sets.Set([4, 5, 6]) >>> s1|s2 Set([2, 4, 5, 6]) >>> s1|=s2 >>> s1 Set([2, 4, 5, 6]) >>> It could be modifies to handle any iterable on the RHS. Colin W. From oliver at obeattie.com Sat Jan 26 08:16:03 2008 From: oliver at obeattie.com (Oliver Beattie) Date: Sat, 26 Jan 2008 05:16:03 -0800 (PST) Subject: Custom class to a dictionary? References: <5025a3f7-9dcf-49d7-876c-df5c8d8a8df5@e6g2000prf.googlegroups.com> <13pm89n9avfl146@corp.supernews.com> Message-ID: <1ac0a4b2-2966-4e44-99ce-6172ea8d4baf@d4g2000prg.googlegroups.com> On Jan 26, 12:01?pm, Steven D'Aprano wrote: > On Sat, 26 Jan 2008 03:35:18 -0800, Oliver Beattie wrote: > > Just wondering if it is possible to pass a custom class instance > > instance to dict() by way of using methods like you can for iterators > > (__iter__, __getitem__ etc.) I see there is no __dict__ -- is there > > anything else I can use to achieve this? > > Just write a method to return (key, value) pairs, and call that: > > >>> class Parrot(object): > > ... ? ? def __init__(self): > ... ? ? ? ? ? ? self.keys = [1, 2, 3, 4] > ... ? ? ? ? ? ? self.values = ["one", "two", "three", "four"] > ... ? ? def generate_tuples(self): > ... ? ? ? ? ? ? for k,v in zip(self.keys, self.values): > ... ? ? ? ? ? ? ? ? ? ? yield (k,v) > ...>>> p = Parrot() > >>> p.generate_tuples() > > >>> dict(p.generate_tuples()) > > {1: 'one', 2: 'two', 3: 'three', 4: 'four'} > > Here's another way: > > >>> class Foo(object): > > ... ? ? def __getitem__(self, i): > ... ? ? ? ? ? ? if i > 4: > ... ? ? ? ? ? ? ? ? ? ? raise IndexError > ... ? ? ? ? ? ? return (i, 'foo %d' % i) > ...>>> dict(Foo()) > > {0: 'foo 0', 1: 'foo 1', 2: 'foo 2', 3: 'foo 3', 4: 'foo 4'} > > Bonus marks if you can explain why they both work :) > > (Hint: consider the "sequence protocol" and the "iterator protocol".) > > -- > Steven Sure, I get what you're saying here and thanks for the advice; but I don't want the keys as the iterator indices -- They should have custom names (latitude, longitude and elevation). Is this possible (outside of the custom method to generate two-tuples?) Sorry to be a pain! The class looks like the below; I just whipped this up real quick but it can generate the iterators it should -- just the dictionaries should be different -- {'latitude': 0.0, 'longitude': 0.0, 'elevation': 0.0} or whatever): class Coordinates(object): """Basic object for storing co-ordinate data.""" latitude = 0.0 longitude = 0.0 elevation = 0.0 def __unicode__(self): return u'Coordinate (%s, %s, %s)' % (self.latitude, self.longitude, self.elevation) def __repr__(self): return '' % (self.latitude, self.longitude, self.elevation) def __iter__(self): return iter((self.latitude, self.longitude, self.elevation)) I guess it's just easier to have a dict() method to this end; just wondered if there was a more 'Pythonic' way to do this. From robin at alldunn.com Fri Jan 25 11:54:52 2008 From: robin at alldunn.com (Robin Dunn) Date: Fri, 25 Jan 2008 08:54:52 -0800 Subject: [wxPython-users] Issue with docking wx.listctrl window In-Reply-To: References: <4798D1B1.7020908@alldunn.com> Message-ID: <479A145C.40802@alldunn.com> tarun wrote: > Thanks a lot Robin. > > I tried using self.log and instead of self.log.list. *Code is attached.* > But this gives me a panel and listctrl in it. The extra blank space > around the listctrl in window1 is something that I don't need. Use a sizer to manage the layout of the listctrl. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From paddy3118 at googlemail.com Sat Jan 5 09:09:06 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 5 Jan 2008 06:09:06 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> Message-ID: <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> On Jan 4, 3:50 pm, "Reedick, Andrew" wrote: > > From: Stephen Hansen [mailto:apt.shan... at gmail.com] > > Sent: Thursday, January 03, 2008 7:39 PM > > To: Reedick, Andrew > > Cc: python-l... at python.org > > Subject: Re: dictionary/hash and '1' versus 1 > > > Well one important thing to learn while learning Python is that while the > > language is dynamically typed-- it is also /strongly/ typed. Every piece > > of data has an explicit type and it doesn't change unless you change it. > > Meh, mixing dynamic and strong typing is a mixed blessing. You don't find out that you screwed up the data types until the code block is actually executed. Reminds me of Nostradamus. He may have predicted the future[1], but the predictions are so vague/convoluted that you can only figure out the predictions in hindsight. > > > It relies on duck typing a lot, and doesn't care if you mix and match > > (even partially) compatible types as long as the operations are there, > > but one type will always be distinct and remain that type until you > > explicitly convert it. > > > A single integer is distinctly different from a sequence of characters in > > some encoding that may just happen to contain representations of a > > number.... so they'll hash differently :) > > Depends on the context. The machine encoding may be different, but in human terms they "should" be the same. Perl managed to achieve an impressive blend of presenting data as human friendly or as machine bits when it made sense to do so. So much so, that Perl is probably the only language I've used that will do what you mean instead of what you say. Nice, but frightening in some ways. There are many character strings that contain numeric characters that are not necessarily to be interpreted as an int or a float, such as string representations of IP addresses, or numbers to other bases than ten, complex numbers, telephone numbers, ... You need to validate your input and convert and pass around the correct type of data. Perl inherited this automatic conversion between strings and numbers from simple shell scripting and the AWK language that was around before Perl. I find that the follow-on need to have separate comparisons for numbers or strings to be awkward in Perl. > > > One type will basically never implicitly convert into another type. > > > To me, this sounds like the function should have converted the type > > explicitly on return. Or maybe you need to convert it explicitly on > > receipt. > > Type casting is easy, IFF you remember to do so. The problem was that I missed the fact that one (important) function was returning a string instead of an int, and since Python supports heterogenous data structures, the human has to remember to keep the key's data type homongenous. > That and Perl does so much automatic type conversion in such a sensible way, that I stopped worrying about mixing data types, which is making the Python transition a tad more error prone. Because of Perl, I almost consider automatic type casting to be the next "you don't have to manage your own memory" that people loved about Java. =O Not really, it seems to me to be going the exact opposite way with languages with automatic type conversions being seen as not suited for larger programs. > > > But if you are in a use-case where you really don't care and only > > want to hash strings, you can create a dict subclass easily that > > overrides __setitem__ to always str() the input. Check out the > > UserDict class. > > UserDict looks like it could be useful. Thanks for the info. > > > A similar method lets you make 'case-insensitive' dicts, for example. > > > Were such a thing to happen automagically, you could get some > > weird situations, such as "assert (key in dict) == (key in dict.keys())" > > failing. > > I'm assuming that you would just need to overload the 'in' operator and .keys() method to be case insensitive also. > > [1] No, he didn't. > From steven at REMOVE.THIS.cybersource.com.au Sun Jan 6 16:56:58 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 06 Jan 2008 21:56:58 -0000 Subject: Delete lines containing a specific word References: Message-ID: On Sun, 06 Jan 2008 13:33:52 -0800, Francesco Pietra wrote: > Steven: > Thanks. See below please (of very marginal interest) > > --- Steven D'Aprano wrote: > >> On Sun, 06 Jan 2008 09:21:33 -0800, Francesco Pietra wrote: >> >> > Please, how to adapt the following script (to delete blank lines) to >> > delete lines containing a specific word, or words? >> >> That's tricky, because deleting lines from a file isn't a simple >> operation. No operating system I know of (Windows, Linux, OS X) has a >> "delete line" function. > > As I am at Debian Linux, I do that with grep -v grep doesn't delete lines. grep matches lines. If you want to delete them, you still have to do the rest of the job yourself. >> Secondly, you might want the script to write its output to a file, >> instead of printing. So, instead of the line "print line", you want it >> to write to a file. > > may be cumbersome, though I use 2>&1 | tee output file.pdb so that I > can see what happens on the screen and have the modified file. Yes, matching lines and sending them to stdout is a better solution than trying to delete them from a file. -- Steven From cjw at sympatico.ca Wed Jan 16 08:14:15 2008 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 16 Jan 2008 08:14:15 -0500 Subject: Why this apparent assymetry in set operations? In-Reply-To: <13oq9uo2rjruhb6@corp.supernews.com> References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> <13oq9uo2rjruhb6@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Tue, 15 Jan 2008 11:25:25 -0500, Colin J. Williams wrote: > >> I'm sorry, there appears to be a bug: # tSet.py >> import sets >> s1= sets.Set([1, 2, 3]) >> s1.union_update([3, 4,5]) >> print(s1) >> s2= sets.Set([6, 7, 8]) >> s1 |+ s2 # This fails: >> exceptions.TypeError: bad operand type for unary +: 'Set' > > And so it should fail. Did you mean |= instead of |+ ? > > Thanks, keyboard error. Colin W. From paddy3118 at googlemail.com Fri Jan 11 15:03:08 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 11 Jan 2008 12:03:08 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <0d29626d-886d-46ea-b387-879e24f41110@t1g2000pra.googlegroups.com> Message-ID: <8c7a77e4-e32b-4459-b7b5-693bf201a063@q39g2000hsf.googlegroups.com> On Jan 11, 9:54 am, Chris wrote: > On Jan 9, 12:34 pm, cesco wrote: > > > Hi, > > > say I have a string like the following: > > s1 = 'hi_cat_bye_dog' > > and I want to replace the even '_' with ':' and the odd '_' with ',' > > so that I get a new string like the following: > > s2 = 'hi:cat,bye:dog' > > Is there a common recipe to accomplish that? I can't come up with any > > solution... > > > Thanks in advance > > Cesco > > A simple list comprehension is all that is needed. > > input_string = 'hi_cat_bye_dog'.split('_') > output_string = ','.join([':'.join(input_string[i:i+2]) for i in > xrange(0,len(input_string),2)]) I tried your example with my extended input cases to get: def altrep6(s): input_string = s.split('_') return ','.join([':'.join(input_string[i:i+2]) for i in xrange(0,len(input_string),2)]) altrep6.author="Chris" Giving output: ## Program by: Chris '' RETURNS '' '1' RETURNS '1' '2_' RETURNS '2:' '3_4' RETURNS '3:4' '5_6_' RETURNS '5:6,' '7_8_9' RETURNS '7:8,9' '10_11_12_' RETURNS '10:11,12:' '13_14_15_16' RETURNS '13:14,15:16' '17_18_19_20_' RETURNS '17:18,19:20,' '_' RETURNS ':' '_21' RETURNS ':21' '_22_' RETURNS ':22,' '_23_24' RETURNS ':23,24' '_25_26_' RETURNS ':25,26:' '_27_28_29' RETURNS ':27,28:29' '_30_31_32_' RETURNS ':30,31:32,' '_33_34_35_36' RETURNS ':33,34:35,36' '__' RETURNS ':,' '___' RETURNS ':,:' '____' RETURNS ':,:,' '_____' RETURNS ':,:,:' - Paddy. From rupert.thurner at gmail.com Sun Jan 20 06:51:17 2008 From: rupert.thurner at gmail.com (rupert.thurner) Date: Sun, 20 Jan 2008 03:51:17 -0800 (PST) Subject: finding memory leak in edgewall trac 0.11 References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> <0c6fc35d-91d2-4767-968d-e6eb56096eba@z17g2000hsg.googlegroups.com> Message-ID: <4f9304e4-3847-41ee-8064-b881f7b9e073@f47g2000hsd.googlegroups.com> On Jan 20, 12:40?pm, "rupert.thurner" wrote: > On Jan 19, 10:31?pm, Christian Heimes wrote: > > > > > > > Jeroen Ruigrok van der Werven wrote: > > > > Hi Christian, > > > > -On [20080119 16:16], Christian Heimes (li... at cheimes.de) wrote: > > >> I forgot one important point in my reply. The GC module contains some > > >> useful methods for debugging. Check gc.garbage. It should be empty. > > > > Yeah, we're messing around with that stuff as well as many other ways of > > > trying to track issues, but it can really be looking for a needle in a > > > haystack to be honest. > > > There's so much output that, I guess, make sense only when you're semi-deep > > > into the Python internals to even make heads or tails out of it. =\ > > > And even third-party code is not helping much to reduce the clutter and > > > provide insight. > > > Under normal circumstances gc.garbage should be an empty list. In > > general it's a bad sign if gc.garbage contains lots of objects. > > > I found several potential leaks in trac: > > > $ find -name \*.py | xargs grep __del__ > > ./trac/versioncontrol/svn_fs.py: ? ?def __del__(self): > > ./trac/versioncontrol/svn_fs.py: ? ?def __del__(self): > > ./trac/db/pool.py: ? ?def __del__(self): > > > $ find -name \*.py | xargs grep frame > > ./trac/web/main.py: > > [...] > > ./trac/core.py: ? ? ? ?frame = sys._getframe(1) > > ./trac/core.py: ? ? ? ?locals_ = frame.f_locals > > > I recommend that you either replace __del__ with a weak reference > > callback or to remove it. Referencing a frame, traceback or f_locals is > > going to leak, too. You *must* explicitly del every frame and locals > > variable. > > > Christian > > many thanks! as the main change was replacing clearsilver with genshi, > this means one could do the same thing with genshi,http://genshi.edgewall.org/? > > $ find -name \*.py | xargs grep frame > ./genshi/filters/html.py: ? ? ? ?'dir', 'disabled', 'enctype', 'for', ... > > - Show quoted text - i forgot to mention that i cannot see any explicit sys._getframe(), or __del__ in the genshi code, while the ones in trac-core seemed to be there in 0.10.4. rupert From bborcic at gmail.com Wed Jan 30 08:45:08 2008 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 30 Jan 2008 14:45:08 +0100 Subject: find nearest time in datetime list In-Reply-To: References: Message-ID: <47a07fa6$1_1@news.bluewin.ch> washakie wrote: > Hello, > > I have a list of datetime objects: DTlist, I have another single datetime > object: dt, ... I need to find the nearest DTlist[i] to the dt .... is > there a simple way to do this? There isn't necessarily an exact match... > > Thanks! > .john > min(DTlist,key=lambda date : abs(dt-date)) From aawood at gmail.com Thu Jan 10 16:46:39 2008 From: aawood at gmail.com (Adrian Wood) Date: Thu, 10 Jan 2008 21:46:39 +0000 Subject: Newbie question on Classes Message-ID: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> Hi al! I'm new to the list, and reasonably new to Python, so be gentle. Long story short, I'm having a hard time finding a way to call a function on every object of a class at once. Example: I have a class Person, which has a function state(). This prints a basic string about the Person (position, for example). In the program, I have created two objects of class Person, called man and woman. I can call man.state() and then woman.state() or Person.state(man) and Person.state(woman) to print the status of each. This takes time and space however, and becomes unmanageable if we start talking about a large number of objects, and unworkable if there is an unknown number. What I'm after is a way to call the status of every instance of Man, without knowing their exact names or number. I've gone through the relevant parts of the online docs, tried to find information elsewhere online, and looked for code samples, but the ionformation either isn't there, or just isn't clicking with me. I've tried tracking the names of each object in a list, and even creating each object within a list, but don't seem to be able to find the right syntax to make it all work. I'd appreciate anyone who could help, especially if they could include a short sample. My apologies if I'm not following the etiquette of the group in some way my making this request. Thank you, Adrian From Lie.1296 at gmail.com Sun Jan 20 17:37:56 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 20 Jan 2008 14:37:56 -0800 (PST) Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> <478e1e3e$0$18054$426a74cc@news.free.fr> Message-ID: <34aa1a1f-2034-471d-91ee-2a758dab555b@f47g2000hsd.googlegroups.com> On Jan 16, 9:23 pm, Bjoern Schliessmann wrote: > Lie wrote: > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > >> I used to systematically use it - like I've always systematically > >> used 'this' in C++ and Java. > > > And that is what reduces readability. > > IMHO not, IOPHO not. This is the nth time (n >> 1) this discussion > comes up here. If I have learned one thing from those very lengthy > discussions, it's that Python's "self" handling is not going to > change. And ah... yes, I don't wish it go away either. In VB, excessive Me reduces readability, but in Python it doesn't. > > A proficient VB/C/Java programmer would frown upon the extra, > > unneeded garbage as they thought it was clear already that the > > variable refers to a class-level variable. > > C programmers surely have no opinion concerning C because it has no > native classes. C-family, ok? Please stop taking my words to its letters. > Personally, I've seen many C++ programs with complex class designs > where it definitely helps to consistently use "this->". I cannot > remember all local (and global) variables in bigger methods. In that case, you have the _option_ to do it. > > There is one major positive point: convenience and shorter code. > > (isn't that two?) > > Shorter code is not per se positive, neither is it convenient. If it > was, everyone would use perl. Not always, but sometimes it do help not to be obliged to use the class name especially in short, simple programs (as opposed to big projects that requires hundreds of thousands of lines of code) that is changed frequently (being in heavy development). A good real-life example for this would be for new learner of programming or the language, they would write a lot of ten liners that is changed a LOT of times due to their (yet) incomplete understanding of the concepts. > >> it's the first argument of the function - which usually happens to be > >> the current instance when the function is used as a method. > > > And that's the point, self (or anything you name it) is almost always > > the current instance > > # this is a plain function. In this function, > # 'obj' can be whatever that happens to have a (numeric) > # 'stuff' attribute > def func(obj, arg): > ? ?return (obj.stuff + arg) / 2.0 > > # this is a class with an instance attribute 'stuff' > class Foo(object): > ? ? def __init__(self, bar): > ? ? ? self.stuff = bar + 42 > > # this is another (mostly unrelated) class > # with a class attribute 'stuff' > class Bar(object): > ? ?stuff = 42 > > # this is a dummy container class: > class Dummy(object): pass > > # now let's play: > import new > > d = Dummy() > d.stuff = 84 > print func(d, 1) > > d.baaz = new.instancemethod(func, d, type(d)) > print d.baaz(2) > > f = Foo(33) > print func(f, 3) > Foo.baaz = func > f.baaz(4) > > print func(Bar, 5) > Bar.baaz = classmethod(func) > Bar.baaz(6) > > > ?and that makes it functionally the same as Me and > > this in VB and Java. > > Depends on the context, cf above !-) Please again, stop taking letters to the words, I don't meant them to be exactly the same, rather the same would meant that they generally can be considered equal, exceptions exists of course. And btw, I don't understand what you meant by your example, they seemed to be a completely OK program for me, even though it's a bit confusing to follow[2]. [2] btw, the reason it's a bit confusing to follow is one of my points: It is a Bad Thing(tm) to use the same name for different variables even in a language like Python that enforce explicit naming of classes > >>> Most other languages > >>> 1) automatically assign the containing class' object > >> s/containing class' object/current instance/ > > >>> in a keyword > >>> (Java: this, VB: Me) behind the screen, > > >> That's not very far from what a Python method object does - > >> automatically assign the current instance to something. The difference > >> is that Python uses functions to implement methods (instead of having > >> two distinct contructs), so the only reliable way to "inject" the > >> reference to the current instance is to pass it as an argument to the > >> function (instead of making it pop from pure air). > > > It isn't very far, but Python makes it obvious about the assignment > > (not behind the screen). > > Exactly. And given both the simplicity of the solution and what it let > you do, that's a *very* GoodThing(tm) IMHO. I agree, it's a Good Thing but it doesn't make the point less pointy, the difference between Me/this and self is just the explicit assignment. Other things that is possible because of the explicit assignment is just a "coincidence" of design choice. > >>> and 2) automatically searches > >>> variable name in both the local variable table and the containing > >>> class variable table ?(so to refer to a class variable named var from a > >>> method inside the class, we only need to write var, not self.var as in > >>> python). > >> This - as you know - cannot work well with Python's scoping rules and > >> dynamicity. Anyway, implicit object reference is definitively a > >> BadThing(tm) wrt/ readbility, specially with multiparadigm languages > >> (like Python or C++). Why do you think soooo many C++ shops impose the > >> m_something naming scheme ? > > > Implicit object reference for the containing class has little harm, if > > a class is so complex that there are more than 10 class-level > > variable, then it is obvious that that class needs to be fragmented to > > smaller classes. > > Not necessarily. There are general rules (like 'keep your classes small > and focused', which I wholefully agree with), there are guidelines (like > 'more than 10 member variables might smell like refactoring), and > there's real life, where one very often faces classes that have much > more than 10 member variables and still are as small and focused as > possible. I'd add "whenever possible" then. I don't consider 10 as a guideline, but rather as a large number I randomly picked for an example, because in most project 10 is A LOT for number of variables, and I'm sure that most well designed program would have less than 10 variables per class (except in cases where it is just impossible to fragment the class any further). > > Remembering less than 10 variable and avoiding naming > > collision among just 10 variable is not hard (and 10 is really too > > many, most classes should only use 2-4 variables), > > I really doubt you'll be able to write any working non-trivial software > trying to strictly follow this rule. In what way have I said that the rule is strict? No rule is ever strict in my book, ALL rules are meant to be bend in exceptional cases and ALL exceptions are meant to be excepted themselves (applying the definition recursively). > > especially if you > > have a good IDE that employs Intellisense-like technology (IDLE has > > it). > > IDLE is certainly not a "good IDE" in my book. What you've just said actually enforce the sentence, even a bad IDE like IDLE have Intellisense-like feature :) I agree that IDLE isn't a good IDE, but it is an example that I could use since it is the only Python IDE I have ever used (although I'm interested to find another, the demand isn't that high ...yet... to _have_ to find another IDE) > > And it is always a Bad Thing(tm) to use the same name for two > > variable in the class and in function (which is the main and only > > source of possible ambiguity) in ANY language, even in Python. > > Ho, yes.... Like, this would be bad ? > > class Person(object): > ? ?def __init__(self, firstname, lastname, birthdate, gender): > ? ? ?self.firstname = firstname > ? ? ?self.lastname = lastname > ? ? ?self.birthdate = birthdate > ? ? ?self.gender = gender > > C'mon, be serious. It's often hard enough to come with sensible names, > why would one have to find synonyms too ? Try to come with something > more readable than the above, and let us know. Seriously, this braindead > rule about ?"not using the same name for an attribute and a local var" > obviously comes from languages where the "this" ref is optional, and > FWIW it's obviously the wrong solution to a real problem (the good > solution being, of course, to use the fully qualified name for > attributes so there's no possible ambiguity). The code fragment you've given way above (about the Foo, Bar, bazz, and func) also suffers from the bad habits of using the same name for different variables. And it's not a "braindead" rule (even though I used the word always, it still isn't a braindead always without exceptions) The example you've given IS the most readable form since the function is _simple_, consider a function that have complex codes, possibly calculations instead of simply assigning initial values I'm sure you'd slip up between the self.* variables and the * variables once or twice, possibly becoming the source of hard-to-find bugs. In other hand in a _complex_ function, if you thought of a new name, like initialfirstname, etc you'd know what is what and what is where immediately And in languages that doesn't enforce explicit naming of classes, when there is the two or more same names, the one with the smallest scope is picked, so in _simple_ functions, the trick of using full qualified names and overloaded local names is still possible and feasible. In complex functions, the trick fails even in Python, because even if Python and our full-concentration-brain is aware of the difference between self.* and *, our spreaded-concentration-brain that is scanning the code for the source of bugs might get stumbled on the confusing use of self.* and *. > >> Anyway, I actually know 3 languages (4 if C# works the same) that has > >> this implicit 'this' (or whatever the name) 'feature', and at least 5 > >> that don't. So I'm not sure that the "most other languages" qualifier > >> really applies to point 2 !-) > > > What's this 5 languages? > > Smalltalk, Python, PHP, javascript, Ruby. I don't remember how Scheme, > CLOS and OCaml handle the case. Among all them, only Javascript is considerably mainstream. Javascript, being virtually the only web-based scripting language that is supported by most browsers. > > Are they a mainstream, high-level languages > > or lesser known, low-level languages? C-family, Java, and Basic are > > the Big Three of high-level programming language. > > None of C, C++, Java nor Basic qualify as "hi-level". C is the lowest > possible level above assembly, C++ is often refered to as an "object > oriented assembler", Java is way too static, crippled, verbose an > unexpressive to qualify as "hi-level" (even if it suffers from some > problems usually associated with higher level languages). I won't even > comment on basic (is that really a language at all ?). Your criteria on being high-level is simply just odd. The rest of the world recognizes C-family, Java, and Basic as high-level languages. I agree C is a lower-level language compared to C++, C#, Basic, and Python, but standing by itself, it still qualifies as high-level language. If I have to say it, Python is actually lower level than Basic. While Java is just below Python and C and C++ is just below Java. Why do I consider Basic the highest-level? Because it is the cleanest to scan (no confusing symbols, i.e. no curly braces, no confusing use of parens (Python uses (), [], and {}, VB only use ()[3]), and that is also the reasons of some of its warts. In what way C++ resembles an assembler? Have you ever programmed in assembly? How hard is it to create a simple program in assembly? And how hard is it to create a complex program in C++ (which AFAIK is used by hundreds of mega projects including CPython)? And have you ever used Basic at all? Some programmers would instantly frown upon Basic, simply because they don't know that Basic is "just another language". Apart from a syntax that is very different from most languages (absence of curly braces, the minimal use of non-alphabet characters in the syntax, minimal use of short keywords, opting for keywords that is (hopefully) understandable to non VBers[4]), and apart from the quality of the implementation, the language itself isn't a bad language. Sure they may have some warts, but I dare to say "Python have no warts". [3] In fact the new VB.NET 2008 adds a syntax that uses curly braces to VB, but it's only for a syntax sugar, in Python, the difference between the different kind of parentheses is significant. [4] The only significant exception to, a (hopefully) understandable keyword names to non-VBers, is probably the most important keyword, "Dim" for variable declaration. > >>> In VB, Me is extremely rarely used, > >> I used to systematically use it - like I've always systematically used > >> 'this' in C++ ?and Java. > > > And that is what reduces readability. A proficient VB/C/Java > > programmer > > There are quite a few proficient C/C++/Java programmers here. As far as > I'm concerned, I would not pretend being one - I just have a good enough > knowledge of C, Java and (alas) VB to be able to get up to speed in a > reasonnable time frame. > > As a side note, the problem just doesn't exists in C, which has > absolutely no support for OO. When I said C, it might mean C and C-family, so please stop misunderstanding me. As a side note, the conversation we're just having is a real life example of using the name C when it means C-family, your mindset instantly protest that C doesn't have objects, while my mindset says "C" can't have meant C as a language since I don't state C++ and C# too while I should have, and knowing the fact that C in C-family doesn't have objects would make it clear that it is an exception. I'm not saying my mindset is better than yours (it have its positives and negatives), in fact I apologize for getting you confused. > > would frown upon the extra, unneeded garbage as they > > thought it was clear already that the variable refers to a class-level > > variable. > > In C++, the canonical way to make this "clear" is to use the m_name > convention. There must be some reason C++ programmers feel a need for > this "extra, unneeded garbage" ?-) In some cases, an extremely complex class that can't be fragmented any further, the m_ convention is surely useful, but in most cases you could skip them out. And the canonical way to make this "clear" is not the m_ convention, it's the name itself. A well-designed class would choose names that is recognizable instantly from the name itself, even without the pseudo-name appended to it (or prepended). btw you must have been memorizing names braindeadly, because the only way you could stumble on that is by memorizing names braindeadly. Names shouldn't be memorized, it should be inferred and memorized. For example, when you met a variable name firstname and lastname inside a class called Person, you'd immediately realize that it is Class Level variable because you know that the function you're currently working on use the name initialfirstname and initiallastname. > > It is a different story if, like Python, the use of self is > > enforced by the language, the self wouldn't be viewed as extra > > unnecessary garbage. > >>> in Python, self is all > >>> over the place. Well, there is positive and negative to both sides, > >>> convenience in VB, and flexibility in Python. > >> As far as I'm concerned, there's *no* positive point in implicit object > >> reference, and there has never been (and before some paranoid nutcase > >> around accuse me of overzealous biggotry : I already held this very same > >> opinion years before I discovered Python). > > > There is one major positive point: convenience and shorter code. > > (isn't that two?) > > These are not rated as "positive" in my book. That's perhaps why Python > is so far MFL ? Not in _your_ book. Different languages have been devised throughout the world to solve various problems, some of which are convenience in using the language itself. > > As I've pointed out, there is little harm in class-level variable's > > implicit reference. > > Have some working experience on any non-trivial C++ project ? No (you could say I'm a student so I've never "worked"[1]). But I've done some medium-sized projects in other languages. [1] If you understand the irony, you'd realized I was deliberately misunderstanding you > >>> Compare the following codes: > >>> VB.NET: > >>> Public Class A > >>> ? ? Dim var > >>> ? ? Public Function aFunction() > >>> ? ? ? ? return var > >> Add three levels of inheritence and a couple globals and you'll find out > >> that readability count !-) > > > It's the mental model that have to be adapted here, if the current > > class is inheriting from another class, you've got to think it as > > names from parent class as it is a native names, so you don't actually > > need to know where the variable comes from > > In C++ (and VB IIRC), it might as well be a global So sorry but yes, I > have to know where it comes from. How many times would you use globals, it is a Bad Thing(tm) to use globals in the first case. In some exceptional cases globals might be unavoidable, but it is trivial to work out that you have to reduce the amount of globals to a minimum, in almost any cases to a number you can use a hand to count with. And applying the hacks mentioned, why don't you use the m_ convention for globals, and retains the convenience of m_-free variables in your class variable. You use class variable much more often than globals, and in most projects class- level variable is used just as often as local-variable. > > since knowing where it > > comes from is breaking the encapsulation > > Nope, it's knowing what you're doing and how the piece of software at > hand is working. And FWIW, while data hiding is one possible mean of > encapsulation, it's by no way a synonym for encapsulation. I agree that knowing an underlying class's implementation is useful (in fact, very useful) but what I'm talking is about should-ness, we shouldn't _need_ to know the underlying implementation, but if we know it, it's fine and it's great, since you can do tricks that you couldn't do otherwise (at your own risks). No it's not synonym, but one way of encapsulation. > > (which, in Python is very > > weakly implemented, which favors flexibility in many cases[1]). > > > [1] In Python, it is impossible to create a completely private > > variable, which is the reason why the mental model of these other > > languages doesn't fit Python. > > Never heard about the infamous '#define private public' hack in C++ ? > And don't worry, there are also ways to get at so called 'private' vars > in Java. No, but it's violating the language's rule. Python OTOH, provides formal ways to got to private vars. > >> In any non-trivial piece of C++ code, and unless the author either used > >> the explicit 'this' reference or the 'm_xxx' naming convention, you'll > >> have hard time figuring out where a given name comes from when browsing > >> a function's code. > > > If you're used to the implicit naming scheme it's easy to know where a > > variable came from, if not the current scope, it's the class' scope > > You forgot the global scope. How many global variables do you have in your projects on average? If you always have a pageful list of globals in your projects, then you should consider unlearning and relearning the basic programming concepts. It's easy to keep track of globals, as you shouldn't have a lot of them even in a huge project. > > As a final note: > > I don't think implicit class reference is superior to explicit class > > reference, neither > > ... I'm sure you don't believe it since I'm talking on implicit's side, but that's the fact, I just pointed you out that implicits do have its positive side (even if you don't consider them positive in _your_ book) but that doesn't meant I believe it is better than the other. To clear things up: As a final note: I don't think implicit class reference is superior to explicit class reference, but I don't think the vice versa is true either. I consider they have their own positive and negative sides and different languages have different "better" definition, for Python it is explicit, for C/Java/Basic it's implicit. From arkanes at gmail.com Fri Jan 18 14:04:36 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 18 Jan 2008 13:04:36 -0600 Subject: strange syntax rules on list comprehension conditions In-Reply-To: References: Message-ID: <4866bea60801181104w46fd2b5cgf7fb436d6aad03e3@mail.gmail.com> On Jan 18, 2008 12:53 PM, Nicholas wrote: > I was quite delighted today, after extensive searches yielded nothing, to > discover how to place an else condition in a list comprehension. > Trivial mask example: > >>> [True if i <5 else False for i in range(10)] # A > [True, True, True, True, True, False, False, False, False, False] > > I then experimented to drop the else statement which yields an error > >>> [i if i>3 for i in range(10)] > Traceback ( File "", line 1 > this syntax works of course > >>> [i if i>3 else i for i in range(10)] > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > Does anybody else find this lack of symmetry odd? > "x if y else x" is an expression - it's the Python equivalent of C's ternary operator. The mechanism for filtering in a list comp is [x for x in y if x]. Your stumbling upon the ternary expression was a happy accident, and your confusing comes from trying to generalize the wrong operation. From pavloutefkros at gmail.com Mon Jan 28 13:10:17 2008 From: pavloutefkros at gmail.com (pavloutefkros at gmail.com) Date: Mon, 28 Jan 2008 10:10:17 -0800 (PST) Subject: referer url References: <0e7fb40e-809c-4979-bbb8-0cd9a7e816c2@t1g2000pra.googlegroups.com> Message-ID: <10f8327e-4348-436e-a771-c075afed559e@e25g2000prg.googlegroups.com> Thanks for that! i found the variable in "ALL_HTTP" and it's working now. Thanks again.. From george.sakkis at gmail.com Thu Jan 17 00:50:44 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 16 Jan 2008 21:50:44 -0800 (PST) Subject: next line (data parsing) References: <13otnvakq8kc6a3@corp.supernews.com> Message-ID: On Jan 17, 12:42 am, George Sakkis wrote: > On Jan 17, 12:01 am, Scott David Daniels > wrote: > > > > > robleac... at gmail.com wrote: > > > Hi there, > > > I'm struggling to find a sensible way to process a large chuck of > > > data--line by line, but also having the ability to move to subsequent > > > 'next' lines within a for loop. I was hoping someone would be willing > > > to share some insights to help point me in the right direction. This > > > is not a file, so any file modules or methods available for files > > > parsing wouldn't apply. > > > > I can iterate over each line by setting a for loop on the data object; > > > no problem. But basically my intension is to locate the line "Schedule > > > HOST" and progressively move on to the 'next' line, parsing out the > > > pieces I care about, until I then hit "Total", then I resume to the > > > start of the for loop which locates the next "Schedule HOST". > > > if you can do: > > > for line in whatever: > > ... > > > then you can do: > > > source = iter(whatever) > > for intro in source: > > if intro.startswith('Schedule '): > > for line in source: > > if line.startswith('Total'): > > break > > process(intro, line) > > > --Scott David Daniels > > Scott.Dani... at Acm.Org > > Or if you use this pattern often, you may extract it to a general > grouping function such ashttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877: Sorry, google groups fscked up with the auto linewrapping (is there a way to increase the line length?); here it is again: import re for line in iterblocks(source, start = lambda line: line.startswith('Schedule HOST'), end = lambda line: re.search(r'^\s*Total',line), skip_delim = False): process(line) George From martin at v.loewis.de Wed Jan 2 15:34:22 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Jan 2008 21:34:22 +0100 Subject: unicode(s, enc).encode(enc) == s ? In-Reply-To: <1310677e-51ec-49f2-9709-196dcc4e1ac9@e4g2000hsg.googlegroups.com> References: <5e49e7e6-f2b3-4c9f-9dec-e5f01f12d59a@e4g2000hsg.googlegroups.com> <4773f0de$0$15825$9b622d9e@news.freenet.de> <7cb20641-ab33-4818-a911-80c684cb9792@q77g2000hsh.googlegroups.com> <4775AC6B.8070109@v.loewis.de> <1310677e-51ec-49f2-9709-196dcc4e1ac9@e4g2000hsg.googlegroups.com> Message-ID: <477BF54E.7090000@v.loewis.de> > Thanks a lot Martin and Marc for the really great explanations! I was > wondering if it would be reasonable to imagine a utility that will > determine whether, for a given encoding, two byte strings would be > equivalent. But that is much easier to answer: s1.decode(enc) == s2.decode(enc) Assuming Unicode's unification, for a single encoding, this should produce correct results in all cases I'm aware of. If the you also have different encodings, you should add def normal_decode(s, enc): return unicode.normalize("NFKD", s.decode(enc)) normal_decode(s1, enc) == normal_decode(s2, enc) This would flatten out compatibility characters, and ambiguities left in Unicode itself. > But I think such a utility will require *extensive* > knowledge about many bizarrities of many encodings -- and has little > chance of being pretty! See above. > In any case, it goes well beyond the situation that triggered my > original question in the first place, that basically was to provide a > reasonable check on whether round-tripping a string is successful -- > this is in the context of a small utility to guess an encoding and to > use it to decode a byte string. This utility module was triggered by > one that Skip Montanaro had written some time ago, but I wanted to add > and combine several ideas and techniques (and support for my usage > scenarios) for guessing a string's encoding in one convenient place. Notice that this algorithm is not capable of detecting the ISO-2022 encodings - they look like ASCII to this algorithm. This is by design, as the encoding was designed to only use 7-bit bytes, so that you can safely transport them in Email and such (*) If you want to add support for ISO-2022, you should look for escape characters, and then check whether the escape sequences are among the ISO-2022 ones: - ESC ( - 94-character graphic character set, G0 - ESC ) - 94-character graphic character set, G1 - ESC * - 94-character graphic character set, G2 - ESC + - 94-character graphic character set, G3 - ESC - - 96-character graphic character set, G1 - ESC . - 96-character graphic character set, G2 - ESC / - 96-character graphic character set, G3 - ESC $ - Multibyte ( G0 ) G1 * G2 + G3 - ESC % - Non-ISO-2022 (e.g. UTF-8) If you see any of these, it should be ISO-2022; see the Wiki page as to what subset may be in use. G0..G3 means what register the character set is loaded into; when you have loaded a character set into a register, you can switch between registers through ^N (to G1), ^O (to G0), ESC n (to G2), ESC o (to G3) (*) > http://gizmojo.org/code/decodeh/ > > I will be very interested in any remarks any of you may have! >From a shallow inspection, it looks right. I would have spelled "losses" as "loses". Regards, Martin (*) For completeness: ISO-2022 also supports 8-bit characters, and there are more control codes to shift between the various registers. From sromero at gmail.com Thu Jan 10 03:14:42 2008 From: sromero at gmail.com (Santiago Romero) Date: Thu, 10 Jan 2008 00:14:42 -0800 (PST) Subject: How to get memory size/usage of python object References: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> Message-ID: <257fa40e-5a6d-4e1d-aefd-9439a182391c@f47g2000hsd.googlegroups.com> > Would you care to precisely define "REAL size" first? Consider: > > >>> atuple = (1, 2) > >>> mylist = [(0, 0), atuple] > > Should sizeof(mylist) include sizeof(atuple) ? No, I'm talking about "simple" lists, without REFERENCES to another objects into it. I mean: lists = [ 0, 1, 2, 3, 4, (1,2), 3] or array = [ [0,0,0,0,0,0,0], [1,1,1,1,2,1,2], ... ] Maybe I can "pickle" the object to disk and see the filesize ... :-? From PurpleServerMonkey at gmail.com Tue Jan 29 21:40:40 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Tue, 29 Jan 2008 18:40:40 -0800 (PST) Subject: Web Interface Recommendations References: <45040839-8b1f-40af-9ef5-1be274c6e95f@z17g2000hsg.googlegroups.com> <80d6ce9f-6c8b-412d-a261-cfe480bd0c3b@e10g2000prf.googlegroups.com> Message-ID: On Jan 30, 12:55 pm, Graham Dumpleton wrote: > On Jan 30, 12:00 pm, PurpleServerMonkey > wrote: > > > > > Looking for suggestions on the best framework to use for an > > applications web interface. > > > The user interface doesn't need immediate feedback and will be cross > > platform so a web interface is a good solution especially since it > > operates as a client\server system and not standalone. > > > However there's just so many frameworks to choose from it's very > > confusing. After a lot of reading it sounds like OSE or Cherrypy might > > be good options but I don't have any real world experience with these > > frameworks to go by. > > > Basically the interface won't be the application, it's used to input > > data and have the application act on it. It's going to have a > > Postgresql database and a number of service\daemon processes that do > > the actual work. It will also contain some form based information for > > keeping track of requests etc. and grow to a fair number of screens > > over time. > > > Given the above what framework would you recommend? > > Surprised you even looked at OSE. Although OSE has some features for > building HTML based web interfaces, they are very basic and not really > intended for building major stuff. OSE can still be useful for writing > backend applications, but would very much suggest you use just the XML- > RPC interfaces it provides to talk into its distributed messaging > system and service agent framework. > > If you use the XML-RPC interfaces then you can use a proper web > application framework for doing the actual HTML based user interface > front end. At that point you can choose any of the major frameworks, > such as Django, Pylons, TurboGears, CherryPy or web.py. > > Splitting the front end from the backend like this also means that > backend itself could be swapped out. Thus, instead of using OSE in the > backend, you could use simpler XML-RPC enabled Python applications, or > even use Pyro. In other words, you avoid intertwining code for front > end and backend too much, thus perhaps making it easier to change and > adapt as it grows. > > Graham Thanks Graham, decoupling the user interface and backend logic makes sense and definitely the way I want to go. Out of the major frameworks is there one that stands out as being particularly well suited for what I'm trying to do? Django and CherryPy are on the short list so I'll give them a detailed look although Pylons does sound rather interesting as well. From winterbeef at gmail.com Wed Jan 30 12:04:26 2008 From: winterbeef at gmail.com (beef) Date: Wed, 30 Jan 2008 09:04:26 -0800 (PST) Subject: MySQLdb and column names Message-ID: <38210bf5-afa4-4e5f-a66b-a6682278251e@l1g2000hsa.googlegroups.com> Hello all, I am using MySQLdb 1.2.2 and have a question about the construction of the dictionary keys of a result set. Here is an example query, from which you may intuit some of the structure of the tables: SELECT shots.*, users.*, sequences.*, jobs.* FROM shots LEFT JOIN users ON users.id=shots.user_id INNER JOIN sequences ON sequences.id=shots.sequence_id INNER JOIN jobs AS j ON j.id=sequences.job_id WHERE shots.id=%s 1. The 'users' table has a column named 'id', as do all the other tables. 2. I define my cursor as a 'DictCursor' so that my results are dictionaries 3. The 'shots' id has the key name of 'id', while all the -other- 'id's have key names of the form: ".id" I would prefer to have the key names consistent, so that event the "shots" fields have key names of the form "
.id" Is this possible? Thanks in advance! -- Wellington From grante at visi.com Sat Jan 26 00:02:43 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 26 Jan 2008 05:02:43 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <13plfnjgsfspr48@corp.supernews.com> On 2008-01-26, over at thepond.com wrote: > Once a python py file is compiled into a pyc file, I can disassemble > it into assembler. No you can't. It's not native machine code. It's byte code for a virtual machine. > Assembler is nothing but codes, which are combinations of 1's > and 0's. You can't read a pyc file in a hex editor, but you > can read it in a disassembler. NO YOU CAN'T. > It doesn't make a lot of sense to me right now, That's because IT'S NOT MACHINE CODE. > but if I was trying to trace through it with a debugger, That wouldn't work. > the debugger would disassemble it into assembler, > not python. You can "disassemble" random bitstreams into assembler. That doesn't make it a useful thing to do. [Honestly, I think you're just trolling.] -- Grant Edwards grante Yow! Yow! Is this sexual at intercourse yet?? Is it, visi.com huh, is it?? From steve at REMOVE-THIS-cybersource.com.au Fri Jan 18 17:43:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 18 Jan 2008 22:43:17 -0000 Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> <7xve5ruiam.fsf@ruckus.brouhaha.com> Message-ID: <13p2as5plhbpm74@corp.supernews.com> On Fri, 18 Jan 2008 09:58:57 -0800, Paul Rubin wrote: > David Sanders writes: >> The data files are large (~100 million lines), and this code takes a >> long time to run (compared to just doing wc -l, for example). > > wc is written in carefully optimized C and will almost certainly run > faster than any python program. However, wc -l doesn't do the same thing as what the Original Poster is trying to do. There is little comparison between counting the number of lines and building a histogram, except that both tasks have to see each line. Naturally the second task will take longer compared to wc. ("Why does it take so long to make a three-tier wedding cake? I can boil an egg in three minutes!!!") -- Steven From charles_hans at yahoo.com Wed Jan 30 16:40:35 2008 From: charles_hans at yahoo.com (Charles_hans) Date: Wed, 30 Jan 2008 13:40:35 -0800 (PST) Subject: Q: paramiko/SSH/ how to get a remote host_key In-Reply-To: References: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> <9077ed27-e9b1-47ca-b30e-918e3b50d517@e4g2000hsg.googlegroups.com> <15189222.post@talk.nabble.com> Message-ID: <15192764.post@talk.nabble.com> Thank you, Guilherme. I was running demo_sftp.py included in paramiko download. It seems that '.ssh/known_hosts' should be the path of a key file on my working directory on local PC. (Right?) I replaced this with 'test_rsa.key' in C:\paramiko-1.7.2\demos and this did not generate error. But the returned host_keys is empty. I traced the code to 'hostkeys.py' and found that the line e = HostKeyEntry.from_line(line) always retuned None. This means that my remote host name should have been in this key file. (Right?) I am very new to paramiko. How to create such a key file (with my remote host name)? Should I also load this key file into the remote server? Please advise. Thanks! Charles 1/30 2008/1/30, Charles_hans : > > I tried to get what host_key has been aquired after AutoPolicy is set. I > added the following code just before client.close() in rosty's final code: > > try: > host_keys = > paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) > except IOError: > try: > host_keys = > paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) > except IOError: > print '*** Unable to open host keys file' > > I still got 'Unable to open host keys file'. Can you tell me how to get > the > remote host_key under this situation? Thanks! > > Charles > 1/30/2008 Hey Charles, If you take a look on your code, you will see that you are catching IOError. So the problem you are noticing is related to I/O failing such as non-existent file. Be sure to check if '~/.ssh/known_hosts' exists, if the first try fails, check if "~/ssh/known_hosts" exists then (since you are trying to access that file). Cheers, > by rosty Jan 21, 2008; 08:43am : > > Thank you! Now it works and the code looks like this: > > import paramiko > import base64 > from paramiko import AutoAddPolicy, SSHClient > > client = paramiko.SSHClient() > client.set_missing_host_key_policy(AutoAddPolicy()) > client.connect('hostIP', username='uname', password='pass') > stdin, stdout, stderr = client.exec_command('ls') > for line in stdout: > print '... ' + line.strip('\n') > > client.close() -- View this message in context: http://www.nabble.com/Q%3A-paramiko-SSH--how-to-get-a-remote-host_key-tp14996119p15192764.html Sent from the Python - python-list mailing list archive at Nabble.com. From 42flicks at gmail.com Thu Jan 31 17:23:50 2008 From: 42flicks at gmail.com (Mike D) Date: Fri, 1 Feb 2008 11:23:50 +1300 Subject: Design question - Sharing of single object by multiple processes In-Reply-To: References: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> <47A1AC61.7080007@holdenweb.com> <2b54d4370801311206j457ef51cm33d2a2420b11e688@mail.gmail.com> <2b54d4370801311208s4af458cdp8cea665a04c3bd7a@mail.gmail.com> Message-ID: <2b54d4370801311423y52904ed9o1e26ac98dced45c6@mail.gmail.com> Steve, You raise some very good (and obvious) issues I did'nt consider. I'll look further into this sort of implementation as I'm quite interested. I suppose a compromise could be to load the objects from a pickle, that may have issues in terms of updating the pickle perhaps, though it would be much safer. I'll continue to investigate, thanks for your input. On Feb 1, 2008 11:00 AM, Steve Holden wrote: > Mike D wrote: > > Steve, > > > > Thanks for the response. My question really comes down to, as you > > suggested, premature optimization. > > > > It is more for my own understanding than a current practical use. > > > > If an object is loaded into memory and other threads(or processes) can > > recieve a pointer to this location, would this not be more efficient > > than to load a new one for every unique request? Wouldn't a method such > > as this prevent bottle necks in a read heavy environment? > > > In theory, yes. In practice there are problems, since modern operating > systems are explicitly designed to place barriers between the address > spaces of different processes. > > Even supposing you could access another Python process's space freely > you would then have issues like: > * does a reference from a foreign process add to an > object's reference count? > * if so, what happens if the foreign process terminates > without decrementing the reference count > * otherwise waht happens if the owning process disposes of > the object while the foreign process stil wants to refer > to it. > > I don't wish to be unkind, but these are well-known issues of > inter-process information sharing, and while superficial solutions can > seem easy, the more you think about and work on them the more obvious it > becomes that these are hard problems in the general case. > > Which will hopefully at least encourage you that you are addressing the > real issues of computing, even though there's a lot to do. > > > [...] > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lasses_weil at klapptsowieso.net Thu Jan 17 16:28:11 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 17 Jan 2008 22:28:11 +0100 Subject: bags? 2.5.x? In-Reply-To: References: <478bbae6$0$25383$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <478fc86f$0$25382$9b4e6d93@newsspool4.arcor-online.net> Dan Stromberg wrote: > The author of the bag class said that he was planning to submit bags for > inclusion in 2.5 - is there a particular reason why they didn't go in? > I wouldn't know. Not enough convincing use cases, I guess. Fools ;) > I keep finding a need for bags. In the past, I've done this sort of > thing with dictionaries, but it's much nicer to have a bag class, and of > course it's better to have it in the standard library than to slurp it > into this, that and the other project. > Then again, it is only one class. Also, if I may be so bold, why wouldn't a simple list fit your needs (other than performance, of course)? /W From tdelaney at avaya.com Thu Jan 10 17:49:30 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 11 Jan 2008 06:49:30 +0800 Subject: ISO Python example projects (like in Perl Cookbook) In-Reply-To: Message-ID: You know you've been working at a large company for too long when you see that subject and think "ISO-certified Python?" Tim Delaney From bkasterm at gmail.com Wed Jan 30 17:01:25 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Wed, 30 Jan 2008 14:01:25 -0800 (PST) Subject: Fw: Undeliverable Message References: Message-ID: On Jan 25, 5:05?am, Matthew_WAR... at bnpparibas.com wrote: > Hallo pyPeople, > > I wrote a little snippet of code that takes a list representing some > 'digits', and according to a list of symbols, increments the digits through > the symbol list. > > so for example, > > digits=["a","a","a"] > symbols=["a","b","c"] > > increment(digits,symbols) repeatedly would return digits as > > aab > aac > aba > abb > abc > aca > > etc.. > > Heres the code > > def increment(digits,symbols): > ? ? ? ? overflow=True > ? ? ? ? digitpos=-1 > ? ? ? ? while overflow and -digitpos<=len(digits): > ? ? ? ? ? ? ? ? digitsymbolindex=symbols.index(digits[digitpos]) > ? ? ? ? ? ? ? ? if digitsymbolindex==len(symbols)-1: > ? ? ? ? ? ? ? ? ? ? ? ? overflow=True > ? ? ? ? ? ? ? ? ? ? ? ? digits[digitpos]=symbols[0] > ? ? ? ? ? ? ? ? ? ? ? ? digitpos=digitpos-1 > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? digits[digitpos]=symbols[digitsymbolindex+1] > ? ? ? ? ? ? ? ? ? ? ? ? overflow=False > ? ? ? ? return digits > > Now, this works. All good. It's nice and simple. ?I'm just wondering how > anyone else might approach it? I (not an expert at all) have only minor comments and one question: comments: why keep setting overflow to True, if you do not touch it will not change. digitpos -= 1 is easier to read in my mind question: Why first extract the indices and then compare (in your if statement), and why do you not just compare the symbols? Best, Bart From faber at linuxnj.com Fri Jan 11 22:36:05 2008 From: faber at linuxnj.com (Faber J. Fedor) Date: Fri, 11 Jan 2008 22:36:05 -0500 Subject: Newbie Q: modifying SQL statements In-Reply-To: <87d4s8ndz2.fsf@mulj.homelinux.net> References: <20080111013206.GA18259@neptune.faber.nom> <20080110225352.2c112555@bhuda.mired.org> <87d4s8ndz2.fsf@mulj.homelinux.net> Message-ID: <20080112033605.GC24213@neptune.faber.nom> On 12/01/08 00:23 +0100, Hrvoje Niksic wrote: > "Faber J. Fedor" writes: > > Does this '("" if not where...' syntax actually work? > > http://docs.python.org/whatsnew/pep-308.html C'mon! I'm in Day Two of learning Python. You can't expect me to be reading "What's New" docs already! :-) I did find it interesting that the page mentioned said "Guido van Rossum eventually chose a surprising syntax:". When I first saw the construct I thought "Oh, they borrowed that from Perl". :-) (Although you can't do the else part in Perl, it is a natural extension, IMO.) -- Regards, Faber Fedor -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From gagsl-py2 at yahoo.com.ar Sat Jan 26 13:21:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 26 Jan 2008 16:21:10 -0200 Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <690cb460-fa8a-49a1-a6fa-69cdf480a918@i3g2000hsf.googlegroups.com> <7xir1hznuu.fsf@ruckus.brouhaha.com> Message-ID: En Fri, 25 Jan 2008 17:50:17 -0200, Paul Rubin <"http://phr.cx"@NOSPAM.invalid> escribi?: > Nicko writes: >> # The next line is order O(n) in the number of chunks >> (line, fileindex) = min(mergechunks) > > You should use the heapq module to make this operation O(log n) instead. Or forget about Python and use the Windows sort command. It has been there since MS-DOS ages, there is no need to download and install other packages, and the documentation at http://technet.microsoft.com/en-us/library/bb491004.aspx says: Limits on file size: The sort command has no limit on file size. Better, since the OP only intents to extract lines starting with "zz", use the findstr command: findstr /l /b "zz" filename.exe would do the job. Why doing things more complicated than that? -- Gabriel Genellina From nyamatongwe+thunder at gmail.com Fri Jan 11 17:18:22 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 11 Jan 2008 22:18:22 GMT Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: Marty: > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) Another way to write this is data_out = [[]] * len(data_in) Neil From xena-die-kriegerprinzessin at gmx.de Fri Jan 25 10:16:34 2008 From: xena-die-kriegerprinzessin at gmx.de (Heiko Niedermeyer) Date: Fri, 25 Jan 2008 15:16:34 +0000 (UTC) Subject: How to create graphs an embed them in GUI? References: Message-ID: This is just a brief summary, how I'm trying to do it now. In case somone ever encouters a problem like this... For the 2D part, I'm going with matplotlib, which seems to do, what I want. The 3D is currently donw be vpython, which is not great, but sufficient... Maybe I will switch when I find something better... ;) Thanks anyway. From bignose+hates-spam at benfinney.id.au Wed Jan 30 00:33:23 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jan 2008 16:33:23 +1100 Subject: ISO with timezone References: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Message-ID: <87tzkvdgik.fsf@benfinney.id.au> "Nicholas F. Fabry" writes: > The constructor for class datetime has a method, .now() that returns > the current date and time, as a naive datetime object (i.e. no > tzinfo attached). It's not "the constructor for class 'datetime'" that has that method; rather, the class 'datetime' has that method. (If anything is "the constructor for class 'datetime'", it's the '__new__' method -- or, some might argue, the '__init__' method -- and that doesn't fit what you say above.) > Dates and Times are a bit ugly in Python. Don't be discouraged, but > you do need to understand them quite well to get bug-free code that > plays with them. This is unfortunately true. Native datetime support is improving, but slowly. -- \ "[T]he speed of response of the internet will re-introduce us | `\ to that from which our political systems have separated us for | _o__) so long, the consequences of our own actions." -- Douglas Adams | Ben Finney From duncan.booth at invalid.invalid Tue Jan 29 15:17:42 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Jan 2008 20:17:42 GMT Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> Message-ID: Berteun Damman wrote: > On Tue, 29 Jan 2008 09:23:16 -0800 (PST), attn.steven.kuo at gmail.com > wrote: >> If you're going to delete elements from >> a list while iterating over it, then do >> it in reverse order: > > Why so hard? Reversing it that way creates a copy, so you might as > well do: >>>> a = [ 98, 99, 100 ] >>>> for i, x in enumerate(a[:]): > ... if x == 99: del(a[i]) > ... print x Why so hard? >>> a = [ 98, 99, 100, 98, 99, 100 ] >>> for i, x in enumerate(a[:]): if x == 99: del(a[i]) >>> a [98, 100, 98, 99] oops! But: >>> a = [ 98, 99, 100, 98, 99, 100 ] >>> last_idx = len(a) - 1 >>> for i, x in enumerate(a[::-1]): if x == 99: del(a[last_idx - i]) >>> a [98, 100, 98, 100] Reversing it works. Your code doesn't. From deets at nospam.web.de Wed Jan 16 10:36:36 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jan 2008 16:36:36 +0100 Subject: list classes in package References: <5cff1706-3bb1-4a54-bccb-175ff384788c@q77g2000hsh.googlegroups.com> Message-ID: <5v6mk4F1kbh4nU1@mid.uni-berlin.de> Dmitry wrote: > Hi All, > > I've trying to develop one Python application, and > neet to solve one problem. I need to list all classes defined in one > package (not module!). > > Could anybody please show me more convinient (correct) way to > implement this? Look at the module inspect and it's predicates. Something like for name in dir(module_or_package): if inspect.isclass(getattr(module_or_package, name)): print "%s is a class" % name Diez From mr.cerutti at gmail.com Fri Jan 4 15:53:06 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 4 Jan 2008 15:53:06 -0500 Subject: fastest method to choose a random element In-Reply-To: <51302a8c0801041247jc9a6c8ej10e346b8357bacdc@mail.gmail.com> References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <51302a8c0801041247jc9a6c8ej10e346b8357bacdc@mail.gmail.com> Message-ID: <51302a8c0801041253q5fd2e2c8tf301d037ad118e01@mail.gmail.com> On Jan 4, 2008 3:47 PM, Neil Cerutti wrote: > On Jan 4, 2008 2:55 PM, wrote: > > > Hello, > > This is a question for the best method (in terms of performance > > only) to choose a random element from a list among those that satisfy > > a certain property. > > > > A simple approach is: > > > > import random > > def random_pick(a_list,property): > > '''Returns a random element from a list that has the property > > > > Returns None if no element has the property > > ''' > > random.shuffle(a_list) > > for i in a_list: > > if property(i): return i > > > I'm pretty sure you don't want to use a destructive random_pick function. > You'll have to shuffle a copy instead to avoid that problem. > I thought of another one based on combining the above with the linear search idea, minimizing the calls to the predicate function. indexes = range(len(a_list)) random.shuffle(indexes) for ix in indexes: if predicate(a_list[ix]) return a_list[ix] raise ValueError('no matching element in list') -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Jan 21 03:53:10 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Jan 2008 09:53:10 +0100 Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> Message-ID: Santiago Romero wrote: > I'm trying to sort both lists so that they end like this: > > preferences = [10, 20, 30] > hosts = [ "mx1.domain.com", "mx2.domain.com", > "anotherhost.domain.com" ] > > I want to sort hosts list depending on the numeric order of > "preferences". The following relies on undocumented (I hope) behaviour: >>> preferences = [10, 30, 20] >>> hosts = [ "mx1.domain.com", "anotherhost.domain.com", "mx2.domain.com"] >>> hosts.sort(key=lambda x, p=iter(preferences).next: p()) >>> preferences.sort() >>> hosts ['mx1.domain.com', 'mx2.domain.com', 'anotherhost.domain.com'] >>> preferences [10, 20, 30] Don't do it, use a list of tuples as already suggested. Peter From fredrik at pythonware.com Fri Jan 4 09:17:22 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 15:17:22 +0100 Subject: how to build a dict including a large number of data In-Reply-To: References: Message-ID: wanzathe wrote: > i have a binary file named test.dat including 9600000 records. > the record format is int a + int b + int c + int d > i want to build a dict like this: key=int a,int b values=int c,int d > i choose using bsddb and it takes about 140 seconds to build the dict. you're not building a dict, you're populating a persistent database. storing ~70000 records per second isn't that bad, really... > what can i do if i want to make my program run faster? > or is there another way i can choose? why not just use a real Python dictionary, and the marshal module for serialization? From fredrik at pythonware.com Thu Jan 10 15:20:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 21:20:42 +0100 Subject: XML+Logs to Latex. XSLT? In-Reply-To: References: Message-ID: Florencio Cano wrote: > I'm thinking about implementing a script in Python to do this task. I > have a XML log and logs from other programs. My aim is to do a report > about all this information. I'm thinking in using Python to transform > the plain logs to XML and combine them with the XML document I have > and later use some kind of XSLT to transform the whole XML document to > Latex. What do you think about that? I have not worked with XSLT > before and I don't know if this would be a correct use. > How will you do the job? why not do it all in Python? From dwbear75 at gmail.com Wed Jan 16 22:12:08 2008 From: dwbear75 at gmail.com (DwBear75) Date: Wed, 16 Jan 2008 19:12:08 -0800 (PST) Subject: examples of logger using smtp Message-ID: I am hoping to find some simple examples of how to create a logger instance using smtphandler. I don't want to create a separate ini file. I just want to sent the smtphost, from, to right in the code when I instantiate the logger. I can't seem to find simple code on how to do this. Any pointers ? From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 19:11:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 00:11:23 -0000 Subject: encrypting python modules References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> Message-ID: <13og1dbe4qcfs2b@corp.supernews.com> On Fri, 11 Jan 2008 10:44:36 +0100, Paul Sijben wrote: > Hello, > > this question has come by repeatedly in several guises over the past > years but has never been solved in this forum as far as I have been able > to Google. > > However since so many people are asking the question, I hope someone has > made a solution and is willing to share it. > > The problem: I have a client-server app written in python. I want to > make sure that the client is not: > 1) destabilized by users accidentally or on purpose dropping python > files in the path (after which calling the helpdesk will not be useful) > 2) extended with "new features" without me knowing about it (again > resulting in calls to my helpdesk...) How often do these things *actually* happen? Of those that actually do it, how many are clueless enough that when they run into problems they blame you for it? (And remember that you won't even find out about the non-clueless ones.) -- Steven From bernard.desnoues at univ-paris1.fr Mon Jan 21 09:24:34 2008 From: bernard.desnoues at univ-paris1.fr (Bernard Desnoues) Date: Mon, 21 Jan 2008 15:24:34 +0100 Subject: stdin, stdout, redmon In-Reply-To: References: <4794a5e3$0$9014$426a74cc@news.free.fr> Message-ID: <4794ab22$0$19179$426a74cc@news.free.fr> Rolf van de Krol a ?crit : > According to various tutorials this should work. > > > |import sys > data = sys.stdin.readlines() > print "Counted", len(data), "lines."| > > > Please use google before asking such questions. This was found with only > one search for the terms 'python read stdin' > > Rolf > > Bernard Desnoues wrote: >> Hi, >> >> I've got a problem with the use of Redmon (redirection port monitor). >> I intend to develop a virtual printer so that I can modify data sent >> to the printer. >> Redmon send the data flow to the standard input and lauchs the Python >> program which send modified data to the standard output (Windows XP >> and Python 2.5 context). >> I can manipulate the standard output. >> >> "import sys >> sys.stdout.write(data)" >> >> it works. >> But how to manipulate standard input so that I can store data in a >> string or in an object file ? There's no "read" method. >> >> "a = sys.stdin.read()" doesn't work. >> "f = open(sys.stdin)" doesn't work. >> >> I don't find anything in the documentation. How to do that ? >> Thanks in advance. >> >> Bernard Desnoues >> Librarian >> Biblioth?que de g?ographie - Sorbonne Hello Rolf, I know this code because I have search a solution ! Your google code doesn't work ! No attribute "readlines". >>> import sys >>> data = sys.stdin.readlines() Traceback (most recent call last): File "", line 1, in data = sys.stdin.readlines() AttributeError: readlines From pyth0nc0d3r at gmail.com Sat Jan 19 14:12:17 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Sat, 19 Jan 2008 13:12:17 -0600 Subject: Okay I got a question regarding Tkinter and Labels Message-ID: Okay I've created a script and basically when I loop through a folder it is supposed to change the Label everytime it updates a file then again it doesn't do nothing but shows the last file edited, whats the best way to loop through files and display that file name in a Label's text without skipping to the last one when the loop is finished? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Mon Jan 28 06:52:01 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 28 Jan 2008 13:52:01 +0200 Subject: Using a dict as if it were a module namespace. Message-ID: <001001c861a4$48e42060$03000080@hendrik> On Sunday 27 January 2008 09:45, Steven D'Aprano wrote: > I have a problem which I think could be solved by using a dict as a > namespace, in a similar way that exec and eval do. > > When using the timeit module, it is very inconvenient to have to define > functions as strings. A good alternative is to create the function as > normal, and import it: > > def myfunc(x, y): > return x+y > > timeit.Timer("myfunc(59, 60)", "from __main__ import myfunc").timeit() > > > Not only is this an easy idiom to follow, but myfunc can live in another > module: just replace __main__ with the module name. > > Now, I'm trying to build a suite of tests to use with timeit. I have a > bunch of tests which I've created as dicts: > > test_suite= [dict(x=59, y=60), dict(x=-1, y=-2)] This is probably the wrong answer: test_suite = [(59,60),(-1,-2)] for test in test_suite: x,y = test Then do the magic with x and y - Hendrik From tenax.raccoon at gmail.com Mon Jan 21 09:55:40 2008 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 21 Jan 2008 06:55:40 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: On Jan 21, 12:00 am, Albert Hopkins wrote: > On Sun, 20 Jan 2008 20:16:18 -0800, Paddy wrote: > > I am definitely NOT a floating point expert, but I did find this: > >http://en.wikipedia.org/wiki/IEEE_754r#min_and_max > > > P.S. What platform /Compiler are you using for Python? > > Linux with GCC 4 > > -a Please note that NaN's are very funky and platform dependent. They depend on their underlying platform's C library for creation and display. On windows, "float('nan')" will cause an exception, as there are no valid string representations of NAN that can be converted to the special floating point value. Also, if you manage to create a nan under Windows, it displays as "1.#QNAN". Infinite values are also problematic. In almost all cases, it is far better to avoid infinite and NaN values. --Jason From paddy3118 at googlemail.com Wed Jan 9 16:25:47 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 13:25:47 -0800 (PST) Subject: alternating string replace: Extended input (Long). References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <3a5c974a-676f-4401-a8bb-06a537b1015c@v4g2000hsf.googlegroups.com> Message-ID: <59decf52-d923-4433-bcad-8c41fc1e13d3@v4g2000hsf.googlegroups.com> On Jan 9, 8:47 pm, bearophileH... at lycos.com wrote: > Donald 'Paddy' McCarthy: > > [... lots and lots and lots of tests...] > > C'mon Paddy, where are the timings too? Are you becoming lazy > lately? ;-) > > Bear bugs, > bearophile Get it right before you get it fast. But what is 'right'. From israelu at elbit.co.il Sun Jan 20 05:51:21 2008 From: israelu at elbit.co.il (iu2) Date: Sun, 20 Jan 2008 02:51:21 -0800 (PST) Subject: Hebrew in idle ans eclipse (Windows) References: <478ee0c0$0$4589$9b622d9e@news.freenet.de> <86ea4c94-f4b3-4bc3-9b2a-bc9b5c182264@i12g2000prf.googlegroups.com> <478FBC1A.4080201@v.loewis.de> Message-ID: <65cc5058-efd1-43bf-91ea-1062daa1fa62@v46g2000hsv.googlegroups.com> On Jan 17, 10:35?pm, "Martin v. L?wis" wrote: > > import pymssql > > > con = > > pymssql.connect(host='192.168.13.122',user='sa',password='',database='tempd?b') > > cur = con.cursor() > > cur.execute('select firstname, lastname from [users]') > > lines = cur.fetchall() > > > print lines > > > or > > > print lines[0] > > > 'lines' is a list containing tuples of 2 values, for firstname and > > lastname. The names areHebrewand their code looks different when I'm > > runnig it fromIDLEthan when running it from Windows shell or > >eclipse, as I described in my first post. > > Ok. Please understand that there are different ways to represent > characters as bytes; these different ways are called "encodings". > > Please also understand that you have to make a choice of encoding > every time you represent characters as bytes: if you read it from a > database, and if you print it to a file or to the terminal. > > Please further understand that interpreting bytes in an encoding > different from the one they were meant for results in a phenomenon > called "moji-bake" (from Japanese, "ghost characters"). You get > some text, but it makes no sense (or individual characters are incorrect). > > So you need to find out > a) what the encoding is that your data have in MySQL > b) what the encoding is that is used when printing inIDLE > c) what the encoding is that is used when printing into > ? ?a terminal window. > > b) and c) are different on Windows; the b) encoding is called > the "ANSI code page", and c) is called the "OEM code page". > What the specific choice is depends on your specific Windows > version and local system settings. > > As for a: that's a choice somebody made when the database > was created; I don't know how to figure out what encoding > MySQL uses. > > In principle, rather than doing > > ? print lines[0] > > you should do > > ? print lines[0].decode("").encode("") > > when printing to the console. Furtenately, you can also write > this as > > ? print lines[0].decode("") > > as Python will figure out the console encoding by itself, but > it can't figure out the MySQL encoding (or atleast doesn't, > the way you use MySQL). > > Regards, > Martin- Hide quoted text - > > - Show quoted text - Thanks for the detailed explanation. I'll try that. From bignose+hates-spam at benfinney.id.au Wed Jan 23 19:14:32 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 24 Jan 2008 11:14:32 +1100 Subject: Increment Variable Name References: <87myqw87lt.fsf@benfinney.id.au> Message-ID: <87abmw84gn.fsf@benfinney.id.au> Pablo Ziliani writes: > Ben Finney wrote: > > This has a very bad code smell (...) > > > > \ `\ _o__) Ben Finney > > That is forcefulness. > (sorry, couldn't resist) I suspect that's a comment on my online nickname, "bignose", and talking about code smells. Nevertheless, it's probably a good opportunity to point out that "code smell" is a term with a specific, useful meaning in programming. -- \ "[Freedom of speech] isn't something somebody else gives you. | `\ That's something you give to yourself." -- _Hocus Pocus_, Kurt | _o__) Vonnegut | Ben Finney From ian at neustyle.com Mon Jan 7 11:13:12 2008 From: ian at neustyle.com (Soviut) Date: Mon, 7 Jan 2008 08:13:12 -0800 (PST) Subject: list property fires get on append References: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com> <930rlf.mc3.ln@127.0.0.1> Message-ID: <04953c5a-dd24-4e80-aed6-0fbb18218759@v4g2000hsf.googlegroups.com> On Jan 6, 11:36 am, Carl Banks wrote: > On Sun, 06 Jan 2008 00:31:13 -0800, Soviut wrote: > > I figured that an append would be treated as a set since I'm adding to > > the list. But what you say makes sense, although I can't say I'm happy > > with the behaviour. Is there any way I can get the append to fire a > > set? I'm thinking of properties from my C# background where i believe > > that manipulation such this would be considered a set. > > You'd have to have to hook into the container object itself to detect the > modification. This might be pretty workable for you since it's an > internal object. Basically, instead of using a list, use a special list- > like object that notifies it's owner when it changes. Here's a simple > example to point you in the right direction: > > class NotifierList(list): > def __init__(self,*args,**kwargs): > super(NotifierList,self).__init__(*args,**kwargs) > self.watchers = [] > def add_watcher(self,watcher): > self.watchers.append(watcher) > def _notify_watchers(self): > for watcher in self.watchers: > watcher.object_changed(self) > def append(self,value): > super(NotifierList,self).append(value) > self._notify_watchers() > # override all other mutating calls, including __setitem__ > # left as exercise > > class Hierarchy(object): > def __init__(self): > self.children = NotifierList() > self.children.add_watcher(self) > def object_changed(self,obj): > print "self.children modified" > # no need to make children a property then > # unless you want to trap rebinding it to new object also > > A couple other minor suggestions: > > print is a statement, not a function. You should write > > print "GETTING" > > not > > print("GETTING") > > The latter works, but it will cease to work if you want to print more > than one thing. Note that print is scheduled to become a function in > Python 3.0, but for now it's a statement. > > Based on the name of your class and typical usage, I'm guessing that you > probably want _children to be an instance attribute rather than a class > attribute, so I redid it that way, but .) > > P.S. Is calling a method called "firing" in C#? > > Carl Banks Thanks for the help, there's a lot to digest there but I realized that I was having issues with _children being a class attribute when I noticed every single instance had the same _children list. I've since moved things into my __init__ method. Basically the reason I needed to use a property was to run a private helper method that sets references to the parent and root nodes of my hierarchy. Since I was simply appending to my children list, there was no callback to tell the container to process the children. And no, calling a method is not necessarily called "firing", but I've been using the term a lot recently when dealing with events so it seemed appropriate. From mayasmith1 at gmail.com Sat Jan 19 06:20:42 2008 From: mayasmith1 at gmail.com (mayasmith1 at gmail.com) Date: Sat, 19 Jan 2008 03:20:42 -0800 (PST) Subject: All about DOGS Message-ID: Hi How much do you know about Dogs? http://www.dogsinfos.com From cokofreedom at gmail.com Wed Jan 23 04:03:14 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 23 Jan 2008 01:03:14 -0800 (PST) Subject: HTML parsing confusion References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> <50269e4a-af44-4d73-b6cb-c42af6b5164d@e10g2000prf.googlegroups.com> <5vmkiiF1nadr7U1@mid.uni-berlin.de> <6cc92ad4-4448-4254-8c01-a04b0c035117@d21g2000prf.googlegroups.com> Message-ID: > The pages I'm trying to write this code to run against aren't in the > wild, though. They are static html files on my company's lan, are very > consistent in format, and are (I believe) valid html. Obvious way to check this is to go to http://validator.w3.org/ and see what it tells you about your html... From cokofreedom at gmail.com Wed Jan 16 12:14:50 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 16 Jan 2008 09:14:50 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> <478c868a$0$7040$426a34cc@news.free.fr> <5c0a472a-5ed6-4b34-9685-42f9a0a4145e@k39g2000hsf.googlegroups.com> <13osdhmkb1jpvd9@corp.supernews.com> Message-ID: <1a1ed037-9af0-4b43-a46a-ed91c9bb205f@q77g2000hsh.googlegroups.com> On Jan 16, 5:52 pm, Ed Jensen wrote: > cokofree... at gmail.com wrote: > > A lecturer gave me the perfect answer to the question of speed. > > > "You have two choices when it comes to programming. Fast code, or fast > > coders." > > "You're either with us, or against us." > > George W. Bush > > My understanding is that while CPython performance won't be winning > any awards anytime soon, Jython and IronPython are pretty impressive > performers. > > Disclaimer: I haven't personally used Jython or IronPython. Indeed, it is as Paul Rudin said; "It's more a continuum than that suggests. The tricky bit is deciding in each situation where you should be on the continuum." From robert.kern at gmail.com Tue Jan 22 03:09:39 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 22 Jan 2008 02:09:39 -0600 Subject: what's this instance? In-Reply-To: <47959D11.3040806@block.duxieweb.com> References: <47959D11.3040806@block.duxieweb.com> Message-ID: J. Peng wrote: > def safe_float(object): > try: > retval = float(object) > except (ValueError, TypeError), oops: > retval = str(oops) > return retval > > x=safe_float([1,2,3,4]) > print x > > > The code above works well.But what's the instance of "oops"? where is it > coming from? I'm totally confused on it.thanks. The line except (ValueError, TypeError), oops: will trap ValueError and TypeError exceptions. The actual exception object will be assigned to the name "oops". -- 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 python.list at tim.thechases.com Fri Jan 18 13:06:56 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 18 Jan 2008 12:06:56 -0600 Subject: Efficient processing of large nuumeric data file In-Reply-To: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <4790EAC0.2000800@tim.thechases.com> > for line in file: The first thing I would try is just doing a for line in file: pass to see how much time is consumed merely by iterating over the file. This should give you a baseline from which you can base your timings > data = line.split() > first = int(data[0]) > > if len(data) == 1: > count = 1 > else: > count = int(data[1]) # more than one repetition Well, some experiments I might try: try: first, count = map(int, data) except: first = int(data[0]) count = 1 or possibly first = int(data[0]) try: count = int(data[1]) except: count = 0 or even # pad it to contain at least two items # then slice off the first two # and then map() calls to int() first, count = map(int,(data + [1])[:2]) I don't know how efficient len() is (if it's internally linearly counting the items in data, or if it's caching the length as data is created/assigned/modifed) and how that efficiency compares to try/except blocks, map() or int() calls. I'm not sure any of them is more or less "pythonic", but they should all do the same thing. > if first in hist: # add the information to the histogram > hist[first]+=count > else: > hist[first]=count This might also be written as hist[first] = hist.get(first, 0) + count > Is a dictionary the right way to do this? In any given file, there is > an upper bound on the data, so it seems to me that some kind of array > (numpy?) would be more efficient, but the upper bound changes in each > file. I'm not sure an array would net you great savings here, since the upper-bound seems to be an unknown. If "first" has a known maximum (surely, the program generating this file has an idea to the range of allowed values), you could just create an array the length of the span of numbers, initialized to zero, which would reduce the hist.get() call to just hist[first] += count and then you'd iterate over hist (which would already be sorted because it's in index order) and use those where count != 0 to avoid the holes. Otherwise, your code looks good...the above just riff on various ways of rewriting your code in case one nets you extra time-savings per loop. -tkc From Max_Abrahams at brown.edu Thu Jan 31 14:34:48 2008 From: Max_Abrahams at brown.edu (Abrahams, Max) Date: Thu, 31 Jan 2008 14:34:48 -0500 Subject: best(fastest) way to send and get lists from files Message-ID: <4A1A35F8C85B294296F1911569C1137D034B5B57@MAIL2.AD.Brown.Edu> I've looked into pickle, dump, load, save, readlines(), etc. Which is the best method? Fastest? My lists tend to be around a thousand to a million items. Binary and text files are both okay, text would be preferred in general unless there's a significant speed boost from something binary. thanks From hniksic at xemacs.org Fri Jan 11 09:41:20 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 11 Jan 2008 15:41:20 +0100 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> Message-ID: <877iiga0hb.fsf@mulj.homelinux.net> Bruno Desthuilliers writes: > fact 1: CPython compiles source code to byte-code. > fact 2: CPython executes this byte-code. > fact 3: Sun's JDK compiles source code to byte-code. > fact 4: Sun's JDK executes this byte-code. > > Care to prove me wrong on any of these points ? Don't bother: you > can't. Fact 4 is misleading because it is only one option available to Sun's JDK. Sun's JDK is also capable of transforming the byte-code to native code and letting the processor execute that instead of the original byte code, and that is where the most significant speed increase comes from. Most importantly, it does so automatically, by default, with no programmer intervention or configuration, and with 100% compatibility, so it doesn't compare well to Python accelerators like psyco. From grflanagan at yahoo.co.uk Fri Jan 18 07:32:36 2008 From: grflanagan at yahoo.co.uk (grflanagan) Date: Fri, 18 Jan 2008 04:32:36 -0800 (PST) Subject: How to detect a remote webpage is accessible? (in HTTP) References: Message-ID: On Jan 18, 6:22 am, "??" wrote: > Howdy, all, > I want to use python to detect the accessibility of website. > Currently, I use urllib > to obtain the remote webpage, and see whether it fails. But the problem is that > the webpage may be very large; it takes too long time. Certainly, it > is no need to download > the entire page. Could you give me a good and fast solution? > Thank you. > -- > ShenLei http://groups.google.com/group/comp.lang.python/browse_frm/thread/bbac82df3d64d48e/da75e45a8da2f6c1 From dannox at gmail.com Tue Jan 22 01:46:03 2008 From: dannox at gmail.com (whatazor) Date: Mon, 21 Jan 2008 22:46:03 -0800 (PST) Subject: Calculate net transfer rate without dummy file Message-ID: Hi, how can I calulate transfer rate to a host , without using a file ? can ping module (written by Jeremy Hylton) be useful ? From workitharder at gmail.com Wed Jan 2 21:20:01 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 2 Jan 2008 18:20:01 -0800 (PST) Subject: Information about including module? References: Message-ID: <211fd5f6-c2c6-43ee-9ce3-56eeba3583fc@h11g2000prf.googlegroups.com> On Jan 2, 4:52 pm, bukzor wrote: > Is there any way to print the docstring of the including module? I'd > like to be able to do something like the following > > file one.py: > > "some docstring" > include two > > file two.py: > from magicmodule import getincluder > print getincluder().__doc__ > > Running one.py would print the docstring. > > Thanks! > Buck Answered my own question: def getimporter(): from inspect import stack for info in stack(): text = info[4][0].split() if 'import' in text and text[0] in ('from', 'import'): return info[0].f_locals print getimporter()['__doc__'] This is a simplified version of the recipe here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473823 From guptaabhishek1983 at gmail.com Sat Jan 12 02:31:03 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Fri, 11 Jan 2008 23:31:03 -0800 (PST) Subject: Successfully created installer for python2.5 compiled code under .net2005 Message-ID: Hi group i have created an installer for python 2.5 compiled under .NET 2005. Any one looking for help on doing this feel free to contact me at abhishek at medspheretech.com or guptaabhishek1983 at gmail.com From musiccomposition at gmail.com Thu Jan 3 13:38:08 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 3 Jan 2008 10:38:08 -0800 (PST) Subject: reassign to builtin possible !? References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> Message-ID: On Jan 3, 7:04 am, Bernhard Merkle wrote: > Hi there, > > I am reading Learning Python 3e from Mark Lutz and just found out that > reassigning to builtins is possible. > What is the reason, why Python allows this ? IMO this is very risky > and can lead to hard to find errors. I don't think it's a huge issue. In fact, I think it's a feature. For example, it'd be extremely issue to reassign open, if you wanted to implement a virtual file system, and you couldn't modify the module the used open. > (see also Learning Python 3e, Chapter 16, Page 315) > > >>> True > True > >>> False > False > >>> True = 1 > >>> True > 1 > >>> True = 0 > >>> True > > 0 > > TIA, > Berni From bj_666 at gmx.net Sun Jan 27 05:36:17 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jan 2008 10:36:17 GMT Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <690cb460-fa8a-49a1-a6fa-69cdf480a918@i3g2000hsf.googlegroups.com> <7xir1hznuu.fsf@ruckus.brouhaha.com> <13polidj792mi26@corp.supernews.com> Message-ID: <603551F1oh17aU2@mid.uni-berlin.de> On Sun, 27 Jan 2008 10:00:45 +0000, Grant Edwards wrote: > On 2008-01-27, Stefan Behnel wrote: >> Gabriel Genellina wrote: >>> use the Windows sort command. It has been >>> there since MS-DOS ages, there is no need to download and install other >>> packages, and the documentation at >>> http://technet.microsoft.com/en-us/library/bb491004.aspx says: >>> >>> Limits on file size: >>> The sort command has no limit on file size. >> >> Sure, since no-one can ever try it with more than 640k, it's >> easy to state that there is no limit. :) > > Huh? I used DOS sort to sort files much bigger than 640K. That was an allusion to a quote misattributed to Bill Gates about DOS: 640K ought to be enough for anybody. http://en.wikiquote.org/wiki/Bill_Gates#Misattributed Ciao, Marc 'BlackJack' Rintsch From gregturn at mindspring.com Tue Jan 8 18:39:04 2008 From: gregturn at mindspring.com (Goldfish) Date: Tue, 8 Jan 2008 15:39:04 -0800 (PST) Subject: Spring Python 0.3.2 is release! Message-ID: <758abcf7-43f4-4fc8-9dcb-57474563e14c@t1g2000pra.googlegroups.com> Spring Python (http://springpython.python-hosting.com) version 0.3.2 was released yesterday. It contains a patch to an error discovered 12/19/2007 in XmlApplicationContext, that broke when PROTOTYPE scoping was used. Test cases have been updated to detect this bug, and in turn the correction was made in released. Get it while its hot! From lasses_weil at klapptsowieso.net Sun Jan 27 18:39:02 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 28 Jan 2008 00:39:02 +0100 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> Message-ID: <479d1616$0$9100$9b4e6d93@newsspool2.arcor-online.net> Dustan wrote: >> Well, you save one or two lines per class. Not enough in my >> opinion. > > Are you referring to the alternate syntax or to the decorator? Either > way, you could be saving 4 or 5 or more lines, if you have enough > arguments. OK, but then again, every decent IDE should give you the tools to write an automation for that. Not that I don't like the idea of auto-assignment, but, you know ... /W From victorsubervi at gmail.com Fri Jan 4 10:17:09 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 4 Jan 2008 11:17:09 -0400 Subject: How Does This Static Variable Work? Message-ID: <4dc0cfea0801040717u9bc67ccr80447dc375502445@mail.gmail.com> Hi; I read this example somewhere, but I don't understand it <:-) Can someone please explain how static variables work? Or recommend a good how-to? import random def randomwalk_static(last=[1]): # init the "static" var(s) rand = random.random() # init a candidate value if last[0] < 0.1: # threshhold terminator return None # end-of-stream flag while abs(last[0]-rand) < 0.4: # look for usable candidate print '*', # display the rejection rand = random.random() # new candidate last[0] = rand # update the "static" var return rand TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From christopher.saunter at durham.ac.uk Fri Jan 25 07:04:45 2008 From: christopher.saunter at durham.ac.uk (c d saunter) Date: Fri, 25 Jan 2008 12:04:45 +0000 (UTC) Subject: Windows AVIFile problems Message-ID: Hi All, I'm trying to access individual video frames of an AVI file from within Python 2.4 or 2.5 under Windows XP. I have found this example code here for that does exactly what I want, using the windows avifile.dll but I am unable to find the AVIFile.h header... http://mail.python.org/pipermail/image-sig/2002-February/001748.html An alternative is to call into avifile.dll dynamically using ctypes, however under both Python 2.4 and 2.5 the following error happens: >>> from ctypes import * >>> windll.AVIFile Traceback (most recent call last): File "", line 1, in windll.AVIFile File "C:\Python25\lib\ctypes\__init__.py", line 415, in __getattr__ dll = self._dlltype(name) File "C:\Python25\lib\ctypes\__init__.py", line 340, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 193] %1 is not a valid Win32 application or WinDLL('c:/windows/system/AVIFILE.DLL') # same for .../system32/AVI... Traceback (most recent call last): File "", line 1, in windll.AVIFile File "C:\Python25\lib\ctypes\__init__.py", line 415, in __getattr__ dll = self._dlltype(name) File "C:\Python25\lib\ctypes\__init__.py", line 340, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 193] %1 is not a valid Win32 application This suggests that the dll is corrupt? However if I download and run the exe's from this example of a VB program calling the DLL, they work: http://www.shrinkwrapvb.com/avihelp/avihelp.htm I'm open to suggestions about the specific problems above or other ways of getting at the frames. I've tried pymedia but it also has issues. Regards Chris Saunter From ask at me Thu Jan 17 14:30:19 2008 From: ask at me (alf) Date: Thu, 17 Jan 2008 13:30:19 -0600 Subject: how django discovers changed sources In-Reply-To: References: <18udndZmKMfMNhLanZ2dnUVZ_rzinZ2d@comcast.com> Message-ID: <18udndFmKMfgMRLanZ2dnUVZ_rzinZ2d@comcast.com> Jeff wrote: > That is the behavior of the development server. When you are writing > your application, you don't want to have to manually restart the > server every time you change a file. On apache it obviously doesn't > do that. thx for clarification, but still I am curious how it is done under the hood. it really impressed me ... From electronixtar at gmail.com Thu Jan 17 15:26:20 2008 From: electronixtar at gmail.com (est) Date: Thu, 17 Jan 2008 12:26:20 -0800 (PST) Subject: dbus-python for windows References: <194e7fee-728a-48eb-9f51-1e272ecca838@j20g2000hsi.googlegroups.com> Message-ID: <553d4985-fd94-4556-9cfa-e09ecc7227a7@s19g2000prg.googlegroups.com> There exists a pre-compiled binary for dbus it was primary wirtten for deluge win32 port http://www.slurdge.org/deluge-on-windows There exists a pre-compiled binary for dbus it was primary wirtten for deluge win32 port http://www.slurdge.org/deluge-on-windows On Jan 15, 9:14?pm, Suraj Barkale wrote: > est gmail.com> writes: > > > I am trying to port Scribes to Windows, > > Hi there like minded fellow > > > sourceforge.net/projects/windbus/? but it not for Python, so how could > > I install dbus module for Windows Python 2.5 ? > > I have also started to dabble in windbus-python for the sake of Scribes. I have > following observations: > 1. I don't have Visual Studio 2003 (required for compiling Python 2.x modules) > so alternative is to use MinGW. Follow instructions athttp://js.cx/~justin/mingwYou can skip the GtkGLExt part. > 2. Checkout windbus from sourceforge, apply the patch (patch.exe doesn't work on > Vista. Rename it to p4tch.exe) > 3. Follow the windows build instructions for windbus. It gets compiled correctly > :). > 4. dbus-python has dependency on dbus AND dbus-glib. But all my attempts of > getting dbus-glib to build have failed so for. > 5. dbus-python looks at wrong place for python headers, this is very easy to > connect and if we can get dbus-glib to build then we are there :) > > I will keep banging my head & let you know once I have cracked it (or the > dbus-python :) > > P.S. Please CC me in your reply as I am not on the list. > > Regards, > Suraj From pavlovevidence at gmail.com Fri Jan 11 00:34:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 11 Jan 2008 00:34:07 -0500 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: On Thu, 10 Jan 2008 22:36:56 -0500, Marty wrote: > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) > > This caused me to wonder why Python does not have a "foreach" statement > (and also why has it not come up in this thread)? I realize the topic > has probably been beaten to death in earlier thread(s), but does anyone > have the short answer? Most languages that have "foreach" use it the same way Python uses "for". The reason they use "foreach" instead of plain "for" is often because they have a separate for statement that mimic C's for. Perhaps you're wondering why there is no syntax for looping a given number of times. (Languages that have this feature, e.g., Ada, often to use "repeat" as the keyword.) 1. Looping a fixed number of times is quite uncommon. 2. A syntax for it buys you almost nothing. Carl Banks From marek.rocki at wp.pl Sun Jan 20 15:06:57 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sun, 20 Jan 2008 12:06:57 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Message-ID: Nice challenge! I came up with something like this: def find_repr(target, numbers): org_reprs = dict((number, str(number)) for number in numbers) curr_reprs = org_reprs while target not in curr_reprs: old_reprs, curr_reprs = curr_reprs, {} for x in old_reprs: for y in org_reprs: repr_x, repr_y = old_reprs[x], old_reprs[y] curr_reprs[x + y] = '(%s)+(%s)' % (repr_x, repr_y) curr_reprs[x - y] = '(%s)-(%s)' % (repr_x, repr_y) curr_reprs[x * y] = '(%s)*(%s)' % (repr_x, repr_y) if y <> 0 and x % y == 0: curr_reprs[x // y] = '(%s)/(%s)' % (repr_x, repr_y) curr_reprs.update(old_reprs) return curr_reprs[target] print '21 =', find_repr(21, [2, 3, 5]) print '923 =', find_repr(923, [7, 8, 50, 8, 1, 3]) Unfortunately, this yields solutions that are a bit lispish (as in 'lots of superfluous parentheses' in the result). Nothing a simple regex or two wouldn't fix ;-) And the solution found would be minimal not with respect to the string length, but rather to the number of operations to be performed. Apart from that, I find it quite elegant. I'd like to know if it has any flaws. Regards, Marek From mwm-keyword-python.b4bdba at mired.org Fri Jan 11 02:19:38 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 02:19:38 -0500 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <20080111021938.69734ca4@bhuda.mired.org> On Fri, 11 Jan 2008 01:48:43 -0500 Marty wrote: > Mike Meyer wrote: > >> This caused me to wonder why Python does not have a "foreach" statement (and > >> also why has it not come up in this thread)? I realize the topic has probably > >> been beaten to death in earlier thread(s), but does anyone have the short answer? > > > > But I'm curious - what's the difference between the "foreach" you have > > in mind and the standard python "for"? > For example, I thought the python "equivalent" of perl's foreach might be: No, python's equivalent of Perl's foreach is "for". I.e. foreach $var (@list) does the same thing as Python's for var in list (except Perl gets the scoping right). Maybe you're thinking of Perls "default variable" feature (I don't know what else to call it), which implicitly uses $_ as a variable in any number of places if you fail to provide a variable? So that you can say: foreach (@list) and apparently not have to use a variable, except it implicitly uses $_. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From nagle at animats.com Thu Jan 17 14:28:26 2008 From: nagle at animats.com (John Nagle) Date: Thu, 17 Jan 2008 11:28:26 -0800 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. Message-ID: <478FAC5A.50206@animats.com> It's possible to use "pickle" for interprocess communication over pipes, but it's not straightforward. First, "pickle" output is self-delimiting. Each dump ends with ".", and, importantly, "load" doesn't read any characters after the "." So "pickle" can be used repeatedly on the same pipe, and one can do repeated message-passing this way. This is a useful, but undocumented, feature. It almost works. Pickle's "dump" function doesn't flush output after dumping, so there's still some data left to be written. The sender has to flush the underlying output stream after each call to "dump", or the receiver will stall. The "dump" function probably ought to flush its output file. It's also necessary to call Pickle's "clear_memo" before each "dump" call, since objects might change between successive "dump" calls. "Unpickle" doesn't have a "clear_memo" function. It should, because if you keep reusing the "Unpickle" object, the memo dictionary fills up with old objects which can't be garbage collected. This creates a memory leak in long-running programs. Then, on Windows, there's a CR LF problem. This can be fixed by launching the subprocess with proc = subprocess.Popen(launchargs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) Failure to do this produces the useful error message "Insecure string pickle". Binary "pickle" protocol modes won't work at all in this situation; "universal newline" translation is compatible, not transparent. On Unix/Linux, this just works, but the code isn't portable. Incidentally, in the subprocess, it's useful to do sys.stdout = sys.stderr after setting up the Pickle objects. This prevents any stray print statements from interfering with the structured Pickle output. Then there's end of file detection. When "load" reaches an end of file, it properly raises EOFError. So it's OK to do "load" after "load" until EOFerror is raised. "pickle" and "cPickle" seem to be interchangeable in this application, so that works. It's a useful way to talk to a subprocess, but you need to know all the issues above to make it work. John Nagle From paddy3118 at googlemail.com Sun Jan 20 23:21:50 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 20 Jan 2008 20:21:50 -0800 (PST) Subject: dynamic type variable References: Message-ID: <7814f8ab-4a3d-4a0d-901e-3ff4a7d8e050@c4g2000hsg.googlegroups.com> On Jan 21, 2:37 am, "J. Peng" wrote: > Python's variable is dynamic type,is it? > But why this can't work? > > >>> 3 + 'a' > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > So I see the number 3 can't be converted to string type automacially. Hi, You are probably confusing Dynamic typing with Weak typing. Python is both dynamically and strongly typed. Perl is both dynamically and weakly typed. It is Perls weak typing that allows automatic conversion between dissimilar types. See: http://en.wikipedia.org/wiki/Type_system - Paddy. From gherzig at fmed.uba.ar Mon Jan 28 12:59:42 2008 From: gherzig at fmed.uba.ar (gherzig at fmed.uba.ar) Date: Mon, 28 Jan 2008 15:59:42 -0200 (ARST) Subject: sharing objects between classes In-Reply-To: <479e0c3b$0$1158$426a74cc@news.free.fr> References: <606aolF1pa0tfU2@mid.uni-berlin.de> <479e0c3b$0$1158$426a74cc@news.free.fr> Message-ID: <28425.190.55.98.232.1201543182.squirrel@www.webmail.fmed.uba.ar> > Diez B. Roggisch a ?crit : >> Gerardo Herzig wrote: >> >>> Hi all. Im wondering the way to share a database connection between >>> some >>> classes: >>> >>> So far, i came up with a simple class schema, where each class means >>> each different relation, i mean i have the follow classes >>> >>> class Database(object): >>> ## make the connection >>> self.conn = make_conn(....) >>> >>> class Table(object): >>> def get_fields: >>> .... >>> > (snip) >> >> Take a look at the sources of e.g. SQLObject and how they do it (in SO, >> the >> concept is called "HUB") >> > And while you're at it, take a look at SQLAlchemy too, and ask yourself > if you really need to roll your own solution !-) Yes, i dont need to reinvent the wheel, i know, it just seems like a pattern i will have to deal with, not just in this case. SQLObject seems like a big peace of code to read. At least to me (not that good programmer). I will take a look at SQLAlchemy, and see a little more. Thanks! Gerardo From http Sun Jan 20 12:13:20 2008 From: http (Paul Rubin) Date: 20 Jan 2008 09:13:20 -0800 Subject: HTTP POST uploading large files References: Message-ID: <7xwsq4zahb.fsf@ruckus.brouhaha.com> Wolfgang Draxinger writes: > Am I just blind for some urllib2/httplib feature, or some other > library? Or do I really have to fiddle around with sockets > myself (I hope not...). I did something like that by just opening a socket and writing the stuff with socket.sendall. It's only about 5 lines of code and it's pretty straightforward. From ggpolo at gmail.com Wed Jan 30 14:04:38 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 30 Jan 2008 17:04:38 -0200 Subject: Q: paramiko/SSH/ how to get a remote host_key In-Reply-To: <15189222.post@talk.nabble.com> References: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> <9077ed27-e9b1-47ca-b30e-918e3b50d517@e4g2000hsg.googlegroups.com> <15189222.post@talk.nabble.com> Message-ID: 2008/1/30, Charles_hans : > > I tried to get what host_key has been aquired after AutoPolicy is set. I > added the following code just before client.close() in rosty's final code: > > try: > host_keys = > paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) > except IOError: > try: > host_keys = > paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) > except IOError: > print '*** Unable to open host keys file' > > I still got 'Unable to open host keys file'. Can you tell me how to get the > remote host_key under this situation? Thanks! > > Charles > 1/30/2008 Hey Charles, If you take a look on your code, you will see that you are catching IOError. So the problem you are noticing is related to I/O failing such as non-existent file. Be sure to check if '~/.ssh/known_hosts' exists, if the first try fails, check if "~/ssh/known_hosts" exists then (since you are trying to access that file). Cheers, > > by Guilherme Polo Jan 21, 2008; 09:08am : > > 2008/1/21, DHR : > > Very nice =) > > Just an advice, you dont need to import base64. Method decode of > strings allows you to specify encoding as 'base64' to perform needed > operations. > > > by rosty Jan 21, 2008; 08:43am : > > Thank you! Now it works and the code looks like this: > > import paramiko > import base64 > from paramiko import AutoAddPolicy, SSHClient > > client = paramiko.SSHClient() > client.set_missing_host_key_policy(AutoAddPolicy()) > client.connect('hostIP', username='uname', password='pass') > stdin, stdout, stderr = client.exec_command('ls') > for line in stdout: > print '... ' + line.strip('\n') > > client.close() > -- > View this message in context: http://www.nabble.com/Q%3A-paramiko-SSH--how-to-get-a-remote-host_key-tp14996119p15189222.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From arnodel at googlemail.com Sat Jan 19 20:01:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 19 Jan 2008 17:01:03 -0800 (PST) Subject: Default attribute values pattern References: Message-ID: <12f1bfa5-09ec-4a4e-a21c-53250369f1a8@v29g2000hsf.googlegroups.com> On Jan 19, 11:02?pm, "David Tweet" wrote: > def Grab(argdict, key, default): > ? """Like argdict.get(key, default), but also deletes key from argdict.""" > ? if key in argdict: > ? ? retval = argdict["key"] > ? ? del(argdict[key]) > ? else: > ? ? retval = default > ? return retval > Dictionaries already have a method for this. It's called pop. It's a good idea to have a look at methods of builtin types before reimplementing the wheel! Grab(argdict, key, default) is argdict.pop(key, default) -- Arnaud From arkanes at gmail.com Fri Jan 11 10:40:49 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 11 Jan 2008 09:40:49 -0600 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> <478732db$0$19250$426a74cc@news.free.fr> <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> <4787762b$0$18777$426a74cc@news.free.fr> Message-ID: <4866bea60801110740o52aacdbdp89f3bf1222e135d7@mail.gmail.com> On Jan 11, 2008 9:10 AM, George Sakkis wrote: > On Jan 11, 8:59 am, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > George Sakkis a ?crit : > > > > > > > > > On Jan 11, 4:12 am, Bruno Desthuilliers > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > > > >> George Sakkis a ?crit : > > > > >>> On Jan 10, 3:37 am, Bruno Desthuilliers wrote: > > >>>> I fail to see how the existence of JIT compilers in some Java VM changes > > >>>> anything to the fact that both Java (by language specification) and > > >>>> CPython use the byte-code/VM scheme. > > >>> Because these "some Java VMs" with JIT compilers are the de facto > > >>> standard used by millions; > > >> Repeating an argument doesn't make it more true nor more relevant. Once > > >> again, this doesn't change anything to the fact exposed above. > > > > >>> the spec is pretty much irrelevant > > >> I mentionned this because this kind of choice is usually not part of the > > >> language spec but of a specific implementation. Java is AFAIK the only > > >> language where this implementation stuff is part of the spec. > > > > >>> (unless > > >>> you're a compiler writer or language theorist). > > >> I thought it was quite clear and obvious that I was talking about points > > >> relating to these fields. > > > > > No it wasn't, > > > > """ > > > or is Python just too slow > > > as an interpreted language > > > > Being "interpreted" is a quality of an implementation, not of a language. > > """ > > If that isn't clear enough what I'm talking about, then sorry but I > > can't help. > > Pedantic once again. For languages with a single (or practically > single) implementation such as Python, the average user couldn't care > less about the distinction. Your point might have more merit if > PyPy or IronPython or Jython enter the same league with CPython in > terms of usage. > > > > and besides the OP is most likely interested in these as > > > a simple user so the distinction between a spec and a de facto > > > standard implementation (such as JDK for Java and CPython for Python) > > > are almost pedantic if not misleading. > > > > I can live with being called "pedantic" - even I'm not sure whether > > correcting a wrong statement about CPython's execution model is pedantic > > or not. But I *still* fail to see how it could be "misleading", and > > *you* still fail to explain in which way it could be misleading. > > > > If your point is that saying that CPython uses a byte-code/VM scheme > > "just like Java" necessarily implies JIT compilation just because some > > JVM support this feature, then it would be time you pay more attention > > to what is effectively written. > > What three different people in this thread have been trying to tell > you but you seem to miss is that claiming CPython's VM "is just like > Java" is comparable to saying "a Yugo's car engine is just like a > BMW's" (or "humans are just like chimpanzees"), which for some value > of "just like" is technically correct but it's not what most people > would call an accurate statement. > The statement was in response to a claim that Python was slow because it is interpreted. This is a little like correcting someone who says that a Yugo is slow because it has a steam engine by telling that no, it's internal combustion, just like the BMW has. It's possible for this a claim like this to lead to a clarifying and informative discussion about JIT technology and how it improves Javas performance, and the use of corresponding techniques in Python. What we got instead was someone who felt some sort of juvenile urge to jump all over a what he thought of as a claim that Python is as fast as Java (which, of course, it sometimes is - the issue is more complicated than a sound bite). > > > We're not Lisp (yet ;-)), with > > > five major implementations and a dozen of minor ones. > > > > And ? In which way does it make the distinction between a language and a > > language implementation less true ? > > In the way that most plain users care (or not) about. Not that I think any of you care about anything except your e-penis at this point, but there is no reason to proscribe discussion to only what "plain users" want, even if the OP was such a person. From rndblnch at gmail.com Fri Jan 25 14:52:44 2008 From: rndblnch at gmail.com (rndblnch) Date: Fri, 25 Jan 2008 11:52:44 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> Message-ID: On Jan 25, 8:43 pm, petr.jakes.... at gmail.com wrote: > This means NO X-windows, NO GTK/Gnome, NO > computer mouse, on my machine (AMD Geode 500MHz CPU, VGA output). > > I would like to write some really light weighted GU interface. My > concept is to have just few user screens (about 10) controlled via 4 > or 5 HW buttons connected to the GPIO pins they are available on the > motherboard (the HW design and the SW concept of reading this buttons > is already solved). what you are looking for is curse :) http://docs.python.org/lib/module-curses.html http://www.ibm.com/developerworks/linux/library/l-python6.html renaud From bearophileHUGS at lycos.com Fri Jan 18 19:37:49 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 18 Jan 2008 16:37:49 -0800 (PST) Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> <54efb87e-5a54-42a4-adcc-3d05e03a4859@s8g2000prg.googlegroups.com> Message-ID: <2f5524f1-2a9b-4d04-8b37-15d20940da72@v4g2000hsf.googlegroups.com> Matt: > from collections import defaultdict > > def get_hist(file_name): > hist = defaultdict(int) > f = open(filename,"r") > for line in f: > vals = line.split() > val = int(vals[0]) > try: # don't look to see if you will cause an error, > # just cause it and then deal with it > cnt = int(vals[1]) > except IndexError: > cnt = 1 > hist[val] += cnt > return hist But usually in tight loops exceptions slow down the Python code, so this is quite faster (2.5 times faster with Psyco, about 2 times without, with about 30% of lines with a space in it): import psyco from collections import defaultdict def get_hist(file_name): hist = defaultdict(int) for line in open(file_name): if " " in line: pair = line.split() hist[int(pair[0])] += int(pair[1]) else: hist[int(line)] += 1 return hist psyco.bind(get_hist) It doesn't work if lines may contain spurious spaces... Bye, bearophile From python.list at tim.thechases.com Wed Jan 16 17:51:39 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 16 Jan 2008 16:51:39 -0600 Subject: Creating unique combinations from lists In-Reply-To: <001640bd-7759-423b-ad74-275b27e5d5d6@v4g2000hsf.googlegroups.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> <13osvl1j4pvka15@corp.supernews.com> <001640bd-7759-423b-ad74-275b27e5d5d6@v4g2000hsf.googlegroups.com> Message-ID: <478E8A7B.7020505@tim.thechases.com> >> for a in range(5): > ... >> for z in range(5): > > means the inner loop runs 5**26 times so perhaps it's not only > unpythonic but also uncomputable... only if you're impatient ;) yes, it was a contrived pessimal example. It could be range(2) to generate boolean-number sequences. I've done 2**26 loops in code before (well, it was on the way to 2**32, just to see how long it took to roll over and hit an error condition). The main emphasis was to show that there was a pattern unfolding that should have been translated into more pythonic code than just hard-coding nested loops. -tkc From ricaraoz at gmail.com Thu Jan 31 06:38:51 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 31 Jan 2008 08:38:51 -0300 Subject: REALLY simple xml reader In-Reply-To: References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> Message-ID: <47A1B34B.4090006@bigfoot.com> Ivan Illarionov wrote: >>>> from xml.etree import ElementTree as et >>>> from decimal import Decimal >>>> >>>> root = et.parse('file/with/your.xml') >>>> debits = dict((debit.attrib['category'], Decimal(debit.find('amount').text)) for debit in root.findall('debit')) >>>> >>>> for cat, amount in debits.items(): > ... print '%s: %s' % (cat, amount) > ... > food: 24.30 > car: 909.56 > medical: 188.20 > savings: 25 > withdrawal: 40 > supplies: 10.58 > clothes: 31.19 > Thanks Ivan, it seems a elegant API, and easy to use. I tried to play a little with it but unfortunately could not get it off the ground. I kept getting >>> root = et.fromstring(doc) Traceback (most recent call last): File "", line 1, in File "E:\Python25\lib\xml\etree\ElementTree.py", line 963, in XML parser.feed(text) File "E:\Python25\lib\xml\etree\ElementTree.py", line 1245, in feed self._parser.Parse(data, 0) ExpatError: XML or text declaration not at start of entity: line 2, column 0 But it's probably my lack of knowledge on the subject. Well, I guess there is no free ride and I'll take a look at ElementTree as soon as I have some spare time, looks promising. One last question. Am I right to believe "debit" would be an "et" object of the same class as "root"? THX From piet at cs.uu.nl Wed Jan 30 03:00:13 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 30 Jan 2008 09:00:13 +0100 Subject: starting programs from python script on windows References: Message-ID: >>>>> Benedict Verheyen (BV) wrote: >BV> Hi, >BV> i want to automate starting programs on my windows machine and i want >BV> to do it with windows. >BV> This is a sample script: >BV> from subprocess import Popen, PIPE >BV> import time >BV> print " Starting app 1" >BV> time.sleep(1) >BV> try: >BV> p1 = Popen(["C:\Program Files\Microsoft Office\OFFICE11\OUTLOOK.EXE"], Use raw strings or escape the \'s. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From mwm-keyword-python.b4bdba at mired.org Thu Jan 10 22:53:52 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 22:53:52 -0500 Subject: Newbie Q: modifying SQL statements In-Reply-To: <20080111013206.GA18259@neptune.faber.nom> References: <20080111013206.GA18259@neptune.faber.nom> Message-ID: <20080110225352.2c112555@bhuda.mired.org> On Thu, 10 Jan 2008 20:32:06 -0500 "Faber J. Fedor" wrote: > Hi all, > > I'm in the process of learning Python by writing a job queue program. > Nothing fancy, mind you, just read from a table, shell out to a program, > write back to the table. > > I'm working off of the tutorial listed here (amongst many places): > http://www.devx.com/dbzone/Article/22093 > > In my Jobs class I have: > > def __iter__(self): > "creates a data set, and returns an iterator (self)" > q = "select * from %s" % (self.name) > self._query(q) > return self # an Iterator is an object > # with a next() method > > def next(self): > "returns the next item in the data set, > or tells Python to stop" > r = self.dbc.fetchone() > if not r: > raise StopIteration > return r > > which works well, but what if I want to modify the __iter__ query? I > want to be able to do something like this (and I know this is not the > right syntax but you'll get my drift): > > > for job in jobs: print job # which the above code does > for job in jobs("status = running"): print job > for job in jobs("jobid = 4"): print job > > What's the pythonic way of doing this? Part of evaluating a for loop is that the expression in the for loop is evaluated, and it's __iter__ method is called. In your first line, the initial evaluation returns the jobs object, whose __iter__ method is then called, giving you the effect you want. For the second and third lines, the first evaluation tries to call the jobs object with the query as an argument. This fails, unless your jobs object is callable. If that returns the jobs object, __iter__ will be called - and thus use the query you want to avoid. So you need to have a __call__ method that leaves a token for __iter__ so it uses the proper query. This will do that, but I'm not sure I'd call it pythonic: _where = "" def __iter__(self): if not self._working: q = "select * from %s" % (self.name + where,) self._query(q) return self def __call__(self, where): self._where = " where %s" % (where,) return self def next(self): ... self._where = self.__class__._where # Put back class default raise StopIteration return r Personally, I think it would be more pythonic to not try and use two different APIs to walk the list of jobs (... One Way To Do it): def __call__(self, where=None): q = "select * from %s" % (self.name,) + ("" if not where else (" where %s" % where)) self._query(q) for r in self.dbc.iterresults() # I assume it has something like this yield r This should cause your first line to fail (possibly, depends on the exact nature of the class); it needs to be "for job in jobs(): print job". http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From google at mrabarnett.plus.com Wed Jan 9 18:45:59 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 9 Jan 2008 15:45:59 -0800 (PST) Subject: Learning Python via a little word frequency program References: <4784bbea$0$17616$426a74cc@news.free.fr> Message-ID: <01ff5c64-994f-4eb3-b634-55e64f3d01cb@k2g2000hse.googlegroups.com> On Jan 9, 12:19 pm, Bruno Desthuilliers wrote: > Andrew Savige a ?crit : > > > > > I'm learning Python by reading David Beazley's "Python Essential Reference" > > book and writing a few toy programs. To get a feel for hashes and sorting, > > I set myself this little problem today (not homework, BTW): > > > Given a string containing a space-separated list of names: > > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > > > produce a frequency table of names, sorted descending by frequency. > > then ascending by name. For the above data, the output should be: > > > kevin : 3 > > jock : 2 > > andrew : 1 > > bill : 1 > > fred : 1 > > freddy : 1 > > > Here's my first attempt: > > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > > freq = {} > > for name in names.split(): > > freq[name] = 1 + freq.get(name, 0) > > deco = zip([-x for x in freq.values()], freq.keys()) > > deco.sort() > > for v, k in deco: > > print "%-10s: %d" % (k, -v) > > > I'm interested to learn how more experienced Python folks would solve > > this little problem. > > For a one-shot Q&D script: > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > freqs = [(- names.count(name), name) for name in set(names.split())] > print "\n".join("%-10s : %s" % (n, -f) for f, n in sorted(freqs)) > [snip] That actually prints: kevin : 3 fred : 2 jock : 2 andrew : 1 bill : 1 freddy : 1 It says that "fred" occurs twice because of "freddy". names = "freddy fred bill jock kevin andrew kevin kevin jock" name_list = names.split() freqs = [(- name_list.count(name), name) for name in set(name_list)] print "\n".join("%-10s : %s" % (n, -f) for f, n in sorted(freqs)) From asmodai at in-nomine.org Sat Jan 12 17:12:22 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 12 Jan 2008 23:12:22 +0100 Subject: where do my python files go in linux? In-Reply-To: <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> <20080112113759.GJ75977@nexus.in-nomine.org> <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> Message-ID: <20080112221222.GL75977@nexus.in-nomine.org> Hi Jorgen, -On [20080112 16:14], Jorgen Bodde (jorgen.maillist at gmail.com) wrote: >I thought about that too. I just wonder why /usr/local/bin is always >empty and every .deb I install from a source (if it's from Ubuntu or >not) installs files in /usr/bin .. So I looked further and noticed >that most python files do reside in /usr/share/{appname} Well, it always seemed that many Linux distributions had to do things different from a file/directory hierarchy point of view and I never fully understood why. It always seemed a bit inspired by NIH-syndrome. But like I said, whatever works for you. >I would agree but it is not a site package I am trying to distribute, >but a wxPython application. I would not think my app belongs in the >python site packages dir. Mmm, I guess Python does not have a wonderful solution for this kind of scenario to be honest. The site-packages solution is one of the cleanest I can think of. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Only I can change my life. No one can do it for me... From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 10 08:05:29 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 10 Jan 2008 14:05:29 +0100 Subject: importing module conflict In-Reply-To: References: Message-ID: <47861812$0$8324$426a74cc@news.free.fr> Matias Surdi a ?crit : > Hi, > > Suppose I've a module named "urllib" and from it I need to import the > urllib module from the python standart library. > > ?how can I do this? > > The problem I found is that when I do: > > > import urrlib > > The imported module is itself, and not the one from the stdlib. > > Any idea? Yes : don't name your module 'urllib' !-) Else, you can play with sys.path before importing the std urllib, etc, etc... From tijotomjoy at gmail.com Thu Jan 10 21:15:56 2008 From: tijotomjoy at gmail.com (tijo) Date: Thu, 10 Jan 2008 18:15:56 -0800 (PST) Subject: Help needed Message-ID: Hi mate i need o do a python program to connect 2 systems using TCP/IP and UDP. Also i need to check the performance of these two protocols (how many bytes received and how much time took). I havent worked in python earlier and have no idea of this. Could someone pls help me. I created a program which can connect between 2 systems using these UDP and TCP/ IP protocols. I dont know how to check the rest like how many bytes send or how much time taken since this is part of my course work could someone please help me thanks in advance. tijo From paul.zorn at gmail.com Tue Jan 29 19:23:28 2008 From: paul.zorn at gmail.com (paul.zorn at gmail.com) Date: Tue, 29 Jan 2008 16:23:28 -0800 (PST) Subject: Telnet Program References: <777d417c-6016-4a44-8d5e-8de6bf604e9a@e6g2000prf.googlegroups.com> <87zluo77qr.fsf@merkury.smsnet.pl> Message-ID: On Jan 29, 12:27 pm, Rob Wolfe wrote: > "paul.z... at gmail.com" writes: > > I am having some issues writing a telnet program, using telnetlib. I > > am not sure if it is the telnet on the connections end or it is my > > program. > > > A little background, when I log in straight from the Linux Command > > prompt. The only thing I get is a blinking cursor. Then I type in my > > command 'FOO' enter then screen on the very next line returns 'OK', > > Then automatically puts the blinking cursor on the next line. Then > > when I want to quit the telnet session I hit CTRL+Z that takes me to > > telnet> then i type quit. > > > My Program currently looks like it connects. Because the last string > > that I get back that is not blank says: "Logged in successfully". > > > So my problem is that when I issue the command through tn.write("FOO > > \n"). Then do a tn.read_until('OK\n', 10). It gets returned nothing. I > > have also added tn.read_until('OK\n', 10).splitlines(). That is also > > returned blank. > > > I have tried various different newlines \n \r \r\n. All the > > documentation for telnet program that I am logging into says, use > > Carriage Return after each command. Nothing seems to get back the > > data. I am not sure if the Python telnet is looking for more of true > > command line like telnet>. > > Have you tried: tn.set_debuglevel(1) ? > > HTH, > Rob Thank You for the response. I did set the debugging level. I get back this. Telnet(192.168.2.75,5000): recv 'Password: ' Telnet(192.168.2.75,5000): send '*****\n' Telnet(192.168.2.75,5000): recv '\r\x00\r\nlogged in successfully\r\n' Telnet(192.168.2.75,5000): send '\n\n' Telnet(192.168.2.75,5000): Sending AT Telnet(192.168.2.75,5000): send 'AT\r\n' Telnet(192.168.2.75,5000): recv '\r\x00' So I on this command I should be getting back a 'OK' or 'ERROR'. But I am not seeing it. I feel like I am missing something. Not sure what would be the or is it the telnet application itself. Thanks, Paul From paddy3118 at googlemail.com Wed Jan 9 11:15:59 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 08:15:59 -0800 (PST) Subject: Collecting Rich Data Structures for students References: Message-ID: <8b4e7954-b666-4515-9ae2-821d979ebd7f@m34g2000hsf.googlegroups.com> On Jan 9, 6:52 am, Paddy wrote: > On Jan 9, 2:19 am, "kirby.ur... at gmail.com" > wrote: > > > > > Greetings Pythoneers -- > > > Some of us over on edu-sig, one of the community actives, > > have been brainstorming around this Rich Data Structures > > idea, by which we mean Python data structures already > > populated with non-trivial data about various topics such > > as: periodic table (proton, neutron counts); Monty Python > > skit titles; some set of cities (lat, long coordinates); types > > of sushi. > > > Obviously some of these require levels of nesting, say > > lists within dictionaries, more depth of required. > > > Our motivation in collecting these repositories is to give > > students of Python more immediate access to meaningful > > data, not just meaningful programs. Sometimes all it takes > > to win converts, to computers in general, is to demonstrate > > their capacity to handle gobs of data adroitly. Too often, > > a textbook will only provide trivial examples, which in the > > print medium is all that makes sense. > > > Some have offered XML repositories, which I can well > > understand, but in this case we're looking specifically for > > legal Python modules (py files), although they don't have > > to be Latin-1 (e.g. the sushi types file might not have a > > lot of romanji). > > > If you have any examples you'd like to email me about, > > kirby.ur... at gmail.com is a good address. > > > Here's my little contribution to the mix:http://www.4dsolutions.net/ocn/python/gis.py > > > Kirby Urner > > 4D Solutions > > Silicon Forest > > Oregon > > I would think there was more data out there formatted as Lisp S- > expressions than Python data-structures. > Wouldn't it be better to concentrate on 'wrapping' XML and CSV data- > sources? > > - Paddy. The more I think on it the more I am against this- data should be stored in programming language agnostic forms but which are easily made available to a large range of programming languages. If the format is easily parsed by AWK then it is usually easy to parse in a range of programming languages. - Paddy. From skip at pobox.com Thu Jan 3 18:10:32 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 3 Jan 2008 17:10:32 -0600 Subject: ctypes - pointer to array of structs? Message-ID: <18301.27496.174107.113205@montanaro.dyndns.org> (Is this the right place to ask ctypes questions? There's a mailing list but the last post to it seems to have been in November 2006.) Using ctypes I reference a structure which contains a pointer to an array of another structure: class SYMBOL(Structure): _fields_ = [("symbol", c_char_p), ("num", c_int), ("units", c_int), ("baseprice", c_int), ("active", c_int)] SYMBOL_PTR = POINTER(SYMBOL) class TABLE(Structure): _fields_ = [("map", SYMBOL_PTR), ("nsymbols", c_uint), ...] Effectively, TABLE.map is an array of TABLE.nsymbols SYMBOLS. How to I reference elements in that array? In C I would just treat TABLE.map like an array and index into it (for i=0; i< TABLE.nsymbols; i++) ...). This is data returned from a C library, not something I'm building in Python to pass into C. Thx, Skip From nyamatongwe+thunder at gmail.com Tue Jan 1 20:12:35 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 02 Jan 2008 01:12:35 GMT Subject: cloud computing (and python)? In-Reply-To: <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> Message-ID: <7yBej.30029$CN4.18224@news-server.bigpond.net.au> Cloud computing is mostly about scalability. You do not need to be concerned so much about low level infrastructure details such as purchasing servers, configuring and maintaining them, hiring space in data centres, linking up data centres, etc. It converts a lot of fixed costs into lower recurring costs so makes it easier for a start up with limited capital to start operating. There are Python libraries for accessing some of the cloud computing services and you can also host Python application code on some services that allow code execution. This includes services that can run arbitrary code on virtual machines such as EC2 and more restricted computational services like Hadoop which can run Jython. Neil From bj_666 at gmx.net Sat Jan 5 06:48:16 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 5 Jan 2008 11:48:16 GMT Subject: Point Object References: <4673edc3-b76c-4c6e-98f0-4f2becee930e@j20g2000hsi.googlegroups.com> Message-ID: <5u9940F1gsfmuU1@mid.uni-berlin.de> On Sat, 05 Jan 2008 03:37:33 -0800, pjmulla at googlemail.com wrote: > I am nes to python and need some help. Can anyone lead me in the > right direction to create and print a Point object, and then use id to > print the object's unique identifier. Translate the hexadecimal form > into decimal and confirm that they match. The right direction would be the tutorial in the docs I guess: http://docs.python.org/tut/tut.html What do you mean by the "hexadecimal form"? `id()` returns ordinary `int`\s and not strings. Ciao, Marc 'BlackJack' Rintsch From Russ.Paielli at gmail.com Mon Jan 28 05:42:31 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jan 2008 02:42:31 -0800 (PST) Subject: optional static typing for Python References: <479da584$0$25625$426a74cc@news.free.fr> Message-ID: <69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com> On Jan 28, 1:51 am, Bruno Desthuilliers wrote: > Russ P. a ?crit :> A while back I came across a tentative proposal from way back in 2000 > > for optional static typing in Python: > > (snip) > > > In any case, optional static typing in Python would help tremendously > > here. The hardest part of automated conversion of Python to a > > statically typed language is the problem of type inference. If the > > types are explicitly declared, that problem obviously goes away. > > (snip) > > > Note also that, while "static" type checking would be ideal, > > "explicit" typing would be a major step in the right direction > > Lord have mercy(tm). What is that supposed to mean? Oh, I almost forgot. I'm supposed to sit here and be polite while clueless dolts make wise cracks. Sorry, but I haven't yet mastered that level of self-control. I would just like to thank you for reminding me about what losers hang out perpetually on sites like this one, thinking they are in some kind of real "community." Being reminded of that will help prevent me from becoming such a loser myself. No, I didn't say that all the "regulars" here are losers, but you most certainly are. Do you have a job? How about a life? Have you ever been "with" a woman? How in the world is it that every time I come to this site, I see your sorry ass hanging around yet again? I can't even imagine how "pointless" your life must be if you have that much time to spend "hanging around" on comp.lang.python -- and being an a--hole to boot. Yeah, Lord have mercy -- on losers like you. And thanks for reminding me to quit wasting so much time here. I've been doing way too much of that lately. From martin at marcher.name Sun Jan 6 16:42:47 2008 From: martin at marcher.name (Martin Marcher) Date: Sun, 06 Jan 2008 22:42:47 +0100 Subject: Delete lines containing a specific word References: <183075.69960.qm@web57604.mail.re1.yahoo.com> Message-ID: On Sunday 06 January 2008 21:25 Francesco Pietra wrote: >> yes lines starting with a "#" are comments in python but that shouldn't >> be of concern for your input data. I don't quite get what you want >> here... > > Leaving the lines commented out would permit to resume them or at least > remeber what was suppressed. During trial and error set up of a > calculation one never knows exactly the outcome Ah I get it. To clarify: The character python uses as a comment has nothing to do with the character your data file uses as a comment. So you could of course use the "#" sign (which makes sense) You could also use "//" (C-Style) or whatever you like class CommentHelper(object): """Provides the necessary methods to comment or uncomment a line of text. """ # Yes I know this docstring is badly formatted but # I thought it's nicer to keep the indentation. def __init__(self, commentStr=None): if commentStr: self.commentStr = commentStr else: self.commentStr = "MY_SUPER_COMMENT_STRING" def commentLine(line): """Comments a line with the initialized comment string. """ return self.commentStr + " " + line def uncommentLine(line): """Uncomments a line iff it is preceded by the comment string. """ if line.startsWith(self.commentStr): return line[len(self.commentStr)].lstrip() raise Exception("Can't uncomment Line with no comment") You want to read up about: * (new style) classes * parameters with default values * docstrings * Exceptions That code is untested and may contain errors. I'll let the debugging be your task :) hope it points you to the right topics to read up about: http://docs.python.org/ http://docs.python.org/tut/tut.html http://www.diveintopython.org/ martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From ryszard.szopa at gmail.com Sat Jan 19 07:01:48 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Sat, 19 Jan 2008 04:01:48 -0800 (PST) Subject: writing Python in Emacs Message-ID: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> Hi All, I am a devoted Emacs user and I write a lot in Python. However, I never managed to get my Emacs configuration right for this purpose. There were some discussions on this, but the threads that show if I search the group are either old or not so relevant. I need the following features: 0) Of course, syntax coloring and so on... But this works good enough ootb in the two most popular python-modes. 1) Tab completion, ideally Slime like. That is, when there's not enough letters to unambiguously complete a symbol, I want it to show a buffer (w/o taking the focus) w/ the possible completions. In an ideal world, it would be able to complete fo.ba to foo.bar. I imagine this would require quite tight Emacs-Python integration. 2) Sending the toplevel definition (class or function) to the Python buffer. 3) Hints on function/method arguments. IDLE has this done nearly right, but the hints are a bit too intrusive for me. I would like to see them in the minibuffer. 4) (optional) I would like to see the definition of a function function or class by hitting M-. on its name. (I understand that this may be impossible for methods, as Emacs would have to automagically infer the type of the object). I have tried a couple of times both python-modes (the one shipped w/ Python and the one shipped w/ Emacs), pymacs and stuff like that... And, as I said, never got it right. But, maybe I just cannot find the way to configure it, and some configuration hints will be enough... As for other editors, I have tried Eclipse and Komodo... But I cannot get used to them. As for non-emacs stuff, the most comfortable for me has been IDLE. Cheers and thanks in advance, -- Richard From haraldarminmassa at gmail.com Tue Jan 8 10:33:54 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Tue, 8 Jan 2008 07:33:54 -0800 (PST) Subject: Intranet Project - Rad Or Waterfall References: <53490824-d95a-43ab-a405-e1249d4b396f@s12g2000prg.googlegroups.com> Message-ID: <82b745a7-875e-4368-b1a0-eee412892620@e10g2000prf.googlegroups.com> > Option 1 - Waterfall I recommend to google "waterfall". First hit after those beatifull pictures will be: http://en.wikipedia.org/wiki/Waterfall_model Within the first paragraph there is: """Ironically, Royce was actually presenting this model as an example of a flawed, non-working model.(Royce 1970)""" So I cannot fight the feeling of seeing the realisation of a xkcd- strip when reading about waterfall models... Harald From jpcc at nowhere.org Tue Jan 22 09:11:54 2008 From: jpcc at nowhere.org (John Carlyle-Clarke) Date: Tue, 22 Jan 2008 14:11:54 +0000 Subject: Problem with processing XML Message-ID: <13pbudgks88rcf3@corp.supernews.com> Hi. I'm new to Python and trying to use it to solve a specific problem. I have an XML file in which I need to locate a specific text node and replace the contents with some other text. The text in question is actually about 70k of base64 encoded data. I wrote some code that works on my Linux box using xml.dom.minidom, but it will not run on the windows box that I really need it on. Python 2.5.1 on both. On the windows machine, it's a clean install of the Python .msi from python.org. The linux box is Ubuntu 7.10, which has some Python XML packages installed which can't easily be removed (namely python-libxml2 and python-xml). I have boiled the code down to its simplest form which shows the problem:- import xml.dom.minidom import sys input_file = sys.argv[1]; output_file = sys.argv[2]; doc = xml.dom.minidom.parse(input_file) file = open(output_file, "w") doc.writexml(file) The error is:- $ python test2.py input2.xml output.xml Traceback (most recent call last): File "test2.py", line 9, in doc.writexml(file) File "c:\Python25\lib\xml\dom\minidom.py", line 1744, in writexml node.writexml(writer, indent, addindent, newl) File "c:\Python25\lib\xml\dom\minidom.py", line 814, in writexml node.writexml(writer,indent+addindent,addindent,newl) File "c:\Python25\lib\xml\dom\minidom.py", line 809, in writexml _write_data(writer, attrs[a_name].value) File "c:\Python25\lib\xml\dom\minidom.py", line 299, in _write_data data = data.replace("&", "&").replace("<", "<") AttributeError: 'NoneType' object has no attribute 'replace' As I said, this code runs fine on the Ubuntu box. If I could work out why the code runs on this box, that would help because then I call set up the windows box the same way. The input file contains an block which is what actually causes the problem. If you remove that node and subnodes, it works fine. For a while at least, you can view the input file at http://rafb.net/p/5R1JlW12.html Someone suggested that I should try xml.etree.ElementTree, however writing the same type of simple code to import and then write the file mangles the xsd:schema stuff because ElementTree does not understand namespaces. By the way, is pyxml a live project or not? Should it still be used? It's odd that if you go to http://www.python.org/ and click the link "Using python for..." XML, it leads you to http://pyxml.sourceforge.net/topics/ If you then follow the download links to http://sourceforge.net/project/showfiles.php?group_id=6473 you see that the latest file is 2004, and there are no versions for newer pythons. It also says "PyXML is no longer maintained". Shouldn't the link be removed from python.org? Thanks in advance! From robin at NOSPAMreportlab.com Sun Jan 20 08:58:12 2008 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sun, 20 Jan 2008 13:58:12 +0000 Subject: bitmap problem Message-ID: <47935374.3010203@jessikat.plus.net> I'm having trouble with defining a completely transparent bitmap for use as a stipple in a canvas import Tkinter Tkinter._default_root.tk.call('image','create', 'bitmap', 'gray0', '-background', '', '-data', '#define gray0_width 1\n#define gray0_height 1\nstatic char gray0_bits[] = {\n0x0\n};') print 'image names', self.tk.call('image','names') print 'image type', self.tk.call('image','type','gray0') self.canv.create_rectangle("10i", "10i", "13.5i", "13.5i", fill="blue",activestipple='gray0') the prints seem to indicate that the bitmap is defined, but the canvas create_rectangle fails image names gray0 image type bitmap Traceback (most recent call last): File "C:\Tmp\test.py", line 67, in main() File "C:\Tmp\test.py", line 62, in main top = PDFMU() File "C:\Tmp\test.py", line 59, in __init__ self.createWidgets() File "C:\Tmp\test.py", line 44, in createWidgets self.canv.create_rectangle("10i", "10i", "13.5i", "13.5i", fill="blue",activestipple='gray0') File "C:\Python\lib\lib-tk\Tkinter.py", line 2166, in create_rectangle return self._create('rectangle', args, kw) File "C:\Python\lib\lib-tk\Tkinter.py", line 2145, in _create *(args + self._options(cnf, kw)))) _tkinter.TclError: bitmap "gray0" not defined if I change gray0 to one of the predefined names eg gray12 then the create_rectangle succeeds. The tk manual seems to suggest I should be able to do this, but it doesn't seem to work even in tk. Is there a way to define a stipple without a file? -- Robin Becker From sipickles at hotmail.com Sat Jan 19 14:46:59 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Sat, 19 Jan 2008 19:46:59 +0000 Subject: del self? Message-ID: Hi, Just curious... What are the implications of a class member calling: del self is that what the __del__ method calls anyway? Thanks Simon -- Linux user #458601 - http://counter.li.org. From stanc at al.com.au Mon Jan 14 22:02:28 2008 From: stanc at al.com.au (Astan Chee) Date: Tue, 15 Jan 2008 14:02:28 +1100 Subject: Restart crashing modules in windows Message-ID: <478C2244.8040102@al.com.au> Hi, I have a python module that keeps on crashing with various windows errors (not BSOD but the less lethal windows XP popup ones). Now these are intentional and rather sporadic so I cant really solve it by attempting to fix the crash; rather what Im trying to do is make another module outside it that restarts this module every time it crashes. Is this possible? How do I do this? Or does one windows crash in one python module crash python entirely and I have to resort in an external program to restart python everytime it crashes? Thanks again for all the help. Astan From fredrik at pythonware.com Mon Jan 7 11:23:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 17:23:42 +0100 Subject: python syntax In-Reply-To: <633886.19582.qm@web45510.mail.sp1.yahoo.com> References: <633886.19582.qm@web45510.mail.sp1.yahoo.com> Message-ID: mpho raborife wrote: > Please help me get this syntax right: > > os.system("HCopy -T 1 -C" 'os.path.join(conf_dir, "/hcopy.conf")' "-S" > 'os.path.join(list_dir, "hcopy_list.txt")') instead of attempting to get your program working by random trial and error process, maybe you should spend an hour or two working through the examples in a nice tutorial? I'd recommend the first few chapters of Swaroop's "A Byte of Python". Make sure you read at least "Basics" and "Operators and Expressions" before returning to the task at hand: http://www.ibiblio.org/swaroopch/byteofpython/read/ From ggpolo at gmail.com Wed Jan 16 12:11:36 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 16 Jan 2008 15:11:36 -0200 Subject: paramiko In-Reply-To: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> Message-ID: 2008/1/16, Tarun Kapoor : > > > > > I am using paramiko to do an SFTP file transfer? I was able to connect to > the remote server using an SFTP client I have just to make sure that > username and password are working.. This is the code. > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > connection > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > sock.connect((hostname, port)) > > > > t = paramiko.Transport(sock) > > event = threading.Event() > > t.start_client(event) > > > > event.wait(15) > > > > if not t.is_active(): > > print 'SSH negotiation failed.' > > sys.exit(1) > > else: > > print "SSH negotiation sucessful" > > > > event.clear() > > > > t.auth_password(username=username, password=password,event=event) > > > > if not t.is_authenticated(): > > print "not authenticated" > > output: > > SSH negotiation successful > > not authenticated > > > > > > > > Tarun > > > > Waterstone Capital Management > > 2 Carlson Parkway, Suite 260 > > Plymouth, MN 55447 > > > > Direct: 952-697-4123 > > Cell: 612-205-2587 > Disclaimer This e-mail and any attachments is confidential and intended > solely for the use of the individual(s) to whom it is addressed. Any views > or opinions presented are solely those of the author and do not necessarily > represent those of Waterstone Capital Management, L.P and affiliates. If you > are not the intended recipient, be advised that you have received this > e-mail in error and that any use, dissemination, printing, forwarding or > copying of this email is strictly prohibited. Please contact the sender if > you have received this e-mail in error. You should also be aware that > e-mails are susceptible to interference and you should not assume that the > contents of this e-mail originated from the sender above or that they have > been accurately reproduced in their original form. Waterstone Capital > Management, L.P. and affiliates accepts no responsibility for information, > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > please verify the authenticity with the sender. > -- > http://mail.python.org/mailman/listinfo/python-list > You are missing an event.wait() after t.auth_password. Also, why are you passing this magic value "15" to event.wait() ? That parameter is passed to class _Verbose to indicate if debug messages should be displayed or not, so typical values would be 0/1 or False/True. -- -- Guilherme H. Polo Goncalves From sjmachin at lexicon.net Sat Jan 19 07:20:08 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jan 2008 04:20:08 -0800 (PST) Subject: Excess whitespace in my soup References: <48eb8853-91b3-4c43-8014-a0c624e4c6e7@t1g2000pra.googlegroups.com> Message-ID: On Jan 19, 11:00 pm, Fredrik Lundh wrote: > John Machin wrote: > > I'm happy enough with reassembling the second item. The problem is in > > reliably and correctly collapsing the whitespace in each of the above > > > fiveelements. The standard Python idiom of u' '.join(text.split()) > > won't work because the text is Unicode and u'\xa0' is whitespace > > > and would be converted to a space. > > would this (or some variation of it) work? > > >>> re.sub("[ \n\r\t]+", " ", u"foo\n frab\xa0farn") > u'foo frab\xa0farn' > > Yes, partially. Leading and trailing whitespace has to be removed entirely, not replaced by one space. Cheers, John From d.l.goldsmith at gmail.com Mon Jan 7 18:10:57 2008 From: d.l.goldsmith at gmail.com (dgoldsmith_89) Date: Mon, 7 Jan 2008 15:10:57 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python References: Message-ID: On Jan 7, 2:54 pm, "mensana... at aol.com" wrote: > On Jan 7, 4:37 pm, dgoldsmith_89 wrote: > > > Can anyone point me to a downloadable open source English dictionary > > suitable for programmatic use with python: I'm programming a puzzle > > generator, and I need to be able to generate more or less complete > > lists of English words, alphabetized. Thanks! DG > > www.puzzlers.orghas numerous word lists & dictionarys in text > format that can be downloaded. I recommend you insert them into > some form of database. I have most of them in an Access db and > it's 95 MB. That's a worse case as I also have some value-added > stuff, the OSPD alone would be a lot smaller. > > Sorry for my ignorance: I can query an Access DB w/ standard SQL queries (and this is how I would access it w/ Python)? DG From jimgardener at gmail.com Mon Jan 28 00:56:59 2008 From: jimgardener at gmail.com (jimgardener) Date: Sun, 27 Jan 2008 21:56:59 -0800 (PST) Subject: getting values from cache References: <480b367b-e5c4-4018-a968-8c146555dbdd@v29g2000hsf.googlegroups.com> Message-ID: <5fedf077-5f0c-42f6-98fc-eac2c9643496@u10g2000prn.googlegroups.com> > > I'd try to avoid duplicating the calculation code. > > Also, if you split the data in two, you can just read the filename list > alone: thanx G those were good suggestions gordon From steve at REMOVE-THIS-cybersource.com.au Mon Jan 28 10:43:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 28 Jan 2008 15:43:10 -0000 Subject: validate string is valid maths References: Message-ID: <13pru0etgp7joc1@corp.supernews.com> On Mon, 28 Jan 2008 15:10:54 +0000, Matthew_WARREN wrote: > Hi pythoners. > > I am generating strings of length n, randomly from the symbols > > +-/*0123456789 > > What would be the 'sensible' way of transforming the string, for example > changing '3++++++8' into 3+8 That's easy: replace pairs of + into a single +, repeatedly until there's nothing left to replace. And so forth. Here's an untested function. It's probably not even close to optimal, but for playing around it is probably fine. def rationalise_signs(s): while "++" in s or "+-" in s or "-+" in s or "--" in s: s = s.replace("++", "+") s = s.replace("--", "+") s = s.replace("+-", "-") s = s.replace("-+", "-") return s > or '3++--*-9' into '3+-9' such that eval(string) will always return a > number? > > in cases where multiple symbols conflict in meaning (as '3++--*-9' the > earliest valid symbols in the sequence should be preserved You have four symbols, so there are just 4*4=16 sets of two symbols. Probably the easiest way is to just list them and their replacements out in a table: table = {"++": "+", "+-": "-", "+*": "+", "+/": "+", "-+": "-", "--": "+", "-*": "-", "-/": "-", "*+": "*", "**": "*", "*/": "*", "/+": "/", "/*": "/", "//": "/", } Notice that both *- and /- don't get changed. # Untested. def rationalise_signs(s): prev = '' while s != prev: prev = s for key, value in table.items(): s = s.replace(key, value) return s -- Steven From grante at visi.com Thu Jan 31 16:48:53 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 31 Jan 2008 21:48:53 -0000 Subject: Naive idiom questions References: Message-ID: <13q4gi56jajqk51@corp.supernews.com> On 2008-01-31, Terran Melconian wrote: > * Why are there no real mutable strings available? [...] > I want to be able to accumulate a string with +=, not by going > through an intermediate list and then doing ''.join(), So what's stopping you? >>> s = "one" >>> s += " two" >>> s 'one two' >>> > because I think the latter is ugly. Then don't do it. :) > There are also times when I'd like to use the string as a > modifiable buffer. That would be an array of characters or bytes: http://docs.python.org/lib/module-array.html > Is the python idiom that this is actually the Right Thing for > reasons I'm not seeing? I'm not sure what you're asking. AFAIK, the main reason that strings are immutable is so they can be used as dict keys. > Is there a fundamental reason it would be hard to > implement a mutable string in cpython? What problem would a mutable string solve that an array of chars won't? > * What's the best way to initialize a list of lists? Hmm. I guess I never need to do that. > * Is there a way to get headings in docstrings? Docstrings? Real Men Don't Write Docstrings! -- Grant Edwards grante Yow! Now, let's SEND OUT at for QUICHE!! visi.com From cbmeeks at gmail.com Mon Jan 7 15:13:05 2008 From: cbmeeks at gmail.com (cbmeeks) Date: Mon, 7 Jan 2008 12:13:05 -0800 (PST) Subject: Any interest in an SQS alternative??? Message-ID: <6d0b8524-e45c-43d4-9c55-ac3e87eead8f@d4g2000prg.googlegroups.com> I'm a big fan of Amazon's SQS web services. However, I think their SQS is simply too expensive. I was doing some tests in python using SQS and created 1,513 messages in just a few minutes. Then I looked at my bill. It was $0.15 not counting the S3 fee. $0.15 seems like a lot to me for the application I was writing. The application was designed to create MANY MANY small messages. SQS allows you to store up to 256k in one message which is pretty cool. But my app only needed to store URL's. They were all under 64 bytes. Granted, I assume most people take that 256k and intelligently handle many messages in one. For example, a photo sharing site would probably store the ID's to maybe 10-50 pictures in one message and another server would process those pictures as one job. But surely, I'm not the only one out there that would rather create 10,000 messages that are very small vs 1,000 messages that are larger? Or am I? So anyway, I wrote my own message passing class that works pretty well. It is "my" message passing system...as in, message passing for what I need. But maybe others need too? I am seriously thinking of putting it live and let people play around with it...as an experiment. I hope this post doesn't come across as spam or "trolley" because I will probably ask the PHP and Ruby guys too. My goal for "myself" would be to create a system that is at least half of what SQS charges. I know I can't compete with the giant Amazon but who knows... Anyway, if anyone has any interest please let me know. If no one cares, then I guess I will use it all for myself. hahaha Feel free to email me directly too. cbmeeks [AT] gmail.com From steven at REMOVE.THIS.cybersource.com.au Wed Jan 23 04:37:03 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 09:37:03 -0000 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> Message-ID: On Tue, 22 Jan 2008 23:33:00 -0800, George Sakkis wrote: > As I mentioned already, I consider the seeking of the most efficient > solution a legitimate question, regardless of whether a "dumb" solution > is fast enough for an application. Call it a "don't be sloppy" principle > if you wish. Sure, by why do you limit "efficient" and "don't be sloppy" to mean "write the fastest executing code you can, regardless of every other trade-off"? Because there are trade-offs: * execution time * compilation time * memory use at run-time * size of source code on disk * size of compiled code on disk * ease of writing it in the first place * ease of maintenance * correctness * fragility in the face of malformed data * readability and ease of comprehension * elegance (however you judge that!) * making sure the usage of various resources never exceed some set of upper bounds etc. Some of these are relatively unimportant (e.g. the size of the source code), but others are extremely important and far too often ignored (e.g. readability and even correctness). In fact, "fastest" isn't even a meaningful attribute. Does it mean: * the worst-case is fastest * the best-case is fastest * the average-case is fastest * fastest on typical data * all of the above etc. What counts as "typical" data? How do you average all the cases? Asking "what's the fastest" without considering these issues is a good sign that the person asking is being sloppy, something you should be against. > It's the same reason I always use xrange() instead of > range() for a loop, although in practice the difference is rarely > measurable. Well, that's (now) a no-brainer. Once upon a time, range() used to be faster for small enough lists, and whatever difference there is in readability is insignificant except for utter newbies, so there's no real trade-off to make unless you care about the extra "x". But... do you write list.__len__() instead of len(list) to save a few nanoseconds? If you do, you're guilty of pessimization instead of optimization: for built-in lists, len() is actually faster, by a lot. It's only an optimization -- and a significant one -- for custom classes. So, do you write this: if isinstance(alist, list): value = len(alist) # optimize for lists else: value = alist.__len__() # optimize for classes every time you want the length of an arbitrary sequence? If you did, you'd be pessimizing again. That code runs nearly twice as slowly as just calling the built-in len(). Optimizing the parts doesn't mean you have optimized the whole. -- Steven From mr.cerutti at gmail.com Fri Jan 4 10:10:41 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 4 Jan 2008 10:10:41 -0500 Subject: Details about pythons set implementation In-Reply-To: References: Message-ID: <51302a8c0801040710s22e7a094i473a3e46fbfc2cca@mail.gmail.com> On Jan 4, 2008 9:54 AM, Achim Domma wrote: > Hi, > > I'm interested in details about how sets are implemented in python. > They seem to be quite fast and I found some remarks who state, that > the implementation is highly optimized. I need to implemented sets in > C/C++ and need a starting point on how to do it right. Could somebody > give me a starting point? #include -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Fri Jan 4 04:27:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 10:27:57 +0100 Subject: C++ equivalent of comp.lang.python? In-Reply-To: <005550c8-00f6-42b2-b804-2d2baea0b60e@s8g2000prg.googlegroups.com> References: <60597295-1493-493c-969c-a14dd7da98a3@s19g2000prg.googlegroups.com> <005550c8-00f6-42b2-b804-2d2baea0b60e@s8g2000prg.googlegroups.com> Message-ID: Russ P. wrote: >> make sense either. As an example, I was recently trying to get >> information about writing cross-platform code for dynamic linking, but >> I couldn't find anywhere appropriate to ask about it. > > Well, if the good folks at comp.lang.c++ can't even direct you to an > appropriate forum on C++, then I doubt the folks at comp.lang.python > can. I suggest you abandon C++ and try Python, Java, or Ada. note that for his specific example, we would of course direct him to the relevant portions of the CPython source code. From rvtol+news at isolution.nl Mon Jan 28 15:00:55 2008 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Mon, 28 Jan 2008 21:00:55 +0100 Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> <13ps95mg8am3l37@corp.supernews.com> Message-ID: Greg Bacon schreef: > #! /usr/bin/perl > > use warnings; > use strict; > > use constant { > MATCH => 1, > NO_MATCH => 0, > }; > > my @tests = ( > [ "winter tire", => MATCH ], > [ "tire", => MATCH ], > [ "retire", => MATCH ], > [ "tired", => MATCH ], > [ "snowbird tire", => MATCH ], > [ "tired on a snow day", => MATCH ], > [ "snow tire and regular tire", => MATCH ], > [ " tire" => MATCH ], > [ "snow tire" => NO_MATCH ], > [ "snow tire" => NO_MATCH ], > [ "some snowtires" => NO_MATCH ], > ); > [...] I negated the test, to make the regex simpler: my $snow_tire = qr/ snow [[:blank:]]* tire (?!.*tire) /x; my $fail; for (@tests) { my($str,$want) = @$_; my $got = $str !~ /$snow_tire/; my $pass = !!$want == !!$got; print "$str: ", ($pass ? "PASS" : "FAIL"), "\n"; ++$fail unless $pass; } print "\n", (!$fail ? "PASS" : "FAIL"), "\n"; __END__ -- Affijn, Ruud "Gewoon is een tijger." From arnodel at googlemail.com Tue Jan 29 08:45:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 29 Jan 2008 05:45:27 -0800 (PST) Subject: extending Python - passing nested lists References: <3ddeaf07-3f4b-4d68-a176-9205fa4d234b@k39g2000hsf.googlegroups.com> Message-ID: On Jan 29, 1:22?pm, Christian Meesters wrote: > Thanks. Point is that all such approaches would require lots(!) of calls to > the Python API - a way by which I won't gain the desired speed. You didn't mention speed in your original post. What about using array.array? Unless I am mistaken, these are just a thin wrapper around normal C arrays. Anyway you could always convert your list into a c array, do lots and lots of fast calculations, then convert it back again to a list. -- Arnaud From stargaming at gmail.com Thu Jan 31 15:05:44 2008 From: stargaming at gmail.com (Stargaming) Date: 31 Jan 2008 20:05:44 GMT Subject: helper function in a class' namespace References: <47a226bb$0$2982$ba620e4c@news.skynet.be> Message-ID: <47a22a17$0$8306$9b622d9e@news.freenet.de> On Thu, 31 Jan 2008 20:51:23 +0100, Helmut Jarausch wrote: > Hi, > > the following code works fine > > def Helper(M) : > return 'H>'+M String concatenation is generally considered unpythonic, better use string interpolation:: 'H> %s' % (M,) > class A(object): > def __init__(self,Msg) : > print Helper(Msg) > > B=A('ZZ') Watch out your names -- they could confuse other Python programmers introspecting your namespaces! Names bound to objects should generally be lowercase (argument ``msg``, object ``b``, argument ``m``, function ``helper``). For details on what the Python community has agreed on is "good style," see the `Style Guide `_. > but the Helper function is in the module's namespace. Where's the problem? If it is "I don't want Helper to be visible", just use this convention: "Names beginning with an underscore are private. Better keep your fingers off." > I'd like to put it into class A's namespace. Note, the Helper function > doesn't need access to any instance attributes. > > The first variant > > class A(object): > def Helper(M) : > return 'H>'+M > def __init__(self,Msg) : > print Helper(Msg) > > doesn't work since Python is looking for a global function Helper (why?) Because in the scope of the ``__init__`` function, the name ``Helper`` is not bound. It then jumps out to the global scope. > The alternative > > class A(object): > def Helper(M) : > return 'H>'+M > def __init__(self,Msg) : > print A.Helper(Msg) > > doesn't work either since now the first argument to A.Helper must be > 'A'. > > So, isn't it possible to have a helper function in the namespace of a > class without (the overhead of) passing a 'self' or a 'cls' parameter? Of course it is! You can decorate certain functions with the `staticmethod `_ wrapper, which will do exactly what you wanted:: class A(object): @staticmethod def helper(m): return 'H>%s' % (m,) def __init__(self, msg): print A.helper(msg) # or self.helper HTH, From python-url at phaseit.net Mon Jan 28 13:06:36 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 28 Jan 2008 18:06:36 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jan 28) Message-ID: QOTW: "The nice thing with Pyrex is that you can use the Python interpreter, or not use it, more or less depending on your way to declare things and your way to code. So, in a way, you have full control over the compromise between speed and facility. The temptation is always strong to use Python facilities, but I guess that with enough discipline, you can displace and put the equilibrium wherever you want." - Francois Pinard "If you don't ever need or have the chance to debug it, you probably aren't doing programming." - Peter Hansen Early-bird registration for PyCon 2008 continues through 20 February: http://us.pycon.org/2008/registration/ Proposal: auto-assignment to self of some constructor arguments: http://groups.google.com/group/comp.lang.python/browse_thread/thread/32b421bbe6caaeed/ Looking for self-evaluating strings, such that eval(s)==s: http://groups.google.com/group/comp.lang.python/browse_thread/thread/11a74d45d713faef/ Four small problems, with several answers and timings: Find the minimum value from those associated to keys in a dict: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c852ac37c28311cb/ Find the index of the maximum element in a list: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d5ff990a1be73846/ Same but minimum element instead: http://groups.google.com/group/comp.lang.python/browse_thread/thread/284094fd1ac25f69/ Take pairs sequentially from a list: http://groups.google.com/group/comp.lang.python/browse_thread/thread/cf5ab4fab83f7988/ Countdown game solver: combine a few numbers with +-*/() to obtain a given result. Several, very different solutions: http://groups.google.com/group/comp.lang.python/browse_thread/thread/64442b609d99a4ba/ Another game: Sudoku, several approaches too, some incredibly short: http://groups.google.com/group/comp.lang.python/browse_thread/thread/99e43f326aaf93e5/ A guy *really* trying to make sense of Python bytecode disassembled as if it were actual 80x86 code (still LOLAROTF!!!): http://groups.google.com/group/comp.lang.python/browse_thread/thread/df14a32d10432940/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From babycode at gmail.com Sat Jan 12 14:41:15 2008 From: babycode at gmail.com (babycode at gmail.com) Date: Sat, 12 Jan 2008 11:41:15 -0800 (PST) Subject: Great Python books for the beginner References: Message-ID: <1a4d8dae-4722-4a10-a638-ac1b2d85227a@i72g2000hsd.googlegroups.com> On Jan 12, 2:03?am, Landon wrote: > I was wondering if anyone had any opinions on what other titles I > could look into since this one seems from a glance at reviews to be > teaching mainly through game programming (a topic I'm not too > interested in) or if this one is a quality book by itself. http://www.diveintopython.org/ From paul.hankin at gmail.com Thu Jan 24 07:35:34 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 24 Jan 2008 04:35:34 -0800 (PST) Subject: Increment Variable Name References: <9e9714f6-24d8-46fe-908f-205d223574cd@p69g2000hsa.googlegroups.com> Message-ID: On Jan 24, 12:02 pm, janislaw wrote: > On Jan 23, 11:45 pm, David Brochu wrote: > > > This is probably really trivial but I'm stumped.... :-( > > > Does anyone know how to increment a variable name? > > > For example: > > > I know the length of a list and I want to pass each element of a list > > to a unique variable, thus I want to increment variable names. If the > > list length = 4, i want to have the following variables: var1, var2, > > var3, var4. > > > Thanks > > Do you want to do this?: > locals()['var'+str(1)] = "spam" As I recently learnt in this newsgroup, that's not guaranteed to work. >From http://docs.python.org/lib/built-in-funcs.html Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. -- Paul Hankin From over at thepond.com Tue Jan 22 17:27:59 2008 From: over at thepond.com (over at thepond.com) Date: Tue, 22 Jan 2008 22:27:59 GMT Subject: Anyone into Paimei?? Need some help. Message-ID: <1arcp3ltqatcge08e56oaniutd3e2us9lp@4ax.com> Hi. I have been trying to get Paimei running on Windoze but find it very inconsistent. It works on certain apps really well, like Notepad, but fails on other apps, especially those written in languages like Delphi. There isn't a lot out there on Paimei and the author's site is very terse on the app. From hrochonwo at googlemail.com Tue Jan 22 14:04:21 2008 From: hrochonwo at googlemail.com (hrochonwo) Date: Tue, 22 Jan 2008 11:04:21 -0800 (PST) Subject: printing escape character References: Message-ID: <5524d3c2-e206-40bb-9e57-d860ed9c6cea@e10g2000prf.googlegroups.com> On Jan 22, 7:58 pm, "Jerry Hill" wrote: > On Jan 22, 2008 1:38 PM, hrochonwo wrote: > > > Hi, > > > I want to print string without "decoding" escaped characters to > > newline etc. > > like print "a\nb" -> a\nb > > is there a simple way to do it in python or should i somehow use > > string.replace(..) function ? > >>> print 'a\nb'.encode('string_escape') > > a\nb > > -- > Jerry thank you, jerry From petr.jakes.tpc at gmail.com Fri Jan 25 15:36:34 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Fri, 25 Jan 2008 12:36:34 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> Message-ID: <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> > > is already solved). > > what you are looking for is curse :) > http://docs.python.org/lib/module-curses.html > http://www.ibm.com/developerworks/linux/library/l-python6.html > > renaud Renaud, thanks for your reply. I think I was not specific/clear enough in my first posting. I know the curses library ( http://pyncurses.sourceforge.net ). It AFIK provides TUI (short for: Text User Interface or Textual User Interface). My needs are GUI, I mean "a nice VGA pictures" on the VGA LCD 10" display. Petr From doug.farrell at gmail.com Thu Jan 17 12:50:22 2008 From: doug.farrell at gmail.com (writeson) Date: Thu, 17 Jan 2008 09:50:22 -0800 (PST) Subject: handlers.SocketHandler and exceptions References: <02de2e9c-331d-45c0-afaa-578ddad55664@j78g2000hsd.googlegroups.com> Message-ID: Vinay, Thanks for your reply, very interesting. We're currently running Python2.3 (though we are getting ready to move to Python2.5), so I'm guessing the code you're showing comes from Python2.5? I'm wondering if I can edit the handlers.py code in my Python2.3 installation, make the changes you show above, and have things work? Any thoughts on this? Thanks for the help!! Doug From te_rem_ra_ove_an_forspam at consistent.org Thu Jan 31 16:30:09 2008 From: te_rem_ra_ove_an_forspam at consistent.org (Terran Melconian) Date: Thu, 31 Jan 2008 15:30:09 -0600 Subject: Naive idiom questions Message-ID: * Why are there no real mutable strings available? I found MutableString in UserString, but further research indicates that it is horribly inefficient and actually just wraps immutable strings for the implementation. I want to be able to accumulate a string with +=, not by going through an intermediate list and then doing ''.join(), because I think the latter is ugly. There are also times when I'd like to use the string as a modifiable buffer. Is the python idiom that this is actually the Right Thing for reasons I'm not seeing? Is there a fundamental reason it would be hard to implement a mutable string in cpython? * What's the best way to initialize a list of lists? I keep wanting to do this: l=[[None]*5]*5 as do many other Python novices, but of course it quickly becomes apparent why this is a bad idea as soon as one modifies a value. The best I've found is: l=[[None]*5 for i in range(5)] I don't particularly like it, though. It bothers me to have to explain list comprehensions, which are a moderately advanced feature conceptually, just to initialize an array. We could get around this if we had a defaultlist, but we don't. Is there a more elegant solution here? * Is there a way to get headings in docstrings? I want to create my own sections, like "OVERVIEW", "EXAMPLES", "AUTHORS", "BUGS", etc. I can't figure out any way to do this. In perldoc, I can easily use =head1, but I can't figure out the Python equivalent. At first I thought I could use (re)structuredtext, but then it became apparent that pydoc(1) does not parse any of this markup. Am I missing something, or is it just not possible to achieve this effect other than by writing separate, independent manpages? Thanks for any suggestions or thoughts. From stef.mientki at gmail.com Thu Jan 17 16:56:16 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 17 Jan 2008 22:56:16 +0100 Subject: get the size of a dynamically changing file fast ? Message-ID: <478FCF00.8060308@gmail.com> hello, I've a program (not written in Python) that generates a few thousands bytes per second, these files are dumped in 2 buffers (files), at in interval time of 50 msec, the files can be read by another program, to do further processing. A program written in VB or delphi can handle the data in the 2 buffers perfectly. Sometimes Python is also able to process the data correctly, but often it can't :-( I keep one of the files open en test the size of the open datafile each 50 msec. I have tried os.stat ( ....) [ ST_SIZE] os.path.getsize ( ... ) but they both have the same behaviour, sometimes it works, and the data is collected each 50 .. 100 msec, sometimes 1 .. 1.5 seconds is needed to detect a change in filesize. I'm using python 2.4 on winXP. Is there a solution for this problem ? thanks, Stef Mientki From teddyber at gmail.com Fri Jan 11 17:35:38 2008 From: teddyber at gmail.com (teddyber) Date: Fri, 11 Jan 2008 14:35:38 -0800 (PST) Subject: split parameter line with quotes References: <37fac828-20ec-4cb9-8ea7-a85cce7d3e91@k39g2000hsf.googlegroups.com> Message-ID: here's the solution i have for the moment : t = shlex.shlex(data) t.wordchars = t.wordchars + "/+.-" r='' while 1: token = t.get_token() if not token: break if not token==',': r = r+token else: r = r + ' ' self.DEBUG(r,'ok') for pair in r.split(' '): key,value=pair.split('=', 1) print(key+':'+value) i know this is not perfect still but i'm coming a long way from very bad php habits! :o) and thanks for your help! On 11 jan, 23:30, teddyber wrote: > wow! that's perfect this shlex module! thanks for pointing this! > > On 11 jan, 20:36, Joshua Kugler wrote: > > > teddyber wrote: > > > first i'm a newbie to python (but i searched the Internet i swear). > > > i'm looking for some way to split up a string into a list of pairs > > > 'key=value'. This code should be able to handle this particular > > > example string : > > > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > > > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > > > i know i can do that with some regexp (i'm currently trying to learn > > > that) but if there's some other way... > > > Take a look at the shlex module. You might be able to fiddle with the shlex > > object and convince it to split on the commas. But, to be honest, that > > above would be a lot easier to parse if the dividing commas were spaces > > instead. > > > j From brkict at gmail.com Tue Jan 29 10:48:58 2008 From: brkict at gmail.com (glomde) Date: Tue, 29 Jan 2008 07:48:58 -0800 (PST) Subject: runscript module, where are the docs... Message-ID: <1fbdde0d-ae09-4b6a-8f08-0713de94cc0b@j78g2000hsd.googlegroups.com> Hi! I am going through some code and found import runscript BUT I cant find and information about this module. I searched Google did a grep in the /usr/lib/python directory. What is the purpose of this module and where can I find information about it. Or the source. Best regards, Toni From azam.farooq3 at gmail.com Sat Jan 26 01:53:33 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Fri, 25 Jan 2008 22:53:33 -0800 (PST) Subject: Mobile Phones, iPods EQ100 www.enmac.com.hk Message-ID: <4def7add-dc5e-4325-a54a-3c1408912e57@i29g2000prf.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 guptaabhishek1983 at gmail.com Thu Jan 3 08:48:16 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Thu, 3 Jan 2008 05:48:16 -0800 (PST) Subject: Trying to build python2.5.msi Message-ID: <8091fa48-7c38-4502-84c9-5527586a6568@i3g2000hsf.googlegroups.com> Hello Group, I have compile the python source code using MSVC 8 (a.k.a VS .NET 2005) . Can i create an MSI ?? similar to one provided by the official python website. What can be the possible procedure to achieve this. I have looked into Tools/msi folder. But i dont know how it works. Thank you Abhishek From terry at jon.es Mon Jan 21 06:54:22 2008 From: terry at jon.es (Terry Jones) Date: Mon, 21 Jan 2008 12:54:22 +0100 Subject: Just for fun: Countdown numbers game solver In-Reply-To: Your message at 03:27:45 on Monday, 21 January 2008 References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <5a26081c-8bcd-440c-bffa-6d730e38ff59@s12g2000prg.googlegroups.com> Message-ID: <18324.34798.714387.580378@terry.local> >>>>> "Arnaud" == Arnaud Delobelle writes: Arnaud> Sorry I gave an incorrect example to illustrate my question last Arnaud> night (I blame this on baby-induced sleep deprivation ;), so I'll Arnaud> have another go: Arnaud> Say I have 2, 3, 4, 100 and I want to make 406. AFAICS there is only Arnaud> one way: (2*3)+(4*100), i.e. in postfix notation: Arnaud> 2 3 * 4 100 * + Arnaud> It seemed to me that your function wouldn't generate that sort of Arnaud> solution (as you always extend partialSolution by [num, op] making Arnaud> the subsequence [mul, add] impossible). Am I wrong? No, you're right. I actually started out with a stack solution, and then switched to something simpler (too simple). I'm going to redo it, but maybe not right now... Thanks! Terry From levilista at gmail.com Thu Jan 10 17:55:18 2008 From: levilista at gmail.com (zslevi@gmail.com) Date: Thu, 10 Jan 2008 14:55:18 -0800 (PST) Subject: adding methods at runtime Message-ID: <940fcb28-764e-46ab-a627-aff513e009e1@j78g2000hsd.googlegroups.com> Can I access the class attributes from a method added at runtime? (My experience says no.) I experimented with the following code: class myclass(object): myattr = "myattr" instance = myclass() def method(x): print x instance.method = method instance.method("hello world") inst2 = myclass() #inst2.method("inst2") def meth2(x): print x.myattr myclass.ujmeth = meth2 inst2 = myclass() inst2.ujmeth() ############ The output: ########## hello world myattr ################ So it seems to me, if you add a method to an instance, the method will not get "self" as parameter. From sergio.correia at gmail.com Wed Jan 30 22:38:55 2008 From: sergio.correia at gmail.com (Sergio Correia) Date: Wed, 30 Jan 2008 22:38:55 -0500 Subject: Fwd: small problem with re.sub In-Reply-To: References: <47A13A0A.3010607@al.com.au> Message-ID: See this: http://www.regular-expressions.info/python.html (the Search and Replace part) You are referring to the group as "(?P=id)", when you should be using r"\g". HTH, Sergio On Jan 30, 2008 10:01 PM, Astan Chee wrote: > Hi, > I have a html text stored as a string. Now I want to go through this > string and find all 6 digit numbers and make links from them. > Im using re.sub and for some reason its not picking up the previously > matched condition. Am I doing something wrong? This is what my code > looks like: > htmlStr = re.sub('(?P\d{6})',' href=\"http://linky.com/(?P=id).html\">(?P=id)',htmlStr) > It seems that it replaces it alright, but it replaces it literally. Am I > not escaping certain characters? > Thanks again for the help. > Cheers > > Animal Logic > http://www.animallogic.com > > Please think of the environment before printing this email. > > This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From michele.simionato at gmail.com Tue Jan 15 00:13:51 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 14 Jan 2008 21:13:51 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> <65cfbd40-6612-4bd5-aa5c-a1338da0f5a7@n20g2000hsh.googlegroups.com> Message-ID: <30c8bfe6-ef36-4f98-b281-f03f62f3d17e@k2g2000hse.googlegroups.com> On Jan 14, 11:47 pm, Richard Szopa wrote: > Could you tell me what are the pros and cons of the two approaches > (i.e. writing a decorator function and a decorator descriptor class)? I prefer to use a class for introspection sake, since there is no way to get information about an inner function in a closure, whereas your users can introspect classes pretty well. > super_object = super(self.__class__, self) Notice that using super(self.__class__, self) is a common mistake: the pitfalls with inheritance were discussed very recently in this same newsgroup, you should be able to find the post. What you need is super(class_where_the_method_is_defined, self) which is in general different from super(self.__class__, self) There is no clean way to determine the current class in Python < 3.0 (Python 3.0 does it automatically); if you want to see a hackish way involving bytecode tricks see http://groups.google.com/group/comp.lang.python/browse_frm/thread/a6010c7494871bb1/62a2da68961caeb6?hl=en&lnk=gst&q=currentClass#62a2da68961caeb6 (and notice that this is really not recommended). Michele Simionato From http Tue Jan 15 13:14:03 2008 From: http (Paul Rubin) Date: 15 Jan 2008 10:14:03 -0800 Subject: Dynamical scoping References: <1a3243ef-13f6-40d6-97eb-198b8742ac3d@d4g2000prg.googlegroups.com> <7xabn7hovr.fsf@ruckus.brouhaha.com> Message-ID: <7xfxwzgdn8.fsf@ruckus.brouhaha.com> Kay Schluehr writes: > On 15 Jan., 02:13, Paul Rubin wrote: > > George Sakkis writes: > > > What's the best way to simulate dynamically scoped variables ala Lisp ? > > > > Ugh.... check the docs for the python 2.5 "with" statement, which > > gives you sort of a programmable unwind-protect (more powerful than > > try/except). You'd have an environment dictionary and use the "with" > > statement to maintain a stack of shallow-binding cells like in an > > old-time lisp system, automatically unwinding when the "with" suite > > finishes. The whole concept sounds hopelessly crufty--I think nobody > > even does it that way in Lisp any more, you're better off passing an > > environment around explicitly. If there were a lot of variables, this > > could be a good application for functional maps, which I've been wanting > > to implemetn for python. Kay, did you have something to add? You quoted the above two posts and then your message stopped. From pinch13 at verizon.net Sun Jan 20 10:24:39 2008 From: pinch13 at verizon.net (BJ) Date: Sun, 20 Jan 2008 07:24:39 -0800 (PST) Subject: Homework Helper and College Companion Websites Message-ID: In 1996 I started BJ Pinchbeck's Homework Helper at www.bjpinchbeck.com which became quite popular among young students throughout the country. Now that I am 20 years old and attending Drexel University in Philadelphia, Pennsylvania, I decided it was time to start a new site, BJ Pinchbeck's College Companion at www.bjpinchbeck.net that could help students prepare for and survive the college experience. College has been a very positive experience for me, but it would have been nice to have more materials readily available to me prior to attending college. Please feel free to link to either site. Thank you BJ Pinchbeck From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 23 12:16:29 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 23 Jan 2008 18:16:29 +0100 Subject: Bug in __init__? In-Reply-To: References: <4795b788$0$11545$426a34cc@news.free.fr> Message-ID: <4797761a$0$4430$426a74cc@news.free.fr> Bart Ogryczak a ?crit : > On 2008-01-22, citizen Bruno Desthuilliers testified: >>> from copy import copy >>> ### see also deepcopy >>> self.lst = copy(val) >> What makes you think the OP wants a copy ? > > I?m guessing he doesn?t want to mutate original list, while changing > contents of self.lst. Once again: what makes you think so ? This is a design choice depending on the concrete use case and context - which we don't know zilch about - and by no mean the default behaviour. From rbonvall at gmail.com Sun Jan 13 01:34:49 2008 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Sat, 12 Jan 2008 22:34:49 -0800 (PST) Subject: Elementary string-formatting References: Message-ID: On Jan 12, 10:15 pm, Odysseus wrote: > P.S. Is there a preferable technique for forcing floating-point division > of two integers to that used above, multiplying by "100.0" first? Put this at the beginning of your program: from __future__ import division This forces all divisions to yield floating points values: >>> 1/3 0 >>> from __future__ import division >>> 1/3 0.33333333333333331 >>> HTH, -- Roberto Bonvallet From ruivaldo at gmail.com Thu Jan 10 09:21:59 2008 From: ruivaldo at gmail.com (rui) Date: Thu, 10 Jan 2008 11:21:59 -0300 Subject: I'm searching for Python style guidelines In-Reply-To: References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: Thanks Caleb. Really liked some points. On Jan 10, 2008 11:20 AM, Caleb wrote: > MartinRinehart at gmail.com wrote: > > > Anything written somewhere that's thorough? Any code body that should > > serve as a reference? > > 1. Don't use tabs (use spaces). > 2. Study "import this" > 3. Use lists and dictionaries as much as you possibly can > 4. Use comprehensions and generators as much as you possibly can > 5. Use the standard library for everything you possibly can > 6. As much as you possibly can, when starting a new project, postpone > setting up classes for everything (start with functions). In some > projects, you might never need the overhead at all. > > It will be difficult to go far wrong regarding style if you do a lot of > what's in this list. This list is not mine. I jotted these points > down, but this information is continually repeated by the actual wise > people (not me) in this newsgroup. > > Caleb > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Rui http://rui.tumblr.com "Rubi? Aquela novela do SBT?" ~ Carla Perez sobre Ruby "Em Python, tudo ? objeto, al?m de lindo e maravilhoso." ~ Caetano Veloso sobre Python From sjmachin at lexicon.net Fri Jan 25 04:28:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 01:28:51 -0800 (PST) Subject: Python ADO Date Time database fields References: Message-ID: On Jan 25, 10:55 am, goldtech wrote: > Hi, > > Given an MS-Access table with a date type field with a value of: > 12:00:00 AM - just"12:00:00 AM", there's nothing else in the field. > > I want to print exactly what's in the field, ie. "12:00:00 AM". What I > get printed is: 12/30/0/ 00:00:00 > > I try: [snip] > print oRS.Fields(dt).Value # print here try this: val = oRS.Fields(dt).Value print type(val) print float(val) If the last one gives you 0.0, then you have got exactly what's in the database -- stored as a fraction of a day. Six AM would give you 0.25. Converting that to 24 hour clock is easy: >>> val = 0.12345 >>> seconds = int(round(val * 60 * 60 * 24)) >>> minutes, second = divmod(seconds, 60) >>> hour, minute = divmod(minutes, 60) >>> '%02d:%02d:%02d' % (hour, minute, second) '02:57:46' >>> ((((46/60.)+57)/60.)+2)/24. # checking 0.12344907407407407 If you don't get 0.0, let us know what you did get. HTH, John From bdesth.quelquechose at free.quelquepart.fr Sun Jan 6 14:43:42 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 06 Jan 2008 20:43:42 +0100 Subject: python interfaces In-Reply-To: References: Message-ID: <47812f6b$0$17701$426a74cc@news.free.fr> Sion Arrowsmith a ?crit : > hyperboreean wrote: > >>Why doesn't python provide interfaces trough its standard library? > > > Because they're pointless. (snip rant about Java's "interfaces") Hem... Zope3's "interface" system is not exactly the same thing as Java's one. From elind at spamcop.net Mon Jan 14 14:25:29 2008 From: elind at spamcop.net (Erik Lind) Date: Mon, 14 Jan 2008 14:25:29 -0500 Subject: help with slicing/replacing matrix sections. Message-ID: <478bb75f$0$5001$4c368faf@roadrunner.com> I see a more complicated thread on a similar sounding question, but my question is simpler, I hope. I have a large numpy matrix, initially created as: Mat = zeros((a,b), int) and a smaller array with other data Sub = [1,2,3,4,5],[6,7,8,9,0] I want to replace a section of Mat matrix with Sub matrix without having to loop through each cell in each matrix individually. I thought index/slice assignments, should be able to do that, but I can only get it to work (as per book examples) with simple arrays. Every syntax combination I have tried gives one error or another, typically "can't broadcast an object....", but intuitively it seems there should be a simple solution. In short, how do I insert the data in the two (or any number of) rows in Sub[0:2] into any part of Mat starting at Mat[x,y] without using "for" loops ? From mensanator at aol.com Fri Jan 18 16:21:55 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 18 Jan 2008 13:21:55 -0800 (PST) Subject: Bit Scan Forward and Reverse References: Message-ID: On Jan 18, 2:01?pm, Thomas Dybdahl Ahle wrote: > Hi, I'm writing an app in python, and I'm storing some a lot of data in > bitmaps. > I need a way to find the first or latest set bit in a 64bit number, and > for that I've implemented a small routine. > > Thing is that this routine is not as fast as I'd wish. I know most > processors implement BSF and BSR calls to do this efficiently. > Is there anyway to access those calls from python? > > I'd still have my routine as a fallback on nonsupporting architectures. Get a copy of the gmpy module. Help on module gmpy: NAME gmpy FILE c:\program files\pygtk\python\lib\site-packages\gmpy.pyd DESCRIPTION gmpy 1.04 - General Multiprecision arithmetic for PYthon: exposes functionality from the GMP 4 library to Python 2.{2,3,4}. Allows creation of multiprecision integer (mpz), float (mpf), and rational (mpq) numbers, conversion between them and to/from Python numbers/strings, arithmetic, bitwise, and some other higher-level mathematical operations; also, pretty good-quality linear-congruential random number generation and shuffling. mpz has comparable functionality to Python's builtin longs, but can be faster for some operations (particularly multiplication and raising-to-power) and has many further useful and speedy functions (prime testing and generation, factorial, fibonacci, binary-coefficients, gcd, lcm, square and other roots, ...). mpf and mpq only offer basic arithmetic abilities, but they do add the ability to have floating-point numbers ensuring at least a predefined number of bits' worth of precision (and with potentially-huge or extremely-tiny magnitudes), as well as unlimited-precision rationals, with reasonably-fast operations, which are not built-in features of Python. FUNCTIONS (selected operations for binary use) getbit(...) getbit(x,n): returns 0 or 1, the bit-value of bit n of x; n must be an ordinary Python int, >=0; x is an mpz, or else gets coerced to one. hamdist(...) hamdist(x,y): returns the Hamming distance (number of bit- positions where the bits differ) between x and y. x and y must be mpz, or else get coerced to mpz. lowbits(...) lowbits(x,n): returns the n lowest bits of x; n must be an ordinary Python int, >0; x must be an mpz, or else gets coerced to one. popcount(...) popcount(x): returns the number of 1-bits set in x; note that this is 'infinite' if x<0, and in that case, -1 is returned. x must be an mpz, or else gets coerced to one. scan0(...) scan0(x, n=0): returns the bit-index of the first 0-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 0-bits are in x at or above bit-index n (which can only happen for x<0, notionally extended with infinite 1-bits), None is returned. x must be an mpz, or else gets coerced to one. scan1(...) scan1(x, n=0): returns the bit-index of the first 1-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 1-bits are in x at or above bit-index n (which can only happen for x>=0, notionally extended with infinite 0-bits), None is returned. x must be an mpz, or else gets coerced to one. setbit(...) setbit(x,n,v=1): returns a copy of the value of x, with bit n set to value v; n must be an ordinary Python int, >=0; v, 0 or ! =0; x must be an mpz, or else gets coerced to one. These work quite nicely. I use scan1() in the following idiom which removes all factors of 2 in one fell swoop. n = 3*n + 1 # always even, but how even? f = gmpy.scan1(n) # bit position of LS 1-bit n = n >> f # ...which is number of 0-bits > > -- > Med venlig hilsen, > Best regards, > Thomas From jamon.ben at gmail.com Wed Jan 9 15:07:16 2008 From: jamon.ben at gmail.com (Ben Fisher) Date: Wed, 9 Jan 2008 15:07:16 -0500 Subject: Structure of packages Message-ID: <741fd030801091207h720ecc2cya4fb543db29ddabc@mail.gmail.com> I am trying to learn the best way to do intra-package references. My package looks like this: PackageName __init__.py /a __init__.py a.py ... /b __init__.py ... /c __init__.py ... /d __init__.py ... I have layered the dependencies so that a depends on b, b depends on c, and c depends on d. There are no circular references. Now I would like to be able to refer to the subpackage b from inside the subpackage a. In effect, I would like to say "from '../b' import *" I had thought that "from PackageName.b import *" would work. This works for a file in the directory /PackageName, but not for a file in the directory /PackageName/a. It's like when you are running a Python file in the directory /PackageName/a it doesn't know about PackageName - No module named "PackageName". Is there a solution to this, or a better way to structure the directories? From nicogrubert at gmail.com Thu Jan 10 05:23:20 2008 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 10 Jan 2008 11:23:20 +0100 Subject: Rebuild list of objects with redundancies on objects' attribute Message-ID: <4785F218.3020905@gmail.com> Hi there I have a list of dummy objects which have the attributes 'location', 'name', 'gender'. Now I want to rebuild this list in order to avoid redundancies on objects with the same 'location'. Example: #------------------------------------------------------------------ class Dummy: pass a = Dummy() a.location = 'tokio' a.name = 'john' a.gender = 'm' b = Dummy() b.location = 'tokio' b.name = 'peter' b.gender = 'm' c = Dummy() c.location = 'madrid' c.name = 'susan' c.gender = 'f' d = Dummy() d.location = 'london' d.name = 'alex' d.gender = 'm' persons = [a, b, c, d] print "loc name gender" print "---------------------" for obj in persons: print "%s - %s - %s" % (obj.location, obj.name, obj.gender) #------------------------------------------------------------------ The output reads like this: loc name gender --------------------- tokio john m tokio peter m madrid susan f london alex m I want to create this list (where name and gender are lists): loc name gender ----------------------------- tokio [john, peter] [m] madrid [susan] [f] london [alex] [m] How can I do this? Thanks in advance. Nico From lists at cheimes.de Thu Jan 3 11:38:52 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 03 Jan 2008 17:38:52 +0100 Subject: How do you pass compiler option to setup.py install? In-Reply-To: <32e43bb70801030824p7099da66s6ffb4ee0ea58b311@mail.gmail.com> References: <32e43bb70801030824p7099da66s6ffb4ee0ea58b311@mail.gmail.com> Message-ID: <477D0F9C.7000507@cheimes.de> Emin.shopper Martinian.shopper wrote: > Dear Experts, > > How do you pass the -c option to setup.py install? Specifically, when I try > to install zope.interfaces version 3.3 from source on a windows machine, I > get a message about using "-c mingw32". That works fine for setup.py build, > but it does not work for "setup.py install". python setup.py build -c mingw32 install You can also change the distutils.cfg file to set mingw32 as the default compiler. Please refer to the documentation for more information. Christian From afriere at yahoo.co.uk Wed Jan 23 02:16:16 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 22 Jan 2008 23:16:16 -0800 (PST) Subject: Removing objects References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> Message-ID: <27c8e3c8-3766-499c-9c62-82b03fa583d6@e23g2000prf.googlegroups.com> On Jan 23, 5:59 pm, bladedpeng... at gmail.com wrote: > I am writing a game, and it must keep a list of objects. I've been > representing this as a list, but I need an object to be able to remove > itself. It doesn't know it's own index. If I tried to make each object > keep track of it's own index, it would be invalidated when any object > with a lower index was deleted. The error was that when I called > list.remove(self), it just removed the first thing in hte list with > the same type as what I wanted, rather than the object I wanted. The > objects have no identifying charachteristics, other than thier > location in memory > > So my question: How do I look something up in a list by it's location > in memory? does python even support pointers? > > Is there a better way? How about adding an id attribute to your objects, which will contain a unique identifier, override __eq__ to use that id to compare itself to others and then simply pop off the object using object_list.pop(object_list.index(self)). Something like this: >>> class Spam (object) : def __init__ (self, id) : self.id = id def __eq__ (self, other) : try : return self.id == other.id except AttributeError : return False >>> >>> a,b,c = Spam(1), Spam(2), Spam(3) >>> x = [a,b,c] >>> x.pop(x.index(c)) <__main__.Spam object at 0x885e5ac> Except your object would be telling the list to pop self of course, and you'd need someway of insuring the uniqueness of your IDs. From jeffrey at fro.man Fri Jan 18 09:27:02 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Fri, 18 Jan 2008 06:27:02 -0800 Subject: Cannot catch _mysql_exceptions.OperationalError References: <5f435c88-ef42-4ca9-921a-675393824ccc@k39g2000hsf.googlegroups.com> Message-ID: <13p1dpnq6icdh0e@corp.supernews.com> Bob wrote: > Here's the code that did not work: > > import _mysql_exceptions > from _mysql_exceptions import OperationalError > > try: > database_code() > except (_mysql_exceptions.OperationalError, OperationalError), e: > error_handling() Both of the above forms work fine here, as does using MySQLdb.OperationalError: ------------------------------------------------ >>> import MySQLdb >>> try: ... db = MySQLdb.connect(user='jeffrey', host='localhost') ... except MySQLdb.OperationalError: ... print 'caught' ... caught >>> import _mysql_exceptions >>> try: ... db = MySQLdb.connect(user='jeffrey', host='localhost') ... except _mysql_exceptions.OperationalError: ... print 'caught' ... caught >>> from _mysql_exceptions import OperationalError >>> try: ... db = MySQLdb.connect(user='jeffrey', host='localhost') ... except OperationalError: ... print 'caught' ... caught >>> MySQLdb.OperationalError is _mysql_exceptions.OperationalError True >>> MySQLdb.__version__ '1.2.2' ------------------------------------------------ Jeffrey From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 08:59:20 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 14:59:20 +0100 Subject: Python too slow? In-Reply-To: <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> <478732db$0$19250$426a74cc@news.free.fr> <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> Message-ID: <4787762b$0$18777$426a74cc@news.free.fr> George Sakkis a ?crit : > On Jan 11, 4:12 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > >> George Sakkis a ?crit : >> >>> On Jan 10, 3:37 am, Bruno Desthuilliers wrote: >>>> I fail to see how the existence of JIT compilers in some Java VM changes >>>> anything to the fact that both Java (by language specification) and >>>> CPython use the byte-code/VM scheme. >>> Because these "some Java VMs" with JIT compilers are the de facto >>> standard used by millions; >> Repeating an argument doesn't make it more true nor more relevant. Once >> again, this doesn't change anything to the fact exposed above. >> >>> the spec is pretty much irrelevant >> I mentionned this because this kind of choice is usually not part of the >> language spec but of a specific implementation. Java is AFAIK the only >> language where this implementation stuff is part of the spec. >> >>> (unless >>> you're a compiler writer or language theorist). >> I thought it was quite clear and obvious that I was talking about points >> relating to these fields. > > No it wasn't, """ > or is Python just too slow > as an interpreted language Being "interpreted" is a quality of an implementation, not of a language. """ If that isn't clear enough what I'm talking about, then sorry but I can't help. > and besides the OP is most likely interested in these as > a simple user so the distinction between a spec and a de facto > standard implementation (such as JDK for Java and CPython for Python) > are almost pedantic if not misleading. I can live with being called "pedantic" - even I'm not sure whether correcting a wrong statement about CPython's execution model is pedantic or not. But I *still* fail to see how it could be "misleading", and *you* still fail to explain in which way it could be misleading. If your point is that saying that CPython uses a byte-code/VM scheme "just like Java" necessarily implies JIT compilation just because some JVM support this feature, then it would be time you pay more attention to what is effectively written. > We're not Lisp (yet ;-)), with > five major implementations and a dozen of minor ones. And ? In which way does it make the distinction between a language and a language implementation less true ? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 28 10:00:25 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 28 Jan 2008 16:00:25 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <60357uF1perd0U1@mid.individual.net> Message-ID: <60690aF1otfruU1@mid.individual.net> over at thepond.com wrote: > Bjoern Schliessmann wrote: >> over at thepond.com wrote: >>> That's not the point, however. I'm trying to say that a >>> processor cannot read a Python script, and since the Python >>> interpreter as stored on disk is essentially an assembler file, >> >> It isn't; it's an executable. > > I appreciated the intelligent response I received from you > earlier, now we're splitting hairs. :-) Not at all. Assembly source is ASCII text. An executable commonly consists of a binary header (which contains various information => man elf) as well as code and data segments. Normally, you're only guaranteed to find machine language inside the code segments. > Assembler, like any other higher level language Assembler is _no_ high level language, though there are some assembly languages striving for resembling HLLs. http://webster.cs.ucr.edu/AsmTools/HLA/index.html > is written as a source file and is compiled to a binary. BMPs are binaries, too. Assembly code is compiled to object code files. > An executable is one form of a binary, as is a dll. When you view > the disassembly of a binary, there is a distinct difference > between C, C++, Delphi, Visual Basic, DOS, I don't think so. How a HLL source is translated to machine code depends on the compiler, and there are cross compilers. > or even between the different file types like PE, NE, MZ, etc. Yes. > But they all decompile to assembler. No. They all _contain_ code segments (which contain machine code), but also different data. > While they are in the binary format, they are exactly > that...binary. http://en.wikipedia.org/wiki/Binary_data > Who would want to interpret a long string of 1's and 0's. Binaries > are not stored in hexadecimal on disk nor are they in hexadecimal > in memory. But, all the 1's and 0's are in codes when they are > instructions or ASCII strings. No -- they're voltages or magnetic fields. (I never saw "0"s or "1"s in a memory chip or on a hard disk.) The representation of this data is up to the viewing human being to choose. > No other high level language has the one to one relationship that > assembler has to machine code, the actual language of the > computer. Yes. That's why Assembly language is not "high level", but "low level". > All the ASCIi strings end with 0x74 in the disassembly. *sigh* > I have noted that Python uses a newline as a line feed/carriage > return. (The means of line separation is not chosen just like this by Python users. It's convention depending on the OS and the application.) > Now I'm getting it. It could all be disassembled with a hex > editor, but a disassembler is better for getting things in order. Argl. A hex editor just displays a binary file as hexadecimal numbers, it does _not_ disassemble. "Disassembly" refers to _interpreting_ a file as machine instructions of one particular architecture. This, of course, only makes sense if this binary file actually contains machine instructions that make sense, not if it's really a picture or a sound file. Regards, Bj?rn -- BOFH excuse #130: new management From tarundevnani at gmail.com Sun Jan 6 08:04:38 2008 From: tarundevnani at gmail.com (tarun) Date: Sun, 6 Jan 2008 18:34:38 +0530 Subject: Killing worker threads Message-ID: Hello All, Can anyone help me with a simple code through which the main thread can kill the worker thread it started. Thanks & Regards, Tarun Devnani -------------- next part -------------- An HTML attachment was scrubbed... URL: From bg_ie at yahoo.com Fri Jan 25 07:05:37 2008 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Fri, 25 Jan 2008 04:05:37 -0800 (PST) Subject: The dimensions of a tuple References: <19d605ab-86de-44ec-8864-864554ffebc1@d21g2000prf.googlegroups.com> Message-ID: <2f6f696c-2914-4e6f-bf6d-584103bcb907@j78g2000hsd.googlegroups.com> On 25 Jan, 12:03, John Machin wrote: > On Jan 25, 9:26 pm, bg... at yahoo.com wrote: > > > Hi, > > > I wish to pass an argument to a function which will inset rows in a > > db. I wish to have the follow possibilities - > > > ("one","two") > > (("one","two"),("three","four")) > > > The first possibility would mean that one row is added with "one and > > "two" being its column values. The second possibility means that two > > rows are added. > > > So to do this I need to establish the dimension of the duple. Is it a > > one dimentional or two dimentional. How do I do this? > > isinstance(arg[0], tuple) > > ... but I wouldn't do it that way. I'd use a list of tuples, not a > tuple of tuples, to allow for ease of building the sequence with > list.append, and two functions: > > insert_one(("one", "two")) > insert_many([("one", "two")]) > insert_many([("one", "two"), ("three", "four")]) > > Which of those 2 functions calls the other depends on which you'd use > more often. > > HTH, > John Thanks for the tip regarding the list of tuples! From gagsl-py2 at yahoo.com.ar Mon Jan 28 11:58:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Jan 2008 08:58:46 -0800 (PST) Subject: SMTP Sending Mail Problem References: <9b00a5f5-277d-4d23-be82-60c2aafc4227@c23g2000hsa.googlegroups.com> Message-ID: On 28 ene, 14:15, the_ricka wrote: > However, whenever I try to read more than one line from the file, the > email is not being delivered. ?The only reason I know this is because > I tried just reading in the first line of the text file, and the email > sent fine. ?Right now I believe this must have something to do with > new line characters at the end of each line, but it doesn't quite make > sense to me why this is a problem, as I have also used the same script > and just created a string in it with multiple lines (\r\n) and sent it > and the email sends fine. ?To complicate the issue further, I have > turned used the set_debuglevel method so I can see the output from the > SMTP server, and it appears that the message was Queued for mail > delivery. Your code is fine, and the message was queued as you noticed. Maybe the recipient has some sort of black list, didn't like the sender, the message was classified as spam, or something like that. I'd look for problems elsewhere, not in the code. > send: 'From: #######@######.com\r\nTo: ######@######.com\r\nSubject: > Test1\r\n\ > r\nThis is from the file\r\nThis concludes our test\r\n\r\n\r\n.\r\n' > reply: '250 2.6.0 <############@###############.com> Qu > eued mail for delivery\r\n' > reply: retcode (250); Msg: 2.6.0 <##########@n#########.com> Queued > mail for delivery > data: (250, '2.6.0 <########@################.com> Q > ueued mail for delivery') > send: 'quit\r\n' > reply: '221 2.0.0 ################.com Service closing transmission > cha > nnel\r\n' > reply: retcode (221); Msg: 2.0.0 #################.com Service closing > t > ransmission channel -- Gabriel Genellina From petr.jakes.tpc at gmail.com Fri Jan 25 22:25:18 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Fri, 25 Jan 2008 19:25:18 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> <45a8d4a7-d24d-461e-9783-59a7d697a041@q77g2000hsh.googlegroups.com> Message-ID: <499aaee4-7e8f-47fb-bedd-7db548b92a5c@i29g2000prf.googlegroups.com> > I agree that SDL is probably the best choice but for the sake of > completeness, Gtk can (at least in theory - I've never tried it) be > built against directfb and run without X. from the Pygame Introduction: Pygame is a Python extension library that wraps the SDL library and it's helpers. So you mean, Pygame can run without X? BTW I have nothing against X, I just have not experiences on the GUI field, so my feeling was it can run faster without X on the 500MHz AMD Geode CPU. Petr From deets at nospam.web.de Sat Jan 19 11:10:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 19 Jan 2008 17:10:35 +0100 Subject: Ruby Programming In-Reply-To: <5b554594-158f-4efe-9cd2-1fb66d150781@d4g2000prg.googlegroups.com> References: <5b554594-158f-4efe-9cd2-1fb66d150781@d4g2000prg.googlegroups.com> Message-ID: <5velo2F1m688bU1@mid.uni-berlin.de> LinkExchange.AB at gmail.com schrieb: > iTechArt has specialized in Ruby on Rails (ROR) development and > provides a complete software outsourcing services for web development > solutions based on Ruby. We suggest use Ruby framework for developing > database-backed web applications with Ajax on front-end because it's a > great fit for practically any type of web application: collaboration, > community, e-commerce, content management and statistics. > > Ruby development environment and technologies: > > * Ruby On Rails development framework > * MySQL, PostgreSQL, SQLite, Oracle, MS SQL Server, DB2 > * RadRails IDE, ActionWebservice for Ruby > * Linux, Apache, lighttpd > * OOP and software development > * Search engines optimization > > > > http://itechart.is.stupid/foo.aspx Funny. Either rails isn't so good for the company's own website - which I doubt - or they don't know as much about it as they claim.... link changed to prevent proper indexing ... Diez From yhvh2000 at googlemail.com Tue Jan 15 20:44:08 2008 From: yhvh2000 at googlemail.com (yhvh) Date: Tue, 15 Jan 2008 17:44:08 -0800 (PST) Subject: error/warning color customization in interactive console? Message-ID: Is it possible to output error messages in a different color? I'm using Terminal on Gnome. From horacius.rex at gmail.com Tue Jan 8 09:29:58 2008 From: horacius.rex at gmail.com (Horacius ReX) Date: Tue, 8 Jan 2008 06:29:58 -0800 (PST) Subject: Look for a string on a file and get its line number References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <03a301c851e1$4f211a00$0203a8c0@MOUSE> Message-ID: <39901b17-8ac2-4c04-8e71-3e27fc795efc@i3g2000hsf.googlegroups.com> Hi, thanks for the help. Then I got running the following code; #!/usr/bin/env python import os, sys, re, string, array, linecache, math nlach = 12532 lach_list = sys.argv[1] lach_list_file = open(lach_list,"r") lach_mol2 = sys.argv[2] # name of the lachand mol2 file lach_mol2_file = open(lach_mol2,"r") n_lach_read=int(sys.argv[3]) # Do the following for the total number of lachands # 1. read the list with the ranked lachands for i in range(1,n_lach_read+1): line = lach_list_file.readline() ll = string.split (line) #print i, ll[0] lach = int(ll[0]) # 2. for each lachand, print mol2 file # 2a. find lachand header in lachand mol2 file (example; kanaka) # and return line number line_nr = 0 for line in lach_mol2_file: line_nr += 1 has_match = line.find('kanaka') if has_match >= 0: print 'Found in line %d' % (line_nr) # 2b. print on screen all the info for this lachand # (but first need to read natoms and nbonds info) # go to line line_nr + 1 ltr=linecache.getline(lach_mol2, line_nr + 1) ll=ltr.split() #print ll[0],ll[1] nat=int(ll[0]) nb=int(ll[1]) # total lines to print: # header, 8 # at, na # b header, 1 # n # lastheaders, 2 # so; nat + nb + 11 ntotal_lines = nat + nb + 11 # now we go to the beginning of the lachand # and print ntotal_lines for j in range(0,ntotal_lines): print linecache.getline(lach_mol2, line_nr - 1 + j ) which almost works. In the last "for j" loop, i expected to obtain an output like: sdsdsdsdsdsd sdsdsfdgdgdgdg hdfgdgdgdg but instead of this, i get: sdsdsdsdsdsd sdsdsfdgdgdgdg hdfgdgdgdg and also the program is very slow. Do you know how could i solve this ? thanks Tim Chase wrote: > >> I have to search for a string on a big file. Once this string > >> is found, I would need to get the number of the line in which > >> the string is located on the file. Do you know how if this is > >> possible to do in python ? > > > > This should be reasonable: > > > >>>> for num, line in enumerate(open("/python25/readme.txt")): > > if "Guido" in line: > > print "Found Guido on line", num > > break > > > > > > Found Guido on line 1296 > > Just a small caveat here: enumerate() is zero-based, so you may > actually want add one to the resulting number: > > s = "Guido" > for num, line in enumerate(open("file.txt")): > if s in line: > print "Found %s on line %i" % (s, num + 1) > break # optionally stop looking > > Or one could use a tool made for the job: > > grep -n Guido file.txt > > or if you only want the first match: > > sed -n '/Guido/{=;p;q}' file.txt > > -tkc From ivlenin at gmail.com Thu Jan 24 00:51:20 2008 From: ivlenin at gmail.com (I V) Date: Thu, 24 Jan 2008 05:51:20 GMT Subject: Problems getting Python scripts to run on server References: <83ae0f82-e9af-433e-936d-d5b5600a315e@j20g2000hsi.googlegroups.com> Message-ID: On Wed, 23 Jan 2008 19:41:17 -0800, Yansky wrote: > Hi, I'm having a lot of problems getting any Python scripts to run on my > website. I have put them in the cgi-bin directory and chmodded both the > directory and files to 755. But when I try to access the script, I get a > 404 error: http://forboden.com/cgi-bin/wp.py Note that you don't get a 404 error _from the web server_ - you get it from wordpress (or at least, I do when I look at your page). So what I think is happening is that either the server, or wordpress, doesn't see a file at the URL "/cgi-bin/wp.py", and so it thinks your are trying to access a wordpress post, and http://forboden.com/cgi-bin/wp.py is getting translated to http://forboden.com/index.php/cgi-bin/wp.py . I suspect the problem is in the rewrite rules in the .htaccess in your root directory. My wordpress installation has these rewrite rules: RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d Which, as I understand it mean "not a file" and "not a directory" respectively. If your cgi-bin is not in your document root, presumably cgi-bin/wp.py will indeed show up as not being a file or directory. I'm no mod_rewrite wizard, but looking at the docs[1], maybe you could replace those two lines above with: RewriteCond %{REQUEST_URI} !-U (thought the docs say this "can impact your server's performance!") I'm just guessing at the cause of your problem, but I hope this helps. [1] http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html From ggpolo at gmail.com Mon Jan 7 08:30:52 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 11:30:52 -0200 Subject: How to refer to the current module? In-Reply-To: References: Message-ID: 2008/1/7, Mike : > I want to do something like the following (let's pretend that this is > in file 'driver.py'): > > #!/bin/env python > > import sys > > def foo(): > print 'foo' > > def bar(arg): > print 'bar with %r' % arg > > def main(): > getattr(driver, sys.argv[1])(*sys.argv[2:]) > > if __name__=='__main__': > main() > > > Essentially what I'm trying to get at here is dynamic function > redirection, like a generic dispatch script. I could call this as > > python driver.py foo > > or > > python driver.py bar 15 > > and at any time later I can add new functions to driver.py without > having to update a dispatch dict or what-have-you. > > The problem is, 'driver' doesn't exist in main() line 1. If I 'import > driver' from the command line, then getattr(driver, ...) works, but > it's not bound here. > > Is there any way around this? Can I somehow scope the 'current > module' and give getattr(...) an object that will (at run time) have > the appropriate bindings? globals() =) > > Thanks in advance for all advice! > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From ckimyt at gmail.com Fri Jan 4 09:13:13 2008 From: ckimyt at gmail.com (Mike) Date: Fri, 4 Jan 2008 06:13:13 -0800 (PST) Subject: Strange varargs issue References: Message-ID: <5d2f89f7-58bb-48c1-bde1-6dfddfb67cac@41g2000hsy.googlegroups.com> You know, every once in a while, self really bites me. (I program in Java too much) Thanks for everyone who replied quickly. Mike wrote: >> [ a bunch of crap because I forgot self, nevermind sorry ] From B.Ogryczak at addr.in.reply-to.invalid Tue Jan 22 16:20:14 2008 From: B.Ogryczak at addr.in.reply-to.invalid (Bart Ogryczak) Date: Tue, 22 Jan 2008 21:20:14 +0000 (UTC) Subject: Bug in __init__? References: <4795b788$0$11545$426a34cc@news.free.fr> Message-ID: On 2008-01-22, citizen Bruno Desthuilliers testified: >> from copy import copy >> ### see also deepcopy >> self.lst = copy(val) > > What makes you think the OP wants a copy ? I?m guessing he doesn?t want to mutate original list, while changing contents of self.lst. bart -- "ch?opcy dali z siebie wszystko, z czego tv pokaza?a g??wnie bebechy" http://candajon.azorragarse.info/ http://azorragarse.candajon.info/ From jr9445 at ATT.COM Thu Jan 10 17:27:03 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 10 Jan 2008 16:27:03 -0600 Subject: Newbie question on Classes In-Reply-To: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> References: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.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 Adrian Wood > Sent: Thursday, January 10, 2008 4:47 PM > To: python-list at python.org > Subject: Newbie question on Classes > > > I can call man.state() and then woman.state() or Person.state(man) and > Person.state(woman) to print the status of each. This takes time and > space however, and becomes unmanageable if we start talking about a > large number of objects, and unworkable if there is an unknown number. > What I'm after is a way to call the status of every instance of Man, > without knowing their exact names or number. > How about searching the garbage collector? import gc from random import random class Person: def __init__(self): self.data= random() * 1000 + 1 def WhoAmI(self): return self.data a = Person() b = Person() for i in gc.get_objects(): try: # classes have __class__ and __dict__ defined according to the docs if i.__class__ and i.__dict__ : print i.__class__ if str(i.__class__) == '__main__.Person': print "\tI am", i.WhoAmI() except: pass ***** 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. GA622 From mr.cerutti at gmail.com Thu Jan 10 09:03:34 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 10 Jan 2008 09:03:34 -0500 Subject: docstrings style question In-Reply-To: <13obcbumpitbe23@corp.supernews.com> References: <13obcbumpitbe23@corp.supernews.com> Message-ID: <51302a8c0801100603o7f893392s3d83070f313c4ddf@mail.gmail.com> On Jan 10, 2008 12:47 AM, Steve Brown wrote: > I've got a series of modules which look like this: > > #************ > # > # Temperature Sense Test > # > #************ > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > > I don't like the duplicated information: But the comment is attractive, and > the docstring self.__doc__ is already in use in the test log. I've read that > all modules and classes should have docstrings, but I don't really have > anything else to say, and each module contains only one class. I don't think > that > > """Temperature Sense Test""" > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > would be a real improvement. > > What do you think? I recommend a careful reading of PEP 257. You shouldn't waste your time creating (at best) decorative comments, like: #************ # # Temperature Sense Test # #************ class Test3(ar_test.AR_TEST): """Temperature Sense Test"" Remember that comments have to maintained along with the rest of the code, so unnecessary ones just create more work for you. Any time you can replace a comment with self-explanatory code, you should. Here's a vast improvement: class TemperatureSenseTester(ar_test.AR_TEST): -- Neil Cerutti From bignose+hates-spam at benfinney.id.au Fri Jan 4 18:13:07 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 05 Jan 2008 10:13:07 +1100 Subject: MRO Error on Multiple Inheritance? References: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> Message-ID: <87prwhp4l8.fsf@benfinney.id.au> Ming writes: > I'm working through Wesley Chun's CPP2e and got this error on 13.11.1, > pp 548 where his interpreter snippet shows no problems: I don't know what a "CPP2e" is. Is it a book? Can you give the ISBN? > ActivePython 2.5.1.1 (ActiveState Software Inc.) b > Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [ > win32 > Type "help", "copyright", "credits" or "license" f > >>> class A(object): pass > ... > >>> class B(A): pass > ... > >>> class C(B): pass > ... > >>> class D(A, B): pass > ... > Traceback (most recent call last): > File "", line 1, in > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases A, B > > (I submitted the problem to the author but I'm not sure I'll ever hear > back.) I'm guessing that this kind of diamond inheritance is > prohibited by the interpreter, and that his lack of error messages > from the interpretation is due to actually leaving out the "class > B(A): pass" Can someone shed light? Thanks. That's not an example of diamond inheritance because classes A and B are not distinct classes with a *common* base. Instead, they're in a direct parent-child relationship. So there's no sense in defining class D to inherit from both A *and* B. To get a descendent of both those classes, inheriting from B is sufficient. It should rather be:: class D(B): pass -- \ "Pinky, are you pondering what I'm pondering?" "Uh, I think so, | `\ Brain, but we'll never get a monkey to use dental floss." -- | _o__) _Pinky and The Brain_ | Ben Finney From bbxx789_05ss at yahoo.com Thu Jan 24 11:13:16 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 24 Jan 2008 08:13:16 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <5vr1ekF1njt09U2@mid.uni-berlin.de> Message-ID: <0b93cf6e-0f55-4421-afde-9246093a5d65@v17g2000hsa.googlegroups.com> On Jan 24, 1:44?am, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote: > > My second question is: is there any one who has tested very long mbcs > > decode? I tried to decode a long(20+MB) xml yesterday, which turns out > > to be very strange and cause SAX fail to parse the decoded string. > > That's because SAX wants bytes, not a decoded string. ?Don't decode it > yourself. > encode() converts a unicode string to a regular string. decode() converts a regular string to a unicode string. So I think what Marc is saying is that SAX needs a regular string(i.e. bytes) not a decoded string(i.e. a unicode string). From peng.kyo at gmail.com Wed Jan 16 02:18:52 2008 From: peng.kyo at gmail.com (J. Peng) Date: Wed, 16 Jan 2008 15:18:52 +0800 Subject: no pass-values calling? In-Reply-To: <13orb15pqgk4h96@corp.supernews.com> References: <13or6esikdrqa33@corp.supernews.com> <13orb15pqgk4h96@corp.supernews.com> Message-ID: <18c1e5f20801152318o3f5fda3dqabca86b351053637@mail.gmail.com> On Jan 16, 2008 3:03 PM, Dennis Lee Bieber wrote: > On Wed, 16 Jan 2008 13:59:03 +0800, "J. Peng" > declaimed the following in comp.lang.python: > > > > How to modify the array passed to the function? I tried something like this: > > > > >>> a > > [1, 2, 3] > > >>> def mytest(x): > > ... x=[4,5,6] > > x is unqualified (in my terms), so you have just disconnected it > from the original argument and connected it to [4,5,6] > Ok, thanks. But there is a following question,when we say, >>> x=[1,2,3] we create a list.then we say, >>> x=[4,5,6] we create a new list and assign it to x for future use. How to destroy the before list [1,2,3]? does python destroy it automatically? From Luke.Visinoni at gmail.com Tue Jan 15 14:11:17 2008 From: Luke.Visinoni at gmail.com (Luke) Date: Tue, 15 Jan 2008 11:11:17 -0800 (PST) Subject: Data mapper - need to map an dictionary of values to a model References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com> <05398cdb-4c75-499b-bb52-d5de627a0906@j20g2000hsi.googlegroups.com> Message-ID: <49753620-df70-4f1a-95bc-7b23667d9edc@s13g2000prd.googlegroups.com> On Jan 15, 1:53 am, bearophileH... at lycos.com wrote: > Luke: > > >What design patterns would you use here?< > > What about "generator (scanner) with parameters"? :-) > > Bye, > bearophile I'm not familiar with this pattern. I will search around, but if you have any links or you would like to elaborate, that would be wonderful. :) From cp02sdh02 at sneakemail.com Mon Jan 7 17:13:41 2008 From: cp02sdh02 at sneakemail.com (C Martin) Date: 7 Jan 2008 22:13:41 -0000 Subject: Tkinter variable trace problem Message-ID: <17687-68562@sneakemail.com> What am I doing wrong in this code? The callback doesn't work from the Entry widget. ##start code import Tkinter tk = Tkinter.Tk() var = Tkinter.StringVar() print var._name def cb(name, index, mode): print "callback called with name=%r, index=%r, mode=%r" % (name, index, mode) varValue = tk.getvar(name) print " and variable value = %r" % varValue var.trace('w', cb) var.set('test') entry = Tkinter.Entry(tk, textvariable=var) entry.pack() tk.mainloop() ##end code It produces the following output. The first three lines appear right away, and the exception occurs when you type in the entry widget: >test.py PY_VAR0 callback called with name='PY_VAR0', index='', mode='w' and variable value = 'test' callback called with name='PY_VAR0', index='', mode='w' Exception in Tkinter callback Traceback (most recent call last): File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) File "D:\APCC\Projects\Utilities\VisualData\test.py", line 9, in cb varValue = tk.getvar(name) File "C:\Python25\lib\lib-tk\Tkinter.py", line 421, in getvar return self.tk.getvar(name) TclError: can't read "PY_VAR0": no such variable > -------------------------------------- Protect yourself from spam, use http://sneakemail.com From simon at simonwillison.net Thu Jan 3 08:31:46 2008 From: simon at simonwillison.net (Simon Willison) Date: Thu, 3 Jan 2008 05:31:46 -0800 (PST) Subject: Treating a unicode string as latin-1 Message-ID: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Hello, I'm using ElementTree to parse an XML file which includes some data encoded as cp1252, for example: Bob\x92s Breakfast If this was a regular bytestring, I would convert it to utf8 using the following: >>> print 'Bob\x92s Breakfast'.decode('cp1252').encode('utf8') Bob's Breakfast But ElementTree gives me back a unicode string, so I get the following error: >>> print u'Bob\x92s Breakfast'.decode('cp1252').encode('utf8') Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/encodings/cp1252.py", line 15, in decode return codecs.charmap_decode(input,errors,decoding_table) UnicodeEncodeError: 'ascii' codec can't encode character u'\x92' in position 3: ordinal not in range(128) How can I tell Python "I know this says it's a unicode string, but I need you to treat it like a bytestring"? Thanks, Simon Willison From sturlamolden at yahoo.no Thu Jan 17 12:21:16 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 17 Jan 2008 09:21:16 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <1966c5b2-09fc-4523-b957-54815d0bd10f@m34g2000hsb.googlegroups.com> On 17 Jan, 14:38, Sacred Heart wrote: > Okey, so if my array1 is has 4 elements, and array2 has 6, it won't > loop trough the last 2 in array2? How do I make it do that? In that case your problem is the data. You'll either have to truncate one array and/or pad the other. Or is this what you want? n = len(array1) if len(array1) < len(array2) else len(array2) for number,letter in zip(array1[:n],array2[:n]): print "%s %s" % (number,letter) reminder = array1[n:] if len(array1) > len(array2) else array2[n:] for x in reminder: print x From sbrown at skyesystems.com Thu Jan 31 12:37:52 2008 From: sbrown at skyesystems.com (Stephen Brown) Date: Thu, 31 Jan 2008 19:37:52 +0200 Subject: pyExcelerator - Can I read and modify an existing Excel-WorkBook? Message-ID: <47A20770.7010900@skyesystems.com> Yes indeed, pyExcelerator does support reading data from excel spreadsheets. An example of how to do this is included in the file xls2csv-gerry.py under the directory ... pyExcelerator/examples/tools Syntax is pretty straight forward. extract_all = parse_xls(filename, CP = None) where CP is the encoding format used within tht file. Uses same codes that xlrd uses, ie 'cp437' = US English. All you need is the "parse_xls" command and simply let it iterate through your spreadsheet file. EXAMPLE: fname = "D:\\Directory\\myfile.xls" # an example filename for sheet_name, values in parse_xls(fname ): # parse_xls(arg) -- default encoding print " name of sheet is = ", sheet_name, Alternatively you can extract everything in one go... extract_all = parse_xls(fname) From gagsl-py2 at yahoo.com.ar Tue Jan 22 20:14:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 Jan 2008 23:14:14 -0200 Subject: Using utidylib, empty string returned in some cases References: <69c38011-4af7-4305-95fb-c824019c1550@v4g2000hsf.googlegroups.com> Message-ID: En Tue, 22 Jan 2008 15:35:16 -0200, Boris escribi?: > I'm using debian linux, Python 2.4.4, and utidylib (http:// > utidylib.berlios.de/). I wrote simple functions to get a web page, > convert it from windows-1251 to utf8 and then I'd like to clean html > with it. Why the intermediate conversion? I don't know utidylib, but can't you feed it with the original page, in the original encoding? If the page itself contains a "meta http-equiv" tag stating its content-type and charset, it won't be valid anymore if you reencode the page. -- Gabriel Genellina From http Mon Jan 28 02:21:58 2008 From: http (Paul Rubin) Date: 27 Jan 2008 23:21:58 -0800 Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <7xbq76pva9.fsf@ruckus.brouhaha.com> <7x1w82xymd.fsf@ruckus.brouhaha.com> Message-ID: <7xsl0iwh2h.fsf@ruckus.brouhaha.com> Paddy writes: > > Fair enough. My main issue was against the notion that random testing > > is the only thing necessary. > > Sorry Paul if I may have given that impression, its just that when you > bring in random testing to a design that until then had only directed > tests you can see the bug rate jump up! Sure, I agree with that as well, what I should have said was I have an issue with the notion that testing (of any sort) is all that is needed to reach high assurance. Directed and random tests BOTH failed to catch the FDIV bug. You need methods that demonstrate the absence of defects, not just fail to demonstrate their presence. From arnodel at googlemail.com Mon Jan 28 17:44:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 28 Jan 2008 14:44:27 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> Message-ID: On Jan 28, 10:27 pm, Tim Chase wrote: > > I've modified my little decorator (see Test1, Test2, Test3 for > > usage). I'll post it later on the cookbook if there seems to be no > > bugs and noone raises valid point against it:) > > One other area that was mentioned obliquely: preservation of > docstrings (and other function attributes) I think @wraps(...) does this (definitely copies __doc__). -- Arnaud From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 05:49:16 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 11:49:16 +0100 Subject: python recursive function In-Reply-To: References: <47872e94$0$29356$426a74cc@news.free.fr> Message-ID: <478749a0$0$22238$426a34cc@news.free.fr> Duncan Booth a ?crit : > Bruno Desthuilliers > wrote: > >> You want: >> return bears(n - 42) > > Actually, no he doesn't. He needs to explore all options when the first > attempt fails. Possibly - I didn't bother checking the algorithm correctness, just pointed out an obvious newbie programming error. > But I'm not going to write his homework for him. Nor do I. From gherzig at fmed.uba.ar Mon Jan 7 08:48:20 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Mon, 07 Jan 2008 10:48:20 -0300 Subject: dealing with binary files Message-ID: <47822DA4.9020401@fmed.uba.ar> Hi all. Im trying to read a binary data from an postgres WAL archive. If i make a xfile = open('filename', 'rb').xreadlines() line = xfile.next() i see this sort of thing: ']\xd0\x03\x00\x01\x00\x00\x00\r\x00\x00\x00\x00\x00\x00JM//DI+,D\x00\x00\x00\x01$\x00\x00\x00\x7f\x06\x00\x00y\r\t\x00\x02\x0f\t\x00\x00\x00\x10\x00)\x00\x01\x00\x12\x08 \x00^\xc2\x0c\x00\x08\x00\x00\x003001({\xe8\x10\r\x00\x00\x00\xe4\xff\xffI\x10?l\x01@\x00\x00\x00$\x00\x00\x00\x00\n' This file suppose to have some information about database activity, but at this point i cant do more than this, because i cant figure out what to do in order to have some 'readable' text. Im guessing is some C code, im reading the struct module to see if it helps, but im not into C programming, and im lost at the start of my problem. Can someone point me out some advice? Thanks! Gerardo From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 17 11:57:24 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 17 Jan 2008 17:57:24 +0100 Subject: Perl Template Toolkit: Now in spicy new Python flavor In-Reply-To: References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> <13a75830-5416-4fe3-9460-018e1240e6e6@e32g2000prn.googlegroups.com> Message-ID: <478f88c3$0$23530$426a74cc@news.free.fr> eefacm at gmail.com a ?crit : > On Jan 15, 1:45 pm, George Sakkis wrote: >>> eef... at gmail.com wrote: >>>> I'd like to inform the Python community that the powerful and popular >>>> Template Toolkit system, previously available only in its original >>>> Perl implementation, is now also available in a beta Python >>>> implementation: >>>> http://tt2.org/python/index.html >>>> I created this port both as a fun programming project, and for use in >>>> environments where Perl is not available, for reasons technical, >>>> cultural, or otherwise. The extensive Perl test suites have also been >>>> ported, and most templates require no or very little modification. > >> How does it compare with other "mainstream" Python template engines >> such as Cheetah, Mako, etc. ? > > I can't claim a comprehensive familiarity with Python template > offerings, but all of the packages approved for use at my previous > workplace left me cold. The most popular were ClearSilver and Django, > and both felt horribly limiting compared to the Template Toolkit, ClearSilver is not a Python templating system, but a C templating system with bindings for various languages including Python. Being (by design) language-agnostic, it's indeed *very* limited (and that's an understatement). wrt/ Django templates, it indeed imposes severe limitations on what can be simply expressed when you are familiar with Python. This is by design - since it has been designed to be safe to use for non-programmers. Now while not my cup of tea, it has proven to be fairly usable, quite less limiting that what I feared at first, and really easy to use for our web designer/integrator. Now there are way more flexible/expressive templating systems in Python, either XML oriented (genshi) or more generic (my favorite one so far being Mako). But anyway, I'm not the one that will complain with Perl templating systems being ported to Python - FWIW, Mako was born from it's author previous experience with porting Mason to Python !-) From lists at cheimes.de Fri Jan 25 07:07:45 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 25 Jan 2008 13:07:45 +0100 Subject: Minimum Requirements for Python In-Reply-To: References: Message-ID: justinrob at gmail.com wrote: > Can someone tell me the minimum requitements for Python as I can't > find it anwhere on the site. I have 3 PC's which are only 256mb RAM, > wanted to know if this was sufficenent. Python runs even on mobile phones with far less memory. However the memory consumption depends on the application. Christian From nick.fabry at coredump.us Tue Jan 29 23:50:18 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Tue, 29 Jan 2008 23:50:18 -0500 Subject: ISO with timezone In-Reply-To: References: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Message-ID: On Jan 29, 2008, at 13:56, nik wrote: > Thanks, > that does help and now I have: > >>>> from datetime import datetime, tzinfo, timedelta >>>> import time >>>> class TZ(tzinfo): > ... def utcoffset(self,dt): return timedelta(seconds=time.timezone) > ... >>>> print datetime(2008,2,29,15,30,11,tzinfo=TZ()).isoformat() > 2008-02-29T15:30:11+8:00 > > > But what I want to know now it how to get the actual time into the > expression instead of typing the 2008,2,29,15.... > So something like: >>> print > datetime(time.gmtime(),tzinfo=TZ()).isoformat(), but that doesn't > work. > > I realize that I could do: >>>> t = time.gmtime() >>>> print >>>> datetime(t[0],t[1],t[2],t[3],t[4],t[5],tzinfo=TZ()).isoformat() > > but I imagine there might be a cleaner way of doing this. > > Thanks, > Nik > No need for the ugliness! The constructor for class datetime has a method, .now() that returns the current date and time, as a naive datetime object (i.e. no tzinfo attached). Since you want an aware datetime object (one with a tzinfo object attached), you can do it simply by feeding .now the tzinfo object you want attached, as below: >>> print datetime.now(TZ()).isoformat('T') 2008-01-29T23:43:16.809049-05:00 See PSL, Sect. 5.1.4 Dates and Times are a bit ugly in Python. Don't be discouraged, but you do need to understand them quite well to get bug-free code that plays with them. Nick Fabry > > On Jan 28, 9:10 pm, "Nicholas F. Fabry" > wrote: >> Hello, nik. >> >> On Jan 28, 2008, at 21:03, nik wrote: >> >> >> >>> Hi, >> >>> How does one express the time in ISO format with the timezone >>> designator? >> >>> what I want is YYYY-MM-DDThh:mm:ss.sTZD >> >>>> From the documentation I see: >>>>>> from datetime import tzinfo, timedelta, datetime >>>>>> class TZ(tzinfo): >>> ... def utcoffset(self, dt): return timedelta(minutes=-399) >>> ... >>>>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') >>> '2002-12-25 00:00:00-06:39' >> >>> and I've also figured out: >>>>>> datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3] >>> '2008-01-23T11:22:54.130' >> >>> But can't figure out how to fit them together. >> >> There is nothing there to 'fit together' - in the first example >> given, >> the datetime object has no time component specified, so it fills in >> default vaules of zero. The following should make this clear: >> >>>>> your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ()) >>>>> print your_time >> 2008-02-29 15:30:11-05:00 >>>>> print your_time.isoformat('T') >> 2008-02-29T15:30:11-05:00 >> >> If you wish to append the NAME of the tzinfo object instead of its >> offset, that requires a bit more playing around (along with a >> properly >> defined tzinfo object - check out dateutil or pytz for a concrete >> implementation of tzinfo subclasses (i.e. timezones)), but the >> following would work: >> >>>>> print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z') >> 2008-02-29T15:30:11 EST >> >> For details on how the .strftime method works, see Python Standard >> Library, Section 14.2. >> >> I hope this helps! >> >> Nick Fabry >> >>> Thank you, >>> Nik >>> -- >>> http://mail.python.org/mailman/listinfo/python-list > >> > -- > http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Sun Jan 20 18:09:17 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jan 2008 15:09:17 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> Message-ID: On Jan 21, 8:58 am, pythonewbie wrote: > I just would like to know if I would ALWAYS find the install directory > in sys.path[6] and site-packages directory in sys.path[7] on any Win32 > platform and sys.path[2] and site-packages directory in sys.path[6] on > any Linux platform. > > If the reply is : "YES you can be sure of it !" No, you can't be sure of any such thing. In general in computing assuming a fixed position in a variable-length list is a nonsense. Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> from pprint import pprint as pp >>> pp([(x, p) for x, p in enumerate(sys.path)]) [(0, ''), (1, 'c:\\python25\\lib\\site-packages\\setuptools-0.6c3-py2.5.egg'), (2, 'C:\\WINDOWS\\system32\\python25.zip'), (3, 'c:\\python25\\DLLs'), (4, 'c:\\python25\\lib'), (5, 'c:\\python25\\lib\\plat-win'), (6, 'c:\\python25\\lib\\lib-tk'), (7, 'c:\\python25'), (8, 'c:\\python25\\lib\\site-packages'), (9, 'c:\\python25\\lib\\site-packages\\win32'), (10, 'c:\\python25\\lib\\site-packages\\win32\\lib'), (11, 'c:\\python25\\lib\\site-packages\\Pythonwin')] >>> Something like this might be more reliable: >>> import sys, re >>> for p in sys.path: ... m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p) ... if m: ... print m.group(1, 0) ... break ... else: ... raise Exception('Huh?') ... ('c:\\python25', 'c:\\python25\\lib\\site-packages') >>> > > All would be great for me and I would be ready to create a script to > detect with a reliable manner the installation dir. et site-packages > dir. for all my Linux/Win32 Python apps. You mentioned Python versions back to 2.1 earlier. However you evidently haven't bothered to start up Python 2.1 and look at sys.path: C:\junk>\python21\python Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import sys; sys.path ['', 'C:\\junk', 'C:\\python21\\DLLs', 'C:\\python21\\lib', 'C:\ \python21\\lib\\ plat-win', 'C:\\python21\\lib\\lib-tk', 'C:\\python21'] >>> Before you rush out and re-invent the wheel, have a look at this: http://www.python.org/community/sigs/current/distutils-sig/ You may like to re-ask your questions on the distutils mailing list. HTH, John From ivlenin at gmail.com Sun Jan 27 01:08:47 2008 From: ivlenin at gmail.com (I V) Date: Sun, 27 Jan 2008 06:08:47 GMT Subject: how to make format operator % work with unicode as expected References: <13po55nc0q0s06@corp.supernews.com> Message-ID: On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: > Yes, it is true that %s already support unicode, and I did not > contradict that. But it counts the number of bytes instead of > characters, and makes things like %-20s out of alignment. If you don't > understand my assertion, please don't argue back and I am only > interested in answers from those who are qualified. What version of python are you using? On python 2.4 and 2.5 on linux, %-20s counts the characters, not the bytes, or, I think it does. when I run: >>> print u'%-20s|\n%-20s|' % (u'foo bar', u'foo b?r') the output is: foo bar | foo b?r | From timr at probo.com Sat Jan 12 00:49:19 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 12 Jan 2008 05:49:19 GMT Subject: FindWindowById returns None..... ? References: Message-ID: Soren wrote: > >I'm trying to split my GUI into several files since its beginning to >become a bit large.. I've placed a panel class inside gui2.py, but it >needs some information from a panel in gui1.py... if I import gui1 in >gui2 and try to find the panel by its ID, (using the Id generated in >gui1) I get a None value returned?? using findwindowbyid in gui1 on >the same ID works fine.. > >I'm guessing i'm doing this the wrong way, can anyone comment on this? Post enough code so we can see how you are doing it. Your description isn't specific enough; there are several ways to do it, some right, some wrong... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From namesagame-usenet at yahoo.com Thu Jan 10 18:22:59 2008 From: namesagame-usenet at yahoo.com (gamename) Date: Thu, 10 Jan 2008 15:22:59 -0800 (PST) Subject: Win32+Cygwin+ActiveState Python+SCons Message-ID: <84d7b056-f46b-4f31-845d-2e27f676ce07@t1g2000pra.googlegroups.com> Hi, I just installed scons on win32 that has cygwin but uses ActiveState python. If I do "import SCons", the lib isn't found. The win32 installer seemed very complete, but the scons lib doesn't seem to be in any dir python knows about. Is there another install step I need to do? TIA, -T From bazwal at googlemail.com Mon Jan 7 16:18:19 2008 From: bazwal at googlemail.com (Baz Walter) Date: Mon, 7 Jan 2008 21:18:19 +0000 (UTC) Subject: Does Python cache the startup module? References: <3c346bb2-c84a-4268-9e7b-b0c601fe9710@s12g2000prg.googlegroups.com> Message-ID: John Machin lexicon.net> writes: > If you execute that stuff inside a function (see below) instead of in > global scope, do you get the same effect? Thanks for your reply. No, running it inside a function means I can't rely on python to garbage collect, so there will be widgets left over whether I've changed names or not. See Frederik Lundh's last message to see what's really happening. From toby at tobiah.org Thu Jan 17 14:43:08 2008 From: toby at tobiah.org (Tobiah) Date: Thu, 17 Jan 2008 11:43:08 -0800 Subject: import from question In-Reply-To: References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> <478d04d4$0$26042$88260bb3@free.teranews.com> <87tzleb2st.fsf@benfinney.id.au> <478E658A.9070003@tobiah.org> <87prw1bftx.fsf@benfinney.id.au> <478e87f6$0$26054$88260bb3@free.teranews.com> Message-ID: <478fa3d1$0$26058$88260bb3@free.teranews.com> >> Ok, I get it. I was locally importing a pointer to an integer > > Really? What language were you using? Python doesn't have pointers. What term do you prefer? Reference? Object id holder? -- Posted via a free Usenet account from http://www.teranews.com From Lie.1296 at gmail.com Sat Jan 5 13:12:19 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 5 Jan 2008 10:12:19 -0800 (PST) Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> Message-ID: <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> On Jan 5, 5:40?pm, MartinRineh... at gmail.com wrote: > Jeroen Ruigrok van der Werven wrote: > > > Shouldn't this be: > > > self.startLoc = start > > self.stopLoc = stop > > Thanks! Of course it should. Old Java habits die slowly. No, seriously it isn't Java habits only, most other languages wouldn't need explicit calling of class name. From rdrink at gmail.com Sat Jan 26 22:02:38 2008 From: rdrink at gmail.com (Robb Lane (SL name)) Date: Sat, 26 Jan 2008 19:02:38 -0800 (PST) Subject: file write question Message-ID: <62b96f11-1a81-4be8-9dcb-348ee38ebe16@f10g2000hsf.googlegroups.com> I have written a script which: - opens a file - does what it needs to do, periodically writing to the file... for a few hours - then closes the file when it's done So my question is: Would it be better to 'open' and 'close' my file on each write cycle? e.g. def writeStuff(content): myFile = open('aFile.txt', 'a+') myFile.write(content) myFile.close() ... or just leave it till it's done? I don't need to use the file contents until the script is done (although it would be nice... just to check it while it's working), so just curious what people think is the better method. - rd From thunder54007 at gmail.com Wed Jan 23 04:46:30 2008 From: thunder54007 at gmail.com (thunder54007 at gmail.com) Date: Wed, 23 Jan 2008 01:46:30 -0800 (PST) Subject: what's wrong with the wmi.Terminate() method? Message-ID: hi, here is my script: import win32con import time import wmi c = wmi.WMI() for process in c.Win32_Process(name = "notepad.exe"): print process.ProcessId, process.Name process.Terminate () when I have only one notepad.exe process in my system, this works fine, but when I have more than one notepad.exe , after terminal the first notepad.exe, the Terminate() for the second notepad.exe process will generate the following error: 3156 notepad.exe 6100 notepad.exe Traceback (most recent call last): File "F:\thunder\python\program\wmi \create_terminal_notepad.py", line 16, in module> process.Terminate () File "C:\Python25\Lib\site-packages\wmi.py", line 376, in __call__ handle_com_error (error_info) File "C:\Python25\Lib\site-packages\wmi.py", line 188, in handle_com_error raise x_wmi, "\n".join (exception_string) wmi.x_wmi: -0x7ffdfff7 - ????(ps: exception happened)? Error in: SWbemObjectEx -0x7ffbeffe - ???(ps:Can not found) I don't know why this happend, is there somebody could give me a hand? From josepharmbruster at gmail.com Tue Jan 8 13:47:42 2008 From: josepharmbruster at gmail.com (josepharmbruster at gmail.com) Date: Tue, 8 Jan 2008 10:47:42 -0800 (PST) Subject: Python or PowerShell ? Message-ID: I am all about using the right tool for the right purposes, which is why I have started reading the GettingStarted guide to PowerShell. I am curious if any other pythoneers have ventured into the world of PowerShell. Mostly, I am interested in grabbing perspectives on the differences noticed from those that have working experience with using both. I dug up one article from Google that talked about comparison but that was about it. http://www.simple-talk.com/sql/database-administration/comparing-python-and-powershell-dba-scripting-/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 21 04:45:41 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 10:45:41 +0100 Subject: Default attribute values pattern In-Reply-To: References: Message-ID: <4794697f$0$16980$426a74cc@news.free.fr> David Tweet a ?crit : (please, don't top-post) > > def Grab(argdict, key, default): cf pep08 for naming conventions... > """Like argdict.get(key, default), but also deletes key from argdict.""" > if key in argdict: > retval = argdict["key"] > del(argdict[key]) > else: > retval = default > return retval def grab(kw, key, default=None): try: return kw.pop(key) except KeyError: return default (snip) From hetileva69812 at hotmail.com Wed Jan 16 13:41:33 2008 From: hetileva69812 at hotmail.com (hetileva69812) Date: Wed, 16 Jan 2008 13:41:33 -0500 Subject: Current Special Vicoden Message-ID: Living in Pain. We can help Pain Meds Online discoveyamazing.com From shansen at advpubtech.com Fri Jan 4 11:54:45 2008 From: shansen at advpubtech.com (Stephen Hansen) Date: Fri, 4 Jan 2008 08:54:45 -0800 Subject: dictionary/hash and '1' versus 1 In-Reply-To: References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> Message-ID: <7a9c25c20801040854t73054af4pac8ce07b31d85c8f@mail.gmail.com> > > > A single integer is distinctly different from a sequence of characters > in > > some encoding that may just happen to contain representations of a > > number.... so they'll hash differently :) > > Depends on the context. The machine encoding may be different, but > in human terms they "should" be the same. Perl managed to achieve an > impressive blend of presenting data as human friendly or as machine bits > when it made sense to do so. So much so, that Perl is probably the only > language I've used that will do what you mean instead of what you say. > Nice, but frightening in some ways. Frightening is the word I'd use-- nice is not ;-) For me, the thought that "assert (1 == '1') is True" should pass is alien and alarming to the point of rising to, "That's obviously wrong." Of course, I know other languages do things their own way .. so to each their own :) Python's philosophy of "explicit is better then implicit" is one that I appreciate and have found to be a saving grace in maintaining huge systems over the last few years. I could so see myself learning perl and sending the exact inverse message to a perl mailing list; I actually /have/ code which relies upon the exact case of numbers and strings never being implicitly converted to compare to each-other. :) Different starting point in mindset, is all. Type casting is easy, IFF you remember to do so. The problem was > that I missed the fact that one (important) function was returning a string > instead of an int, and since Python supports heterogenous data structures, > the human has to remember to keep the key's data type homongenous. > This is true; there does need to be a more aware/complete understanding of the input/output API of the code you're using. That and Perl does so much automatic type conversion in such a > sensible way, that I stopped worrying about mixing data types, which is > making the Python transition a tad more error prone. Because of Perl, I > almost consider automatic type casting to be the next "you don't have to > manage your own memory" that people loved about Java. =O Heathen. ;-) I prescribe meditation, green leaf tea, and continual chanting of the sacred scroll provided by "import this" until this unwholesome adoration of black magic practices has been cleansed from your mind. In all seriousness, I can see the appeal; but prefer the strongly typed world. Partly because of where I use it, when we do a LOT of CORBA communication (which is massively strongly typed in and of itself), protocols and careful data management/conversion. Partly habit. I don't ever worry about mixing data types; I'm just aware of what type things are (although often in vague trusting ways such as 'I am sure you are a file; please do not disappoint me'). In the end I highly doubt requiring explicit conversions has a notable negative on productivity or makes the code/logic much bigger or more complicated... whereas not having to manage one's own memory is a fairly huge savings :) > A similar method lets you make 'case-insensitive' dicts, for example. > > > > Were such a thing to happen automagically, you could get some > > weird situations, such as "assert (key in dict) == (key in dict.keys())" > > failing. > > I'm assuming that you would just need to overload the 'in' operator > and .keys() method to be case insensitive also. > For my case-insensitive dict I didn't need to modify keys at all. I wasn't interested in it being "case-preserving"; all keys were lower cased on insert(via .update, __setitem__, or .setdefault), and the 'check' value when testing or fetching was lowercased for comparison (via __contains__, __getitem__, and .get) For example, a less functional version: class caseinsensitivedict(dict): def __contains__(self, key): return dict.__contains__(self, key.lower()) def __getitem__(self, key): return dict.__getitem__(self, key.lower()) def __setitem__(self, key, value): return dict.__setitem__(self, key.lower(), value) >>> cid = caseinsensitivedict() >>> cid['This'] = 5 >>> cid {'this': 5} >>> cid.keys() ['this'] >>> print 'THIS' in cid: True I could do a case-preserving one, but it wasn't needed for the solution. --Stephen -------------- next part -------------- An HTML attachment was scrubbed... URL: From loupgaroublond at gmail.com Fri Jan 4 21:19:05 2008 From: loupgaroublond at gmail.com (Yaakov Nemoy) Date: Fri, 4 Jan 2008 21:19:05 -0500 Subject: Memory Leaks and Heapy In-Reply-To: <477E6525.3010805@egenix.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> <477E5A73.9070400@egenix.com> <7f692fec0801040823q14d16429y370ffceaf046a6f3@mail.gmail.com> <477E6525.3010805@egenix.com> Message-ID: <7f692fec0801041819r675e2137i293084baeae4954f@mail.gmail.com> On Jan 4, 2008 11:56 AM, M.-A. Lemburg wrote: > > The most common answer I heard was possible fragmentation, meaning > > there are no or few completely empty blocks to be found. If there are > > no 'leaks' in the VM, then it's probably related to how memory is > > freed. > > You can check for this by using a special build of Python > with disabled PyMalloc - Python will then use the standard > OS malloc for all object allocations. It still uses free lists > for a couple of object types, but those won't cause major > leak problems. How do I go about setting this up? > Alternatively, try to tune the PyMalloc implementation (see > objmalloc.c), e.g. enable WITH_MEMORY_LIMITS. > > >> This could be caused by interned strings which are kept in a special > >> pool dictionary to speed up string comparisons. > > > > That's quite possible, a majority of the code is a huge number of SQL > > connections and code. All string based. > > Note that strings are normally *not* interned. However, you can > write code in a way that causes Python to intern more strings > than needed, e.g. if you dynamically compile code in your app, > which then causes all identifiers in the compiled code to be > interned. > > The interned dictionary is not exposed in Python, but you can > access it using a debugger via Objects/stringobject.c:interned. That's going a bit more low level detail than I think I can handle. I'm not much for C programming, and i'll have a hard time sifting through the noise to find the signal. > >> However, the first thing to check is whether any of the C extension > >> modules you are using is leaking memory. Python itself is usually > >> well tested for memory leaks, but this is less so for C extension > >> modules and it's easy to mis a few Py_DECREFs (decrementing a > >> Python object's reference count), causing objects to live forever. > > > > I'll try to track it down, but AFAIK, most of the code is python, and > > the only C code there would be is the MySQL container. How can I > > debug the VM though, to determine where the leak lies? Heapy wasn't > > able to tell me this, and this is the important aspect. I'm wondering > > how most people go about determining the causes of leaks like these, > > so I can provide some accurate bug information. > > Building Python in debug mode provides some help with this. > You can then detect whether objects get properly freed. Again, what's the best way to go about doing this? > Doing explicit garbage collection via the gc module also > helps in narrowing down the leak. Adding an explicit gc.collect() statement at the end of the offending function didn't do much to solve matters much. It slowed the rate that garbage piled up, but it's not a solution. Thanks for all the help. From mwilson at the-wire.com Wed Jan 16 10:52:08 2008 From: mwilson at the-wire.com (Mel) Date: Wed, 16 Jan 2008 10:52:08 -0500 Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> Message-ID: J. Peng wrote: > Sounds strange. > In perl we can modify the variable's value like this way: > > $ perl -le ' >> $x=123; >> sub test { >> $x=456; >> } >> test; >> print $x ' > 456 Not all that strange. The Python equivalent is x=123 sub test() global x x=456 test() print x Python assignment works by binding an object with a name in a namespace. I suspect that perl does something similar, and the differences are in the rules about which namespace to use. Mel. From nicola.jean at gmail.com Thu Jan 31 06:03:20 2008 From: nicola.jean at gmail.com (Nicola Jean) Date: Thu, 31 Jan 2008 12:03:20 +0100 Subject: dl module Message-ID: <11ed47ab0801310303w44b173a1sacfb317bb2737b3@mail.gmail.com> Hi everyone, I'm having a problem compiling Python2.4.4 on a 64 bits machine. It looks like I cannot compile the dl module. When I run test_dl.py I get the following error message: SystemError: module dl requires sizeof(int) == sizeof(long) == sizeof(char*) Do I need to put any special flag when I run the configure script? Cheers N.Jean From paul at boddie.org.uk Mon Jan 28 05:28:55 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 28 Jan 2008 02:28:55 -0800 (PST) Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: <200aa7ec-de64-41ac-8453-6e97fa867a51@q21g2000hsa.googlegroups.com> On 28 Jan, 02:05, ajaksu wrote: > > Hmmm. Seems to me that "Is X Standardized" in the given context means > having a formal, published standard issued by some Standards > organization. While you can discuss the meaning of some so-called > standards (like W3C's 'recommendations', RFCs, etc.), Python, IMHO, > doesn't fit the label. There is no "Standard" to reference that is > implementation, documentation and core-dev's opinion independent to a > reasonable degree. > > I guess MilesAgain gives the best arguments regarding this issue. Agreed. The supposed definition of Python is decided by the developers of CPython, which is why every other implementation has to chase behind that group making changes as the language definition shifts. You could argue that Java is in a similar situation: a controlling body with their own implementations, albeit with a process for suggesting changes and arguably more complete documentation. Looking at the table of languages, we see that Java is indeed categorised as not having a standard. Of course, one could contend that languages like C# aren't really standardised either, since everyone knows that ECMA standardisation is just a convenient rubber-stamping process, as we have seen with the adoption of "Office Open XML" (OOXML) as a standard by ECMA, whilst the ISO standardisation attempt for OOXML was sunk (despite Microsoft ballot-stuffing) due to glaring flaws in that so-called standard. As I probably pointed out before, people have advocated a standard for Python, such as a presenter at EuroPython 2006 who had been alarmed that features such as lambda which his team used extensively were at one point scheduled for removal from the language. Unfortunately, there hasn't been significant scope for differentiation between implementations of Python, so one could argue that demand for a standard hasn't yet reached a critical level, but I imagine that some kind of independent documentation of what Python (or a subset of Python) is may eventually emerge in some form or other. Paul From steveo at syslang.net Wed Jan 9 13:47:30 2008 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 9 Jan 2008 13:47:30 -0500 (EST) Subject: Another dumb scope question for a closure. Message-ID: So sorry because I know I'm doing something wrong. 574 > cat c2.py #! /usr/local/bin/python2.4 def inc(jj): def dummy(): jj = jj + 1 return jj return dummy h = inc(33) print 'h() = ', h() 575 > c2.py h() = Traceback (most recent call last): File "./c2.py", line 10, in ? print 'h() = ', h() File "./c2.py", line 5, in dummy jj = jj + 1 UnboundLocalError: local variable 'jj' referenced before assignment I could have sworn I was allowed to do this. How do I fix it? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From fredrik at pythonware.com Sun Jan 13 15:18:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 13 Jan 2008 21:18:37 +0100 Subject: Manually installing PIL In-Reply-To: References: <001001c84dda$23d26760$2000a8c0@depid.local> Message-ID: j igisbert.etra-id wrote: > this. I have download Imaging-1.1.6 source code, and I found PIL folder, > but not binary file. If I download windows exe installer, it works > great, but I want to install manually for installing it on my PDA.... as the name implies, the source code distribution contains source code only. to turn that into a binary component, you need a working compiler for your target platform. what OS does your PDA run? From ajaksu at gmail.com Wed Jan 30 20:31:10 2008 From: ajaksu at gmail.com (ajaksu) Date: Wed, 30 Jan 2008 17:31:10 -0800 (PST) Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! References: Message-ID: <832c7add-b222-46d7-a151-45f02444d520@s19g2000prg.googlegroups.com> On Jan 30, 10:40 pm, "Blubaugh, David A." wrote: > I do not understand why no one has answered the following question: > > Has anybody worked with Gene Expression Programming???? > > David Blubaugh I see. You don't understand. That's a fact. I'm sure there are free online resources about the best way to understand why no one answered your question in particular, or why people don't answer some questions in a more comparative way. See? That's as far as this rude message will get you. Thanks for the laugh, though. (On a more useful note, try visiting http://groups.google.com/group/comp.lang.python/ and thinking real hard for a minute or fifty: why?) From bborcic at gmail.com Thu Jan 24 08:09:34 2008 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 24 Jan 2008 14:09:34 +0100 Subject: sudoku solver in Python ... In-Reply-To: <222A1E46-A1C1-4793-A91E-9E0785463278@gmail.com> References: <43b2a56b-c8eb-4851-a9f6-10aa7e32e3ce@i29g2000prf.googlegroups.com> <222A1E46-A1C1-4793-A91E-9E0785463278@gmail.com> Message-ID: Shawn Milochik wrote: > On Jan 23, 2008, at 10:02 PM, Derek Marshall wrote: > >> This is just for fun, in case someone would be interested and because >> I haven't had the pleasure of posting anything here in many years ... >> >> http://derek.marshall.googlepages.com/pythonsudokusolver >> >> Appreciate any feedback anyone who takes the time to have a look would >> want to give ... >> >> Yours with-too-much-time-to-kill-on-the-train'ly, >> Derek >> -- >> http://mail.python.org/mailman/listinfo/python-list > > For those interested in this topic, here's another (much shorter) one: > > http://norvig.com/sudoku.html > > I'm not making any judgements here, though. If anyone takes the time > to actually review them, I'd be interested in hearing any educated > comparisons. > > Shawn So would I. Below is the "winner" of my hacking for an as fast as possible 110% pure python (no imports at all!) comprehensive sudoku solver under 50 LOCs, back in 2006. Performance is comparable to the solver you advertize - numbers are slightly better, but platform differences could easily absorb that - eg (not counting module initialization and not using psyco) it takes 9.3 ms average on the "AI escargot" problem linked to in Norwig's page, 5.6 ms/problem on some standard "top1465" list of hard problems, and 3.4 ms/problem on the first 1000 on some other "top50000" list of relatively hard problems. This on my 2GHz Intel Centrino '05 laptop. Psyco reduces times by about 50%. Dropping performance requirements by half allows reducing LOC count in proportion. OTOH, the code although short is nearly unreadable, sorry; should probably feature/comment it on some web page, like the two already proposed in the thread. Will do if/for reviewer. Interface is calling sudoku99(problem) with 'problem' a standard 81 character string with '0' or '.' placeholder for unknowns. Returns same with values filled in. Beware that although in practice it solved all well-formed human-solvable problems I could find, it is not guaranteed to deal properly (or even terminate?) for underdetermined problems or determined problems that would require exploring choicepoints with more than 2 possibilities (if such exist). Cheers, Boris w2q = [[n/9,n/81*9+n%9+243,n%81+162,n%9*9+n/243*3+n/27%3+81] for n in range(729)] q2w = (z[1] for z in sorted((x,y) for y,s in enumerate(w2q) for x in s)) q2w = map(set,zip(*9*[q2w])) w2q2w = [set(w for q in qL for w in q2w[q] if w!=w0) for w0,qL in enumerate(w2q)] empty = set(range(729)).copy def sudoku99(problem) : givens = set(9*j+int(k)-1 for j,k in enumerate(problem) if '0' vmax : ixmax = ix if v >=thres : break vmax = v w0s.add(w0) else : continue break except : pass w0,w1 = q2w[ixmax]&free try : w0s.clear() w0s.add(w0) return search(w0s,q2nw[:],free.copy()) except ValueError : w0s.clear() w0s.add(w1) From socyl at 987jk.com.invalid Fri Jan 25 08:47:59 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 25 Jan 2008 13:47:59 +0000 (UTC) Subject: Text-based data inspector for Python? References: <6398ab68-da01-408e-902b-0b488310e9b0@e10g2000prf.googlegroups.com> Message-ID: In <6398ab68-da01-408e-902b-0b488310e9b0 at e10g2000prf.googlegroups.com> Paddy writes: >I tend to do the following at the python prompt: > from pprint import pprint as pp Thanks, that's a good one to know, but isn't there a way to automate it??? I looked around, but I couldn't find the name of any *rc-type file that would hold interpreter customizations. The closest I found was ~/.pythonrc.py, but that still requires doing "import user" at every interpreter session. (As annoyances go, this is certainly a minor one, but with me the psychological effects of such small annoyances gets magnified in proportion to how unnecessary they seem.) Plus, I'm not sure that it'd be such a great idea to execute code intended to customize the interpreter every time that the user module gets loaded... kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From carsten at uniqsys.com Thu Jan 3 22:11:26 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 03 Jan 2008 22:11:26 -0500 Subject: Cursors in a Loop In-Reply-To: References: <3da337d8-2de0-4fdb-8c38-2f6fcd8348ac@i72g2000hsd.googlegroups.com> Message-ID: <1199416286.3319.19.camel@localhost.localdomain> On Thu, 2008-01-03 at 17:25 -0800, t_rectenwald wrote: > On Jan 3, 7:47 pm, t_rectenwald wrote: > > I have a python script that uses the cx_Oracle module. I have a list > > of values that I iterate through via a for loop and then insert into > > the database. This works okay, but I'm not sure whether I can use one > > cursor for all inserts, and define it outside of the loop, or > > instantiate and close the cursor within the loop itself. For example, > > I have: > > > > for i in hostlist: > > cursor = connection.cursor() > > sql= "insert into as_siebel_hosts_temp values('%s')" % (i) > > cursor.execute(sql) > > cursor.close() > > > > And I've also tried: > > > > cursor = connection.cursor() > > for i in hostlist: > > sql= "insert into as_siebel_hosts_temp values('%s')" % (i) > > cursor.execute(sql) > > cursor.close() > > > > Both work fine, and execute in the same amount of time. I'm just > > trying to understand what is the "correct" approach to use. Actually, the correct approach would be "neither." You should NEVER use string formatting to fill values into an SQL query. (Doing so causes security vulnerabilities and performance problems. See, for example, http://informixdb.blogspot.com/2007/07/filling-in-blanks.html for detailed explanations.) Instead, you should use a parametrized query. With a parametrized query, your code becomes this: cursor = connection.cursor() for i in hostlist: cursor.execute("insert into as_siebel_hosts_temp values(?)", (i,) ) cursor.close() Since this will save the database engine from having to re-parse the query every time, it will run much faster if the list is long. Even better would be to use executemany: cursor = connection.cursor() cursor.executemany("insert into as_siebel_hosts_temp values(?)", [(i,) for i in hostlist] ) cursor.close() Depending on whether cx_Oracle allows this, the list comprehension in that example could be replaced by the generator expression ((i,) for i in hostlist), but I don't know if cx_Oracle allows executemany with an arbitrary iterable. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From bignose+hates-spam at benfinney.id.au Wed Jan 9 17:53:46 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 10 Jan 2008 09:53:46 +1100 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <87fxx6k3ut.fsf@benfinney.id.au> Christian Heimes writes: > dongie.agnir at gmail.com wrote: > > [...] after running the code with the included sample input file, > > it seems quite slow (1-2 seconds from start to finish to do the > > 800 by 600 gif image). > > Have you profiled your application? Do you know the bottle necks and > the reason for the bottle necks? Is your application IO, memory or > CPU bound? Have you considered rewriting the bottle necks in C? All good questions. Another important one: Is the startup time of the Python process (i.e. before executing any of the actual statements in the program) a significant part of the total time in this case? -- \ "In the long run, the utility of all non-Free software | `\ approaches zero. All non-Free software is a dead end." ?Mark | _o__) Pilgrim | Ben Finney From socyl at 987jk.com.invalid Fri Jan 25 10:42:47 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 25 Jan 2008 15:42:47 +0000 (UTC) Subject: Text-based data inspector for Python? References: <6398ab68-da01-408e-902b-0b488310e9b0@e10g2000prf.googlegroups.com> <98d4d552-20d6-42f4-9d50-2c9ca1b3a4d0@e25g2000prg.googlegroups.com> Message-ID: In <98d4d552-20d6-42f4-9d50-2c9ca1b3a4d0 at e25g2000prg.googlegroups.com> Paddy writes: >python -h gives me: > ... > Other environment variables: > PYTHONSTARTUP: file executed on interactive startup (no default) > ... Sweet. Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From fredrik at pythonware.com Fri Jan 4 15:12:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 21:12:58 +0100 Subject: MRO Error on Multiple Inheritance? In-Reply-To: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> References: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> Message-ID: Ming wrote: > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases A, B > > (I submitted the problem to the author but I'm not sure I'll ever hear > back.) I'm guessing that this kind of diamond inheritance is > prohibited by the interpreter, and that his lack of error messages > from the interpretation is due to actually leaving out the "class > B(A): pass" or, alternatively, leaving out the (object) in the first class definition: >>> class A: pass ... >>> class B(A): pass ... >>> class D(A, B): pass ... >>> From salgerman at gmail.com Tue Jan 15 13:01:02 2008 From: salgerman at gmail.com (gsal) Date: Tue, 15 Jan 2008 10:01:02 -0800 (PST) Subject: Open existing Word document, modify and save. Message-ID: <1ab91596-e868-4b28-9fe3-34f9129a114f@s8g2000prg.googlegroups.com> New to Python and new to Win32. Help please. O.k., so this might seem like one of those "can you do my homework" kind of postings, except that is not homework, it is officework. I have been reading the Core Python book and I am really excited about starting my next project with Python, instead of tcl/tk/Fortran/C. While I can see how to use it for scientific computing and have gone with the NumPy and SciPy tutorials, I am having a hard time with Win32. Attempted to read some of the documentation for Win32 and while the basic stuff talks about creating a document, I did not see how to open an existing document and modify certain parts of it...and then it seems that it got very complicated (for me) really quick. Sure, it seems powerful, but all I need is a small part of it, I think. Here is the thing. Here at the office, we have computer programs to generate spec data and the Applications people have MS-Word documents in a very specific format where they would like to put such spec data. Initially, I was using merge fields and VB macros, until they stopped working when newer (non-backwards-compatible) versions came along; then, I switched to generating *.xml out of the original *.doc file, breaking it appart, modifying it and gluing back together...this is very laborious task and I have to go through the whole exercise, should the application people modify the original *.doc So, basically, I am looking for a way to work directly with the original *.doc, assuming I know everything about it...which I do; in fact, I have it and can also modify it, should I need to bookmark it or otherwise modify as needed. How to go about it? What's the python code to open an existing document, modify it and save it back? how does the Word document needs to be bookmarked/formatted so that it can be modified? For example, after the computer program has been run and the new, say, "machine rating" calculated, I need to deposit such value in a very specific spot in the Word document. I presume somebody out there already does this and is willing to provide some code?. Thank you very much in advance. gsal From gagsl-py2 at yahoo.com.ar Tue Jan 1 19:13:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Jan 2008 22:13:01 -0200 Subject: Catching external program exceptions References: <25qdnZuc2dn0WOfanZ2dnUVZ_gWdnZ2d@wideopenwest.com> Message-ID: En Tue, 01 Jan 2008 20:57:44 -0200, Marty escribi?: > I need to catch exceptions thrown by programs started by the os.system > function, > as indicated by a non-zero return code (e.g. the mount utility). For Notice that these are two different things. You can wait until the external program ends, and get its return code; and you can sometimes read a message from its stderr. But none of these things by itself throws an exception in Python. > example, > if I get the following results in a bash shell: > > $mount test > mount: can't find /home/marty/test in /etc/fstab or /etc/mtab > > then I want to catch the same exception from the corresponding > os.system() call, > i.e. "os.system('mount test')", but it doesn't work as expected: Perhaps it doesn't work as *you* expected, but it does work as specified. From the os.system description at http://docs.python.org/lib/os-process.html "On Unix, the return value is the exit status of the process encoded in the format specified for wait(). [...] [That return value] is system-dependent." Later on the same page, describing the wait function, says that the return value is "a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero)" So os.system does NOT raise an exception when the executed program ends with a non-zero exit code. > I get the same results with popon, popen2, popen3, etc. Apparently > these also > work only when the program does not generate an exception. An external program cannot generate an exception inside the Python program. Only Python itself can do that. > Is there any way to > catch the return code. or if not, a workaround? From the description above, you could do some math to obtain the exit code looking at the os.system return value. But perhaps it's easier to use subprocess.check_call, see "Convenience functions" at http://docs.python.org/lib/module-subprocess.html -- Gabriel Genellina From bblais at bryant.edu Wed Jan 9 09:40:20 2008 From: bblais at bryant.edu (Brian Blais) Date: Wed, 9 Jan 2008 09:40:20 -0500 Subject: problem building simple package with extensions in Windows, but not OS X Message-ID: <947247E2-B9F8-4DAD-AEB1-87574E3BE64A@bryant.edu> Hello, I am trying to build a package of mine, and for some reason the build process with distutils is failing in Windows, but not in OS X (and I imagine also in Linux, but I haven't tested it). I am not sure if this is a Pyrex problem, a distutils problem, or me doing something stupid problem. :) I boiled it down to the simplest package that still fails. My setup.py is: from distutils.core import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name = 'myproject', version='0.0.1', description="Here is a description", author="Brian Blais", ext_modules=[ Extension("myproject/train",["myproject/train.pyx"]), ], packages=['myproject'], cmdclass = {'build_ext': build_ext} ) and my project has one directory, myproject, with two files. train.pyx is: def func(blah): print blah and an __init__.py, which has the single line: import train So, in OS X, I can do python setup.py build and the build goes through. In windows, with the same basic setup (version numbers all below), I get: [Desktop\test]|5> !python setup.py build running build running build_py creating build creating build\lib.win32-2.5 creating build\lib.win32-2.5\myproject copying myproject\__init__.py -> build\lib.win32-2.5\myproject running build_ext building 'myproject/train' extension creating build\temp.win32-2.5 creating build\temp.win32-2.5\Release creating build\temp.win32-2.5\Release\myproject c:\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Ic:\python25\include -Ic:\pytho n25\PC -c myproject/train.c -o build\temp.win32-2.5\Release\myproject \train.o writing build\temp.win32-2.5\Release\myproject\train.def c:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.5 \Release\myproje ct\train.o build\temp.win32-2.5\Release\myproject\train.def -Lc: \python25\libs - Lc:\python25\PCBuild -lpython25 -lmsvcr71 -o build\lib.win32-2.5 \myproject/train .pyd Cannot export initmyproject/train: symbol not defined collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 On both the Mac and the PC I have: Python 2.5.1 Pyrex version 0.9.5.1a distutils 2.5.1 am I doing something wrong? thanks, Brian Blais -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From sanjeetsanju at gmail.com Sat Jan 5 02:03:15 2008 From: sanjeetsanju at gmail.com (sanjeet) Date: Fri, 4 Jan 2008 23:03:15 -0800 (PST) Subject: mail Message-ID: hi all, I am facing problem to fetch mail from internet mail server. Plz help me, how can do this? thanks , sanjeet From grante at visi.com Sun Jan 6 14:15:10 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 06 Jan 2008 19:15:10 -0000 Subject: Delete lines containing a specific word References: <489729.25110.qm@web57603.mail.re1.yahoo.com> Message-ID: <13o2a5ucddj913e@corp.supernews.com> On 2008-01-06, Matt Nordhoff wrote: >> Please, how to adapt the following script (to delete blank lines) to delete >> lines containing a specific word, or words? > If you're on Linux, why not just use grep? > > $ grep -v theword output.pdb And if you're on Windows, install Cygwin, and then use grep. Or install any of about a half-dozen native Win23 implementations of grep. -- Grant Edwards grante Yow! I'm having a BIG BANG at THEORY!! visi.com From http Sun Jan 27 06:42:33 2008 From: http (Paul Rubin) Date: 27 Jan 2008 03:42:33 -0800 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> <7xy7acsx2l.fsf@ruckus.brouhaha.com> <8ddebd68-43dc-4320-86e1-887aadff4af3@d70g2000hsb.googlegroups.com> <7xmyqs722t.fsf@ruckus.brouhaha.com> <13pnbp9l8lk1j8b@corp.supernews.com> Message-ID: <7xzlur336e.fsf@ruckus.brouhaha.com> Arnaud Delobelle writes: > def simple_posmax(l, key=None): > if key: > return l.index(max(l, key=key)) > else: > return l.index(max(l)) def simple_posmax(l, **kw): return l.index(max(l, **kw)) > simple_posmax is more than 3x faster on my machine. It's not > surprising as even though the list is walked twice, it is all done in > C and no new objects have to be created. Then only non-C bit is when > the result of max(l) is fed to l.index(). It does expose a slight danger in that the list might somehow self-mutate during the first traversal. From lists at cheimes.de Fri Jan 4 11:27:59 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 04 Jan 2008 17:27:59 +0100 Subject: Memory Leaks and Heapy In-Reply-To: <20080104153441.GO82115@nexus.in-nomine.org> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> <20080104153441.GO82115@nexus.in-nomine.org> Message-ID: <477E5E8F.7070503@cheimes.de> Jeroen Ruigrok van der Werven wrote: > Aside from that (rant), I seriously dislike Python's memory management and > even more the fairly arcane ways people have to go about > debugging/troubleshooting some 600 MB to 2-3 GB(!) of resident memory use by > Python. > > Personally I consider this the weakest point of Python. Given the fact there > is a garbage collector this sort of keeping track of memory seems a bit > contradictory to the concept of garbage collection. You are welcome to join the team and improve the memory management. We are constantly looking for new developers and way to enhance Python. If you feel so strong about the memory management please provide patches and benchmarks. Christian From pavlovevidence at gmail.com Fri Jan 18 20:25:55 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 18 Jan 2008 17:25:55 -0800 (PST) Subject: I don't understand what is happening in this threading code References: Message-ID: <0c86b828-883a-4b80-ac11-a5eddea7825c@e4g2000hsg.googlegroups.com> On Jan 18, 7:43 pm, Matthew Wilson wrote: > In this code, I tried to kill my thread object by setting a variable on it > to False. > > Inside the run method of my thread object, it checks a different > variable. > > I've already rewritten this code to use semaphores, but I'm just curious > what is going on. > > Here's the code: > > import logging, threading, time > logging.basicConfig(level=logging.DEBUG, > format="%(threadName)s: %(message)s") > > class Waiter(threading.Thread): > def __init__(self, hot_food): > super(Waiter, self).__init__() > self.should_keep_running = True > self.hot_food = hot_food > > def run(self): > while self.should_keep_running: > logging.debug("Inside run, the id of should_keep_running is %s." > % id(self.should_keep_running)) > self.hot_food.acquire() > > def cook_food(hot_food): > i = 5 > while i >= 0: > logging.debug("I am cooking food...") > time.sleep(1) > hot_food.release() > logging.debug("Andiamo!") > i -= 1 > > def main(): > > hot_food = threading.Semaphore(value=0) > > chef = threading.Thread(name="chef", target=cook_food, args=(hot_food, )) > chef.start() > > w = Waiter(hot_food) > logging.debug("Initially, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > w.start() > logging.debug("After start, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > > # Wait for the chef to finish work. > chef.join() > > # Now try to kill off the waiter by setting a variable inside the waiter. > w.should_keep_running = False > logging.debug("Now, the id of w.should_keep_running is %s." > % id(w.should_keep_running)) > > if __name__ == "__main__": > main() It looks like your program's hanging while the waiter is waits to acquire another plate of hot food. Quick and dirty solution is to have waiter timeout at intervals while waiting for the chef and check the clock to see if his shift has ended. Better solution is to rewrite the logic, which you did. Carl Banks From bronger at physik.rwth-aachen.de Thu Jan 10 03:39:51 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 10 Jan 2008 09:39:51 +0100 Subject: Conventions for dummy name References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de> <873at6k2qt.fsf_-_@benfinney.id.au> Message-ID: <87sl1613c8.fsf@physik.rwth-aachen.de> Hall?chen! Ben Finney writes: > "Diez B. Roggisch" writes: > >> The underscore is used as "discarded" identifier. So maybe >> >> for _ in xrange(10): >> ... > > The problem with the '_' name is that it is already well-known and > long-used existing convention for an entirely unrelated purpose: > in the 'gettext' i18n library, the '_' function to get the > locally-translated version of a text string. Right, that's because I've used "__" where not all returning values are interesing to me such as a, b, __ = function_that_returns_three_values(x, y) However, in loops, I prefer real names, even if the loop variable isn't used outside. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From adonisv at REMOVETHISearthlink.net Fri Jan 11 20:21:03 2008 From: adonisv at REMOVETHISearthlink.net (Adonis Vargas) Date: Fri, 11 Jan 2008 20:21:03 -0500 Subject: converting JSON to string In-Reply-To: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> References: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> Message-ID: <13og5g06rvrtefa@corp.supernews.com> Gowri wrote: > Hello, > > I actually have two questions: > 1. Are there any libraries which convert XML to JSON? > 2. I am currently doing the above using the DOM parser and creating a > JSON array > > > for node in doc.getElementsByTagName("book"): > isbn = node.getAttribute("isbn") > titleNode = (node.getElementsByTagName("title") > [0]).childNodes[0] > title = titleNode.data > primarykeys.append({'isbn': isbn, 'title': title}) > return primarykeys > > I want to send primarykeys as a response to my client. i use > mod_python and apache. The problem is, I have not been able to figure > out how to convert my JSON output to a string. > > Could someone please help me? > > Thanks in advance do: return str(primarykeys) Also there are Python modules for just this. Here is the very first link from Google: http://pypi.python.org/pypi/python-json I have used this one personally and have been very satisfied with it. There is another one (CJSON?) which is similar, but written in C, for when performance may be an issue. Hope this helps. Adonis From deets at nospam.web.de Fri Jan 25 14:16:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jan 2008 20:16:52 +0100 Subject: Operator overloading In-Reply-To: <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> References: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com> <5vuob3F1nd2bhU1@mid.uni-berlin.de> <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> Message-ID: <5vuqt8F1olnneU1@mid.uni-berlin.de> MartinRinehart at gmail.com schrieb: > > Diez B. Roggisch wrote: >> No, there is no way. You would change general interpreter behavior if >> you could set arbitrary operators for predefined types. >> >> Start grumping... > > Thank you, Diez. > > If I ever design a language, please remind me that complete, easy, > well-documented access to the working of the internals (and the > ability to change same) would be very, uh, what's the right word? > Pythonic? As you say - it's a question of design & thus taste. Python has chosen to _not_ allow to change (all) inner workings of itself in favor of not introducing subtle bugs that arise from somebody (accidentially or not) altering behavior of builtins that might effect code he'd never intended to touch. But you _can_ create subclasses of these builtins and adapt their behavior. I for once like it that way. If you don't - to bad for you. It won't change, so either you live with it, or start working on your lex/yacc skillz and create your own language. Or switch to Ruby, which allow for what you desire (AFAIK, not entirely sure though) Diez From http Sat Jan 12 13:26:04 2008 From: http (Paul Rubin) Date: 12 Jan 2008 10:26:04 -0800 Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> <354c74f6-6e56-4e41-a686-56239aa4cea9@f47g2000hsd.googlegroups.com> Message-ID: <7x8x2uj3yb.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > 2) List is referenced by others; concurrent modifications may be going > on; can not replace it. Can I make asynchronous modifications and > merge the changes, SCM-style? Nothing else should have direct access to the list. > 3) Dictionary returns non-static order; order is important. Create a > int-func tuple and sort dictionary results? Perhaps. That's sounding > pretty good. If the list is not too long, that is reasonable. If it -is- long, the remove operations can be slow, but that's ok if there's not too many. If the list is long -and- there's a lot of adds/removes, maybe you want something like an AVL tree. From sndive at gmail.com Wed Jan 16 17:44:36 2008 From: sndive at gmail.com (Squat'n Dive) Date: Wed, 16 Jan 2008 14:44:36 -0800 (PST) Subject: -fno-strict-aliasing turned off when cross compiling Message-ID: <66c2d5b4-c84f-47d9-aa4a-1cca3ae594b2@q39g2000hsf.googlegroups.com> Does anyone have an idea why -fno-strict-aliasing is turned off when cross compiling? in configure generated for 2.4.4: case $GCC in yes) # Python violates C99 rules, by casting between incompatible # pointer types. GCC may generate bad code as a result of that, # so use -fno-strict-aliasing if supported. echo "$as_me:$LINENO: checking whether $CC accepts -fno-strict- aliasing" >&5 echo $ECHO_N "checking whether $CC accepts -fno-strict-aliasing... $ECHO_C" >&6 ac_save_cc="$CC" CC="$CC -fno-strict-aliasing" if test "$cross_compiling" = yes; then ac_cv_no_strict_aliasing_ok=no ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ why? else From hyperboreean at nerdshack.com Fri Jan 4 09:59:34 2008 From: hyperboreean at nerdshack.com (hyperboreean) Date: Fri, 04 Jan 2008 16:59:34 +0200 Subject: python interfaces Message-ID: <477E49D6.1090506@nerdshack.com> Hi, Probably it has been asked before, but I'll still ask. Why doesn't python provide interfaces trough its standard library? Or it was ever proposed to be included in the language? Zope's implementation seems pretty flexible and straightforward. Thanks. From mathewbrown at fastmail.fm Wed Jan 9 10:17:44 2008 From: mathewbrown at fastmail.fm (Mrown) Date: Wed, 9 Jan 2008 07:17:44 -0800 (PST) Subject: subprocess.Popen spawning cmd shells Message-ID: Hi, I'm currently writing a python program that relies on a CLI program. What I'm currently doing is using subprocess.Popen on Python 2.5.1. Here's the line that I'm currently running: child = subprocess.Popen(["c:\app.exe", node, "-w", str(tmpTime * 1000), '-n', str(1), '-l'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) The problem is that although the above works, a CMD shell is spawned and becomes visible for each time I run the above. I thought that by redircting stdin, stdout and stderr, no CMD shell should pop-up. Is something wrong in the way I'm using subprocess? Thanks for your help. From rw at smsnet.pl Sun Jan 20 10:42:38 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Sun, 20 Jan 2008 16:42:38 +0100 Subject: writing Python in Emacs References: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> Message-ID: <87r6gc5wr5.fsf@merkury.smsnet.pl> Terry Jones writes: >>>>>> "Richard" == Richard Szopa writes: I don't see Richard's original post, so I reply to Terry. > > Richard> I am a devoted Emacs user and I write a lot in Python. > > Me too. The good news is that I managed to configure completion for Python in Emacs using pymacs, python-mode.el, pycomplete.el and pycomplete.py. For contents of my pycomplete.el, pycomplete.py and necessary settings in .emacs see below. > > Richard> I need the following features: > > Richard> 1) Tab completion, ideally Slime like. That is, when there's not > Richard> enough letters to unambiguously complete a symbol, I want it to > Richard> show a buffer (w/o taking the focus) w/ the possible > Richard> completions. In an ideal world, it would be able to complete > Richard> fo.ba to foo.bar. I imagine this would require quite tight > Richard> Emacs-Python integration. Works for me. [...] > Richard> 2) Sending the toplevel definition (class or function) to the Python > Richard> buffer. That feature is defined in python-mode.el: "\e\C-x" 'py-execute-def-or-class "\C-c|" 'py-execute-region [...] > Richard> 3) Hints on function/method arguments. IDLE has this done nearly > Richard> right, but the hints are a bit too intrusive for me. I would like to > Richard> see them in the minibuffer. Works for me, but only for pure python functions (`inspect.getargspec` constraint). [...] > Richard> I have tried a couple of times both python-modes (the one shipped w/ > Richard> Python and the one shipped w/ Emacs), pymacs and stuff like that... > Richard> And, as I said, never got it right. But, maybe I just cannot find the > Richard> way to configure it, and some configuration hints will be enough... I mixed solutions found around the net and finally got it working: - hitting TAB complete function/method name - f1 shows description of object at point - hitting '(' and ',' shows function parameters Copy `pycomplete.py` on your PYTHONPATH (e.g. /usr/lib/python2.5/site-packages) and `pycomplete.el` on your Emacs load_path (e.g. /usr/share/emacs/site-lisp). Copy my settings to your `.emacs` file and hopefully it will work. ;) My files: # .emacs (require 'pycomplete) (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) (autoload 'python-mode "python-mode" "Python editing mode." t) (autoload 'pymacs-load "pymacs" nil t) (autoload 'pymacs-eval "pymacs" nil t) (autoload 'pymacs-apply "pymacs") (autoload 'pymacs-call "pymacs") (setq interpreter-mode-alist(cons '("python" . python-mode) interpreter-mode-alist)) (setq python-mode-hook '(lambda () (progn (set-variable 'py-python-command "/usr/bin/python2.5") (set-variable 'py-indent-offset 4) (set-variable 'py-smart-indentation nil) (set-variable 'indent-tabs-mode nil)))) # end of .emacs # pycomplete.el (require 'pymacs) (require 'python-mode) (pymacs-load "pycomplete") ;;check if prev character is blank-type (defun char-before-blank () (save-excursion (forward-char -1) (looking-at "[\n\t\r]"))) (defun py-complete () (interactive) (let ((pymacs-forget-mutability t)) (if (and (and (eolp) (not (bolp)) (not (char-before-blank)))) (insert (pycomplete-pycomplete (py-symbol-near-point) (py-find-global-imports))) (indent-for-tab-command)))) (defun py-find-global-imports () (save-excursion (let ((imports nil)) (goto-char (point-min)) (while (re-search-forward "\\(import \\|from \\([A-Za-z_][A-Za-z_0-9\\.]*\\) import \\).*" nil t) (setq imports (append imports (list (buffer-substring (match-beginning 0) (match-end 0)))))) imports))) (defun py-complete-python-dotexpr-begin nil (interactive) (re-search-backward "[^a-zA-Z_0-9\\.]") (forward-char)) (defun py-complete-python-dotexpr-end nil (interactive) (re-search-forward "[a-zA-Z_0-9\\.]*")) (put 'python-dotexpr 'beginning-op 'py-complete-python-dotexpr-begin) (put 'python-dotexpr 'end-op 'py-complete-python-dotexpr-end) (defun py-complete-show (string) (display-message-or-buffer string "*PythonHelp*")) (defun py-complete-help (string) "get help on a python expression" (let ((help-string (pycomplete-pyhelp string (py-find-global-imports)))) (if (and help-string (> (length help-string) 300)) (with-output-to-temp-buffer "*Python Help*" (print help-string)) (py-complete-show help-string)))) (defun py-complete-help-thing-at-point nil (interactive) (require 'thingatpt) (let ((sym (thing-at-point 'python-dotexpr))) (if sym (py-complete-help sym)))) (set 'py-complete-current-signature nil) (defun py-complete-signature (function) "get signature of a python function or method" (interactive) (set 'py-complete-current-signature (pycomplete-pysignature function))) (defun py-complete-signature-show nil (interactive) (require 'thingatpt) (let ((sym (thing-at-point 'python-dotexpr))) (if sym (progn (py-complete-show (py-complete-signature sym)))))) (defun py-complete-signature-expr nil (interactive) (require 'thingatpt) (let ((dotexpr (read-string "signature on: " (thing-at-point 'python-dotexpr)))) (if dotexpr (py-complete-show (py-complete-signature dotexpr))))) (defun py-complete-electric-lparen nil "electricly insert '(', and try to get a signature for the stuff to the left" (interactive) (py-complete-signature-show) (self-insert-command 1)) (defun py-complete-electric-comma nil "electricly insert ',', and redisplay latest signature" (interactive) (self-insert-command 1) (if py-complete-current-signature (py-complete-show (format "%s" py-complete-current-signature)))) (define-key py-mode-map "\M-\C-i" 'py-complete) (define-key py-mode-map "\t" 'py-complete) (define-key py-mode-map [f1] 'py-complete-help-thing-at-point) (define-key py-mode-map "(" 'py-complete-electric-lparen) (define-key py-mode-map "," 'py-complete-electric-comma) (define-key py-mode-map [f2] 'py-complete-signature-expr) (provide 'pycomplete) # end of pycomplete.el # pycomplete.py import sys import inspect from StringIO import StringIO import os.path try: x = set except NameError: from sets import Set as set else: del x from Pymacs import lisp sys.path.append('.') def pycomplete(s, imports=None, debug=False): """Display completion in Emacs window""" completions = _get_all_completions(s, imports) dots = s.split(".") result = os.path.commonprefix([k[len(dots[-1]):] for k in completions]) if result == "": if completions: if debug: width = 80 else: width = lisp.window_width() - 2 column = width / 20 white = " " * 20 msg = "" counter = 0 for completion in completions : if len(completion) < 20 : msg += completion + white[len(completion):] counter += 1 else : msg += completion + white[len(completion) - 20:] counter += 2 if counter >= column: counter = 0 msg += '\n' else: msg = "no completions!" if debug: print msg else: lisp.message(msg) return result def pyhelp(s, imports=None): """Return object description""" _import_modules(imports, globals(), None) return _getdoc(s) def pysignature(s): """Return info about function parameters""" f = None try: f = eval(s) except Exception, ex: return "%s" % ex if inspect.ismethod(f): f = f.im_func if not inspect.isfunction(f): return '' (args, varargs, varkw, defaults) = inspect.getargspec(f) return('%s: %s' % (f.__name__, inspect.formatargspec(args,varargs,varkw,defaults))) def _getdoc(s): """Return string printed by `help` function""" obj = None try: obj = eval(s) except Exception, ex: return "%s" % ex out = StringIO() old = sys.stdout sys.stdout = out help(obj) sys.stdout = old return out.getvalue() def _import_modules(imports, dglobals, dlocals): """If given, execute import statements""" if imports is not None: for stmt in imports: try: exec stmt in dglobals, dlocals except TypeError: raise TypeError, 'invalid type: %s' % stmt except: continue def _get_all_completions(s, imports=None): """Return contextual completion of s (string of >= zero chars)""" dlocals = {} _import_modules(imports, globals(), dlocals) dots = s.split(".") if not s or len(dots) == 1: keys = set() keys.update(dlocals.keys()) keys.update(globals().keys()) import __builtin__ keys.update(dir(__builtin__)) keys = list(keys) keys.sort() if s: return [k for k in keys if k.startswith(s)] else: return keys sym = None for i in range(1, len(dots)): s = ".".join(dots[:i]) try: sym = eval(s, globals(), dlocals) except NameError: try: sym = __import__(s, globals(), dlocals, []) except ImportError: return [] if sym is not None: s = dots[-1] return [k for k in dir(sym) if k.startswith(s)] def _test(): print ' ->', pycomplete('', debug=True) print 'sys.get ->', pycomplete('sys.get', debug=True) print 'settr ->', pycomplete('settr', debug=True) print 'settr (plat in context) ->', print pycomplete('settr', imports=['from sys import settrace'], debug=True) print 'foo. ->', pycomplete('foo.', debug=True) print 'Enc (email * imported) ->', print pycomplete('Enc', imports=['from email import *'], debug=True) print 'E (email * imported) ->', print pycomplete('E', imports=['from email import *'], debug=True) print 'Enc ->', pycomplete('Enc', debug=True) print 'E ->', pycomplete('E', debug=True) if __name__ == "__main__": _test() # end of pycomplete.py HTH, Rob From apardon at forel.vub.ac.be Fri Jan 25 02:57:13 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Jan 2008 07:57:13 GMT Subject: When is min(a, b) != min(b, a)? References: <13pi8fiiqgljdb5@corp.supernews.com> Message-ID: On 2008-01-24, Steven D'Aprano wrote: > On Thu, 24 Jan 2008 13:34:56 +0000, Antoon Pardon wrote: > >> On 2008-01-21, Steven D'Aprano >> wrote: >>> On Sun, 20 Jan 2008 21:15:02 -0600, Albert Hopkins wrote: >>> >>> According to the IEEE-754 standard the usual trichotomy of "x is less >>> than y, x is equal to y, or x is greater than y" has to be extended to >>> include "x and y are unordered". Comparisons with NaNs are unordered, >>> and so expressions like "x < nan" should signal an exception. >> >> That doesn't follow. The problem is not that x < nan returns False >> because that is correct since x isn't smaller than nan. > > Comparisons between things which are not comparable risk being terribly > misleading, and depend very much on how you define "less than" and > "greater than". If you insist that everything must have a boolean yes/no > answer ("Does the colour red have a better chance of becoming President > than a kick to the head?") then False is not an entirely unreasonable > result to return. > > But if you consider that having "x is not smaller than y" be equivalent > to "x is greater than or equal to y" is more important than forcing a > boolean answer in the first place, then you need something to signal > Undefined, and an exception is the right solution unless you have multi- > valued logic system (True, False, Maybe, Undefined, ...) Why should we consider that? The world is full of partial orders. In python we have sets and a partial order is perfectly mathematically sound. > SANE (Standard Apple Numerics Environment) explicitly states that it > signals an exception when doing ordered comparisons against NaNs because > to return False would be misleading. Apple went on to use the same rule > in their PowerPC Numerics. That's straight out of the Zen: Practicality > Beats Purity. What is misleading and what is not depends on the context. One could argue that if comparisons against NaN should signal an exception that the exception comes late and should already have been signaled at the moment the NaN was produced because producing a NaN is already misleading. It gives the impression you have a (meaningfull) result until you later try to do something with it that is illegal for a NaN but for legal for a float. If you allow NaN's as a result then you have extended the floats to a mathematical set that is now only partially ordered. I see nothing wrong in having the comparion operators give the result that belongs to such a partial order. -- Antoon Pardon From http Tue Jan 15 13:22:34 2008 From: http (Paul Rubin) Date: 15 Jan 2008 10:22:34 -0800 Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> <5a3ace63-a8cf-4970-a95e-4243226fbac7@j20g2000hsi.googlegroups.com> Message-ID: <7x3aszgd91.fsf@ruckus.brouhaha.com> Chris M writes: > precludes error-prone constructions like set('abc') & 'cbs' in favor > of the more readable set('abc').intersection('cbs')." set('abc') & set('cbs') From terry at jon.es Sat Jan 19 11:51:50 2008 From: terry at jon.es (Terry Jones) Date: Sat, 19 Jan 2008 17:51:50 +0100 Subject: writing Python in Emacs In-Reply-To: Your message at 04:01:48 on Saturday, 19 January 2008 References: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> Message-ID: <18322.10918.59701.913455@terry.local> >>>>> "Richard" == Richard Szopa writes: Richard> I am a devoted Emacs user and I write a lot in Python. Me too. Richard> I need the following features: Richard> 1) Tab completion, ideally Slime like. That is, when there's not Richard> enough letters to unambiguously complete a symbol, I want it to Richard> show a buffer (w/o taking the focus) w/ the possible Richard> completions. In an ideal world, it would be able to complete Richard> fo.ba to foo.bar. I imagine this would require quite tight Richard> Emacs-Python integration. I know this is not what you want, but I use hippie expand (M-/) to cycle through possible completions. It's not Python aware, but it is of some use. Richard> 2) Sending the toplevel definition (class or function) to the Python Richard> buffer. I switched to IPython to have better interaction with a spawned Python. To use IPython you need to use the Python mode that is NOT the one from (endorsed?) by the FSF. It gives you some completion (at least in the *Python* buffer) and you can send pieces of the buffer to the python process, via py-send-region (C-c |), py-execute-def-or-class (M-C-x), etc. Richard> 3) Hints on function/method arguments. IDLE has this done nearly Richard> right, but the hints are a bit too intrusive for me. I would like to Richard> see them in the minibuffer. I don't have this. Richard> 4) (optional) I would like to see the definition of a function Richard> function or class by hitting M-. on its name. (I understand that Richard> this may be impossible for methods, as Emacs would have to Richard> automagically infer the type of the object). This is just an emacs tag file need. Have you googled for something like emacs tags python? The issue of methods might be overcome by just moving through tags with the same name. Yes, that requires _you_ to know when you've hit the right thing. That's not optimal, but it's better than nothing. Ideally you could send the definition to IPython, ask it for the class info, and use that to jump to the right tag. Richard> I have tried a couple of times both python-modes (the one shipped w/ Richard> Python and the one shipped w/ Emacs), pymacs and stuff like that... Richard> And, as I said, never got it right. But, maybe I just cannot find the Richard> way to configure it, and some configuration hints will be enough... If you have the time, please summarize your findings. The emacs/python world has always seemed quite amorphous to me too. Terry From patrick.waldo at gmail.com Sat Jan 19 08:46:42 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Sat, 19 Jan 2008 05:46:42 -0800 (PST) Subject: pyExcelerator: writing multiple rows Message-ID: <3b2b19a9-f0b6-487d-887b-064ad4039091@v67g2000hse.googlegroups.com> Hi all, I was just curious if there was a built-in or a more efficient way to do take multiple rows of information and write them into excel using pyExcelerator. This is how I resolved the problem: from pyExcelerator import * data = [[1,2,3],[4,5,'a'],['','s'],[6,7,'g']] wb=pyExcelerator.Workbook() test = wb.add_sheet("test") c=1 r=0 while r Message-ID: <8b3d7751-9bfe-47f8-a15d-e73ac3a34b41@s8g2000prg.googlegroups.com> On Jan 9, 3:52 pm, Waldemar Osuch wrote: > On Jan 9, 11:47 am, "Steven W. Orr" wrote: > > > > > So sorry because I know I'm doing something wrong. > > > 574 > cat c2.py > > #! /usr/local/bin/python2.4 > > > def inc(jj): > > def dummy(): > > jj = jj + 1 > > return jj > > return dummy > > > h = inc(33) > > print 'h() = ', h() > > 575 > c2.py > > h() = > > Traceback (most recent call last): > > File "./c2.py", line 10, in ? > > print 'h() = ', h() > > File "./c2.py", line 5, in dummy > > jj = jj + 1 > > UnboundLocalError: local variable 'jj' referenced before assignment > > > I could have sworn I was allowed to do this. How do I fix it? > > I have seen this approach on ActiveState Cookbook but can not find a > reference to it right now. > > >>> def inc(jj): > > ... def dummy(): > ... dummy.jj += 1 > ... return dummy.jj > ... dummy.jj = jj > ... return dummy > ...>>> h = inc(33) > >>> h() > 34 > >>> h() > 35 > >>> i = inc(12) > >>> i() > 13 > >>> i() > > 14 > > Waldemar Here it is: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474122 From p at ulmcnett.com Fri Jan 25 01:03:19 2008 From: p at ulmcnett.com (Paul McNett) Date: Thu, 24 Jan 2008 22:03:19 -0800 Subject: Terminology: "script" versus "program" In-Reply-To: <13pid16l607s065@corp.supernews.com> References: <1666950d-e9a5-4b7c-a614-5bba90e5b4ca@y5g2000hsf.googlegroups.com> <87ir1j7r9k.fsf_-_@benfinney.id.au> <13pid16l607s065@corp.supernews.com> Message-ID: <47997BA7.9090309@ulmcnett.com> Steven D'Aprano wrote: > Linux/Unix/Mac admins may be excused for saying that they've never come > across a .BAT file at all. > > $ locate .bat | wc -l > 14 > $ locate .sh | wc -l > 606 $ locate .bat | wc -l 115 $ locate .sh | wc -l 763 $ locate .py | wc -l 44030 Hmmm... that matched all the .pyo and .pyc files, too. Not fair. $ locate -r '\.py$' | wc -l 17425 $ locate -r '\.sh$' | wc -l 278 $ locate -r '\.bat$' | wc -l 49 Still a bit unbelievable, although I do have all the branches and tags checked out of my main projects, and I tend to make lots of little .py files so most of that 17,425 number is probably me. Paul -- http://paulmcnett.com From dongie.agnir at gmail.com Wed Jan 9 15:46:12 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Wed, 9 Jan 2008 12:46:12 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: Thanks for the clarification. Though I was hoping someone could give me a definitive answer. I was quite excited about this project initially, but seeing the actual execute times was a big downer. Seeing that the original laser marker by GRL Vienna is done in Processing which from what I know is built on Java, I was hoping that Python would be up to a similar task. From bs866806 at 163.com Tue Jan 8 07:22:35 2008 From: bs866806 at 163.com (bs866806 at 163.com) Date: Tue, 8 Jan 2008 04:22:35 -0800 (PST) Subject: =?ISO-8859-1?Q?Intranet_Project_-_Rad_Or_Waterfall??= Message-ID: <53490824-d95a-43ab-a405-e1249d4b396f@s12g2000prg.googlegroups.com> I have often used the analogy of building a bridge to explain to business colleagues the difference between Rapid Application Development (RAD) and Waterfall. Let's say that we are in the middle ages and the Mayor of Kingston- upon-Thames is evaluating whether or not to build a bridge over the river to the north side, to replace the current ferry. The whole area has been growing rapidly and a bridge at Kingston should give his town a lead against competing local towns like Ham and Richmond (who also have their own ferries). However, building a bridge presents problems. Firstly, the bedrock north and south of the river are very different. Secondly, the river is still tidal at this point and its path continues to vary across the floodplain. Finally - and perhaps most importantly - there is no guarantee that the projected growth in cross-river traffic will indeed materialise - or that people will wish to cross at this precise point, rather than further up, or down, river. A new bridge could prove an expensive white elephant and divert much-needed town resources away from other projects. The increased local taxes required could also scare the very businesses he is hoping to attract away to other local towns. Option 1 - Waterfall Waterfall, as a methodology, is all about building reliable systems. At each stage of the lifecycle, the results are correct. The Mayor's engineer believes that - when building a bridge - the result needs to be safe, sound and capable of lasting for decades. He recommends a design phase, which includes thoroughly testing the bedrock by driving piles and developing ways to limit the future variance of the river's course. During the build phase, the bridge would be tested to ensure it can take the loads that will be placed upon it and to deal with high winds or flood conditions. The engineer confirms that each stage would only start once the previous stage had been proved correct beyond reasonable doubt. The stone bridge will take five whole years to build (with a high upfront cost commitment). If the project were ever stopped, the value tied up in phases to date would be lost. The engineer reminds the Mayor that a collapsed bridge would not help his place in history! Option 2 - RAD RAD, as a methodology is all about building relevant systems. The argument runs that it is better to be there quickly with 80% of the functionality in 20% of the time, so as to take full advantage of the business opportunity. The Mayor's political advisors recommend the RAD option; to lay a pontoon bridge first alongside the existing ferry. This can be achieved in just three months, using a series of boats with a makeshift road surface and swing bridge lock for river vessels to navigate. The pontoon bridge allows the business model to be tested very quickly; If the expected benefits materialise, then further iterations of the bridge can be constructed later on. Sounds good, but of course (overall) the costs will be higher than waterfall if a full, stone bridge is ultimately required. In the meantime, if the river changes course, or floods impact the area, then the pontoon bridge will be washed away. His chief advisor reminds him that a bridge five years from now would not help his re-election prospects two years hence! The Mayor's selected option Hmm. Interesting, isn't it. Not a clear-cut decision. There are good arguments for either approach. The Mayor's decision will ultimately depend on (a) how sure he is of his own vision, (b) his financial and time constraints and (c) how changeable these factors are likely to be over time. In short, he has a trade-off decision of relevance vs. reliability. Turning the analogy onto Intranet Projects In chapter 16 of my Intranet Portal Guide, I explore these concepts in a bit more depth.However - put simply - the answer for you will depend largely on how sure you are of your vision, the support of stakeholders, the availability of resources and the degree of change in your organisation and it's requirements. If you are operating in a stable business environment and are well funded and supported, then waterfall offers real benefits. You could establish an Intranet Portal that is well founded, scalable and secure. If not, then RAD could offer you the means to make some progress now at low cost and use the results of your early work to build a stronger case for future investment. It also allows you to vary the approach - or begin again - should circumstances or requirements change. Most Intranet evangelists will find themselves perhaps in a mixed situation, where there is support and funding but there is also the risk of rapid changes to the underlying business environment and requirements. Here, I would recommend a mixed approach: Use a waterfall project to establish the underlying portal infrastructure (as this platform will be the bedrock on which you will build and needs to stand the test of time). Then use a RAD method to build the content and applications (developing solutions that are timely and relevant to businesses operating in a fast-moving and competitive environment). http://cncarrental.cn/html/Internet/20060929/31828.html From mani.agape at gmail.com Tue Jan 29 22:54:18 2008 From: mani.agape at gmail.com (Manikandan R) Date: Wed, 30 Jan 2008 09:24:18 +0530 Subject: How to collect all the IP address of the system connected in network? Message-ID: Hai, I am working with python 2.4. I am new to python, I need to collect all the ipaddress of the systems connected in the network for my project. While browsing I come accross Ur link. I think U peoples can help me. Can U please send me the code and guide me to get it. I am in dead line so can U make it fast ................ Thank's and Regard's, R.Manikandan. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Jan 23 03:12:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 06:12:29 -0200 Subject: python24 symbol file...pyhon24.pdb References: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> Message-ID: En Wed, 23 Jan 2008 05:04:35 -0200, escribi?: > I've seen a few references on the net to a python24.pdb file. I assume > it's a symbol file along the lines of the pdb files issued by > microsoft for their products. Maybe I'm wrong. > > Has anyone seen such an animal? I don't get why you care so much about that file. It's useful to debug a crash in python.exe, but I can't see any other useful purpose (if you only have the python executable and the .pdb available). > Also, is there source code available for python24 for Windoze? I have > seen reference to source code but not in a package for Windows. There is a single source package shared by all platforms. You can download and compile it, and you'll get your own version of python.pdb if you like. -- Gabriel Genellina From lefevrol at yahoo.com Mon Jan 28 14:34:04 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Mon, 28 Jan 2008 20:34:04 +0100 Subject: read and readline hanging In-Reply-To: References: Message-ID: >> Yes, that has since occurred to me. I need to echo some magic string >> after each command to know that I reached the end of the answer to >> the previous command. In interactive mode the prompt fulfills that >> role. > > And hope that that "magic string" does not occur somewhere within > the response... In a numerical setting there are strings you can be pretty sure will not occur, esp. alone on their own line. It might be harder if you were dealing with arbitrary text but I'm not. > I think you would be better off looking into the correctly spelled > 'threading' module rather than the misspelled 'trheading' module. :-) That was a just a copy-and-paste from the original reply. It would not have caused me to segfault not to find a module named 'trhreading': I'm a human, not a 'puter ;-) -- O.L. From ricaraoz at gmail.com Mon Jan 14 13:09:07 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 14 Jan 2008 15:09:07 -0300 Subject: split parameter line with quotes In-Reply-To: References: <37fac828-20ec-4cb9-8ea7-a85cce7d3e91@k39g2000hsf.googlegroups.com> Message-ID: <478BA543.7030508@bigfoot.com> teddyber wrote: > here's the solution i have for the moment : > > t = shlex.shlex(data) > t.wordchars = t.wordchars + "/+.-" > r='' > while 1: > token = t.get_token() > if not token: > break > if not token==',': r = r+token > else: r = r + ' ' > self.DEBUG(r,'ok') > for pair in r.split(' '): > key,value=pair.split('=', 1) > print(key+':'+value) > > i know this is not perfect still but i'm coming a long way from very > bad php habits! :o) > and thanks for your help! > > On 11 jan, 23:30, teddyber wrote: >> wow! that's perfect this shlex module! thanks for pointing this! >> >> On 11 jan, 20:36, Joshua Kugler wrote: >> >>> teddyber wrote: >>>> first i'm a newbie to python (but i searched the Internet i swear). >>>> i'm looking for some way to split up a string into a list of pairs >>>> 'key=value'. This code should be able to handle this particular >>>> example string : >>>> qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, >>>> 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess >>>> i know i can do that with some regexp (i'm currently trying to learn >>>> that) but if there's some other way... >>> Take a look at the shlex module. You might be able to fiddle with the shlex >>> object and convince it to split on the commas. But, to be honest, that >>> above would be a lot easier to parse if the dividing commas were spaces >>> instead. >>> j > Maybe you like : >>> x = 'qop = "auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess' >>> dict(zip([k[-1].strip() for k in (j.split(',') for j in ''.join(i for i in x if i != '"').split('='))][:-1], [k[:-1] or k for k in (j.split(',') for j in ''.join(i for i in x if i != '"').split('='))][1:])) {'maxbuf': ['1024'], 'cipher': ['rc4-40', 'rc4-56', 'rc4', 'des', ' 3des'], 'charset': ['utf-8'], 'algorithm': ['md5-sess'], 'qop': [' auth', 'auth-int', 'auth-conf']} From martin at marcher.name Tue Jan 8 05:01:03 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 08 Jan 2008 11:01:03 +0100 Subject: Look for a string on a file and get its line number References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <20080108083302.GD75977@nexus.in-nomine.org> Message-ID: Jeroen Ruigrok van der Werven wrote: > -On [20080108 09:21], Horacius ReX (horacius.rex at gmail.com) wrote: >>I have to search for a string on a big file. Once this string is >>found, I would need to get the number of the line in which the string >>is located on the file. Do you know how if this is possible to do in >>python ? > > (Assuming ASCII, otherwise check out codecs.open().) > > big_file = open('bigfile.txt', 'r') > > line_nr = 0 > for line in big_file: > line_nr += 1 > has_match = line.find('my-string') > if has_match > 0: > print 'Found in line %d' % (line_nr) > > Something to this effect. apart from that look at the linecache module. If it's a big file it could help you with subsequent access to the line in question hth martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From bignose+hates-spam at benfinney.id.au Mon Jan 14 06:18:44 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 14 Jan 2008 22:18:44 +1100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: <87prw4fyej.fsf@benfinney.id.au> "A.T.Hofkamp" writes: > while you think you are doing "Person('me', 'here', 31)", you are in > reality executing "Person.__init__(self, 'me', 'here', 31)", where > 'self' is refers to a shiny new, empty object created for you. This is misleading, and founders on many discrepancies, not least of which is that '__init__' always returns None, yet the 'Person()' call returns the new instance. So it's quite untrue to say that one is "in reality" calling the '__init__' method. What one is "in reality" calling is the '__new__' method of the Person class. That function, in turn, is creating a new Person instance, and calling the '__init__' method of the newly-created instance. Finally, the '__new__' method returns that instance back to the caller. -- \ "Probably the toughest time in anyone's life is when you have | `\ to murder a loved one because they're the devil." -- Emo | _o__) Philips | Ben Finney From gagsl-py2 at yahoo.com.ar Sun Jan 27 12:45:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 15:45:14 -0200 Subject: getting values from cache References: <480b367b-e5c4-4018-a968-8c146555dbdd@v29g2000hsf.googlegroups.com> Message-ID: En Sat, 26 Jan 2008 05:21:52 -0200, nodrogbrown escribi?: > hi > i am writing code to check a folder containing images and then process > thir vals using PIL and do some calc to create a matrix of values .if > the folder has any new imgs added the program will do all calc again > and dump the values into a cachefile.If the folder contents remain > unaltered the program should not do calc but load the vals from > cachefile..it is assumed that malicious alterations are not made on > the folder and so i wont be doing any thorogh check but just checking > if contents of folder have changed..i do something like this > > > def checkCache(self): > filenameslist=getfilenameslist() # made by parsing folder before > this > try: > f=open(cachefile) > > except IOError: > #no cache found ,do all calc > mynumpymatrix1,imgwdth,imght=docalculations() > f2=open(cachefile,"w") > #dump values as tuple > pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f2) > f2.close() > else: > #cache exists, need to check if folder contents changed > oldfilenameslist,wd,ht, mynumpymatrix1=pickle.load(f) > f.close() > > if(filenamelist==oldfilelist): > #if oldfilenamelst same,it means folder hasn't changed > #use the vals from cache..... > else: > #folder changed > mynumpymatrix1,imgwdth,imght=docalculations() > f3=open(cachefile,"w") > pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f3) > f3.close() > > this works and does what i need in my code..but i want to know if a > more elegant solution is possible > i am not worried about someone deliberately renaming files like > aaaa.jpeg to aaa.jped and a.jpeg to deceive the checking > since it is assumed that noone has permission to modify the folder > except a trusted admin/code > > will be grateful for your suggestions > tia I'd try to avoid duplicating the calculation code. get newfilenameslist update_cache = True try: f=open(cachefile) except IOError: pass else: read oldfilenameslist f.close() if oldfilenameslist==newfilenameslist: update_cache = False if update_cache: do calculations write file Also, if you split the data in two, you can just read the filename list alone: pickle.dump(filenameslist, f2) pickle.dump((imgwdth,imght,mynumpymatrix1),f2) -- Gabriel Genellina From mwm-keyword-python.b4bdba at mired.org Wed Jan 9 19:08:53 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Wed, 9 Jan 2008 19:08:53 -0500 Subject: Python too slow? In-Reply-To: References: <7115e305-429c-47d3-a942-8a0e2a0e846f@m34g2000hsf.googlegroups.com> Message-ID: <20080109190853.6fe75851@bhuda.mired.org> On Wed, 9 Jan 2008 15:45:41 -0800 (PST) "dongie.agnir at gmail.com" wrote: > Okay I profiled the code and here is the output: > > http://heightened.files.wordpress.com/2008/01/output.txt > > It seems that the function it spends the longest on is the red_points > function that he uses to find the points. Ok, so what's that look like? Python - used properly - can be quite fast. We process 1.5 billion rows a day through our python-based ETL system. The trick is to arrange things so that the cpu-intensive work gets done by C code. Preferably by tightly coded C written by very sharp people and extensively tweaked to make it go fast. In our case, the T part of our ETL system is handled by a custom C library that's been around - and being debugged and tweaked - for quite some time. Other examples include much of the code for python's builtins, and things like the Numpy extension library. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From steven.p.clark at gmail.com Sun Jan 27 19:01:49 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Sun, 27 Jan 2008 19:01:49 -0500 Subject: Python Genetic Algorithm In-Reply-To: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> References: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <663744510801271601g7f41d550w793c62bd79b3d78e@mail.gmail.com> Why not make chromosome itself a class? class BasicChromosome(object): def __init__(self, data): self.data = data def crossover(self): [stuff here] You can subclass this as needed, altering the crossover method as necessary. ...perhaps I didn't understand your question. -Steven On Jan 27, 2008 6:35 PM, Wildemar Wildenburger wrote: > Max wrote: > > In GAs, you operate on a Population of solutions. Each Individual from > > the Population is a potential solution to the problem you're > > optimizing, and Individuals have what's called a chromosome - a > > specification of what it contains. For example, common chromosomes are > > bit strings, lists of ints/floats, permutations...etc. I'm stuck on > > how to implement the different chromosomes. I have a Population class, > > which is going to contain a list of Individuals. Each individual will > > be of a certain chromosome. I envision the chromosomes as subclasses > > of an abstract Individual class, perhaps all in the same module. I'm > > just having trouble envisioning how this would be coded at the > > population level. Presumably, when a population is created, a > > parameter to its __init__ would be the chromosome type, but I don't > > know how to take that in Python and use it to specify a certain class. > > > I'm not sure I'm following you here. So a "chromosome" is bit of > functionality, right? So basically it is a function. So my advice would > be to write these functions and store it to the "indivuals"-list like so: > > class Population(object): > def __init__(self, *individuals): > self.individuals = list(individuals) > > Then you can say: > p = Population(indiv1, indiv2, indiv3) > for individual in p.individual: > individual(whatever_your_problem) > > (Don't know if this is the way GA's are supposed to work) > > You can also create callable classes (that is, classes that implement > the __call__ method), and use instances of these as the individuals. For > example you can create a Permutation class that returns a permutation > (defined in it's __init__()) when it's __call__ method is called. (Am I > making sense?) > > This is just generic advice, maybe this helps and maybe it doesn't at > all. :) > > > > > I'm doing something similar with my crossover methods, by specifying > > them as functions in a module called Crossover, importing that, and > > defining > > > > crossover_function = getattr(Crossover, "%s_crossover" % xover) > > > > Where xover is a parameter defining the type of crossover to be used. > > I'm hoping there's some similar trick to accomplish what I want to do > > with chromosomes - or maybe I'm going about this completely the wrong > > way, trying to get Python to do something it's not made for. Any help/ > > feedback would be wonderful. > > > This isn't too bad, but for such things dictionaries are your Go-To > datatype. Just have a dictionary of xover-functions handy and call the > thusly: > > crossover_function = Crossover.function[xover] > > > > Thanks, > > Max Martin > If that helps :) > > regards > /W > > -- > http://mail.python.org/mailman/listinfo/python-list > From bignose+hates-spam at benfinney.id.au Thu Jan 24 16:16:09 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 25 Jan 2008 08:16:09 +1100 Subject: Reporting Python bugs (was: Can someone explain this unexpected raw_input behavior?) References: <13ff90c7-60ee-4306-8459-890a2b2b178a@e25g2000prg.googlegroups.com> Message-ID: <8763xi7wme.fsf_-_@benfinney.id.au> Mike Kent writes: > A bug issue has been opened in the Python Trac system for this. Wouldn't it be better to report it in the official Python bug tracker , which is Roundup, not Trac? -- \ "The right to use [strong cryptography] is the right to speak | `\ Navajo." -- Eben Moglen | _o__) | Ben Finney From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 21 13:15:29 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 19:15:29 +0100 Subject: Trouble writing to database: RSS-reader In-Reply-To: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> Message-ID: <4794e0f9$0$4429$426a74cc@news.free.fr> Arne a ?crit : > Hi! > > I try to make a rss-reader in python just for fun, and I'm almost > finished. Bad news : you're not. > I don't have any syntax-errors, but when i run my program, > nothing happends. > > This program is supposed to download a .xml-file, save the contents in > a buffer-file(buffer.txt) and parse the file looking for start-tags. > When it has found a start tag, it asumes that the content (between the > start-tag and the end-tag) is on the same line, Very hazardous assumption. FWIW, you can more safely assule this will almost never be the case. FWIW, don't assume *anything* wrt/ newlines when it comes to XML - you can even have newlines between two attributes of a same tag... > so then it removes the > start-tag and the end-tag and saves the content and put it into a > database. > > The problem is that i cant find the data in the database! If i watch > my program while im running it, i can see that it sucsessfuly > downloads the .xml-file from the web and saves it in the buffer. > > But I dont think that i save the data in the correct way, so it would > be nice if someone had some time to help me. > > Full code: http://pastebin.com/m56487698 > Saving to database: http://pastebin.com/m7ec69e1b > Retrieving from database: http://pastebin.com/m714c3ef8 1/ you don't need to make each and every variable an attribute of the class - only use attributes for what constitute the object state (ie: need to be maintain between different, possibly unrelated method calls). In your update_sql method, for exemple, beside self.connection and _eventually_ self.cursor, you don't need any attribute - local variables are enough. 2/ you don't need these Stored variables at all - just reset title/link/description to None *when needed* (cf below), then test these variables against None. 3/ learn to use if/elif properly !-) 4/ *big* logic flaw (and probably the first cause of your problem): on *each* iteration, you reset your Stored flags to False - whether you stored something in the database or not. Since you don't expect to have all there data on a single line (another wrong assumption : you might get a whole rss stream as one single big line), I bet you never write anything into the database . 5/ other big flaw : either use an autoincrement for your primary key - and *dont* pass any value for it in your query - or provide (a *unique*) id by yourself. 6/ FWIW, also learn to properly use the DB api - don't build your SQL query using string formatting, but pass the argument as a tuple, IOW: # bad: cursor.execute( '''INSERT INTO main VALUES(null, %s, %s, %s)''' % title, link, description ) # good (assuming you're using an autoincrementing key for your id) : cursor.execute( "INSERT INTO main VALUES(, , )", (title, link, description) ) NB : replace with the appropriate placeholder for your database - cf your db module documentation (usually either '?' or '%s') This will make the db module properly escape and convert values. 7/ str.replace() doesn't modify the string in-place (Python strings are immutable), but returns a new string. so you want: line = line.replace('x', 'y') 8/ you don't need to explicitely call connection.commit on each and every statement, and you don't need to call it at all on SELECT statements !-) 9/ have you tried calling print_rss *twice* on the same instance ?-) 10/ are you sure it's useful to open the same 'buffer.txt' file for writing *twice* (once in __init__, the other in update_sql). BTW, use open(), not file(). 11/ are you sure you need to use this buffer file at all ? 12/ are you really *sure* you want to *destroy* your table and recreate it each time you call your script ? > And yes, I know that there is rss-parseres already built, but this is > only for learning. This should not prevent you from learning how to properly parse XML (hint: with an XML parser). XML is *not* a line-oriented format, so you just can't get nowhere trying to parse it this way. HTH From bruno.desthuilliers at gmail.com Sat Jan 12 12:08:40 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jan 2008 09:08:40 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: On 10 jan, 03:10, Steven D'Aprano wrote: > On Wed, 09 Jan 2008 21:26:05 +0100, Bruno Desthuilliers wrote: > > hint: how can a compiler safely optimize anything in a language so > > dynamic that even the class of an object can be changed at runtime ? > > Is that a trick question? > Nope. Just an observation about the tradeoffs of dynamism. From skip at pobox.com Tue Jan 15 11:07:07 2008 From: skip at pobox.com (Skip Montanaro) Date: Tue, 15 Jan 2008 16:07:07 +0000 (UTC) Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: > > Why is that? Doesn't the |= operator essentially map to an update() call? > > No, according to 3.7 Set Types, s | t maps to s.union(t). I was asking about the |= assignment operator which according to the docs *does* map to the update method. Skip From Russ.Paielli at gmail.com Fri Jan 11 16:02:58 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Fri, 11 Jan 2008 13:02:58 -0800 (PST) Subject: split parameter line with quotes References: <9dd22f5e-5fda-42b9-b812-abb79db973fd@v67g2000hse.googlegroups.com> Message-ID: On Jan 11, 12:53 pm, "Russ P." wrote: > On Jan 11, 10:50 am, teddyber wrote: > > > Hello, > > > first i'm a newbie to python (but i searched the Internet i swear). > > i'm looking for some way to split up a string into a list of pairs > > 'key=value'. This code should be able to handle this particular > > example string : > > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > > i know i can do that with some regexp (i'm currently trying to learn > > that) but if there's some other way... > > > thanks > > The problem is that you are using commas for delimiters at two > different levels. > > I would start by replacing the commas between quotation marks with > some other delimiter, such as spaces of semicolons. To do that, step > through each character and keep a count of quotation marks. While the > count is odd, replace each comma with the selected alternative > delimiter. While the count is even, leave the comma. [An alternative > would be to replace the commas outside the quotation marks.] > > Once that is done, the problem is straightforward. Split the string on > commas (using string.split(",")). Then split each item in the list by > "=". Use the [0] element for the key, and use the [1] element for the > value (first stripping off the quotation marks if necessary). If you > need to further split each of the values, just split on whatever > delimiter you chose to replace the commas. One more point. Whoever chose the structure of the string you are parsing didn't do a very good job. If you know that person, you should tell him or her to use different delimiters at the different levels. Use commas for one level, and spaces or semicolons for the other level. Then you won't have to "correct" the string before you parse it. From bj_666 at gmx.net Sun Jan 27 07:51:47 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jan 2008 12:51:47 GMT Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> Message-ID: <603d33F1oh17aU5@mid.uni-berlin.de> On Sun, 27 Jan 2008 10:55:20 +0000, over wrote: > On Sat, 26 Jan 2008 14:47:50 +0100, Bjoern Schliessmann > wrote: > > The script is essentially gone. I'd like to know how to read the pyc > files, but that's getting away from my point that there is a link > between python scripts and assembler. At this point, I admit the code > above is NOT assembler, but sooner or later it will be converted to > machine code by the interpreter and the OS and that can be > disassembled as assembler. No it will not be converted to assembler. The byte code is *interpreted* by Python, not compiled to assembler. If you want to know how this happens get the C source code of the interpreter and don't waste your time with disassembling `python.exe`. C is much easier to read and there are useful comments too. Ciao, Marc 'BlackJack' Rintsch From bignose+hates-spam at benfinney.id.au Wed Jan 30 20:31:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 31 Jan 2008 12:31:29 +1100 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> <13q1132200cf537@corp.supernews.com> Message-ID: <87abmmok5q.fsf@benfinney.id.au> Peter Schuller writes: > I *DON'T* want anything to depend on the physical location on disk. Importing the code in the first place will ? unavoidably, it seems to me ? depend on the file location from which to load the module. After that, nothing depends on the physical location on disk, unless it's buggy. Imported modules are available from 'sys.modules', and that's where subsequent 'import' statements will find them, with no reference to file locations. > That was exactly what I was after from the beginning; a total > separation of location on disk from the location in the module > hiearachy. As you say, the location of the source should be an > implementation detail. That is exactly what I am after. It *is* an implementation detail, once the module is loaded from disk. -- \ "Philosophy is questions that may never be answered. Religion | `\ is answers that may never be questioned." ?anonymous | _o__) | Ben Finney From bignose+hates-spam at benfinney.id.au Sat Jan 12 08:47:56 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 13 Jan 2008 00:47:56 +1100 Subject: Great Python books for the beginner References: Message-ID: <87fxx3gnoz.fsf@benfinney.id.au> Landon writes: > I was wondering if anyone had any opinions on what other titles I > could look into since this one seems from a glance at reviews to be > teaching mainly through game programming (a topic I'm not too > interested in) or if this one is a quality book by itself. The book "Learning Python" is currently proving very useful to an associate of mine. I'm watching his knowledge of Python grow substantially every week, from what was an essentially zero start. Learning Python, 3rd Edition Mark Lutz O'Reilly Looking through the text, it is very well structured, thoroughly teaching all the fundamentals of the language and types and idioms while referring back to already-learned material. The author makes a living training people in Python, and the third edition has benefited from his many years of experience finding effective ways to teach the language. -- \ "If you ever teach a yodeling class, probably the hardest thing | `\ is to keep the students from just trying to yodel right off. | _o__) You see, we build to that." -- Jack Handey | Ben Finney From Luke.Visinoni at gmail.com Thu Jan 17 11:18:15 2008 From: Luke.Visinoni at gmail.com (Luke) Date: Thu, 17 Jan 2008 08:18:15 -0800 (PST) Subject: working with a subversion repo Message-ID: <7f156399-d9ae-4f13-a80f-0ffe41d89427@s12g2000prg.googlegroups.com> I want to write a script that automatically generates a subversion repository and configures apache serve the svn repo. Is there a python module that will allow me to work with subversion? I am able to import a module named "svn" on my ubuntu machine, but this module is not available on windows. I also can't seem to find any documentation on it. Thanks! From fredrik at pythonware.com Thu Jan 3 03:53:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 09:53:57 +0100 Subject: Manually installing PIL In-Reply-To: <001001c84dda$23d26760$2000a8c0@depid.local> References: <001001c84dda$23d26760$2000a8c0@depid.local> Message-ID: Jose Ignacio Gisbert wrote: > Does somebody install PIL manually??, I mean, copy directories manually > without executing setup.py. I saw an identical message from Guirai, but > I didn?t see any response. Thanks in advance! PIL's just a bunch of modules in a single PIL directory; you can put that directory (or the modules themselves) wherever you want. (if you're on windows, unzip the EXE installer to get the files) From theller at ctypes.org Mon Jan 21 15:42:59 2008 From: theller at ctypes.org (Thomas Heller) Date: Mon, 21 Jan 2008 21:42:59 +0100 Subject: ctypes CDLL - which paths are searched? In-Reply-To: <4794d573$0$2980$ba620e4c@news.skynet.be> References: <4794d573$0$2980$ba620e4c@news.skynet.be> Message-ID: Helmut Jarausch schrieb: > Hi, > > how can I specify the paths to be searched for a dynamic library > to be loaded by ctypes' CDLL class on a Linux system. > > Do I have to set os.environment['LD_LIBRARY_PATH'] ? > ctypes passes the argument given to CDLL(path) straight to the dlopen(3) call, so your system documentation should tell you. Thomas From caca at mailinator.com Mon Jan 7 06:44:21 2008 From: caca at mailinator.com (caca at mailinator.com) Date: Mon, 7 Jan 2008 03:44:21 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> <617182dc-3ca1-4cf5-b1ca-1779dd8d6550@i3g2000hsf.googlegroups.com> Message-ID: <151627bb-8600-4552-b50d-29b04fab3094@l1g2000hsa.googlegroups.com> > Just for fun, I profiled my answer versus the final answer... This mailing list is awesome! PS:ajaksu, I have to leave now, I hope bukzor's answer was enough to you (at least for the moment) From bladedpenguin at gmail.com Fri Jan 25 02:04:42 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Thu, 24 Jan 2008 23:04:42 -0800 (PST) Subject: global/local variables References: <13pia51grjfo2ed@corp.supernews.com> Message-ID: <4d161c89-7e33-4ddc-851f-bc9beb537229@q21g2000hsa.googlegroups.com> On Jan 24, 7:09 pm, Steven D'Aprano wrote: > On Thu, 24 Jan 2008 15:37:09 -0800, Tim Rau wrote: > > What makes python decide whether a particular variable > > is global or local? > > For starters, if the line of code is not inside a class or function, that > is, it's at the top level of a module, it is global. > > More interesting is if it is inside a function or class. If you assign to > the name in the function, Python assumes it is local *unless* you have > defined it as global with the global statement. > > Otherwise, Python will treat it as global. > > > I've got a list and a integer, both defined at top level, no > > indentation, right next to each other: > > > allThings = [] > > nextID = 0 > > > and yet, in the middle of a function, python sees one and doesn't see > > the other: > > I've tried to run your code -- and it isn't easy, involving much > backwards-and-forwards copying and pasting, thanks to word-wrap in you > post -- and the error I get is: > > SyntaxError: invalid syntax > > because you left off the colon from the first if statement. > > I'm not especially inclined to start hunting through your code fixing any > other errors in order to find the error you think you're getting. How > about if you quote the exception traceback you actually get? > > > I don't think it's important, but the function is defined before > > the two globals. > > Nope, not important. What's important is whether the function is *called* > before or after the globals are created. That's been my experience so far. > > If you're using global variables in your code, you probably should stop. > As a general rule, global variables are poor programming practice for a > number of reasons. Google on "Global variables considered harmful" for > some examples. > > -- > Steven I'm sorry: I forgot to say what my problem was. Python seems to think that nextID is a local, and complains that it can't find it. THis is not the full text of the function, just the level that is causing errors. the lack of : on the if is a transcription error. Traceback (most recent call last): File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox \sandbox.py", line 248, in thing.step() File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox \sandbox.py", line 112, in step allThings[len(allThings)-1].id = nextID UnboundLocalError: local variable 'nextID' referenced before assignment I want to know why it says 'local variable' it never had a problem when just allThings was in there. as for the objection to global variable: If I didn't make them global, I'd make them part of a singleton class called gameVars that would get passed everywhere. It's unlikely that they'll get mixed in with anyhting else, as they fulfill a unique function. Also, I think it's more convenient, and I am, after all, my own employer when it comes to programming. From nikbaer at gmail.com Tue Jan 29 14:06:36 2008 From: nikbaer at gmail.com (nik) Date: Tue, 29 Jan 2008 11:06:36 -0800 (PST) Subject: ISO with timezone References: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Message-ID: <82906208-c7ad-49c3-a91f-851add8cd6cd@s19g2000prg.googlegroups.com> On Jan 29, 10:56 am, nik wrote: > Thanks, > that does help and now I have: > > >>> from datetime import datetime, tzinfo, timedelta > >>> import time > >>> class TZ(tzinfo): > > ... def utcoffset(self,dt): return timedelta(seconds=time.timezone) > ...>>> print datetime(2008,2,29,15,30,11,tzinfo=TZ()).isoformat() > > 2008-02-29T15:30:11+8:00 > > But what I want to know now it how to get the actual time into the > expression instead of typing the 2008,2,29,15.... > So something like: >>> print > datetime(time.gmtime(),tzinfo=TZ()).isoformat(), but that doesn't > work. > > I realize that I could do: > > >>> t = time.localtime() > >>> print datetime(t[0],t[1],t[2],t[3],t[4],t[5],tzinfo=TZ()).isoformat() > > but I imagine there might be a cleaner way of doing this. > > Thanks, > Nik > > On Jan 28, 9:10 pm, "Nicholas F. Fabry" > wrote: > > > Hello, nik. > > > On Jan 28, 2008, at 21:03, nik wrote: > > > > Hi, > > > > How does one express the time in ISO format with the timezone > > > designator? > > > > what I want is YYYY-MM-DDThh:mm:ss.sTZD > > > >> From the documentation I see: > > >>>> from datetime import tzinfo, timedelta, datetime > > >>>> class TZ(tzinfo): > > > ... def utcoffset(self, dt): return timedelta(minutes=-399) > > > ... > > >>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') > > > '2002-12-25 00:00:00-06:39' > > > > and I've also figured out: > > >>>> datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3] > > > '2008-01-23T11:22:54.130' > > > > But can't figure out how to fit them together. > > > There is nothing there to 'fit together' - in the first example given, > > the datetime object has no time component specified, so it fills in > > default vaules of zero. The following should make this clear: > > > >>> your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ()) > > >>> print your_time > > 2008-02-29 15:30:11-05:00 > > >>> print your_time.isoformat('T') > > 2008-02-29T15:30:11-05:00 > > > If you wish to append the NAME of the tzinfo object instead of its > > offset, that requires a bit more playing around (along with a properly > > defined tzinfo object - check out dateutil or pytz for a concrete > > implementation of tzinfo subclasses (i.e. timezones)), but the > > following would work: > > > >>> print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z') > > 2008-02-29T15:30:11 EST > > > For details on how the .strftime method works, see Python Standard > > Library, Section 14.2. > > > I hope this helps! > > > Nick Fabry > > > > Thank you, > > > Nik > > > -- > > >http://mail.python.org/mailman/listinfo/python-list From deets at nospam.web.de Tue Jan 22 07:18:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 13:18:05 +0100 Subject: possible to overide setattr in local scope? References: <9dac9675-992e-4dc5-b085-06f0811939ca@1g2000hsl.googlegroups.com> Message-ID: <5vm57tF1m6cucU1@mid.uni-berlin.de> glomde wrote: > In a class it is poosible to override setattr, so that you can decide > how you should > handle setting of variables. > > Is this possible to do outside of an class on module level. > > mysetattr(obj, var, value): > print "Hello" > > So that > > test = 5 > > > would print > Hello No, that's not possible. What you could do instead is to create a singlton that you use to store the values in, instead of the module directly. Like this (untested): class ModuleState(object): # borg pattern - why not... _shared_state = {} def __init__(self): self.__dict__ = ModuleState._shared_state def __setattr__(self, name, value): setattr(self, name, "hello") state = ModuleState() Then you do state.test = 5 Diez From deets at nospam.web.de Mon Jan 21 12:08:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Jan 2008 18:08:42 +0100 Subject: building psycopg2 on windows using mingw, "cannot find -lpq" References: Message-ID: <5vk1sqF1mal8qU1@mid.uni-berlin.de> GHUM wrote: > The compile works, BUT linking fails: > > 2.5\Release\psycopg\_psycopg.def -Lc:\python25\libs -Lc: > \python25\PCBuild -Lc:/p > ostgres/83RC2/lib -lpython25 -lpq -lws2_32 -ladvapi32 -o build > \lib.win32-2.5\psy > copg2\_psycopg.pyd > c:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: > cannot find -lpq > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 > > if I google for the error > > "ld.exe: cannot find -lpq" > > there is allways the information that the lib-dir of libpq is missing; > but : > > -Lc:/postgres/83RC2/lib > > is clearly in the commandline, and within c:/postgres/83RC2/lib > there is one libqp.lib > > What am I missing? any hints? Are you sure using forward slashes in the path works here? Diez From mobiledreamers at gmail.com Tue Jan 8 19:26:54 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Tue, 8 Jan 2008 16:26:54 -0800 Subject: Spaces and tabs messing up code Message-ID: my friend uses vim and i use xemacs so our shared python code is a mix of tabs and spaces and it is hard for him to edit it in vim any idea on how to make it clean convert it all to 4 spaces? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas.troeger.ext at siemens.com Thu Jan 10 08:10:05 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 10 Jan 2008 14:10:05 +0100 Subject: Embedding python code into text document question. Message-ID: Dear all, I've written a program that parses a string or file for embedded python commands, executes them and fills in the returned value. The input might look like this: process id: $$return os.getpid()$$ current date: $$return time.ctime()$$ superuser: $$ if os.geteuid(): return "Yes" else: return "No"$$ I've tried several solutions using eval, execfile or compile, but none of those would solve my problem. Does anyone have a solution that works? Any suggestions? Any help will be appreciated :) Regards, Thomas. From gagsl-py2 at yahoo.com.ar Thu Jan 24 02:29:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 Jan 2008 05:29:38 -0200 Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> Message-ID: En Thu, 24 Jan 2008 04:52:22 -0200, glacier escribi?: > According to your reply, what will happen if I try to decode a long > string seperately. > I mean: > ###################################### > a='???'*100000 > s1 = u'' > cur = 0 > while cur < len(a): > d = min(len(a)-i,1023) > s1 += a[cur:cur+d].decode('mbcs') > cur += d > ###################################### > > May the code above produce any bogus characters in s1? Don't do that. You might be splitting the input string at a point that is not a character boundary. You won't get bogus output, decode will raise a UnicodeDecodeError instead. You can control how errors are handled, see http://docs.python.org/lib/string-methods.html#l2h-237 -- Gabriel Genellina From apardon at forel.vub.ac.be Tue Jan 22 07:23:32 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 22 Jan 2008 12:23:32 GMT Subject: assigning values in python and perl References: <18c1e5f20801161934m69ff44edo1e35f5381f7d2928@mail.gmail.com> Message-ID: On 2008-01-17, Steven D'Aprano wrote: > On Thu, 17 Jan 2008 11:40:59 +0800, J. Peng wrote: > >> May I ask, python's pass-by-reference is passing the object's reference >> to functions, but perl, or C's pass-by-reference is passing the variable >> itself's reference to functions. So althought they're all called >> pass-by-reference,but will get different results.Is it? > > Python is not call by reference. > > Any book or person that says it is, is wrong to do so. > > Python's function call semantics are not the same as C, or Perl, or > Pascal. They are, however, similar to those of Lisp, Scheme, Emerald and > especially CLU. It is neither pass by reference, nor pass by value. I don't think it is the function call semantics that are so different as it is the assignment itself that is different. an assignment in C, doesn't bind a new object to the name, but stores new information in the object. Trying to explain the different behaviour of C and python of examples calling function that assign to a parameter, without explaining how the assignment works will IMO not give people enough to understand what is happening. -- Antoon Pardon From basilisk96 at gmail.com Fri Jan 11 01:56:18 2008 From: basilisk96 at gmail.com (Basilisk96) Date: Thu, 10 Jan 2008 22:56:18 -0800 (PST) Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <496d868e-09a5-4410-bbfc-b382ce6f0587@f10g2000hsf.googlegroups.com> On Jan 10, 10:36 pm, Marty wrote: > Hrvoje Niksic wrote: > > Mike Meyer writes: > > >> It sounds to me like your counter variable actually has meaning, > > > It depends how the code is written. In the example such as: > > > for meaningless_variable in xrange(number_of_attempts): > > ... > > > the loop variable really has no meaning. Rewriting this code only to > > appease pylint is exactly that, it has nothing with making the code > > more readable. > > >> you've hidden that meaning by giving it the meaningless name "i". If > >> you give it a meaningful name, then there's an obvious way to do it > >> (which you listed yourself): > > >> while retries_left: > > [...] > > > This loop contains more code and hence more opportunities for > > introducing bugs. For example, if you use "continue" anywhere in the > > loop, you will do one retry too much. > > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) > > This caused me to wonder why Python does not have a "foreach" statement (and > also why has it not come up in this thread)? I realize the topic has probably > been beaten to death in earlier thread(s), but does anyone have the short answer? But it does: data_in = (1,2,3,4,5) data_out = [] data_out += [[] for blah in data_in] print data_out [[], [], [], [], []] Cheers, -Basilisk96 From bladedpenguin at gmail.com Wed Jan 23 07:13:21 2008 From: bladedpenguin at gmail.com (bladedpenguin at gmail.com) Date: Wed, 23 Jan 2008 04:13:21 -0800 (PST) Subject: Removing objects References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> Message-ID: On Jan 23, 2:24 am, Robert Kern wrote: > bladedpeng... at gmail.com wrote: > > I am writing a game, and it must keep a list of objects. I've been > > representing this as a list, but I need an object to be able to remove > > itself. It doesn't know it's own index. If I tried to make each object > > keep track of it's own index, it would be invalidated when any object > > with a lower index was deleted. The error was that when I called > > list.remove(self), it just removed the first thing in hte list with > > the same type as what I wanted, rather than the object I wanted. The > > objects have no identifying charachteristics, other than thier > > location in memory > > By default, classes that do not implement the special methods __eq__ or __cmp__ > get compared by identity; i.e. "(x == y) == (x is y)". Double-check your classes > and their super-classes for implementations of one of these methods. > mylist.remove(x) will check "x is mylist[i]" first and only check "x == > mylist[i]" if that is False. > > In [1]: class A(object): > ...: def __eq__(self, other): > ...: print '%r == %r' % (self, other) > ...: return self is other > ...: def __ne__(self, other): > ...: print '%r != %r' % (self, other) > ...: return self is not other > ...: > ...: > > In [2]: As = [A() for i in range(10)] > > In [3]: As > Out[3]: > [<__main__.A object at 0xf47f70>, > <__main__.A object at 0xf47d90>, > <__main__.A object at 0xf47db0>, > <__main__.A object at 0xf47cb0>, > <__main__.A object at 0xf47eb0>, > <__main__.A object at 0xf47e70>, > <__main__.A object at 0xf47cd0>, > <__main__.A object at 0xf47e10>, > <__main__.A object at 0xf47dd0>, > <__main__.A object at 0xf47e90>] > > In [4]: A0 = As[0] > > In [5]: A0 > Out[5]: <__main__.A object at 0xf47f70> > > In [6]: As.remove(A0) > > In [7]: As > Out[7]: > [<__main__.A object at 0xf47d90>, > <__main__.A object at 0xf47db0>, > <__main__.A object at 0xf47cb0>, > <__main__.A object at 0xf47eb0>, > <__main__.A object at 0xf47e70>, > <__main__.A object at 0xf47cd0>, > <__main__.A object at 0xf47e10>, > <__main__.A object at 0xf47dd0>, > <__main__.A object at 0xf47e90>] > > In [8]: A0 > Out[8]: <__main__.A object at 0xf47f70> > > In [9]: A9 = As[-1] > > In [10]: As.remove(A9) > <__main__.A object at 0xf47d90> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47db0> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47cb0> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47eb0> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47e70> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47cd0> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47e10> == <__main__.A object at 0xf47e90> > <__main__.A object at 0xf47dd0> == <__main__.A object at 0xf47e90> > > In [11]: As > Out[11]: > [<__main__.A object at 0xf47d90>, > <__main__.A object at 0xf47db0>, > <__main__.A object at 0xf47cb0>, > <__main__.A object at 0xf47eb0>, > <__main__.A object at 0xf47e70>, > <__main__.A object at 0xf47cd0>, > <__main__.A object at 0xf47e10>, > <__main__.A object at 0xf47dd0>] > > In [12]: A9 > Out[12]: <__main__.A object at 0xf47e90> > > If you cannot find an implementation of __eq__ or __cmp__ anywhere in your code, > please try to make a small, self-contained example like the one above but which > demonstrates your problem. > > > So my question: How do I look something up in a list by it's location > > in memory? does python even support pointers? > > If you need to keep an __eq__ that works by equality of value instead of > identity, then you could keep a dictionary keyed by the id() of the object. That > will correspond to its C pointer value in memory. > > In [13]: id(A9) > Out[13]: 16023184 > > In [14]: hex(_) > Out[14]: '0xf47e90' > > > Is there a better way? > > Possibly. It looks like you are implementing a cache of some kind. Depending on > exactly how you are using it, you might want to consider a "weak" dictionary > instead. A weak dictionary, specifically a WeakValueDictionary, acts like a > normal dictionary, but only holds a weak reference to the object. A weak > reference does not increment the object's reference count like a normal > ("strong") reference would. Consequently, once all of the "strong" references > disappear, the object will be removed from the WeakValueDictionary without your > having to do anything explicit. If this corresponds with when you want the > object to be removed from the cache, then you might want to try this approach. > Use "id(x)" as the key if there is no more meaningful key that fits your > application. > > http://docs.python.org/lib/module-weakref.html > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco So, in general, is it more efficient to use a dictionary or to override the __eq__ function? From guptaabhishek1983 at gmail.com Tue Jan 8 01:18:41 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Mon, 7 Jan 2008 22:18:41 -0800 (PST) Subject: web service between python and c# Message-ID: <12f6e713-392e-4fda-8354-51a8337d77dc@l6g2000prm.googlegroups.com> Hello group i need to make a web service to work between python and c# . Where python would server as backend (server) preferebly cherrypy (turbogears) and client would be on a c# appln. I have developed a webservice using TGWebServices package which runs on top of turbogears. but have no idea on how to interface it with c# client. Thank YOu From mwm at mired.org Fri Jan 11 11:57:03 2008 From: mwm at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 11:57:03 -0500 Subject: How to POST call and retrieve result page In-Reply-To: <16314edc0801110114t346bca6ek71660132de60b91e@mail.gmail.com> References: <16314edc0801110114t346bca6ek71660132de60b91e@mail.gmail.com> Message-ID: <20080111115703.16dbabd7@mbook.mired.org> On Fri, 11 Jan 2008 14:44:19 +0530 "suyash jape" wrote: > Hi all > i want to access a web page through python script, fillup the necessary > fields, > and press submit button (which does POST call) and retrieve the result page > and retrieve some values from it. > > Here is the script i have written till now. > > >import urllib2 > > # create array of name/value pairs > > self.params = urllib.urlencode({'seqname': 'BioSequence', 'sequence': > 'ATACATTATCCAAACATAAAAAGCATGGCTT'}) > > > > # send http-post > > request = urllib.urlopen("http://www.hydrazome.metazome.net/search.php", > params) > > > > # read back each line of reply > > line = request.read() > >print line > > This script fills up the correct values in the search.php page.But i am not > sure if it is doing the POST (submit call). > Beacause in 'line' varialble, i am getting the search.php page.Not the > result page which is blast_results.php. > > How to retrieve the result page? Sounds like you're not POSTing to the right page. The form on .../search.php lets you fill in values, but those values are not necessarily POSTed to search.php. In particular, the form element has an action attribute that has a URL to which the values on the page should be posted. If that points to .../blast_results.php, then that's the page you need to pass to urlopen with your data. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From ptmcg at austin.rr.com Wed Jan 2 03:50:15 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 2 Jan 2008 00:50:15 -0800 (PST) Subject: pyparsing question References: <8df809a0-1950-4250-a968-2d366f64cdb4@d21g2000prf.googlegroups.com> Message-ID: <8a68b387-01c9-4dc7-8a48-3fb146395ea7@n20g2000hsh.googlegroups.com> On Jan 1, 5:32?pm, hubritic wrote: > I am trying to parse data that looks like this: > > IDENTIFIER ? ?TIMESTAMP ? T ?C ? RESOURCE_NAME ? DESCRIPTION > 2BFA76F6 ? ? 1208230607 ? T ? S ? SYSPROC ? ? ? ? ? ? ? ? ? ?SYSTEM > SHUTDOWN BY USER > A6D1BD62 ? 1215230807 ? ? I > H ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Firmware Event > > The data I have has a fixed number of characters per field, so I could > split it up that way, but wouldn't that defeat the purpose of using a > parser? ? I think you have this backwards. I use pyparsing for a lot of text processing, but if it is not a good fit, or if str.split is all that is required, there is no real rationale for using anything more complicated. > I am determined to become proficient with pyparsing so I am > using it even when it could be considered overkill; thus, it has gone > past mere utility now, this is a matter of principle! > Well, I'm glad you are driven to learn pyparsing if it kills you, but John Machin has a good point. This data is really so amenable to something as simple as: for line in logfile: id,timestamp,t,c resource_and_description = line.split(None,4) that it is difficult to recommend pyparsing for this case. The sample you posted was space-delimited, but if it is tab-delimited, and there is a pair of tabs between the "H" and "Firmware Event" on the second line, then just use split("\t") for your data and be done. Still, pyparsing may be helpful in disambiguating that RESOURCE_NAME and DESCRIPTION text. One approach would be to enumerate (if possible) the different values of RESOURCE_NAME. Something like this: ident = Word(alphanums) timestamp = Word(nums,exact=10) # I don't know what these are, I'm just getting the values # from the sample text you posted t_field = oneOf("T I") c_field = oneOf("S H") # I'm just guessing here, you'll need to provide the actual # values from your log file resource_name = oneOf("SYSPROC USERPROC IOSUBSYS whatever") logline = ident("identifier") + timestamp("time") + \ t_field("T") + c_field("C") + \ Optional(resource_name, default="")("resource") + \ Optional(restOfLine, default="")("description") Another tack to take might be to use a parse action on the resource name, to verify the column position of the found token by using the pyparsing method col: def matchOnlyAtCol(n): def verifyCol(strg,locn,toks): if col(locn,strg) != n: raise ParseException(strg,locn,"matched token not at column %d" % n) return verifyCol resource_name = Word(alphas).setParseAction(matchOnlyAtCol(35)) This will only work if your data really is columnar - the example text that you posted isn't. (Hmm, I like that matchOnlyAtCol method, I think I'll add that to the next release of pyparsing...) Here are some similar parsers that might give you some other ideas: http://pyparsing.wikispaces.com/space/showimage/httpServerLogParser.py http://mail.python.org/pipermail/python-list/2005-January/thread.html#301450 In the second link, I made a similar remark, that pyparsing may not be the first tool to try, but the variability of the input file made the non-pyparsing options pretty hairy-looking with special case code, so in the end, pyparsing was no more complex to use. Good luck! -- Paul From richard at pyweek.org Thu Jan 31 16:11:34 2008 From: richard at pyweek.org (richard at pyweek.org) Date: Fri, 1 Feb 2008 08:11:34 +1100 Subject: PyWeek 6 is coming! Message-ID: <200802010811.34973.richard@pyweek.org> 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 at http://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/ From kyosohma at gmail.com Fri Jan 18 17:17:33 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jan 2008 14:17:33 -0800 (PST) Subject: Core Python Programming . . . References: <7xir1q29j5.fsf@ruckus.brouhaha.com> Message-ID: On Jan 18, 1:55 pm, Paul Rubin wrote: > FireNWater writes: > > 1) convert a 4-digit Integer (WXYZ) to an IP address (WWW.XXX.YYY.ZZZ) > > > or > > > 2) convert an 8-digit Integer (WWWXXXYYYZZZ) to (WWW.XXX.YYY.ZZZ) > > > Thanks for anyone with the clue!!! > > Without being able to see the exercise I suspect it's turn a 4-byte > string (i.e. 32 bits) into an IP address (int8.int8.int8.int8). > Or, it might be turn a 32-bit int into such an address. I've got the book and I think the OP may be referring to this: 6-11 Conversion. (a) Create a program that will convert from an integer to an Internet Protocol (IP) address in the four-octet format of WWW.XXX.YYY.ZZZ (b) Update your program to be able to do the vice verse of the above. It could be a 12 digit int...or it could be what you (Paul) are referring to. Mike From aisaac at american.edu Fri Jan 25 11:56:44 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 25 Jan 2008 16:56:44 GMT Subject: find minimum associated values Message-ID: I have a small set of objects associated with a larger set of values, and I want to map each object to its minimum associated value. The solutions below work, but I would like to see prettier solutions... Thank you, Alan Isaac =================================================================== import time, random from itertools import groupby from collections import defaultdict class Pass: pass # arbitrary setup keys = [Pass() for i in range(10)]*3 vals = [random.random() for i in range(30)] kv = zip(keys,vals) random.shuffle(kv) #OBJECTIVE: # find minimum val associated with each "key" in kv print "method 1: brute force" t=time.clock() d = dict() for k,v in kv: if k in d: if d[k] > v: d[k] = v else: d[k] = v print time.clock()-t print d print print "method 2: groupby" t=time.clock() d = dict() kv_sorted = sorted(kv, key=lambda x: id(x[0])) for k, g in groupby( kv_sorted, key=lambda x: x[0] ): d[k] = min(gi[1] for gi in g) print time.clock()-t print d print print "method 3: defaultdict" t=time.clock() d = defaultdict(list) for k,v in kv: d[k].append(v) for k in d: d[k] = min(d[k]) print time.clock()-t print d From workitharder at gmail.com Sat Jan 5 16:45:16 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 5 Jan 2008 13:45:16 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <477fba91$0$8348$9b622d9e@news.freenet.de> Message-ID: On Jan 5, 9:12 am, "Martin v. L?wis" wrote: > > Any other ideas? > > How about this: > > def random_pick(list, property): > L = len(list) > pos = start = random.randrange(L) > while 1: > x = list[pos] > if property(x): return x > pos = (pos + 1) % L > if pos == start: > raise ValueError, "no such item" > > Regards, > Martin I thought about this, but in the sequence "00012" (and property = bool) the 1 will be returned four times as often as the 2. Maybe that's ok... From fredrik at pythonware.com Sun Jan 27 13:27:19 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Jan 2008 19:27:19 +0100 Subject: python regex: misbehaviour with "\r" (0x0D) as Newline character in Unicode Mode In-Reply-To: <479C6B56.5030402@sanusi.de> References: <479C6B56.5030402@sanusi.de> Message-ID: Arian Sanusi wrote: > concerning to unicode, "\n", "\r "and "\r\n" (0x000A, 0x000D and 0x000D+0x000A) should be threatened as newline character the link says that your application should treat them line terminators, not that they should all be equal to a new line character. to split on Unicode line endings, use the splitlines method. for the specific characters you mention, you can also read the file in universal mode. From rschroev_nospam_ml at fastmail.fm Fri Jan 25 03:44:47 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 25 Jan 2008 08:44:47 GMT Subject: Test driven development In-Reply-To: <273268bb-421f-4228-a16b-a64ea38869b8@m34g2000hsf.googlegroups.com> References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> <53bae618-0a57-470e-b698-3f936ef7c0e7@s12g2000prg.googlegroups.com> <98f3ca4c-a7f0-4707-b09d-8012b86de96b@x69g2000hsx.googlegroups.com> <273268bb-421f-4228-a16b-a64ea38869b8@m34g2000hsf.googlegroups.com> Message-ID: <3khmj.45198$k72.3681428@phobos.telenet-ops.be> alex23 schreef: > On Jan 25, 5:44 am, Roel Schroeven > wrote: >> I guess I just need to try somewhat harder to use TDD in my daily >> coding. Apart from books, are there other resources that can help >> beginners with TDD? Mailing lists, forums, newsgroups possibly? > > There's the Testing-in-Python mailing list. It's pretty low traffic > but generally relevant: > > http://lists.idyll.org/listinfo/testing-in-python Thank you, I'll have a look at it. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From ejensen at visi.com Fri Jan 11 11:23:46 2008 From: ejensen at visi.com (Ed Jensen) Date: Fri, 11 Jan 2008 16:23:46 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> Message-ID: <13of60ikspqhh06@corp.supernews.com> Bruno Desthuilliers wrote: > fact 1: CPython compiles source code to byte-code. > fact 2: CPython executes this byte-code. > fact 3: Sun's JDK compiles source code to byte-code. > fact 4: Sun's JDK executes this byte-code. > > Care to prove me wrong on any of these points ? Don't bother: you can't. > So my first assertion that "CPython is compiled to byte-code, which is > then executed by a VM" is true, and since the same assertion also stands > for Java (ie: sun's JDK), then the "just like" qualifier is true too. > Period. #2 and #4 are wrong (or, at best, misleading). Here, I'll fix them for you: Fact 2: CPython interprets the bytecode. Fact 4: Sun's JVM does some interpretation of the bytecode, but also compiles some of the bytecode to native code and executes the resulting native code. These distinctions can be important and it's intellectually dishonest to gloss over them. From arnodel at googlemail.com Tue Jan 8 16:59:37 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 8 Jan 2008 13:59:37 -0800 (PST) Subject: mod-python on Mac OSX 10.5 References: <4782fe18$0$26015$88260bb3@free.teranews.com> Message-ID: <7f9cef14-6d94-4a6b-a843-58ee9e4e4f60@i3g2000hsf.googlegroups.com> On Jan 8, 5:27?am, Gnarlodious wrote: > I am trying to install mod_python on OSX 10.5, Intel version. > > sudo apachectl configtest tells me this: > > httpd: Syntax error on line 114 of /private/etc/apache2/httpd.conf: > Cannot load /usr/libexec/apache2/mod_python.so into server: > dlopen(/usr/libexec/apache2/mod_python.so, 10): no suitable image > found. Did find:\n\t/usr/libexec/apache2/mod_python.so: mach-o, but > wrong architecture > > I attempted to follow instructions found on these pages but it didn't work: > > > > > > Can > > anyone tell me what is causing this error? (Sorry no time to read the references you provide) This is because httpd is running in 64 bits (arch x86_64) but mod_python.so is only 32 bits by default. You need to modify this. what I did was: make the following changes to src/Makefile: * Add -arch x86_64 to the LDFLAGS line * Change the build line in mod_python.so to: $(APXS) $(INCLUDES) -c -Wc,"-arch x86_64" $(SRCS) $(LDFLAGS) $ (LIBS) Now that I look at this, I don' know if both are necessary... But it worked for me. There was a discussion to the mod_python mailing list in october 2007: http://www.modpython.org/pipermail/mod_python/2007-October/ -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 02:45:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 27 Jan 2008 07:45:29 -0000 Subject: Using a dict as if it were a module namespace Message-ID: <13podkpqqvef674@corp.supernews.com> I have a problem which I think could be solved by using a dict as a namespace, in a similar way that exec and eval do. When using the timeit module, it is very inconvenient to have to define functions as strings. A good alternative is to create the function as normal, and import it: def myfunc(x, y): return x+y timeit.Timer("myfunc(59, 60)", "from __main__ import myfunc").timeit() Not only is this an easy idiom to follow, but myfunc can live in another module: just replace __main__ with the module name. Now, I'm trying to build a suite of tests to use with timeit. I have a bunch of tests which I've created as dicts: test_suite= [dict(x=59, y=60), dict(x=-1, y=-2)] What I *think* I want to do is use the from ... import idiom to grab arguments from the dicts as if they were modules, but this doesn't work: expr = "myfunc(x, y)" for test in test_suite: setup = "from __main__ import myfunc; from test import x, y" t = timeit.Timer(expr, setup).timeit() Even if the Timer could see test, it is not a module and you can't import from it. Naturally. Alternatives that I have found: (1) Import the test and grab the values needed from it: setup = """from __main__ import myfunc, test x, y = test['x'], test['y']""" I don't like this one. It doesn't seem very elegant to me, and it gets unwieldy as the complexity increases. Every item I need from test has to be named twice, violating the principle Don't Repeat Yourself. If the tests change, the setup string has to be explicitly changed also. (2) Mess with the global namespace: globals().update(t) setup = "from __main__ import myfunc" I don't like this one. It looks hackish, and I worry about conflicts and side-effects. If it works (and I haven't tested it) it relies on an implementation detail of timeit.Timer.__init__, namely the line "exec code in globals(), ns". Worst of all, it pollutes or even mangles the global namespace of the calling code, not the code being tested. (3) Explicitly pass a namespace dict to the Timer class, possibly even getting rid of setup altogether: test['myfunc'] = myfunc t = timeit.Timer(expr, '', ns=test).timeit() This would be the most elegant solution, but at this time it is completely hypothetical. Timer does not have that functionality. (4) Dump the test data straight into the setup string: setup = "from __main__ import myfunc; x = %(x)s; y = %(y)s" % t Again, unwieldy and against DRY. The additional disadvantage is that there are many types of test data that can't be converted to and from strings like that. What do others think? Have I missed something? What other alternatives are there? -- Steven From pavlovevidence at gmail.com Mon Jan 14 19:38:56 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 14 Jan 2008 16:38:56 -0800 (PST) Subject: module naming conventions References: <7f39199a-3334-4bcc-a424-5102f042ed01@1g2000hsl.googlegroups.com> Message-ID: On Jan 14, 11:44 am, grackle wrote: > Obviously Java-style naming is a mistake in Python, since top-level > names have to be unique. Is there a standard naming convention to > facilitate mixing code from different sources, such as > mygroupname_modulename? Is there a best practices guide for module > naming? Not really. Try to pick a unique name for your project. <:\ Carl Banks From bronger at physik.rwth-aachen.de Wed Jan 2 02:15:34 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 02 Jan 2008 08:15:34 +0100 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au> <87bq85rp2d.fsf@physik.rwth-aachen.de> <87abnoc13h.fsf@benfinney.id.au> Message-ID: <87lk78hf55.fsf@physik.rwth-aachen.de> Hall?chen! Ben Finney writes: > Torsten Bronger writes: > >> [...] the width of a tab is nowhere defined. It really is a >> matter of the editor's settings. > > RFC 678 "Standard File Formats" > : > > Horizontal Tab > > [...] As far as I can see, this excerpt of a net standard has been neither normative nor influential on the behaviour of text editors. >> I, for example, dislike too wide indenting. I use four columns in >> Python and two in Delphi. However, there are Python projects >> using eight spaces for each indentation level. > > How many columns to indent source code is an orthogonal question > to how wide an ASCII TAB (U+0009) should be rendered. [...] I don't know what you want to say with this. Obviousy, it is impossible to indent four columns with 8-columns tabs. Anyway, my sentence was supposed just to lead to the following: >> If all Python code used tabs, everybody could use their own >> preferences, for both reading and writing code, and >> interoperability would be maintained nevertheless. > > Interoperability isn't the only criterion though. On the contrary, > source code is primarily for reading by programmers, and only > incidentally for reading by the compiler. Well, I, the programmer, want code snippets from different origins fit together as seemlessly as possible, and I want to use my editor settings for every piece of Python code that I load into it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From nagle at animats.com Sun Jan 20 22:32:52 2008 From: nagle at animats.com (John Nagle) Date: Sun, 20 Jan 2008 19:32:52 -0800 Subject: Is there a portable way to tell if data is available on a pipe? Message-ID: <47941112$0$36375$742ec2ed@news.sonic.net> I need some way to find out if a pipe has data available for a read without blocking if it does not. "select", unfortunately, doesn't work on pipes on Windows. I think there's something proposed for Python 3000, but that's not useful now. I'd like to avoid having a thread to manage each pipe, but if I have to, so be it. John Nagle From jzgoda at o2.usun.pl Tue Jan 15 06:43:39 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 15 Jan 2008 12:43:39 +0100 Subject: MySQL-python-1.2.2 install with no mysql In-Reply-To: References: <14836669.post@talk.nabble.com> Message-ID: washakie napisa?(a): > Okay, I've installed mysql then using yum... it installed the same version > running on another machine with identical python where all works well... but > now I get this error during build... thoughts?!?? mysql_config is there, and > the site.cfg file is pointing correctly to it... : You need to install -dev package too. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From steven at REMOVE.THIS.cybersource.com.au Wed Jan 16 21:35:39 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 17 Jan 2008 02:35:39 -0000 Subject: import from question References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> <478d04d4$0$26042$88260bb3@free.teranews.com> <87tzleb2st.fsf@benfinney.id.au> <478E658A.9070003@tobiah.org> <87prw1bftx.fsf@benfinney.id.au> <478e87f6$0$26054$88260bb3@free.teranews.com> Message-ID: On Wed, 16 Jan 2008 15:31:54 -0800, Tobiah wrote: >> Again, those aren't copies. There is only one instance of each value, >> referenced by multiple names. > > > Ok, I get it. I was locally importing a pointer to an integer Really? What language were you using? Python doesn't have pointers. Some *implementations* of Python (e.g. CPython) might have pointers *in the implementation*, but others (e.g. PyPy, Jython) don't. > which is > really the same object as the module name points to, but the assignment > changes that. The confusion for me centered around the fact that a local > name can be used to change values in mutables that are visible from > within the module. This however, does not include assignment to the > local name. If you haven't already done so, you should read: http://effbot.org/zone/python-objects.htm http://effbot.org/zone/call-by-object.htm and remember that imports are (more or less) equivalent to assignments. When you do this: >>> import module it is roughly equivalent to: >>> module = get_a_module_from_file_name('module') Alternatively: >>> from module import foo is roughly equivalent to: >>> temp = get_a_module_from_file_name('module') >>> foo = temp.foo >>> del temp (and the magic function "get_a_module_from_file_name" is actually called __import__ with double underscores.) -- Steven From python.list at tim.thechases.com Fri Jan 11 17:41:52 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 11 Jan 2008 16:41:52 -0600 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <4787F0B0.9060701@tim.thechases.com> >> I recently faced a similar issue doing something like this: >> >> data_out = [] >> for i in range(len(data_in)): >> data_out.append([]) > > Another way to write this is > data_out = [[]] * len(data_in) ...if you're willing to put up with this side-effect: >>> data_in = range(10) >>> data_out = [[]] * len(data_in) >>> data_out [[], [], [], [], [], [], [], [], [], []] >>> data_out[0].append('hello') >>> data_out [['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello']] For less flakey results: >>> data_out = [[] for _ in data_in] >>> data_out [[], [], [], [], [], [], [], [], [], []] >>> data_out[0].append('hello') >>> data_out [['hello'], [], [], [], [], [], [], [], [], []] -tkc From mwm-keyword-python.b4bdba at mired.org Thu Jan 10 14:50:24 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 14:50:24 -0500 Subject: for loop without variable In-Reply-To: <87fxx6p1nr.fsf@mulj.homelinux.net> References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <20080110145024.32b06514@bhuda.mired.org> On Thu, 10 Jan 2008 08:42:16 +0100 Hrvoje Niksic wrote: > Mike Meyer writes: > > It sounds to me like your counter variable actually has meaning, > It depends how the code is written. In the example such as: > > for meaningless_variable in xrange(number_of_attempts): > ... > > the loop variable really has no meaning. Rewriting this code only to > appease pylint is exactly that, it has nothing with making the code > more readable. Except in this case, the variable *has* a meaning. You've just chosen to obfuscate it. > > you've hidden that meaning by giving it the meaningless name "i". If > > you give it a meaningful name, then there's an obvious way to do it > > (which you listed yourself): > > > > while retries_left: > [...] > > This loop contains more code and hence more opportunities for > introducing bugs. For example, if you use "continue" anywhere in the > loop, you will do one retry too much. All correct - and I'm a big fan of minimizing code, as code you don't write has no bugs in it. But you can still show the meaning of this "meaningless" variable: for number_of_attempts in xrange(maximum_attempts): Of course, the OP's request is a better solution: since he doesn't actually need the variable, removing it completely means there's one less variable, which is one less thing you can set to the wrong value. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From donn.ingle at gmail.com Sun Jan 13 08:50:49 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 15:50:49 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A0F5D.3030906@v.loewis.de> References: <200801131427.54672.donn.ingle@gmail.com> <478A0F5D.3030906@v.loewis.de> Message-ID: <200801131550.50119.donn.ingle@gmail.com> > If you can all ls them, and if the file names come out right, then > they'll have the same encoding. Could it not be that the app doing the output (say konsole) could be displaying a filename as best as it can (doing the ignore/replace) trick and using whatever fonts it can reach) and this would disguise the situation? I don't think one can call any string a plain ascii string anymore. I have been looking for somewhere online that I can download files obviously in a non-ascii set (like japan someplace) but can't find anything easy. I want to see exactly how my system (Kubuntu 7.10) handles things. > I never heard before that font files use non-ASCII file names, They are files, named as any other file - those that are created by people get called whatever they want, under whatever locale they used. Still, I don't fully understand how this is all handled. > don't see the point in doing so - isn't there typically a font name > *inside* the font file as well, so that you'd rather use that for > display than the file name? Yes, but sometimes I can't reach that - segfaults and so forth. I also need to write the filename to a text file for logging. > Of course, *other* files (text files, images etc) will often use > non-ASCII file names. Same as font files - I am talking mainly about TTF files here. Mainly Arrr, pass the rum, matey fonts ;) (Which I don't use in designs, but have kept over the years.) > However, they won't normally have mixed > encodings - most user-created files on a single system should typically > have the same encoding (there are exceptions possible, of course). Well, if I am collecting fonts from all over the place then I get a mixed-bag. > > Meaning, I am led to assume, the LANG variable primarily? > Yes. Thanks. Good to know I'm on the right track. \d From sjmachin at lexicon.net Sat Jan 12 16:12:26 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 12 Jan 2008 13:12:26 -0800 (PST) Subject: Is unicode.lower() locale-independent? References: Message-ID: On Jan 12, 10:51 pm, Fredrik Lundh wrote: > Robert Kern wrote: > >> However it appears from your bug ticket that you have a much narrower > >> problem (case-shifting a small known list of English words like VOID) > >> and can work around it by writing your own locale-independent casing > >> functions. Do you still need to find out whether Python unicode > >> casings are locale-dependent? > > > I would still like to know. There are other places where .lower() is used in > > numpy, not to mention the rest of my code. > > "lower" uses the informative case mappings provided by the Unicode > character database; see > > http://www.unicode.org/Public/4.1.0/ucd/UCD.html of which the relevant part is """ Case Mappings There are a number of complications to case mappings that occur once the repertoire of characters is expanded beyond ASCII. For more information, see Chapter 3 in Unicode 4.0. For compatibility with existing parsers, UnicodeData.txt only contains case mappings for characters where they are one-to-one mappings; it also omits information about context-sensitive case mappings. Information about these special cases can be found in a separate data file, SpecialCasing.txt. """ It seems that Python doesn't use the SpecialCasing.txt file. Effects include: (a) one-to-many mappings don't happen e.g. LATIN SMALL LETTER SHARP S: u'\xdf'.upper() produces u'\xdf' instead of u'SS' (b) language-sensitive mappings (e.g. dotted/dotless I/i for Turkish (and Azeri)) don't happen (c) context-sensitive mappings don't happen e.g. lower case of GREEK CAPITAL LETTER SIGMA depends on whether it is the last letter in a word. > > afaik, changing the locale has no influence whatsoever on Python's > Unicode subsystem. > > From tim.arnold at sas.com Tue Jan 22 09:28:26 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Tue, 22 Jan 2008 09:28:26 -0500 Subject: docbook and xmlproc Message-ID: hi, I'm unable to get xmlproc to validate my docbook test file. This is new territory for me, so I'd appreciate any advice on what I'm doing wrong. Using python 2.4 on HPux10.20. The test file (testdb.xml) Test Chapter This is a test document. The python code: from xml.parsers.xmlproc import xmlproc from xml.parsers.xmlproc import xmlval print 'Validate without DTD' p0 = xmlproc.XMLProcessor() p0.set_application(xmlproc.Application()) p0.parse_resource('testdb.xml') print # print 'Validate with DTD' p1 = xmlval.XMLValidator() p1.set_application(xmlval.Application()) p1.parse_resource('testdb.xml') Of course it gets through the 'Validate without DTD' portion fine, but I get this error on the 'Validate with DTD' part: ----------------------- ERROR: Internal error: External PE references not allowed in declarations at /dept/app/doc/xml/DocBook/dbcentx.mod:308:10 TEXT: ' ]]> ]]> and these lines later on (307-9) : 307 The isoamsa.ent file is in the ent subdir relative to the dbcentx.mod file, so I'm at a loss. thanks, --Tim Arnold From martin at v.loewis.de Sun Jan 13 08:17:17 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jan 2008 14:17:17 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801131427.54672.donn.ingle@gmail.com> References: <200801131351.59005.donn.ingle@gmail.com> <4789FE1C.9000002@v.loewis.de> <200801131427.54672.donn.ingle@gmail.com> Message-ID: <478A0F5D.3030906@v.loewis.de> > I guess I'm confused by that. I can ls them, so they appear and thus have > characters displayed. I can open and cat them and thus the O/S can access > them, but I don't know whether their characters are strictly in ascii-limits > or drawn from a larger set like unicode. I mean, I have seen Japanese > characters in filenames on my system, and that can't be ascii. > > You see, I have a large collection of fonts going back over 10 years and they > came from usenet years ago and so have filenames mangled all to hell. If you can all ls them, and if the file names come out right, then they'll have the same encoding. > I can't always *type* some of their names and have to use copy/paste to, for > example, ls one of them. > > Again, it's working from ignorance (my own) : I assume filenames in different > countries will be in character sets that I have never (nor will I ever) see. I never heard before that font files use non-ASCII file names, and I don't see the point in doing so - isn't there typically a font name *inside* the font file as well, so that you'd rather use that for display than the file name? Of course, *other* files (text files, images etc) will often use non-ASCII file names. However, they won't normally have mixed encodings - most user-created files on a single system should typically have the same encoding (there are exceptions possible, of course). >> If the user has set up his machine correctly: yes. > Meaning, I am led to assume, the LANG variable primarily? Yes. Regards, Martin From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 02:42:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 27 Jan 2008 07:42:00 -0000 Subject: how to make format operator % work with unicode as expected References: <13po55nc0q0s06@corp.supernews.com> Message-ID: <13pode8n39n8ea8@corp.supernews.com> On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: > You didn't understand my question, but thanks any way. > > Yes, it is true that %s already support unicode, and I did not > contradict that. But it counts the number of bytes instead of > characters, and makes things like %-20s out of alignment. If you don't > understand my assertion, please don't argue back and I am only > interested in answers from those who are qualified. I understand your assertion. I think it is nonsense. >>> def test(): ... print "12345678901234567890 +" ... print "%-20s +" % "Plain ASCII" ... print u"%-20s +" % u"Les mis?rables-\320\321\322" ... >>> test() 12345678901234567890 + Plain ASCII + Les mis?rables-??? + -- Steven From martin at v.loewis.de Sat Jan 5 11:00:53 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 05 Jan 2008 17:00:53 +0100 Subject: Question on os.tempnam() vulnerability In-Reply-To: <13nv5m68qeknk1f@corp.supernews.com> References: <13nt81gftkfa32d@corp.supernews.com> <13nv5m68qeknk1f@corp.supernews.com> Message-ID: <477FA9B5.9050609@v.loewis.de> > I know. That's the point of my question: how do you do that > under Windows? When you create a new process, you have the option to inherit file handles to the new process. So the parent should open the file, and then inherit the handle to the new process. The new process will need to know what the file handle it should use. There are two basic options: a) pass the file handle number as a string on the command line b) make the handle either stdin or stdout of the new process, and have the new process ask for its stdin/stdout handle. IOW, it's the same approach as on Unix. Regards, Martin From alexandrov.dmitry at gmail.com Wed Jan 16 09:11:29 2008 From: alexandrov.dmitry at gmail.com (Dmitry) Date: Wed, 16 Jan 2008 06:11:29 -0800 (PST) Subject: list classes in package Message-ID: <5cff1706-3bb1-4a54-bccb-175ff384788c@q77g2000hsh.googlegroups.com> Hi All, I've trying to develop one Python application, and neet to solve one problem. I need to list all classes defined in one package (not module!). Could anybody please show me more convinient (correct) way to implement this? Thanks, Dmitry From lepto.python at gmail.com Fri Jan 4 05:38:27 2008 From: lepto.python at gmail.com (oyster) Date: Fri, 4 Jan 2008 18:38:27 +0800 Subject: Why python says "unexpected parameter 'mini.py'" for my code? Message-ID: <6a4f17690801040238s492a0299s60cf41c2e238081a@mail.gmail.com> The following is my pure-python wxwidgets test. It runs and give a frame, but soon python comes up to say "unexpected parameter 'mini.py'" and I have to close it. I cannot find the reason. Can somebody give me a hint to let it work well? Thanks http://pyguiviactypes.googlepages.com/mini.py From bazwal at googlemail.com Mon Jan 7 14:53:09 2008 From: bazwal at googlemail.com (Baz Walter) Date: Mon, 7 Jan 2008 19:53:09 +0000 (UTC) Subject: Does Python cache the startup module? References: Message-ID: Fredrik Lundh pythonware.com> writes: > > Baz Walter wrote: > > > It's hard to supply an example for this, since it is local to the machine I am > > using. The startup module would look something like this: > > would look, or does look? if it doesn't look like this, what else does > it contain? What I did was create a minimal version of the module which still exhibits the same behaviour (for me, that is). Basically, QWidget in the example below replaces my MainWindow class. > > #!/usr/local/bin/python > > > > if __name__ == '__main__': > > > > import sys > > from qt import QApplication, QWidget > > > > application = QApplication(sys.argv) > > mainwindow = QWidget() > > application.setMainWidget(mainwindow) > > mainwindow.show() > > sys.exit(application.exec_loop()) > > > > If I change the name 'mainwindow' to 'mainwidget', the widget it refers to does > > not get destroyed; when I change it back again, it does get destroyed. > > Otherwise, the program runs completely normally. > > I don't see any code in there that destroys the widget, and I also don't > see any code in there that creates more than one instance of the main > widget. Qt will try to destroy all widgets that are linked together in the object hierarchy. > what do you do to run the code, and how to you measure leakage? I run it with: python app.py -widgetcount The widgetcount switch is a Qt facility which counts how many widgets are created and how many destroyed. Before changing the name 'mainwindow' to 'mainwidget' it reports: Widgets left: 0 Max widgets: 2 Widgets left: 0 Max widgets: 149 (full program) Afterwards it reports: Widgets left: 1 Max widgets: 2 Widgets left: 146 Max widgets: 149 (full program) > is the name "mainwidget" used for some other purpose in your application? No From fredrik at pythonware.com Wed Jan 9 06:33:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 12:33:56 +0100 Subject: Learning Python via a little word frequency program In-Reply-To: <493158.64888.qm@web56406.mail.re3.yahoo.com> References: <493158.64888.qm@web56406.mail.re3.yahoo.com> Message-ID: Andrew Savige wrote: > Here's my first attempt: > > names = "freddy fred bill jock kevin andrew kevin kevin jock" > freq = {} > for name in names.split(): > freq[name] = 1 + freq.get(name, 0) > deco = zip([-x for x in freq.values()], freq.keys()) > deco.sort() > for v, k in deco: > print "%-10s: %d" % (k, -v) > > I'm interested to learn how more experienced Python folks would solve > this little problem. Though I've read about the DSU Python sorting idiom, > I'm not sure I've strictly applied it above ... and the -x hack above to > achieve a descending sort feels a bit odd to me, though I couldn't think > of a better way to do it. sort takes a reverse flag in recent versions, so you can do a reverse sort as: deco.sort(reverse=True) in older versions, just do: deco.sort() deco.reverse() # this is fast! also note that recent versions also provide a "sorted" function that returns the sorted list, and both "sort" and "sorted" now allow you to pass in a "key" function that's used to generate a sort key for each item. taking that into account, you can simply write: # sort items on descending count deco = sorted(freq.items(), key=lambda x: -x[1]) simplifying the print statement is left as an exercise. > I also have a few specific questions. Instead of: > > for name in names.split(): > freq[name] = 1 + freq.get(name, 0) > > I might try: > > for name in names.split(): > try: > freq[name] += 1 > except KeyError: > freq[name] = 1 > > Which is preferred? for simple scripts and small datasets, always the former. for performance-critical production code, it depends on how often you expect "name" to be present in the dictionary (setting up a try/except is cheap, but raising and catching one is relatively costly). > Ditto for: > > deco = zip([-x for x in freq.values()], freq.keys()) > > versus: > > deco = zip(map(operator.neg, freq.values()), freq.keys()) using zip/keys/values to emulate items is a bit questionable. if you need to restructure the contents of a dictionary, I usually prefer items (or iteritems, where suitable) and tuple indexing/unpacking in a list comprehension (or generator expression, where suitable). > Finally, I might replace: > > for v, k in deco: > print "%-10s: %d" % (k, -v) > > with: > > print "\n".join("%-10s: %d" % (k, -v) for v, k in deco) why? From apardon at forel.vub.ac.be Thu Jan 24 08:34:56 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Jan 2008 13:34:56 GMT Subject: When is min(a, b) != min(b, a)? References: Message-ID: On 2008-01-21, Steven D'Aprano wrote: > On Sun, 20 Jan 2008 21:15:02 -0600, Albert Hopkins wrote: > > According to the IEEE-754 standard the usual trichotomy of "x is less > than y, x is equal to y, or x is greater than y" has to be extended to > include "x and y are unordered". Comparisons with NaNs are unordered, and > so expressions like "x < nan" should signal an exception. That doesn't follow. The problem is not that x < nan returns False because that is correct since x isn't smaller than nan. The problem is cmp(x, nan) returning 1, because that indicates that x is greater than nan and that isn't true. -- Antoon Pardon From martin at marcher.name Tue Jan 22 17:58:15 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 22 Jan 2008 23:58:15 +0100 Subject: UDP Client/Server Message-ID: Hello, I created a really simple udp server and protocol but I only get every 2nd request (and thus answer just every second request). Maybe someone could shed some light, I'm lost in the dark(tm), sorry if this is a bit oververbose but to me everything that happens here is black magic, and I have no clue where the packages go. I can't think of a simpler protocol than to just receive a fixed max UDP packet size and answer immediately (read an "echo" server). thanks martin ### server >>> from socket import * >>> import SocketServer >>> from SocketServer import BaseRequestHandler, UDPServer >>> class FooReceiveServer(SocketServer.UDPServer): ... def __init__(self): ... SocketServer.UDPServer.__init__(self, ("localhost", 4321), FooRequestHandler) ... >>> class FooRequestHandler(BaseRequestHandler): ... def handle(self): ... data, addr_info = self.request[1].recvfrom(65534) ... print data ... print addr_info ... self.request[1].sendto("response", addr_info) ... >>> f = FooReceiveServer() >>> f.serve_forever() request 0 ('127.0.0.1', 32884) request 1 ('127.0.0.1', 32884) request 2 ('127.0.0.1', 32884) request 2 ('127.0.0.1', 32884) request 2 ('127.0.0.1', 32884) ### client >>> target = ('127.0.0.1', 4321) >>> from socket import * >>> s = socket(AF_INET, SOCK_DGRAM) >>> for i in range(10): ... s.sendto("request " + str(i), target) ... s.recv(65534) ... 9 Traceback (most recent call last): File "", line 3, in KeyboardInterrupt >>> s.sendto("request " + str(i), target) 9 >>> str(i) '0' >>> for i in range(10): ... s.sendto("request " + str(i), target) ... s.recv(65534) ... 9 'response' 9 'response' 9 Traceback (most recent call last): File "", line 3, in KeyboardInterrupt >>> #this was hanging, why? ... >>> s.sendto("request " + str(i), target) 9 >>> s.recv(65534) 'response' >>> s.sendto("request " + str(i), target) 9 >>> s.recv(65534) Traceback (most recent call last): File "", line 1, in KeyboardInterrupt >>> s.sendto("request " + str(i), target) 9 >>> s.sendto("request " + str(i), target) 9 >>> s.recv(65534) 'response' >>> s.recv(65534) Traceback (most recent call last): File "", line 1, in KeyboardInterrupt >>> s.sendto("request " + str(i), target) 9 >>> -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From justin.mailinglists at gmail.com Wed Jan 16 00:38:44 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Tue, 15 Jan 2008 21:38:44 -0800 (PST) Subject: Image to browser References: <8c014bd1-7040-4ba3-9206-e1567c4a391a@n20g2000hsh.googlegroups.com> Message-ID: <1d223aa2-1297-4b01-854a-2a502f5f0ed1@l1g2000hsa.googlegroups.com> On Jan 16, 1:19 pm, danielatdavesch... at gmail.com wrote: > On Jan 16, 12:16 am, danielatdavesch... at gmail.com wrote: > > > Im using mod_python and apache2 using psp for output of page, i open a > > file and resize it with the following code > > > <% > > import Image, util > > > fields = util.FieldStorage(req) > > filename = fields.getlist('src')[0] > > > path = '/var/www/content/' + filename > > size = 128, 128 > > > im = Image.open(path) > > print im.resize(size, Image.ANTIALIAS) > > %> > > > so for one, I dont think print does much with psp as far as i can > > tell, i cant even do a print 'hello world', it has to be a > > req.write('hello world'), but i cant req.write the im.resize. The > > manual for im.resize states that its return can go ahead and be > > streamed via http but I get a blank page when im expecting to see > > image characters dumped to my screen. Python doesn't throw up any > > errors. Im not sure where else to look or what to do. > > > Thanks for any help, > > Daniel > > its worth noting that ive tried using > print "Content-Type: image/jpeg\n" > before the print im.resize and still no luck If you're using the Image module from PIL then im.resize(...) returns an Image instance. I have not used mod_python and psp, but try the following: >>> import Image >>> i = Image.open('server.JPG') >>> r = i.resize((32,32)) >>> from StringIO import StringIO >>> b = StringIO() >>> r.save(b, 'JPEG') >>> b.seek(0) >>> req.write("Content-Type: image/jpeg\r\n\r\n") >>> req.write(b.read()) There's a r.tostring(...) method but I don't see how to make that return a JPEG stream. From fredrik at pythonware.com Wed Jan 9 03:24:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 09:24:34 +0100 Subject: how to open a file in some application using Tkinter i am using TKINTER to create GUI application i want to know how to open a word document in open office or any other applicatio In-Reply-To: References: Message-ID: brindly sujith wrote: > i am using TKINTER to create GUI application > > i want to know how to open a word document in open office or any other > application > > please send me the tkinter coding for this reposting the reply you received when you posted this on another mailing list: --- on windows, you can use the "os.startfile" function: import os os.startfile("mydocument.doc") (this is the same as double-clicking on a document in the file explorer) on other platforms, use os.system() and specify what application to run: import os os.system("someapp mydocument.doc") --- From Graham.Dumpleton at gmail.com Tue Jan 8 18:08:09 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 8 Jan 2008 15:08:09 -0800 (PST) Subject: Python setup not working on Windows XP References: <661089ec-1725-43d1-b8b3-f5c07eb115ac@k39g2000hsf.googlegroups.com> Message-ID: <8e15b643-5ce8-44a6-8ba1-caf8b3494336@i29g2000prf.googlegroups.com> On Jan 8, 5:31?pm, Tim Roberts wrote: > Gowri wrote: > > >I am new to Python and am trying to setup Apache to serve Python using > >mod_python. I'm using a Windows XP box. here is a list of steps i > >followed for the installation: > > >1. Installed Apache 2.2.6 > >2. Installed Python 2.5.1 > >3. Installedmod_python3.3.1 > > >I then included the line > >LoadModule python_module modules/mod_python.so in httpd.conf > > >I had this one line python file (print "Hello") in htdocs of Apache. > > Did you put it in a file called "hello.py"? ?Did you create an AddHandler > for .py files? ?Did you create a PythonHandler referring to hello.py? And did you (OP) read the mod_python documentation enough to know that 'print "Hello" is in no way going to work with mod_python. You cannot just throw an arbitrary bit of Python code in a file using 'print' statements and it will somehow magically work. You need to write your code to the mod_python APIs. Graham From steve551979 at hotmail.com Wed Jan 23 21:13:25 2008 From: steve551979 at hotmail.com (steve551979 at hotmail.com) Date: Wed, 23 Jan 2008 18:13:25 -0800 (PST) Subject: os.system behavior when calling SQLPlus with spooling Message-ID: I'm trying to execute SQLPlus in python (on Redhat linux). when calling sqlplus, i'm referencing an sql file which spools results to a file, for e.g.: spool "/tmp/qctemp2.out"; SELECT %s FROM bug WHERE BG_BUG_ID = %s; spool off; exit; I'm noticing that when using: os.system("sqlplus -S -L %s @/tmp/qctemp3.sql" % qc_login) I'm able to execute fine, however, when I use: f = popen4(("sqlplus -S -L %s @/tmp/qctemp3.sql" % qc_login) print f.read() I get problems where occasionally, sqlplus is run, but has problems spooling results to a file, and python hangs on the print f.read() statement. I would prefer not to use os.system() since I want to analyze the results. Can anyone suggest how I should go about executing sqlplus in this case? Thanks for your help, Steve (note: please do not reply to my email address, only reply to this group) From fredrik at pythonware.com Wed Jan 2 09:56:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 02 Jan 2008 15:56:46 +0100 Subject: ElementTree should parse string and file in the same way In-Reply-To: <13njba091eipl6f@corp.supernews.com> References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > Fredrik, if you're reading this, I'm curious what your reason is. I don't > have an opinion on whether you should or shouldn't treat files and > strings the same way. Over to you... as Diez shows, it's all about use cases. and as anyone who's used my libraries or read my code knows, I'm a big fan of minimalistic but highly composable object API:s and liberal use of short helper functions to wire them up to fit the task at hand. kitchen sink API design is a really bad idea, for more reasons than I can fit in this small editor window. From kyosohma at gmail.com Fri Jan 25 08:54:22 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 25 Jan 2008 05:54:22 -0800 (PST) Subject: Python ADO Date Time database fields References: <30222931-7fa9-4dd5-bdc8-d1313c37a144@i3g2000hsf.googlegroups.com> Message-ID: On Jan 25, 7:48 am, goldtech wrote: > snip > > > > > try this: > > > val = oRS.Fields(dt).Value > > print type(val) > > this gives: > > > print float(val) > > yes, it gives 0.0 > > But there should be a way to print what is *actually in the field*. > When I open the DB table in Access I see: 12:00:00 AM. > > That's what I want - the value, and the form of the value, exactly as > seen in the field... > > As an aside, the roughly eqivalent code in Perl will print the > "12:00:00 AM" - (the trick for the date types in Perl is to add: "use > Win32::OLE::Variant;" > > There has to be a way:^) > > snip You could try posting to the PyWin32 group too. They would probably know. http://mail.python.org/mailman/listinfo/python-win32 Mike From bearophileHUGS at lycos.com Wed Jan 9 21:46:49 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 9 Jan 2008 18:46:49 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <41548a0d-eb74-4cd5-94b7-0ca11e691204@f3g2000hsg.googlegroups.com> <1199925201.586849@www.vif.com> Message-ID: <61d06e1a-c0c6-459d-92de-14968381be0f@v29g2000hsf.googlegroups.com> Gordon C: > This is very cool stuff but I suspect that the code is unreadable > to many readers, including me. Just for fun here is a complete program, > written in Turbo Pascal, circa 1982, that does the job. Readable > n'est pas? I think it's quite readable, especially if you indent it more correctly. Pascal is usually among the most readable languages, for not-too-much complex tasks. I don't mind its mutable strings too much. Bye, bearophile From bignose+hates-spam at benfinney.id.au Wed Jan 16 03:19:30 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jan 2008 19:19:30 +1100 Subject: import from question References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> <478d04d4$0$26042$88260bb3@free.teranews.com> Message-ID: <87tzleb2st.fsf@benfinney.id.au> Tobiah writes: > This is a little surprising. So "from mod import *" really copies > all of the scalars into new variables in the local namespace. No. Nothing is copied. All the objects (remembering that in Python, *everything* is an object) created by the code in module 'mod' are given names in the current namespace. > I always ASSumed that the two forms of import were equivalent, but > that one form did away with the need to be explicit about the > namespace: mod.thing Obviously this is far from the case. Yes. In fact the main difference is in what namespace the module's objects are made available. -- \ "The way to build large Python applications is to componentize | `\ and loosely-couple the hell out of everything." -- Aahz | _o__) | Ben Finney From ryan at ryankaskel.com Wed Jan 23 14:12:44 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 11:12:44 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> Message-ID: On Jan 23, 2:04 pm, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jan 2008 10:50:02 -0800, ryan k wrote: > > Hello. I have a string like 'LNAME > > PASTA ZONE'. I want to create a list of those words and > > basically replace all the whitespace between them with one space so i > > could just do lala.split(). Thank you! > > You *can* just do ``lala.split()``: Indeed you can thanks! > > In [97]: lala = 'LNAME PASTA ZONE' > > In [98]: lala.split() > Out[98]: ['LNAME', 'PASTA', 'ZONE'] > > Ciao, > Marc 'BlackJack' Rintsch From bigblueswope at gmail.com Tue Jan 8 21:03:08 2008 From: bigblueswope at gmail.com (BJ Swope) Date: Tue, 8 Jan 2008 21:03:08 -0500 Subject: Open a List of Files In-Reply-To: <874pdomrrd.fsf@mulj.homelinux.net> References: <874pdomrrd.fsf@mulj.homelinux.net> Message-ID: On Jan 8, 2008 7:22 AM, Hrvoje Niksic wrote: > Fredrik Lundh writes: > > > BJ Swope wrote: > > > >> the code looks ok. please define "not working". > >> > >> Yep, defining "not working" is always helpful! :) > >> > >> I want to have all 3 files open at the same time. I will write to > >> each of the files later in my script but just the last file is open > >> for writing. > > > > to keep more than one file open, you need more than one variable, or a > > variable that can hold more than one object. > > > > if the number of files may vary, put the file objects in a list. > > Or in a dict: > > open_files = {} > for fn in ['messages', 'recipients', 'viruses']: > open_files[fn] = open(getfilename(fn), 'w') > > # open_files['messages'] is the open file 'messages' etc. > -- > http://mail.python.org/mailman/listinfo/python-list > I decided that I was just trying to be "too smooth by 1/2" so I fell back to ... messages = open(os.path.join(host_path,'messages.txt'), 'wb') deliveries = open(os.path.join(host_path,'deliveries.txt'), 'wb') actions = open(os.path.join(host_path,'actions.txt'), 'wb') parts = open(os.path.join(host_path,'parts.txt'), 'wb') recipients = open(os.path.join(host_path,'recipients.txt'), 'wb') viruses = open(os.path.join(host_path,'viruses.txt'), 'wb') esp_scores = open(os.path.join(host_path,'esp_scores.txt'), 'wb') Thank you to everybody who answered. -------------- next part -------------- An HTML attachment was scrubbed... URL: From killerkiwi2005 at gmail.com Sun Jan 27 15:24:15 2008 From: killerkiwi2005 at gmail.com (Jason Taylor) Date: Mon, 28 Jan 2008 09:24:15 +1300 Subject: Klik2 Project, Python apps on linux In-Reply-To: <94dd8f6f0801262249v1c07cf3em2548c470a523291e@mail.gmail.com> References: <94dd8f6f0801262249v1c07cf3em2548c470a523291e@mail.gmail.com> Message-ID: <94dd8f6f0801271224h76485e91n56df5c32a6fcc287@mail.gmail.com> Perhaps this would help, heres a list of our error reports http://klik.atekon.de/feedback/details.php?e=ImportError On 27/01/2008, Jason Taylor wrote: > > Hi > > We've been working on klik2, http://code.google.com/p/klikclient/, which > implements OSX like application files on linux (with applications working on > all distros), In which every user desktop application is 1 file > > We've run into a bit of a problem with python apps, so while we can run a > complicated application like openoffice.org on ubuntu, fedora and suse > from a single file we cant run any python applications such as > > jokosher > gnome-specimen > angrydd > gausssum > pathological > quodlibet > webboard > istanbul > exaile > ccsm > bittornado > pessulus > labyrinth > wammu > accerciser > > > We'd like to fix this in a clean way with out resorting to nasty hacks > involving $PYTHON_PATH. > > If any one has any suggestions please email me or drop by #klik on > freenode > > Issue http://code.google.com/p/klikclient/issues/detail?id=144 > > Cheers > > Jason Taylor > > -- > "Why isn't my life like a situation comedy? Why don't I have a bunch of > friends with nothing better to do but drop by and instigate wacky > adventures? Why aren't my conversations peppered with spontaneous > witticisms? Why don't my friends demonstrate heartfelt concern for my well > being when I have problems? ...I gotta get my life some writers." - Calven -- "Why isn't my life like a situation comedy? Why don't I have a bunch of friends with nothing better to do but drop by and instigate wacky adventures? Why aren't my conversations peppered with spontaneous witticisms? Why don't my friends demonstrate heartfelt concern for my well being when I have problems? ...I gotta get my life some writers." - Calven -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Fri Jan 4 10:40:03 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 04 Jan 2008 15:40:03 -0000 Subject: choosing random dynamic port number References: <32e43bb70801031409o5d1dcd2at5a159339cd43ae52@mail.gmail.com> <3e6cca84-f8cf-4947-931c-18d6af748f13@l6g2000prm.googlegroups.com> Message-ID: <13nskqjrrgb9qd1@corp.supernews.com> On 2008-01-04, Giampaolo Rodola' wrote: >> ? ? def GenerateDynamicPortNumber(): >> ? ? ? ? return 0 >> >> (to get the actual number, use getsockname() on the socket after you've >> called "bind" on it) >> >> > > By using 0 as port number value you let kernel choose a free > unprivileged random port: The port number chosen isn't random on many OSes. If the OP really wants a random port number, he'll have to generate it himself. -- Grant Edwards grante Yow! Look! A ladder! at Maybe it leads to heaven, visi.com or a sandwich! From rrr at ronadam.com Sun Jan 13 23:02:39 2008 From: rrr at ronadam.com (Ron Adam) Date: Sun, 13 Jan 2008 22:02:39 -0600 Subject: time.time or time.clock In-Reply-To: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> References: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> Message-ID: <478ADEDF.2070306@ronadam.com> John Machin wrote: > On Jan 14, 7:05 am, Ron Adam wrote: >> I'm having some cross platform issues with timing loops. It seems >> time.time is better for some computers/platforms and time.clock others, but > > Care to explain why it seems so? > >> it's not always clear which, so I came up with the following to try to >> determine which. >> >> import time >> >> # Determine if time.time is better than time.clock >> # The one with better resolution should be lower. >> if time.clock() - time.clock() < time.time() - time.time(): >> clock = time.clock >> else: >> clock = time.time >> >> Will this work most of the time, or is there something better? >> > > Manual: > """ > clock( ) > > On Unix, return the current processor time as a floating point number > expressed in seconds. The precision, and in fact the very definition > of the meaning of ``processor time'', depends on that of the C > function of the same name, but in any case, this is the function to > use for benchmarking Python or timing algorithms. > > On Windows, this function returns wall-clock seconds elapsed since the > first call to this function, as a floating point number, based on the > Win32 function QueryPerformanceCounter(). The resolution is typically > better than one microsecond. > [snip] > > time( ) > > Return the time as a floating point number expressed in seconds since > the epoch, in UTC. Note that even though the time is always returned > as a floating point number, not all systems provide time with a better > precision than 1 second. While this function normally returns non- > decreasing values, it can return a lower value than a previous call if > the system clock has been set back between the two calls. > """ > > AFAICT that was enough indication for most people to use time.clock on > all platforms ... before the introduction of the timeit module; have > you considered it? I use it to time a Visual Python loop which controls frame rate updates and set volocities according to time between frames, rather than frame count. The time between frames depends both on the desired frame rate, and the background load on the computer, so it isn't constant. time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't high enough resolution on windows. I do use timeit for bench marking, but haven't tried using in a situation like this. > It looks like your method is right sometimes by accident. func() - > func() will give a negative answer with a high resolution timer and a > meaningless answer with a low resolution timer, where "high" and "low" > are relative to the time taken for the function call, so you will pick > the high resolution one most of the time because the meaningless > answer is ZERO (no tick, no change). Some small fraction of the time > the low resolution timer will have a tick between the two calls and > you will get the wrong answer (-big < -small). If the difference is between two high resolution timers then it will be good enough. I think the time between two consectutive func() calls is probably low enough to rule out low resolution timers. In the case of two > "low" resolution timers, both will give a meaningless answer and you > will choose arbitrarily. In the case of two low resolution timers, it will use time.time. In this case I probably need to raise an exception. My program won't work correctly with a low resolution timer. Thanks for the feed back, I will try to find something more dependable. Ron From jipksaman at gmail.com Thu Jan 24 04:12:17 2008 From: jipksaman at gmail.com (abdo911) Date: Thu, 24 Jan 2008 01:12:17 -0800 (PST) Subject: The Way to Paradise Message-ID: <673d9870-35d5-440f-a728-9dade02e6071@t1g2000pra.googlegroups.com> We are all in quest of true happiness. In this world, the idea of true/perfect happiness is not feasible because this world is inevitably doomed to total annihilation. True happiness is found only in dwelling upon Paradise, and enjoying its blessings. However, none would enter Paradise except the purified (those who are void of sins, void of an atom of grudge or malignance). Since Paradise is created only for the purified/pious, those who have evil looks (looking lustfully at strange women, and vice versa), who envy others, treat their fellowmen badly, hate mankind, or backbite cannot enter Paradise. To conclude, none can enter Paradise unless totally purified (sin-free). Those who indulge in illegal talk (backbiting, using indecent language, etc.), or have sinful hearts are denied entry to Paradise. Allah (The sublime) said: "And those who kept their duty to Lord (AL- Muttaquin) will be driven/led to Paradise in groups, and when they reach there, its gates will be opened (before their arrival for their reception) and its keepers will say: Salamun Alaikum (peace be upon you)! How blessed you are (being sin-free and having done well), enter here (Paradise) to abide therein eternally." Surat Az-Zumar/The Groups: 73. In another Surah, Allah says: "Those whose lives the angels take while they are in a pious state (pure from all evil, and worshipping none but only Allah) will be addressed as such: Salamun Alaikum (peace be upon you) enter Paradise due to that which you used to do (during your mortal life/in the world). Surat An-Nahl/The Bees: 32. The above-mentioned verses set the condition that, in order to enter Paradise, we have to be sin-free and void of an atom of guilt! One may argue that since we are all sinners, it seems that none can enter Paradise! Well, it is true that only the pious can enter Paradise, but, Allah (The Glorified), with His vast mercy, established eleven means to help us be purified: 4 in this world, 3 in the grave, and another 4 on the Day of Resurrection. These eleven means of purification aim at enabling us to cross/walk on the straight path rather than to slip and fall. This path is stretched over Hell fire and it is finer than a hair and sharper than the edge of a razor/sword! Knowing the nature of the straight path, one may question how people would tread on that path! Well, some will cross/walk on it as fast as the blink of an eye, others will be as fast as the light, others will be as fast as the wind, others will crawl, and others will cling to the path, then the angels will lead and/or encourage them onwards (lest they should fall into Hell fire), while others will be snatched by the hooks (attached to the path) to ensure/hasten their fall into Fire. 4 Means/Standpoints of Purification in this World 1. Repentance: Repentance is not limited to asking for forgiveness or invoking Allah's mercy, rather, it is one of the greatest religious rituals to win Allah's love/satisfaction and a means to get closer to Him. Allah (The Sublime) says: "Allah loves those who turn unto Him in repentance and loves those who purify themselves (by taking a bath and cleaning and washing thoroughly their private parts/bodies (in preparation for their prayers)". Surat AL-Baqarah/The Cow: 222. Repentance removes sins, as Allah (The Sublime) says: "And verily, I'm indeed forgiving to him who repents, believes in My Oneness, and associates none in worshipping with Me, did righteous good deeds, and then remained faithful to such belief and good deeds". Surat Ta-Ha: 82. Repentance changes evil deeds into good ones. Allah (The Glorified and The Exalted) said: "Except those who repented, believed in monotheism, and did righteous deeds; for those, Allah will change their sins into good deeds, and Allah is Oft-Forgiving, Most Merciful ". Surat AL-Furqan/The Criterion: 70. 2. Asking for Forgiveness: We (Moslems) should always ask Allah to forgive our sins (whether remembered or not). Allah's Messenger (PBUH), though being the most pious, endowed with the most knowledge of his Lord, and having had both his past and future guilt pardoned/forgiven (by Allah), he used to ask for Allah's forgiveness as many as a hundred times a day (an action that won't take more than a minute of your time). In this respect, the prophet (PBUH) says: "I swear by Allah, I do ask for Allah's forgiveness more than 70 times a day". This Hadith is quoted by AL- Bokhari. Also, Bin Omar (the son of Omar)-may Allah be content with them all- said: we used to count for the messenger of Allah (in one session and before leaving his place) as many as 100 times saying: "O Lord! Forgive me my sins and accept my repentance, you are the One Who accepts repentance, the Most Merciful". This Hadith is quoted by Abu Dawoud and AL-Turmuzi. 3. Good Deeds Remove Bad deeds: Change bad deeds with good ones because Abu Dhar Ibn Jundub and Abu abdulrahman Bin Muaz Bin Jabal (may Allah be content with them all) narrated that the Messenger of Allah said: "Fear Allah wherever you are and be keen to always change your bad deeds with good ones, and be nice to people." This Hadith is quoted by AL-Turmuzi. Allah also said: "And perform As-Salaah (the daily five prayers) at the two ends of the day and in some hours in the night. Verily, the good deeds remove the bad ones. That is a reminder to those who always remember Allah (in prayers, while standing, sitting, or lying down on their sides)". Surat Hud: 114. We must endeavor to do good deeds (no matter how simple they are). For example, we can replace "Hi" and/or "Bye" (even these two simple words are considered as "Good Deeds") with As-Salamu Alaikum and utilize our leisure time by always remembering Allah at all times (standing, sitting, eating, sleeping, working, driving, etc.). The Messenger of Allah (PBUH) had always the desire to do a lot of good deeds (on a daily basis). For example, he refused to accept a present (a camel as a means of transportation) from his best companion (Abu Bark) for free, and insisted that he share its cost, thus hoping to be worthy of winning the reward of AL-Hijra (immigration to Medina). We, likewise, need to do good deeds (not in quantity but in quality). Good deeds are best manifested in being wholly dedicated to your parents (especially in their old age) praying in the late hours of the night, praying in the early hours of dawn time, wearing the veil, and performing work perfectly. 4. Purifying Calamities: Allah puts His servants under severe tests (in this world) to have them purified from their sins and to enter Paradise sin-free. However, some people (not realizing the wisdom of such plights/tests) lament their destiny by saying; "O Lord, why have You ordained us (especially us) with such calamities?" Those who did not repent, did not ask for forgiveness, did not do good deeds, and/or were not put to tests (i.e., not purified) in this world still have another chance for purification and that will take place in their graves! Thus, missing purification in this world (while being alive) will be completed in one's grave (while lying dead)! And that shows how great this religion is, as you won't be left but sin-free (either in this world or while lying dead in your grave). To conclude, due to Allah's vast mercy and the simple demands for entering Paradise, we can say that none (of the Moslems) will enter Fire, (i.e., or more accurately, they will not abide there eternally). 3 Means/Standpoints of Purification in the Grave 5. The Funeral Prayer In this prayer, it is not the number of those standing behind the deceased (in a mosque) performing due funeral prayer that counts, instead it is the quality of the true believers who are present in this kind of prayer. The sincere supplications that come from such believers (in such congregations) will benefit the deceased. Though being dead, sincere supplication will greatly help the deceased to be purified for Paradise. 6. The Trial of the Grave Trial of the grave is best manifested in the questions asked by two angels (immediately after lying the dead in his grave): Who is your Lord? What is your religion? And what do you think about the man who was sent amongst you? (Referring to Allah's Messenger, PBUH). Other examples are: your fear facing these two angels, being alone in the grave (nobody there to support you), the darkness of the grave and, finally, your fear as you are enclosed therein. These trials are other means to remove all of our sins. Those who have already been purified (while alive in the world) will not be subject to other trials (while lying dead in their graves.) The prophet (PBUH) says: "A grave is either an orchard for Paradise or a pitfall for Hell". To conclude, a grave is not (as it is thought to be) a hideous dark place for beasts; on the contrary, it could be an orchard for Paradise! 7. Contribution of the Living to the Dead: When a Moslem dies, he can still have his sins removed by the good and sincere deeds dedicated to him by the living (especially from his relatives). The Ulamah (the religiously lectured of the nation) unanimously agree that all good deeds done by the living such as performing pilgrimage, Umrah (the visit to Al-Ka'ba in Makka), and sincere supplications do reach the dead only to purify them and then be sin-free. In this respect, Abu Hurairah (one of the prophet's, PBUH, companions) said: The Messenger of Allah (PBUH) said: "When the son of Adam dies, nothing will benefit him except one of the following three good righteous deeds: a non-stop Sadakah (charity), some kind of knowledge he left behind (useful to society), or a sincere supplication of his son." This Hadith is quoted by Moslim. Therefore, if someone (who is really dear to you) is dead, you can perform pilgrimage, do Umrah, or pay Sadakah on their behalf (so that they become sin-free). Remember that the more useful the Sadakah to society is, the more the reward is, (needless to say that you will have your share as well). To realize how merciful/great this religion is, it is important to know that somebody (while lying dead in his grave) can be freed from suffering/torment by the supplications of others who wish the deceased to be purified and sin-free for entry into Paradise. 4 Means/Standpoints of Purification on the Day of Resurrection 8. Horrors on the Day of Resurrection: Seeing the sun folded-up, the stars fall (after loosing their light), the seas blown-up, and the earth shaken with its (final) earthquake are all sin removers. 9. Standing Before Allah (The Glorified, The AL-Mighty): Another means to purify us from our sins is standing humbly before Allah in an attempt to answer/face His following questions/ blame: My servant, didn't I bestow you with My blessings? Didn't I give you wealth? Weren't I the Watchful when you had illegal looks (Men looking lustfully at women, and vice versa, or at whatever you shouldn't)? Weren't I the Watchful when you used indecent language (thus misusing communication with others? Allah then keeps addressing His servant as saying: My servant, you have underestimated the day when you stand before Me! Were you fearless of the notion that the time will come when you stand before Me! You have put on beautiful masks (before all people) only to come before Me with the worst in you! My servant, what made you fall into deception (ignoring that I Am the Watchful)? 10.Allah's Amnesty: This is the greatest means in purifying us from our sins. Just as the prophets have already interceded, as did His Messengers and as did the believers, Allah (The Glorified, the Sublime) says: Wouldn't I? Even knowing that we can all enter Paradise, there are still those who will fall off the path (for they deserve it). Others will not be purified even after passing through the above-mentioned eleven means of purification! They will fall into Fire, as they are sinful as well as guilty of committing foul/bad deeds, full of hatred and ever holding on to grudges. And the only way to purify such sinners is to let Fire do its job (similar to a piece of gold, which doesn't get its purity unless it is put into fire for the period required to make all other alloys vanish! In fact, the more it stays there, the greater its purity gets! Likewise, whoever eventually falls into Fire will stay there long enough to become purified (depending on how sinful he is). Immediately after being completely purified (after dwelling in Hell for some time), the angels will greet him saying: "Peace be upon you, dwell here (in Paradise) forever." In conclusion, in this world we own three of the means of the above- mentioned eleven purification standpoints: repentance, asking for forgiveness, and performing good deeds to remove the bad ones. Therefore, let's make as much use of them as we can (while we are still alive/before it is too late). Remember that if you are a true believer (paying duty to Allah, believing in monotheism and associating none with Allah in worshipping), you will not suffer the trials in your grave and/or the horrors of the Day of Resurrection. (May Allah Bless You All) From romo20350 at gmail.com Mon Jan 21 16:21:57 2008 From: romo20350 at gmail.com (romo20350 at gmail.com) Date: Mon, 21 Jan 2008 13:21:57 -0800 (PST) Subject: Help with cPAMIE References: Message-ID: <65036852-3cb2-4efe-bb96-8eb357af1689@d21g2000prf.googlegroups.com> On Jan 21, 11:09?am, romo20... at gmail.com wrote: > Hi, I'm in need of help with cPAMIE. I'm currently trying to submit > this form on a webpage: > > >
> Submit Coupon >
>
>
> > >
> > > I can fill in the textboxes alright but I'm having trouble submitting > it. I've tried using: > ie.buttonClick('action') but It returns some thing about it being > hidden... > Ive also tried: > ie.buttonClick('Submit Coupon') but it says it can't find the string > anywhere... > Any help would be greatly appreciated! Thank you so much! Okay I kinda figured it out...I'm now trying to use formSubmit but it seems that the form has no name its just blank. So i tried ie.formSubmit("") but it didn't work. I'm a beginner so I really need some help :) Thanks! From hniksic at xemacs.org Thu Jan 10 02:42:16 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 10 Jan 2008 08:42:16 +0100 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> Message-ID: <87fxx6p1nr.fsf@mulj.homelinux.net> Mike Meyer writes: > It sounds to me like your counter variable actually has meaning, It depends how the code is written. In the example such as: for meaningless_variable in xrange(number_of_attempts): ... the loop variable really has no meaning. Rewriting this code only to appease pylint is exactly that, it has nothing with making the code more readable. > you've hidden that meaning by giving it the meaningless name "i". If > you give it a meaningful name, then there's an obvious way to do it > (which you listed yourself): > > while retries_left: [...] This loop contains more code and hence more opportunities for introducing bugs. For example, if you use "continue" anywhere in the loop, you will do one retry too much. From lizm at rcsltd.co.uk Thu Jan 24 09:17:37 2008 From: lizm at rcsltd.co.uk (LizzyLiz) Date: Thu, 24 Jan 2008 06:17:37 -0800 (PST) Subject: Which reportlab version for python 2.1.3? Message-ID: Hiya Probably me being thick but I can't find which version of reportlab I should use for python 2.1.3. Many thanks Liz From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Jan 6 18:33:36 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 07 Jan 2008 00:33:36 +0100 Subject: Delete lines containing a specific word References: Message-ID: <5ud6qgF1hlfdaU1@mid.individual.net> Steven D'Aprano wrote: > grep doesn't delete lines. grep matches lines. If you want to > delete them, you still have to do the rest of the job yourself. In which way does "grep -v mypattern myfile > myfile" not delete the lines matching mypattern? Regards, Bj?rn -- BOFH excuse #184: loop found in loop in redundant loopback From http Thu Jan 10 22:05:10 2008 From: http (Paul Rubin) Date: 10 Jan 2008 19:05:10 -0800 Subject: Fate of itertools.dropwhile() and itertools.takewhile() References: <7a86a421-089f-4634-8902-e9edfe139f03@e23g2000prf.googlegroups.com> <1a35dcbb-593c-45b8-a450-5245e75b1c9d@21g2000hsj.googlegroups.com> Message-ID: <7x3at5cba1.fsf@ruckus.brouhaha.com> Raymond Hettinger writes: > > I presume you did scans of > > large code bases and you did not find occurrences of > > takewhile and dropwhile, right? > > Yes. I think I have used them. I don't remember exactly how. Probably something that could have been done more generally with groupby. I remember a clpy thread about a takewhile gotcha, that it consumes an extra element: >>> from itertools import takewhile as tw >>> x = range(10) >>> z = iter(x) >>> list(tw(lambda i:i<5, z)) [0, 1, 2, 3, 4] >>> z.next() 6 I.e. I had wanted to use takewhile to split a list into the initial sublist satisfying some condition, and the rest of the list. This all by itself is something to at least warn about. I don't know if it's enough for deprecation. I've been cooking up a scheme for iterators with lookahead, that I want to get around to coding and posting. It's a harder thing to get right than it at first appears. From mwm-keyword-python.b4bdba at mired.org Thu Jan 10 22:59:07 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 22:59:07 -0500 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <20080110225907.19aa060d@bhuda.mired.org> On Thu, 10 Jan 2008 22:36:56 -0500 Marty wrote: > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) More succinctly: data_out = [] for _ in data_in: data_out.append([]) Or, as has already been pointed out: data_out = [[] for _ in data_in] > This caused me to wonder why Python does not have a "foreach" statement (and > also why has it not come up in this thread)? I realize the topic has probably > been beaten to death in earlier thread(s), but does anyone have the short answer? But I'm curious - what's the difference between the "foreach" you have in mind and the standard python "for"? http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From asmodai at in-nomine.org Wed Jan 9 12:42:27 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 9 Jan 2008 18:42:27 +0100 Subject: centre of mass of protein In-Reply-To: <22c5c6390801090913w6667560cv809a2e5fc8ad7e5b@mail.gmail.com> References: <22c5c6390801090913w6667560cv809a2e5fc8ad7e5b@mail.gmail.com> Message-ID: <20080109174227.GR75977@nexus.in-nomine.org> -On [20080109 18:15], smriti Sebastian (smriti.sebastuan at gmail.com) wrote: >Is there any script or module in python where we can find the centre of mass of >protein? Not sure, but perhaps http://biopython.org/ has something. And otherwise I am sure they would be more knowledgeable if something like that exists. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Only the wisest and the stupidest of men never change... From BjornSteinarFjeldPettersen at gmail.com Sun Jan 27 03:54:18 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 27 Jan 2008 00:54:18 -0800 (PST) Subject: file write question References: <62b96f11-1a81-4be8-9dcb-348ee38ebe16@f10g2000hsf.googlegroups.com> Message-ID: <5845751a-717e-4476-bdd5-4b7d09406fe4@j20g2000hsi.googlegroups.com> On Jan 27, 4:02 am, "Robb Lane (SL name)" wrote: > I have written a script which: > - opens a file > - does what it needs to do, periodically writing to the file... for a > few hours > - then closes the file when it's done > So my question is: > Would it be better to 'open' and 'close' my file on each write cycle? > e.g. > def writeStuff(content): > myFile = open('aFile.txt', 'a+') > myFile.write(content) > myFile.close() > > ... or just leave it till it's done? > I don't need to use the file contents until the script is done > (although it would be nice... just to check it while it's working), so > just curious what people think is the better method. > - rd Sounds like a classic case for a database to me (long running process producing sporadic output that you might want to tinker with as it's being produced). Python 2.5 comes with sqlite3 included... -- bjorn From bladedpenguin at gmail.com Fri Jan 25 06:28:05 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 03:28:05 -0800 (PST) Subject: global/local variables References: <13pia51grjfo2ed@corp.supernews.com> <4d161c89-7e33-4ddc-851f-bc9beb537229@q21g2000hsa.googlegroups.com> <13pjekb7r9jja4c@corp.supernews.com> Message-ID: <8d7caad9-fcc3-4bb5-bd7b-dd71e6bd6099@d4g2000prg.googlegroups.com> On Jan 25, 5:31 am, Steven D'Aprano wrote: > On Thu, 24 Jan 2008 23:04:42 -0800, Tim Rau wrote: > > UnboundLocalError: local variable 'nextID' referenced before assignment > > When you assign to a name in Python, the compiler treats it as a local > variable. So when you have a line like this: > > nextID += 1 # equivalent to nextID = nextID + 1 > > you are getting the value of the _local_ nextID before you have assigned > a value to it. > > > I want to know why it says 'local variable' it never had a problem when > > just allThings was in there. > > Because you don't assign to allThings, and therefore it is treated as > global. > Hmm.... so I can't assign to globals in a local environment? How do I make it see that I'm assigning to a global? > > as for the objection to global variable: If I didn't make them global, > > I'd make them part of a singleton class called gameVars that would get > > passed everywhere. > > *shrug* Or you could consider a different program structure completely. > > > It's unlikely that they'll get mixed in with anyhting > > else, as they fulfill a unique function. Also, I think it's more > > convenient, and I am, after all, my own employer when it comes to > > programming. > > Hey, it's your time and effort. If you want to, you can download the > Python "goto" module, and use goto and comefrom in your code. > > No, that's unfair. Globals aren't as harmful as goto. I'm not saying that > globals are verboten or that they have no place in 21st century > programming at all. Since I know nothing about your program, I can't > judge whether globals are the right way to go or not. But I am saying > that as a general rule, reliance on global variables often leads to > fragile code with hard-to-diagnose bugs. Your mileage may vary. > > -- > Steven Ha! Gotos I understand the evil of. Human beings don't think that way. Humans are not put together in terms of gotos. Human language does not normally contain gotos. Global, however, seem useful to me. It seems like there are a few things which EVERYONE should know. When you find something often used from a variety of different places, everyone should know about it. It saves time from developing lengthy argument passing chains to follow the passing chains of your program. It keeps the number of arguments low, and easily remembered. This may be more important in python, because python has no type, and where you would have had a type error for forgetting which arg goes where, you have some random thing. Also, My programming style tends towards a mongrel of functional and object oriented programming. I tend to use lone functions when they have no internal state, and objects when they have internal state, but it's not ironclad. It's just what makes sense to me at the time. I'm not defending myself, I'm just setting out my point of view. I'd like to see what you think of it. From ggpolo at gmail.com Mon Jan 7 13:47:07 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 16:47:07 -0200 Subject: Does Python cache the startup module? In-Reply-To: References: Message-ID: 2008/1/7, Baz Walter : > Hello > > I remember reading somewhere (probably this list) that python may cache the > module that starts a program (e.g. 'main.py'). Something like mod_python will do caching. > I'm asking because I have found > that this can sometimes cause problems when making small edits to the module. > For instance, in my current module I changed the name of the main gui widget. > When I ran the program, the program started to leak memory like a sieve. I then > changed the name back again, and the problem went away. This looks very much > like some sort of weird caching behaviour to me. Uhm.. this didn't make much sense. If you say the module is cached, then supposing you did a minor edit, and then supposing because it is cached your application wouldn't detect the change, then I don't see the connection with memory leak. Bring some concrete proof. > > I've tried deleting the .pyc file and even re-booting, but I can't make the > problem go away! > > Can anyone confirm that this caching happens? And if so, is it documented > anywhere? > > TIA > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From scrdhrt at gmail.com Thu Jan 17 07:21:55 2008 From: scrdhrt at gmail.com (Sacred Heart) Date: Thu, 17 Jan 2008 04:21:55 -0800 (PST) Subject: Loop in a loop? Message-ID: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Hi, I'm new to Python and have come across a problem I don't know how to solve, enter com.lang.python :) I'm writing some small apps to learn the language, and I like it a lot so far. My problem I've stumbled upon is that I don't know how to do what I want. I want to do a loop in a loop. I think. I've got two arrays with some random stuff in, like this. array1 = ['one','two','three','four'] array2 = ['a','b','c','d'] I want to loop through array1 and add elements from array2 at the end, so it looks like this: one a two b three c four c I'm stuck. I know how to loop through the arrays separatly and print them, but both at the same time? Hmmm. A push in the right direction, anyone? R, SH From joshuagilman at gmail.com Sun Jan 20 11:38:06 2008 From: joshuagilman at gmail.com (Joshua Gilman) Date: Sun, 20 Jan 2008 08:38:06 -0800 Subject: Looping through the gmail dot trick Message-ID: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> So I have a very interesting task ahead of me and it is to loop through an email using the 'gmail dot trick'. Essentially this trick puts periods throughout your email to make it look different. Even though it has periods gmail will replace them all and send it to that email. So blah at gmail.com is the same as bl.ah at gmail.com. My task is this: Loop through an email and create as many combinations of periods as possible. So all the combinations for blah would be: b.lah bl.ah bla.h b.l.ah b.la.h bl.a.h I'm still rather new to python so this is turning out to be rather tricky. My current code is as follows: for d in range(1, len(email)): > for i in range(1, len(email)): > y = i > temail = email > for x in range(d): > if email[y] == '.': break > temail = temail.replace(email[y], '.' + email[y]) > if not y > len(email) - 2: y += 1 > print temail > It's not looking too bad except for some reason it's making emails like bl..ah which is invalid. So can anyone help me out with getting this to work? Thanks. Cheers, Josh -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Sun Jan 13 09:46:33 2008 From: cwitts at gmail.com (Chris) Date: Sun, 13 Jan 2008 06:46:33 -0800 (PST) Subject: Exceptions - How do you make it work like built-in exceptions? References: <7888e20f-0775-46c4-a6e2-3fc3825c5145@e23g2000prf.googlegroups.com> Message-ID: On Jan 13, 4:14 pm, Lie wrote: > A built-in exceptions, when raised, would print traceback that points > out the offending code, like this: > > Traceback (most recent call last): > File "F:\dir\code.py", line 43, in > a = 1/0 <<<--- > ZeroDivisionError: integer division or modulo by zero > > a user-made exception, when raised, would print traceback that points > out the code that raises the exception > > Traceback (most recent call last): > File "F:\dir\code.py", line 48, in > raise SomeException('Some Exception Message') <<<--- > SomeException: Some Exception Message > > which is generally of little use (yeah, it's possible to trace the > code from the line number, but sometimes it might not be that easy, > cause the line number is (again) the line number for the raising code > instead of the offending code) > > The sample exception was generated from this code: > #### > class SomeException(Exception): > pass > > try: > a = 1/0 > except: > raise SomeException('Some Exception Message') > #### > > Is it possible to make the user-made exception points out the > offending code? from sys import exc_info try: a = 1/0 except: type, value, traceback = exc_info() raise SomeException(type) From petr.jakes.tpc at gmail.com Wed Jan 2 20:16:18 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Wed, 2 Jan 2008 17:16:18 -0800 (PST) Subject: Pivot Table/Groupby/Sum question References: <148c3214-77b9-47b0-a680-ffb85dd3efcd@e6g2000prf.googlegroups.com> <7f396128-2ce2-4dd6-bdc0-855bab8750c7@w38g2000hsf.googlegroups.com> <9f7b6dcc-216d-46a9-a9d5-022c00ee9d7d@d21g2000prf.googlegroups.com> <1caf93fd-3a50-4c77-87b0-5312cdebd35f@d21g2000prf.googlegroups.com> <63a5a87e-3385-4ef0-80a3-cd1a01eeeac3@w38g2000hsf.googlegroups.com> <276d150b-6b2a-4973-8569-bd8cad6df948@s19g2000prg.googlegroups.com> <018c37d5-67c0-4995-88e3-86f701580c26@e23g2000prf.googlegroups.com> <5d6721cc-1912-4adc-9e47-0afa21c51c89@21g2000hsj.googlegroups.com> Message-ID: <17de023b-8dfd-4478-8271-96e21968d489@s8g2000prg.googlegroups.com> > So the data comes in as a long list. I'm dealing with some > information on various countries with 6 pieces of information to > pivot. Just to make it simple it's like a video store database. The > data is like [Country, Category, Sub Category, Film Title, Director, > Number of Copies]. data = [['Italy', 'Horror', '70s', 'Suspiria', > 'Dario Argento', 4],['Italy', 'Classics', 'Neo-Realist', 'Otto e > Mezzo', 'Fellini', 3],['Italy', 'Horror', '70s', 'Profondo Rosso', > 'Dario Argento', 4],...]. So there are 4 copies of Suspiria and 3 of > 8 1/2. What I want is the total number of films for each country, > category and subcategory, ie there are 11 Italian films and 8 Italian > horror films from the 70s, etc...I will then output the data like this > | Horror | Classics ... > Total | 70s Slasher | Neo-Realist Western ... > Total > America 200 20 30 0 10 ... > Argentina 304 1 0 0 0 ... > .... > Italy 11 7 0 3 0 ... Did you mean your table has to look like the following? | Horror | Horror | Classics | Classics Total | 70s | Slasher | Neo-Realist | Western ... Total America 200 20 30 0 10 ... Argentina 304 1 0 0 0 ... .... From ptmcg at austin.rr.com Tue Jan 22 09:31:29 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 22 Jan 2008 06:31:29 -0800 (PST) Subject: HTML parsing confusion References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com> <1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> <6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> Message-ID: On Jan 22, 7:44?am, Alnilam wrote: > ...I move from computer to > computer regularly, and while all have a recent copy of Python, each > has different (or no) extra modules, and I don't always have the > luxury of downloading extras. That being said, if there's a simple way > of doing it with BeautifulSoup, please show me an example. Maybe I can > figure out a way to carry the extra modules I need around with me. Pyparsing's footprint is intentionally small - just one pyparsing.py file that you can drop into a directory next to your own script. And the code to extract paragraph 5 of the "Dive Into Python" home page? See annotated code below. -- Paul from pyparsing import makeHTMLTags, SkipTo, anyOpenTag, anyCloseTag import urllib import textwrap page = urllib.urlopen("http://diveintopython.org/") source = page.read() page.close() # define a simple paragraph matcher pStart,pEnd = makeHTMLTags("P") paragraph = pStart.suppress() + SkipTo(pEnd) + pEnd.suppress() # get all paragraphs from the input string (or use the # scanString generator function to stop at the correct # paragraph instead of reading them all) paragraphs = paragraph.searchString(source) # create a transformer that will strip HTML tags tagStripper = anyOpenTag.suppress() | anyCloseTag.suppress() # get paragraph[5] and strip the HTML tags p5TextOnly = tagStripper.transformString(paragraphs[5][0]) # remove extra whitespace p5TextOnly = " ".join(p5TextOnly.split()) # print out a nicely wrapped string - so few people know # that textwrap is part of the standard Python distribution, # but it is very handy print textwrap.fill(p5TextOnly, 60) From steven at REMOVE.THIS.cybersource.com.au Mon Jan 21 04:21:32 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 09:21:32 -0000 Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> <479451D9.3060207@block.duxieweb.com> Message-ID: On Mon, 21 Jan 2008 16:23:50 +0800, J. Peng wrote: > J. Peng ??: > >> k = (i.split())[3] >> y = (i.split())[1] > > btw, why can't I write the above two into one statement? > > (k,y) = (i.split())[3,1] I don't know. What's "i"? I'm guessing "i" is a string (and what a horrible choice of a name for a string!) So i.split() will return a list. List indexing with multiple arguments isn't defined, which is why you can't write k, y = (i.split())[3,1] BTW, the outermost set of brackets is unnecessary. You can write: i.split()[3] instead of (i.split())[3] -- Steven From mail at timgolden.me.uk Tue Jan 22 04:58:33 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 22 Jan 2008 09:58:33 +0000 Subject: stdin, stdout, redmon In-Reply-To: <4795ba80$0$17176$426a74cc@news.free.fr> References: <4794a5e3$0$9014$426a74cc@news.free.fr> <4794ab22$0$19179$426a74cc@news.free.fr> <4795ba80$0$17176$426a74cc@news.free.fr> Message-ID: <4795BE49.5000708@timgolden.me.uk> Bernard Desnoues wrote: > Hello, > > I checked under linux and it works : > text.txt : > "first line of the text file > second line of the text file" > > test.py : > "import sys > a = sys.stdin.readlines() > x = ''.join(a) > x = x.upper() > sys.stdout.write(x)" > > >cat text.txt | python test.py > > But I reinstalled Python 2.5 under Windows XP and it doesn't work > anyway. Can you confirm that your script works with Win XP and Python 2.5 ? How are you invoking the script under WinXP? If you're using the standard file associations then stdin/stdout won't work correctly. However, they produce a specific error message: C:\temp>type test3.py import sys print sys.stdin.readlines () C:\temp> C:\temp>type test3.py | test3.py Traceback (most recent call last): File "C:\temp\test3.py", line 3, in print sys.stdin.readlines () IOError: [Errno 9] Bad file descriptor C:\temp>type test3.py | python test3.py ['import sys\n', '\n', 'print sys.stdin.readlines ()'] TJG From albert at spenarnc.xs4all.nl Sat Jan 19 13:16:59 2008 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 19 Jan 2008 18:16:59 GMT Subject: Details about pythons set implementation References: <13ntbv51tqcm7c@corp.supernews.com> <83b78deb-b7c4-4fa3-b9ad-1a40be4f9231@n22g2000prh.googlegroups.com> Message-ID: In article <83b78deb-b7c4-4fa3-b9ad-1a40be4f9231 at n22g2000prh.googlegroups.com>, bukzor wrote: >On Jan 4, 2:15 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 04 Jan 2008 09:29:50 -0800, bukzor wrote: >> > Why cant you implement < for complex numbers? Maybe I'm being naive, but >> > isn't this the normal definition? >> > a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) >> >> No, it is not. Ordered comparisons are not defined for complex numbers. Mathematically speaking, it depends what you require from ordering. Mostly (and what we need for fast lookup) we want transitivity: A>=B & B>=C => A>=C Requiring transitivity you are right with your concern about the OP's version of <. Although in mathematics you can define things as you like, a non-transitive < is frowned upon. >> Which is bigger, 4+2j or 2+4j? We can make a useful ordering by defining A<=B : if RE(A) /= RE(B) then RE(A) <= RE(B) else IM(A) <= IM(B) So for the OP's example: 4+2i is bigger. This is sufficient to put a bunch of complex numbers in an array, sort the array, and have a lookup using binary search. (Or a heap: a heap is better for frequent additions and deletions.) >> >> > How do you implement a set without sorting? >> >> With a hash table. >> >> Or if you are willing to limit yourself to sets of small integers, you >> can implement it using bit flipping. E.g. 5 is an element of the set if >> bit 5 is on. Or if you can live with O(n) implementations are trivial. >> >> > Are you expecting better than O(log n)? >> >> Sure. The same applies to sets of complex numbers the C++ way with the above definition of for < for complex numbers. >> >> -- >> Steven > >Good Answers! -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- like all pyramid schemes -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From deets at nospam.web.de Tue Jan 29 17:50:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jan 2008 23:50:23 +0100 Subject: Terse Syntax through External Methods In-Reply-To: References: <5vu9gaF1no9i1U1@mid.uni-berlin.de> Message-ID: <609otnF1phb32U2@mid.uni-berlin.de> Jens schrieb: > On Jan 25, 3:19 pm, "Diez B. Roggisch" wrote: >> Jens schrieb: >> >> >> >>> Hello Everyone >>> I'm newbie to Zope and i have a few questions regarding external >>> methods. What i wan't to do >>> is provide a terse syntax for converting urls to special tracking >>> urls: >>> >>> turns the provided url into something like >>> http://host/tracking?url=http%3A%2F%2Fmyurl%2F >>> in the output. >>> i've been trying to use a external procedure like this. >>> ## Script (Python) "track_link" >>> ##bind container=container >>> ##bind context=context >>> ##bind namespace=_ >>> ##bind script=script >>> ##bind subpath=traverse_subpath >>> ##parameters=self,url >>> ##title=track link >>> ## >>> return "%s%s" % (self.tracking_prefix, url_quote(url)) >>> This doesn't work because because the method doesn't have access to >>> the environment. Obviously I don't wan't to pass everything explicitly >>> into the function as this would defeat the purpose of the exercise, >>> namely to provide a terse syntax. >>> I have a background in other languages so I might be missing something >>> conceptually with regard Zope and DTML.. Is there a better was of >>> doing this, perhaps without using external methods? Currently im doing >>> the following which isn't very elegant: >>> in content document >>>
>> tracking>">link >>> ... >>> tracking: >>> >>> Appreciate any input you might have on this- >> Is it really needed to use an external method for this, or isn't a >> "normal" python script enough already? >> >> If it has to be an External method, you can't access such a context >> AFAIK. But then you can create a python script that _has_ this context, >> and passese it to the external method. Not the nicest solution, but >> should work. >> >> Diez > > Like I said i'm a newbie. I though the deal with Zope was that i > couldn't really do inline scripting (for security reasons) > like in php but had to use these external methods. how does one go > about creating a "normal" python script exactly and > how do I invoke it's functionality? Read the docs: http://www.zope.org/Documentation/Books/ZopeBook/2_6Edition/ScriptingZope.stx There's everything in there you need. Diez From sunilkrghai at gmail.com Wed Jan 2 09:57:09 2008 From: sunilkrghai at gmail.com (Sunil Ghai) Date: Wed, 2 Jan 2008 20:27:09 +0530 Subject: Network-Packets Message-ID: <52da23100801020657v2d6e001ck5a9e126db77eb511@mail.gmail.com> Hello guys, I know this is not the right place for asking about this but i am sure some of you must have an idea about this. I have a bit knowledge about networking and protocols. I would like to know what do we actually mean by "Bandwidth". As in if a person is allowed to download stuff of about 400MB than is it the size of all the Packets the system recieves? and if by some reason the operating system discards the packet it recieves and does not forward to the appropiate application through port number then that packet size gets include in the limited access of user or not? I am really in need to get clear this point. Thanks alot in advance.. -- Sunil Kumar Ghai -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Tue Jan 8 09:10:45 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 8 Jan 2008 06:10:45 -0800 (PST) Subject: windows service References: Message-ID: On Jan 7, 6:42 pm, Michael Chesterton wrote: > I'm trying to get a program that uses M2Crypto ThreadingSSLServer to > run in windows as a service. I have a few problem, it doesn't listen > on its port and I don't know how to debug it. > > I used the pipeservice example as a framework to get it running as a > service > > def SvcDoRun(self): > # Write an event log record - in debug mode we will also > # see this message printed. > servicemanager.LogMsg( > servicemanager.EVENTLOG_INFORMATION_TYPE, > servicemanager.PYS_SERVICE_STARTED, > (self._svc_name_, '') > ) > > daemonserver = do_daemon() > while 1: > daemonserver.handle_request() > > I think I need a way to break out of that while loop when a service > stop is sent, but not knowing what happening at that point I'm not > sure how. It's not even listening on its port. > > daemonserver is > > daemonserver = SSL.ThreadingSSLServer((host_ip_addr, int > (host_port_num)), TestRequestHandler, ctx) > > any help? > > -- > Michael Chestertonhttp://chesterton.id.au/blog/http://barrang.com.au/ > > -- > Michael Chestertonhttp://chesterton.id.au/blog/http://barrang.com.au/ Before you get it going as a service, test it as just a regular Python script. I've created local servers using CherryPy before and been able to test them. I recommend you do the same with yours before changing it to a service. If you have a firewall installed (which you should), you may need to allow your program access through it. I've occasionally had to allow localhost with some of the more stringent firewalls. I found this post on creating a Windows Service for Windows 2000, which can probably be modified for XP: http://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html There's also this one: http://essiene.blogspot.com/2005/04/python-windows-services.html They both sound different from the way you did it, but maybe I misunderstood. Mike From jeya.jpl62 at gmail.com Mon Jan 28 07:55:01 2008 From: jeya.jpl62 at gmail.com (jpl) Date: Mon, 28 Jan 2008 04:55:01 -0800 (PST) Subject: confidence your earning power Message-ID: <89cbb38b-d0e4-4d8e-9f23-07ed2d8266af@e6g2000prf.googlegroups.com> By increasing your earning power you may be able to get a better job and more pay. Many people suffer a money loss because of their lack in confidence and knowledge. There are several ways you can increase your earning power but the first way is to realize what you are really worth. Take a long hard look at yourself and figure out who you really are and what you really want to be. Have you done that? If you are ready to learn how to increase your earning power then continue to read. http://ingreasingyourearningsuccess.blogspot.com From bearophileHUGS at lycos.com Wed Jan 30 08:17:41 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jan 2008 05:17:41 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> <745a5833-b963-4eba-8dda-f54d267e00d1@p69g2000hsa.googlegroups.com> <90051f5f-6fce-4fec-b8a3-0e4a87a464c9@i3g2000hsf.googlegroups.com> Message-ID: <3afdfcbd-2624-4b67-9ffc-1d0aa5690aa1@i72g2000hsd.googlegroups.com> If you don't want to reinvent the wheel all the time you can use this one: def inplacefilter(pred, alist): """inplacefilter(pred, alist): filters the given list like filter(), but works inplace, minimizing the used memory. It returns None. >>> pr = lambda x: x > 2 >>> l = [] >>> inplacefilter(pr, l) >>> l [] >>> l = [1,2,2] >>> inplacefilter(pr, l) >>> l [] >>> l = [3] >>> inplacefilter(pr, l) >>> l [3] >>> l = [1,2,3,1,5,1,6,0] >>> r = filter(pr, l) # normal filter >>> r [3, 5, 6] >>> inplacefilter(pr, l) >>> r == l True """ slow = 0 for fast, item in enumerate(alist): if pred(item): if slow != fast: alist[slow] = alist[fast] slow += 1 del alist[slow:] If you use Psyco you can replace the enumerate() with a manually incremented counter to speed up the code a bit, like this (untested): def inplacefilter(pred, alist): slow = 0 fast = 0 for item in alist: if pred(item): if slow != fast: alist[slow] = alist[fast] slow += 1 fast += 1 del alist[slow:] Bye, bearophile From danielsson.lorenzo at gmail.com Fri Jan 25 16:06:57 2008 From: danielsson.lorenzo at gmail.com (Lorenzo E. Danielsson) Date: Fri, 25 Jan 2008 21:06:57 +0000 Subject: looking for a light weighted library/tool to write simple GUI above the text based application In-Reply-To: <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> Message-ID: <479A4F71.9060501@gmail.com> petr.jakes.tpc at gmail.com wrote: >>> is already solved). >> what you are looking for is curse :) >> http://docs.python.org/lib/module-curses.html >> http://www.ibm.com/developerworks/linux/library/l-python6.html >> >> renaud > > Renaud, thanks for your reply. > > I think I was not specific/clear enough in my first posting. I know > the curses library ( http://pyncurses.sourceforge.net ). It AFIK > provides TUI (short for: Text User Interface or Textual User > Interface). My needs are GUI, I mean "a nice VGA pictures" on the VGA > LCD 10" display. > > Petr What you need then is something like SVGAlib (http;//svgalib.org). Only really old people like myself know that it exists. I've never heard of any Python bindings for it, but that might be where you come in. I haven't looked at SVGAlib for years, and I'm not sure about the state of the video drivers. I suggest you look at that first. You could also look at GGI (http://ggi-project.org). GGI has different output targets. IIRC, one of them is directfb. To tell you the truth I've never really used GGI. There seems to be a python wrapper for GGI, although it is fairly old. Maybe you could look at the code for some ideas. You should also be able to compile SDL to be able to use directfb as a target. If your libSDL handles it, then that should apply to wrapper libraries as well, including pygame. I've never tried running SDL apps this way, but if it works well, that would probably be your 'best' option. Lorenzo From arnodel at googlemail.com Tue Jan 22 11:42:06 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 08:42:06 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: On Jan 22, 4:10?pm, Alan Isaac wrote: > > > fwiw, > Alan Isaac Thanks. So I guess I shouldn't take the code snippet I quoted as a specification of izip but rather as an illustration. -- Arnaud From andre.roberge at gmail.com Sun Jan 27 12:46:29 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 27 Jan 2008 09:46:29 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: Message-ID: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> On Jan 27, 1:06 pm, coldpizza wrote: > There is a pattern that occurs fairly often in constructors in Python > and other OOP languages. > > Let's take an example: > > class Server(object): > def __init__(self, host, port, protocol, bufsize, timeout): > self.host = host > self.port = port > self.protocol = protocol > self.bufsize = bufsize > self.maxthreads = maxthreads > self.timeout = timeout > > Imho, in the class above the assignment to instance fields does not > contain much programming logic and therefore can be safely 'abstracted > away' by the language itself with a syntax which would look something > like this: > > class Server(object): > def __init__(self, @host, @port, @protocol, @bufsize, @timeout): > pass > > This would be equivalent to the first example above, yet it does not > obfuscate the code in any way. Or does it? It does look much cleaner > to me. > > Of course, the ampersand is just an arbitrary choice and might have > bad connotations for those who read it as 'take address of' but @ has > some allusion to delegates which maybe is ok. > > I am not an experienced programmer and I am not sure if this is > necessarily a good idea, so I wanted to get some feedback from more > experienced Pythonistas before submitting it elsewhere. If you search on this list, you will find that there has been *many* proposals to remove self (which, I realize is slightly different than what yo propose) and that the main argument can be summarized as "Explicit is better than implicit." Personally, I like the idea you suggest, with the modification that I would use "." instead of "@", as in class Server(object): def __init__(self, .host, .port, .protocol, .bufsize, .timeout): pass Andr? From arnodel at googlemail.com Thu Jan 3 14:04:06 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 3 Jan 2008 11:04:06 -0800 (PST) Subject: Fate of itertools.dropwhile() and itertools.takewhile() References: <7a86a421-089f-4634-8902-e9edfe139f03@e23g2000prf.googlegroups.com> <33c108cb-4378-4f34-bc52-b179772a73cb@n20g2000hsh.googlegroups.com> Message-ID: <72039809-9ad0-486a-b2fc-a01221eda8b8@1g2000hsl.googlegroups.com> On Jan 3, 4:39?pm, "win... at gmail.com" wrote: > On Dec 29 2007, 11:10 pm, Raymond Hettinger wrote: > > > I'm considering deprecating these two functions and would like some > > feedback from the community or from people who have a background in > > functional programming. > > Well I have just this minute used dropwhile in anger, to find the next > suitable filename when writing database dumps using date.count names: > > ? ? filename = "%02d-%02d-%d" % (now.day, now.month, now.year) > ? ? if os.path.exists(filename): > ? ? ? ? candidates = ("%s.%d" % (filename, x) for x in count(1)) > ? ? ? ? filename = dropwhile(os.path.exists, candidates).next() > > Much clearer than the alternatives I think, please keep dropwhile and > takewhile in itertools ;) Wouldn't using ifilterfalse instead of dropwhile produce the same result? -- Arnaud From python at rcn.com Wed Jan 2 19:33:11 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 2 Jan 2008 16:33:11 -0800 (PST) Subject: Two candies References: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com> <736e51b5-d7f6-4523-89f1-df62256ce7c0@s19g2000prg.googlegroups.com> Message-ID: [Raymond] > >#3 is a fine choice. It is memory efficient -- the repeat() itertool takes-up only a few bytes. It doesn't need psyco, you already have to fast C routines talking to each other without having to go through the interpreter loop.< [bearophile] > In my code I have found otherwise, so to be more sure I have just done > few benchmarks on a Pentium3 CPU, 256 MB RAM, ActivePython 2.5.1.1, on > Win. I applaud your efforts to measure performance -- that is a reasonably good way to find-out the best approach (though you have to be very careful about what you measure, how you measure it, that the system state hasn't changed between measurements, and how your interpret the results). Here's a few thoughts based on knowing what's under-the-hood. * xrange() and repeat() objects only take-up a few bytes. * xrange() creates a new integer object for every iteration * repeat() will re-use the same object over and over * the counter for repeat() does not use integer objects * the list approach takes 4 bytes of memory per entry (pointers to a single object) * lists, xrange objects, and repeat objects all support the iteration protocol * lists and xrange objects also support the sequence protocol (getitem and len) * array_new has a special case for lists -- it uses the known length to pre-size the array and it uses the getitem protocol to access the elements * array_new handles repeat() and xrange() by using the iterator protocol and it grows the array one element at a time, with periodic resizing and over-allocation -- this is dog slow * in most apps (except for sparse arrays), the initialization time for an array is dominated by the time spent actually doing something useful with the array (iow, this is an odd place to be optimizing) * the array module could be made a little smarter by checking the iterators for a hint about their size (this would speed-up the xrange() and repeat() versions considerably). * the array module is not designed for speed -- it is all about storing data compactly * in contract, numpy and other numerical apps are more thoroughly optimized * memory consumption is very difficult to measure since the operating system has a say in the matter (ask for 1 byte of allocation and you may get an enormous chunk in return). That being said, I'll cut to the chase: * sometimes its easy to get so wrapped-up in thinking this though, that the obvious gets missed. * try adding this one to your test suite: a = array('l', [0]) * n Raymond From paul at boddie.org.uk Wed Jan 16 07:21:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 16 Jan 2008 04:21:17 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> Message-ID: <60b75f24-d33a-476e-932d-11dfb9880562@v4g2000hsf.googlegroups.com> On 16 Jan, 02:17, "Jaimy Azle" wrote: > > Wow, serious... what you've done was really, really cool... :) In practice, not that cool. ;-) > I was expect there are nobody willing to do to have python runs Java > Language (such as PyPy) over CPython. Perhaps your javaclass does not work > just like as PyPy, but really... it is damned cool to get CPython execute > java byte-code, congratulations... Well, the limitations that stopped me working on it are listed on the page I referenced, so it wasn't that cool in the end. In fact, the project grew out of just wanting to inspect .class files and pull out method signatures, but it was so tempting to see whether Java bytecodes could be rewritten and run in a CPython environment. I think the benefits of running Java on CPython are significantly less than those had by running Python on the Java VM (or another VM). Firstly, who wants to write statically typed code which then runs on a virtual machine that can't take advantage of the type declarations? Secondly, isn't it just better to use a virtual machine with just-in- time compilation and all sorts of security mechanisms if you're wanting to write the Java code that, when compiled, can take advantage of all that stuff? In other words: what makes CPython a compelling VM for the Java programmer? My perspective now is that it's a lot more interesting to target Python for virtual machines other than the CPython one because that's where the performance and functionality benefits are most likely to be found. And the most important motivation for this: I prefer writing Python, not Java. ;-) Paul From paddy3118 at googlemail.com Mon Jan 7 12:51:58 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 7 Jan 2008 09:51:58 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com><7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com><8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> <13o06hleh4dkj45@corp.supernews.com> Message-ID: On Jan 7, 5:09 pm, "Reedick, Andrew" wrote: > Bingo. Perl has specific operators to establish intent: > > Perl -e "'1' + 1" > > 2 > > Perl -e "'1' . 1" > > 11 > '+' is the operator for addition > '.' is the operator for string concatenation > > int and string comparisons also have specific operators: > $a == $b # compare as integers: ==, >, <, <=, >= > $a eq $b # compare as strings: eq, gt, lt, le, ge > > Which now morphs the conversation into the issue of how too much > operator overloading creates confusion and/or ambiguity. > Or how using different operators for similar operations on different types causes confusion. i.e. == versus eq; > versus gt If Perl had, for example, a complex number 'base' type would that need yet another set of operators? Well enough Perl vs Python. The thing is, that when writing in another programming language you have to use its idioms or you end up fighting the language in attempt to make it work like another language you are more familiar with. In Python strings won't ever automatically change to numbers. - Paddy. From mraborife at yahoo.com Tue Jan 8 02:21:17 2008 From: mraborife at yahoo.com (mpho raborife) Date: Mon, 7 Jan 2008 23:21:17 -0800 (PST) Subject: python syntax:urgent Message-ID: <645055.89441.qm@web45511.mail.sp1.yahoo.com> Anyone please help me get this syntax right subprocess.Popen(["gmmscore", "-i", Input, "-l", List, "-t", modeltype, > "-m", str(mixture), "-d", str(dimension), "-v", str(vfloor), "-n", str(number), "-r", str(results)]) --------------------------------- Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dpsanders at gmail.com Sat Jan 19 10:36:29 2008 From: dpsanders at gmail.com (David Sanders) Date: Sat, 19 Jan 2008 07:36:29 -0800 (PST) Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <2d7f8b3b-afc5-4948-9207-0f39de7d6a96@i12g2000prf.googlegroups.com> On Jan 18, 11:15 am, David Sanders wrote: > Hi, > > I am processing large files of numerical data. Each line is either a > single (positive) integer, or a pair of positive integers, where the > second represents the number of times that the first number is > repeated in the data -- this is to avoid generating huge raw files, > since one particular number is often repeated in the data generation > step. > > My question is how to process such files efficiently to obtain a > frequency histogram of the data (how many times each number occurs in > the data, taking into account the repetitions). My current code is as > follows: Many thanks to all for the very detailed and helpful replies. I'm glad to see I was on the right track, but more happy to have learnt some different approaches. Thanks and best wishes, David. From steven at REMOVE.THIS.cybersource.com.au Wed Jan 23 01:39:26 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 06:39:26 -0000 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Tue, 22 Jan 2008 18:32:22 -0800, George Sakkis wrote: > The OP didn't mention anything about the context; for all we know, this > might be a homework problem or the body of a tight inner loop. There is > this tendency on c.l.py to assume that every optimization question is > about a tiny subproblem of a 100 KLOC application. Without further > context, we just don't know. Funny. As far as I can tell, the usual assumption on c.l.py is that every tiny two-line piece of code is the absolute most critically important heart of an application which gets called billions of times on petabytes of data daily. Given the human psychology displayed involved, in the absence of definitive evidence one way or another it is a far safer bet to assume that people are unnecessarily asking for "the fastest" out of a misguided and often ignorant belief that they need it, rather than the opposite. People who actually need a faster solution usually know enough to preface their comments with an explanation of why their existing solution is too slow rather than just a context-free demand for "the fastest" solution. Fast code is like fast cars. There *are* people who really genuinely need to have the fastest car available, but that number is dwarfed by the vast legions of tossers trying to make up for their lack of self-esteem by buying a car with a spoiler. Yeah, you're going to be traveling SO FAST on the way to the mall that the car is at risk of getting airborne, sure, we believe you. (The above sarcasm naturally doesn't apply to those who actually do need to travel at 200mph in a school zone, like police, taxi drivers and stock brokers.) -- Steven From fredrik at pythonware.com Thu Jan 3 10:21:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 16:21:50 +0100 Subject: Treating a unicode string as latin-1 In-Reply-To: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> References: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Message-ID: Simon Willison wrote: > But ElementTree gives me back a unicode string, so I get the following > error: > >>>> print u'Bob\x92s Breakfast'.decode('cp1252').encode('utf8') > Traceback (most recent call last): > File "", line 1, in > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/encodings/cp1252.py", line 15, in decode > return codecs.charmap_decode(input,errors,decoding_table) > UnicodeEncodeError: 'ascii' codec can't encode character u'\x92' in > position 3: ordinal not in range(128) > > How can I tell Python "I know this says it's a unicode string, but I > need you to treat it like a bytestring"? ET has already decoded the CP1252 data for you. If you want UTF-8, all you need to do is to encode it: >>> u'Bob\x92s Breakfast'.encode('utf8') 'Bob\xc2\x92s Breakfast' From hanke at volny.cz Wed Jan 23 02:58:38 2008 From: hanke at volny.cz (hanke at volny.cz) Date: Wed, 23 Jan 2008 08:58:38 +0100 (CET) Subject: python2.4-dbg and C modules Message-ID: <3bd1fcabde7f9c96bd50d23e961c3b95@www1.mail.volny.cz> Hello, please, when I try to run my code under python2.4-dbg from Ubuntu, the interpreter complains that the Py_InitModule4 symbol is undefined in a C module I'm using (PyOpenAL): ImportError: /var/lib/python-support/python2.4/_openal.so: undefined symbol: Py_InitModule4 Google reveals that this problem is not specific just to PyOpenAL, but I couldn't find out what is the essence of the problem and how python-2.4dbg is different from python2.4 except for including debugging symbols, because in plain python2.4 the module works fine. Also, the same thing happens with python 2.5 (not the -dbg variant). Please, what is the problem and how to overcome it? Thank you, Hynek Hanke From ben at morrow.me.uk Fri Jan 25 22:37:53 2008 From: ben at morrow.me.uk (Ben Morrow) Date: Sat, 26 Jan 2008 03:37:53 +0000 Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> Message-ID: [newsgroups line fixed, f'ups set to clpm] Quoth Summercool : > On Jan 25, 5:16 pm, Summercool wrote: > > somebody who is a regular expression guru... how do you negate a word > > and grep for all words that is > > > > tire > > > > but not > > > > snow tire > > > > or > > > > snowtire > > i could think of something like > > /[^s][^n][^o][^w]\s*tire/i > > but what if it is not snow but some 20 character-word, then do we need > to do it 20 times to negate it? any shorter way? This is no good, since 'snoo tire' fails to match even though you want it to. You need something more like / (?: [^s]... | [^n].. | [^o]. | [^w] | ^ ) \s* tire /ix but that gets *really* tedious for long strings, unless you generate it. Ben From martin at marcher.name Thu Jan 10 05:11:15 2008 From: martin at marcher.name (Martin Marcher) Date: Thu, 10 Jan 2008 11:11:15 +0100 Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: Russ P. wrote: > On Jan 9, 9:47 pm, "Steve Brown" wrote: >> I've got a series of modules which look like this: >> >> #************ >> # >> # Temperature Sense Test >> # >> #************ >> class Test3(ar_test.AR_TEST): >> """Temperature Sense Test""" >> >> I don't like the duplicated information: But the comment is attractive, >> and the docstring self.__doc__ is already in use in the test log. I've >> read that all modules and classes should have docstrings, but I don't >> really have anything else to say, and each module contains only one >> class. I don't think that >> >> """Temperature Sense Test""" >> class Test3(ar_test.AR_TEST): >> """Temperature Sense Test""" >> >> would be a real improvement. >> >> What do you think? It's still duplicated information. > I tend to be a bit skimpy with one-line comments for classes and > methods, but I think a more complete (""" style) comment is often > appropriate for the top of the file. > > I'm sure you can think of more to say than "Temperature Sense Test." exactly my opinion > What temperature? What kind of temperature sensor? What kind of test > is it, and why are you doing it? That may all be obvious in context, > but you've provided no context in your post. Also, if the module is of > any significant size, you might want to provide a clue about who wrote > it. Then, if someone has a question about it later, they will know who > to ask. I tend to mention the main use cases for test classes (especially) and also a "human readable" description of what can happen (forgive me the missing line breaks). Something like this: class Test3(ar_test.AR_TEST): """Temperature Sense Test. This class assures that the connection to the hardware sensor can be established. It also checks a reference sensor that always reports a certain value so that one can be sure correct data values are reported. """ hth martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From george.sakkis at gmail.com Sat Jan 12 00:16:25 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 21:16:25 -0800 (PST) Subject: Import and execfile() References: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> Message-ID: <865225ff-d212-4b22-bd3f-85d0721e3346@f3g2000hsg.googlegroups.com> On Jan 11, 6:54 pm, Mitko Haralanov wrote: > On Fri, 11 Jan 2008 14:05:11 -0800 (PST) > > George Sakkis wrote: > > # trying to set the configuration: > > CFG = {} > > execfile('path/to/some_config.py', CFG) > > > Traceback (most recent call last): > > ... > > ImportError: No module named master_config > > > I understand why this fails but I'm not sure how to tell execfile() to > > set the path accordingly. Any ideas ? > > This might be overly simplistic but you could have a load_config > function which takes the path to the config file and the variable where > to load the config as arguments. > > In the load_config function, you could get the directory part of the > config file path, appending it to sys.path, load the config, and then > remove the newly added directory from sys.path. Thanks, that's basically what I did eventually and it works for my simple requirements. Another alternative would be to require the config files to be modules already in the path. In this case setConfig becomes almost trivial using __import__ instead of execfile(): import inspect def setConfig(configfile): return dict(inspect.getmembers(__import__(configfile, fromlist=True))) On the downside, the config files cannot be moved around as easily as with execfile. Also, if placed in directories that are not in the path, one or more ancestor directories may have to be populated with (empty) __init__.py files to denote them as Python packages. So generally speaking, when should execfile be preferred to __import__, or the other way around ? George From fredrik at pythonware.com Wed Jan 9 07:41:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 13:41:51 +0100 Subject: "Canonical" way of deleting elements from lists In-Reply-To: References: <5ujkbaF1e11ksU1@mid.dfncis.de> <87ejcri96v.fsf@mulj.homelinux.net> <87abnfi84i.fsf@mulj.homelinux.net> <5ujp20F1ehvg2U2@mid.dfncis.de> Message-ID: Nick Craig-Wood wrote: > Using keywords[:] stops the creation of another temporary list. in CPython, "list[:] = iter" actually creates a temporary list object on the inside, in case "iter" isn't already a list or a tuple. (see the implementation of PySequence_Fast() for details). From http Wed Jan 30 02:09:56 2008 From: http (Paul Rubin) Date: 29 Jan 2008 23:09:56 -0800 Subject: Removal of element from list while traversing causes the next element to be skipped References: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com> Message-ID: <7xabmnbxh7.fsf@ruckus.brouhaha.com> Santiago Romero writes: > > >>> li = [1,2,3,4,5] > > >>> filter(lambda x: x != 3, li) > > [1, 2, 4, 5] > > I haven't measured it, but this should be the fast solution in all > the thread ... li.remove(3) is probably faster. From kyosohma at gmail.com Tue Jan 15 13:51:32 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 15 Jan 2008 10:51:32 -0800 (PST) Subject: Open existing Word document, modify and save. References: <1ab91596-e868-4b28-9fe3-34f9129a114f@s8g2000prg.googlegroups.com> Message-ID: On Jan 15, 12:01 pm, gsal wrote: > New to Python and new to Win32. Help please. > > O.k., so this might seem like one of those "can you do my homework" > kind of postings, except that is not homework, it is officework. > > I have been reading the Core Python book and I am really excited about > starting my next project with Python, instead of tcl/tk/Fortran/C. > While I can see how to use it for scientific computing and have gone > with the NumPy and SciPy tutorials, I am having a hard time with > Win32. > > Attempted to read some of the documentation for Win32 and while the > basic stuff talks about creating a document, I did not see how to open > an existing document and modify certain parts of it...and then it > seems that it got very complicated (for me) really quick. Sure, it > seems powerful, but all I need is a small part of it, I think. > > Here is the thing. Here at the office, we have computer programs to > generate spec data and the Applications people have MS-Word documents > in a very specific format where they would like to put such spec > data. > > Initially, I was using merge fields and VB macros, until they stopped > working when newer (non-backwards-compatible) versions came along; > then, I switched to generating *.xml out of the original *.doc file, > breaking it appart, modifying it and gluing back together...this is > very laborious task and I have to go through the whole exercise, > should the application people modify the original *.doc > > So, basically, I am looking for a way to work directly with the > original *.doc, assuming I know everything about it...which I do; in > fact, I have it and can also modify it, should I need to bookmark it > or otherwise modify as needed. > > How to go about it? > > What's the python code to open an existing document, modify it and > save it back? > > how does the Word document needs to be bookmarked/formatted so that it > can be modified? For example, after the computer program has been run > and the new, say, "machine rating" calculated, I need to deposit such > value in a very specific spot in the Word document. > > I presume somebody out there already does this and is willing to > provide some code?. > > Thank you very much in advance. > > gsal As I understand it, the only way to work with MS Word in Python is through COM in much the same manner as VB does. So if you know the COM model that MS Word uses, you shouldn't have too much trouble. I would recommend getting Hammond's and Robinson's book "Python Programming on Win32" though, as it explains using Python this way. They have a sample chapter here: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html It should be noted that Hammond is the author of the PyWin32 modules. ActiveState's website has a special version of Python that includes a COM browser and you can install it without harming your current installation. At least, I've had no problems. Other than that, you'll probably be spending a lot of time on MSDN. Mike From rhamph at gmail.com Tue Jan 15 12:23:53 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 15 Jan 2008 09:23:53 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> Message-ID: <88ef2477-78b7-48d4-9bf7-89ef8340ad33@d21g2000prg.googlegroups.com> On Jan 13, 5:51 am, Richard Szopa wrote: > On Jan 13, 8:59 am, Marc 'BlackJack' Rintsch wrote: > > > On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: > > > However, I am very surprised to learn that > > > > super_object.__getattr__(name)(*args, **kwargs) > > > > getattr(super_object, name)(*args, **kwargs) > > > > are not equivalent. This is quite odd, at least when with len() > > > and .__len__, str() and .__str__. Do you maybe know what's the > > > rationale behind not following that convention by getattr? > > > I think you are confusing `__getattr__` and `__getattribute__` here! > > `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's > > different. > > Well, in my code calling super_object.__getattr__(name)(*args, > **kwargs) and getattr(super_object, name)(*args, **kwargs) gives > *different* effects (namely, the latter works, while the former > doesn't). That kinda suggests that they don't map to each other :-). > And that makes me feel confused. Don't think of them as mappings. Think of them as a way for a class to hook into getattr's protocol, conveniently named similar to getattr (__getattr__ and __getattribute__). getattr() may call several methods, no methods at all, change the arguments, etc. Although len() may seem simple, many others are not so simple. -- Adam Olsen, aka Rhamphoryncus From martin at v.loewis.de Wed Jan 2 03:30:00 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Jan 2008 09:30:00 +0100 Subject: different encodings for unicode() and u''.encode(), bug? In-Reply-To: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> Message-ID: <477B4B88.6070207@v.loewis.de> > i stumbled on this situation, that is if I decode some string, below > just the empty string, using the mcbs encoding, it succeeds, but if I > try to encode it back with the same encoding it surprisingly fails > with a LookupError. This seems like something to be corrected? Indeed - in your code. It's not the same encoding. >>>> unicode(s, 'mcbs') > u'' >>>> unicode(s, 'mcbs').encode('mcbs') > Traceback (most recent call last): > File "", line 1, in > LookupError: unknown encoding: mcbs Use "mbcs" in the second call, not "mcbs". HTH, Martin From sipickles at hotmail.com Tue Jan 29 06:21:52 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Tue, 29 Jan 2008 11:21:52 +0000 Subject: refcount Message-ID: Hi, Is is possible to access the refcount for an object? Ideally, I am looking to see if I have a refcount of 1 before calling del Thanks Simon -- Linux Counter: User# 424693 From basilisk96 at gmail.com Thu Jan 10 19:03:22 2008 From: basilisk96 at gmail.com (Basilisk96) Date: Thu, 10 Jan 2008 16:03:22 -0800 (PST) Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87abneibc7.fsf@benfinney.id.au> Message-ID: On Jan 9, 10:55 pm, Ben Finney wrote: > erik gartz writes: > > The loop performs some actions with web services. The particular > > iteration I'm on isn't important to me. It is only important that I > > attempt the web services that number of times. If I succeed I > > obviously break out of the loop and the containing function (the > > function which has the loop in it) returns True. If all attempts > > fail the containing loop returns False. > > When you have iteration requirements that don't seem to fit the > built-in types (lists, dicts, generators etc.), turn to 'itertools' > in the standard > library. > > >>> from itertools import repeat > > >>> def foo(): > ... import random > ... print "Trying ..." > ... success = random.choice([True, False]) > ... return success > ... > >>> max_attempts = 10 > >>> for foo_attempt in repeat(foo, max_attempts): > ... if foo_attempt(): > ... break > ... > Trying ... > Trying ... > Trying ... > Trying ... > Trying ... > Trying ... > >>> > > Note that this is possibly more readable than 'for foo_attempt in > [foo] * max_attempts", and is more efficient for large values of > 'max_attempts' because 'repeat' returns an iterator instead of > actually allocating the whole sequence. > > > I guess based on the replies of everyone my best bet is to leave the > > code the way it is and suck up the warning from pylint. > > I think your intent -- "repeat this operation N times" -- is better > expressed by the above code, than by keeping count of something you > don't actually care about. > > > I don't want to turn the warning off because catching unused > > variables in the general is useful to me. > > Agreed. > > -- > \ "Dyslexia means never having to say that you're ysror." | > `\ --anonymous | > _o__) | > Ben Finney Neat! That is the best solution I've seen so far. I should definitely dig into the itertools module more often. Cheers, -Basilisk96 From asmodai at in-nomine.org Fri Jan 4 08:21:19 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jan 2008 14:21:19 +0100 Subject: Fortran to Python Message-ID: <20080104132119.GK82115@nexus.in-nomine.org> I got someone who asked me to make changes in an old Fortran program she is using for some calculations. The calculations are pretty standard aside from 2 calls to DLINCG (an IMSL numerical_libraries function to calculate an inverse matrix). What I wonder about, does anybody have a Fortran to Python conversion page somewhere to map some of the basic types to Python equivalents? What kind of speed difference should I expect? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ One often hears the most when everyone is silent... From martin at marcher.name Thu Jan 24 17:49:52 2008 From: martin at marcher.name (Martin Marcher) Date: Thu, 24 Jan 2008 23:49:52 +0100 Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <4798ec32$0$36333$742ec2ed@news.sonic.net> Message-ID: On Thursday 24 January 2008 20:56 John Nagle wrote: > Ira.Kovac at gmail.com wrote: >> Hello all, >> >> I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like >> to sort based on first two characters. > > Given those numbers, the average number of characters per line is > less than 2. Please check. which would be true if 1.599.999.999 had 2 chars and the rest of the lines just one :) (but yes that would be an interesting question how to sort a 1 character line based on the first 2 of that line) martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From bernhard.merkle at googlemail.com Fri Jan 4 03:18:42 2008 From: bernhard.merkle at googlemail.com (Bernhard Merkle) Date: Fri, 4 Jan 2008 00:18:42 -0800 (PST) Subject: reassign to builtin possible !? References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> <477CEB93.8000706@tim.thechases.com> Message-ID: <3ea5c5c2-0d7c-4dc2-a5b9-ea9b0c895a5f@i3g2000hsf.googlegroups.com> On Jan 3, 8:06 pm, "Chris Mellon" wrote: > In Py3k this will be a syntax error, like assigning to None is now. > Possibly also in 2.6. thanks. I feed much better with that :-) From yann.le_boulanger at u-paris10.fr Tue Jan 22 15:09:50 2008 From: yann.le_boulanger at u-paris10.fr (Yann Leboulanger) Date: Tue, 22 Jan 2008 21:09:50 +0100 Subject: PyGTK, Glade, and ComboBoxEntry.append_text() In-Reply-To: <4066a33f-6293-48e3-a48c-66af699d0eb9@i29g2000prf.googlegroups.com> References: <4066a33f-6293-48e3-a48c-66af699d0eb9@i29g2000prf.googlegroups.com> Message-ID: <47964d8b$0$963$426a74cc@news.free.fr> Greg Johnston wrote: > Hey all, > > I'm a relative newbie to Python (switched over from Scheme fairly > recently) but I've been using PyGTK and Glade to create an interface, > which is a combo I'm very impressed with. > > There is, however, one thing I've been wondering about. It doesn't > seem possible to modify ComboBoxEntry choice options on the fly--at > least with append_text(), etc--because they were not created with > gtk.combo_box_entry_new_text(). Basically, I'm wondering if there's > any way around this. > > Thank you, > Greg Johnston PyGTK mailing list: http://pygtk.org/feedback.html From jarausch at skynet.be Wed Jan 9 13:31:08 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 09 Jan 2008 19:31:08 +0100 Subject: asynchronous timer events - how to? In-Reply-To: References: <4784fd96$0$22305$ba620e4c@news.skynet.be> Message-ID: <478512EC.8000404@skynet.be> Fredrik Lundh wrote: > Helmut Jarausch wrote: > >> I'm using a web server (Karrigell) which is based on the asyncore module. >> I'd like to be able to checkpoint some data (e.g. pickled >> dictionaries) to disk >> from time to time. >> For that I would need to setup a timer which calls a Python >> object/function when its time interval has expired. While this >> function is running I need access to the variables of the server. > > the usual way to do that with asyncore is to add an outer control loop > that calls asyncore.loop with a count argument (or poll directly), and > checks a "task queue" at regular intervals. > > but in your case, it's probably easier to set up a cron job that does > a "wget" against your server with a "secret" URL, and have the server do > the checkpointing whenever that URL is fetched. Thanks for this ingenious idea, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From hniksic at xemacs.org Thu Jan 17 10:44:15 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 17 Jan 2008 16:44:15 +0100 Subject: Is this a bug, or is it me? References: Message-ID: <87myr4o3sg.fsf@mulj.homelinux.net> "Neil Cerutti" writes: > You cannot access a class's class variables in it's class-statement > scope, since the name of the type is not bound until after the class > statement is completed. But they are still available as locals, so you can access them using their names, like this: >>> class C: ... a = 1 ... b = 2 ... print a+b ... 3 The question is, why doesn't the OP's code snippet work? It seems that the generator expression can't read the surrounding locals(). But when you change the generator expression to a list comprehension using a pair of [] around it, it starts working. Compare: class C(object): d = {} for a in 1, 2, 3: ignore = list((a, b) for b in (4, 5, 6)) Traceback (most recent call last): File "", line 1, in File "", line 4, in C File "", line 4, in NameError: global name 'a' is not defined with: class C(object): d = {} for a in 1, 2, 3: ignore = [(a, b) for b in (4, 5, 6)] It seems that generator expressions and list comprehensions have subtly different scoping rules. Whether this is a bug or not is a good question. From eproust at gmail.com Sun Jan 20 16:58:13 2008 From: eproust at gmail.com (pythonewbie) Date: Sun, 20 Jan 2008 13:58:13 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> Message-ID: <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> On 20 jan, 20:59, "Diez B. Roggisch" wrote: > pythonewbie schrieb: > > > > > On 20 jan, 19:50, "Diez B. Roggisch" wrote: > >> pythonewbie schrieb: > > >>> On 20 jan, 12:20, Christian Heimes wrote: > >>>> pythonewbie wrote: > >>>>> I am stucked on creating a function to get the Python install > >>>>> directory (and site-packages directory) with a 100% reliable method... > >>>> Only one method is 100% reliable: > >>>> try: > >>>> import yourextension > >>>> except ImportError: > >>>> available = False > >>>> else: > >>>> available = True > >>>> Christian > >>> Hi Christian, > >>> OK thanks, interesting to detect if an extension is available or not. > >>> But for different reasons I also want to get the absolute path of > >>> Python install directory (not only the executable under Linux) and > >>> site-packages directory. > >>> How could I proceed ? > >> Maybe sys.path is a starter? > > >> Diez > > > Yes, it is, but my problem is that I am not sure to find the > > information I need at the same position of the list generated by > > sys.path. > > > I explain, for Win32, I find install directory using sys.path[6] and > > site-package directory using sys.path[7], for Linux I find install > > directory using sys.path[2] and site-package directory using > > sys.path[6]. > > > For my tests, I have used XP Pro and Ubuntu Gutsy. > > > I am not sure to find these information at the same position in the > > sys.path list using Win9x, Win2k, Ubuntu Dapper, Redhat FC6, FreeBSD > > and using Python v2.1 2.2 2.3 etc ? > > > This why I'm asking experienced programmers of this usenet group for > > advices. > > Sorry, I missed your first post. However, I don't see what your problem > actually is. If you want to look for any extension, you need to consider > whatever can be seen in the sys.path. So what do you care about the > order of them? > > Diez I just would like to know if I would ALWAYS find the install directory in sys.path[6] and site-packages directory in sys.path[7] on any Win32 platform and sys.path[2] and site-packages directory in sys.path[6] on any Linux platform. If the reply is : "YES you can be sure of it !" All would be great for me and I would be ready to create a script to detect with a reliable manner the installation dir. et site-packages dir. for all my Linux/Win32 Python apps. Thanks for your interest on this topic. From deets at nospam.web.de Fri Jan 4 08:50:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 04 Jan 2008 14:50:59 +0100 Subject: Strange varargs issue In-Reply-To: References: Message-ID: <5u6ru4F1gplq5U1@mid.uni-berlin.de> Mike schrieb: > I'm not sure if this is a bug or if I'm just not understanding > something correctly. I'm running the following (broken.py) on > ActivePython 2.5.1.1, based on Python 2.5.1 (r251:54863 5/1/2007) as > "python broken.py foo" (on Windows, of course): > > > #!/bin/env python > > import sys > > class foobar(object): > def func(arg): > print 'foobar.func: %r' % arg This needs to be def func(self, arg): .... And then of course for aclling, you need an instance of foobar as first argument. Either explicit, or implicit: unbound_m = foobar.func unbound_m(some_foobar, arg) bound_m = foobar().func bound_m(arg) Or you do @classmethod def func(cls, arg): ... Then you only need one argument, but beware: it's a classmethod, not an instancemethod anymore. Diez Diez From steve at holdenweb.com Wed Jan 30 11:13:09 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Jan 2008 11:13:09 -0500 Subject: Removing Pubic Hair Methods In-Reply-To: <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> Message-ID: Wildemar Wildenburger wrote: > Gerardo Herzig wrote: >> I will use genital().extend(), thats for shure ^^ > > Well, you never go wrong with apply(genital(), females), do you? > > /W That's enough genitalia [ed] -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From paul at boddie.org.uk Wed Jan 23 10:28:45 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 23 Jan 2008 07:28:45 -0800 (PST) Subject: Problem with processing XML References: <13pbudgks88rcf3@corp.supernews.com> <47971EFF.8070701@web.de> <6c291c78-7a11-4d6f-be15-c916017ccf60@s13g2000prd.googlegroups.com> <47974B47.5000509@web.de> Message-ID: <03f25aca-33ee-4dc4-8b67-9a9dbb9aa8e5@y5g2000hsf.googlegroups.com> On 23 Jan, 15:12, Stefan Behnel wrote: > > Paul Boddie wrote: > > I'm not disputing the benefits of the ElementTree approach, but one > > has to recall that the DOM is probably the most widely used XML API > > out there (being the one most client-side developers are using) and > > together with the other standards (XPath and so on) isn't as bad as > > most people like to make out. > > I didn't deny that it works in general. However, it does not fit into the > standard ways things work in Python. You're only one step away from using the magic word. I agree that writing getAttribute all the time instead of, say, using magic attributes (provided the characters employed are lexically compatible with Python - another thing that people tend to overlook) can be distressing for some people, but as usual the language comes to the rescue: you can assign the method to a shorter name, amongst other things. If you want to stray from the standards then with some APIs (as you know), you can override various classes and provide your own convenience attributes and methods, but the interoperability remains beneath. > > Furthermore, I don't think it does > > Python much good to have people "acting all Ruby on Rails" and telling > > people to throw out everything they ever did in order to suck up the > > benefits, regardless of the magnitude of those benefits; it comes > > across as saying that "your experience counts for nothing compared to > > our superior skills". Not exactly the best way to keep people around. > > I would have formulated it a bit different from my experience, which usually > is: people complain on the list that they can't manage to get X to work for > them. Others tell them: "don't use X, use Y", implicitly suggesting that you > may have to learn it, but it will help you get your problem done in a way that > you can /understand/ (i.e. that will fix your code for you, by enabling you to > fix it yourself). If people feel that they've solved 90% of the problem using tools they're become familiar with, I think it's somewhat infuriating to be told to forget about the last 10% and to use something else. We don't know how nasty the code is in the case of this particular inquirer, but I've seen nothing recently where the DOM specifically was obstructing anyone's comprehension. In one case, had PyXML or minidom been up-to-date, the solution would have been within easy reach (the textContent property), but with everyone being waved off to greener pastures, there's probably little gratitude to be had in doing the legwork to fix and enhance those implementations. [...] > > like the DOM stuff, if the support for standardised/ > > recognised technologies is perceived as deficient, and given the point > > above about glossing over what people themselves bring with them to > > solve a particular problem, then people are quite likely to gloss over > > Python than hear anyone's sermon about how great Python's other XML > > technologies are. > > It's not about "other XML technologies", it's only about making the standard > XML technologies accessible and usable. It's about designing interfaces in a > way that matches the tool people are using anyway, which in this case is Python. Well, the standard XML technologies include those covered by PyXML, like it or not, and whilst some APIs may be nicer than the variants of the standard APIs provided by PyXML, there's a lot of potential in those standards that hasn't been exploited in Python. Consider why the last Web browser of note written in Python was Grail, circa 1996, for example. Paul From castironpi at gmail.com Sat Jan 12 08:53:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 05:53:47 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> Message-ID: <354c74f6-6e56-4e41-a686-56239aa4cea9@f47g2000hsd.googlegroups.com> On Jan 12, 3:51 am, Fredrik Lundh wrote: > castiro... at gmail.com wrote: > > I'm writing an NxN observer pattern, mostly for my own personal > > exploration. Two threads -might- be calling 'Disconnect' at the same > > time, and I can't even guarantee that the function runs properly. > > > for emelem in [ e for e in emlist if e.func is func ]: > > try: > > emlist.remove( emelem ) > > except ValueError: > > pass > > so use a lock. it's a whopping two lines of code: > > creation: > > lock = threading.Lock() > > usage: > > with lock: > for emelem in ... > ... > > more here: > > http://effbot.org/zone/thread-synchronization.htm > > and btw, looping over a list to figure out what you want to remove from > that list is a bit pointless. better just create a new list: > > with lock: > # get rid of all func instances > emlist = [e for e in emlist if e.func is not func] > > an alternative approach would be to replace emlist with a dictionary, > keyed on func objects. that'll let you remove all items associated with > a given function with a single atomic operation: > > del emdict[func] > > -> so use a lock. it's a whopping two lines of code: Yes. 1) I'm wondering what the specifics are on [Rubin]: >>2. Associate a lock with the list. Anything wanting to access the list should acquire the lock, do its stuff, then release the lock. This gets confusing after a while.<< I considered these suggestions early on. They apply often but I ruled them out for reasons: 2) List is referenced by others; concurrent modifications may be going on; can not replace it. Can I make asynchronous modifications and merge the changes, SCM-style? 3) Dictionary returns non-static order; order is important. Create a int-func tuple and sort dictionary results? Perhaps. That's sounding pretty good. From lasses_weil at klapptsowieso.net Sun Jan 27 20:13:07 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 28 Jan 2008 02:13:07 +0100 Subject: py3k feature proposal: field auto-assignment in constructors In-Reply-To: <87d4rm93l1.fsf@benfinney.id.au> References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> Message-ID: <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> Ben Finney wrote: > "Andr?" writes: > >> Personally, I like the idea you suggest, with the modification that I >> would use "." instead of "@", as in >> >> class Server(object): >> def __init__(self, .host, .port, .protocol, .bufsize, .timeout): >> pass > > -1. > > That leading dot is too easy to miss when looking over the code. > class Server(object): def __init__(self, self.host, self.port, self.protocol, self.bufsize, self.timeout): pass ? /W From tdelaney at avaya.com Sun Jan 20 17:58:26 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 21 Jan 2008 06:58:26 +0800 Subject: Looping through the gmail dot trick In-Reply-To: <13p7i5qaihgte12@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > Postfix, I think, interpets "foo+bar" the same as "foo". Gmail does the same. It's quite useful - apart from using it to determine which site I signed up to has sent me mail, I also use it so I can have multiple Guild Wars accounts using the same email account e.g. +gw1 at gmail.com +gw2 at gmail.com All resolve to @gmail.com. I have a couple of spare accounts so when friends or relative visit we can all play together ... Tim Delaney From gagsl-py2 at yahoo.com.ar Tue Jan 29 14:57:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jan 2008 17:57:40 -0200 Subject: Zipfile content reading via an iterator? References: <475EEF96.2070203@tim.thechases.com> <475FF830.4070508@tim.thechases.com> <479F24C4.9000402@tim.thechases.com> Message-ID: En Tue, 29 Jan 2008 11:06:12 -0200, Tim Chase escribi?: > Just to follow up on this, I dropped the the 2.6 version of > zipfile.py in my project folder (where the machine is currently > running Python2.4), used the ZipFile.open() and it worked fine. > [...] > Anyways, thanks to Gabriel (and all the authors of Python > zipfile.py library) for the solution. I just bring attention to the upcoming feature. All credit should go to the patch author, Alan McIntyre. -- Gabriel Genellina From exarkun at divmod.com Tue Jan 22 09:34:33 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 22 Jan 2008 09:34:33 -0500 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <5vmc4fF1n9pk6U1@mid.uni-berlin.de> Message-ID: <20080122143433.15391.1130108145.divmod.quotient.1468@ohm> On Tue, 22 Jan 2008 15:15:43 +0100, "Diez B. Roggisch" wrote: >Jean-Paul Calderone wrote: > >> On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" >> wrote: >>>For a simple greenlet/tasklet/microthreading experiment I found myself in >>>the need to ask the question >>> >>> [snip] >> >> Why do you need a special case for generators? If you just pass the >> object in question to iter(), instead, then you'll either get back >> something that you can iterate over, or you'll get an exception for >> things that aren't iterable. > >Because - as I said - I'm working on a micro-thread thingy, where the >scheduler needs to push returned generators to a stack and execute them. >Using send(), which rules out iter() anyway. Sorry, I still don't understand. Why is a generator different from any other iterator? Jean-Paul From gagsl-py2 at yahoo.com.ar Wed Jan 23 16:27:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 19:27:39 -0200 Subject: A global or module-level variable? References: <7637fd0b-961e-4730-abd8-96e85c907082@i72g2000hsd.googlegroups.com> <7xwsq1tyts.fsf@ruckus.brouhaha.com> <63002d69-7738-4cae-bfb5-b933f16591b8@t1g2000pra.googlegroups.com> Message-ID: En Wed, 23 Jan 2008 11:58:05 -0200, Bret escribi?: > On Jan 22, 1:00 pm, Paul Rubin wrote: > >> If you have to do it that way, use: > > Is there a better way? A more Pythonic way? It's simple, clear and works fine, why make it more complicated? Unless you have additional requirements, like a multithreaded program. -- Gabriel Genellina From jpeng at block.duxieweb.com Mon Jan 21 22:00:53 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Tue, 22 Jan 2008 11:00:53 +0800 Subject: read files Message-ID: <47955C65.8080604@block.duxieweb.com> first I know this is the correct method to read and print a file: fd = open("/etc/sysctl.conf") done=0 while not done: line = fd.readline() if line == '': done = 1 else: print line, fd.close() I dont like that flag of "done",then I tried to re-write it as: fd = open("/etc/sysctl.conf") while line = fd.readline(): print line, fd.close() this can't work.why? From roy at panix.com Tue Jan 29 09:00:02 2008 From: roy at panix.com (Roy Smith) Date: Tue, 29 Jan 2008 09:00:02 -0500 Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> .1201577269.8966python-list@pyttttttttt 05C.23015128012208@70-1-84-166..rea1.spcsdns.neee Message-ID: In article , "Terry Reedy" wrote: > "Roy Smith" wrote in message > news:roy-3C105C.23015128012008 at 70-1-84-166.area1.spcsdns.net... > | But, surely Python has plenty of "implementation defined" aspects. > | Especially in the libraries. > > I personally do not consider the libraries as part of the language (as > opposed to the distribution) and was not referring to them. I realize that there is a difference between the core language and the libraries, but Python depends on the libraries more than a lot of other languages do. They are the "batteries included" part. Indeed, there is a lot of stuff in the "Python Library Reference" which in most languages would be considered part of the core. The description of boolean operations (and, or, not), for example. String, sequence, and dictionary methods. Where do you draw the line and say, "The core language ends here; the rest is just libraries"? From paul.hankin at gmail.com Wed Jan 9 05:29:14 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 9 Jan 2008 02:29:14 -0800 (PST) Subject: Open a List of Files References: <874pdomrrd.fsf@mulj.homelinux.net> <4f67337a-14ea-4552-8a5a-6de9703e58ff@d70g2000hsb.googlegroups.com> Message-ID: On Jan 9, 10:02 am, Fredrik Lundh wrote: > Paul Hankin wrote: > > This can be more cleanly written using locals() > > > for fn in filenames: > > locals()[fn] = open(os.path.join(host_path, fname + '.txt', 'wb') > > from the reference manual: > > locals() > > Update and return a dictionary representing the current > local symbol table. > > Warning: The contents of this dictionary should not be > modified; changes may not affect the values of local > variables used by the interpreter. Thanks Fredrik! I learnt something today. I wonder if there's a reason why it doesn't raise an exception when you try to write to it? That would seem better to me than having it sometimes update variables and sometimes not. -- Paul Hankin From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 05:51:40 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 11:51:40 +0100 Subject: what does **kw mean? In-Reply-To: <99cc3280-bffd-4004-a3ae-a06244a82759@e6g2000prf.googlegroups.com> References: <99cc3280-bffd-4004-a3ae-a06244a82759@e6g2000prf.googlegroups.com> Message-ID: <47874a30$0$22238$426a34cc@news.free.fr> zslevi at gmail.com a ?crit : > I've been reading the following example, and couldn't figure out, what > **kw mean. (It's an empty dictionary, but what's the semantics): Keyword varargs. And FWIW, *args is for positional varargs. From steven.klass at gmail.com Mon Jan 21 17:30:07 2008 From: steven.klass at gmail.com (rh0dium) Date: Mon, 21 Jan 2008 14:30:07 -0800 (PST) Subject: Prioritization function needed (recursive help!) Message-ID: <51180fda-304d-4f7e-812a-32032585675b@e23g2000prf.googlegroups.com> Hi all, I need some help on writing a recursive priority function Given a list = [ A, B, C, D] Where the following constraints are in place: A depends on [B, C] C depends on [B] Figure out real order that prioritizes these. Output [ B, C, A, D ] is valid. (Actually D could be anywhere in it as it doesn't matter..) I am really struggling on simply how to organize the data and write the corresponding function - I tried classes but I don't know if that's the best approach. See my other post on this. Thanks From fredrik at pythonware.com Wed Jan 9 05:30:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 11:30:41 +0100 Subject: "Canonical" way of deleting elements from lists In-Reply-To: References: <5ujkbaF1e11ksU1@mid.dfncis.de> Message-ID: Fredrik Lundh wrote: > creating a new list is always almost the right way to do things like message = message.replace("always almost", "almost always") From mathieu.malaterre at gmail.com Thu Jan 10 03:27:48 2008 From: mathieu.malaterre at gmail.com (mathieu) Date: Thu, 10 Jan 2008 00:27:48 -0800 (PST) Subject: PyGILState_Release produces a seg fault Message-ID: <11e94b09-c972-48d8-b6f0-c20a08b5face@j20g2000hsi.googlegroups.com> Hello and happy new year folks, I am experiencing a seg fault while using the python interface to the VTK library (debian oldstable, python 2.3). The VTK library is wrapped by a custom mechanism to provide a python API. In particular they implemented a way so that a python function can be called in response to an event(*). Basically all the code is doing is: { PyGILState_STATE state = PyGILState_Ensure(); // construct arglist from C++ args: ... // call python function: result = PyEval_CallObject(this->obj, arglist); PyGILState_Release(state); // crash happens here } However the event being triggered from the C++ layer is done from multiple threads. After reading : http://docs.python.org/api/threads.html I tought that the VTK-python layer was simply missing a call to : PyEval_InitThreads() just before Py_InitModule(), but now my python shell appears as hung ! The only solution I found is that if I comment out the function calls PyGILState_Ensure/PyGILState_Release then everything goes smoothly. Am I reading the docs backward ? I do need to keep the call to PyGILState_Ensure/PyGILState_Release, right ? I am also copying the log from valgrind (VTK lib untouched, no call to PyEval_InitThreads), UpdateProgress being the function called from multiple threads: ==20066== Thread 2: ==20066== Invalid read of size 4 ==20066== at 0x403232A: sem_post@@GLIBC_2.1 (in /usr/lib/debug/ libpthread-2.5.so) ==20066== by 0x80B0D53: PyEval_ReleaseLock (in /usr/bin/python2.4) ==20066== by 0x80DDB20: PyGILState_Release (in /usr/bin/python2.4) ==20066== by 0x45C7AB4: vtkPythonCommand::Execute(vtkObject*, unsigned long, void*) (vtkPythonUtil.cxx:2016) ==20066== by 0x483C0DF: vtkSubjectHelper::InvokeEvent(unsigned long, void*, vtkObject*) (vtkObject.cxx:547) ==20066== by 0x483C18E: vtkObject::InvokeEvent(unsigned long, void*) (vtkObject.cxx:713) ==20066== by 0x4E67E6A: vtkAlgorithm::UpdateProgress(double) (vtkAlgorithm.cxx:115) Thanks, -Mathieu Original post: http://public.kitware.com/pipermail/vtk-developers/2008-January/004890.html (*) See line 1906->2019 at: http://public.kitware.com/cgi-bin/viewcvs.cgi/Common/vtkPythonUtil.cxx?annotate=1.80 From george.sakkis at gmail.com Fri Jan 11 10:10:00 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 07:10:00 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <3f8981a6-e26b-420d-9b24-eed878631317@e10g2000prf.googlegroups.com> <478732db$0$19250$426a74cc@news.free.fr> <7cbc897a-5c2f-46bf-99bf-ee35cb6cdf46@e25g2000prg.googlegroups.com> <4787762b$0$18777$426a74cc@news.free.fr> Message-ID: On Jan 11, 8:59 am, Bruno Desthuilliers wrote: > George Sakkis a ?crit : > > > > > On Jan 11, 4:12 am, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > >> George Sakkis a ?crit : > > >>> On Jan 10, 3:37 am, Bruno Desthuilliers wrote: > >>>> I fail to see how the existence of JIT compilers in some Java VM changes > >>>> anything to the fact that both Java (by language specification) and > >>>> CPython use the byte-code/VM scheme. > >>> Because these "some Java VMs" with JIT compilers are the de facto > >>> standard used by millions; > >> Repeating an argument doesn't make it more true nor more relevant. Once > >> again, this doesn't change anything to the fact exposed above. > > >>> the spec is pretty much irrelevant > >> I mentionned this because this kind of choice is usually not part of the > >> language spec but of a specific implementation. Java is AFAIK the only > >> language where this implementation stuff is part of the spec. > > >>> (unless > >>> you're a compiler writer or language theorist). > >> I thought it was quite clear and obvious that I was talking about points > >> relating to these fields. > > > No it wasn't, > > """ > > or is Python just too slow > > as an interpreted language > > Being "interpreted" is a quality of an implementation, not of a language. > """ > If that isn't clear enough what I'm talking about, then sorry but I > can't help. Pedantic once again. For languages with a single (or practically single) implementation such as Python, the average user couldn't care less about the distinction. Your point might have more merit if PyPy or IronPython or Jython enter the same league with CPython in terms of usage. > > and besides the OP is most likely interested in these as > > a simple user so the distinction between a spec and a de facto > > standard implementation (such as JDK for Java and CPython for Python) > > are almost pedantic if not misleading. > > I can live with being called "pedantic" - even I'm not sure whether > correcting a wrong statement about CPython's execution model is pedantic > or not. But I *still* fail to see how it could be "misleading", and > *you* still fail to explain in which way it could be misleading. > > If your point is that saying that CPython uses a byte-code/VM scheme > "just like Java" necessarily implies JIT compilation just because some > JVM support this feature, then it would be time you pay more attention > to what is effectively written. What three different people in this thread have been trying to tell you but you seem to miss is that claiming CPython's VM "is just like Java" is comparable to saying "a Yugo's car engine is just like a BMW's" (or "humans are just like chimpanzees"), which for some value of "just like" is technically correct but it's not what most people would call an accurate statement. > > We're not Lisp (yet ;-)), with > > five major implementations and a dozen of minor ones. > > And ? In which way does it make the distinction between a language and a > language implementation less true ? In the way that most plain users care (or not) about. George From paul at boddie.org.uk Thu Jan 17 12:29:42 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 17 Jan 2008 09:29:42 -0800 (PST) Subject: Perl Template Toolkit: Now in spicy new Python flavor References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> <13a75830-5416-4fe3-9460-018e1240e6e6@e32g2000prn.googlegroups.com> Message-ID: <18fdac42-b0fe-4e23-8c1f-2c5671bb3bf7@i12g2000prf.googlegroups.com> On 16 Jan, 21:01, "eef... at gmail.com" wrote: > > I can't claim a comprehensive familiarity with Python template > offerings, but all of the packages approved for use at my previous > workplace left me cold. There are a few offerings listed on this page: http://wiki.python.org/moin/Templating I suppose you could add Template Toolkit somewhere on that page, indicating where it fits into the bigger picture. Paul From support at wingware.com Mon Jan 21 19:52:32 2008 From: support at wingware.com (Wingware Support) Date: Mon, 21 Jan 2008 19:52:32 -0500 Subject: problem With Psyco on Wingide mac In-Reply-To: References: Message-ID: <47953E50.4030004@wingware.com> Arash Arfaee wrote: > I am trying to use psyco with wingide on mac. when I open Mac Python > shell I can import psyco, but not inside the wingide. Even python > shell on wingide cannot import psyco. > Can anybody help me to solvethis problem? I suspect Wing is finding a different Python installation than you want or expect it to. In Project Properties, you can set Python Executable to change this. Note, BTW, that running in the debugger w/ psyco may skip breakpoints in optimized code, or may not work at all. Hope that's helpful. - Stephan From ceccarelli.aldo at gmail.com Mon Jan 28 08:23:29 2008 From: ceccarelli.aldo at gmail.com (Aldo Ceccarelli) Date: Mon, 28 Jan 2008 05:23:29 -0800 (PST) Subject: Anybody has ported talib to Python via SWIG References: <6fa2a3e3-ab77-41dc-a01e-55770a764b0e@k39g2000hsf.googlegroups.com> Message-ID: <4db2f6dd-b007-44ef-81c9-cce03fb12b59@y5g2000hsf.googlegroups.com> On 26 Gen, 19:33, "Gabriel Genellina" wrote: > En Thu, 24 Jan 2008 20:49:33 -0200, Aldo Ceccarelli ? > escribi?: > > > Hi Everybody, > > TaLib (technical analysis package with function indicators coded in C/C > > ++,http://www.ta-lib.org) has a complete library with source in C/C+ > > +. > > > I am new to SWIG (wrapper interface generator) and would really > > appreciate any Python (.py) port of TaLib to be able to call and test > > TaLib's functions (f.i. MACD, Parabolic SAR and so on) in some Python > > (2.5) script. > > > Do you have idea whether TaLib Python package has already been > > generated and can be eventually downloaded anywhere? > > If Talib has a C API (not C++), the ctypes module can be used to call ? > those C functions, so there is no need to write a special SWIG wrapper. In ? > fact it may be much easier to do that way. > > ctypes is a standard module on Python 2.5, and is documented here:http://docs.python.org/lib/module-ctypes.html > > -- > Gabriel Genellina Many thanks a lot, Gabriel. I will study ctypes and its applicability to ta-lib in particular; in negative case I will go through ta-lib forum available (for registered users) at http://www.tadoc.org here I have just found several posts of people describing their path to ta-lib port via SWIG too. Again thanks and kindest regards:-) Aldo From jpeng at block.duxieweb.com Tue Jan 22 02:36:49 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Tue, 22 Jan 2008 15:36:49 +0800 Subject: what's this instance? Message-ID: <47959D11.3040806@block.duxieweb.com> def safe_float(object): try: retval = float(object) except (ValueError, TypeError), oops: retval = str(oops) return retval x=safe_float([1,2,3,4]) print x The code above works well.But what's the instance of "oops"? where is it coming from? I'm totally confused on it.thanks. From lists at cheimes.de Thu Jan 3 11:38:52 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 03 Jan 2008 17:38:52 +0100 Subject: How do you pass compiler option to setup.py install? In-Reply-To: <32e43bb70801030824p7099da66s6ffb4ee0ea58b311@mail.gmail.com> References: <32e43bb70801030824p7099da66s6ffb4ee0ea58b311@mail.gmail.com> Message-ID: <477D0F9C.7000507@cheimes.de> Emin.shopper Martinian.shopper wrote: > Dear Experts, > > How do you pass the -c option to setup.py install? Specifically, when I try > to install zope.interfaces version 3.3 from source on a windows machine, I > get a message about using "-c mingw32". That works fine for setup.py build, > but it does not work for "setup.py install". python setup.py build -c mingw32 install You can also change the distutils.cfg file to set mingw32 as the default compiler. Please refer to the documentation for more information. Christian From ggpolo at gmail.com Thu Jan 24 16:16:44 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 24 Jan 2008 19:16:44 -0200 Subject: object vs class oriented -- xotcl In-Reply-To: References: Message-ID: 2008/1/24, William Pursell : > > I've been away from Python for at least a year, and in the interim > have spent a little time looking at the XOTcl object framework for > Tcl. One of the interesting features of XOTcl is the ability for an > object to change class dynamically. The XOtcl documentation makes the > claim that this makes it object oriented, while most other languages > are "class oriented". Here's a snippet from the wiki, from a post to > the mailing list by Gustaf Neumann: (http://wiki.tcl.tk/1297) > > Class-oriented means: look at the class and you know exactly how all > of the instances look alike. The class is the first and primary > language construct; the class is well the place where you specify the > instance variables (there are no instance variables except those > specified in the class). The only kind of individualism left in the > objects is to let them differ by their state (the values of their > instance variables). Changing classes (class migration) is > conceptually quite hard for this setup. > > Object-oriented (in this distinction) means that the primary elements > are objects, which keep all instance variables. classes my be used to > specify the behavior of objects, they are container for methods and > they control the life-cycle of objects. Objects are like the facts, > and classes are like rules, that determine the behavior of the > objects. Since the connection between objects and classes is rather > loose, it is sufficient to define their relation through an > association. Therefore it is quite easy to change the relation between > objects and classes (and between classes and classes) dynamically. > Objects have arbitrary individualism, they may have variables never > used in any class, they may have private procs etc. > > I'm not sure that describes the method well. Basically, you can > instantiate an object A of class Foo, and later change A to be an > object of class Bar. Does Python support this type of flexibility? > As I stated above, I've been away from Python for awhile now, and am a > bit rusty, but it seems that slots or "new style" objects might > provide this type of behavior. The ability to have an object change > class is certainly (to me) a novel idea. Can I do it in Python? > -- > http://mail.python.org/mailman/listinfo/python-list > class A(object): pass class B(object): pass a = A() a.__class__ = B That ? Maybe you meant something else. -- -- Guilherme H. Polo Goncalves From david.hotham at blueyonder.co.uk Mon Jan 28 16:40:49 2008 From: david.hotham at blueyonder.co.uk (david.hotham at blueyonder.co.uk) Date: Mon, 28 Jan 2008 13:40:49 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <92b67efe-c437-40bc-89fc-bbdd85d6e718@s19g2000prg.googlegroups.com> Message-ID: <4ce44a0d-6745-4f55-b2fb-038cb2ea6c76@k39g2000hsf.googlegroups.com> I see I don't have as many columns as I'd expected. Here's a reformatted listing. from time import time from bisect import insort from sys import argv #--------------------------------------------------------------------- # Hash table is a global variable #--------------------------------------------------------------------- global hash_table #--------------------------------------------------------------------- # countdown.py # # Python script to solve the Countdown numbers game # # Remarks on optimization: # # - Without the hash table, the following all proved beneficial: # - Keep a list of numbers used so far, and never create a number # that you've already used # - Make sure only to return unique pairs from the generate_pairs # function # - Don't ever perform two consecutive substractions # - (Don't ever perform two consecutive divisions would also be # valid, though it's not something that happens a lot so the # benefit is small) # # - These tricks work by avoiding performing the same search more # than once # # - With only six seeds, it's possible to implement a perfect hash # table that remembers every list that we try to solve (and indeed # this is what the implementation here does) # # - With that hash table, the optimizations above become largely # redundant, so for the sake of simplicity I've removed them # # - Solving for larger numbers of seeds would require a smarter # approach, as it would soon become infeasible to maintain a # complete hash table. Then the tricks above might be useful # again. # #--------------------------------------------------------------------- #--------------------------------------------------------------------- # Returns all useful combinations of two numbers, and a string # representing the operation used to get there. #--------------------------------------------------------------------- def generate_combinations(higher_number, lower_number): #----------------------------------------------------------------- # Useful operations are: # - addition (always) # - subtraction (of the lower number from the higher number, so # long as they are not equal) # - multiplication (so long as not multiplying by one) # - division (if it's exact, and not by one) #----------------------------------------------------------------- yield "+", higher_number + lower_number if (higher_number != lower_number): yield "-", higher_number - lower_number if (lower_number != 1): yield "*", higher_number * lower_number if ((higher_number % lower_number) == 0): yield "/", higher_number / lower_number #--------------------------------------------------------------------- # Returns all pairs from a list of seeds. # # Pairs always have the first number lower than or equal to the second # number, provided that the list is ordered on entry (as it should # be). #--------------------------------------------------------------------- def generate_pairs(seeds): for ii in xrange(len(seeds)): for higher_num in seeds[ii+1:]: yield seeds[ii], higher_num #--------------------------------------------------------------------- # Solves a seed list. Takes pairs, combines them, and recursively # calls solve_list again with the new shorter list. # # Seeds should be sorted on entry. #--------------------------------------------------------------------- def solve_list(seeds, target, depth, solution_so_far): #----------------------------------------------------------------- # Loop through possible pairs. #----------------------------------------------------------------- for lower_num, higher_num in generate_pairs(seeds): #------------------------------------------------------------- # Make a copy of the list, and remove this pair. # # Taking a copy appears to be quicker than using the original # list and then reinstating the chosen pair later. #------------------------------------------------------------- new_seeds = seeds[:] new_seeds.remove(lower_num) new_seeds.remove(higher_num) #------------------------------------------------------------- # Try out all possible combinations of our pair. #------------------------------------------------------------- for operation, combination in generate_combinations( higher_num, lower_num): #--------------------------------------------------------- # If we hit our target, we're happy. # # Else if the list has gotten too short already, move on. # # Else make a new, shorter, list containing our new value. # # If we've already tried to solve the new list, there's no # point in trying again. # # Else try to solve the shorter list. #---------------------------------------------------------- if combination == target: print "made target!" print "%s%d %s %d = %d\n" % (solution_so_far, higher_num, operation, lower_num, combination) return(0) elif (depth > 0): insort(new_seeds, combination) seeds_tuple = tuple(new_seeds) if (seeds_tuple in hash_table): pass else: hash_table[seeds_tuple] = 1 new_soln_so_far = ("%s%d %s %d = %d\n" % (solution_so_far, higher_num, operation, lower_num, combination)) if (solve_list(new_seeds, target, depth - 1, new_soln_so_far) == 0): #--------------------------------------------- # Success! #--------------------------------------------- return(0) #----------------------------------------------------- # Remove the value that we made out of our number # pair, in preparation for the next try. #----------------------------------------------------- new_seeds.remove(combination) #----------------------------------------------------------------- # Didn't solve it. #----------------------------------------------------------------- return(1) #--------------------------------------------------------------------- # OK, let's go. Get the puzzle, and solve it. The last argument is # the target and the others are the seeds. #--------------------------------------------------------------------- original_seeds = map(int, argv[1:-1]) target = int(argv[-1]) start_time = time() failed = 1; if target in original_seeds: print "Target is amongst seeds!" else: original_seeds.sort() #----------------------------------------------------------------- # First look for one-step solutions, then for two-step solutions, # etc. That way we always get a shortest solution first. #----------------------------------------------------------------- for depth in xrange(len(original_seeds)): hash_table = {} failed = solve_list(original_seeds, target, depth, "") if (failed == 0): break if (failed != 0): print "No solution!" print "Took %.3f seconds" % (time() - start_time) From martin at marcher.name Thu Jan 24 17:41:57 2008 From: martin at marcher.name (Martin Marcher) Date: Thu, 24 Jan 2008 23:41:57 +0100 Subject: Email module, how to add header to the top of an email? References: <97c04812-3b66-4d84-9e92-21de72a3ca56@c23g2000hsa.googlegroups.com> Message-ID: On Thursday 24 January 2008 20:32 David Erickson wrote: > I have been using the Email module and Message class for awhile, > however I have been unable to find a way to add a header to the top of > the email similar to what is done with Received: headers... the > add_header method only appends to the bottom. ?Is there someway this > can be done? if by bottom you mean added as the "new last" header than you don't have to care, afaik email headers do not have a notion of order e.g To: bob at example.com From: alice at example.com is equal to From: alice at example.com To: bob at example.com if by bottom you mean it's appended to the body...well that is a problem :) hth martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From sjmachin at lexicon.net Mon Jan 21 04:16:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jan 2008 01:16:15 -0800 (PST) Subject: eucledian dist calculations References: <87aff9a8-a9d8-4236-8a86-66aa58417792@i72g2000hsd.googlegroups.com> Message-ID: <13c59b0c-534a-4a4a-bad3-f6f51721ab78@n20g2000hsh.googlegroups.com> On Jan 21, 6:44 pm, nodrogbrown wrote: > hi > i am using python to do some image data calculations..I use the > following numpy.ndarrays ,(i have given their shapes and ranks) > > weights=ndarray :shape(100,30),ndim=2 will have vals like > 2458121847.49 (of type 'numpy.float64') > input_weight=ndarray :shape(30,),ndim=1 (similar to above but diff > vals) > distance =ndarray :shape(30,),ndim=1 > mindistance==ndarray :shape(30,),ndim=1 > > now i am calculating the euclidian distance of 'input_weight' from > 'weight' > since this is the cumulative diff i do this in this way > > > for image in range(100): > temp=0.0 > for j in range(30): > distance[j]=abs(input_weight[j]-weights[image,j]) > > if(image==0): > #at the start copy from distance to mindistance > mindistance=distance.copy() > if (sum(mindistance) > sum(distance)): > imgindex=image # i use this later to access a list > mindistance=distance.copy() > > # now normalise the mindistance > array > if (max(mindistance) > 0.0): > mindistance=mindistance/(max(mindistance)) > > dist=sum(mindistance) > > > > this gives me the correct results Are you sure? What happens if the vector with the smallest sum(distance) is the first one? > but i am worried if this is a bit > unpythonish? > (been a java programmer for a long time..) i wd like to know if there > is a better way 1. 'temp' is not used 2. Lose the superfluous parentheses in 'if' statements 3. Put space around operators 4. I've never used any of numpy & friends, but: (a) Can't you replace the inner loop with something like this: distance = abs(input_weight - weights[image, :]) (b) I doubt that you need the .copy() 5. Lose the hard-wired numbers like 30 and 100 6. Put it inside a function and *TEST* it The word you were looking for is 'unpythonic', but the principles behind the above apply to any language. HTH, John From d.l.goldsmith at gmail.com Mon Jan 7 17:37:12 2008 From: d.l.goldsmith at gmail.com (dgoldsmith_89) Date: Mon, 7 Jan 2008 14:37:12 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python Message-ID: Can anyone point me to a downloadable open source English dictionary suitable for programmatic use with python: I'm programming a puzzle generator, and I need to be able to generate more or less complete lists of English words, alphabetized. Thanks! DG From deets at nospam.web.de Tue Jan 22 09:52:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 15:52:02 +0100 Subject: isgenerator(...) - anywhere to be found? References: Message-ID: <5vme8iF1mqjl6U1@mid.uni-berlin.de> Jean-Paul Calderone wrote: > On Tue, 22 Jan 2008 15:15:43 +0100, "Diez B. Roggisch" > wrote: >>Jean-Paul Calderone wrote: >> >>> On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" >>> wrote: >>>>For a simple greenlet/tasklet/microthreading experiment I found myself >>>>in the need to ask the question >>>> >>>> [snip] >>> >>> Why do you need a special case for generators? If you just pass the >>> object in question to iter(), instead, then you'll either get back >>> something that you can iterate over, or you'll get an exception for >>> things that aren't iterable. >> >>Because - as I said - I'm working on a micro-thread thingy, where the >>scheduler needs to push returned generators to a stack and execute them. >>Using send(), which rules out iter() anyway. > > Sorry, I still don't understand. Why is a generator different from any > other iterator? Because you can use send(value) on it for example. Which you can't with every other iterator. And that you can utizilize to create a little framework of co-routines or however you like to call it that will yield values when they want, or generators if they have nested co-routines the scheduler needs to keep track of and invoke after another. I'm currently at work and can't show you the code - I don't claim that my current approach is the shizzle, but so far it serves my purposes - and I need a isgenerator() Diez From mr.cerutti at gmail.com Mon Jan 14 09:32:16 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Mon, 14 Jan 2008 09:32:16 -0500 Subject: NotImplimentedError In-Reply-To: References: <882739.52486.qm@web63705.mail.re1.yahoo.com> Message-ID: <51302a8c0801140632h5ac589e5ya08c846ecaae61af@mail.gmail.com> On Jan 14, 2008 9:01 AM, George Sakkis wrote: > By the way, why do we need both NotImplementedError and the > NotImplemented singleton object ? Couldn't we have just one of them ? I think we need both because an unimplemented method is an error, while an unimplemented rich comparison between disparate types is (usually) not. It could be made to work with one object fulfilling both functions, but then the name would be wrong for one case or the other. -- Neil Cerutti From pavlovevidence at gmail.com Tue Jan 8 11:13:33 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 8 Jan 2008 08:13:33 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <7c77bd1c-3930-4078-b687-12cc7df849a9@d21g2000prf.googlegroups.com> On Jan 7, 6:29 pm, MRAB wrote: > On Jan 7, 5:40 pm, Martin Marcher wrote:> MartinRineh... at gmail.com wrote: > > > The best thing about Python is _______. > > > it's pythonicness. > > I think it sounds better as "its pythonicity". Mixing Greek and Latin suffixes usually works better than mixing Greek and Germanic, doesn't it. Carl Banks From asmodai at in-nomine.org Thu Jan 17 13:27:12 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 17 Jan 2008 19:27:12 +0100 Subject: working with a subversion repo In-Reply-To: <0e4caa20-1080-41fb-8e77-610c0e61af48@t1g2000pra.googlegroups.com> References: <7f156399-d9ae-4f13-a80f-0ffe41d89427@s12g2000prg.googlegroups.com> <0e4caa20-1080-41fb-8e77-610c0e61af48@t1g2000pra.googlegroups.com> Message-ID: <20080117182712.GO61556@nexus.in-nomine.org> -On [20080117 19:04], Luke (Luke.Visinoni at gmail.com) wrote: >Does that mean that libsvn and svn are not modules? If they are modules, >where can I find documentation for them? What do they do? They are modules, but not part of a standard install. Subversions uses a program called SWIG to generate APIs for various languages (perl, python, ruby for example). The libsvn/svn modules you see in site-packages are generated from Subversion's API by SWIG. So you need to install, for most operating systems, the Subversion-Python package in order to get these modules. I am sure the Subversion project has adequate documentation on this on their website. Just look for documentation on their (SWIG) bindings. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ I was searching through the Heavens and somehow I slipped... From secretquiet.423 at gmail.com Thu Jan 3 05:41:41 2008 From: secretquiet.423 at gmail.com (secretquiet.423 at gmail.com) Date: Thu, 3 Jan 2008 02:41:41 -0800 (PST) Subject: sexi girl Message-ID: sexi girl bollywood music video You can download latest videos of bollywood 2006. You may share your files with us. Adult contents shouldn't be there.Thanks ************************************************* http://www.geocities.com/lordsnile ************************************************* From arnodel at googlemail.com Fri Jan 4 06:19:44 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 4 Jan 2008 03:19:44 -0800 (PST) Subject: adding class functionality, nested scoping References: Message-ID: On Jan 4, 10:43?am, jh... at gmx.de wrote: > Hi, Hi [...] > # Does not work: all enhanced methods only call the last wrapped originial > # method. It seems the name 'method' in the surrounding scope of the > # def _(...) function definition only refers to the last loop value(?) > def ERRONEOUS_enhance_all_methods(cls, replacement): > ? ? for methodname in cls.__dict__: > ? ? ? ? if not methodname.startswith("__"): > ? ? ? ? ? ? method = getattr(cls, methodname) > ? ? ? ? ? ? def _f(*args, **kwargs): > ? ? ? ? ? ? ? ? return replacement(method, *args, **kwargs) > ? ? ? ? ? ? _f.__name__ = methodname > ? ? ? ? ? ? setattr(cls, methodname, types.MethodType(_f, None, cls)) > This is normal: After ERRONEOUS_enhance_all_methods is called, the value method is the one from the last iteration of the loop. All subsequent references to 'method' (in function _f) will return that last value. To solve this problem you need to fix the object 'method' is bound to in function _f: def enhance_all_methods(cls, replacement): # The following binds 'method' to its current value in _f def replace(method): def _f(*args, **kwargs): return replacement(method, *args, **kwargs) return _f for methodname in cls.__dict__: if not methodname.startswith("__"): _f = replace(getattr(cls, methodname)) _f.__name__ = methodname setattr(cls, methodname, types.MethodType(_f, None, cls)) Of course this looks more like your first version, which trims down to the following and is probably a better option: def enhance_all_methods(cls, replacement): for methodname in cls.__dict__: if not methodname.startswith("__"): enhance_method(cls, methodname, replacement) HTH -- Arnaud From rong.xian at gmail.com Thu Jan 24 01:52:22 2008 From: rong.xian at gmail.com (glacier) Date: Wed, 23 Jan 2008 22:52:22 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> Message-ID: On 1?24?, ??1?41?, Ben Finney wrote: > Ben Finney writes: > > glacier writes: > > > > I use chinese charactors as an example here. > > > > >>>s1='???' > > > >>>repr(s1) > > > "'\\xc4\\xe3\\xba\\xc3\\xc2\\xf0'" > > > >>>b1=s1.decode('GBK') > > > > My first question is : what strategy does 'decode' use to tell the > > > way to seperate the words. I mean since s1 is an multi-bytes-char > > > string, how did it determine to seperate the string every 2bytes > > > or 1byte? > > > The codec you specified ("GBK") is, like any character-encoding > > codec, a precise mapping between characters and bytes. It's almost > > certainly not aware of "words", only character-to-byte mappings. > > To be clear, I should point out that I didn't mean to imply static > tabular mappings only. The mappings in a character encoding are often > more complex and algorithmic. > > That doesn't make them any less precise, of course; and the core point > is that a character-mapping codec is *only* about getting between > characters and bytes, nothing else. > > -- > \ "He who laughs last, thinks slowest." -- Anonymous | > `\ | > _o__) | > Ben Finney- ??????? - > > - ??????? - thanks for your respoonse:) When I mentioned 'word' in the previous post, I mean character. According to your reply, what will happen if I try to decode a long string seperately. I mean: ###################################### a='???'*100000 s1 = u'' cur = 0 while cur < len(a): d = min(len(a)-i,1023) s1 += a[cur:cur+d].decode('mbcs') cur += d ###################################### May the code above produce any bogus characters in s1? Thanks :) From lefevrol at yahoo.com Sun Jan 27 13:58:27 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Sun, 27 Jan 2008 19:58:27 +0100 Subject: read and readline hanging In-Reply-To: <5vuv9iF1o6ambU2@mid.uni-berlin.de> References: <5vuv9iF1o6ambU2@mid.uni-berlin.de> Message-ID: > The `trheading` module is modeled after Java's threading API. OK. Thanks for the hint. However BufferedReader.readline() does not block in Java, so it is still difficult to transpose. >> But how can I find out *programmatically* that there is no more >> input? > > You can't. How do people handle this, then? Reading from a process that will block if you ask too much yet won't let you know how much there is to read right now has to be some kind of FAQ. > This doesn't answer if the interpreter doesn't flush its output buffer > after every line. I think it must otherwise you might get incomplete answers or no answers at the interactive prompt and that never happens. It may not flush its buffer after every line but it must flush them at the end of an answer. -- O.L. From mr.cerutti at gmail.com Wed Jan 16 09:42:33 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 16 Jan 2008 09:42:33 -0500 Subject: Python help for a C++ programmer In-Reply-To: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> References: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> Message-ID: <51302a8c0801160642r4b8f3fc1h88263863ab505849@mail.gmail.com> On Jan 16, 2008 9:23 AM, mlimber wrote: > I'm writing a text processing program to process some survey results. > I'm familiar with C++ and could write it in that, but I thought I'd > try out Python. I've got a handle on the file I/O and regular > expression processing, but I'm wondering about building my array of > classes (I'd probably use a struct in C++ since there are no methods, > just data). > > I want something like (C++ code): > > struct Response > { > std::string name; > int age; > int iData[ 10 ]; > std::string sData; > }; > > // Prototype > void Process( const std::vector& ); > > int main() > { > std::vector responses; > > while( /* not end of file */ ) > { > Response r; > > // Fill struct from file > r.name = /* get the data from the file */; > r.age = /* ... */; > r.iData[0] = /* ... */; > // ... > r.sData = /* ... */; > responses.push_back( r ); > } > > // Do some processing on the responses > Process( responses ); > } > > What is the preferred way to do this sort of thing in Python? It depends on the format of your data (Python provides lots of shortcuts for handling lots of kinds of data), but perhaps something like this, if you do all the parsing manually: class Response(object): def __init__(self, extern_rep): # parse or translate extern_rep into ... self.name = ... self.age = ... # Use a dictionary instead of parallel lists. self.data = {...} def process(self): # Do what you need to do. fstream = open('thedatafile') for line in fstream: # This assumes each line is one response. Response(line).process() -- Neil Cerutti From theller at ctypes.org Wed Jan 9 18:06:00 2008 From: theller at ctypes.org (Thomas Heller) Date: Thu, 10 Jan 2008 00:06:00 +0100 Subject: for loop without variable In-Reply-To: References: Message-ID: erik gartz schrieb: > Hi. I'd like to be able to write a loop such as: > for i in range(10): > pass > but without the i variable. The reason for this is I'm using pylint > and it complains about the unused variable i. Pychecker won't complain if you rename 'i' to '_', IIRC: for _ in range(10): pass Thomas From eefacm at gmail.com Mon Jan 14 18:00:52 2008 From: eefacm at gmail.com (eefacm at gmail.com) Date: Mon, 14 Jan 2008 15:00:52 -0800 (PST) Subject: Perl Template Toolkit: Now in spicy new Python flavor Message-ID: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> I'd like to inform the Python community that the powerful and popular Template Toolkit system, previously available only in its original Perl implementation, is now also available in a beta Python implementation: http://tt2.org/python/index.html I created this port both as a fun programming project, and for use in environments where Perl is not available, for reasons technical, cultural, or otherwise. The extensive Perl test suites have also been ported, and most templates require no or very little modification. Discussion of the Python implementation should be conducted on the main Template Toolkit developer mailing list; see the site above for details. From mr.cerutti at gmail.com Fri Jan 18 10:12:34 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 18 Jan 2008 10:12:34 -0500 Subject: Filtering two files with uncommon column In-Reply-To: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> Message-ID: <51302a8c0801180712m60c0019dk52a51d740416324c@mail.gmail.com> On Jan 18, 2008 4:23 AM, Madhur wrote: > I would like to know the best way of generating filter of two files > based upon the following condition As a bit of friendly advice, you'll get much more useful assistance if you post your code. If you don't have any code to show, write some. Unless it's a quine, a program won't write itself. -- Neil Cerutti From israelu at elbit.co.il Tue Jan 29 01:01:16 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 28 Jan 2008 22:01:16 -0800 (PST) Subject: A question about osyco References: <606hucF1p0rptU1@mid.uni-berlin.de> <4e8bd7b3-29d2-4fcc-baad-7e6ecfe829c4@v4g2000hsf.googlegroups.com> Message-ID: <2f24b4c6-0a62-4623-b96d-ea44f003eedd@m34g2000hsf.googlegroups.com> On Jan 29, 1:48?am, bearophileH... at lycos.com wrote: > Marc 'BlackJack' Rintsch: > > > Try calling the iterative one twice and measure the time of the second > > call. ?IIRC psyco needs at least one call to analyze the function, so the > > first call is not speed up. > > That's how Java HotSpot works, but Psyco is very different from > HotSpot, and I think you are wrong. > I don't exactly know the answer to the question of the OP, but I think > the two functions are different: in the second function most time > isn't spent in managing the xrange or in the assign, but in the sum > between long ints, and Psyco can't speed up that operation (you need > gmpy for that, and in certain tricky situations gmpy may even result > slower, maybe when you use small numbers). > > Bye, > bearophile Thanks, that's probably it I've tested >>> timeit.Timer('c+d', 'from __main__ import c, d').timeit(1000) 6.6209532214145383e-005 >>> timeit.Timer('a+b', 'from __main__ import a, b').timeit(1000) 0.10513989906537802 >>> where c and d are equal to 1, and a, b are very long integers (a=b=fib2(100000)) From gregcorradini at gmail.com Tue Jan 29 14:07:34 2008 From: gregcorradini at gmail.com (Greg Corradini) Date: Tue, 29 Jan 2008 11:07:34 -0800 (PST) Subject: Mx.ODBC insert error In-Reply-To: References: <15163149.post@talk.nabble.com> Message-ID: <15166795.post@talk.nabble.com> Thanks John. I now see it John Machin wrote: > > On Jan 30, 3:27 am, Greg Corradini wrote: >> Hello, >> I've never gotten this traceback error before using mx.ODBC. > > "traceback error"?? I see no problem with the traceback. > >> Any ideas about >> resolving this issue? The statement and the error it generates are listed >> below. > > The error was "generated" by you. The error message was generated by > "[Microsoft][ODBC Microsoft Access Driver]" > >> >> curse.execute("Insert into FHWA_StandSamp_2008(LRS_ID_NEW) >> values('0402000010') where LRS_ID = '0403700010'") >> >> Traceback (most recent call last): >> File "", line 1, in ? >> curse.execute("Insert into FHWA_StandSamp_2008(LRS_ID_NEW) values >> ('0402000010') where LRS_ID = '0403700010'") >> ProgrammingError: ('37000', -3516, '[Microsoft][ODBC Microsoft Access >> Driver] Missing semicolon (;) at end of SQL statement.', 4612) >> > > Like it says, ProgrammingError. > > Try > INSERT INTO table (columns) VALUES (values) > or > INSERT INTO table (columns) > SELECT stuff FROM somewhere [WHERE boolean_expression] .... > or perhaps even > UPDATE table SET column = expression WHERE boolean_expression > > Perhaps you could consider avoiding combining random fragments of SQL > or English and hoping for tolerant fuzzy parsing by the recipient :-) > > HTH, > John > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Mx.ODBC-insert-error-tp15163149p15166795.html Sent from the Python - python-list mailing list archive at Nabble.com. From steve at REMOVE-THIS-cybersource.com.au Fri Jan 4 21:30:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 05 Jan 2008 02:30:41 -0000 Subject: Questions about subclassing an int References: <38614926-19fe-49f8-aa08-fe68449aae70@f3g2000hsg.googlegroups.com> Message-ID: <13ntquhaucon89@corp.supernews.com> On Fri, 04 Jan 2008 15:36:27 -0800, Arnaud Delobelle wrote: > > Now it's no longer a syntax error but I don't see why it's different? > > Same as above, though I don't understand why you get a SyntaxError for T > and a TypeError for R. AFAICT both shoult give a TypeError. Probably because it was never a SyntaxError in the first place. If you execute the code given for T, it gives a TypeError, just as you would expect. Possibly the Original Poster had mistyped something at some point and got a SyntaxError, or more likely he's just using "syntax error" to mean "some exception which I haven't actually looked at". -- Steven From jatinpatni at gmail.com Wed Jan 9 10:28:51 2008 From: jatinpatni at gmail.com (jatin patni) Date: Wed, 9 Jan 2008 15:28:51 +0000 Subject: Re(Thanks...Re: Problem in the program flow...please help?) Message-ID: Thanks Jerry..For the link...I am looking into it... On Jan 9, 2008 2:36 PM, Jerry Hill wrote: > On Jan 9, 2008 7:44 AM, jatin patni wrote: > > I have a button(GUI) which when clicked, calls a function connect( ) > which > > takes around 5-20 seconds to complete(As I mentioned Earlier) > > The problem is, during this time the other part of the code is rendered > > useless, I cannot access other parts of the code, for example a cancel( > ) > > function to be called when cancel button is pressed, cannot be pressed > until > > the previous function is completed and moreover the GUI hangs(stops > > responding). > > See http://wiki.wxpython.org/LongRunningTasks for a discussion of some > of the ways you can deal with this. > > -- > Jerry > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Tue Jan 15 16:32:52 2008 From: nagle at animats.com (John Nagle) Date: Tue, 15 Jan 2008 13:32:52 -0800 Subject: "env" parameter to "popen" won't accept Unicode on Windows -minor Unicode bug In-Reply-To: <5v3qtsF1khn11U1@mid.uni-berlin.de> References: <478bfcb0$0$36378$742ec2ed@news.sonic.net><5v2cudF1k5a1oU1@mid.individual.net><478c551a$0$36354$742ec2ed@news.sonic.net> <5v3dq9F1k2577U1@mid.uni-berlin.de> <5v3qtsF1khn11U1@mid.uni-berlin.de> Message-ID: <478d2569$0$36379$742ec2ed@news.sonic.net> Diez B. Roggisch wrote: > Brian Smith wrote: > >> Diez B. Roggisch wrote: >>> Sure thing, python will just magically convert unicode to the >>> encoding the program YOU invoke will expect. Right after we >>> introduced the >>> >>> solve_my_problem() >>> >>> built-in-function. Any other wishes? >> There's no reason to be rude. > > If you'd know John, you'd know there is. ? >> Anyway, at least on Windows it makes perfect sense for people to expect >> Unicode to be handled automatically. popen() knows that it is running on >> Windows, and it knows what encoding Windows needs for its environment >> (it's either UCS2 or UTF-16 for most Windows APIs). At least when it >> receives a unicode string, it has enough information to apply the >> conversion automatically, and doing so saves the caller from having to >> figure out what exact encoding is to be used. > > > For once, the distinction between windows and other platforms is debatable. > I admit that subprocess contains already quite a few platform specific > aspects, but it's purpose is to abstract these away as much as possible. > > However, I'm not sure that just because there are wide-char windows apis > available automatically means that using UCS2/UTF-16 would succeed. A look > into the python sources (PC/_subprocess.c) reveals that someone already > thought about this, but it seems that just setting a > CREATE_UNICODE_ENVIRONMENT in the CreateProcess-function should have been > easy enough to do it if there weren't any troubles to expect. The problem is that only the NT-derived Microsoft systems talk Unicode. The DOS/Win16/Win9x family did not. But they did have CreateProcess. So the current code will handle Win9x, but not Unicode. When do we drop support for Win9x? It probably has to happen in Python 3K, since that's Unicode-everywhere. John Nagle From deets at nospam.web.de Thu Jan 24 04:36:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Jan 2008 10:36:22 +0100 Subject: Increment Variable Name In-Reply-To: <13pfkt53kq7jo7c@corp.supernews.com> References: <5vq0rjF1o724kU1@mid.uni-berlin.de> <13pfkt53kq7jo7c@corp.supernews.com> Message-ID: <5vr4gpF1nj41eU1@mid.uni-berlin.de> Grant Edwards schrieb: > On 2008-01-23, Diez B. Roggisch wrote: >> David Brochu schrieb: >>> This is probably really trivial but I'm stumped.... :-( >>> >>> Does anyone know how to increment a variable name? >>> >>> For example: >>> >>> I know the length of a list and I want to pass each element of a list to >>> a unique variable, thus I want to increment variable names. If the list >>> length = 4, i want to have the following variables: var1, var2, var3, var4. >>> >> Use a dictionary >> >> value_dict = {} >> >> for i, value in values: >> value_dict["var%i" % i] = value > > That assumes that the OPs "list" is actually a list of tumples: Tumples? :) I forgot the enumerate... Diez From arkanes at gmail.com Wed Jan 2 13:29:07 2008 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 2 Jan 2008 12:29:07 -0600 Subject: ElementTree should parse string and file in the same way In-Reply-To: References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> Message-ID: <4866bea60801021029s2f4b36b4s1e114e7ae5255844@mail.gmail.com> On Jan 2, 2008 8:56 AM, Fredrik Lundh wrote: > Steven D'Aprano wrote: > > > Fredrik, if you're reading this, I'm curious what your reason is. I don't > > have an opinion on whether you should or shouldn't treat files and > > strings the same way. Over to you... > > as Diez shows, it's all about use cases. > > and as anyone who's used my libraries or read my code knows, I'm a big > fan of minimalistic but highly composable object API:s and liberal use > of short helper functions to wire them up to fit the task at hand. > > kitchen sink API design is a really bad idea, for more reasons than I > can fit in this small editor window. > On that note, I really don't like APIs that take either a file name or a file object - I can open my own files, thanks. File objects are fantastic abstractions and open(fname) is even shorter than StringIO(somedata). My take on the API decision in question was always that a file is inherently an XML *document*, while a string is inherently an XML *fragment*. From gagsl-py2 at yahoo.com.ar Sun Jan 27 12:44:48 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 15:44:48 -0200 Subject: How to modify the content of an email References: <3f39a8c3-7e47-4971-84db-f26f03e0abae@d70g2000hsb.googlegroups.com> Message-ID: En Fri, 25 Jan 2008 20:59:41 -0200, escribi?: > Hello, I'm trying to make a python script that take an email in (raw) > text format, and add a footer to the text (or html) body of the email. > > I'm aware of the email and email.mime modules, but I can't figure out > how to identify 'the main text (or html) content' from the email, and > how to be sure that I don't incorrectly identify a txt (or html) > attach as the main content of the email. > By 'main text (or html) content' I mean the text (or html) that is > showed by a Mail User Agent when it display the email to the > recipient. I suggest you read or overview the MIME specification (RFC 2045 and a few others), or some introductory text, in order to understand the terminology and what the email package does. Simple messages have is_multipart()==False and get_payload() gives you the message text. Multipart messages (e.g. having attachments, or an html/plaintext alternative) have is_multipart()==False and get_payload() returns a list of its parts. The parts may be Messages too, and can be multipart also. HTML messages usually have Content-Type: multipart/alternative, coming first the text part and later the HTML part. You probably will have to modify both, because it's up to the MUA to decide which part to show. When you modify an existing part you have to *remove* some headers like Content-Transfer-Encoding if you don't honor them in the replaced part. By example, the original may have been encoded in base64 or quoted-printable (but you didn't notice that because Python decoded the part for you). -- Gabriel Genellina From timr at probo.com Sat Jan 12 00:51:27 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 12 Jan 2008 05:51:27 GMT Subject: Image/Video Processing in Python References: <68c3707e-1c37-470d-9408-80819103959a@e6g2000prf.googlegroups.com> Message-ID: <28lgo3t65s1ln6s2tlj1kbmpsh7arphcha@4ax.com> "dongie.agnir at gmail.com" wrote: > >Hello, I'm trying to work on a project in Python that involves the use >of a webcam to track a laser pointer. I found some example code here >http://janto.blogspot.com/2006/01/motion-capture-in-python.html, but >the problem is that it's quite slow (about a sec to process a 800 by >600 image). Can anyone who has experience with computer vision help >me? Are there any existing algorithms for finding a color in an image >and plotting its coordinates? It would help me very much. You're talking about raw number crunching. This is exactly the kind of case where you should write some C or C++ code and call it from Python. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From waldemar.osuch at gmail.com Wed Jan 9 17:52:09 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Wed, 9 Jan 2008 14:52:09 -0800 (PST) Subject: Another dumb scope question for a closure. References: Message-ID: On Jan 9, 11:47 am, "Steven W. Orr" wrote: > So sorry because I know I'm doing something wrong. > > 574 > cat c2.py > #! /usr/local/bin/python2.4 > > def inc(jj): > def dummy(): > jj = jj + 1 > return jj > return dummy > > h = inc(33) > print 'h() = ', h() > 575 > c2.py > h() = > Traceback (most recent call last): > File "./c2.py", line 10, in ? > print 'h() = ', h() > File "./c2.py", line 5, in dummy > jj = jj + 1 > UnboundLocalError: local variable 'jj' referenced before assignment > > I could have sworn I was allowed to do this. How do I fix it? > I have seen this approach on ActiveState Cookbook but can not find a reference to it right now. >>> def inc(jj): ... def dummy(): ... dummy.jj += 1 ... return dummy.jj ... dummy.jj = jj ... return dummy ... >>> h = inc(33) >>> h() 34 >>> h() 35 >>> i = inc(12) >>> i() 13 >>> i() 14 Waldemar From mani.agape at gmail.com Tue Jan 29 22:59:29 2008 From: mani.agape at gmail.com (Manikandan R) Date: Wed, 30 Jan 2008 09:29:29 +0530 Subject: Fwd: The results of your email commands In-Reply-To: References: Message-ID: Hai, I am working with python 2.4. I am new to python, I need to collect all the ipaddress of the systems connected in the network for my project. While browsing I come accross Ur link. I think U peoples can help me. Can U please send me the code and guide me to get it. I am in dead line so can U make it fast ................ Thank's and Regard's, R.Manikandan. -------------- next part -------------- An HTML attachment was scrubbed... URL: From finite.automaton at gmail.com Fri Jan 11 09:41:06 2008 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: Fri, 11 Jan 2008 06:41:06 -0800 (PST) Subject: Help with Windows build of Yapgvb Python extension Message-ID: I'm the author of Yapgvb, a Python binding for Graphviz. Yapgvb enjoys modest success, but for some time it has been in dire need of a Python 2.5 build for Windows. I'm posting this message in the hopes of finding someone who is interested in making this build. This is a relatively quick task for someone who is comfortable with building C extensions and has an operational Windows build environment for Python 2.5 (which I don't). Alternately, it's a great way to learn about these things, and to get involved with a small open source project. Technologies used: graphviz distutils boost.python boost.graph See: http://yapgvb.sourceforge.net From jr9445 at ATT.COM Wed Jan 9 10:02:13 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 9 Jan 2008 09:02:13 -0600 Subject: 'Borg' and multiple threads. In-Reply-To: <47829a95$0$26035$88260bb3@free.teranews.com> References: <47829a95$0$26035$88260bb3@free.teranews.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 Tobiah > Sent: Monday, January 07, 2008 5:24 PM > To: python-list at python.org > Subject: 'Borg' and multiple threads. > > I have a class that I call Borg that starts like this: > > class Borg(dict): > > static_state = {} > def __init__(self): > self.__dict__ = self.static_state > > > > My question is why this seems to work. I had the idea that > there was a class object that is created when the file containing > the definition is read, which actually contains the static > information that is later accessed by instances. Isn't this > done when the cherrypy app first loads, rather than each time > a browser hits the app? Otherwise, where is the individual data > stored for each of two simultaneous hits of the web page? > I had a similar question except mine was from a bug. (Thinking in c++ lead me to inadvertently create static class vars.) You can "print self" and use the id() function to get the memory addresses of the variables and see what's going on. In the code below, mem4 is equivalent to your static_state. count = 1 class Foo: mem4 = {} mem5 = {} def __init__(self): self.mem = {} global count count += 1 self.mem2 = count self.mem3 = "%x" % (id(self)) self.mem5 = {} print 'init count =', count def me(self): print "object: ", self print "\tid(self.mem) %x" % (id(self.mem)), " self.mem =", self.mem print "\tid(self.mem2) %x" % (id(self.mem2)), " self.mem2 =", self.mem2 print "\tid(self.mem3) %x" % (id(self.mem3)), " self.mem3 =", self.mem3 print "\tid(self.mem4) %x" % (id(self.mem4)), " self.mem4 =", self.mem4 print "\tid(self.mem5) %x" % (id(self.mem5)), " self.mem5 =", self.mem5 global count count += 1 print '\tcount =', count self.mem4[count] = count print "\tid(self.mem4) %x" % (id(self.mem4)), " self.mem4 =", self.mem4 #self.mem += count #print "\tid(self.mem) %x" % (id(self.mem)), " self.mem =", self.mem print a = Foo() b = Foo() c = Foo() a.me() b.me() c.me() From Frank.Aune at broadpark.no Tue Jan 15 08:59:00 2008 From: Frank.Aune at broadpark.no (Frank Aune) Date: Tue, 15 Jan 2008 14:59:00 +0100 Subject: Retrieving info from DBUS at application startup Message-ID: <200801151459.00794.Frank.Aune@broadpark.no> Hello, Detecting Hotpluggable hardware using DBUS works great, but usually peripherals are already connected when launching the application. How can I (preferably using DBUS) detect which USB printers for example are connected to the system at application launch without engaging in some insane probing activity? Thanks, Frank Aune From peter2 at hipson.net Sat Jan 12 19:18:05 2008 From: peter2 at hipson.net (PeterD) Date: Sat, 12 Jan 2008 19:18:05 -0500 Subject: *** American nationalism is FAKE and its MYTHS are LIES, YANK BASTARDS RAPED BY THEIR OWN MARINES - *** References: Message-ID: <32mio3hp9a8sj9hgbe1982rqs5t3vfro79@4ax.com> On Sat, 12 Jan 2008 11:50:07 -0800 (PST), thermate2 at india.com wrote: >THE YANK CHRISTIAN WHITE MARINE Recently in Chicago an Indian father killed his daughter, and and her two children... Why? Because she'd married without his permission. So that seems to make your and your countrymen so many steps below Americans that this becomes the stupidest thread of the year... Fortunately there are still 11 months to go for you to come wup with something better. Peter's Troll-o-Meter Not Troll Troll 0 1 2 3 4 5 6 7 8 9 10 / / / / / / / O (Pegged the needle!) From Russ.Paielli at gmail.com Mon Jan 7 23:10:58 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 7 Jan 2008 20:10:58 -0800 (PST) Subject: use fileinput to read a specific line References: Message-ID: <6f2db44c-2641-47cb-ab24-4177ccc96d6e@m77g2000hsc.googlegroups.com> On Jan 7, 7:15 pm, jo3c wrote: > hi everybody > im a newbie in python > i need to read line 4 from a header file > using linecache will crash my computer due to memory loading, because > i am working on 2000 files each is 8mb > > fileinput don't load the file into memory first > how do i use fileinput module to read a specific line from a file? > > for line in fileinput.Fileinput('sample.txt') > ???? Assuming it's a text file, you could use something like this: lnum = 0 # line number for line in file("sample.txt"): lnum += 1 if lnum >= 4: break The variable "line" should end up with the contents of line 4 if I am not mistaken. To handle multiple files, just wrap that code like this: for file0 in files: lnum = 0 # line number for line in file(file0): lnum += 1 if lnum >= 4: break # do something with "line" where "files" is a list of the files to be read. That's not tested. From socyl at 987jk.com.invalid Fri Jan 25 09:28:08 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 25 Jan 2008 14:28:08 +0000 (UTC) Subject: Text-based data inspector for Python? References: Message-ID: In Terry Jones writes: >>>>>> "kj" == kj writes: >You actually liked the perl debugger... gasp! Still do, in fact!. >OK, I used it too, but it >left a few things to be desired... I'd love to read your thoughts on the matter. My biggest complain about it is that its underlying code is very poorly designed and it's having a difficult time keeping up with the language. With each new version of Perl it springs new leaks, unfortunately. For example, it's much worse than Perl itself at dealing with Unicode. ...And its documentation is probably the worst of all of the core Perl docs. Let's see, what else...? Nothing else comes to mind at the moment. >I use M-x pydb to debug python from inside emacs. I like it more than the >straight pdb as it's a bit more like gdb. >In pydb (and pdb) there's p and pp to print and pretty print a python >object. They work pretty well & there's no need for the mouse. Thank you much for the tip. I just skimmed over its documentation and I'm looking forward to using it. The one thing I couldn't find, and would greatly miss if not available, is the ability to set breakpoints by inserting a particular indication right in the code. In the Perl debugger one can insert something like the following anywhere in the code: $DB::single = 1; When such a line executes, the debugger immediately switches to single-step mode. It's a very flexible technique, and I like it a lot more than setting breakpoints the "usual" way (i.e. "b [line] [condition]"). For example, for a conditional breakpoint one can do something like: $DB::single = some_boolean_test(); Or if one isn't sure exactly when one wants to stop at the location, one can just write: $DB::single = ( $::SOME_GLOBAL_VARIABLE || 0 ); (The "|| 0" is there so that the debugger won't complain over assigning an undefined RHS in the assignment.) If while stopped at some other breakpoint, and perhaps having inspected some data, we decide that it's time to stop at this line, we just assign 1 to the global, hit the old "c"(ontinue), and one's there. In fact, setting $DB::single is the only way I know to have a breakpoint in code that executes at compile time (such as anything in a BEGIN block and any top-level code in modules imported via the "use" directive). Setting a breakpoint with b at such points and restarting the program won't work. Extremely handy. Maybe something like this (or even better!) is already possible in pydb, but I couldn't find it. If it is, though, I'll be very psyched. kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From gagsl-py2 at yahoo.com.ar Mon Jan 28 19:15:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Jan 2008 22:15:56 -0200 Subject: post variable References: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> <87ir1dr8ms.fsf@mulj.homelinux.net> <0f634854-7d7a-4ad8-ba04-38d239ecf850@d70g2000hsb.googlegroups.com> Message-ID: En Mon, 28 Jan 2008 19:32:45 -0200, pavloutefkros at gmail.com escribi?: > 1. yes i've tried that technique but its annoying, the user can easily > stop the redirection and not "elegant". > > 2. yes i'm aware of that, however what i've mentioned above is just an > example, it's actually way more serious. See this sequence: User POSTs a form Web app processes the form. Web app updates its internal state. Web app don't output anything, and finishes the POST handling with a redirect (implicit GET) Browser receives the redirect and issues a GET request Web app returns content The important thing is that a POST request *never* returns content, always redirects. All content is retrieved using GET. -- Gabriel Genellina From tjreedy at udel.edu Mon Jan 28 22:27:33 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jan 2008 22:27:33 -0500 Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: "Paddy" wrote in message news:4dc87a25-1d90-4b66-8fa4-d0d41f48344e at i29g2000prf.googlegroups.com... |I would value the opinion of fellow Pythoneers who have also | contributed to Wikipedia, on the issue of "Is Python Standardized". Depends entirely on the operative meaning of standardized. Formal standards body? Obviously no. Specified in a standard-setting document? Yes. In fact, in someways, Python is better standardized that C, for instance, in that the Python standard usefully standardizes some things that the C standard leaved unstandardized as 'implementation defined'. Example 1. Order of evaluation of function arguments. Python: left to right. C: undefined (and unstandardized), I believe. Example 2: Strings for Infinity and Not-A-Number. Python: will standardize in 2.6 to hide the variation in C implementations (or is Microsoft just non-compliant here?). From paul at boddie.org.uk Wed Jan 30 18:59:00 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 30 Jan 2008 15:59:00 -0800 (PST) Subject: Trying to understand Python web-development References: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com> <2bb822db-0a33-4c47-bdd1-f4980a73fc00@m34g2000hsf.googlegroups.com> <85a24948-9e59-4b74-95e8-6d9c75e9bff7@e23g2000prf.googlegroups.com> Message-ID: On 30 Jan, 21:27, walterbyrd wrote: > Thanks for all that posts. This thread has been helpful. > > I have seen a lot of posts about the importance of decoupling the > deployment technologies from the framework technologies. This is how I > have done that in PHP. I develop on my home box. When I get something > working the way I want, I ftp those files to the remote server. To me, > that seems to make more sense that trying to run two different web > servers on the same system. My PHP system involves no monkeying with > special config files, or running special servers to couple the > different environments, or setting special ports, or paths. For PHP > development, I don't even need ssh access. Various solutions like WebStack or WSGI should permit you to choose Apache and/or other servers and hopefully not notice big differences in your application. Various WebStack examples should run out of the distribution, admittedly using their own server processes, and there's plenty of choice when it comes to configuration complexity across the supported server technologies (CGI, mod_python, Java Servlet, and so on). Perhaps the range of WSGI adapters offer a similar range of choices. In short, flexibility is definitely here for Python Web frameworks. I'd agree that PHP is usually configured to be as easy to deploy as possible, but I guess that's because the (admittedly straightforward) configuration is typically already done for users of shared hosting. I've just got into a shared hosting situation, and PHP is set up alongside CGI and static pages - you just drop the files into the directory and Apache serves them up according to their filename extensions. To configure mod_python isn't that much harder, but there are some tricky elements which often defeat people. However, some hosting providers (such as mine) do make it just as easy, but just not at less than $1 per month. > > I think that this (the ease of PHP application deployment) is one of > > the things that keeps Python framework developers up at night > > I think you may have something there. For $10 a year I can get an > account at dollar-hosting.net, copy some php files there, and that's > all there to it. I have been beating my brains out trying to get > anything working with a python framework, and I have not been able to > do it. I even bought VPS hosting just for the sake of python > development. I have to admit that I've only fairly recently had experiences with getting Django and MoinMoin working from scratch, and the latter is mostly set up on Ubuntu systems if you install the package and know how to add a site to the Apache configuration. My observation with regard to Django 0.96 (at least, and perhaps 1.0 is a bit better) is that there's a lot of stuff that I'm moderately comfortable with - setting up mod_python, for example - but I'd be really put off doing any of it if I hadn't had the experience of doing it (and troubleshooting it) before. MoinMoin seems to be easier: you just have to copy the files into the right places. It's a lot nicer than some other solutions, notably "old school" Perl applications, which need lots of Apache tweaking to avoid easily overlooked insecurity issues. Nevertheless, there's potential for making mistakes, having the wrong permissions, and so on. > But, I still can not seem to make the quantum leap of > getting something that works locally, to work remotely. BTW: with the > VPS hosting, I had to install and configure my own web-hosting and > PHP, including setting up lighttpd with fastcgi and php modules - and > I still found that much easier than getting anything to work with > python. System packages of Python frameworks should mostly leave you with only a bit of configuration file editing to do, perhaps with some database initialisation where necessary, but I suppose that some frameworks don't have up-to-date-enough packages. Even then, perhaps it's the last bit which causes the most problems - you'll have to remind us where you got stuck, I think. Paul From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 21:40:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 02:40:34 -0000 Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> <13og1lgcespv6c2@corp.supernews.com> Message-ID: <13oga52q3f2gg1c@corp.supernews.com> On Fri, 11 Jan 2008 17:36:10 -0800, Michael Tobis wrote: > On Jan 11, 6:15 pm, Steven D'Aprano cybersource.com.au> wrote: >> Your users are *scientists*, and you don't trust their intellectual >> ability to learn a programming language as simple as Python? >> >> Instead of spending time and effort writing, debugging and maintaining >> such a fragile approach, why not invest in a couple of introductory >> books on Python programming and require your scientists to go through >> the first few chapters? Or write out a one-page "cheat sheet" showing >> them simple examples. Or, and probably most effectively, make sure all >> your classes have doc strings with lots of examples, and teach them how >> to use help(). >> >> Some people problems are best dealt with by a technical solution, and >> some are not. >> >> -- >> Steven > > I am currently talking very similar trash on my blog, See > http://initforthegold.blogspot.com/2008/01/staying-geeky.html and > http://initforthegold.blogspot.com/2007/12/why-is-climate-modeling- stuck.html > > You seem to think that learning the simple language is equivalent to > grasping the expressive power that the language provides. I do? What did I say that led you to that conclusion? > Yes, users are scientists. Therefore they do not have the time or > interest to gain the depth of skill to identify the right abstractions > to do their work. I don't follow you. If they aren't learning the skills they need to do their work, what are they doing? Hammering screws in with a hacksaw? (Metaphorically speaking.) > There are many abstractions that could be useful in science that are > currently provided with awkward libraries or messy one-off codes. I'm sure you're right. Attempts to make elegant libraries and re-usable code should be encouraged. The OP's attempt to dumb-down his library strikes me as a step in the wrong direction. > The idea that a scientist should be expected to be able to write correct > and useful Python is reasonable. I and the OP are relying on it. Please go back and look at the example the OP gave. According to the example given, his users would find this too difficult to deal with: obj1 = Obj(params1) obj2 = Obj(params2) ... bigobj = Bigobj(objects=[obj1,obj2]) bigobj.run() That's not terribly complex code, thanks to Python's easy-to-use object model. Dropping the explicit construction of the Bigobj in favour of a mysterious, implicit auto-magic run() is a serious step in the wrong direction. Any scientist working with this can see exactly what is being run(), and not have to rely on hunting through the entire source code looking for Obj() calls he might have missed. As simple as the above is, it could be made simpler. Judging from the example given, the Bigobj constructor doesn't need a keyword argument, it could just as easily take an arbitrary number of arguments: bigobj = Bigobj(obj1, obj2, obj3, obj4...) > The idea that a scientist should be expected to identify and build > clever and elegant abstractions is not. But that's their job. That's what scientists do: identify and build clever and elegant abstractions, such as Newton's Laws of Motion, Special Relativity, Evolution by Natural Selection, the Ideal Gas Laws, and so on. Even climate change models are abstractions, and we would hope they are clever and elegant rather than stupid and ugly. > If you think every scientist can > be a really good programmer you underestimate at least one of what good > scientists do or what good programmers do or what existing high > performance scientific codes are called upon to do. Read the OP's post again. His (her?) users aren't expected to create the toolkit, merely to use it. To create good toolkits you need both a master programmer and an expert in the field. It is an advantage if they are the same person. But to use such a good toolkit, you shouldn't need to be a master programmer. -- Steven From ornto at nospam.org Fri Jan 18 06:04:57 2008 From: ornto at nospam.org (ornto) Date: Fri, 18 Jan 2008 12:04:57 +0100 Subject: [HELP] SMTPlib not sending my mail Message-ID: Hi, I'm trying to create an application which checks a dynamic web site and on certain events sends an email to me. My problem though is with the email task. By now I made this simple test code: #prova invio email smtpserver = smtplib.SMTP(mailserver) messaggio= "Messaggio di prova" print mail print messaggio smtpresult=smtpserver.sendmail("Watcher",mail,messaggio) if smtpresult: print smtpresult smtpserver.quit() "mailserver" and "mail" values are loaded from a ini file and they're correct. The call to smtpserver gives back no errors (smtpresult remains empty). The running enviroment gives no error. So, it looks like that the program works alloright, sending the mail- BUT, I receive no mail! I've tried to change the smtp server with another one which still works with my isp, with no luck. If I try a smtp which doesn't give me access, I correctly receive an error from the program. What might be the problem? From mensanator at aol.com Sat Jan 12 14:54:08 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Sat, 12 Jan 2008 11:54:08 -0800 (PST) Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> Message-ID: On Jan 12, 12:37?pm, marcstuart wrote: > How do I divide a list into a set group of sublist's- if the list is > not evenly dividable ? > consider this example: > > x = [1,2,3,4,5,6,7,8,9,10] > y = 3 ? ? ?# number of lists I want to break x into > z = y/x > > what I would like to get is 3 sublists > > print z[0] = [1,2,3] > print z[2] = [4,5,6] > print z[3] = [7,8,9,10] > > obviously not even, one list will have 4 elements, the other 2 will > have 3., > the overriding logic, is that I will get 3 lists and find a way for > python to try to break it evenly, if not one list can have a greater > amount of elements > > Would I use itertools ? How would I do this ? > > Thanks def list_split(x,y): dm = divmod(len(x),y) if dm[1] != 0: z = [x[i*y:i*y+y] for i in xrange(len(x)/y) if len(x[i*y:])>=2*y] z.append(x[(len(x)/y-1)*y:]) else: z = [x[i*y:i*y+y] for i in xrange(len(x)/y)] return z >>> list_split([1,2,3,4,5,6,7,8,9,10],3) [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] >>> list_split([1,2,3,4,5,6,7,8,9,10],5) [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] >>> list_split([1,2,3,4,5,6,7,8,9,10],4) [[1, 2, 3, 4], [5, 6, 7, 8, 9, 10]] >>> list_split([1,2,3,4,5,6,7,8,9,10],2) [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] From gagsl-py2 at yahoo.com.ar Sun Jan 20 15:14:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 20 Jan 2008 18:14:39 -0200 Subject: Looping through the gmail dot trick References: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> Message-ID: En Sun, 20 Jan 2008 14:38:06 -0200, Joshua Gilman escribi?: > My task is this: Loop through an email and create as many combinations of > periods as possible. So all the combinations for blah would be: > > b.lah > bl.ah > bla.h > b.l.ah > b.la.h > bl.a.h I'd use a recursive generator (the divide-and-conquer approach): def genalldots(txt): if len(txt)<=1: yield txt else: head, tail = txt[0], txt[1:] for item in genalldots(tail): yield head+item yield head+'.'+item print sorted(genalldots('blah')) (I got your six spellings above, plus 'blah' and 'b.l.a.h') > I'm still rather new to python so this is turning out to be rather > tricky. > My current code is as follows: > > for d in range(1, len(email)): >> for i in range(1, len(email)): >> y = i >> temail = email >> for x in range(d): >> if email[y] == '.': break >> temail = temail.replace(email[y], '.' + email[y]) >> if not y > len(email) - 2: y += 1 >> print temail The replace function is dangerous, in case a letter appears more than once, you are replacing all instances. Anyway, since you *know* you want to replace the y-th item, just do: temail = temail[:y] + '.' + temail[y:] -- Gabriel Genellina From nikolaskaralis at gmail.com Tue Jan 15 23:22:36 2008 From: nikolaskaralis at gmail.com (Nikolas Karalis) Date: Wed, 16 Jan 2008 06:22:36 +0200 Subject: reliable whois in python In-Reply-To: References: Message-ID: <85b2e0230801152022w5a6cdb86u133a4795f562becc@mail.gmail.com> I had done a project part of which was what you want to do. You can find it here... http://users.ntua.gr/ge04042/projects/dns/ Feel free to use the code. I hope this helps. Nikolas On Jan 15, 2008 5:48 AM, eliss wrote: > Hi everyone, > > I'm trying to write a python script to whois a few domains twice a day > so I get notified when they become available. I did it 2 ways, but > neither way is very reliable, so I'm asking here. > > 1) I tried just calling "whois %s" using popen, but I found that once > every few weeks, I get errors like: > connect: No route to host OR > fgets: Connection reset by peer > I don't think it's a connectivity issue because looking up the other > domains that day works, and just one domain will give an error. So > it's probably more like a networking issue? I don't know... > > 2) I tried using sockets to connect to the whois port of > whois.internic.net and then read the info, which works a little better > than 1). However, sometimes this is not reliable too and I get errors. > > Does anyone have any ideas how I can do this better? > > Thanks, > > eliss > -- > http://mail.python.org/mailman/listinfo/python-list > -- Nikolas Karalis Applied Mathematics and Physics Undergraduate National Technical University of Athens, Greece http://users.ntua.gr/ge04042 -------------- next part -------------- An HTML attachment was scrubbed... URL: From B.Ogryczak at addr.in.reply-to.invalid Sun Jan 20 12:07:17 2008 From: B.Ogryczak at addr.in.reply-to.invalid (Bart Ogryczak) Date: Sun, 20 Jan 2008 17:07:17 +0000 (UTC) Subject: Bug in __init__? References: <88580064-3590-471e-8036-a631dd5a38b4@i3g2000hsf.googlegroups.com> Message-ID: On 2008-01-20, citizen Arnaud Delobelle testified: > On Jan 20, 3:39?pm, Bart Ogryczak to.invalid> wrote: >> On 2008-01-18, citizen Zbigniew Braniecki testified: >> >> > It's really a nice pitfall, I can hardly imagine anyone expecting this, >> >> AFAIR, it's described in Diving Into Python. > > Still there seems to be about one message a week about this. Indeed I > reckon the greatest benefit of early binding of default function > arguments is that it attracts lots of new people to comp.lang.python. Generally there's lot of confusion about assigments of objects. I guess, there are lot of ppl, who started with languages like PHP, where $a = $b, translates to Python's a = copy(b). >> It's quiet elegant way of creating cache. > > IMHO, calling it 'elegant' is pushing it too far! Ok, maybe that's not a good choice of word. Not elegant, minimalist. bart -- "The first version of iBook looked a bit too much like toilet seat" (c)Newsweek http://candajon.azorragarse.info/ http://azorragarse.candajon.info/ From tjhnson at gmail.com Mon Jan 21 19:50:44 2008 From: tjhnson at gmail.com (tjhnson at gmail.com) Date: Mon, 21 Jan 2008 16:50:44 -0800 (PST) Subject: Max Long References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> <5vkog7F1m4dhvU1@mid.individual.net> Message-ID: On Jan 21, 3:34 pm, Bjoern Schliessmann wrote: > tjhn... at gmail.com wrote: > > How can I figure out the largest long available? > > Why would you? AFAIK, longs are only limited by available memory. Indeed, as the docs pointed out. I guess I was confused by "If pylong is greater than ULONG_MAX, an OverflowError is raised." at http://docs.python.org/api/longObjects.html. From http Mon Jan 28 05:04:33 2008 From: http (Paul Rubin) Date: 28 Jan 2008 02:04:33 -0800 Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> Message-ID: <7xk5lul0zy.fsf@ruckus.brouhaha.com> "Russ P." writes: > You might want to check into what the FAA allows in "flight-critical" > code, for example. I am certainly not an expert in that area, but I've > had a passing exposure to it. My understanding is that every possible > branch of the code must be fully and meticulously analyzed and > verified. Hence, the dynamic dispatching of ordinary object-oriented > code is either prohibited or severely frowned upon. This would also seem to impact higher-order functions, which are prominent in fancy verification systems based on extracting code from constructive theorem provers. I know those things are used in some sensitive security applications. I wonder what the aerospace community thinks of that area. From musiccomposition at gmail.com Tue Jan 29 09:44:27 2008 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 29 Jan 2008 06:44:27 -0800 (PST) Subject: refcount References: Message-ID: On Jan 29, 5:46 am, Christian Heimes wrote: > Simon Pickles wrote: > > Hi, > > > Is is possible to access the refcount for an object? > > > Ideally, I am looking to see if I have a refcount of 1 before calling del > > Help on built-in function getrefcount in module sys: > > getrefcount(...) > getrefcount(object) -> integer > > Return the reference count of object. The count returned is generally > one higher than you might expect, because it includes the (temporary) > reference as an argument to getrefcount(). Are there any cases when it wouldn't? > > Christian From grante at visi.com Wed Jan 30 20:59:17 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 31 Jan 2008 01:59:17 -0000 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! References: <832c7add-b222-46d7-a151-45f02444d520@s19g2000prg.googlegroups.com> Message-ID: <13q2arlaqtsjo13@corp.supernews.com> On 2008-01-31, ajaksu wrote: > On Jan 30, 10:40 pm, "Blubaugh, David A." > wrote: >> I do not understand why no one has answered the following question: >> >> Has anybody worked with Gene Expression Programming???? >> >> David Blubaugh > > I see. You don't understand. That's a fact. I'm sure there are free > online resources about the best way to understand why no one answered > your question in particular, or why people don't answer some questions > in a more comparative way. Like this: http://catb.org/~esr/faqs/smart-questions.html -- Grant Edwards grante Yow! Well, I'm on the at right planet---everyone visi.com looks like me!!! From over at thepond.com Wed Jan 23 13:38:57 2008 From: over at thepond.com (over at thepond.com) Date: Wed, 23 Jan 2008 18:38:57 GMT Subject: python24 symbol file...pyhon24.pdb References: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> Message-ID: On Wed, 23 Jan 2008 08:54:19 +0100, Christian Heimes wrote: >over at thepond.com wrote: >> I've seen a few references on the net to a python24.pdb file. I assume >> it's a symbol file along the lines of the pdb files issued by >> microsoft for their products. Maybe I'm wrong. > >.pdb files (program database) are created by MS' compiler, see >http://en.wikipedia.org/wiki/Program_database. Python doesn't ship the >files. You have to compile Python yourself to get the pdb files. > >Christian thanks From mal at egenix.com Fri Jan 4 11:10:27 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 04 Jan 2008 17:10:27 +0100 Subject: Memory Leaks and Heapy In-Reply-To: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> Message-ID: <477E5A73.9070400@egenix.com> On 2008-01-04 16:07, Yaakov Nemoy wrote: > Hi list, > > Firstly, this is my first post here, so I hope I'm not breaking some > unwritten etiquette rule about asking questions involving several > different libraries. > > I'm trying to plug some memory leaks in a TurboGears program. We (the > Fedora Project) have a few apps in Turbogears in infrastructure that > all seem to be running into the same issues in a variety of > configurations. Hopefully when I get to the cause of this in one app, > Smolt, we can fix the others too. > > The app in question is Smolt, which uses TurboGears, SQLAlchemy with a > MySQL backend, and simplejson for message passing between the server > and client. Smolt takes voluntary hardware reports from its clients, > and generally is configured to submit around the beginning of the > month. Normally, our main data is cached by some separate processes > that run short term, so we don't see any rapid memory growth, except > for the beginning of each month, which makes isolating the problem to > a few function calls fairly simple. To watch for memory growth, I > simply have a client hammer the server with 1-3 threads submitting > information simultaneously, 100 times, with a few deletion operations > in between. To monitor for memory leaks, I'm using Heapy. > > To insert Heapy into the process, instead of calling 'start_server', a > cherrypy method that does what you think it does and blocks, I'm using > the module 'threading' to push it into a new thread. Using the > process in heapy's documentation, I find that after running a single > thread, there is about 1200 bytes of leaked memory. Despite this, the > python process running the server has managed to grow from 16-18MB to > something between 23-28MB each time I try this. After a second > iteration, heapy shows 1168 bytes leaked. If heapy is correct, this > means there are not many leaked objects in the python space. Running > a larger example, say 100 threads, for a total of 10k submissions > takes about an hour, and in the process, python baloons up to about > 48MB. Still no signs of any missing objects. > > 48MB is not alot relatively speaking, but no amount of waiting seems > to show python giving back that memory afterwards. On our production > server, we have up to 200k machines all updating their information > over a 3 day period, in which the server process manages to reach > 600MB before we forcefully restart it. > > A couple of developers have mentioned that python might be fragmenting > its memory space, and is unable to free up those pages. How can I go > about testing for this, and are there any known problems like this? > If not, what else can I do to look for leaks? If you're using lots of small objects, you may be running into a problem with the Python memory allocation mechanism, pymalloc. It used to not return memory to the system. In Python 2.5 (IIRC, could be 2.6) this was changed to at least return completely empty blocks back to the OS. For details, see Objects/obmalloc.c This could be caused by interned strings which are kept in a special pool dictionary to speed up string comparisons. However, the first thing to check is whether any of the C extension modules you are using is leaking memory. Python itself is usually well tested for memory leaks, but this is less so for C extension modules and it's easy to mis a few Py_DECREFs (decrementing a Python object's reference count), causing objects to live forever. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jan 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From nytrokiss at gmail.com Mon Jan 7 16:54:05 2008 From: nytrokiss at gmail.com (James Matthews) Date: Mon, 7 Jan 2008 22:54:05 +0100 Subject: Python's great, in a word In-Reply-To: <87ve65mie1.fsf@benfinney.id.au> References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <87ve65mie1.fsf@benfinney.id.au> Message-ID: <8a6b8e350801071354m6666534ai2440705db722807d@mail.gmail.com> Just Another Vague Acronym = (Java) On Jan 7, 2008 10:32 PM, Ben Finney wrote: > MartinRinehart at gmail.com writes: > > > The best thing about Python is _______. > > The best thing about Python is its elegance. > > -- > \ "Like the creators of sitcoms or junk food or package tours, | > `\ Java's designers were consciously designing a product for | > _o__) people not as smart as them." -- Paul Graham | > Ben Finney > -- > 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 mark.e.tolonen at mailinator.com Fri Jan 25 23:40:23 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Fri, 25 Jan 2008 20:40:23 -0800 Subject: regular expression negate a word (not character) References: <27249159-9ff3-4887-acb7-99cf0d2582a8@n20g2000hsh.googlegroups.com> Message-ID: "Summercool" wrote in message news:27249159-9ff3-4887-acb7-99cf0d2582a8 at n20g2000hsh.googlegroups.com... > > somebody who is a regular expression guru... how do you negate a word > and grep for all words that is > > tire > > but not > > snow tire > > or > > snowtire > > so for example, it will grep for > > winter tire > tire > retire > tired > > but will not grep for > > snow tire > snow tire > some snowtires > > need to do it in one regular expression > What you want is a negative lookbehind assertion: >>> re.search(r'(?>> re.search(r'(? Unfortunately you want variable whitespace: >>> re.search(r'(?", line 1, in File "C:\dev\python\lib\re.py", line 134, in search return _compile(pattern, flags).search(string) File "C:\dev\python\lib\re.py", line 233, in _compile raise error, v # invalid expression error: look-behind requires fixed-width pattern >>> Python doesn't support lookbehind assertions that can vary in size. This doesn't work either: >>> re.search(r'(? Here's some code (not heavily tested) that implements a variable lookbehind assertion, and a function to mark matches in a string to demonstrate it: ### BEGIN CODE ### import re def finditerexcept(pattern,notpattern,string): for matchobj in re.finditer('(?:%s)|(?:%s)'%(notpattern,pattern),string): if not re.match(notpattern,matchobj.group()): yield matchobj def markexcept(pattern,notpattern,string): substrings = [] current = 0 for matchobj in finditerexcept(pattern,notpattern,string): substrings.append(string[current:matchobj.start()]) substrings.append('[' + matchobj.group() + ']') current = matchobj.end() # substrings.append(string[current:]) return ''.join(substrings) ### END CODE ### >>> sample='''winter tire ... tire ... retire ... tired ... snow tire ... snow tire ... some snowtires ... ''' >>> print markexcept('tire','snow\s*tire',sample) winter [tire] [tire] re[tire] [tire]d snow tire snow tire some snowtires --Mark From ajsavige at yahoo.com.au Wed Jan 9 05:58:20 2008 From: ajsavige at yahoo.com.au (Andrew Savige) Date: Wed, 9 Jan 2008 02:58:20 -0800 (PST) Subject: Learning Python via a little word frequency program Message-ID: <493158.64888.qm@web56406.mail.re3.yahoo.com> I'm learning Python by reading David Beazley's "Python Essential Reference" book and writing a few toy programs. To get a feel for hashes and sorting, I set myself this little problem today (not homework, BTW): Given a string containing a space-separated list of names: names = "freddy fred bill jock kevin andrew kevin kevin jock" produce a frequency table of names, sorted descending by frequency. then ascending by name. For the above data, the output should be: kevin : 3 jock : 2 andrew : 1 bill : 1 fred : 1 freddy : 1 Here's my first attempt: names = "freddy fred bill jock kevin andrew kevin kevin jock" freq = {} for name in names.split(): freq[name] = 1 + freq.get(name, 0) deco = zip([-x for x in freq.values()], freq.keys()) deco.sort() for v, k in deco: print "%-10s: %d" % (k, -v) I'm interested to learn how more experienced Python folks would solve this little problem. Though I've read about the DSU Python sorting idiom, I'm not sure I've strictly applied it above ... and the -x hack above to achieve a descending sort feels a bit odd to me, though I couldn't think of a better way to do it. I also have a few specific questions. Instead of: for name in names.split(): freq[name] = 1 + freq.get(name, 0) I might try: for name in names.split(): try: freq[name] += 1 except KeyError: freq[name] = 1 Which is preferred? Ditto for: deco = zip([-x for x in freq.values()], freq.keys()) versus: deco = zip(map(operator.neg, freq.values()), freq.keys()) Finally, I might replace: for v, k in deco: print "%-10s: %d" % (k, -v) with: print "\n".join("%-10s: %d" % (k, -v) for v, k in deco) Any feedback on good Python style, performance tips, good books to read, etc. is appreciated. Thanks, /-\ Make the switch to the world's best email. Get the new Yahoo!7 Mail now. www.yahoo7.com.au/worldsbestemail From andre.john at s1999.tu-chemnitz.de Wed Jan 16 12:07:14 2008 From: andre.john at s1999.tu-chemnitz.de (Andre' John) Date: Wed, 16 Jan 2008 18:07:14 +0100 Subject: Generic string import like in strptime? In-Reply-To: References: Message-ID: Nice. Thanks a lot. Andre On Wed, 16 Jan 2008, Paul Hankin wrote: > On Jan 16, 8:34 am, Andre wrote: > > Hi there > > > > Is there a function like strptime, which takes a string and converts it > > into an array depending on a format string I provide. Like:>>> a = '3456\tblub-blib.0.9' > > >>> b = '%d\t%s-%s.%f' > > >>> c = mysticalfunction(a,b) > > >>> print c > > > > [3456,'blub','blib',0.9] > > Use regular expressions: see http://docs.python.org/lib/node49.html > > -- > Paul Hankin > From lotrpy at gmail.com Sun Jan 13 06:24:59 2008 From: lotrpy at gmail.com (lotrpy) Date: Sun, 13 Jan 2008 03:24:59 -0800 (PST) Subject: about sort a list with integer key Message-ID: <986e05f3-2fe9-4fe8-94e2-fef26713a78c@i72g2000hsd.googlegroups.com> hi, if I want sort each line ,by the last part,of a file, below is the source. from operator import itemgetter content = (line.split() for line in file('foo.txt', 'rb')) for cursor, line in enumerate(sorted(content, key = itemgetter(-1), reverse = True)): print cursor, ' '.join(line) the content of foo.txt is 21 job 3 joke the result is 0 3 joke 1 21 job if i want sort each line by the first part,(it's a integer, in fact). don't know how to do it with itemgetter. key = int(itemgetter(0)) is wrong, key = lambda x:int(x[0]) works. but s.b. told me itemgetter execute more quickly . From tarundevnani at gmail.com Mon Jan 28 02:52:43 2008 From: tarundevnani at gmail.com (tarun) Date: Mon, 28 Jan 2008 13:22:43 +0530 Subject: [wxPython-users] Issue with docking wx.listctrl window In-Reply-To: References: <4798D1B1.7020908@alldunn.com> <479A145C.40802@alldunn.com> Message-ID: Robin, I can use sizers and divide my frames into sections. But I also want to add menu options for display/hide window1 and window2 in my original example. Is this possible even if I use sizers. Regards, Tarun On Jan 28, 2008 1:09 PM, tarun wrote: > Thanks Robin. > Can you please elobrate more on this. > > Regards, > Tarun Devnani > On Jan 25, 2008 10:24 PM, Robin Dunn wrote: > > > tarun wrote: > > > Thanks a lot Robin. > > > > > > I tried using self.log and instead of self.log.list. *Code is > > attached.* > > > But this gives me a panel and listctrl in it. The extra blank space > > > around the listctrl in window1 is something that I don't need. > > > > Use a sizer to manage the layout of the listctrl. > > > > -- > > Robin Dunn > > Software Craftsman > > http://wxPython.org Java give you jitters? > > Relax with wxPython! > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Sat Jan 26 02:30:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 26 Jan 2008 08:30:53 +0100 Subject: python and multithreading problem In-Reply-To: <3a1379f5-f5f5-4af1-903c-8b1f52eb9ed7@k2g2000hse.googlegroups.com> References: <3a1379f5-f5f5-4af1-903c-8b1f52eb9ed7@k2g2000hse.googlegroups.com> Message-ID: <6005tiF1oad5lU1@mid.uni-berlin.de> whatazor schrieb: > Hi all, > I made an application that use multithreading (indifferently importing > thread or threading module) , but when I call some wrapped modules > (with swig) from my application they run like there is only a single > thread (and my application gui ,made with wxPython, freezes). If I use > other modules not wrapped, but created for test that multithread > works, and gui is not freezing are ok. > Modules that wrap DLL are not my product but are created by another > developer with VS.NET, and the only thing I can think is that they're > builded without multithreaded compiler option. Can it be another cause > for this behaviour, can this explanation be correct? maybe also swig > have a multithreading option. There is something called Global Interpreter Lock (GIL) that causes such behavior. It will ensure that python-code won't interfere with each other in multiple threads. However, for C-extensions it is common to release that GIL when a thread enters the extenison, and grab it again when finished. I don't know if SWIG does so, but to me it looks as if that is the problem. You might consider googling swig + gil or something to learn more about it. Diez From donn.ingle at gmail.com Mon Jan 14 11:02:56 2008 From: donn.ingle at gmail.com (Donn) Date: Mon, 14 Jan 2008 18:02:56 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A77F0.4000502@v.loewis.de> References: <200801132048.08966.donn.ingle@gmail.com> <478A77F0.4000502@v.loewis.de> Message-ID: <200801141802.56353.donn.ingle@gmail.com> Given that getlocale() is not to be used, what's the best way to get the locale later in the app? I need that two-letter code that's hidden in a typical locale like en_ZA.utf8 -- I want that 'en' part. BTW - things are hanging-together much better now, thanks to your info. I have it running in locale 'C' as well as my other test locales. What a relief! \d From sjmachin at lexicon.net Tue Jan 22 05:02:19 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 22 Jan 2008 02:02:19 -0800 (PST) Subject: stdin, stdout, redmon References: <4794a5e3$0$9014$426a74cc@news.free.fr> <4794ab22$0$19179$426a74cc@news.free.fr> <4795ba80$0$17176$426a74cc@news.free.fr> Message-ID: On Jan 22, 8:42 pm, Bernard Desnoues wrote: > Hello, > > I checked under linux and it works : > text.txt : > "first line of the text file > second line of the text file" > > test.py : > "import sys > a = sys.stdin.readlines() > x = ''.join(a) > x = x.upper() > sys.stdout.write(x)" > > >cat text.txt | python test.py > > But I reinstalled Python 2.5 under Windows XP and it doesn't work > anyway. Can you confirm that your script works with Win XP and Python 2.5 ? > > Regards > > Rolf van de Krol a ?crit : > > > I don't know what you did with your Python installation, but for me this > > works perfectly. > > > test3.py contains: > > > > import sys > > > print sys.stdin.readlines() > > > > > test.txt contains: > > > > Testline1 > > Testline2 > > > > > Output of 'python test3.py < test.txt' is: > > > > ['Testline1\n', 'Testline2'] > > > > > Just plain simple and just works. > > > Rolf > > > Bernard Desnoues wrote: > >> Rolf van de Krol a ?crit : > > >>> According to various tutorials this should work. > > >>> > >>> |import sys > >>> data = sys.stdin.readlines() > >>> print "Counted", len(data), "lines."| > >>> > > >>> Please use google before asking such questions. This was found with > >>> only one search for the terms 'python read stdin' > > >>> Rolf > > >>> Bernard Desnoues wrote: > > >>>> Hi, > > >>>> I've got a problem with the use of Redmon (redirection port > >>>> monitor). I intend to develop a virtual printer so that I can modify > >>>> data sent to the printer. > >>>> Redmon send the data flow to the standard input and lauchs the > >>>> Python program which send modified data to the standard output > >>>> (Windows XP and Python 2.5 context). > >>>> I can manipulate the standard output. > > >>>> "import sys > >>>> sys.stdout.write(data)" > > >>>> it works. > >>>> But how to manipulate standard input so that I can store data in a > >>>> string or in an object file ? There's no "read" method. > > >>>> "a = sys.stdin.read()" doesn't work. > >>>> "f = open(sys.stdin)" doesn't work. > > >>>> I don't find anything in the documentation. How to do that ? > >>>> Thanks in advance. > > >>>> Bernard Desnoues > >>>> Librarian > >>>> Biblioth?que de g?ographie - Sorbonne > > >> Hello Rolf, > > >> I know this code because I have search a solution ! > >> Your google code doesn't work ! No attribute "readlines". > > >> >>> import sys > >> >>> data = sys.stdin.readlines() > > >> Traceback (most recent call last): > >> File "", line 1, in > >> data = sys.stdin.readlines() > >> AttributeError: readlines Excuse me, gentlemen, may I be your referee *before* you resort to pistols at dawn? ===== IDLE ===== IDLE 1.2.1 >>> import sys >>> sys.stdin.readlines Traceback (most recent call last): File "", line 1, in sys.stdin.readlines AttributeError: readlines >>> ===== Command Prompt ===== C:\junk>python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdin.readlines >>> HTH, John From jr9445 at ATT.COM Fri Jan 18 13:25:55 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 18 Jan 2008 12:25:55 -0600 Subject: Filtering two files with uncommon column In-Reply-To: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.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 Madhur > Sent: Friday, January 18, 2008 4:23 AM > To: python-list at python.org > Subject: Filtering two files with uncommon column > > > Basically I want to compare the two files based on second column. If > the second > column matches on both the files do not print anything, else if there > is no matc > h in for the second column for first file in second file then print it > under Fil > e1 header, else if there is no match for the second column for second > file in fi > rst file print it under File2 header. > I often do this to compare property files between environments. The follow algorithm works for any number of files by creating a dictionary of lists (or hash of arrays in Perl-ese.) Create a dictionary Index = -1 For file in files Index++ For line in file col = match/split/regex the column If col not in dictionary Dictionary[col] = [] extend dictionary[col] to length of index dictionary[col][index] = col for col in sort(dictionary.keys()): extend dictionary[col] to length of index print dictionary[col] ***** 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. GA622 From hniksic at xemacs.org Mon Jan 14 18:00:45 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 15 Jan 2008 00:00:45 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> Message-ID: <87ir1wf1wi.fsf@mulj.homelinux.net> Ben Finney writes: > Hrvoje Niksic writes: > >> Wildemar Wildenburger writes: >> > __init__() /initializes/ an instance (automatically after >> > creation). It is called, /after/ the instance has been constructed >> >> I don't understand the purpose of this "correction". After all, >> __init__ *is* the closest equivalent to what other languages would >> call a constructor. > > No. That would be '__new__', which actually constructs the instance, That's not what other OO languages (C++, Java) actually call a constructor, so your correction is misplaced. My other posts in this thread have expanded on this. From ivan.illarionov at gmail.com Wed Jan 30 17:04:23 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 30 Jan 2008 14:04:23 -0800 (PST) Subject: Events in Python References: Message-ID: <2b005569-3dbc-41c1-aebf-8b6fd8d2175e@v46g2000hsv.googlegroups.com> You may need Louie (http://louie.berlios.de) Django (http://djangoproject.com) does the same in django.dispatch - and Django version works about 33% faster. Note that all those signals/events are very slow in Python. --Ivan From cwitts at gmail.com Fri Jan 4 09:07:08 2008 From: cwitts at gmail.com (Chris) Date: Fri, 4 Jan 2008 06:07:08 -0800 (PST) Subject: how to build a dict including a large number of data References: Message-ID: <6d89cea7-9c21-4c26-9659-aef204df1f09@c4g2000hsg.googlegroups.com> On Jan 4, 3:57 pm, wanzathe wrote: > hi everyone > i'm a newbie to python :) > i have a binary file named test.dat including 9600000 records. > the record format is int a + int b + int c + int d > i want to build a dict like this: key=int a,int b values=int c,int d > i choose using bsddb and it takes about 140 seconds to build the dict. > what can i do if i want to make my program run faster? > or is there another way i can choose? > Thanks in advance. > > My Code: > ----------------------------------------------------------------------------------- > my_file = file('test.dat','rb') > content = my_file.read() > record_number = len(content) / 16 > > db = bsddb.btopen('test.dat.db','n',cachesize=500000000) > for i in range(0,record_number): > a = struct.unpack("IIII",content[i*16:i*16+16]) > db['%d_%d' % (a[0],a[1])] = '%d_%d' % (a[2],a[3]) > > db.close() > my_file.close() my_file = file('test.dat','rb') db = bsddb.btopen('test.dat.db','n',cachesize=500000000) content = myfile.read(16) while content: a = struct.unpack('IIII',content) db['%d_%d' % (a[0],a[1])] = '%d_%d' % (a[2],a[3]) content = myfile.read(16) db.close() my_file.close() That would be more memory efficient, as for speed you would need to time it on your side. From mmanns at gmx.net Fri Jan 25 21:01:04 2008 From: mmanns at gmx.net (Martin Manns) Date: Sat, 26 Jan 2008 03:01:04 +0100 Subject: pyfov Package Index link broken Message-ID: Hi, I am looking for the code of pyfov, which is on the Package Index. However, the link is broken and the author does not seem to respond to e-mails. Any chance to get hands on the code? Martin From pete.forman at westerngeco.com Fri Jan 25 02:57:38 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Fri, 25 Jan 2008 07:57:38 +0000 Subject: When is min(a, b) != min(b, a)? References: <13pia6m7phe2n22@corp.supernews.com> <71a066ac-f7a4-4f3d-b154-353b88af24f2@x69g2000hsx.googlegroups.com> Message-ID: Mark Dickinson writes: > Any change to Python that made == and != checks involving NaNs raise > an exception would have to consider the consequences for set, dict, > list membership testing. > > > and if Python had separate operators for these two purposes it > wouldn't be Python any more. There are separate Python operators, "==" and "is". The C99 standard, which Python defers to for its implementation, says in 6.2.6.1.4: Two values (other than NaNs) with the same object representation compare equal, but values that compare equal may have different object representations. In 7.12.13, the fmax and fmin functions treat NaNs as missing arguments. Most other operations return NaN if an argument is NaN, or for a domain error. 7.12.14 specifies comparison macros that are quiet versions of the relational operators. BTW floating-point exceptions in C and IEEE are not the same as exceptions in higher level languages. The behavior of signalling NaNs are not defined in C. Only quiet NaNs are returned from operations. An invalid floating-point exception may well just set a status flag. That may be tested after a set of calculations. With pipelining the exact cause of the exception will be unknown. -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.port5.com -./\.- WesternGeco. From paul.sijben at xs4all.nl Mon Jan 14 05:58:43 2008 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Mon, 14 Jan 2008 11:58:43 +0100 Subject: encrypting python modules In-Reply-To: <5v0mquF1jhm3dU7@mid.dfncis.de> References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <5v0mquF1jhm3dU7@mid.dfncis.de> Message-ID: <478b4043$0$85785$e4fe514c@news.xs4all.nl> Robert Latest wrote: > Paul Sijben wrote: > >> The problem: I have a client-server app written in python. I want to >> make sure that the client is not: >> 1) destabilized by users accidentally or on purpose dropping python >> files in the path (after which calling the helpdesk will not be useful) >> 2) extended with "new features" without me knowing about it (again >> resulting in calls to my helpdesk...) > > You could check the MD5 hashes of your files. > > robert indeed but I still need to hook into import to do that reliably, right? From fredrik at pythonware.com Wed Jan 9 09:33:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 15:33:38 +0100 Subject: How does unicode() work? In-Reply-To: <1199888091.3474.9.camel@dot.uniqsys.com> References: <5ujt96F1i6h37U1@mid.dfncis.de> <1199888091.3474.9.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > If that really is the line that barfs, wouldn't it make more sense to > repr() the unicode object in the second position? > > import sys > for k in sys.stdin: > print '%s -> %s' % (k, repr(k.decode('iso-8859-1'))) > > Also, I'm not sure if the OP has told us the truth about his code and/or > his error message. The implicit str() call done by formatting a unicode > object with %s would raise a UnicodeEncodeError, not the > UnicodeDecodeError that the OP is reporting. So either I need more > coffee or there is something else going on here that hasn't come to > light yet. When mixing Unicode with byte strings, Python attempts to decode the byte string, not encode the Unicode string. In this case, Python first inserts the non-ASCII byte string in "%s -> %s" and gets a byte string. It then attempts to insert the non-ASCII Unicode string, and realizes that it has to convert the (partially built) target string to Unicode for that to work. Which results in a *UnicodeDecodeError*. >>> "%s -> %s" % ("???", "???") '\x86\x84\x94 -> \x86\x84\x94' >>> "%s -> %s" % (u"???", u"???") u'\xe5\xe4\xf6 -> \xe5\xe4\xf6' >>> "%s -> %s" % ("???", u"???") Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'ascii' codec can't decode byte 0x86 ... (the actual implementation differs a bit from the description above, but the behaviour is identical). From steve at REMOVE-THIS-cybersource.com.au Tue Jan 1 16:54:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 01 Jan 2008 21:54:27 -0000 Subject: Newbie: Why doesn't this work References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> Message-ID: <13nldkj6ecl4j31@corp.supernews.com> On Tue, 01 Jan 2008 13:01:24 -0800, petr.jakes.tpc wrote: >> > My question is: is it possible to set the "property" for any >> > attribute when I do not know what will be the name of the attribute >> > in the future? >> >> Uhm... I don't understand the question. Perhaps if you think of a >> concrete case...? > > Thanks for reply, > > few minutes after i posted my question, I have realized my posting is > probably a "nonsense". > > If I understand it properly, it is necessary, in the respect of > encapsulation, to define attributes inside the class (even it is > possible to add a new attribute to the existing object outside class > definition). > > The meaning of my question was: > Is it possible to define some general sort of set/get/del/doc rules for > the attributes which are defined in the code AFTER the instantiation of > an object. > > I am sending this question even I feel such a "on the fly" creation of > the attribute is probably not a good trick. Like all dynamic modification of classes, it is liable to abuse, but Python allows such things and trusts the programmer not to be foolish. class Parrot(object): pass def set_property(cls, propertyname, defaultvalue=None, docstring=''): """Make a readable, writable but not deletable property.""" privatename = '_' + propertyname setattr(cls, privatename, defaultvalue) def getter(self): return getattr(self, privatename) def setter(self, value): setattr(self, privatename, value) setattr(cls, propertyname, property(getter, setter, None, docstring)) set_property(Parrot, 'colour', 'red', """Parrots have beautiful coloured plumage.""") Now that you know how to do it, please don't. Except for the lack of docstring, the above is much better written as: class Parrot(object): colour = 'red' -- Steven From lasses_weil at klapptsowieso.net Wed Jan 30 09:29:45 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Wed, 30 Jan 2008 15:29:45 +0100 Subject: Removing Pubic Hair Methods In-Reply-To: References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> Message-ID: <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> Gerardo Herzig wrote: > I will use genital().extend(), thats for shure ^^ Well, you never go wrong with apply(genital(), females), do you? /W From projecteclipsor at gmail.com Sat Jan 12 02:03:42 2008 From: projecteclipsor at gmail.com (Landon) Date: Sat, 12 Jan 2008 01:03:42 -0600 Subject: Great Python books for the beginner Message-ID: Hi, I'm a freshman in college and I'm going to be taking an intro to programming course next semester which mainly uses Python, so I thought it might be a good time to pick up Python beyond the scope of the class as well. The text book for this class is Python for the Absolute Beginner or something similar to that name. I was wondering if anyone had any opinions on what other titles I could look into since this one seems from a glance at reviews to be teaching mainly through game programming (a topic I'm not too interested in) or if this one is a quality book by itself. From bj_666 at gmx.net Tue Jan 8 04:38:50 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 8 Jan 2008 09:38:50 GMT Subject: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> Message-ID: <5ugulaF1hqn2cU1@mid.uni-berlin.de> On Tue, 08 Jan 2008 09:20:16 +0000, Robert Latest wrote: > The program "slow" just writes the numbers 0 through 9 on stdout, one line a > second, and then quits. > > I would have expected the python program to spit out a numbers one by one, > instead I see nothing for 10 seconds and then the whole output all at once. > > How can I get and process the pipe's output at the pace it is generated? Both processes have to make their communication ends unbuffered or line buffered. See the documentation of `os.popen()` for the `bufsize` argument. And do whatever is needed to output the numbers from ``slow`` unbuffered or line buffered. Ciao, Marc 'BlackJack' Rintsch From python.list at tim.thechases.com Wed Jan 16 15:40:07 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 16 Jan 2008 14:40:07 -0600 Subject: Creating unique combinations from lists In-Reply-To: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> Message-ID: <478E6BA7.5030509@tim.thechases.com> > a = ['big', 'small', 'medium']; > b = ['old', 'new']; > c = ['blue', 'green']; > > I want to take those and end up with all of the combinations they > create like the following lists > ['big', 'old', 'blue'] > ['small', 'old', 'blue'] > ['medium', 'old', 'blue'] > ['big', 'old', 'green'] > ['small', 'old', 'green'] > ['medium', 'small', 'green'] > ['big', 'new', 'blue'] > ['small', 'new', 'blue'] > ['medium', 'new', 'blue'] > ['big', 'new', 'green'] > ['small', 'new', 'green'] > ['medium', 'new', 'green' ] > > I could do nested for ... in loops, but was looking for a Pythonic way > to do this. Ideas? You can use a recursive generator: def iterall(*iterables): if iterables: for head in iterables[0]: for remainder in iterall(*iterables[1:]): yield [head] + remainder else: yield [] for thing in iterall( ['big', 'medium', 'small'], ['old', 'new'], ['blue', 'green'], ): print thing The two for-loops plus recursion should handle any number of parameters, so if you were so inclined, you could do for thing in iterall( ['big', 'medium', 'small'], ['old', 'new'], ['blue', 'green'], ['smelly', 'fragrant'], ['spatula', 'avocado'], ): print thing and get all 3*2*2*2*2 items. Or count in binary: for i, bitstream in enumerate(iterall( [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], )): print ''.join(map(str, bitstream)), '=', i When you're iterating over combinations of items in groups of lists, I prefer the clarity of this over something like [(a,b,c,d,e) for a in [0,1] for b in [0,1] for c in [0,1] for d in [0,1] for e in [0,1]] -tkc From nagle at animats.com Sat Jan 26 12:28:04 2008 From: nagle at animats.com (John Nagle) Date: Sat, 26 Jan 2008 09:28:04 -0800 Subject: Portably killing/signalling another process not supported? Message-ID: <479b6c58$0$36354$742ec2ed@news.sonic.net> There doesn't seem to be any way to portably kill another process in Python. "os.kill" is Mac/Unix only. The "signal" module only lets you send signals to the current process. And the "subprocess" module doesn't have a "kill" function. Subprocess objects really should have a portable "interrupt" or "kill" function. They already have "poll" and "wait", which have to be implemented differently for different systems; that's the logical place for "kill". Yes, there are nonportable workarounds (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462) but no portable solution. John Nagle From lefevrol at yahoo.com Mon Jan 28 14:35:07 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Mon, 28 Jan 2008 20:35:07 +0100 Subject: read and readline hanging In-Reply-To: <9caacced-0f60-4552-b750-c6684acde062@d21g2000prg.googlegroups.com> References: <9caacced-0f60-4552-b750-c6684acde062@d21g2000prg.googlegroups.com> Message-ID: pexpect looks promising, thanks. -- O.L. From steve at REMOVE-THIS-cybersource.com.au Tue Jan 1 09:45:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 01 Jan 2008 14:45:58 -0000 Subject: ElementTree should parse string and file in the same way References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> <5tuqfaF1f8u9tU1@mid.uni-berlin.de> Message-ID: <13nkkh6almg8o6b@corp.supernews.com> On Tue, 01 Jan 2008 13:36:57 +0100, Diez B. Roggisch wrote: > And codemonkeys know that in python > > doc = et.parse(StringIO(string)) > > is just one import away Yes, but to play devil's advocate for a moment, doc = et.parse(string_or_file) would be even simpler. Is there any reason why it should not behave that way? It could be as simple as adding a couple of lines to the parse method: if isinstance(arg, str): import StringIO arg = StringIO(arg) I'm not saying it *should*, I'm asking if there's a reason it *shouldn't*. "I find it aesthetically distasteful" would be a perfectly acceptable answer -- not one I would agree with, but I could accept it. -- Steven From jarausch at skynet.be Mon Jan 21 12:25:06 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 21 Jan 2008 18:25:06 +0100 Subject: ctypes CDLL - which paths are searched? Message-ID: <4794d573$0$2980$ba620e4c@news.skynet.be> Hi, how can I specify the paths to be searched for a dynamic library to be loaded by ctypes' CDLL class on a Linux system. Do I have to set os.environment['LD_LIBRARY_PATH'] ? Many thanks for a hint, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From lists at cheimes.de Sat Jan 19 11:48:40 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 19 Jan 2008 17:48:40 +0100 Subject: What is a shortcut to the Default home directory in Windows In-Reply-To: <4791A092.7090704@timgolden.me.uk> References: <1f85750e-a85a-4bb5-8f20-cbb5939f89a3@p69g2000hsa.googlegroups.com> <1fddf38d-e6a2-416f-a8f8-020560970ab5@z17g2000hsg.googlegroups.com> <4791A092.7090704@timgolden.me.uk> Message-ID: Tim Golden wrote: > Umm... Is it not? The only thing I'm aware of doing is > retaining backwards compat. by using SHGetPathFromIDList > on the SHGetSpecialFolderLocation because I was writing against > Win9x at the time. Or are you saying something else? > > (Admit I haven't checked all the docs since I wrote it > to see what's been "deprecated" this week). A lot has been deprecated :( MS has deprecated all functions which are using CSIDL and introduced a new stack for Vista. Christian From software at ginstrom.com Thu Jan 10 04:55:17 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Thu, 10 Jan 2008 18:55:17 +0900 Subject: Win32com and Excel In-Reply-To: <096bc326-3c91-4287-817f-79994a8c507d@k39g2000hsf.googlegroups.com> References: <096bc326-3c91-4287-817f-79994a8c507d@k39g2000hsf.googlegroups.com> Message-ID: <013c01c8536e$e8181720$030ba8c0@MOUSE> > On Behalf Of Mike P > Does anyone have any code that does something similar? My > guess is i have to do something like thefollowing to enable > python to read xl? I think that what you want is UsedRange for row in sheet.UsedRange.Value: ... Regards, Ryan Ginstrom From gandalf at shopzeus.com Sun Jan 13 05:29:23 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Sun, 13 Jan 2008 11:29:23 +0100 Subject: ftplib question (cannot open data connection) In-Reply-To: <13ofegohhiu4uc9@corp.supernews.com> References: <13ofegohhiu4uc9@corp.supernews.com> Message-ID: <4789E803.8050604@shopzeus.com> > BUT: active FTP does not just send the data to the port that was in > the random port that was sent to the server... it addresses to the port > you sent, but it sends its data response FROM port 20. This means the > response looks like a totally unsolicited connection attempt from the > outside -- the firewall doesn't even have enough information to > determine which machine (if multiple) inside the firewall should be > receiving the data; since the server is sending the data stream on its > port 20 and there is no active connection for server:20 to ANY > client:???? Yes, I know. But it DOES work from inside my NAT network. I have no clue how. I'm sure that it is using active connections because this server cannot use passive mode. It might be a very clever firewall that does packet sniffing for "ftp PORT" commands. (?) Anyway, the problem is not with this computer, it was a counter-example. > Even if you could tell the firewall to let in connections on > the specified port, the NAT tables won't know what inside IP to > translate the inbound server port 20... > It does not need to. I can reconfigure the firewall to directly forward all incoming TCP connections from a specified port range to a given IP inside the internal network. But I do not even need to do that. The problem is with a computer that is NOT behind NAT. It is a single computer connected directly to the internet, but it has a firewall installed. So everything would be fine except one thing: I should tell ftplib which port(s) to open, and open those ports on my firewall. For example, I can open TCP ports between 50000 and 60000, and then tell ftplib to use ports between 50000 and 60000 in PORT and EPRT commands. How can I do that? If that is not possible, then what is the workaround? (Definitely I do not want to turn off the firewall completely on a production server.) > Passive mode turns this around. Yep, but this ftp server cannot use passive mode and I cannot change this. And finally, if this cannot be done in ftplib, then I would like to suggest to add this method to Ftp objects. :-) Best, Laszlo From ian at neustyle.com Sun Jan 6 02:21:54 2008 From: ian at neustyle.com (ian at neustyle.com) Date: Sat, 5 Jan 2008 23:21:54 -0800 (PST) Subject: list property fires get on append Message-ID: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com> I've created a class that has a property which points at a private list. When I try to use the append() function on this list property, the fget method is fired rather than the fset method. If I directly set my property to a literal list, the set method fires. Here's a stripped down version of my code: class Hierarchy(object): _children = [] def __init__(self): return def get_children(self): print("GETTING") return self._children def set_children(self, value): print("SETTING") self._children = value children = property(get_children, set_children) -----USAGE------ import Hierarchy hierarchy = Hierarchy.Hierarchy() # this fires a get for some reason hierarchy.children.append( Hierarchy.Hierarchy()) # this fires a set as expected hierarchy.children = [Hierarchy.Hierarchy()] ------RESULT------ it prints: GETTING SETTING From http Thu Jan 31 18:09:03 2008 From: http (Paul Rubin) Date: 31 Jan 2008 15:09:03 -0800 Subject: How to identify which numbers in a list are within each others' range References: <6b4ac79b-6267-438d-8b28-aa4bba78a586@i3g2000hsf.googlegroups.com> Message-ID: <7xzlula8z4.fsf@ruckus.brouhaha.com> "attn.steven.kuo at gmail.com" writes: > mysets = [set(range(x[2],x[1])) for x in mylist] This is pretty horrible, each set can be arbitrarily large, i.e. if x[2] and x[1] are 0 and 1000000, you get a set with a million elements. From http Fri Jan 11 18:26:42 2008 From: http (Paul Rubin) Date: 11 Jan 2008 15:26:42 -0800 Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> Message-ID: <7xsl147xl9.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > This function just wants X out of the list. It doesn't matter if this > happens before, during, or after something else; so long as it happens. If you're asking in a general way how to do something like that, there are several basic methods: 1. Put a single thread in charge of the list, and communicate with it by message passing through Queues. To get X out of the list, you'd send the mutator thread a message asking for removal. The mutator thread would loop reading and processing messages from the queue, blocking when no requests are pending. This is sort of the preferred Python style and is pretty simple to get correct, but if there are many such objects you can end up with more threads than you really want. 2. Associate a lock with the list. Anything wanting to access the list should acquire the lock, do its stuff, then release the lock. This gets confusing after a while. 3. Various other schemes involving finer grained locks etc. that get horrendously error prone (race conditions etc). There is probably a good tutorial somewhere about programming with threads. It's sometimes a tricky subject, so it's worth taking the time to study various approaches rather than re-inventing the wheeel. From vedrandekovic at gmail.com Wed Jan 2 06:43:23 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Wed, 2 Jan 2008 03:43:23 -0800 (PST) Subject: wxpython application ( problem ? ) References: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> <5u1asvF1fgr5bU2@mid.uni-berlin.de> Message-ID: <7cb975f6-e9a6-4527-bd84-2041aede197f@j20g2000hsi.googlegroups.com> On 2 sij, 12:29, Marc 'BlackJack' Rintsch wrote: > On Wed, 02 Jan 2008 03:24:56 -0800, vedrandekovic wrote: > > Here is sample of my simple script with wxpython and modules: > > subprocess,threading, directpython....... > > Are you accessing the GUI from threads? > > Ciao, > Marc 'BlackJack' Rintsch Hi again, yes, so what's the problem? Regards, Vedran From chiendarret at yahoo.com Mon Jan 7 01:49:47 2008 From: chiendarret at yahoo.com (Francesco Pietra) Date: Sun, 6 Jan 2008 22:49:47 -0800 (PST) Subject: Delete lines containing a specific word In-Reply-To: Message-ID: <281534.89912.qm@web57616.mail.re1.yahoo.com> --- Steven D'Aprano wrote: > On Sun, 06 Jan 2008 13:33:52 -0800, Francesco Pietra wrote: > > > Steven: > > Thanks. See below please (of very marginal interest) > > > > --- Steven D'Aprano wrote: > > > >> On Sun, 06 Jan 2008 09:21:33 -0800, Francesco Pietra wrote: > >> > >> > Please, how to adapt the following script (to delete blank lines) to > >> > delete lines containing a specific word, or words? > >> > >> That's tricky, because deleting lines from a file isn't a simple > >> operation. No operating system I know of (Windows, Linux, OS X) has a > >> "delete line" function. > > > > As I am at Debian Linux, I do that with grep -v > > grep doesn't delete lines. grep matches lines. If you want to delete > them, you still have to do the rest of the job yourself. Well, I use Debian Linux for scientific purposes, so that I have no much time toget expertise even in the OS. Though, from the command (as user) grep -v theword thefile.pdb I get thefile.pdb without the lines containing "theword". > > > >> Secondly, you might want the script to write its output to a file, > >> instead of printing. So, instead of the line "print line", you want it > >> to write to a file. > > > > may be cumbersome, though I use 2>&1 | tee output file.pdb so that I > > can see what happens on the screen and have the modified file. > > Yes, matching lines and sending them to stdout is a better solution than > trying to delete them from a file. > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From mr.cerutti at gmail.com Wed Jan 16 07:21:07 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 16 Jan 2008 07:21:07 -0500 Subject: no pass-values calling? In-Reply-To: <18c1e5f20801151909u4cdd227ah685741ea21734491@mail.gmail.com> References: <18c1e5f20801151909u4cdd227ah685741ea21734491@mail.gmail.com> Message-ID: <51302a8c0801160421i1a9db1aala222b847d4e01f3a@mail.gmail.com> On Jan 15, 2008 10:09 PM, J. Peng wrote: > Hello, > > I saw this statement in Core Python Programming book, > > All arguments of function calls are made by reference, meaning that > any changes to these parameters within the function > affect the original objects in the calling function. Yes, that's generally correct. But you must be careful about what is meant by "changes to parameters". Assigning a new value to a parameter name (inside the function, a parameter is just a local variable) does not change the original object--it only rebinds the local variable to a new object. In the following function, a is rebound with an assignment statement, while b is mutated, i.e., changed, with an assignment statement. def f(a, b): a = 12 b.value = 14 Argument a will never be changed, while argument b will be. Python's argument passing semantics are extremely simple. It's the assignment statement that's tricky: some assignments mutate/change objects, and some only rebind names. > Does this mean there is not pass-values calling to a function in > python? only pass-reference calling? Thanks! Neither is quite true. Values are passed by binding parameter names to their corresponding arguments. This is similar to pass-by-reference in some cases (when the argument is mutated) but not in others (when the argument is not mutated). Thinking of it as pass-by-reference may help you to understand it, but bear in mind that Python's "references" may be rebound to new objects, which is quite different from the usual behavior of references. -- Neil Cerutti From kyosohma at gmail.com Mon Jan 28 13:42:02 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 28 Jan 2008 10:42:02 -0800 (PST) Subject: Question on importing wxPython References: Message-ID: <3d81547e-7d9e-47a1-9b82-b571c20646fa@i72g2000hsd.googlegroups.com> On Jan 28, 12:06 pm, "Steven W. Orr" wrote: > python-2.3.5 > wx-2.6 > > I just bought the wxPython In Action book and I see that all the examples > say to > import wx > All of our pre-existing code was horribly doing a > from wxPython import * > > I changed all the code so that it was doing an import wx and found that > everything was broken. In particular, references to wxNewId would fail. > > 634 > python > Python 2.3.5 (#2, May 4 2005, 08:51:39) > [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> import wx > >>> wx.wxNewId > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'wxNewId' > > > > In fact, the *only* way to get it was to go back to > import wxPython > and then refer to it as wxPython.wx.wxNewId > > Is my system broken or am I missing something? i.e., should I be able to > say import wx? > > TIA > > -- > Time flies like the wind. Fruit flies like a banana. Stranger things have .0. > happened but none stranger than this. Does your driver's license say Organ ..0 > Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 > individuals! What if this weren't a hypothetical question? > steveo at syslang.net I think the issue is that you are using the old style of wxPython. The new style is wx.Something, so in this case, you want wx.NewId(). See sample code below: import wx new_id = wx.NewId() This helps the developer know what library that function comes from. I see you are using 2.6. Just so you know, 2.8 is out now...you may want to upgrade. Also, there's a really nice wxPython community mailing list you can join, which you'll find here: http://wxpython.org/maillist.php Mike From fredrik at pythonware.com Fri Jan 4 13:30:43 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 19:30:43 +0100 Subject: Simple calculation error In-Reply-To: <3CDC4613E97B134A9A7E61A5E43DCA55010FDE36@fr-mail1.fr.kyriba.com> References: <3CDC4613E97B134A9A7E61A5E43DCA55010FDE36@fr-mail1.fr.kyriba.com> Message-ID: Francois Liot wrote: > > I observed a strange calculation answer, on both python 2.3.4 and 2.4.4 > >> >> print 753343.44 - 753361.89 > > -18.4500000001 > >> >> print ( (753361.89*100) - (753343.44*100) ) / 100 > > 18.45 > > Can somebody help me to play correctly with decimal values? A 64-bit binary floating point number can hold values between -1e308 and +1e308, in only 64 bits of memory. Since 1e308 is a *lot* larger than float(2**64) = ~1.8e19, it does this by splitting the number in a binary fraction, and a multiplier (stored as an exponent). Unfortunately, very few decimal fractions can be *exactly* represented as binary fractions, so you often get representation errors: http://docs.python.org/tut/node16.html This is usually not much of a problem, since you usually end up rounding things to a suitable number of decimals or significant digits when you print them anyway (see below), but repr() doesn't do that -- it always outputs enough digits to get back the *exact* binary representation if you convert the string back to a floating point value again. In practice, you can usually ignore this; just use the appropriate output methods, and things will just work: While pathological cases do exist, for most casual use of floating-point arithmetic you'll see the result you expect in the end if you simply round the display of your final results to the number of decimal digits you expect. str() usually suffices, and for finer control see the discussion of Python's % format operator: the %g, %f and %e format codes supply flexible and easy ways to round float results for display. (from the above link) If you really need full control over this, no matter what, use the Decimal type, as provided by the decimal module in the standard library. See the library reference for the full story. From fabiofz at gmail.com Tue Jan 29 05:54:21 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 29 Jan 2008 08:54:21 -0200 Subject: Pydev 1.3.12 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.12 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: ----------------------------------------------------------------- * Mark occurrences: only requested on mouse-clicks and cursor changes. * Code-Analysis: No longer running in UI-Thread (bug which slowed things down in 1.3.10 and 1.3.11). * Code-Analysis: Cache optimizations. * Code-Analysis: Fixed 'statement without effect' when raising exception with arguments without using the exception constructor. * Code-Analysis: Fixed 'statement without effect' on tuple creation. * Code-Analysis: __path__ found for packages (__init__.py files). * Context-insensitive info: Correctly updated when code-analysis is off (or if file is not analyzed). Release Highlights in Pydev: ---------------------------------------------- * Code Coverage: coverage.py updated to version 2.78 (http://nedbatchelder.com/code/modules/coverage.html). * Optimization: Caches (with no memory overhead) added for a number of situations, which can speed completion requests a lot (up to 40x on tests). 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 lists at cheimes.de Sun Jan 6 11:13:58 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 06 Jan 2008 17:13:58 +0100 Subject: Cost of "unicode(s)" where s is Unicode In-Reply-To: <4780fb68$0$36341$742ec2ed@news.sonic.net> References: <4780fb68$0$36341$742ec2ed@news.sonic.net> Message-ID: <4780FE46.1070101@cheimes.de> John Nagle wrote: > Does > > text = unicode(text) > > make a copy of a Unicode string, or is that essentially a > free operation if the input is already Unicode? >>> u = u"some long unicode object" >>> unicode(u) is u True From kw at codebykevin.com Mon Jan 7 18:30:32 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 07 Jan 2008 18:30:32 -0500 Subject: Does PIL work with Tk 8.5? In-Reply-To: <4782B244.7010706@codebykevin.com> References: <2870$4782a5c4$4275d90a$673@FUSE.NET> <4782B074.8080709@v.loewis.de> <4782B244.7010706@codebykevin.com> Message-ID: <6b9d3$4782b618$4275d90a$4415@FUSE.NET> Kevin Walzer wrote: > > Tk itself has a stubs mechanism that allows libraries compiled against > earlier versions to be used with later versions. It's different than > Python in this respect. A pure-Tk library (such as Img or TkPNG) built > against Tk 8.4 would not require re-compilation to be used with 8.5. > Since PIL is a Python library, however, you may be right. > Indeed, this appears to be the problem. I tested my script against the Python bundled with Mac OS X, which links against 8.4, and it worked fine. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From jarausch at skynet.be Tue Jan 15 09:55:23 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 15 Jan 2008 15:55:23 +0100 Subject: common problem - elegant solution sought In-Reply-To: References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <478cc95b$0$29247$ba620e4c@news.skynet.be> Neil Cerutti wrote: > On Jan 15, 2008 5:33 AM, Helmut Jarausch wrote: >> Hi, >> >> I'm looking for an elegant solution of the following tiny but common problem. >> >> I have a list of tuples (Unique_ID,Date) both of which are strings. >> I want to delete the tuple (element) with a given Unique_ID, but >> I don't known the corresponding Date. >> >> My straight forward solution is a bit lengthy, e.g. >> >> L=[("a","070501"),("b","080115"),("c","071231")] > > If the data is truly sorted by Unique_ID, then binary search may be > feasible (though not actually recommended for such small list). > > import bisect > > i = bisect.bisect_left(L, ('b', '000000')) > if i[0] == 'b': > del L[i] > Thanks, unfortunately, they are sorted on 'Date' Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From bignose+hates-spam at benfinney.id.au Wed Jan 2 08:47:58 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 03 Jan 2008 00:47:58 +1100 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au> <87bq85rp2d.fsf@physik.rwth-aachen.de> <87abnoc13h.fsf@benfinney.id.au> Message-ID: <8763ycbapd.fsf@benfinney.id.au> Steven D'Aprano writes: > On Wed, 02 Jan 2008 15:17:54 +1100, Ben Finney wrote: > > > Torsten Bronger writes: > > > >> [...] the width of a tab is nowhere defined. It really is a matter of > >> the editor's settings. > > > > RFC 678 "Standard File Formats" > > : > > Dated 19 December 1974. So? The point is made: it's not true to say "the width of a tab is nowhere defined". Everything I can find that is in any way close to a "standard" defines the canonical width of an ASCII TAB as being eight columns. At least that one also acknowledges what we all know: that (even in those times) actually enforcing that canonical width is difficult. > I think it tells a lot about the spaces-only argument that it is > based on the state of the art thirty years ago I think it says a lot about this thread that you've devolved to taking a side point I raise merely to disprove a distracting fallacy, and claim that my core argument "is based on" it. It says, at least, that it's time for me to stop contributing to this thread, as it won't improve from here. My argument is made, earlier in this thread, utterly unrelated to this "width of a TAB" point, and it remains whether it convinces anyone who contributed or not. -- \ "Don't worry about people stealing your ideas. If your ideas | `\ are any good, you'll have to ram them down people's throats." | _o__) -- Howard Aiken | Ben Finney From bignose+hates-spam at benfinney.id.au Mon Jan 7 04:05:24 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 07 Jan 2008 20:05:24 +1100 Subject: do - loop References: Message-ID: <87zlvim2ej.fsf@benfinney.id.au> Hita Vora writes: > I have a dataset which has about 3000 subjects in it. I take each > subject and perform 3 to 4 geoprocessing tasks on it. Currently I > have a model where I manually feed in each subject's ID and then the > rest of the process is automated. I would like to automate the > process such that it would automatically select another subject > after the process has been completed on a specfic subject. ie to > repeat the same process on each of the IDs. def do_the_stuff(subject): """ Do the stuff to a single subject """ pass for this_subject in all_subjects: do_the_stuff(this_subject) -- \ "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 fredrik at pythonware.com Sun Jan 13 07:44:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 13 Jan 2008 13:44:58 +0100 Subject: __init__ explanation please In-Reply-To: <47895d25$0$30708$4c368faf@roadrunner.com> References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: Erik Lind wrote: > I'm new to Python, and OOP. I've read most of Mark Lutz's book and more > online and can write simple modules, but I still don't get when __init__ > needs to be used as opposed to creating a class instance by assignment. nothing is ever created by plain assignment in Python; to create a class instance in Python, you *call* the class object. an example: class MyClass: pass # create three separate instances obj1 = MyClass() obj2 = MyClass() obj3 = MyClass() (it's the () that creates the object, not the =) if you want to initialize the method's state (that is, set some attributes), you can do that from the outside: obj1.attrib = "some value" or in an "initialization" method in the class: class MyClass: def init(self): self.attrib = "some value" obj1 = MyClass() obj1.init() but in both cases, you'll end up with an inconsistent object state (in this case, no attribute named "attrib") if you forget to do this. obj1 = MyClass() print obj1.attrib # this will fail to avoid such mistakes, you can use __init__ instead. this is just a initialization method that's automatically called by Python *after* the object is created, but *before* the call to the class object returns. class MyClass: def __init__(self): self.attrib = "some value" obj1 = MyClass() print obj1.attrib # this will succeed also, any arguments that you pass to the class object call are passed on to the initialization method. class MyClass: def __init__(self, value): self.attrib = value obj1 = MyClass("hello") print obj1.attrib # prints "hello" as Jeroen points out, this is pretty much the same thing as a constructor in other languages -- that is, a piece of code that's responsible for setting up an object's state. Python's a bit different; the object is in fact created before the call to __init__, but this doesn't matter much in practice; if construction fails, the assignment will fail, so the object will be lost, and is reclaimed by the GC later on. (unless you explicitly store a reference to the object somewhere else, of course: >>> class MyClass: ... def __init__(self): ... global secret ... secret = self ... raise ValueError("oops! failed!") ... def method(self): ... print "here I am!" ... >>> obj = MyClass() Traceback (most recent call last): File "", line 1, in File "", line 5, in __init__ ValueError: oops! failed! >>> obj Traceback (most recent call last): File "", line 1, in NameError: name 'obj' is not defined >>> secret.method() here I am! ) finally, if you want full control also over the actual creation of the object, more recent Python versions support a __new__ method that can be used instead of __init__, or as a complement. but that's an advanced topic, and is nothing you need to worry about while trying to the hang of class basics. hope this helps! From stargaming at gmail.com Mon Jan 7 18:40:28 2008 From: stargaming at gmail.com (Stargaming) Date: 07 Jan 2008 23:40:28 GMT Subject: How to refer to the current module? References: Message-ID: <4782b86c$0$12421$9b622d9e@news.freenet.de> On Mon, 07 Jan 2008 05:21:42 -0800, Mike wrote: > I want to do something like the following (let's pretend that this is in > file 'driver.py'): > > #!/bin/env python > > import sys > > def foo(): > print 'foo' > > def bar(arg): > print 'bar with %r' % arg > > def main(): > getattr(driver, sys.argv[1])(*sys.argv[2:]) > > if __name__=='__main__': > main() > > > Essentially what I'm trying to get at here is dynamic function > redirection, like a generic dispatch script. I could call this as > > python driver.py foo > > or > > python driver.py bar 15 > > and at any time later I can add new functions to driver.py without > having to update a dispatch dict or what-have-you. > > The problem is, 'driver' doesn't exist in main() line 1. If I 'import > driver' from the command line, then getattr(driver, ...) works, but it's > not bound here. > > Is there any way around this? Can I somehow scope the 'current module' > and give getattr(...) an object that will (at run time) have the > appropriate bindings? > > Thanks in advance for all advice! > > Mike `__main__` (after you did ``import __main__``) could be an option as well. But I'd prefer a custom dictionary for your dispatch, rather than some magic with the module's names. See http://docs.python.org/ref/programs.html for details on __main__. From aisaac at american.edu Fri Jan 25 17:30:30 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 25 Jan 2008 22:30:30 GMT Subject: find minimum associated values In-Reply-To: References: <7xd4rpznl0.fsf@ruckus.brouhaha.com> Message-ID: Alan Isaac wrote: > #sort by id and then value > kv_sorted = sorted(kv, key=lambda x: (id(x[0]),x[1])) > #groupby: first element in each group is object and its min value > d =dict( g.next() for k,g in groupby( kv_sorted, key=lambda x: x[0] ) ) > > Yes, that appears to be fastest and is > pretty easy to read. On average. For the specified problem. ;-) From sjmachin at lexicon.net Thu Jan 3 18:02:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 3 Jan 2008 15:02:46 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> <76ba16c8-6ba0-4609-80bd-cd54aa08d74b@5g2000hsg.googlegroups.com> Message-ID: <590e6f12-16ad-4919-a87d-a2f2cc0b3516@t1g2000pra.googlegroups.com> On Jan 4, 8:03 am, mario wrote: > On Jan 2, 2:25 pm, Piet van Oostrum wrote: > > > Apparently for the empty string the encoding is irrelevant as it will not > > be used. I guess there is an early check for this special case in the code. > > In the module I an working on [*] I am remembering a failed encoding > to allow me, if necessary, to later re-process fewer encodings. If you were in fact doing that, you would not have had a problem. What you appear to have been doing is (a) remembering a NON-failing encoding, and assuming that it would continue not to fail (b) not differentiating between failure reasons (codec doesn't exist, input not consistent with specified encoding). A good strategy when dealing with encodings that are unknown (in the sense that they come from user input, or a list of encodings you got out of the manual, or are constructed on the fly (e.g. encoding = 'cp' + str(code_page_number) # old MS Excel files)) is to try to decode some vanilla ASCII alphabetic text, so that you can give an immemdiate in-context error message. > In the > case of an empty string AND an unknown encoding this strategy > failed... > > Anyhow, the question is, should the behaviour be the same for these > operations, and if so what should it be: > > u"".encode("non-existent") > unicode("", "non-existent") Perhaps you should make TWO comparisons: (1) unistrg = strg.decode(encoding) with unistrg = unicode(strg, encoding) [the latter "optimises" the case where strg is ''; the former can't because its output may be '', not u'', depending on the encoding, so ut must do the lookup] (2) unistrg = strg.decode(encoding) with strg = unistrg.encode(encoding) [both always do the lookup] In any case, a pointless question (IMHO); the behaviour is extremely unlikely to change, as the chance of breaking existing code outvotes any desire to clean up a minor inconsistency that is easily worked around. From http Mon Jan 21 15:56:14 2008 From: http (Paul Rubin) Date: 21 Jan 2008 12:56:14 -0800 Subject: index of min element of sequence References: <7xfxwrt1dx.fsf@ruckus.brouhaha.com> <6243b2e3-e2eb-41fb-bb7c-88b40ffcef60@e25g2000prg.googlegroups.com> Message-ID: <7xabmyyk29.fsf@ruckus.brouhaha.com> John Machin writes: > s/[1]/[0]/ or more generally: Oops, got two spellings confused. Originally was going to use from itertools import count, izip min(izip(seq, count()))[1] but did it with enumerate instead. I don't know which is actually faster. > minindex, minvalue = min(enumerate(seq), key=itemgetter(1)) Cool, I like this best of all. Or alternatively, minindex, minvalue = min(izip(seq, count())) From jazle at localhost.com Wed Jan 16 19:53:25 2008 From: jazle at localhost.com (Jaimy Azle) Date: Thu, 17 Jan 2008 07:53:25 +0700 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> <60b75f24-d33a-476e-932d-11dfb9880562@v4g2000hsf.googlegroups.com> Message-ID: "Paul Boddie" wrote: > I think the benefits of running Java on CPython are significantly less > than those had by running Python on the Java VM (or another VM). > Firstly, who wants to write statically typed code which then runs on a > virtual machine that can't take advantage of the type declarations? > Secondly, isn't it just better to use a virtual machine with just-in- > time compilation and all sorts of security mechanisms if you're > wanting to write the Java code that, when compiled, can take advantage > of all that stuff? In other words: what makes CPython a compelling VM > for the Java programmer? I agree, that's why i expecting nobody willing to. But despite of that, at least what you've done is a proof-of-concept that java byte-code could also be executed by python. Salam, -Jaimy. From bearophileHUGS at lycos.com Thu Jan 24 12:55:46 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 24 Jan 2008 09:55:46 -0800 (PST) Subject: Duplicating a variable References: Message-ID: <1f5684fd-d8e6-4429-953f-b57362eeb4d1@s19g2000prg.googlegroups.com> Hans: > I have run into a bit of a subtle problem. How do I go about > duplicating a variable (particularly a list of lists) in python. I > was surprised when simple assignment didn't work. Python is quite high-level language, but now and then it too accepts some compromises to increase its speed/size performance. Probably after Python someone will invent a language that may be slower than Python because it's higher level than Python, and avoids that problem you talk about (and other things). (And with a strategy of smart data sharing and copy-on-write the interpreter can avoid part of that overhead). > how do I go about duplicating a variable > which I can then manipulate independently? If your variable contains a list, then you can copy it like this: >>> l1 = [1, 2, 3] >>> l2 = l1[:] >>> l2[1] = 4 As you can see now they are two distinct lists: >>> l1 [1, 2, 3] >>> l2 [1, 4, 3] If you want to copy any kind of object you can use the copy function (instead of a simpler copy method that's absent): >>> d1 = {1:2, 3:4} >>> from copy import copy >>> d2 = copy(d1) >>> d1[1] = 5 >>> d1 {1: 5, 3: 4} >>> d2 {1: 2, 3: 4} But as you can see copy works only one level deep: >>> d3 = {1:[1], 3:4} >>> d3 {1: [1], 3: 4} >>> d4 = copy(d3) >>> d3[1][0] = 2 >>> d3 {1: [2], 3: 4} >>> d4 {1: [2], 3: 4} To copy all levels you need deepcopy: >>> from copy import deepcopy >>> d5 = deepcopy(d3) >>> d3[1][0] = 5 >>> d3 {1: [5], 3: 4} >>> d4 {1: [5], 3: 4} >>> d5 {1: [2], 3: 4} Bye, bearophile From lasses_weil at klapptsowieso.net Mon Jan 14 14:41:27 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 14 Jan 2008 20:41:27 +0100 Subject: bags? 2.5.x? In-Reply-To: References: Message-ID: <478bbae6$0$25383$9b4e6d93@newsspool4.arcor-online.net> Dan Stromberg wrote: > Is there a particular reason why bags didn't go into 2.5.x or 3000? > > I keep wanting something like them - especially bags with something akin > to set union, intersection and difference. > How about this recepie ? /W From colinlandrum at gmail.com Tue Jan 1 18:32:17 2008 From: colinlandrum at gmail.com (hubritic) Date: Tue, 1 Jan 2008 15:32:17 -0800 (PST) Subject: pyparsing question Message-ID: <8df809a0-1950-4250-a968-2d366f64cdb4@d21g2000prf.googlegroups.com> I am trying to parse data that looks like this: IDENTIFIER TIMESTAMP T C RESOURCE_NAME DESCRIPTION 2BFA76F6 1208230607 T S SYSPROC SYSTEM SHUTDOWN BY USER A6D1BD62 1215230807 I H Firmware Event My problem is that sometimes there is a RESOURCE_NAME and sometimes not, so I wind up with "Firmware" as my RESOURCE_NAME and "Event" as my DESCRIPTION. The formating seems to use a set number of spaces. I have tried making RESOURCE_NAME an Optional(Word(alphanums))) and Description OneOrMore(Word(alphas) + LineEnd(). So the question is, how can I avoid having the first word of Description sucked into RESOURCE_NAME when that field should be blank? The data I have has a fixed number of characters per field, so I could split it up that way, but wouldn't that defeat the purpose of using a parser? I am determined to become proficient with pyparsing so I am using it even when it could be considered overkill; thus, it has gone past mere utility now, this is a matter of principle! thanks From arne.k.h at gmail.com Mon Jan 21 15:38:48 2008 From: arne.k.h at gmail.com (Arne) Date: Mon, 21 Jan 2008 12:38:48 -0800 (PST) Subject: Trouble writing to database: RSS-reader References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> <4794e0f9$0$4429$426a74cc@news.free.fr> Message-ID: <739742b0-7d3d-4039-b793-ccefae4be721@1g2000hsl.googlegroups.com> On 21 Jan, 19:15, Bruno Desthuilliers wrote: > This should not prevent you from learning how to properly parse XML > (hint: with an XML parser). XML is *not* a line-oriented format, so you > just can't get nowhere trying to parse it this way. > > HTH Do you think i should use xml.dom.minidom for this? I've never used it, and I don't know how to use it, but I've heard it's useful. So, I shouldn't use this techinicke (probably wrong spelled) trying to parse XML? Should i rather use minidom? Thank you for for answering, I've learnt a lot from both of you, Desthuilliers and Genellina! :) From ptmcg at austin.rr.com Tue Jan 22 09:59:35 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 22 Jan 2008 06:59:35 -0800 (PST) Subject: Problem with processing XML References: <13pbudgks88rcf3@corp.supernews.com> Message-ID: <1839ec4e-045e-4ce2-a3ea-78ed83a8c288@u10g2000prn.googlegroups.com> On Jan 22, 8:11?am, John Carlyle-Clarke wrote: > Hi. > > I'm new to Python and trying to use it to solve a specific problem. ?I > have an XML file in which I need to locate a specific text node and > replace the contents with some other text. ?The text in question is > actually about 70k of base64 encoded data. > Here is a pyparsing hack for your problem. I normally advise against using literal strings like "" to match XML or HTML tags in a parser, since this doesn't cover variations in case, embedded whitespace, or unforeseen attributes, but your example was too simple to haul in the extra machinery of an expression created by pyparsing's makeXMLTags. Also, I don't generally recommend pyparsing for working on XML, since there are so many better and faster XML-specific modules available. But if this does the trick for you for your specific base64-removal task, great. -- Paul # requires pyparsing 1.4.8 or later from pyparsing import makeXMLTags, withAttribute, keepOriginalText, SkipTo xml = """ ... long XML string goes here ... """ # define a filter that will key off of the tag with the # attribute 'name="PctShow.Image"', and then use suppress to filter the # body of the following tag dataTag = makeXMLTags("data")[0] dataTag.setParseAction(withAttribute(name="PctShow.Image"), keepOriginalText) filter = dataTag + "" + SkipTo("").suppress() + "" xmlWithoutBase64Block = filter.transformString(xml) print xmlWithoutBase64Block From george.sakkis at gmail.com Thu Jan 17 19:41:03 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 17 Jan 2008 16:41:03 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> <7xy7aong73.fsf@ruckus.brouhaha.com> Message-ID: <4eba552a-3f9f-4bc7-81e7-150f109013ad@c23g2000hsa.googlegroups.com> On Jan 17, 7:13 pm, Paul Rubin wrote: > George Sakkis writes: > > And if the iterables don't necessarily support len(), here's a more > > general solution: > > Not trying to pick on you personally but there's this disease > when a newbie comes with a basically simple question (in this case, > how to solve the problem with ordinary lists) and gets back a lot > of complex, overly general "graduate level" solutions. Fair enough, although I don't think it's bad to show more general/ efficient/flexible solutions after the simple quick & dirty ones have been shown, as in this thread. My solution is just a step further from Paul Hankin's, not a direct response to the OP. > There's a humorous set of Haskell examples that takes this to extremes: > > http://www.willamette.edu/~fruehr/haskell/evolution.html Hehe.. I remember seeing a similar one for Java and "Hello world" using more and more elaborate abstractions and design patterns but I can't find the link. George From karlheinz.klingbeil at gmx.net Fri Jan 25 08:04:18 2008 From: karlheinz.klingbeil at gmx.net (Karlheinz Klingbeil) Date: Fri, 25 Jan 2008 14:04:18 +0100 Subject: Email module, how to add header to the top of an email? References: <97c04812-3b66-4d84-9e92-21de72a3ca56@c23g2000hsa.googlegroups.com> <088eeaff-8251-49a4-9202-a9481f5e8aaa@x69g2000hsx.googlegroups.com> Message-ID: Am 25.01.2008, 06:21 Uhr, schrieb David Erickson : > Bottom of the headers... but I am looking to insert at the top, and re- > ordering/inserting does matter depending on what type of header you > are, received headers for example must be inserted at the top of the > header list so you can watch the progression of the email. I was > unable to find a clean way to do this via the API which seems very > strange to me.. but perhaps I am just missing something? I think your are really missing something. First, Email-headers are unordered and every relay can, and probably will, rearrange them, add or delete headers. You therefore most definitely should not add any headers which are position-dependent. If you want to track mails somehow, add headers with timestamps. This way you can watch the progression of an email without being dependend on "sorted" headerlines. -- Greetz, lunqual - http://www.lunqual.de http://www.42pixels.de - Bilder http://www.rezeptbuch-pro.de - Software f?r den Destillateur From williampaul28 at yahoo.com Sat Jan 19 10:09:06 2008 From: williampaul28 at yahoo.com (william paul) Date: Sat, 19 Jan 2008 07:09:06 -0800 (PST) Subject: python scripts with IIS Message-ID: <120794.61529.qm@web38414.mail.mud.yahoo.com> Hello: I am trying to configure IIS to work with Python scripts: I've added in the Home Directory/Configuration the .py extention and the path to the python.exe as: c:\Python24\python.exe %S %S The python script has 1 line: print "This is a test for python scripts with IIS" When I launch the file using IE I get the message: CGI Error The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: This is a test for python scripts with IIS How can I remove the CGI error? Thank you William ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -------------- next part -------------- An HTML attachment was scrubbed... URL: From ggpolo at gmail.com Thu Jan 17 14:51:56 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 17 Jan 2008 17:51:56 -0200 Subject: how django discovers changed sources In-Reply-To: <18udndFmKMfgMRLanZ2dnUVZ_rzinZ2d@comcast.com> References: <18udndZmKMfMNhLanZ2dnUVZ_rzinZ2d@comcast.com> <18udndFmKMfgMRLanZ2dnUVZ_rzinZ2d@comcast.com> Message-ID: 2008/1/17, alf : > Jeff wrote: > > That is the behavior of the development server. When you are writing > > your application, you don't want to have to manually restart the > > server every time you change a file. On apache it obviously doesn't > > do that. > > thx for clarification, but still I am curious how it is done under the > hood. it really impressed me ... > -- > http://mail.python.org/mailman/listinfo/python-list > It checks if modification time on registered files have changed since last check -- -- Guilherme H. Polo Goncalves From grante at visi.com Fri Jan 18 11:48:38 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 18 Jan 2008 16:48:38 -0000 Subject: how to resolve Windows pathnames into cygwin ones References: <2ba97fb6-6bef-44aa-937b-2aa9582e4341@e4g2000hsg.googlegroups.com> Message-ID: <13p1m36m9htom5f@corp.supernews.com> On 2008-01-18, apatheticagnostic wrote: > On Jan 18, 11:10 am, "mgier... at gmail.com" wrote: >> I am looking for a function to resolve 'F:/foo/bar' into '/cygdrive/f/ >> foo/bar'. I get the original dirpath from tkFileDialog.askdirectory in >> a Windows form and none of os.path.* functions seem to resolve it to a >> cygwin form. Rather they _append_ it to the current directory, >> resulting at best in a monster '/cygdrive/c/whatever/f/foo/bar'. >> It's all being developed under cygwin currently (so it is a kind of >> mixed environment), but I would like the fix to work correctly in any >> environment. >> >> Thanks, >> Marcin > > Well, you could write it yourself.... > > (assuming path is a string, here's a first go at it...) > def path_into_cygpath(path): > drive, destination = path.split(':') > newpath = '/cygdrive/' + drive.lower() + destination > return newpath Don't forget to convert backslashes into forward slashes. -- Grant Edwards grante Yow! TONY RANDALL! Is YOUR at life a PATIO of FUN?? visi.com From sjmachin at lexicon.net Tue Jan 29 14:00:21 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 29 Jan 2008 11:00:21 -0800 (PST) Subject: Error in parsing XML for following test data References: Message-ID: <082482fe-65b8-4854-b567-30cc4fbc8a24@s13g2000prd.googlegroups.com> On Jan 29, 9:29 pm, abhishek wrote: > Hello group, > > I am having problem parsing following data set from XML. Please > provide hints on how to rectify this problem. You have provided no hints on what your problem is. What output do you want? What have you tried? What output and/or error message(s) did you get? What does "from XML" mean? > > I am using python2.4 version > > this is te test data that i am using -- > > """"""" > 1!!!!!!!!!!!!!!!11 > 2@@@@@@@@@@@@@@@22 [snip] > 33................. > Special Characters > #!/bin/bash > #start TG app > cd $1 > exec ./start-infopsyM.py > > """"""" > > This is really a nasty data set. It looks like (a) easily parseable but totally uninteresting guff followed by (b) the start of a bash script Is this some kind of joke? You are not trying to disassemble it, are you? From ivan.illarionov at gmail.com Wed Jan 30 17:24:48 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 30 Jan 2008 14:24:48 -0800 (PST) Subject: Events in Python References: <2b005569-3dbc-41c1-aebf-8b6fd8d2175e@v46g2000hsv.googlegroups.com> <60carvF1q0a0rU1@mid.individual.net> Message-ID: > Compared to what, did you measure something? As example, instantiation of Model classes in Django (Model.__init__) sends two signals (pre_init and post_init) - they are rarely used in practice - but they make instantiation about two times slower. Yes, I measured that. The creator of Louie (Patrick K. O'Brien) himself seems to use them only as an option that can be enabled/disabled in his projects (e.g. Schevo) - because they are slow. From fredrik at pythonware.com Mon Jan 7 11:17:12 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 17:17:12 +0100 Subject: I'm searching for Python style guidelines In-Reply-To: References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > Here's just one of my questions: > > foo = [ > 'some item, quite long', > 'more items, all demanding there own line as they are not short', > ... > > Where would you put the closing ']'? on a line by itself, indented as your favourite Python editor indents it. From steven at REMOVE.THIS.cybersource.com.au Wed Jan 16 01:30:27 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Jan 2008 06:30:27 -0000 Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> Message-ID: On Wed, 16 Jan 2008 13:59:03 +0800, J. Peng wrote: > Hi, > > How to modify the array passed to the function? I tried something like > this: > >>>> a > [1, 2, 3] >>>> def mytest(x): > ... x=[4,5,6] This line does NOT modify the list [1, 2, 3]. What it does is create a new list, and assign it to the name "x". It doesn't change the existing list. If you have not already done this, you should read this: http://effbot.org/zone/python-objects.htm Consider this function: def test(alist): alist.append(0) # this modifies the existing list alist = [1, 2, 3] # this changes the name "alist" return alist Now try it: oldlist = [10, 9, 8, 7] newlist = test(oldlist) Can you predict what oldlist and newlist will be equal to? oldlist will be [10, 9, 8, 7, 0] and newlist will be [1, 2, 3]. Do you see why? -- Steven From antroy at gmail.com Thu Jan 10 08:00:55 2008 From: antroy at gmail.com (Ant) Date: Thu, 10 Jan 2008 05:00:55 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <8f99cb7e-5664-4ebb-b3fc-dd32124ea5f4@m77g2000hsc.googlegroups.com> On Jan 10, 12:04 pm, "dongie.ag... at gmail.com" wrote: > For the most part, I agree with you, which is why I chose Python in > the first place. I like quick development. Unfortunately, this is > one of those cases where execution time is a factor. Who knows, maybe > someone who's done camera vision with Python will come in and say it's > just the algorithm in the example that needs work (I'm crossing my > fingers that that's the case). It would probably be worth reposting your question with a different subject line. Something along the lines of "Image/Video processing performance in Python", and explaining what you actually want to achieve. "Python too slow?" doesn't give enough information - clearly Python is fast enough for many many tasks, since it is so widely used. It also sounds like a troll - so many people who would actually be able to assist you (such as the PIL, pygame and numpy/scipy communities) may have ignored this thread. Cheers, -- Ant. From yantao at telus.com Tue Jan 1 21:17:17 2008 From: yantao at telus.com (Peter Pei) Date: Wed, 02 Jan 2008 02:17:17 GMT Subject: ElementTree should parse string and file in the same way In-Reply-To: <4778A47B.9020201@web.de> References: <4778A47B.9020201@web.de> Message-ID: To answer something posted deep down... It is fine with me if there are two functions - one to parse a file or file handler and one to parse a string, yet the returned objects should be consistent. From rw at smsnet.pl Fri Jan 11 13:27:33 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 11 Jan 2008 19:27:33 +0100 Subject: Using a proxy with urllib2 References: <2qhhj.38168$Pv2.26753@newssvr23.news.prodigy.net> <87ir21o8sj.fsf@merkury.smsnet.pl> <26Ohj.3530$jJ5.1972@newssvr11.news.prodigy.net> Message-ID: <87odbs6wve.fsf@merkury.smsnet.pl> "Jack" writes: > Rob, > > I tried your code snippet and it worked great. I'm just wondering if > getopener( ) call > is lightweight so I can just call it in every call to fetchurl( )? Or I > should try to share > the opener object among fetchurl( ) calls? Creating an opener for every url is rather not reasonable way to go. Sharing is the better approach. In your case you might create e.g. two instances: simple_opener and proxy_opener. Regards, Rob From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 04:00:34 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 10:00:34 +0100 Subject: improving performance of python webserver running python scripts in cgi-bin In-Reply-To: <0842faf5-879b-4f50-bfd8-ce17ea7f9673@d4g2000prg.googlegroups.com> References: <0842faf5-879b-4f50-bfd8-ce17ea7f9673@d4g2000prg.googlegroups.com> Message-ID: <47873026$0$21435$426a74cc@news.free.fr> Dale a ?crit : > I am using a simple python webserver (see code below) to serve up > python scripts located in my cgi-bin directory. > > import BaseHTTPServer > import CGIHTTPServer > class Handler(CGIHTTPServer.CGIHTTPRequestHandler): > cgi_directories = ['/cgi-bin'] > httpd = BaseHTTPServer.HTTPServer(('',8000), Handler) > httpd.serve_forever() > > > This works fine, but now I would like to combine the python scripts > into the server program to eliminate starting the python interpreter > on each script call. I am new to python, and was wondering if there > is a better techique that will be faster. > > Also, can someone reccommend an alternative approach to > httpd.serve_forever(). I would like to perform other python functions > (read a serial port, write to an Ethernet port, write to a file, etc.) > inside the web server program above. Is there an example of how to > modify the code for an event loop style of operation where the program > mostly performs my python I/O functions until an HTTP request comes > in, and then it breaks out of the I/O operations to handle the HTTP > request. > May I suggest that you take a look at more sophisticated solutions, like either wsgi, CherryPy or Twisted ? From fredrik at pythonware.com Wed Jan 2 09:39:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 02 Jan 2008 15:39:11 +0100 Subject: PyCairo, PIL and StringIO In-Reply-To: <366566.9612.qm@web52211.mail.re2.yahoo.com> References: <366566.9612.qm@web52211.mail.re2.yahoo.com> Message-ID: Jair Trejo wrote: > I'm doing some image processing in PIL, and I want to > display the results in a GTK window using PyCairo, so > I create a Cairo image surface from the PIL Image like > this: > data > mfile = StringIO.StringIO() > final.save(mfile, format="PNG") > ima = > cairo.ImageSurface.create_from_png(mfile) > mfile.close() > return ima > > Where final is a PIL image. The problem is, I get a > IOError: error while reading from Input Stream. > > ?Any idea of why is this happening? "save" leaves the file pointer at an undefined position (usually at the end), so my guess is that you have to rewind the file before you pass it to the next function: final.save(mfile, format="PNG") mfile.seek(0) # rewind also note that compressing and decompressing will introduce unnecessary overhead; chances are that you might get a lot better performance if you just shuffle the raw pixels. I haven't used PyCairo myself, but from a quick look at the ImageSurface documentation, something like this should work (untested): if final.mode != "RGB": final = final.convert("RGB") w, h = final.size data = final.tostring() # get packed RGB buffer ima = cairo.ImageSurface.create(data, FORMAT_RGB24, w, h, w*3) (tweak as necessary) From sigpoggy at hotmail.com Sat Jan 26 14:30:02 2008 From: sigpoggy at hotmail.com (sigpoggy at hotmail.com) Date: Sat, 26 Jan 2008 11:30:02 -0800 (PST) Subject: wx.EVT_RIGHT_UP strangeness? Message-ID: I am playing with wxPython 2.8.7.1 on OS X 10.4.11 with MacPython 2.5 When running the demo program, the ShapeWindow demo does not close the window on right click. It turns out that the wx.EVT_RIGHT_UP does not fire. I discovered that one way to get it to fire is to bind the wx.EVT_RIGHT_DOWN event also. Thus adding the following two lines solves the problem: in __init__ add: self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) secondly add: def OnRightDown(self, evt): pass Everything then works ok. My question is: Is this how it is supposed to work, and if not, am I the only one with this problem? From JO3chiang at gmail.com Mon Jan 7 22:26:47 2008 From: JO3chiang at gmail.com (jo3c) Date: Mon, 7 Jan 2008 19:26:47 -0800 (PST) Subject: linecache and glob References: <0e16ca26-9e34-4f97-83de-9ddc3693d085@i12g2000prf.googlegroups.com> <0a62d553-7fe9-41c0-84dc-a1f3749b46f8@e23g2000prf.googlegroups.com> <3682a1dd-a3a6-436f-87a0-37feaef65ccc@h11g2000prf.googlegroups.com> Message-ID: <7dc7aac7-c3e7-4a88-8528-3ac350e0e1a3@j78g2000hsd.googlegroups.com> On Jan 4, 5:25 pm, Fredrik Lundh wrote: > jo3c wrote: > > i have a 2000 files with header and data > > i need to get the date information from the header > > then insert it into my database > > i am doing it in batch so i use glob.glob('/mydata/*/*/*.txt') > > to get the date on line 4 in the txt file i use > > linecache.getline('/mydata/myfile.txt/, 4) > > > but if i use > > linecache.getline('glob.glob('/mydata/*/*/*.txt', 4) won't work > > glob.glob returns a list of filenames, so you need to call getline once > for each file in the list. > > but using linecache is absolutely the wrong tool for this; it's designed > for *repeated* access to arbitrary lines in a file, so it keeps all the > data in memory. that is, all the lines, for all 2000 files. > > if the files are small, and you want to keep the code short, it's easier > to just grab the file's content and using indexing on the resulting list: > > for filename in glob.glob('/mydata/*/*/*.txt'): > line = list(open(filename))[4-1] > ... do something with line ... > > (note that line numbers usually start with 1, but Python's list indexing > starts at 0). > > if the files might be large, use something like this instead: > > for filename in glob.glob('/mydata/*/*/*.txt'): > f = open(filename) > # skip first three lines > f.readline(); f.readline(); f.readline() > # grab the line we want > line = f.readline() > ... do something with line ... > > thank you guys, i did hit a wall using linecache, due to large file loading into memory.. i think this last solution works well for me thanks From shriphanip at gmail.com Tue Jan 1 01:27:10 2008 From: shriphanip at gmail.com (Shriphani) Date: Mon, 31 Dec 2007 22:27:10 -0800 (PST) Subject: pdf library. References: <133097f4-de83-4e13-93f1-1404213333a4@l6g2000prm.googlegroups.com> Message-ID: On Dec 30 2007, 5:08 am, Waldemar Osuch wrote: > On Dec 29, 11:54 am,Shriphani wrote: > > > Hi, > > I am looking for a pdf library that will give me a list of pages where > > new chapters start. Can someone point me to such a module ? > > Regards, > >ShriphaniP. > > pyPdf may help you with that:http://pybrary.net/pyPdf/ I tried pyPdf for this and decided to get the pagelinks. The trouble is that I don't know how to determine whether a particular page is the first page of a chapter. Can someone tell me how to do this ? From bs866806 at 163.com Sat Jan 19 06:05:47 2008 From: bs866806 at 163.com (bs866806 at 163.com) Date: Sat, 19 Jan 2008 03:05:47 -0800 (PST) Subject: Movie Stars As Sources Of Wisdom Message-ID: Why do many people look to movie stars for answers to some of life's most challenging questions? While we have great respect for the art of acting, as explicated from Stanislavsky to Strasberg, the latter of whom we knew well and were fond of, we have never understood how the usual snippets who decide to become actors ascend in the minds of the public from being initially generally regarded as likely ne'er-do-wells to being considered the most readily available font of insightful advice on just about every topic that troubles the frontal lobe of contemporary humanity. Are we so doubtful of our own confidence to make up our minds that the resplendent light in which a current movie star is illuminated by his own publicity agents blinds us to the very probable vapidity of his or her own mind? After all, there is a certain disjunction between what movie stars do to win our attentions and what we expect of them once they succeed. They bring themselves to our attention by committing to memory, or by reading off one kind of prompter or another, words devised by others. We won't go so far as to say they achieve renown by presenting the thoughts of others, since realistic drama, in most of its contemporary manifestations, is apparently unable to present characters who might actually have an occasional considerable thought. But, once they ascend to the starry vault that hovers over us, do we expect of them anything consonant with the ability to recite the usual inanities? No, suddenly we want these storied performers to transform themselves into the wise harbingers of original insight and exemplary advice. We even search the most mundane aspects of their personal lives for a hint or two as to how we might enhance the happiness of our own comparatively desultory lives. Or, just as often, we suppose, in the hope of finding that, despite their great reservoir of astonishing expertise, their own lives are inexplicably entangled in antics so confoundedly absurd that their shortcomings make us feel far superior in the relatively rickety guidance of our own lives. Since we can only be sure that the lights of stage and screen will continue to be presented to us with all the wiles that can be managed through the deft employment of colorful media, as the engaging exemplars of how we should only hope to live, it appears that the only way to alter the mutual mockery is to become more realistic about what we really ought to expect from our dazzling stars-brights. http://www.cncarrental.cn/html/Humor/20060929/25390.html From deets at nospam.web.de Mon Jan 28 07:02:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jan 2008 13:02:59 +0100 Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> <479da620$0$25625$426a74cc@news.free.fr> <13067a3e-bce7-45ea-beba-4dc83c749a72@i12g2000prf.googlegroups.com> Message-ID: <605ujjF1o66nmU1@mid.uni-berlin.de> > If Python could be automatically converted to Ada or Java, that could > potentially be used as a baseline for actual operational software. > That would capture the algorithmic details more reliably than recoding > from scratch by hand. But such an automatic conversion is not feasible > without explicit typing. If python could be automatically converted to ADA or Java, it wouldn't be python. The fundamental difference IS the lack of static type annotations. The problem is that people often confuse type inference with dynamic typing, because it looks similar - but it isn't the same. All typeinference does is to take an expression like this: a = 10 * 100 and place type-variables on it, like this: a:t_0 = 10:int * 100:int Actually, the multiplication also gets annotated, like this: a:t_0 = *(10:int, 100:int):t_1 Then the unknown type variables are inferred - it is known (and that is an important property: ALL FUNCTIONS ARE KNOWN AT THIS POINT) that there exists a multiplication function that has this signature: _ * _ : [int, int] -> int so t_1 can be inferred to be int, thus t_0 can be inferred to be int as well. But the key-point is: each and every function declaration is and has to be fully statically typed. And all of them have to be known at compile-time!! And of course this extends to classes or interfaces and such. There are some nice tricks like generic types that themselves containt type-variables in their declaration, so that you can declcare e.g. map, reduce, filter and so forth in generic ways. But they are _fully_ type annotated. And the "normal" (Henly/Millner) type inference fails to produce correct results in cases like this: def foo(arg): if arg > 10: return 100 else: return "n/a" Which is perfectly legal and sometimes useful in python. Yes, there is dependent typing, but this also goes only so far. Additionally, it can be shown that type-inferencing becomes non-deterministic or even unsolvable in the very moment you start introducing recursive types - so, away with lists, arrays, trees and so forth. Which of course also means that the statically typed languages will produce errors, unless you restrict them heavily with respect to dynamic memory allocation and so forth (that restricted ADA variant sometimes popping up in discussions about this is one such case) bottom-line: type-inference doesn't do magic, fully staticly annotated languages still fail, and efforts like shedskin are interesting but will never grow to a full-fledged python. And adding static type-declarations to python will make it NotPython, a totally different language. Diez From gagsl-py2 at yahoo.com.ar Fri Jan 18 11:49:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 18 Jan 2008 14:49:23 -0200 Subject: How to use only a sub shell to execute many commands in python References: Message-ID: En Fri, 18 Jan 2008 09:31:25 -0200, raocheng escribi?: > Please see the following code. > Suppose I have many shell commands to be executed. And I don't want to > fork a sub shell for each command(eg: status,output = > commands.getstatusoutput(cmd)) because it is too expensive. I want to > use only one sub shell to execute all these commands and want to get > each command's output. How can I accomplish this task ? Thanks in > advance. The hard part is to determine WHEN the command has completed its execution, because there is no indication of that. One way would be to set a relatively uncommon prompt, and look for that string in stdout. You can't read beyond that, else the code would block. Another way is to use a separate thread to read from stdout/stderr, and set a timeout; when no more output comes whithin the timeout, you assume the command has finished. The code below uses the first approach, changing the prompt to <$$$>\r\n. I've tested it on Windows only, but should work on Linux too with some minor modifications. import subprocess from os import getenv # Windows only, this is to determine the shell in use # Linux users may try with getenv("SHELL", "sh") shell = getenv("COMSPEC", "cmd") p = subprocess.Popen(shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) expected = '<$$$>\r\n' cmds = ['prompt $L$$$$$$$G$_','date /t','cd','dir','ipconfig /all'] # The first command above sets an uncommon prompt, ending with a newline. # On Linux use PS1=whatever, but make sure it ends in \n and set the # expected variable accordingly. for cmd in cmds: print ">>>",cmd p.stdin.write('%s\n' % cmd) while True: line = p.stdout.readline() if line.endswith(expected): break print line, print "Waiting for subshell to terminate" p.stdin.write("exit\n") p.wait() print "Done" -- Gabriel Genellina From imageguy1206 at gmail.com Tue Jan 29 12:06:26 2008 From: imageguy1206 at gmail.com (imageguy) Date: Tue, 29 Jan 2008 09:06:26 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: Message-ID: <2f010feb-d745-4516-9b4f-b225e25670a9@f47g2000hsd.googlegroups.com> On Jan 29, 12:34?pm, William McBrine wrote: > Look at this -- from Python 2.5.1: > > >>> a = [1, 2, 3, 4, 5] > >>> for x in a: > > ... ? ? if x == 3: > ... ? ? ? ? a.remove(x) > ... ? ? print x > ... > 1 > 2 > 3 > 5 > > >>> a > [1, 2, 4, 5] > > Sure, the resulting list is correct. But 4 is never printed during the > loop! > > What I was really trying to do was this: > > apps = [name for name in os.listdir(ROOT) if > ? ? ? ? os.path.isdir(os.path.join(ROOT, name))] > > apptitles = {} > > for name in apps: > ? ? try: > ? ? ? ? app = __import__(name) > ? ? except: > ? ? ? ? apps.remove(name) > ? ? else: > ? ? ? ? apptitles[name] = getattr(app, 'TITLE', name.title()) > > which worked fine, until I actually had a directory with no module in it. > Then that directory was correctly removed from the list, but the _next_ > one was skipped, so its title was never assigned, which caused problems > later in the program. > > -- > 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on You should not change/modify the original sequence iterating over. In the list comprehension, try changing os.listdir(ROOT) to os.listdir(ROOT)[:] so you are get a copy of the original list. geoff. From bj_666 at gmx.net Fri Jan 25 15:31:47 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Jan 2008 20:31:47 GMT Subject: read and readline hanging References: Message-ID: <5vuv9iF1o6ambU2@mid.uni-berlin.de> On Fri, 25 Jan 2008 17:31:16 +0100, Olivier Lefevre wrote: > Thanks for the answer. Yes this is tricky. I have done it in Java > before, where you can, e.g., set up a thread to pump stuff out of > both stderr and stdout continuously but my python is too rudimentary > for that. The `trheading` module is modeled after Java's threading API. > There is a key difference anyway: in Java you can write > > while (br.readLine() != null) { } > > where br is the buffered reader in which you've wrapped the stdout > of the child process and it will not hang. But in python eventually > stdout.readline() hangs. This is a real nuisance: why can't it just > return None? Because that would be quite annoying because most of the time people want blocking behavior. >> 1. The subprocess has stopped producing output. > > Indeed, if I do this interactively, I can tell after 3 lines that I've > gotten all there is to get right now and the fourth readline() call > hangs. But how can I find out *programmatically* that there is no more > input? You can't. >> If you are only reading its standard output, are you sure that the > > subprocess is flushing its buffers so you can recognize it's time to > > provide more input? > > The subprocess in a purely passive position: it is an interpreter: I > send it commands and I read the answers. The python side is in charge. This doesn't answer if the interpreter doesn't flush its output buffer after every line. Ciao, Marc 'BlackJack' Rintsch From jura.grozni at gmail.com Mon Jan 28 10:05:55 2008 From: jura.grozni at gmail.com (azrael) Date: Mon, 28 Jan 2008 07:05:55 -0800 (PST) Subject: PYS file Message-ID: A I Understood correctly, pyc files are compiled py scripts. Is it possible to decomplite them. I guess it's possible, but how hard is it. From justin.mailinglists at gmail.com Thu Jan 3 00:45:07 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Wed, 2 Jan 2008 21:45:07 -0800 (PST) Subject: Python CGI - Presenting a zip file to user References: <475074c1-ef0d-4551-834c-5a16781de3f8@m34g2000hsf.googlegroups.com> Message-ID: On Jan 3, 1:35 pm, jwwest wrote: > Thanks! That worked like an absolute charm. > > Just a question though. I'm curious as to why you have to use the > msvcrt bit on Windows. If I were to port my app to *NIX, would I need > to do anything similar? > > - James not needed for *NIX as *NIX does not have a notion of binary- vs text- mode I seem to recall not needing the msvcrt stuff a while ago on Windows but recently needed it again for Python CGI on IIS From yantao at telus.com Sun Jan 27 10:56:14 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 15:56:14 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: References: <13po55nc0q0s06@corp.supernews.com> Message-ID: "I V" wrote in message news:PdVmj.1467$uE.1363 at newssvr22.news.prodigy.net... > On Sun, 27 Jan 2008 05:32:40 +0000, Peter Pei wrote: >> Yes, it is true that %s already support unicode, and I did not >> contradict that. But it counts the number of bytes instead of >> characters, and makes things like %-20s out of alignment. If you don't >> understand my assertion, please don't argue back and I am only >> interested in answers from those who are qualified. > > What version of python are you using? On python 2.4 and 2.5 on linux, 2.5.2 on windows, if you have tested linux, maybe... windows is the issue? > %-20s counts the characters, not the bytes, or, I think it does. when I > run: > >>>> print u'%-20s|\n%-20s|' % (u'foo bar', u'foo b?r') > > the output is: > > foo bar | > foo b?r | > From bignose+hates-spam at benfinney.id.au Wed Jan 9 22:55:04 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 10 Jan 2008 14:55:04 +1100 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> Message-ID: <87abneibc7.fsf@benfinney.id.au> erik gartz writes: > The loop performs some actions with web services. The particular > iteration I'm on isn't important to me. It is only important that I > attempt the web services that number of times. If I succeed I > obviously break out of the loop and the containing function (the > function which has the loop in it) returns True. If all attempts > fail the containing loop returns False. When you have iteration requirements that don't seem to fit the built-in types (lists, dicts, generators etc.), turn to 'itertools' in the standard library. >>> from itertools import repeat >>> def foo(): ... import random ... print "Trying ..." ... success = random.choice([True, False]) ... return success ... >>> max_attempts = 10 >>> for foo_attempt in repeat(foo, max_attempts): ... if foo_attempt(): ... break ... Trying ... Trying ... Trying ... Trying ... Trying ... Trying ... >>> Note that this is possibly more readable than 'for foo_attempt in [foo] * max_attempts", and is more efficient for large values of 'max_attempts' because 'repeat' returns an iterator instead of actually allocating the whole sequence. > I guess based on the replies of everyone my best bet is to leave the > code the way it is and suck up the warning from pylint. I think your intent -- "repeat this operation N times" -- is better expressed by the above code, than by keeping count of something you don't actually care about. > I don't want to turn the warning off because catching unused > variables in the general is useful to me. Agreed. -- \ "Dyslexia means never having to say that you're ysror." | `\ ?anonymous | _o__) | Ben Finney From a at b.c Thu Jan 10 09:20:23 2008 From: a at b.c (Caleb) Date: Thu, 10 Jan 2008 16:20:23 +0200 Subject: I'm searching for Python style guidelines In-Reply-To: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > Anything written somewhere that's thorough? Any code body that should > serve as a reference? 1. Don't use tabs (use spaces). 2. Study "import this" 3. Use lists and dictionaries as much as you possibly can 4. Use comprehensions and generators as much as you possibly can 5. Use the standard library for everything you possibly can 6. As much as you possibly can, when starting a new project, postpone setting up classes for everything (start with functions). In some projects, you might never need the overhead at all. It will be difficult to go far wrong regarding style if you do a lot of what's in this list. This list is not mine. I jotted these points down, but this information is continually repeated by the actual wise people (not me) in this newsgroup. Caleb From bkasterm at gmail.com Thu Jan 24 21:57:58 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Thu, 24 Jan 2008 18:57:58 -0800 (PST) Subject: Convert list to file object without creating an actual file. Message-ID: <32ae7d79-248a-4ac3-b51c-756699f11837@t1g2000pra.googlegroups.com> I have written a little program that takes as input a text file, converts it to a list with appropriate html coding (making it into a nice table). Finally I want to upload this list as a textfile using ftp. If homeworkhtml contains the list of lines; e.g. homeworkhtml = ["
", "", "" ..... I want to call: ftp.storlines("STOR " + filename, homeworkhtml) which gives me the error Traceback (most recent call last): File "./testhw.py", line 67, in ? ftp.storlines("STOR " + filename, homeworkhtml) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/ftplib.py", line 428, in storlines AttributeError: 'list' object has no attribute 'readline' Expected since homeworkhtml is in fact not a file. Is there a way to convert this list to a file object without first writing it to disc and then opening the resulting file? Best, Bart From http Sat Jan 12 03:51:50 2008 From: http (Paul Rubin) Date: 12 Jan 2008 00:51:50 -0800 Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> <437bac5f-7213-48d1-9c72-203cadffa664@k39g2000hsf.googlegroups.com> Message-ID: <7x8x2vifyx.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > > I'm writing an NxN observer pattern, mostly for my own personal > > exploration. Two threads -might- be calling 'Disconnect' at the same > > time, and I can't even guarantee that the function runs properly. I think the Pythonic way to do this is have the targets communicate with the observers through queues rather than with callbacks. From tgrav at mac.com Fri Jan 11 16:35:55 2008 From: tgrav at mac.com (Tommy Grav) Date: Fri, 11 Jan 2008 16:35:55 -0500 Subject: number of element in array/matrix In-Reply-To: <1200067795.478794d335c84@webmailimpb.dur.ac.uk> References: <1200067795.478794d335c84@webmailimpb.dur.ac.uk> Message-ID: <233643D4-3AA2-406A-A259-4EF89C3792B9@mac.com> On Jan 11, 2008, at 11:09 AM, m.s.mould at durham.ac.uk wrote: > > Hi, > I have what I suspect to be a fairly simple problem while using > python Numeric. > I am attempting to count the number of times that an element 'b' > occurs in > numeric array 'a'. I tried unsuccessfully to find a more efficient > function to > do this for me such as that offered when using a list, but couldn't > seem to find > anything for Numeric arrays. However, I suspect that my loop is not > the most > efficient way to achieve this. > > def countel(a, b): #counts the number of times value 'b' is found > in array 'a' > i=0 > count=0 > while (i j=0 > while (j if (a[i][j]==b): > count=count+1 > else: > pass > j=j+1 > i=i+1 > return count > > Any help or advice would be greatly appreciated, > Matt something like this? >>> import numpy as n >>> a = n.matrix([[1,2,3,4,1],[2,3,4,1,2],[3,4,1,2,3]],"float") >>> a matrix([[ 1., 2., 3., 4., 1.], [ 2., 3., 4., 1., 2.], [ 3., 4., 1., 2., 3.]]) >>> k = n.where(a==1,1,0) >>> k matrix([[1, 0, 0, 0, 1], [0, 0, 0, 1, 0], [0, 0, 1, 0, 0]]) >>> k.sum() 4 >>> Cheers Tommy From exarkun at divmod.com Tue Jan 22 08:42:33 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 22 Jan 2008 08:42:33 -0500 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <5vm8t3F1m1797U1@mid.uni-berlin.de> Message-ID: <20080122134233.15391.1170589248.divmod.quotient.1460@ohm> On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" wrote: >For a simple greenlet/tasklet/microthreading experiment I found myself in >the need to ask the question > >isgenerator(v) > >but didn't find any implementation in the usual suspects - builtins or >inspect. > >I was able to help myself out with a simple (out of my head, hope its > >def isgenerator(v): > def _g(): yield > return type(v) == type(_g()) > >But I wonder why there is no such method already available? > Why do you need a special case for generators? If you just pass the object in question to iter(), instead, then you'll either get back something that you can iterate over, or you'll get an exception for things that aren't iterable. Jean-Paul From mrmakent at cox.net Wed Jan 23 22:00:53 2008 From: mrmakent at cox.net (Mike Kent) Date: Wed, 23 Jan 2008 19:00:53 -0800 (PST) Subject: Can someone explain this unexpected raw_input behavior? References: Message-ID: Gabriel, thank you for clarifying the source of this behavior. Still, I'm surprised it would be hard-coded into Python. Consider an interactive program, that asks the user several questions, and displays paragraphs of information based on those questions. The paragraphs are output using print, and the questions are asked via raw_input. You want to do some simple debugging of the program by printing some debugging statements via 'print >>sys.stderr', and you don't want the debug output mixed in with the normal output on the screen, so you try to route the debugging output to a file by adding '2>filename' to the end of the command line. Unfortunately, you will no longer see any of the questions being printed via raw_input. The rest of the output will be fine, but the questions disappear. Your program just stops, without asking anything... you have to guess what should be there. I'm surprised that Python hard-codes this behavior without giving the programmer any way to change it. It leaves me with two options: to either always use the logging module for debugging messages (which is not odious at all, it's just that the code in question predates the logging module, which is why debugging was done as it is), or change the program so that raw_input is never used with a prompt parameter; the prompt must always be printed separately. At least I now know I'm not crazy... regarding this, anyway. From ptmcg at austin.rr.com Fri Jan 11 15:20:25 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 11 Jan 2008 12:20:25 -0800 (PST) Subject: split parameter line with quotes References: Message-ID: <7125d8e2-4881-46e8-9ffd-ab4feaf7430e@j20g2000hsi.googlegroups.com> On Jan 11, 12:50?pm, teddyber wrote: > Hello, > > first i'm a newbie to python (but i searched the Internet i swear). > i'm looking for some way to split up a string into a list of pairs > 'key=value'. This code should be able to handle this particular > example string : > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > i know i can do that with some regexp (i'm currently trying to learn > that) but if there's some other way... > > thanks Those quoted strings sure are pesky when you try to split along commas. Here is a solution using pyparsing - note the argument field access methods at the bottom. Also, the parse action attached to integer will do conversion of the string to an int at parse time. More info on pyparsing at http://pyparsing.wikispaces.com. -- Paul from pyparsing import Word, nums, alphas, quotedString, \ delimitedList, Literal, CharsNotIn, Dict, Group, \ removeQuotes arg = '''qop="auth,auth-int,auth-conf", cipher="rc4-40,rc4-56,rc4,des,3des", maxbuf=1024,charset=utf-8,algorithm=md5-sess''' # format is: delimited list of key=value groups, where value is # a quoted string, an integer, or a non-quoted string up to the next # ',' character key = Word(alphas) EQ = Literal("=").suppress() integer = Word(nums).setParseAction(lambda t:int(t[0])) quotedString.setParseAction(removeQuotes) other = CharsNotIn(",") val = quotedString | integer | other # parse each key=val arg into its own group argList = delimitedList( Group(key + EQ + val) ) args = argList.parseString(arg) # print the parsed results print args.asList() print # add dict-like retrieval capabilities, by wrapping in a Dict expression argList = Dict(delimitedList( Group(key + EQ + val) )) args = argList.parseString(arg) # print the modified results, using dump() (shows dict entries too) print args.dump() # access the values by key name print "Keys =", args.keys() print "cipher =", args["cipher"] # or can access them like attributes of an object print "maxbuf =", args.maxbuf Prints: [['qop', 'auth,auth-int,auth-conf'], ['cipher', 'rc4-40,rc4-56,rc4,des, 3des'], ['maxbuf', 1024], ['charset', 'utf-8'], ['algorithm', 'md5- sess']] [['qop', 'auth,auth-int,auth-conf'], ['cipher', 'rc4-40,rc4-56,rc4,des, 3des'], ['maxbuf', 1024], ['charset', 'utf-8'], ['algorithm', 'md5- sess']] - algorithm: md5-sess - charset: utf-8 - cipher: rc4-40,rc4-56,rc4,des,3des - maxbuf: 1024 - qop: auth,auth-int,auth-conf Keys = ['maxbuf', 'cipher', 'charset', 'algorithm', 'qop'] maxbuf = 1024 cipher = rc4-40,rc4-56,rc4,des,3des From python at rolfvandekrol.nl Mon Jan 21 09:52:59 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Mon, 21 Jan 2008 15:52:59 +0100 Subject: stdin, stdout, redmon In-Reply-To: <4794ab22$0$19179$426a74cc@news.free.fr> References: <4794a5e3$0$9014$426a74cc@news.free.fr> <4794ab22$0$19179$426a74cc@news.free.fr> Message-ID: <4794B1CB.2050908@rolfvandekrol.nl> I don't know what you did with your Python installation, but for me this works perfectly. test3.py contains: import sys print sys.stdin.readlines() test.txt contains: Testline1 Testline2 Output of 'python test3.py < test.txt' is: ['Testline1\n', 'Testline2'] Just plain simple and just works. Rolf Bernard Desnoues wrote: > Rolf van de Krol a ?crit : > >> According to various tutorials this should work. >> >> >> |import sys >> data = sys.stdin.readlines() >> print "Counted", len(data), "lines."| >> >> >> Please use google before asking such questions. This was found with only >> one search for the terms 'python read stdin' >> >> Rolf >> >> Bernard Desnoues wrote: >> >>> Hi, >>> >>> I've got a problem with the use of Redmon (redirection port monitor). >>> I intend to develop a virtual printer so that I can modify data sent >>> to the printer. >>> Redmon send the data flow to the standard input and lauchs the Python >>> program which send modified data to the standard output (Windows XP >>> and Python 2.5 context). >>> I can manipulate the standard output. >>> >>> "import sys >>> sys.stdout.write(data)" >>> >>> it works. >>> But how to manipulate standard input so that I can store data in a >>> string or in an object file ? There's no "read" method. >>> >>> "a = sys.stdin.read()" doesn't work. >>> "f = open(sys.stdin)" doesn't work. >>> >>> I don't find anything in the documentation. How to do that ? >>> Thanks in advance. >>> >>> Bernard Desnoues >>> Librarian >>> Biblioth?que de g?ographie - Sorbonne >>> > > Hello Rolf, > > I know this code because I have search a solution ! > Your google code doesn't work ! No attribute "readlines". > > >>> import sys > >>> data = sys.stdin.readlines() > > Traceback (most recent call last): > File "", line 1, in > data = sys.stdin.readlines() > AttributeError: readlines > From bearophileHUGS at lycos.com Sat Jan 5 18:07:10 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 5 Jan 2008 15:07:10 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> Message-ID: <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> Paddy: > Not really, it seems to me to be going the exact opposite way with > languages with automatic type conversions being seen as not suited for > larger programs. In Java you can add the number 1 to a string, and have it automatically converted to string before the string join... What do you think of that feature? Bye, bearophile From israelu at elbit.co.il Mon Jan 14 16:22:47 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 14 Jan 2008 13:22:47 -0800 (PST) Subject: import from question Message-ID: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> Hi all I've got three files: file a1.py: ======== the_number = None file a2.py: ======== import a1 def init(): a1.the_number = 100 file a3.py: ======== from a1 import the_number import a2 a2.init() print the_number, type(the_number) Runninr a3.py I get: None Changing a3.py to: import a1 import a2 a2.init() print a1.the_number, type(a1.the_number) gives: 100 Why doesn't it work in the first version of a3.py? Thanks, iu2 From ggpolo at gmail.com Wed Jan 23 17:42:02 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jan 2008 20:42:02 -0200 Subject: Creating new types and invoking super In-Reply-To: References: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> Message-ID: 2008/1/23, Guilherme Polo : > 2008/1/23, Arnaud Delobelle : > > On Jan 23, 8:55 pm, "Guilherme Polo" wrote: > > > Hello, > > > > Hi > > [...] > > > First I tried this: > > > > > > def init(func): > > > def _init(inst): > > > super(inst.__class__, inst).__init__() > > > func(inst) > > > > > > return _init > > > > > > class A(object): > > > @init > > > def __init__(self): pass > > > > This kind of approach can't work, you need to call super(A, obj). > > super(type(obj), obj) is pointless, it defeats the whole purpose of > > the mro! > > > > Yeh, as shown in the next examples in the previous email. Using a > decorator for that doesn't sound useful at all, was just trying > something different ;) I will stick to the no-decorator option. > > > The only way I can think of would be to create a metaclass, but I > > don't think it's worth it. super(A, obj).__init__() isn't that bad! > > > > Metaclass doesn't apply here because metaclass is related to > class-construction. This is related to instance initialization, and > I'm creating the types as the user asks. Oops, actually it can be done. But I am not going to stick to it, just did a sample here that "solves" for a not so deep structure: def init(func): def _init(cls): if hasattr(cls, "myclass"): super(cls.myclass, cls).__init__() else: super(cls.__class__, cls).__init__() func(cls) return _init class M(type): def __new__(cls, classname, bases, classdict): if not len(classdict): if 'myclass' in bases[0].__dict__: classdict['myclass'] = bases[0].__dict__['myclass'] else: classdict['myclass'] = bases[0] return type.__new__(cls, classname, bases, classdict) class Y(object): __metaclass__ = M class X(Y): @init def __init__(self): print "X" X() y = type("Z", (X, ), {}) w = type("W", (y, ), {}) y() w() > > > -- > > Arnaud > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > -- Guilherme H. Polo Goncalves > -- -- Guilherme H. Polo Goncalves From Scott.Daniels at Acm.Org Tue Jan 1 00:11:48 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 31 Dec 2007 21:11:48 -0800 Subject: using super In-Reply-To: <13nj9oc1vo7j10@corp.supernews.com> References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> <13niugpmvdls482@corp.supernews.com> <13nj1fp5m8u1i6f@corp.supernews.com> <13nj9oc1vo7j10@corp.supernews.com> Message-ID: <13njikdi21168e7@corp.supernews.com> Steven D'Aprano wrote: > On Mon, 31 Dec 2007 16:19:11 -0800, Scott David Daniels wrote: > >> Steven D'Aprano wrote: >>> On Mon, 31 Dec 2007 08:03:22 -0800, Scott David Daniels wrote: >>>> Steven D'Aprano wrote: ... >>>>> def chain(meth): # A decorator for calling super. >>>>> def f(self, *args, **kwargs): >>>>> result = meth(self, *args, **kwargs) >>>>> S = super(self.__class__, self) >>>> This line is the problem. The class parameter needs to be the class >>>> (B in this case) in which the chaining method is defined, not that of >>>> the object itself. >>> One minor correction: the class parameter needs to be the class >>> *itself*, not the class *name* (which would be the string "B"). >> Point taken. >> >>> I don't quite understand your description though. What do you mean "the >>> chaining method is defined"? chain() is defined outside of a class. >> The class where f (the chaining method) is defined; equivalently, the >> class in which the @chain is used. > > So why doesn't self.__class__ work? That's the class in which @chain is > used. OK, here's a simple 3-class example: class A(object): def meth(self): print 'A.meth:', self.__class__, '---' def pn(self): return '' class B(A): def meth(self): super(B, self).meth() print 'B.meth:', self.__class__, super(B, self).pn() def pn(self): return '' class C(B): def meth(self): super(C, self).meth() print 'C.meth:', self.__class__, super(C, self).pn() def pn(self): return '' c = C() c.meth() # Figure out why it printed what it did. # If not clear yet, how about this: for class_ in C, B: print class_.__name__, super(class_, c).pn() # And a bigger example (re-using A) to show why we class B0(A): def meth(self): super(B0, self).meth() print 'B0.meth:', self.__class__, super(B0, self).pn() def pn(self): return '' class B1(B0): def meth(self): super(B1, self).meth() print 'B1.meth:', self.__class__, super(B1, self).pn() def pn(self): return '' class B2(B0): def meth(self): super(B2, self).meth() print 'B2.meth:', self.__class__, super(B2, self).pn() def pn(self): return '' class C1(B1, B2): def meth(self): super(C1, self).meth() print 'C1.meth:', self.__class__, super(C1, self).pn() def pn(self): return '' class D1(C1): def meth(self): super(D1, self).meth() print 'D1.meth:', self.__class__, super(D1, self).pn() def pn(self): return '' d = D1() d.meth() # Figure out why it printed what it did. for class_ in D1, C1, B1, B2, B0: print class_.__name__, super(class_, d).pn() # Now (after much cogitation) might that do it? # finally, just a fillip, predict this before you run it: class E(D1, C): def meth(self): super(E, self).meth() print 'E.meth:', self.__class__, super(E, self).pn() def pn(self): return '' e = E() e.meth() for class_ in E, D1, C1, B1, B2, B0, C, B: print class_.__name__, super(class_, e).pn() > I can clearly see that it doesn't work, I just don't understand why. I'd > be inclined to chalk it up to super() being a mysterious black box that > makes no sense *wink* .... super (and mro) work to get to all the superclasses in an order that produces subtypes before their supertypes. The diamond inheritance examples "show" why its needed. -Scott From ec21i at hotmail.com Tue Jan 1 06:23:27 2008 From: ec21i at hotmail.com (ec21i at hotmail.com) Date: Tue, 1 Jan 2008 03:23:27 -0800 (PST) Subject: Fashion Footwear Industrial Co.,Ltd(Fujian,CHINA) Message-ID: <3a1b5ef1-ad23-4609-98cf-8b590bcc11f2@u10g2000prn.googlegroups.com> Dear my friend It is our pleasure to meet you here. we are wholesaler sport shoes,clothing,electrons in Fujian of China. our website: http://www.ec21i.com We are professional and honest wholesaler of all kinds of brand sneaks and apparel.the products our company supply are as follows: 1).Nike Jordans Jordan 1 jordan 1.5 jordan 2 jordan 3 jordan 3.5 jordan 4 jordan 5 jordan 5.5 jordan 6 jordan 6.5 jordan 7 jordan 8 jordan 9 jordan 9.5 jordan 10 jordan 11 jordan 12 jordan 13 jordan 13.5 jordan 14 jordan 15 jordan 16 jordan 17 jordan 18 jordan 18.5 jordan 19 jordan 20 jordan 21 jordan 21.5 jordan 22 jordan King jordan Dub Zero Jordan 23 Jordan 7.5 2).Air Force One Air Force one (low) Air Force one (High) Air Force one (Mid) Air Force one (clear) Air Force One 25 year 3).SHOX Shox R3 Shox R4 Shox R5 Shox TL1 Shox TL2 Shox TL3 Shox NZ Shox OZ Shox Turbo Show GO Shox CL Shox Coqnescenti Shox Energia Shox Explodine Shox Monster Shox Rhythmic Shox Warrior 4).Bape Shoes Bape Bape (transparent) 5).Air max AirMax 90 AirMax 95 AirMax 97 AirMax 2003 AirMax 2004 AirMax 2005 Air Max 2006 AirMax 180 AirMax LTD AirMax TN AirMax solas AirMax 87 AirMax Rift 6).Puma Puma Rpt2 Puma SK6 Puma Jayfi Puma Cir Puma Speed Puma Repli Puma Future Cat Puma Mostro Puma Lifestyle 7).Dunk SB Dunk High Dunk Low 8).Timberland Timberland High Timberland Low 9).Adidas Adidas 35 Adicolor Country city sense Adidas NBA 11).Prada & Gucci Prada Gucci 12).Footballer Shoes Footballer 13).Locaste 14).converse & Reebok converse Reebok 15).D&G shoes 16).Dsquared2 shoes 17).James shoes 18).Nike King 9).Children shoes Jordan Shox 20).Women shoes Women Jordans Women Shox R3 Women Shox R4 Women AirMax 95&97 Women AirMax 03&06 Women Dunk Women Shox NZ Women AF1 21).sandal & baboosh Nike Puma Gucci Prada CLOTHES 1).Bape 2).ED Hardy 3).BBC 4).CLH 5).LRG 6).Artful Dodger Hoodies 7).GINO GREEN GLOBAL 8).10 Deep 9).A&F Coat 11).Jersey NBA Jersey Football Jersey 12).Juicy Bikini 13).Adidas Coat 14).F1 Coat 15).D&G Coat 16).Superman Coat 17).NBA Coat JEAN 1).E&D Jeans 2).BBC Jeans 3).BAPE Jeans 4).D&G Jeans 5).EVSIU Jeans 6).Red monkey 7).COOGI Jeans T-shirt 1).POLO 2007 polo(women) 2007 POLO IIII(Men) POLO (stripe) polo (small ) 2).Lacoste Lacoste (LONG) Lacoste (SHORT) 3).Name Brand shirt D&G Shirt Giorgio Armani TN Shirt 4).BBC T-shirt 5).LRG & gina green glalal 6).Triumvir 7).ED handy 8).Evsiu 9).R.M.B 10).CLOT Burse & Handbag 1).LV Bag 2).Gucci Bag 3).Dior Bag 4).Chanel Bag 5).Fendi Bag 6).Coach Bag 7).Burberrys Bag 8).Prada Bag 9).Man Leisure Bag 11).D&G bag 12).nike bag 13).Wallet 14).Suitcase Electronics 1).Vertu Mobile 2).New iphone Mobile 3).Nokia Mobile 4).moto Mobile 5).PSP Game & memory card 6).Sony Mobile 7).Samsung Mobile 8).Ipod nano 9).Sony PS3 10).Laptops IBM laptops DELL laptops Sony laptops ASUS laptops CAP 1).ED Hardy Cap 2).New Bape & NY Cap 3).RMC Cap 4).New era NBA 5).F1 6).Chanel 7).D&G 8).gucci 9).LV 10).Prada 11).PUMA 12).wool WATCH 1).Rolex 2).Omega 3).Cartier 4).Chanel 5).Piaget 6).Breitling 7).Bvlgari 8).Corum Sunglasses 1).Gucci Sunglasses 2).D&G Sunglasses 3).Dior Sunglasses 4).LV Sunglasses 5).Chanel Sunglasses 6).Prada Sunglasses 7).Versace Sunglasses 8).Giorgio Armani Strap 1).Bape Strap 2).D&G Strap 3).Gucci Strap 4).LV Strap 5).Scarf Other 1).Lighter size chart Men Size: US: 7 8 8.5 9 9.5 10 10.5 11 11.5 12 13 14 15 UK: 6 7 7.5 8 8.5 9 9.5 10 10.5 11 12 13 14 EUR: 40 41 42 42.5 43 44 44.5 45 45.5 46 47.5 48 49 Women Size: US: 5 5.5 6 6.5 7 7.5 8 8.5 UK: 2.5 3 3.5 4 4.5 5 5.5 6 EUR: 35.5 36 36.5 37.5 38 38.5 39 40 Kid's US: 1 2 3 4 5 6 7 7.5 8 8.5 9 9.5 10 10.5 11 11.5 12 12.5 13 13.5 UK: 13 1 2 3 4 5 6 6.5 7 7.5 8 8.5 9 9.5 10 10.5 11 11.5 12 12.5 EUR:17 18 19 20 21 22 23 24 24.5 25 25.5 26 26.5 27 27.5 28 29 30 30.5 31 Clothing Size: S M L XL XXL XXXL XXXXL XXXXXL 7.because the space of the website is limited,we can also supply many other products which be not showed out in our site. if you have the photos of the products you need , we are pleasure to supply for your orders. And our company can supply for our customers ,as follow: 1. top quality.all our products have top quality. 2. most rational price. we offer the most competitive price to you to open your market. So today most of our products have sold well in the America, Europe, Middle East, Southeast Asia etc.. 3. safe and fast shipment. As different country you are in, we will deliver the products to you by different ways and pledge to arrive to your address 100%.and we will send the products to you within 24h after we get your payment. 4.many products in stock. We have many products in stock and kinds of size you need , also include kid's. 5.our credit. If the products can be not delivered to your address as our reason, we will refund the money you paid. Hope sincerely to have glad and long term business relationship with you. If you are interested in our products and have any problem, welcome to contact us. Please trust us , we will be your best choice !!! Website : http://www.ec21i.com MSN and E-mail: ec21i at hotmail.com Michael Fashion Footwear Industrial Co.,Ltd.(Fujian,CHINA) From asmodai at in-nomine.org Thu Jan 17 12:14:13 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 17 Jan 2008 18:14:13 +0100 Subject: working with a subversion repo In-Reply-To: <7f156399-d9ae-4f13-a80f-0ffe41d89427@s12g2000prg.googlegroups.com> References: <7f156399-d9ae-4f13-a80f-0ffe41d89427@s12g2000prg.googlegroups.com> Message-ID: <20080117171412.GN61556@nexus.in-nomine.org> -On [20080117 17:21], Luke (Luke.Visinoni at gmail.com) wrote: >I am able to import a module named "svn" on my ubuntu machine, but this >module is not available on windows. The entries libsvn and svn are installed in site-packages when you install the Python (SWIG) bindings for Subversion. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Nothing is constant but change... From martin at librador.com Mon Jan 21 02:01:20 2008 From: martin at librador.com (Martin Vilcans) Date: Mon, 21 Jan 2008 08:01:20 +0100 Subject: Looping through the gmail dot trick In-Reply-To: References: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> Message-ID: On Jan 20, 2008 8:58 PM, Martin Marcher wrote: > are you saying that when i have 2 gmail addresses > > "foo.bar at gmail.com" and > "foobar at gmail.com" > > they are actually treated the same? That is plain wrong and would break a > lot of mail addresses as I have 2 that follow just this pattern and they > are delivered correctly! > > Do you have any reference on that where one could read up why gmail would > have such a behaviour? Try the SMTP spec. IIRC there's a passage there that says that the server should try to make sense of addresses that don't map directly to a user name. Specifically, it says that firstname.lastname should be mapped to the user with those first and last names. -- martin at librador.com http://www.librador.com From gagsl-py2 at yahoo.com.ar Tue Jan 1 12:50:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Jan 2008 15:50:33 -0200 Subject: Using mouse References: <13nkl1ubh76bo8e@corp.supernews.com> Message-ID: En Tue, 01 Jan 2008 12:54:54 -0200, Grant Edwards escribi?: > On 2007-12-31, Lucas Prado Melo wrote: > >> I would like to control mouse events (i.e. I would like to >> "click" and move mouse around by code). How do I do this in >> python? > > http://python-xlib.sourceforge.net/doc/html/python-xlib_14.html On Windows, use the mouse_event function http://msdn2.microsoft.com/en-us/library/ms646260.aspx Available on pywin32 https://sourceforge.net/projects/pywin32/ or using ctypes directly. -- Gabriel Genellina From rong.xian at gmail.com Sun Jan 27 22:53:02 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 19:53:02 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> Message-ID: <72a03212-7cf3-486d-ac70-c97a002d90c7@n20g2000hsh.googlegroups.com> On 1?28?, ??5?50?, John Machin wrote: > On Jan 28, 7:47 am, "Mark Tolonen" > wrote: > > > > > > > >"John Machin" wrote in message > > >news:eeb3a05f-c122-4b8c-95d8-d13741263374 at h11g2000prf.googlegroups.com... > > >On Jan 27, 9:17 pm, glacier wrote: > > >> On 1?24?, ??3?29?, "Gabriel Genellina" > > >> wrote: > > > >*IF* the file is well-formed GBK, then the codec will not mess up when > > >decoding it to Unicode. The usual cause of mess is a combination of a > > >human and a text editor :-) > > > SAX uses the expat parser. From the pyexpat module docs: > > > Expat doesn't support as many encodings as Python does, and its repertoire > > of encodings can't be extended; it supports UTF-8, UTF-16, ISO-8859-1 > > (Latin1), and ASCII. If encoding is given it will override the implicit or > > explicit encoding of the document. > > > --Mark > > Thank you for pointing out where that list of encodings had been > cunningly concealed. However the relevance of dropping it in as an > apparent response to my answer to the OP's question about decoding > possibly butchered GBK strings is .... what? > > In any case, it seems to support other 8-bit encodings e.g. iso-8859-2 > and koi8-r ... > > C:\junk>type gbksax.py > import xml.sax, xml.sax.saxutils > import cStringIO > > unistr = u''.join(unichr(0x4E00+i) + unichr(ord('W')+i) for i in > range(4)) > print 'unistr=%r' % unistr > gbkstr = unistr.encode('gbk') > print 'gbkstr=%r' % gbkstr > unistr2 = gbkstr.decode('gbk') > assert unistr2 == unistr > > print "latin1 FF -> utf8 = %r" % > '\xff'.decode('iso-8859-1').encode('utf8') > print "latin2 FF -> utf8 = %r" % > '\xff'.decode('iso-8859-2').encode('utf8') > print "koi8r FF -> utf8 = %r" % '\xff'.decode('koi8-r').encode('utf8') > > xml_template = """%s data>""" > > asciidoc = xml_template % ('ascii', 'The quick brown fox etc') > utf8doc = xml_template % ('utf-8', unistr.encode('utf8')) > latin1doc = xml_template % ('iso-8859-1', 'nil illegitimati > carborundum' + '\xff') > latin2doc = xml_template % ('iso-8859-2', 'duo secundus' + '\xff') > koi8rdoc = xml_template % ('koi8-r', 'Moskva' + '\xff') > gbkdoc = xml_template % ('gbk', gbkstr) > > for doc in (asciidoc, utf8doc, latin1doc, latin2doc, koi8rdoc, > gbkdoc): > f = cStringIO.StringIO() > handler = xml.sax.saxutils.XMLGenerator(f, encoding='utf8') > xml.sax.parseString(doc, handler) > result = f.getvalue() > f.close > print repr(result[result.find(''):]) > > C:\junk>gbksax.py > unistr=u'\u4e00W\u4e01X\u4e02Y\u4e03Z' > gbkstr='\xd2\xbbW\xb6\xa1X\x81 at Y\xc6\xdfZ' > latin1 FF -> utf8 = '\xc3\xbf' > latin2 FF -> utf8 = '\xcb\x99' > koi8r FF -> utf8 = '\xd0\xaa' > 'The quick brown fox etc' > '\xe4\xb8\x80W\xe4\xb8\x81X\xe4\xb8\x82Y\xe4\xb8\x83Z' > 'nil illegitimati carborundum\xc3\xbf' > 'duo secundus\xcb\x99' > 'Moskva\xd0\xaa' > Traceback (most recent call last): > File "C:\junk\gbksax.py", line 27, in > xml.sax.parseString(doc, handler) > File "C:\Python25\lib\xml\sax\__init__.py", line 49, in parseString > parser.parse(inpsrc) > 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 > xml.sax._exceptions.SAXParseException: :1:30: unknown > encoding > > C:\junk>- ??????? - > > - ??????? - Thanks,John. It's no doubt that you proved SAX didn't support GBK encoding. But can you give some suggestion on how to make SAX parse some GBK string? From grante at visi.com Mon Jan 21 11:15:02 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 21 Jan 2008 16:15:02 -0000 Subject: When is min(a, b) != min(b, a)? References: Message-ID: <13p9h86e9aoa43e@corp.supernews.com> On 2008-01-21, Albert Hopkins wrote: > This issue may have been referred to in > news: but I didn't > entirely understand the explanation. Basically I have this: > > >>> a = float(6) > >>> b = float('nan') > >>> min(a, b) > 6.0 > >>> min(b, a) > nan > >>> max(a, b) > 6.0 > >>> max(b, a) > nan > > Before I did not know what to expect, but I certainly didn't expect > this. So my question is what is the min/max of a number and NaN or is it > not defined (for which I would have expected either an exception to be > raised or NaN returned in each case). For applications I work on, it should be NaN. But I think the result of comparing a Normal to a NaN is undefined, so the above behavior is allowed by the IEEE spec. > As a corrollary would I be able to rely on the above behavior or is it > subject to change (to fix a bug in min/max perhaps :-)? According to Wikipedia: In the proposed IEEE 754r revision of that standard the same rule applies, except that a few anomalous functions (such as the maxnum function, which returns the maximum of two operands which are expected to be numbers) favour numbers -- if just one of the operands is a NaN then the value of the other operand is returned. A different approach has been implemented in the NaN 'toolbox' for GNU Octave and MATLAB. In that toolbox, NaNs are assumed to represent missing values and so the statistical functions ignore NaNs in the data instead of propagating them. Every computation in the NaN toolbox is based on the data values only, which can be useful if it is known that NaNs cannot be produced by errors. -- Grant Edwards grante Yow! Remember, in 2039, at MOUSSE & PASTA will visi.com be available ONLY by prescription!! From sallport at altirium.com Wed Jan 2 04:12:32 2008 From: sallport at altirium.com (Steven Allport) Date: Wed, 2 Jan 2008 09:12:32 -0000 Subject: Problem with parsing email message with extraneous MIMEinformation References: <3PCdnchSqYywI_banZ2dnUVZ8qydnZ2d@bt.com> Message-ID: <79KdnVCfW_cfyObanZ2dnUVZ8u-dnZ2d@bt.com> Thanks for the response. The section of the email is an actual message fragment. The first blank line that appears in the message is immediately after the 1st ' boundary="------------m.182DA3C.BE6A21A3"' There are no blank line prior to this in the message. In the example that was snipped from an actual exported message there is a set of 5 _NextPart_ lines followed by the message header for the 1st attached message then a set of 7 _NextPart_ lines followed by the messge header for the 2nd attached message. Comprising in total 6 set of _NextPart_ lines. As some of the attached messages also contained messages as attachments. Unfortunately it is not possible for me to post or leave the message anywhere for you and so far I have been unable to recreate a test message of similar format. I will endeavour to do so and will if I can will let you know where it is. "Gabriel Genellina" wrote in message news:mailman.2780.1198749836.13605.python-list at python.org... > En Fri, 21 Dec 2007 10:22:53 -0300, Steven Allport > escribi?: > >> I am working on processing eml email message using the email module >> (python >> 2.5), on files exported from an Outlook PST file, to extract the >> composite >> parts of the email. In most instances this works fine, the message is >> read >> in using message_from_file, is_multipart returns True and I can process >> each >> component and extract message attachments. >> >> I am however running into problem with email messages that contain emails >> forwarded as attachments. The email has some additional encapulated >> header >> information from each of the forwared emails.When I processes the files >> is_multipart returns False the content-type is reported as text/plain >> and the payload includes all the message body from 'This message is in >> MIME >> format' though to the end. >> >> for example. >> >> >> MIME-Version: 1.0 >> X-Mailer: Internet Mail Service (5.5.2448.0) >> This message is in MIME format. Since your mail reader does not >> understand >> this format, some or all of this message may not be legible. >> ------_=_NextPart_000_01C43634.1A06A235 >> ------_=_NextPart_001_01C43634.1A06A235 >> ------_=_NextPart_001_01C43634.1A06A235 >> ------_=_NextPart_001_01C43634.1A06A235-- >> ------_=_NextPart_000_01C43634.1A06A235 >> >> ------_=_NextPart_002_01C43634.1A06A235 >> ------_=_NextPart_003_01C43634.1A06A235 >> ------_=_NextPart_003_01C43634.1A06A235 >> ------_=_NextPart_003_01C43634.1A06A235-- >> ------_=_NextPart_002_01C43634.1A06A235 >> ------_=_NextPart_002_01C43634.1A06A235-- >> ------_=_NextPart_000_01C43634.1A06A235 >> Mime-Version: 1.0 >> Content-Type: multipart/mixed; >> boundary="------------m.182DA3C.BE6A21A3" >> >> >> If I remove the section of the email from the 'This is in MIME format' >> through to Mime-Version: 1.0 the message is processed correctly. (ie. >> is_multipart = True , Content-Type = multipart/mixed etc.) > > Is this an actual message fragment? Can't be, or else it's broken. Headers > are separated from message body by one blank line. At least there should > be a blank line before "This message is in MIME...". > And are actually all those xxx_NextPart_xxx lines one after the other? > >> Could anybody tell me if the above message header breaks the conventions >> for >> email messages or is it just some that is not handled correctly by the >> email >> module. > > Could you post, or better leave available somewhere, a complete message > (as originally exported by Outlook, before any processing)? > > -- > Gabriel Genellina > > From hat at se-162.se.wtb.tue.nl Wed Jan 23 06:39:27 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 23 Jan 2008 12:39:27 +0100 Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? References: Message-ID: On 2008-01-23, ioscas at gmail.com wrote: > Hi, I am looking for a HTML parser who can parse a given page into > a DOM tree, and can reconstruct the exact original html sources. Why not keep a copy of the original data instead? That would be VERY MUCH SIMPLER than trying to reconstruct a parsed tree back to original source text. sincerely, Albert From deets at nospam.web.de Tue Jan 1 07:36:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 Jan 2008 13:36:57 +0100 Subject: ElementTree should parse string and file in the same way In-Reply-To: <13njba091eipl6f@corp.supernews.com> References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> Message-ID: <5tuqfaF1f8u9tU1@mid.uni-berlin.de> Steven D'Aprano schrieb: > On Tue, 01 Jan 2008 01:53:47 +0000, Peter Pei wrote: > >> You are talking shit. It is never about whether it is hard to write a >> wrapper. It is about bad design. I should be able to parse a string and >> a file in exactly same way, and that should be provided as part of the >> package. > > Oh my, somebody decided to start the new year with all guns blazing. > > Before abusing anyone else, have you considered asking *why* ElementTree > does not treat files and strings the same way? I believe the writer of > ElementTree, Fredrik Lundh, frequents this newsgroup. > > It may be that Fredrik doesn't agree with you that you should be able to > parse a string and a file the same way, in which case there's nothing you > can do but work around it. On the other hand, perhaps he just hasn't had > a chance to implement that functionality, and would welcome a patch. > > Fredrik, if you're reading this, I'm curious what your reason is. I don't > have an opinion on whether you should or shouldn't treat files and > strings the same way. Over to you... I think the decision is pretty clear to everybody who is a code-monkey and not a Peter-Pei-School-of-Excellent-And-Decent-Designers-attendant: when building a XML-document, you start from a Element or Elementtree and often do things like root_element = for child in some_objects: root_element.append(XML("""""" % child.attribute)) Which is such a common usage-pattern that it would be extremely annoying to get a document from XML/fromstring and then needing to extract the root-element from it. And codemonkeys know that in python doc = et.parse(StringIO(string)) is just one import away, which people who attend to Peter-Pei-School-of-Excellent-And-Decent-Designers may have not learned yet - because they are busy praising themselves and coating each other in edible substances before stepping out into the world and having all code-monkeys lick off their greatness in awe. http://www.youtube.com/watch?v=FM7Rpf1x7RU Diez From kyosohma at gmail.com Fri Jan 11 12:11:08 2008 From: kyosohma at gmail.com (Mike) Date: Fri, 11 Jan 2008 09:11:08 -0800 (PST) Subject: Using eggs References: <9a2575c7-5b62-4f00-a813-635a82e96b79@k39g2000hsf.googlegroups.com> Message-ID: <50913183-4424-47db-9bfa-5606a1be81d2@21g2000hsj.googlegroups.com> On Jan 11, 10:33 am, oj wrote: > Hi all! > > As is about to become apparent, I really don't know what I'm doing > when it comes to using eggs. > > I'm writing some software that is going to be deployed on a machine as > a number of eggs. Which is all well and good. > > These eggs all end up depending on each other; modules in egg A want > to import modules in egg B etc. > > It's not really practical to add the path to each individual egg to > the PYTHONPATH (although there's all in a directory that is in > PYTHONPATH). > > Do I have to add boiler-plate code to the beginning of all the modules > with these dependencies to check if modules are available and require > the eggs if they aren't? Or is there a way I can have stuff 'just > work' as it does in the development environment when the modules > haven't been bundled up into eggs? > > On a similar note, I can't seem to get the automatic script creation > stuff in setuptools to create scripts that have additional > requirements. I tried defining extra requires giving the names of > other eggs that will be required, and then specifying these as extras > to the console_scripts, but the generated scripts were no different. > Am I doing something wrong? Or am I just not understanding something? > > I'm muddling through getting this all working at the moment, but I get > the distinct impression that there's a better (correct?) way that I'm > not aware of. > > Sorry for such a vague posting. > > -Oli I know when I've asked questions about eggs and setup-tools, I was referred to the Distutils user group. I would cross-post there for double the fun! http://mail.python.org/mailman/listinfo/distutils-sig Mike From info at wingware.com Wed Jan 16 14:50:20 2008 From: info at wingware.com (Wingware) Date: Wed, 16 Jan 2008 14:50:20 -0500 Subject: ANN: Wing IDE 3.0.3 released Message-ID: <478E5FFC.2070008@wingware.com> Hi, We're happy to announce version 3.0.3 of Wing IDE, an advanced development environment for the Python programming language. It is available from: http://wingware.com/downloads This release focuses on fixing some usability issues found in Wing 3.0.2, including fixes for input handling in Debug I/O, Zope debugging on 64-bit Linux, several emacs and vi mode improvements, and about 34 other bugs. See the change log for details: http://wingware.com/pub/wingide/3.0.3/CHANGELOG.txt It is a free upgrade for all Wing 3.0 users. *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. New features added in Wing 3.0 include: * Multi-threaded debugger * Debug value tooltips in editor, debug probe, and interactive shell * Autocompletion and call tips in debug probe and interactive shell * Automatically updating project directories * Testing tool, currently supporting unittest derived tests (*) * OS Commands tool for executing and interacting with external commands (*) * Rewritten indentation analysis and conversion (*) * Introduction of Wing IDE 101, a free edition for beginning programmers * Available as a .deb package for Debian and Ubuntu * Support for Stackless Python * Support for 64 bit Python on Windows and Linux (*)'d items are available in Wing IDE Professional only. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). *Purchasing & Upgrading* Wing IDE Professional & Wing IDE Personal are commercial software and require a license to run. To upgrade a 2.x license or purchase a new 3.x license: Upgrade: https://wingware.com/store/upgrade Purchase: https://wingware.com/store/purchase Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From jr9445 at ATT.COM Fri Jan 11 16:21:06 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 11 Jan 2008 15:21:06 -0600 Subject: split parameter line with quotes 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 teddyber > Sent: Friday, January 11, 2008 1:51 PM > To: python-list at python.org > Subject: split parameter line with quotes > > Hello, > > first i'm a newbie to python (but i searched the Internet i swear). > i'm looking for some way to split up a string into a list of pairs > 'key=value'. This code should be able to handle this particular > example string : > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > i know i can do that with some regexp (i'm currently trying to learn > that) but if there's some other way... > import re s='''qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,3des",m axbuf=1024,charset=utf-8,algorithm=md5-sess''' print s all = re.findall(r'(.*?)=(".*?"|[^"]*?)(,|$)', s) print all for i in all: print i[0], "=", i[1].strip('"') Output: qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,3des",maxbuf =1024,charset=utf-8,algorithm=md5-sess [ ('qop', '"auth,auth-int,auth-conf"', ','), ('cipher', '"rc4-40,rc4-56,rc4,des,3des"', ','), ('maxbuf', '1024', ','), ('charset', 'utf-8', ','), ('algorithm', 'md5-sess', '') ] qop = auth,auth-int,auth-conf cipher = rc4-40,rc4-56,rc4,des,3des maxbuf = 1024 charset = utf-8 algorithm = md5-sess ***** 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 grante at visi.com Tue Jan 1 09:54:54 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Jan 2008 14:54:54 -0000 Subject: Using mouse References: Message-ID: <13nkl1ubh76bo8e@corp.supernews.com> On 2007-12-31, Lucas Prado Melo wrote: > I would like to control mouse events (i.e. I would like to > "click" and move mouse around by code). How do I do this in > python? http://python-xlib.sourceforge.net/doc/html/python-xlib_14.html -- Grant Edwards grante Yow! Pardon me, but do you at know what it means to be visi.com TRULY ONE with your BOOTH! From george.maggessy at gmail.com Tue Jan 8 13:32:06 2008 From: george.maggessy at gmail.com (George Maggessy) Date: Tue, 8 Jan 2008 10:32:06 -0800 (PST) Subject: Pet Store References: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com> <5ugv69F1hqn2cU3@mid.uni-berlin.de> Message-ID: <44713824-c8c9-4a4c-af7e-042260068c0c@x69g2000hsx.googlegroups.com> Yeap. It is. I'm looking for something like that app. Smth that I could base my future developments on. On Jan 8, 1:47 am, Marc 'BlackJack' Rintsch wrote: > On Mon, 07 Jan 2008 22:21:53 -0800, George Maggessy wrote: > > I'm an experience Java developer trying to learn Python. I just > > finished the Python tutorial on python.org and I'm currently reading > > the "Learning Python" book. However, if I could find something like a > > simple web app with some best practices, such as those famous "Java > > Pet Store" apps, I think that would help me to fill up some gaps in my > > learning process. Does anybody know any app like that? > > Isn't that a web application using Java web frameworks? So you are > looking for a Python web framework with a "Pet Store" tutorial? > > Ciao, > Marc 'BlackJack' Rintsch From steven at REMOVE.THIS.cybersource.com.au Sun Jan 6 16:09:41 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 06 Jan 2008 21:09:41 -0000 Subject: Delete lines containing a specific word References: Message-ID: On Sun, 06 Jan 2008 09:21:33 -0800, Francesco Pietra wrote: > Please, how to adapt the following script (to delete blank lines) to > delete lines containing a specific word, or words? That's tricky, because deleting lines from a file isn't a simple operation. No operating system I know of (Windows, Linux, OS X) has a "delete line" function. Do you really need to delete the lines in place? It would be much simpler to leave the original data as-is, and create a new file with just the lines that aren't deleted. > f=open("output.pdb", "r") > for line in f: > line=line.rstrip() > if line: > print line > f.close() How to adapt this script: First, think about what this script does. That is, it goes through each line, and if the line is not blank, it prints it. What do you want it to do instead? You want it to print the line if the line doesn't contain a specific word. So that's the first thing you need to change. Secondly, you might want the script to write its output to a file, instead of printing. So, instead of the line "print line", you want it to write to a file. Before you can write to a file, you need to open it. So you will need to open another file: you will have two files open, one for input and one for output. And you will need to close them both when you are finished. Does that help you to adapt the script? > If python in Linux accepts lines beginning with # as comment lines, > please also a script to comment lines containing a specific word, or > words, and back, to remove #. The same process applies. Instead of "delete line", you want to "comment line". -- Steven From python at rolfvandekrol.nl Mon Jan 28 20:47:58 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Tue, 29 Jan 2008 02:47:58 +0100 Subject: Executing other python code In-Reply-To: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: <479E85CE.6000507@rolfvandekrol.nl> AFAIK this can't be done with just python. You can use the C API of Python to achieve this. I don't know the details of that, but I guess you will need this (http://docs.python.org/api/api.html). Rolf Tim Rau wrote: > I'm working on a game, and I'd like players to be able to define thier > ships with scripts. Naturally, I don't want to give them the entire > program as thier romping ground. I would like to invoke a seperate > interpreter for these files, and give it a limited subset of the > functions in my game. What is the best way to achieve this effect? > From carsten at uniqsys.com Thu Jan 17 09:48:23 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 17 Jan 2008 09:48:23 -0500 Subject: Stop tab-completing empty lines! In-Reply-To: References: Message-ID: <1200581303.3475.9.camel@dot.uniqsys.com> On Thu, 2008-01-17 at 00:58 -0800, Casey Rodarmor wrote: > Hi everybody, > > I have the following in my python startup file: > > import readline, rlcompleter > readline.parse_and_bind("tab: complete") > > This lets me tab complete identifiers in the interpreter beautifully, > but there's a tiny problem... If I'm sitting at the beginning of a > blank line and just want a tab, it tries to tab complete, which kind > of a pain. > > -=SIMULATED PYTHON PROMPT=- > >>> def mega_awesome_function(cool_stuff, **some_sweet_kwargs): > ... X > > (The X is where I press tab and get super annoyed) Patching rlcompleter.py in the python library thusly seems to do the trick: """ --- rlcompleter.py.bak 2008-01-17 09:35:06.000000000 -0500 +++ rlcompleter.py 2008-01-17 09:35:08.000000000 -0500 @@ -99,6 +99,7 @@ defined in self.namespace that match. """ + if text=="": return ['\t'] import keyword matches = [] n = len(text) """ Note that this prevents tab-completion not only at the beginning of the line but also at the beginning of a token, i.e. after a parenthesis or a comma etc. I don't know if it's possible to have the completer distinguish between the beginning of a token in the middle of the line and the beginning of the line, though. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 04:44:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 27 Jan 2008 09:44:49 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> Message-ID: <13pokkh4ilf5227@corp.supernews.com> On Sun, 27 Jan 2008 08:58:01 +0000, over wrote: > On Fri, 25 Jan 2008 17:44:07 -0800 (PST), ajaksu > wrote: > >>On Jan 25, 11:36 pm, ajaksu wrote: >>> On Jan 25, 11:10 pm, o... at thepond.com wrote: >>[...] >> >>Gaah, is this what's going on? >> >>ajaksu at Belkar:~$ cat error.txt >>This is not assembler... >> >>ajaksu at Belkar:~$ ndisasm error.txt >>00000000 54 push sp >>00000001 686973 push word 0x7369 00000004 206973 >>and [bx+di+0x73],ch 00000007 206E6F and [bp+0x6f],ch >>0000000A 7420 jz 0x2c >>0000000C 61 popa >>0000000D 7373 jnc 0x82 >>0000000F 656D gs insw >>00000011 626C65 bound bp,[si+0x65] 00000014 722E >> jc 0x44 >>00000016 2E db 0x2E >>00000017 2E db 0x2E >>00000018 0A db 0x0A >> >>:/ > > not sure what you're saying. Sure looks like assembler to me. Take the > '54 push sp'. The 54 is an assembler opcode for push and the sp is the > stack pointer, on which it is operating. Deary deary me... Have a close look again at the actual contents of the file: $ cat error.txt This is not assembler... If you run the text "This is not assembler..." through a disassembler, it will obediently disassemble the bytes "This is not assembler..." into a bunch of assembler opcodes. Unfortunately, although the individual opcodes are "assembly", the whole set of them together is nonsense. You'll see that it is nonsense the moment you try to execute the supposed assembly code. It would be a fascinating exercise to try to generate a set of bytes which could be interpreted as both valid assembly code *and* valid English text simultaneously. For interest, here you will find one quine (program which prints its own source code) which is simultaneously valid in C and TCL, and another which is valid in C and Lisp: http://www.uwm.edu/~chruska/recursive/selfish.html -- Steven From xkenneth at gmail.com Wed Jan 2 12:18:38 2008 From: xkenneth at gmail.com (xkenneth) Date: Wed, 2 Jan 2008 09:18:38 -0800 (PST) Subject: XML-XSD Processing/Creation. Message-ID: Hi All, So i'm working with the WITSML standard, which is a pretty massive standard defined in XML for the transfer of oilfield data. There are a ton of XSD files for defining and checking all data in the WITSML format. I'd like to be able to easily create XML based on the types defined by the WITSML XSD files. Is there any way to create a basic XML object based on an XSD file and then populate it with data. Can i create python classes based off the XSD files? What else can I do with the XSD files? I'm looking for a really simplistic way to work with WITSML in python. Regards, Kenneth Miller Thanks a ton! From martin at marcher.name Tue Jan 8 09:18:33 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 08 Jan 2008 15:18:33 +0100 Subject: use fileinput to read a specific line References: Message-ID: Fredrik Lundh wrote: > Martin Marcher wrote: > >>> i need to read line 4 from a header file >> >> http://docs.python.org/lib/module-linecache.html > > I guess you missed the "using linecache will crash my computer due to > memory loading, because i am working on 2000 files each is 8mb" part. oops sorry indeed still the enumerate version seems fine: >>> for no, line in enumerate(file("data.txt", "r")): ... print no, line ... someone posted this already i think (or was it another thread?) -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From max at alcyone.com Fri Jan 4 04:24:48 2008 From: max at alcyone.com (Erik Max Francis) Date: Fri, 04 Jan 2008 01:24:48 -0800 Subject: dictionary/hash and '1' versus 1 In-Reply-To: References: Message-ID: Reedick, Andrew wrote: > As a Perl monkey in the process of learning Python, I just stepped on > the "'1' (string) is not the same as 1 (integer) in regards to keys for > dictionaries/hashes" landmine. This isn't a landmine; this is a _good_ thing. Python is strongly typed. > Is there a good way to ensure that > numbers represented as strings or ints do not get mixed up as keys? Convert them all to either strings or integers (whichever is more useful) before you add them to the dictionary, really. > It's fugly to wrap every key reference in str(), ex: > foo[str(some_func(i))]. Then wrap it in a function or a method of one of your classes. You only need to write it once. > It's tedious to add a has_key before every key > lookup. There's no need to do this, though you don't say why you're bothering to. Either use .setdefault, or just query and get the exception, or just insert the new key, value pair to override the contents. > Any good solutions or accepted practices to prevent the intermixing of > number strings and integers as hash keys? A hash wrapper class seems to > be the best bet so far. If you want to make sure something is always done in a particular situation, then solution is to have a function or method that does that, and then just call that function or method. That's true in any language -- any one that has functions, anyway. -- 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 Laws are silent in time of war. -- Cicero From jpeng at block.duxieweb.com Mon Jan 21 00:16:37 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Mon, 21 Jan 2008 13:16:37 +0800 Subject: object scope In-Reply-To: <13p8803q11tm32d@corp.supernews.com> References: <13p8803q11tm32d@corp.supernews.com> Message-ID: <47942AB5.4040301@block.duxieweb.com> Dennis Lee Bieber ??: > The scope of "name" is the entire function; lacking a "global name" > statement, AND being on the left side of an assignment, it is a function > local name. Thank you. Does python have so-called 'block scope' object? or if you can,please show me the doc for python's object scope. From arnodel at googlemail.com Tue Jan 29 16:33:12 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 29 Jan 2008 13:33:12 -0800 (PST) Subject: breaking out of outer loops References: <20080129215513.3352a90d@hyperspace> Message-ID: On Jan 29, 8:55?pm, pataphor wrote: > On Tue, 29 Jan 2008 11:51:04 -0800 (PST) > > noemailplease0... at gmail.com wrote: > > Any elegant way of breaking out of the outer for loop than below, I > > seem to have come across something, but it escapes me > > > for i in outerLoop: > > ? ?for j in innerLoop: > > ? ? ? ?if condition: > > ? ? ? ? ? break > > ? ?else: > > ? ? ? ?continue > > ? ? break > > Ha! Think outside the box to begin with ... > > P. > > def cross(args): > ? ? ans = [[]] > ? ? for arg in args: > ? ? ? ? ans = [x+[y] for x in ans for y in arg] > ? ? return ans ? ? While we're at it, a generator version: def iproduct(head=None, *tail): if head is None: return ((),) else: return ((x,)+y for x in head for y in iproduct(*tail)) for a, b, c in iproduct('124', 'ab', 'AB'): print a, b, c ;-) -- Arnaud From pavlovevidence at gmail.com Fri Jan 18 20:08:53 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 18 Jan 2008 17:08:53 -0800 (PST) Subject: TopSort in Python? References: <0000161d@bossar.com.pl> <358cc5a3-300f-49ba-9857-2f0cd629a4df@i12g2000prf.googlegroups.com> Message-ID: <12f0f54e-5d30-40bc-9135-2c59b8a5acc2@i3g2000hsf.googlegroups.com> On Jan 18, 7:01 pm, Paddy wrote: > On Jan 18, 9:47 pm, startec... at gmail.com wrote:> Tim, > > > Thanks for the topsort code. It would be useful in a project I'm > > working on. Can I use the code for free under public domain? Thanks! > > When I needed one I didn't know the name. I'm curious, how did you > know to look for the topological sort algorithm by name? I spent quite a bit of time looking for this one myself. It was quite a stumper. Sometimes Google gets us in the habit of just firing random search terms when we ought to be thinking it out. After quite of bit of dead end searching--like a week--I stepped back, thought about what I was looking for. I wanted a sort of dependency system: A must happen before B. What other programs do that? make, of course. I looked at the documents for make and found the term "directed acyclic graph", and pretty much instantly knew I had it. (It seems silly in retrospect that I didn't think of graphs before that, but then it also seems silly no one invented movable type before 1436.) Once I had that term, a quick Google search led me to the Wikipedia article, which led me to the topsort algorithm. I did a dance of joy. Ten minutes later I saw it mentioned it on comp.lang.python. Carl Banks From samuel.progin at gmail.com Thu Jan 10 02:43:19 2008 From: samuel.progin at gmail.com (Sam) Date: Wed, 9 Jan 2008 23:43:19 -0800 (PST) Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> Message-ID: <68516e24-9393-46ec-9772-2e6ecd7dcee5@n20g2000hsh.googlegroups.com> > Unfortunately, I don't *think* I can shut the > warning for that line or function off, only for the entire file. > Pylint gives you a rating of your quality of code which I think is wrong :) # pylint: disable-msg=XXXXX will only impact the current line! $ cat -n dummy.py 1 for i in range(2): # pylint: disable-msg=W0612 2 print "foo" 3 for i in range(2): 4 print "foo" pylint will not generate a warning on line 1, but will on line 3! Cheers. Sam From PrinceOfDataMining at gmail.com Sat Jan 19 11:30:39 2008 From: PrinceOfDataMining at gmail.com (Samuel) Date: Sat, 19 Jan 2008 08:30:39 -0800 (PST) Subject: ANN:proxysocket(socks4,socks5)v0.1 References: <7228288b-cb34-40ba-8483-a2dc57115511@d21g2000prf.googlegroups.com> Message-ID: <14b208ca-f2ea-44bd-823a-6c0070b8162e@d21g2000prg.googlegroups.com> v0.2 http://proxysocket.googlecode.com/files/ProxySocket.py On 1?18?, ??3?04?, Tim Roberts wrote: > Samuel wrote: > > >http://code.google.com/p/proxysocket/downloads/list > > Allow me to introduce you to the concept of comments. Python allows you to > include descriptive sentences in your program that explain what the > functions do, what your intentions were, what the variables do, what the > states mean, etc. It's easy to do; you just start the text with # signs. > > # This function allows you to ... > > # These variables define the connection state as the connection is > # made. > > They're great. You should try them. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From steve at holdenweb.com Thu Jan 31 06:09:21 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 06:09:21 -0500 Subject: Design question - Sharing of single object by multiple processes In-Reply-To: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> References: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> Message-ID: <47A1AC61.7080007@holdenweb.com> Mike D wrote: > Hello, I've just picked up the Python language and am really enjoying it. > > I've just signed up to this mailing list and I'm looking forward to > taking part in some discussions. > > My first post is a question I've been pondering for the last couple of days: > > For relatively static data (such as a list), is it possible to load a > single instance and have many python processes access it? > First there's the problem of having multiple processes access any kind of shared resource. So your question makes me wonder whether you mean processes, or threads. Are you *sure* you mean processes? > I want to have an object in memory. This object will be loaded on > application start up and will contain a list of objects. These will be > obtained from (most likely) the file system. > So "application startup" is different from "process startup"? Your application is a group of co-operating processes? Really? > My reasoning is: I want to prevent a file system or database fetch each > time as it seems unnecessary. > It might also seem unnecessary to start the Python interpreter for each process, but you are going to have to ... > Is this possible? In Java I'm pretty sure this could implemented with an > object factory and static methods. My understanding is that python > invokes a separate process for each request however. > Your understanding is clearly informed by some information you have omitted to share with us. > If possible, what would be a good way of providing a new structure as it > is updated. > > If anyone could give me some advice or point me in the correct direction > I'd really appreciate it. > > Thanks in advance, > More answers, please. There are mechanisms such as Pyro (Python remote objects) that allow inter-process method calls, but I am far from convinced that's what you really want (or need, anyway). Perhaps yo could let us know a little more about what it really is you are trying to do, and convince me, at least, that this isn't just a case of premature optimization. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From siona at chiark.greenend.org.uk Wed Jan 9 08:00:51 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Jan 2008 13:00:51 +0000 (GMT) Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <5ujp0tF1ehvg2U1@mid.dfncis.de> Message-ID: Robert Latest wrote: > BTW, where can I find all methods of the built-in types? >Section 3.6 only talks about strings and mentions the list append() method >only in an example. Am I too stupid to read the manual, or is this an >omission? 3.6 talks about features common to all "sequence" types. Strings are discussed specifically in 3.6.1 ("String Methods"). Lists are similarly discussed in 3.6.4 ("Mutable Sequence Types"). They are certainly not omitted, although maybe the title of 3.6.4 could be take a leaf from the Zen and be more explicit. -- \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 ms at cerenity.org Sat Jan 12 18:11:23 2008 From: ms at cerenity.org (Michael Sparks) Date: Sat, 12 Jan 2008 23:11:23 +0000 Subject: [Kamaelia] TCPClient: How to sense connection failure? References: <5uq49vF1jkgcoU1@mid.individual.net> Message-ID: <13oiho63bri4c76@corp.supernews.com> Bjoern Schliessmann wrote: > Hello, > > I'm currently trying to implement a simulation program with Kamaelia > and need a reliable TCP connection to a data server. The behaviour you're seeing sounds odd (which is hopefully encouraging :-), but it's not clear from the description whether its a bug in your code or Kamaelia. One question I really have as a result is what version are you using? Current release version 0.5.0, the version on /trunk, or the bleeding edge version on /branches/private_MPS_Scratch. (I'm using the latter to run my greylisting server - as are a few others). All that said though, looking at the differences between versions, I'm not convinced they're large enough to show the problem you're seeing. I'm not about to rule out a bug I don't know about though :-) > From Twisted, I know that a method is called if the connection fails > by whatever reason. I tried to get the same results with Kamaelia's > TCPClient component. If I start up the component and try to connect > to a closed TCP port it fails and sends a message out of the signal > box, that's okay. If you'd prefer more information in that message, please let me know. (all components send out a message when they shutdown. For things that send data out as one of their primary actions send out a producerFinished message) > But if the connection attempt succeeds and, after some time, the > server drops the connection with full TCP handshake (FIN, FIN+ACK, > ACK), the component just hangs and does nothing. Is this by design, > or could there be an error in my setup? It sounds like an error in your setup... but I hate saying that. (Doesn't tell me or you what it is, and doesn't help change things to discourage or detect mistakes in usage) When the server drops the connection in my setups, the client disconnects cleanly when the server dies, with the client code looking like this: self.send(producerFinished(self,self.howDied), "signal") Meaning you get a message telling you how the component shutdown as well as the fact it shutdown. (If "howDied" is None, it's just a normal shutdown - ie as a result of being told to shut down) The function where this is managed is runClient in the class Kamaelia.Internet.TCPClient.TCPClient (fully qualified name) The actual socket connections are handled by a class called ConnectedSocketAdapter which manages all logic of checking for errors, remote shutdown etc. That works the same for both servers and clients so breakage in clients would show up as breakage in servers as well, which would be particularly bad. > Also, how long does a TCPClient component live -- or how can/should > I terminate it explicitly? I'm afraid that if I create > a "ReconnectingTCPClient" component, it could eat up memory over > long runtime with hanging TCPClients. That shouldn't be an issue (I hate the word "should"), but you can do this using a carousel component. (I ought to write that as an example of how to use the Carousel component) In the meantime - whilst I check to see if there's a bug I didn't know about, the following 2 cookbook entries may be of use: * http://kamaelia.sourceforge.net/Cookbook/TCPSystems * http://kamaelia.sourceforge.net/Cookbook/Carousels - allows you to make something that exits reusable. It's a little awkward to get your head around, but is quite useful when you do. (I've heard of others using Carousel & TCPClient to make a reconnecting TCPClient in the past) All that said, I'm not going to rule out a bug and look into it. (if you have a simple example you find fails, please forward it to me :) *thinks* The following code may also be useful when debugging: from Kamaelia.Chassis.Pipeline import Pipeline class PeriodicWakeup(Axon.ThreadedComponent.threadedcomponent): interval = 300 def main(self): while 1: time.sleep(self.interval) self.send("tick", "outbox") class WakeableIntrospector(Axon.Component.component): def main(self): while 1: Q = [ q.name for q in self.scheduler.listAllThreads() ] Q.sort() print "*debug* THREADS"+ str(Q) self.scheduler.debuggingon = False yield 1 while not self.dataReady("inbox"): self.pause() yield 1 while self.dataReady("inbox"): self.recv("inbox") Pipeline( PeriodicWakeup(), WakeableIntrospector(), ).activate() If you put this code somewhere before your "run" call, you'll get periodic output to tell you what's running. When debugging manually I'd drop the interval to 3-10 seconds or so. I use 300 for a server. Now, off to see if I can reproduce your problem... :) Regards, Michael. -- http://kamaelia.sourceforge.net/Home http://yeoldclue.com/blog From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jan 24 10:14:28 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 24 Jan 2008 16:14:28 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <5vroakF1o4jkvU1@mid.individual.net> Tim Roberts wrote: > Bjoern Schliessmann >> So, how do processors execute Python scripts? :) > > Is that a rhetorical question? A little bit. > Grant is quite correct; Python scripts (in the canonical CPython) > are NOT compiled into assembly language. Scripts are compiled to > an intermediate language. Processors execute Python scripts when > the interpreter, written in a high-level language and compiled to > assembly, interprets the intermediate language created by the > Python "compiler". So in the end, the program defined in the Python script _is_ compiled to the CPU's language. But never mind, it depends on how you define "compile" in the end. Regards, Bj?rn -- BOFH excuse #225: It's those computer people in X {city of world}. They keep stuffing things up. From ajaksu at gmail.com Sun Jan 6 08:15:31 2008 From: ajaksu at gmail.com (ajaksu) Date: Sun, 6 Jan 2008 05:15:31 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> <617182dc-3ca1-4cf5-b1ca-1779dd8d6550@i3g2000hsf.googlegroups.com> Message-ID: <1926019f-bf46-4fbb-990d-ed0b9cf18353@n20g2000hsh.googlegroups.com> On Jan 5, 11:36 pm, c... at mailinator.com wrote: > > This one is good. Someone commented that you destroy the list, but > that can be fixed: > > def pick_random(seq, prop): > L = len(seq) > for i in xrange(L): > r = random.randrange(L - i) > if prop(seq[r]): > return seq[r] > seq[r], seq[L - i - 1]= seq[L - i - 1],seq[r] > > just pushing elements without the property to the end of the list > (list is mutated, true, but shuffle will do that too). In each > iteration of the for loop, there is only one random element, one check > of the property, and rebinding of elements without altering the lenght > of the list. This is optimal and has all the functionality. > > Two more comments: > for buzcor: deleting an element in the middle of a list is costly > for martin: that is certainly enough for me > > Thanks everybody! How about some benchmarks as a token of gratitude? ;) Or at least a nice hint on your expected number of lists (and their sizes) :) From pakmarshal at gmail.com Wed Jan 23 04:37:17 2008 From: pakmarshal at gmail.com (pakmarshal at gmail.com) Date: Wed, 23 Jan 2008 01:37:17 -0800 (PST) Subject: InstallShield file properties issues Message-ID: Hi, I am using Install Shield 11 express to create an upgrade package (msi) and came across an issue i.e. when installer installs the package it changes the created date of the files to modified date (changes created date with modified date), in my situation the files have modified date newer than the created date on source system and which I want to retain on the target system. That date difference helps me not to over write these files in next upgrade package. My questions are why Install Shield is showing that behavior or is there another reason for this? Is there any way to retain the created date, originally the file has? For this purpose I tested Install Shield's file properties options i.e. "Use System Attributes" which is used as, file installed with the same properties that it has on the development system, but it don't seems to be working in my case. Regards, Hassan From winjer at gmail.com Thu Jan 3 11:39:36 2008 From: winjer at gmail.com (winjer at gmail.com) Date: Thu, 3 Jan 2008 08:39:36 -0800 (PST) Subject: Fate of itertools.dropwhile() and itertools.takewhile() References: <7a86a421-089f-4634-8902-e9edfe139f03@e23g2000prf.googlegroups.com> Message-ID: <33c108cb-4378-4f34-bc52-b179772a73cb@n20g2000hsh.googlegroups.com> On Dec 29 2007, 11:10 pm, Raymond Hettinger wrote: > I'm considering deprecating these two functions and would like some > feedback from the community or from people who have a background in > functional programming. Well I have just this minute used dropwhile in anger, to find the next suitable filename when writing database dumps using date.count names: filename = "%02d-%02d-%d" % (now.day, now.month, now.year) if os.path.exists(filename): candidates = ("%s.%d" % (filename, x) for x in count(1)) filename = dropwhile(os.path.exists, candidates).next() Much clearer than the alternatives I think, please keep dropwhile and takewhile in itertools ;) Cheers, Doug. From emin.shopper at gmail.com Thu Jan 3 11:24:13 2008 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Thu, 3 Jan 2008 11:24:13 -0500 Subject: How do you pass compiler option to setup.py install? Message-ID: <32e43bb70801030824p7099da66s6ffb4ee0ea58b311@mail.gmail.com> Dear Experts, How do you pass the -c option to setup.py install? Specifically, when I try to install zope.interfaces version 3.3 from source on a windows machine, I get a message about using "-c mingw32". That works fine for setup.py build, but it does not work for "setup.py install". Note: I would have just used the binary installer for windows but couldn't find one for version 3.3. Thanks, -Emin -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at marcher.name Wed Jan 9 11:56:39 2008 From: martin at marcher.name (Martin Marcher) Date: Wed, 09 Jan 2008 17:56:39 +0100 Subject: printing dots in simple program while waiting References: Message-ID: John wrote: > import time > s = '.' > print 'working', # Note the "," at the end of the line > while True: > print s > time.sleep(1) see my comment in the code above... if that's what you mean /martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From DustanGroups at gmail.com Sat Jan 12 18:08:18 2008 From: DustanGroups at gmail.com (Dustan) Date: Sat, 12 Jan 2008 15:08:18 -0800 (PST) Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> <7xprw6g59t.fsf@ruckus.brouhaha.com> Message-ID: <6bcd73cf-8d36-4592-80e4-fefeb189090c@f10g2000hsf.googlegroups.com> On Jan 12, 2:25 pm, Paul Rubin wrote: > marcstuart writes: > > what I would like to get is 3 sublists > > > print z[0] = [1,2,3] > > print z[2] = [4,5,6] > > print z[3] = [7,8,9,10] > > Are you SURE you want that? In almost every situation I've seen, > > print z[0] = [1,2,3] > print z[2] = [4,5,6] > print z[3] = [7,8,9] > print z[4] = [10] > > is preferable. Even more preferable is: print z[0] = [1,2,3] print z[1] = [4,5,6] print z[2] = [7,8,9] print z[3] = [10] From asmodai at in-nomine.org Sat Jan 26 08:56:02 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 26 Jan 2008 14:56:02 +0100 Subject: Doesn't know what it wants In-Reply-To: <13plo358k5rf059@corp.supernews.com> References: <13plo358k5rf059@corp.supernews.com> Message-ID: <20080126135602.GI1050@nexus.in-nomine.org> -On [20080126 08:31], Steven D'Aprano (steve at REMOVE-THIS-cybersource.com.au) wrote: >The OP's code calls vec2d with a single tuple argument (0,0). Jeroen's >version calls vec2d with two int arguments, 0 and 0. Yes, but it was not what I intended at all. I guess I am just a bit too used to tacking on a , to denote a tuple since in almost every other language seeing (()) is just an additional layer of braces. I had totally forgotten Python would make it a tuple. And I guess my head was still stuck with some other languages as well when I made my other suggestion. Mea culpa. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ We have met the enemy and they are ours... From jimis at gmx.net Wed Jan 2 16:03:52 2008 From: jimis at gmx.net (Dimitrios Apostolou) Date: Wed, 2 Jan 2008 23:03:52 +0200 Subject: urllib2 disable proxy Message-ID: <200801022303.53722.jimis@gmx.net> Hello list, I've been looking for a way to explicitly disable the use of proxies with urllib2, no matter what the environment dictates. Unfortunately I can't find a way in the documentation, and reading the source leads me to believe that something like the following does the job: req.set_proxy(None,None) Where req is a urllib2.Request instance. So is there an official way of doing this? Perhaps it should be added in the documentation? Thanks in advance, Dimitris From patrick.waldo at gmail.com Wed Jan 2 09:33:00 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Wed, 2 Jan 2008 06:33:00 -0800 (PST) Subject: Pivot Table/Groupby/Sum question References: <148c3214-77b9-47b0-a680-ffb85dd3efcd@e6g2000prf.googlegroups.com> <2ada2837-7625-43c1-8264-5edc9046fbc8@i29g2000prf.googlegroups.com> <7f396128-2ce2-4dd6-bdc0-855bab8750c7@w38g2000hsf.googlegroups.com> <9f7b6dcc-216d-46a9-a9d5-022c00ee9d7d@d21g2000prf.googlegroups.com> <1caf93fd-3a50-4c77-87b0-5312cdebd35f@d21g2000prf.googlegroups.com> <63a5a87e-3385-4ef0-80a3-cd1a01eeeac3@w38g2000hsf.googlegroups.com> <276d150b-6b2a-4973-8569-bd8cad6df948@s19g2000prg.googlegroups.com> <018c37d5-67c0-4995-88e3-86f701580c26@e23g2000prf.googlegroups.com> Message-ID: <5d6721cc-1912-4adc-9e47-0afa21c51c89@21g2000hsj.googlegroups.com> Sorry for the delay in my response. New Year's Eve and moving apartment > - Where the data come from (I mean: are your data in Excel already > when you get them)? > - If your primary source of data is the Excel file, how do you read > data from the Excel file to Python (I mean did you solve this part of the task already)? Yes, the data comes from Excel and I use xlrd and PyExcelerator to read and write, respectively. #open for reading path_file = "c:\\1\\data.xls" book = xlrd.open_workbook(path_file) Counts = book.sheet_by_index(1) #get data n=1 data = [] while n References: Message-ID: <4784FEF9.9080807@tim.thechases.com> Martin Marcher wrote: > John wrote: > >> import time >> s = '.' >> print 'working', # Note the "," at the end of the line >> while True: >> print s, #Note the "," at the end of this line too... >> time.sleep(1) > > see my comment in the code above... see my added comment in the code above... Though this will produce spaces between the dots: waiting . . . . . . To eliminate the spaces, you need to write to a file-stream such as sys.stdout: from sys import stdout stdout.write('working') while True: stdout.write('.') # might need something like stdout.flush() here time.sleep(1) stdout.write('\n') -tkc From steve at holdenweb.com Thu Jan 31 10:31:43 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 10:31:43 -0500 Subject: Fwd: Re: Problems installing Python on server In-Reply-To: <200801310946.50733.inq1ltd@inqvista.com> References: <3bf78e92-1c95-4255-95fd-ca17c81d215b@i29g2000prf.googlegroups.com> <200801310946.50733.inq1ltd@inqvista.com> Message-ID: jim-on-linux wrote: > > >>> Also be careful and setup all the paths >>> that is required for compiling various >>> Python modules etc. >>> >>> On Jan 29, 8:28 am, Yansky >> wrote: >>>> I asked my hosting company if they >>>> would upgrade Python on my server to >>>> the latest version. They responded >>>> with: >>>> >>>> "Sorry no. We tend to stick with what >>>> comes packaged with the unix >>>> distribution to ease maintenance >>>> issues. >>>> >>>> There is nothing stopping you from >>>> running your own version of python >>>> from within your own account. Download >>>> the source and compile it and install >>>> it into your own space. Adjust the >>>> fist line of your python scripts to >>>> reflect the location of YOUR python >>>> binary: >>>> >>>> #! /home/youraccount/yourlibs/python >>>> >>>> and you should be all set." >> Go to the ReadME file after you unpack >> python. >> Open and look for "Installing". >> Read the section, it explains how to >> install on the entire system and how to >> install locally. >> "Make altinstall" is what you are looking >> for. >> >> jim-on-linux >> http:\\www.inqvista.com >> >>>> The build instructions for Python are: >>>> To start building right away (on >>>> UNIX): type "./configure" in the >>>> current directory and when it >>>> finishes, type "make". This creates an >>>> executable "./python"; to install in >>>> usr/local, first do "su root" and then >>>> "make install". >>>> >>>> The problem is, I don't have root >>>> access to the server so I can't do the >>>> "make install". I have ubuntu on my >>>> computer, but from what I understand I >>>> can't compile it on that and upload it >>>> because the server runs Red Had and >>>> the ./configure would have made it >>>> incompatible right? >>>> >>>> So how can I build Python without root >>>> access? > > Will the "make install" make my Python the > default one? If I want to install some > Python modules, will I need to alter their > installation as well or will it see my > Python version as the right one to install > too? > The "default one"? That's just the one that runs when a user enters the python command, right? "make install" will install Python wherever you told the configure utility to build it for. "make altinstall" is a convenience method that (IIRC) builds for /usr/local/bin. Generally speaking when you install an extension or other module, nowadays you use the command python setup.py install The installation takes place in whichever copy of Python runs setup.py, so with a "default" /usr/bin/python and an "alternate" /usr/local/bin/python, to install a module in the alternate you would run /usr/local/bin/python setup.py install The same is true of a Python you have installed somewhere under your home directory. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From savinovboris at gmail.com Tue Jan 22 12:35:16 2008 From: savinovboris at gmail.com (Boris) Date: Tue, 22 Jan 2008 09:35:16 -0800 (PST) Subject: Using utidylib, empty string returned in some cases Message-ID: <69c38011-4af7-4305-95fb-c824019c1550@v4g2000hsf.googlegroups.com> Hello I'm using debian linux, Python 2.4.4, and utidylib (http:// utidylib.berlios.de/). I wrote simple functions to get a web page, convert it from windows-1251 to utf8 and then I'd like to clean html with it. Here is two pages I use to check my program: http://www.ya.ru/ (in this case everything works ok) http://www.yellow-pages.ru/rus/nd2/qu5/ru15632 (in this case tidy did not return me anything just empty string) code: -------------- # coding: utf-8 import urllib, urllib2, tidy def get_page(url): user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)' headers = { 'User-Agent' : user_agent } data= {} req = urllib2.Request(url, data, headers) responce = urllib2.urlopen(req) page = responce.read() return page def convert_1251(page): p = page.decode('windows-1251') u = p.encode('utf-8') return u def clean_html(page): tidy_options = { 'output_xhtml' : 1, 'add_xml_decl' : 1, 'indent' : 1, 'input-encoding' : 'utf8', 'output-encoding' : 'utf8', 'tidy_mark' : 1, } cleaned_page = tidy.parseString(page, **tidy_options) return cleaned_page test_url = 'http://www.yellow-pages.ru/rus/nd2/qu5/ru15632' #test_url = 'http://www.ya.ru/' #f = open('yp.html', 'r') #p = f.read() print clean_html(convert_1251(get_page(test_url))) -------------- What am I doing wrong? Can anyone help, please? From arnodel at googlemail.com Tue Jan 29 05:34:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 29 Jan 2008 02:34:10 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <92b67efe-c437-40bc-89fc-bbdd85d6e718@s19g2000prg.googlegroups.com> <816442e1-be46-4543-88dc-1b328ced7231@j20g2000hsi.googlegroups.com> Message-ID: <8a7722da-7dd4-4135-862d-baec92b79abb@e25g2000prg.googlegroups.com> On Jan 29, 9:02?am, david.hot... at blueyonder.co.uk wrote: Oops I sent too quickly... > If you've found an efficient way to walk through the possible > solutions only once, then > - ?I expect that yours will be faster > - ?and well done! > > I guess I should try to understand your code... My code is quite naive and I suspect that combining your caching and the tree pruning discussed in this thread would yield faster results. Not sure if I'll have time to try this though... -- Arnaud From steven at REMOVE.THIS.cybersource.com.au Sun Jan 6 22:42:11 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 Jan 2008 03:42:11 -0000 Subject: Delete lines containing a specific word References: <5ud6qgF1hlfdaU1@mid.individual.net> Message-ID: On Mon, 07 Jan 2008 00:33:36 +0100, Bjoern Schliessmann wrote: > Steven D'Aprano wrote: > >> grep doesn't delete lines. grep matches lines. If you want to delete >> them, you still have to do the rest of the job yourself. > > In which way does "grep -v mypattern myfile > myfile" not delete the > lines matching mypattern? Okay, that will delete the lines matching mypattern. Unfortunately it will also delete all the lines NOT matching mypattern as well. Try it for yourself -- just not on anything you care about. This is what happens when abstractions leak. You *think* you're deleting lines, but you're not. That's just an abstraction, and when it leaks, you break things. -- Steven From jr9445 at ATT.COM Mon Jan 14 12:08:02 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Mon, 14 Jan 2008 11:08:02 -0600 Subject: __init__ explanation please In-Reply-To: <873at0mkv7.fsf@mulj.homelinux.net> References: <47895d25$0$30708$4c368faf@roadrunner.com><20080113104641.GN75977@nexus.in-nomine.org><478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net><87myr8v3p4.fsf@mulj.homelinux.net> <873at0mkv7.fsf@mulj.homelinux.net> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Hrvoje Niksic > Sent: Monday, January 14, 2008 11:29 AM > To: python-list at python.org > Subject: Re: __init__ explanation please > > Mel writes: > > >> I don't understand the purpose of this "correction". After all, > >> __init__ *is* the closest equivalent to what other languages would > >> call a constructor. > > > > Nevertheless, __init__ doesn't construct anything. > > Only if by "construct" you mean "allocate". __init__ starts out with > an empty object and brings it to a valid state, therefore > "constructing" the object you end up with. That operation is exactly > what other languages call a constructor. Nah. Most other languages combine the constructor and an init function. Normally with c++ I'll have the constructor call an Init() function so I can re-initialize the object as needed. Python has explicitly split the two. Besides, the Python docs say that __new__ is the constructor and __init__ may or may not be called after the instance is created: __new__( cls[, ...]) Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls). ... If __new__() returns an instance of cls, then the new instance's __init__() method will be invoked ... If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked. __init__( self[, ...]) Called when the instance is created. ... As a special constraint on constructors, no value may be returned; Also, how can a constructor require 'self' as an argument...? __init__(self, ...) If the __init__ function is called by the constructor it cannot return a value. However if called as a normal function, it can return a value. __init__ is just a function that gets called by the constructor, which is __new__. count = 0 class AClass (object): def __init__ (self): self.a = 4 global count if count > 0: return 'hello world' count += 1 a = AClass() print a.a print a.__init__() c:\foo\a.py> 4 hello world ***** 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. GA622 From fredrik at pythonware.com Sun Jan 20 07:43:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jan 2008 13:43:56 +0100 Subject: Okay I got a question regarding Tkinter and Labels In-Reply-To: References: Message-ID: Lamonte Harris wrote: > Okay I've created a script and basically when I loop through a folder it > is supposed to change the Label everytime it updates a file then again > it doesn't do nothing but shows the last file edited, whats the best way > to loop through files and display that file name in a Label's text > without skipping to the last one when the loop is finished? Tkinter is event-driven, and you need to keep the event loop running to make sure that changes to the widgets makes it to the screen. Usually, this is handled by the "mainloop" function, but if you're spending considerable time at the Python level, you need to call the "update" or "update_idletasks" methods from time to time to give Tkinter a chance to process incoming events. In your case, you can simply call the method after you've modified the label: label.config(text="something") label.update() Hope this helps! From BjornSteinarFjeldPettersen at gmail.com Sun Jan 13 07:55:04 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 13 Jan 2008 04:55:04 -0800 (PST) Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> <00cb6e9d-e8b6-4e65-be58-5a4472413c53@j78g2000hsd.googlegroups.com> Message-ID: <64a76486-2dd2-4a09-bc4f-0a1ddf49ba89@f3g2000hsg.googlegroups.com> On Jan 13, 1:05 pm, thebjorn wrote: > On Jan 12, 8:33 pm, Fredrik Lundh wrote: > > > > > marcstuart wrote: > > > How do I divide a list into a set group of sublist's- if the list is > > > not evenly dividable ? consider this example: > > > > x = [1,2,3,4,5,6,7,8,9,10] > > > y = 3 # number of lists I want to break x into > > > z = y/x > > > > what I would like to get is 3 sublists > > > > print z[0] = [1,2,3] > > > print z[2] = [4,5,6] > > > print z[3] = [7,8,9,10] > > > > obviously not even, one list will have 4 elements, the other 2 will > > > have 3., > > > here's one way to do it: > > > # chop it up > > n = len(x) / y > > z = [x[i:i+n] for i in xrange(0, len(x), n)] > > > # if the last piece is too short, add it to one before it > > if len(z[-1]) < n and len(z) > 1: > > z[-2].extend(z.pop(-1)) > > > > > Eh... > > def chop(lst, length): > n = len(lst) / length > z = [lst[i:i+n] for i in xrange(0, len(lst), n)] > if len(z[-1]) < n and len(z) > 1: > z[-2].extend(z.pop(-1)) > return z > > gives > > >>> chop(range(1,9), 3) > > [[1, 2], [3, 4], [5, 6], [7, 8]]>>> chop(range(1,8), 3) > > [[1, 2], [3, 4], [5, 6, 7]]>>> chop(range(1,6), 3) > > [[1], [2], [3], [4], [5]]>>> chop([1], 3) > > Traceback (most recent call last): > File "", line 1, in > File "beforemeth.py", line 9, in chop > if len(z[-1]) < n and len(z) > 1: > ValueError: xrange() arg 3 must not be zero > > Perhaps something like this? > > def chop(lst, length): > from itertools import islice > it = iter(lst) > z = [list(islice(it, length)) for i in xrange(1 + len(lst) // > length)] > if len(z) > 1: > z[-2].extend(z.pop()) # the last item will be empty or contain > "overflow" elements. > return z > > -- bjorn Bad for to reply to myself, I know, but I just realized that the OP wanted to control the _number_ of chunks, not the size of the chunks... Building on the above would give something like from itertools import islice from operator import add def chop(lst, nchunks): chunksize, extra = divmod(len(lst), nchunks) if not chunksize: raise ValueError('More chunks than elements in list.') it = iter(lst) z = [list(islice(it, chunksize)) for i in xrange(nchunks + extra)] z, extra = z[:nchunks], z[nchunks:] z[-1].extend(reduce(add, extra, [])) # because sum ain't add :-( return z -- bjorn From Brett.Friermood at gmail.com Tue Jan 22 11:23:11 2008 From: Brett.Friermood at gmail.com (Brett.Friermood at gmail.com) Date: Tue, 22 Jan 2008 08:23:11 -0800 (PST) Subject: Curses and Threading References: <3924ad84-a513-4b25-b9af-cbd358f5d40a@i3g2000hsf.googlegroups.com> Message-ID: > In fact you have *two* threads: the main thread, and the one you create > explicitly. > After you start the clock thread, the main thread continues executing, > immediately entering the finally clause. > If you want to wait for the other thread to finish, use the join() method. > But I'm unsure if this is the right way to mix threads and curses. This is what the python documentation says: join([timeout]) Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates. So according to this since I need to block the main thread until the clock thread ends I would need the main thread to call "cadtime().join()", correct? I'm not sure how to do this because I don't have a class or anything for the main thread that I know of. I tried putting that after cadtime().start() but that doesn't work. I guess what I'm trying to say is how can I tell the main thread what to do when it doesn't exist in my code? Thanks for the help -Brett From tjreedy at udel.edu Mon Jan 28 22:58:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jan 2008 22:58:52 -0500 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com><479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net><60411eF1ors2pU1@mid.uni-berlin.de><479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net><7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13pqd16n4o3rufe at corp.supernews.com... | I don't like the name convention. _name already has a perfectly good | convention: it's a private name, don't mess with it. That includes in | function/method signatures. With your convention, _foo is public. Since local names, including params are inaccesible outside a function, I don't see how the convention applies. However, the underscore could just as well go at the end of the name. There no current convention I know of with that. tjr From fredrik at pythonware.com Fri Jan 18 13:11:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 18 Jan 2008 19:11:14 +0100 Subject: Bug in __init__? In-Reply-To: References: Message-ID: Zbigniew Braniecki wrote: > It's really a nice pitfall, I can hardly imagine anyone expecting this, > or how easily could I find this info (e.g. what query should I give to > google to get it without bothering people on this group) looking things up in the documentation *before* deciding that you might have done something that nobody's done before is often a good idea: http://docs.python.org/tut/node6.html#SECTION006710000000000000000 "Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. /.../" http://docs.python.org/ref/function.html "Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same ``pre-computed'' value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary /.../ (to be precise, the default values are evaluated when the "def" state- ment is executed, in the same scope as the "def" statement itself. if you execute the same "def" statement multiple times, the values are recalculated.) From myth at spam.no Thu Jan 3 02:51:08 2008 From: myth at spam.no (Thin Myrna) Date: Thu, 03 Jan 2008 08:51:08 +0100 Subject: PyInstaller: Need some hints (perhaps a good example?) Message-ID: <477c93e9$0$29612$5402220f@news.sunrise.ch> I gave PyInstaller a shot and was pleased by the results so far. The usual problems occurred with missing data and icon files (the latter for splash screens only). However, it's a bit hard for me to overcome them. I tried COLLECT but the files don't seem to be added to the install. The reason is most likely, that I dont know, where to put the result of COLLECT: Is it pyz, is it exe, or...? Is anyone willing to post an example or two here, how this is done? Kind regards Thin From sjmachin at lexicon.net Tue Jan 15 16:58:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 15 Jan 2008 13:58:44 -0800 (PST) Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: <8a1bd1ac-037f-49ee-91e8-9875ed0a1b43@k39g2000hsf.googlegroups.com> On Jan 16, 3:25 am, "Colin J. Williams" wrote: Colin W. > > I'm sorry, there appears to be a bug: There is, but but not where you think it is :-) > # tSet.py > import sets [not the bug] Earlier evidence is that you are using 2.5.1; why import sets?? > s1= sets.Set([1, 2, 3]) > s1.union_update([3, 4,5]) > print(s1) > s2= sets.Set([6, 7, 8]) > s1 |+ s2 # This fails: > exceptions.TypeError: bad operand type > for unary +: 'Set' Try reading and understanding the exception message ... "unary +" as in the syntactically equivalent expression s1 | +s2 HTH, John From fredrik at pythonware.com Thu Jan 10 13:07:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 19:07:58 +0100 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: A.T.Hofkamp wrote: > Now the question you need to answer for yourself, is how much more worth is > your own time compared to the gain in CPU time. If you think they are equal (ie > the problem as a whole should be solved as fast as possible, thus the sum of > development time + execution time should be as short as possible), you can > spend an additional 1.5 seconds development in the alternative solution. so you only run your programs once? From hyugaricdeau at gmail.com Fri Jan 11 09:49:09 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Fri, 11 Jan 2008 06:49:09 -0800 (PST) Subject: Help needed References: Message-ID: On Jan 10, 9:15 pm, tijo wrote: > Hi mate > > i need o do a python program to connect 2 systems using TCP/IP and > UDP. Also i need to check the performance of these two protocols (how > many bytes received and how much time took). I havent worked in python > earlier and have no idea of this. Could someone pls help me. I created > a program which can connect between 2 systems using these UDP and TCP/ > IP protocols. I dont know how to check the rest like how many bytes > send or how much time taken > since this is part of my course work could someone please help me > thanks in advance. > > tijo The standard library documentation, while lacking in some areas, is very much your friend here: >From http://docs.python.org/lib/socket-objects.html (emphasis mine) send(string[, flags]) Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. *Returns the number of bytes sent.* recv(bufsize[, flags]) Receive data from the socket. The return value is a string representing the data received. For timing you can probably use the timeit module (http:// docs.python.org/lib/module-timeit.html) but I'm not really sure how you're defining "performance". I mean, I can already tell you that overall UDP will be "faster", as it has much less overhead. Surely your course has covered this... Hyuga From fredrik at pythonware.com Mon Jan 7 17:55:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 23:55:31 +0100 Subject: Tkinter variable trace problem In-Reply-To: <17687-68562@sneakemail.com> References: <17687-68562@sneakemail.com> Message-ID: C Martin wrote: > What am I doing wrong in this code? The callback doesn't work from the Entry widget. > > ##start code > import Tkinter > > tk = Tkinter.Tk() > var = Tkinter.StringVar() > print var._name > > def cb(name, index, mode): > print "callback called with name=%r, index=%r, mode=%r" % (name, index, mode) > varValue = tk.getvar(name) > print " and variable value = %r" % varValue iirc, getvar only looks at local Tcl variables when used inside a callback. variables created with StringVar are global Tcl variables. but instead of monkeying around at the Tcl level, why not just solve this on the Python level instead? def cb(variable, name, index, mode): ... var.trace('w', lambda *args: cb(var, *args)) # or some variation thereof (and for this specific case, Entry content tracking, binding to KeyRelease and possibly also ButtonRelease is usually good enough). From ptmcg at austin.rr.com Fri Jan 18 17:35:46 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 18 Jan 2008 14:35:46 -0800 (PST) Subject: strange syntax rules on list comprehension conditions References: Message-ID: On Jan 18, 1:04?pm, "Chris Mellon" wrote: > On Jan 18, 2008 12:53 PM, Nicholas wrote: > > > I was quite delighted today, after extensive searches yielded nothing, to > > discover how to place an else condition in a list comprehension. > > Trivial mask example: > > >>> [True if i <5 else False for i in range(10)] ? ? ? # A > > [True, True, True, True, True, False, False, False, False, False] > I think this would be preferred over your ternary-ish expression: >>> [ i<5 for i in range(10) ] [True, True, True, True, True, False, False, False, False, False] Do you also write code like: if i<5 == True: blah... If so, please just write: if i<5: better blah... -- Paul From Russ.Paielli at gmail.com Sun Jan 27 17:52:59 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 14:52:59 -0800 (PST) Subject: optional static typing for Python References: Message-ID: On Jan 27, 2:36 pm, Jarek Zgoda wrote: > Russ P. pisze: > > > I noticed that Guido has expressed further interest in static typing > > three or four years ago on his blog. Does anyone know the current > > status of this project? Thanks. > > I thought it was april fools joke? On January 21, 2000? Which calendar do you use? From Russ.Paielli at gmail.com Mon Jan 28 05:21:23 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jan 2008 02:21:23 -0800 (PST) Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <94682b6b-9488-44ce-af69-0b6a16f82c0f@l32g2000hse.googlegroups.com> <479da620$0$25625$426a74cc@news.free.fr> Message-ID: <13067a3e-bce7-45ea-beba-4dc83c749a72@i12g2000prf.googlegroups.com> On Jan 28, 1:53 am, Bruno Desthuilliers wrote: > Russ P. a ?crit : > > > > > On Jan 27, 5:03 pm, Paddy > > >> If static typing is optional then a program written in a dynamic > >> language that passes such an automated static analysis of source code > >> would have to be a simple program written in a simplistic way, and > >> also in a static style. > > > Yes, but for safety-critical software you usually want the simplest > > possible solution. The last think you want is an unnecessarily "fancy" > > design. Unless there is a darn good reason to write a "non-static" > > program, you just don't do it. > > > You might want to check into what the FAA allows in "flight-critical" > > code, for example. I am certainly not an expert in that area, but I've > > had a passing exposure to it. My understanding is that every possible > > branch of the code must be fully and meticulously analyzed and > > verified. Hence, the dynamic dispatching of ordinary object-oriented > > code is either prohibited or severely frowned upon. > > Then Python is definitively out, so this whole thread is pointless. Yes, Python as it stands now is "definitely out" as the ultimate implementation language for flight-critical software. That's essentially a no-brainer. But it can certainly be useful as a prototyping language for R&D. The question then arises as to how to best make use of the prototype. Do you throw away the code and start from scratch? That doesn't seem wise to me. But maybe that's because I have some idea of how much effort can go into developing a good prototype. If Python could be automatically converted to Ada or Java, that could potentially be used as a baseline for actual operational software. That would capture the algorithmic details more reliably than recoding from scratch by hand. But such an automatic conversion is not feasible without explicit typing. And speaking of "pointless," ... I just wasted a significant amount of time replying to a pointless post. Oh, well. From google at mrabarnett.plus.com Wed Jan 30 21:24:37 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 30 Jan 2008 18:24:37 -0800 (PST) Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <9275bfdb-8f07-4c63-abbf-40c136388bf3@i7g2000prf.googlegroups.com> On Jan 31, 12:57 am, Asun Friere wrote: > On Jan 31, 3:13 am, Steve Holden wrote: > > > Wildemar Wildenburger wrote: > > > Well, you never go wrong with apply(genital(), females), do you? > > Never?! > > class PowerSocket () : > def __init__ (self, plug=female, active=False) : > self.plug = plug > self.active = active > > females = [p for p in powersockets if p.active and p.plug == 'female'] > > Ouch!! If on the other hand 'females' is populated by instances of > (or merely includes instances of) class 'Human', I suggest you test > for female.consent somewhere in your code! > The Pythonic approach would be to try the action and catch a NoConsentException. From pablo at decode.com.ar Mon Jan 7 15:55:33 2008 From: pablo at decode.com.ar (Pablo Ziliani) Date: Mon, 07 Jan 2008 18:55:33 -0200 Subject: Python's great, in a word In-Reply-To: References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <478291C5.1000609@decode.com.ar> Dustan wrote: > On Jan 7, 11:40 am, Martin Marcher wrote: > >> it's pythonicness. >> > > "it is pythonicness"??? > Obviously a typo, for "It is pythonic, Ness". A reference to the well-known Loch Ness Monster, definitely pythonic if you see some pictures: http://images.google.com/images?q=loch+ness My 2 cents, Pablo From __peter__ at web.de Mon Jan 21 13:48:18 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Jan 2008 19:48:18 +0100 Subject: index of min element of sequence References: Message-ID: Neal Becker wrote: > What's a good/fast way to find the index of the minimum element of a > sequence? (I'm fairly sure sorting the sequence is not the fastest > approach) >>> items = "defbhkamnz" >>> min(xrange(len(items)), key=items.__getitem__) 6 >>> items[6] 'a' Peter From paul at subsignal.org Wed Jan 2 16:03:10 2008 From: paul at subsignal.org (paul) Date: Wed, 02 Jan 2008 22:03:10 +0100 Subject: XML-XSD Processing/Creation. In-Reply-To: References: Message-ID: xkenneth schrieb: > Hi All, > > So i'm working with the WITSML standard, which is a pretty > massive standard defined in XML for the transfer of oilfield data. > There are a ton of XSD files for defining and checking all data in the > WITSML format. I'd like to be able to easily create XML based on the > types defined by the WITSML XSD files. Is there any way to create a > basic XML object based on an XSD file and then populate it with data. > Can i create python classes based off the XSD files? What else can I > do with the XSD files? This might be worth looking at: http://www.rexx.com/~dkuhlman/#generateDS cheers Paul From ivan at 0x4849.net Thu Jan 10 23:45:31 2008 From: ivan at 0x4849.net (Ivan Novick) Date: Thu, 10 Jan 2008 20:45:31 -0800 (PST) Subject: Persistent HTTP Connections with Python? References: Message-ID: On Jan 10, 10:46 am, Scott Sharkey wrote: > Hello All, > > I am trying to write a python script to talk to an xml-based stock feed > service. They are telling me that I must connect and login, and then > "issue refresh requests" to fetch the data. This sounds a lot (to me) > like HTTP 1.1 persistent connections. Can I do that with the urllib > functions, or do I need to use the httplib functions for this kind of > work. Pointers and/or sample code would be much appreciated. Your questions leaves out all important details like the exact nature of the API being provided. I highly doubt HTTP persistent connections has anything to do with what you will need to connect to there service. Services like this normally come with example code, i recommend you get access to that. Regards, Ivan Novick http://www.0x4849.net From suyashjape at gmail.com Fri Jan 11 04:14:19 2008 From: suyashjape at gmail.com (suyash jape) Date: Fri, 11 Jan 2008 14:44:19 +0530 Subject: How to POST call and retrieve result page Message-ID: <16314edc0801110114t346bca6ek71660132de60b91e@mail.gmail.com> Hi all i want to access a web page through python script, fillup the necessary fields, and press submit button (which does POST call) and retrieve the result page and retrieve some values from it. Here is the script i have written till now. >import urllib2 > # create array of name/value pairs > self.params = urllib.urlencode({'seqname': 'BioSequence', 'sequence': 'ATACATTATCCAAACATAAAAAGCATGGCTT'}) > > # send http-post > request = urllib.urlopen("http://www.hydrazome.metazome.net/search.php", params) > > # read back each line of reply > line = request.read() >print line This script fills up the correct values in the search.php page.But i am not sure if it is doing the POST (submit call). Beacause in 'line' varialble, i am getting the search.php page.Not the result page which is blast_results.php. How to retrieve the result page? Thanks Suyash -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Fri Jan 11 04:16:42 2008 From: cwitts at gmail.com (Chris) Date: Fri, 11 Jan 2008 01:16:42 -0800 (PST) Subject: python recursive function References: Message-ID: On Jan 11, 10:30 am, Tom_chicollegeboy wrote: > here is what I have to do: > > This question involves a game with teddy bears. The game starts when I > give you some bears. You then start giving me back some bears, but you > must follow these rules (where n is the number of bears that you > have): > > If n is even, then you may give back exactly n/2 bears. (Hint: To test > whether n is even, use the expression ((n % 2) == 0).) > If n is divisible by 3 or 4, then you may multiply the last two digits > of n and give back this many bears. (By the way, the last digit of n > is n%10, and the next-to-last digit is (n%100)/10; this rule may not > be used if either of the last two digits is 0.) > > If n is divisible by 5, then you may give back exactly 42 bears. > The goal of the game for you is to end up with EXACTLY 42 bears. > > For example, suppose that you start with 250 bears. Then you could > make these moves: > > Start with 250 bears. > Since 250 is divisible by 5, you may return 42 of the bears, leaving > you with 208 bears. > Since 208 is even, you may return half of the bears, leaving you with > 104 bears. > Since 104 is even, you may return half of the bears, leaving you with > 52 bears. > Since 52 is divisible by 4, you may multiply the last two digits > (resulting in 10) and return these 10 bears. This leaves you with 42 > bears. > You have reached the goal! > Now, you are to write a program that, if I give you n bears, returns > true if it is at all possible for you to win the game. Your program > must use recursion to check all possible ways in which you can apply > the rules. > > Usage: > > >>> bears(42) > True > >>> bears(250) > True > >>> bears(50) > False > >>> bears(84) > True > >>> bears(41) > > False > > As you see my program must use recursion. > > I came up with this idea but I am not sure if its right or are there > any minor errors that I can easily fix: > > def bears (n): > if n==42: > return True > if n%5==0: > bears(n-42) > if n%2==0: > bears(n/2) > if n%3==0 or n%4==0: > one = (n%10) > two = ((n%100)/10) > if one!=0 and two!=0: > bears(n-(one*two)) > return False > > If a game hits 42 it should return True, otherwise False. If program > never hits 42 and return True, then it returns False. I figured out > base case, but I still get False when I enter bears(250). Any help > would be very appreciated! Stylistically I prefer 'if not n % 5', looks neater. As for your assignment, the hardest task will be creating an effective method of ensuring you recurse through all possibilities. ie. do you brute force on every step, or when getting to step do you fork your possibilities. That is more a design question rather than a python one though. From http Tue Jan 29 04:35:53 2008 From: http (Paul Rubin) Date: 29 Jan 2008 01:35:53 -0800 Subject: Encryption Recommendation References: <6b40b773-8554-4e9c-838f-e6934212d16e@n20g2000hsh.googlegroups.com> <606aj3F1pa0tfU1@mid.uni-berlin.de> Message-ID: <7xzlupug7a.fsf@ruckus.brouhaha.com> Michael Str?der writes: > But if the password checking is done with a challenge-response > mechanism (e.g. HTTP-Digest Auth or SASL with DIGEST-MD5) it's > required that the instance checking the password has the clear-text > password available. So reversible encryption for storing passwords > might be required. If you're trying to authenticate network logins using passwords, and if you have control over both ends of the protocol but for some reason don't want to use a full-blown encryption scheme, it's far better to authenticate with something like SRP (http://srp.stanford.edu) than a more primitive method like HTTP digest auth. SRP doesn't require storing plaintext passwords, and more importantly, it protects the password from offline dictionary searches by someone sniffing the network connection. There is a Python SRP implementation embedded in TLSLite (www.trevp.com/tlslite) but it might be nice to extract or reimplement the SRP code so that it can be used separately from TLS. From MartinRinehart at gmail.com Fri Jan 25 13:59:05 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Fri, 25 Jan 2008 10:59:05 -0800 (PST) Subject: Operator overloading References: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com> <5vuob3F1nd2bhU1@mid.uni-berlin.de> Message-ID: <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> Diez B. Roggisch wrote: > No, there is no way. You would change general interpreter behavior if > you could set arbitrary operators for predefined types. > > Start grumping... Thank you, Diez. If I ever design a language, please remind me that complete, easy, well-documented access to the working of the internals (and the ability to change same) would be very, uh, what's the right word? Pythonic? From Graham.Dumpleton at gmail.com Tue Jan 29 20:55:27 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 29 Jan 2008 17:55:27 -0800 (PST) Subject: Web Interface Recommendations References: <45040839-8b1f-40af-9ef5-1be274c6e95f@z17g2000hsg.googlegroups.com> Message-ID: <80d6ce9f-6c8b-412d-a261-cfe480bd0c3b@e10g2000prf.googlegroups.com> On Jan 30, 12:00 pm, PurpleServerMonkey wrote: > Looking for suggestions on the best framework to use for an > applications web interface. > > The user interface doesn't need immediate feedback and will be cross > platform so a web interface is a good solution especially since it > operates as a client\server system and not standalone. > > However there's just so many frameworks to choose from it's very > confusing. After a lot of reading it sounds like OSE or Cherrypy might > be good options but I don't have any real world experience with these > frameworks to go by. > > Basically the interface won't be the application, it's used to input > data and have the application act on it. It's going to have a > Postgresql database and a number of service\daemon processes that do > the actual work. It will also contain some form based information for > keeping track of requests etc. and grow to a fair number of screens > over time. > > Given the above what framework would you recommend? Surprised you even looked at OSE. Although OSE has some features for building HTML based web interfaces, they are very basic and not really intended for building major stuff. OSE can still be useful for writing backend applications, but would very much suggest you use just the XML- RPC interfaces it provides to talk into its distributed messaging system and service agent framework. If you use the XML-RPC interfaces then you can use a proper web application framework for doing the actual HTML based user interface front end. At that point you can choose any of the major frameworks, such as Django, Pylons, TurboGears, CherryPy or web.py. Splitting the front end from the backend like this also means that backend itself could be swapped out. Thus, instead of using OSE in the backend, you could use simpler XML-RPC enabled Python applications, or even use Pyro. In other words, you avoid intertwining code for front end and backend too much, thus perhaps making it easier to change and adapt as it grows. Graham From asmodai at in-nomine.org Fri Jan 4 05:32:21 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jan 2008 11:32:21 +0100 Subject: NetSpeed In-Reply-To: <52da23100801030810u72e0a06asa69438e9ebe6abfc@mail.gmail.com> References: <52da23100801030810u72e0a06asa69438e9ebe6abfc@mail.gmail.com> Message-ID: <20080104103221.GH82115@nexus.in-nomine.org> -On [20080104 10:34], Sunil Ghai (sunilkrghai at gmail.com) wrote: >Hey can i check the average Downloading speed of available internet connection >without downloading any dummy file? :o For all I know you cannot check anything until you have established some data over a given period of time. So at the start it will be: N/A Only after data has been passing through the connection and it having been measured can you calculate an average. But perhaps I missed something. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Death is that state where one exists only in the memories of others... From arnodel at googlemail.com Tue Jan 29 02:06:34 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 28 Jan 2008 23:06:34 -0800 (PST) Subject: Python self-evaluating strings References: <1BEEBF03-1A38-4745-B08B-DCA3106D1CC5@gmail.com> Message-ID: On Jan 29, 3:48 am, "Terry Reedy" wrote: > "Arnaud Delobelle" wrote in message > > news:a04ca850-fe63-4b7e-abff-cdacab3bcc0f at i29g2000prf.googlegroups.com... > | I found this:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > Exactly the one I meant. > > | It contains a lambda-solution similar to mine, only more concise: > > | (lambda x:x%`x`)('(lambda x:x%%`x`)(%s)') > > Being a Lisp novice, I was rather proud of that translation > > | I have been using python for 7 years, and it the first time ever that > | I see the `...` construct being used! > > It is going away in 3.0, so the above would need revision to work with > repr(), if indeed it will. Here's the py3k-compliant version: >>> k=(lambda x:x%repr(x))('(lambda x:x%%repr(x))(%s)') >>> k == eval(k) True -- Arnaud From grante at visi.com Sat Jan 12 11:26:15 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 12 Jan 2008 16:26:15 -0000 Subject: where do my python files go in linux? References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> <20080112113759.GJ75977@nexus.in-nomine.org> Message-ID: <13ohqh7fggu7i7c@corp.supernews.com> On 2008-01-12, Jorgen Bodde wrote: >> Normally you'd split up the bulk of the code into a module which gets >> installed into site-packages and a piece of stand-alone front-end code which >> imports the module and executes whatever you need to do and gets installed >> into a typical PATH directory. > > I would agree but it is not a site package I am trying to distribute, > but a wxPython application. I would not think my app belongs in the > python site packages dir. That's my opinion also, but I've seen several apps that are distributed that way. The bulk of the application code goes into the site-packages directory and then there's a 5-line script in /usr/bin that calls the application's main module that's in site-packages. That seems wrong to me... -- Grant Edwards grante Yow! Civilization is at fun! Anyway, it keeps visi.com me busy!! From toby at tobiah.org Mon Jan 7 17:59:13 2008 From: toby at tobiah.org (Tobiah) Date: Mon, 07 Jan 2008 14:59:13 -0800 Subject: Open source English dictionary to use programmatically w/ python In-Reply-To: References: Message-ID: <4782a2d2$0$26002$88260bb3@free.teranews.com> dgoldsmith_89 wrote: > Can anyone point me to a downloadable open source English dictionary > suitable for programmatic use with python: I'm programming a puzzle > generator, and I need to be able to generate more or less complete > lists of English words, alphabetized. Thanks! DG If all you want are the words themselves, then any linux box has a fairly complete list. I put mine here: http://tobiah.org/words.zip -- Posted via a free Usenet account from http://www.teranews.com From grahn+nntp at snipabacken.dyndns.org Sun Jan 20 08:53:54 2008 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 20 Jan 2008 13:53:54 GMT Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: On Fri, 18 Jan 2008 09:15:58 -0800 (PST), David Sanders wrote: > Hi, > > I am processing large files of numerical data. Each line is either a > single (positive) integer, or a pair of positive integers, where the > second represents the number of times that the first number is > repeated in the data -- this is to avoid generating huge raw files, > since one particular number is often repeated in the data generation > step. > > My question is how to process such files efficiently to obtain a > frequency histogram of the data (how many times each number occurs in > the data, taking into account the repetitions). My current code is as > follows: ... > The data files are large (~100 million lines), and this code takes a > long time to run (compared to just doing wc -l, for example). I don't know if you are in control of the *generation* of data, but I think it's often better and more convenient to pipe the raw data through 'gzip -c' (i.e. gzip-compress it before it hits the disk) than to figure out a smart application-specific compression scheme. Maybe if you didn't have a homegrown file format, there would have been readymade histogram utilities? Or at least a good reason to spend the time writing an optimized C version. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From hnessenospam at yahoo.com Thu Jan 24 12:36:37 2008 From: hnessenospam at yahoo.com (hnessenospam at yahoo.com) Date: Thu, 24 Jan 2008 09:36:37 -0800 (PST) Subject: Duplicating a variable Message-ID: I have run into a bit of a subtle problem. How do I go about duplicating a variable (particularly a list of lists) in python. I was surprised when simple assignment didn't work. For example, let y = [1,2,3] >>> x = y >>> x[2] = 5 >>> y [1,2,5] It seems that simply assigning x to y allows further modification of y via x. (I'm new to python and I'm sure this is obvious to experienced users). So my question, how do I go about duplicating a variable which I can then manipulate independently? Thanks, -Hans From deets at nospam.web.de Wed Jan 16 14:35:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jan 2008 20:35:34 +0100 Subject: Help with python shell In-Reply-To: References: <2706aa71-b072-4cbb-a7d9-abbfadd7d35a@c4g2000hsg.googlegroups.com> <5v7100F1kmtinU2@mid.uni-berlin.de> Message-ID: <5v74kaF1kt3a3U1@mid.uni-berlin.de> cbmeeks schrieb: > On Jan 16, 1:33 pm, "Diez B. Roggisch" wrote: >> cbmeeks schrieb: >> >>> I just upgraded my Python install up to version 2.5.1 (from 2.4.x) >>> using source code and compiling. >>> Everything went fine until I enter the command line mode and press any >>> arrow keys. >>> When I press UP arrow, I was getting my previous command as always but >>> now I get: ^[[A >>> What can I do to fix this?? >> Compiling with readline support? I guess that's missing. >> >> Diez > > I tried ./configure --enable-readline but that didn't do the trick. > ARG!! This is annoying. You don't just need to enable it - the readline lib needs to be installed, including the possible devel-package (If you are under linux) for the headers. Diez From martin at v.loewis.de Sun Jan 13 06:26:17 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jan 2008 12:26:17 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801131224.10263.donn.ingle@gmail.com> References: <200801130930.07852.donn.ingle@gmail.com> <4789D98A.80609@v.loewis.de> <200801131224.10263.donn.ingle@gmail.com> Message-ID: <4789F559.1090703@v.loewis.de> > I have found that os.listdir() does not always return unicode objects when > passed a unicode path. Sometimes "byte strings" are returned in the list, > mixed-in with unicodes. Yes. It does so when it fails to decode the byte string according to the file system encoding (which, in turn, bases on the locale). > I will try the technique given > on:http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html#guessing-the-encoding > Perhaps that will help. I would advise against such a strategy. Instead, you should first understand what the encodings of the file names actually *are*, on a real system, and draw conclusions from that. > I gather you mean that I should get a unicode path, encode it to a byte string > and then pass that to os.listdir > Then, I suppose, I will have to decode each resulting byte string (via the > detect routines mentioned in the link above) back into unicode - passing > those I simply cannot interpret. That's what I meant, yes. Again, you have a number of options - passing those that you cannot interpret is but one option. Another option is to accept moji-bake. >> Then, if the locale's encoding cannot decode the file names, you have >> several options >> a) don't try to interpret the file names as character strings, i.e. >> don't decode them. Not sure why you need the file names - if it's >> only to open the files, and never to present the file name to the >> user, not decoding them might be feasible > So, you reckon I should stick to byte-strings for the low-level file open > stuff? It's a little complicated by my using Python Imaging to access the > font files. It hands it all over to Freetype and really leaves my sphere of > savvy. > I'll do some testing with PIL and byte-string filenames. I wish my memory was > better, I'm pretty sure I've been down that road and all my results kept > pushing me to stick to unicode objects as far as possible. I would be surprised if PIL/freetype would not support byte string file names if you read those directly from the disk. OTOH, if the user has selected/typed a string at a GUI, and you encode that - I can easily see how that might have failed. >> That's correct, and there is no solution (not in Python, not in any >> other programming language). You have to made trade-offs. For that, >> you need to analyze precisely what your requirements are. > I would say the requirements are: > 1. To open font files from any source (locale.) > 2. To display their filename on the gui and the console. > 3. To fetch some text meta-info (family etc.) via PIL/Freetype and display > same. > 4. To write the path and filename to text files. > 5. To make soft links (path + filename) to another path. > > So, there's a lot of unicode + unicode and os.path.join and so forth going on. I notice that this doesn't include "to allow the user to enter file names", so it seems there is no input of file names, only output. Then I suggest this technique of keeping bytestring/unicode string pairs. Use the Unicode string for display, and the byte string for accessing the disc. >>> I went through this exercise recently and had no joy. It seems the string >>> I chose to use simply would not render - even under 'ignore' and >>> 'replace'. >> I don't understand what "would not render" means. > I meant it would not print the name, but constantly throws ascii related > errors. That cannot be. Both the ignore and the replace error handlers will silence all decoding errors. > I don't know if the character will survive this email, but the text I was > trying to display (under LANG=C) in a python script (not the immediate-mode > interpreter) was: "M?gul". The second character is a capital O with an umlaut > (double-dots I think) above it. For some reason I could not get that to > display as "M?gul" or "Mgul". I see no problem with that: >>> u"M\xd6gul".encode("ascii","ignore") 'Mgul' >>> u"M\xd6gul".encode("ascii","replace") 'M?gul' Regards, Martin From ptmcg at austin.rr.com Tue Jan 22 18:31:19 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 22 Jan 2008 15:31:19 -0800 (PST) Subject: Processing XML that's embedded in HTML References: Message-ID: <1d163d82-db6b-4f43-8462-4359fb1f4b01@f47g2000hsd.googlegroups.com> On Jan 22, 10:57?am, Mike Driscoll wrote: > Hi, > > I need to parse a fairly complex HTML page that has XML embedded in > it. I've done parsing before with the xml.dom.minidom module on just > plain XML, but I cannot get it to work with this HTML page. > > The XML looks like this: > ... Once again (this IS HTML Day!), instead of parsing the HTML, pyparsing can help lift the interesting bits and leave the rest alone. Try this program out: from pyparsing import makeXMLTags,Word,nums,Combine,oneOf,SkipTo,withAttribute htmlWithEmbeddedXml = """

Hey! this is really bold! Owner 1 07/16/2007 No Doe, John

1905 S 3rd Ave , Hicksville IA 99999
Owner 2 07/16/2007 No Doe, Jane
1905 S 3rd Ave , Hicksville IA 99999
", "test", "
more HTML blah blah blah... """ # define pyparsing expressions for XML tags rowStart,rowEnd = makeXMLTags("Row") relationshipStart,relationshipEnd = makeXMLTags("Relationship") priorityStart,priorityEnd = makeXMLTags("Priority") startDateStart,startDateEnd = makeXMLTags("StartDate") stopsExistStart,stopsExistEnd = makeXMLTags("StopsExist") nameStart,nameEnd = makeXMLTags("Name") addressStart,addressEnd = makeXMLTags("Address") # define some useful expressions for data of specific types integer = Word(nums) date = Combine(Word(nums,exact=2)+"/"+ Word(nums,exact=2)+"/"+Word(nums,exact=4)) yesOrNo = oneOf("Yes No") # conversion parse actions integer.setParseAction(lambda t: int(t[0])) yesOrNo.setParseAction(lambda t: t[0]=='Yes') # could also define a conversion for date if you really wanted to # define format of a , plus assign results names for each data field rowRec = rowStart + \ relationshipStart + SkipTo(relationshipEnd)("relationship") + relationshipEnd + \ priorityStart + integer("priority") + priorityEnd + \ startDateStart + date("startdate") + startDateEnd + \ stopsExistStart + yesOrNo("stopsexist") + stopsExistEnd + \ nameStart + SkipTo(nameEnd)("name") + nameEnd + \ addressStart + SkipTo(addressEnd)("address") + addressEnd + \ rowEnd # set filtering parse action rowRec.setParseAction(withAttribute(relationship="Owner",priority=1)) # find all matching rows, matching grammar and filtering parse action rows = rowRec.searchString(htmlWithEmbeddedXml) # print the results (uncomment r.dump() statement to see full # result for each row) for r in rows: # print r.dump() print r.relationship print r.priority print r.startdate print r.stopsexist print r.name print r.address This prints: Owner 1 07/16/2007 False Doe, John 1905 S 3rd Ave , Hicksville IA 99999 In addition to parsing this data, some conversions were done at parse time, too - "1" was converted to the value 1, and "No" was converted to False. These were done by the conversion parse actions. The filtering just for Row's containing Relationship="Owner" and Priority=1 was done in a more global parse action, called withAttribute. If you comment this line out, you will see that both rows get retrieved. -- Paul (Find out more about pyparsing at http://pyparsing.wikispaces.com.) From mr.cerutti at gmail.com Wed Jan 16 07:33:11 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 16 Jan 2008 07:33:11 -0500 Subject: Generic string import like in strptime? In-Reply-To: References: Message-ID: <51302a8c0801160433s8789ba9i9bb666a38e085983@mail.gmail.com> On Jan 16, 2008 3:34 AM, Andre wrote: > Hi there > > Is there a function like strptime, which takes a string and converts it > into an array depending on a format string I provide. Like: > >>> a = '3456\tblub-blib.0.9' > >>> b = '%d\t%s-%s.%f' > >>> c = mysticalfunction(a,b) > >>> print c > [3456,'blub','blib',0.9] No, not in the standard distribution of Python. In Python, you're expected to use appropriate string methods, or hold your nose and drag out the re module. There are some scanf-like libraries for Python available on the net, e.g., http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/. None of them have become popular enough with Python users to make it into the standard distribution. An excellent tool that can be used in these cases is pyparsing, which is also not in the standard distribution. http://pyparsing.wikispaces.com/ -- Neil Cerutti From gnewsg at gmail.com Sat Jan 12 11:31:59 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 12 Jan 2008 08:31:59 -0800 (PST) Subject: How to get user home directory on Windows Message-ID: Hi all, I'm trying to use the pywin32 extension to find out the user's home directory but currently I didn't find a solution yet. What I'd need to do is not getting the home directory of the currently logged in user but something like: >>> get_homedir("frank") "C:\home\users\frank" >>> get_homedir("josh") "C:\home\users\josh" Is there a way to do that? I tried to search through the Pywin32 documentation with no luck. In addition I'm not practiced with the Windows API at all. From nurple11 at gmail.com Sun Jan 27 16:36:56 2008 From: nurple11 at gmail.com (nurple11 at gmail.com) Date: Sun, 27 Jan 2008 13:36:56 -0800 (PST) Subject: python valentine Message-ID: <8b3988e8-aabf-456c-b748-10cc273ff050@i7g2000prf.googlegroups.com> Slightly off-topic, but this is the best Valentine's Day card I've seen in a while: http://unholidaycards.com/code.html I think I just might get some for my lab. #!/usr/bin/env python from relationships import * from alcohol import shot, beer def valentines_day(self): if self.dating: if self.money == 0: self.dating = False elif self.num_prev_dates == 0: self.money -= dinner() self.money -= pointless_gift() else: self.money -= dinner()/sqrt(self.num_prev_dates) if randInt(self.num_prev_dates): self.money -= pointless_gift()/self.num_prev_dates elif self.married: if self.years_married < 5: self.money -= dinner()/(self.years_married ** 2) else: pass else: while self.blood_alcohol < .08: self.blood_alcohol += beer() while self.blood_alcohol < .22: self.blood_alcohol += shot() sleep(86400) From eduardo.padoan at gmail.com Fri Jan 18 12:20:55 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Fri, 18 Jan 2008 15:20:55 -0200 Subject: Bug in __init__? In-Reply-To: References: Message-ID: On Jan 18, 2008 3:09 PM, Zbigniew Braniecki wrote: > I found a bug in my code today, and spent an hour trying to locate it > and then minimize the testcase. > > Once I did it, I'm still confused about the behavior and I could not > find any reference to this behavior in docs. > > testcase: > > class A(): > > def add (self, el): > self.lst.extend(el) > > def __init__ (self, val=[]): > print val > self.lst = val > > > def test (): > x = A() > x.add(["foo1","foo2"]) > b = A() > > > So, what I would expect here is that I will create two instances of > class A with empty self.lst property. Right? > > In fact (at least with my Python 2.5) > > gandalf at gandalf-desktop:~/projects/pyl10n$ ./scripts/test.py > [] > ['foo1', 'foo2'] > > This bug does not happen when I switch to __init__ (self, *args) and > assign self.lst= args[0]. > > Any clue on what's going on here, and/if where I should report it? It is a FAQ, not a bug: http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From jimis at gmx.net Thu Jan 10 15:15:37 2008 From: jimis at gmx.net (Dimitrios Apostolou) Date: Thu, 10 Jan 2008 22:15:37 +0200 (EET) Subject: urllib2 rate limiting In-Reply-To: <87ejcpo7r8.fsf@merkury.smsnet.pl> References: <87ejcpo7r8.fsf@merkury.smsnet.pl> Message-ID: On Thu, 10 Jan 2008, Rob Wolfe wrote: > Dimitrios Apostolou writes: > >> P.S. And something simpler: How can I disallow urllib2 to follow >> redirections to foreign hosts? > > You need to subclass `urllib2.HTTPRedirectHandler`, override > `http_error_301` and `http_error_302` methods and throw > `urllib2.HTTPError` exception. Thanks! I think for my case it's better to override redirect_request method, and return a Request only in case the redirection goes to the same site. Just another question, because I can't find in the docs the meaning of (req, fp, code, msg, hdrs) parameters. To read the URL I get redirected to (the 'Location:' HTTP header?), should I check the hdrs parameter or there is a better way? Thanks, Dimitris > > http://diveintopython.org/http_web_services/redirects.html > > HTH, > Rob > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Sun Jan 6 08:57:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 06 Jan 2008 14:57:34 +0100 Subject: Killing worker threads In-Reply-To: <8a6b8e350801060548m6f39594che1207cc5bc4b6487@mail.gmail.com> References: <8a6b8e350801060548m6f39594che1207cc5bc4b6487@mail.gmail.com> Message-ID: James Matthews wrote: > You can use the stop method! You can? >>> import threading >>> t = threading.Thread() >>> t.stop() Traceback (most recent call last): File "", line 1, in AttributeError: 'Thread' object has no attribute 'stop' >>> What Python version are you using? From jarausch at igpm.rwth-aachen.de Tue Jan 22 07:58:55 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 22 Jan 2008 13:58:55 +0100 Subject: ctypes CDLL - which paths are searched? In-Reply-To: References: <4794d573$0$2980$ba620e4c@news.skynet.be> Message-ID: <4795E88F.7050406@igpm.rwth-aachen.de> Thomas Heller wrote: > Helmut Jarausch schrieb: >> Hi, >> >> how can I specify the paths to be searched for a dynamic library >> to be loaded by ctypes' CDLL class on a Linux system. >> >> Do I have to set os.environment['LD_LIBRARY_PATH'] ? >> > > ctypes passes the argument given to CDLL(path) straight to > the dlopen(3) call, so your system documentation should tell you. > Thanks, but then it's difficult to use CDLL. Setting os.environ['LD_LIBRARY_PATH'] within the script which calls CDLL is too late. What other methods are possible rather than put an explicit export LD_LIBRARY_PATH=... before running the script, if I don't want to put the dynamic library into a standard system library. Many thanks, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From miki.tebeka at gmail.com Thu Jan 17 19:42:01 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 17 Jan 2008 16:42:01 -0800 (PST) Subject: "Code Friendly" Blog? References: <0fd979c6-5a11-4989-9438-51a7b20ecd23@n20g2000hsh.googlegroups.com> Message-ID: <12e6dfa8-a550-4485-8a4c-721baadd79a5@e6g2000prf.googlegroups.com> Hello Mel, [Hai] >> how about bracketing your code in the
 tags?
[Mel]
> That won't help the escape problem, though it will preserve vital
> Python whitespace.  HTML has to be interpreting '<' characters to
> recognize the ''.
They also manage to mess up the first indentation in the 
section :)

Thanks,
--
Miki 
http://pythonwise.blogspot.com


From petr.jakes.tpc at gmail.com  Tue Jan  1 16:01:24 2008
From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com)
Date: Tue, 1 Jan 2008 13:01:24 -0800 (PST)
Subject: Newbie: Why doesn't this work
References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com>
	
	
	
	
	
Message-ID: 

> > My question is: is it possible to set the "property" for any attribute
> > when I do not know what will be the name of the attribute in the
> > future?
>
> Uhm... I don't understand the question. Perhaps if you think of a concrete
> case...?

Thanks for reply,

few minutes after i posted my question, I have realized my posting is
probably a "nonsense".

If I understand it properly, it is necessary, in the respect of
encapsulation, to define attributes inside the class (even it is
possible to add a new attribute to the existing object outside class
definition).

The meaning of my question was:
Is it possible to define some general sort of set/get/del/doc rules
for the attributes which are defined in the code AFTER the
instantiation of an object.

I am sending this question even I feel such a "on the fly" creation of
the attribute is probably not a good trick.

Petr Jakes


From chiendarret at yahoo.com  Sun Jan  6 16:33:52 2008
From: chiendarret at yahoo.com (Francesco Pietra)
Date: Sun, 6 Jan 2008 13:33:52 -0800 (PST)
Subject: Delete lines containing a specific word
In-Reply-To: 
Message-ID: <210501.70143.qm@web57616.mail.re1.yahoo.com>

Steven:
Thanks. See below please (of very marginal interest)

--- Steven D'Aprano  wrote:

> On Sun, 06 Jan 2008 09:21:33 -0800, Francesco Pietra wrote:
> 
> > Please, how to adapt the following script (to delete blank lines) to
> > delete lines containing a specific word, or words?
> 
> That's tricky, because deleting lines from a file isn't a simple 
> operation. No operating system I know of (Windows, Linux, OS X) has a 
> "delete line" function.

As I am at Debian Linux, I do that with grep -v


> 
> Do you really need to delete the lines in place? It would be much simpler 
> to leave the original data as-is, and create a new file with just the 
> lines that aren't deleted.
> 
> 
> > f=open("output.pdb", "r")
> > for line in f:
> > 	line=line.rstrip()
> > 	if line:
> > 		print line
> > f.close()
> 
> How to adapt this script:
> 
> First, think about what this script does. That is, it goes through each 
> line, and if the line is not blank, it prints it.
> 
> What do you want it to do instead? You want it to print the line if the 
> line doesn't contain a specific word. So that's the first thing you need 
> to change.
> 
> Secondly, you might want the script to write its output to a file, 
> instead of printing. So, instead of the line "print line", you want it to 
> write to a file.

may be cumbersome, though I use  2>&1 | tee output file.pdb so that I can see
what happens on the screen and have the modified file.

> 
> Before you can write to a file, you need to open it. So you will need to 
> open another file: you will have two files open, one for input and one 
> for output. And you will need to close them both when you are finished.
> 
> Does that help you to adapt the script?
> 
> 
> > If python in Linux accepts lines beginning with # as comment lines,
> > please also a script to comment lines containing a specific word, or
> > words, and back, to remove #.
> 
> The same process applies. Instead of "delete line", you want to "comment 
> line". 
> 
> 
> 
> -- 
> Steven
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 



      ____________________________________________________________________________________
Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ 



From br.rizwan at googlemail.com  Thu Jan 17 17:30:50 2008
From: br.rizwan at googlemail.com (Rizwan)
Date: Thu, 17 Jan 2008 14:30:50 -0800 (PST)
Subject: Python Tutorial.
Message-ID: <2537f4eb-c047-4eae-9d26-93c7498b5840@f47g2000hsd.googlegroups.com>


Hiya,

I found one good website for python tutorial. just thought to share
with community.

Hope you all also like it..

 http://python.objectis.net


-MR



From kw at codebykevin.com  Mon Jan  7 18:14:12 2008
From: kw at codebykevin.com (Kevin Walzer)
Date: Mon, 07 Jan 2008 18:14:12 -0500
Subject: Does PIL work with Tk 8.5?
In-Reply-To: <4782B074.8080709@v.loewis.de>
References: <2870$4782a5c4$4275d90a$673@FUSE.NET>
	<4782B074.8080709@v.loewis.de>
Message-ID: <4782B244.7010706@codebykevin.com>

Martin v. L?wis wrote:

> OTOH, it's more likely that the PIL binaries you are using conflict with
> your Tk installation - if the binaries were for Tk 8.4 (which isn't
> quite clear to me whether that's indeed the case), then they can't work
> with Tk 8.5, as Tk doesn't provide that kind of binary compatibility.

Tk itself has a stubs mechanism that allows libraries compiled against 
earlier versions to be used with later versions. It's different than 
Python in this respect. A pure-Tk library (such as Img or TkPNG) built 
against Tk 8.4 would not require re-compilation to be used with 8.5. 
Since PIL is a Python library, however, you may be right.

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com


From alnilam at gmail.com  Tue Jan 22 22:41:20 2008
From: alnilam at gmail.com (Alnilam)
Date: Tue, 22 Jan 2008 19:41:20 -0800 (PST)
Subject: HTML parsing confusion
References: <1d920c58-c71e-4d8d-9cfb-0d2b49982ecc@c4g2000hsg.googlegroups.com>
	<1f32c6a5-264c-41ab-b6b7-c88f59ae0216@1g2000hsl.googlegroups.com> 
	<6a05dcf8-362c-4bb8-be3b-f3876e2663a4@v46g2000hsv.googlegroups.com> 
	<50269e4a-af44-4d73-b6cb-c42af6b5164d@e10g2000prf.googlegroups.com> 
	<5vmkiiF1nadr7U1@mid.uni-berlin.de>
	
	
Message-ID: <6cc92ad4-4448-4254-8c01-a04b0c035117@d21g2000prf.googlegroups.com>

On Jan 22, 7:29?pm, "Gabriel Genellina" 
wrote:
>
> > I was asking this community if there was a simple way to use only the
> > tools included with Python to parse a bit of html.
>
> If you *know* that your document is valid HTML, you can use the HTMLParser ?
> module in the standard Python library. Or even the parser in the htmllib ?
> module. But a lot of HTML pages out there are invalid, some are grossly ?
> invalid, and those parsers are just unable to handle them. This is why ?
> modules like BeautifulSoup exist: they contain a lot of heuristics and ?
> trial-and-error and personal experience from the developers, in order to ?
> guess more or less what the page author intended to write and make some ?
> sense of that "tag soup".
> A guesswork like that is not suitable for the std lib ("Errors should ?
> never pass silently" and "In the face of ambiguity, refuse the temptation ?
> to guess.") but makes a perfect 3rd party module.
>
> If you want to use regular expressions, and that works OK for the ?
> documents you are handling now, fine. But don't complain when your RE's ?
> match too much or too little or don't match at all because of unclosed ?
> tags, improperly nested tags, nonsense markup, or just a valid combination ?
> that you didn't take into account.
>
> --
> Gabriel Genellina

Thanks, Gabriel. That does make sense, both what the benefits of
BeautifulSoup are and why it probably won't become std lib anytime
soon.

The pages I'm trying to write this code to run against aren't in the
wild, though. They are static html files on my company's lan, are very
consistent in format, and are (I believe) valid html. They just have
specific paragraphs of useful information, located in the same place
in each file, that I want to 'harvest' and put to better use. I used
diveintopython.org as an example only (and in part because it had good
clean html formatting). I am pretty sure that I could craft some
regular expressions to do the work -- which of course would not be the
case if I was screen scraping web pages in the 'wild' -- but I was
trying to find a way to do that using one of those std libs you
mentioned.

I'm not sure if HTMLParser or htmllib would work better to achieve the
same effect as the regex example I gave above, or how to get them to
do that. I thought I'd come close, but as someone pointed out early
on, I'd accidently tapped into PyXML which is installed where I was
testing code, but not necessarily where I need it. It may turn out
that the regex way works faster, but falling back on methods I'm
comfortable with doesn't help expand my Python knowledge.

So if anyone can tell me how to get HTMLParser or htmllib to grab a
specific paragraph, and then provide the text in that paragraph in a
clean, markup-free format, I'd appreciate it.


From cain171562 at gmail.com  Wed Jan  9 17:41:10 2008
From: cain171562 at gmail.com (mike)
Date: Wed, 9 Jan 2008 14:41:10 -0800 (PST)
Subject: mysqldb SELECT COUNT reurns 1
References: 
	
Message-ID: <4338fe75-e67d-41ec-a2ad-30c5303c941e@y5g2000hsf.googlegroups.com>

On Dec 27 2007, 5:25 pm, Ian Clark  wrote:
> On 2007-12-27, SMALLp  wrote:
>
> > connectionString = {"host":"localhost", "user":"root",
> > "passwd":"pofuck", "db":"fileshare"}
> > dataTable = "files"
> > conn = mysql.connect(host=connectionString["host"],
> > user=connectionString["user"], passwd=connectionString["passwd"],
> > db=connectionString["db"])
>
> Just to let you know, that last line can be rewritten as:
>
> conn = mysql.connect(**connectionString)
>
> Ian

Try using cursor.fetchall() instead of cursor.fetchone()


From nick at craig-wood.com  Fri Jan 11 07:30:04 2008
From: nick at craig-wood.com (Nick Craig-Wood)
Date: Fri, 11 Jan 2008 06:30:04 -0600
Subject: python recursive function
References: 
	<01c6fa55-3836-4d92-aaf4-02fec7fa529c@l6g2000prm.googlegroups.com>
Message-ID: 

HYRY  wrote:
>  def bears (n):
>      if n==42:
>          return True
>      if n%5==0:
>          if bears(n-42):
>              return True
>      if n%2==0:
>          if bears(n/2):
>              return True
>      if n%3==0 or n%4==0:
>          one = (n%10)
>          two = ((n%100)/10)
>          if one!=0 and two!=0:
>              if bears(n-(one*two)):
>                  return True
>      return False

Almost but you missed a case...

>>> for i in range(100):
...     try:
...         print i, bears(i)
...     except RuntimeError, e:
...         print i, e
...
0 0 maximum recursion depth exceeded
1 False
2 False
3 False
4 False
5 False
6 False
7 False
8 False
9 False
10 10 maximum recursion depth exceeded
11 False
12 12 maximum recursion depth exceeded
113 False
14 False
15 15 maximum recursion depth exceeded
16 16 maximum recursion depth exceeded
17 False
[snip]
89 False
90 90 maximum recursion depth exceeded
91 False
92 False
93 93 maximum recursion depth exceeded
94 False
95 False
96 96 maximum recursion depth exceeded
97 False
98 False
99 99 maximum recursion depth exceeded

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick


From phillip.sitbon at gmail.com  Tue Jan 15 13:58:57 2008
From: phillip.sitbon at gmail.com (Phillip Sitbon)
Date: Tue, 15 Jan 2008 10:58:57 -0800 (PST)
Subject: Python in IIS + WSGI
References: <86d01390-fb1c-4806-a10b-92446c008b10@k2g2000hse.googlegroups.com>
	<728a3b8a-074f-4435-89e3-4cdb095f193a@q39g2000hsf.googlegroups.com>
Message-ID: 

Looks like Sourceforge had a problem with the file upload, causing it
to be empty - I just fixed it.

http://pyisapie.sourceforge.net/

> On Jan 11, 4:37 pm, Phillip Sitbon  wrote:
>
> > Recently (finally) updated the PyISAPIe project. Version 1.0.4
> > includes WSGI support (tested with current Django SVN and Trac 0.10)
> > and a Django-native handler, as well as other examples of using it as
> > a standalone web app.
>
> > Also added some installation/usage docs on the project page.
>
> > Comments/feedback welcome!
>




From henry.baxter at gmail.com  Fri Jan 25 18:19:42 2008
From: henry.baxter at gmail.com (Henry Baxter)
Date: Fri, 25 Jan 2008 15:19:42 -0800
Subject: Index of maximum element in list
In-Reply-To: <479A58F9.4090805@gmx.net>
References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com>
	<8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com>
	<479A58F9.4090805@gmx.net>
Message-ID: <8d04436f0801251519g482a697dn625223b6d46e8f2c@mail.gmail.com>

Thanks Hexamorph and Neal. Somehow I didn't make the connection with using
'index', but I'm all sorted out now :)

On Jan 25, 2008 1:47 PM, Hexamorph  wrote:

> Henry Baxter wrote:
> > Oops, gmail has keyboard shortcuts apparently, to continue:
> >
> > def maxi(l):
> >     m = max(l)
> >     for i, v in enumerate(l):
> >         if m == v:
> >             return i
> >
>
> What's about l.index(max(l)) ?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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

From castironpi at gmail.com  Fri Jan 11 15:22:53 2008
From: castironpi at gmail.com (castironpi at gmail.com)
Date: Fri, 11 Jan 2008 12:22:53 -0800 (PST)
Subject: removeall() in list
Message-ID: 

Any ideas for a thread-safe list.removeall( X ): removing all
occurrences of X within list L, when L might be modified concurrently?

Sincerely,
Aaron


From socyl at 987jk.com.invalid  Tue Jan 29 11:39:02 2008
From: socyl at 987jk.com.invalid (kj)
Date: Tue, 29 Jan 2008 16:39:02 +0000 (UTC)
Subject: Python noob SOS (any [former?] Perlheads out there?)
Message-ID: 



For many months now I've been trying to learn Python, but I guess
I'm too old a dog trying to learn new tricks...  For better or
worse, I'm so used to Perl when it comes to scripting, that I'm
just having a very hard time getting a hang of "The Python Way."

It's not the Python syntax that I'm having problems with, but rather
with larger scale issues such as the structuring of packages,
techniques for code reuse, test suites, the structure of
distributions,...  Python and Perl seem to come from different
galaxies altogether...

Be that as it may, the activation barrier to using Python for my
scripting remains too high.

I'd written a Perl module to facilitate the writing of scripts.
It contained all my boilerplate code for parsing and validating
command-line options, generating of accessor functions for these
options, printing of the help message and of the full documentation,
testing, etc.

Of course, for Python now I don't have any of this, so I must write
it all from scratch, and the thing is *I don't even know where to
begin*!  And meanwhile works needs to get done, projects finished,
etc.  So naturally I revert to Perl, yadda-yadda-yadda, and the
Python project gets pushed back another week...

In a way it's the usual story with learning a new language, but
I've taught myself new languages before.  (After all, there was a
time when I didn't know Perl.)  It's harder this time, somehow...

Anyway, pardon the ramble.

Is there any good reading (to ease the transition) for Perl
programmers trying to learn Python?

Thanks!

kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.


From robleachza at gmail.com  Thu Jan 17 11:35:24 2008
From: robleachza at gmail.com (robleachza at gmail.com)
Date: Thu, 17 Jan 2008 08:35:24 -0800 (PST)
Subject: next line (data parsing)
References: 
	<13otnvakq8kc6a3@corp.supernews.com>
	
	
Message-ID: <6df36bbb-61a2-47b0-8df6-a7e37d782923@k2g2000hse.googlegroups.com>

I'm very appreciative for the comments posted. Thanks to each of you.
All good stuff.
Cheers,
-Rob


On Jan 16, 9:50 pm, George Sakkis  wrote:
> On Jan 17, 12:42 am, George Sakkis  wrote:
>
>
>
> > On Jan 17, 12:01 am, Scott David Daniels 
> > wrote:
>
> > > robleac... at gmail.com wrote:
> > > > Hi there,
> > > > I'm struggling to find a sensible way to process a large chuck of
> > > > data--line by line, but also having the ability to move to subsequent
> > > > 'next' lines within a for loop. I was hoping someone would be willing
> > > > to share some insights to help point me in the right direction. This
> > > > is not a file, so any file modules or methods available for files
> > > > parsing wouldn't apply.
>
> > > > I can iterate over each line by setting a for loop on the data object;
> > > > no problem. But basically my intension is to locate the line "Schedule
> > > > HOST" and progressively move on to the 'next' line, parsing out the
> > > > pieces I care about, until I then hit "Total", then I resume to the
> > > > start of the for loop which locates the next "Schedule HOST".
>
> > > if you can do:
>
> > >      for line in whatever:
> > >          ...
>
> > > then you can do:
>
> > >      source = iter(whatever)
> > >      for intro in source:
> > >          if intro.startswith('Schedule '):
> > >              for line in source:
> > >                  if line.startswith('Total'):
> > >                      break
> > >                  process(intro, line)
>
> > > --Scott David Daniels
> > > Scott.Dani... at Acm.Org
>
> > Or if you use this pattern often, you may extract it to a general
> > grouping function such ashttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877:
>
> Sorry, google groups fscked up with the auto linewrapping (is there a
> way to increase the line length?); here it is again:
>
> import re
>
> for line in iterblocks(source,
>         start = lambda line: line.startswith('Schedule HOST'),
>         end = lambda line: re.search(r'^\s*Total',line),
>         skip_delim = False):
>     process(line)
>
> George


From tezlo at gmx.net  Thu Jan 10 09:27:17 2008
From: tezlo at gmx.net (tezlo)
Date: Thu, 10 Jan 2008 15:27:17 +0100
Subject: Embedding python code into text document question.
References: 
Message-ID: <20080110152717.9fdd6d0f.tezlo@gmx.net>

Thomas Troeger  wrote:
> I've written a program that parses a string or file for embedded
> python commands, executes them and fills in the returned value.
> ...
> I've tried several solutions using eval, execfile or compile, but
> none of those would solve my problem. Does anyone have a solution
> that works? Any suggestions? Any help will be appreciated :)

Hi,
first, to quote the manual [1]
> Be aware that the return and yield statements may not be used
> outside of function definitions even within the context of code
> passed to the exec statement.

Once you get rid of those return statements, the first two
substitutions could simpy be eval'ed. Conditions and loops can be
exec'ed, but you need to capture the output somehow. You could
replace sys.stdout with your own StringIO before you exec, and
use 'print' instead of 'return' in your templates.

Two basic approaches: you eval every substitution by itself [2], or you
parse the whole template into one big python chunk, and exec that [3].

[1] http://docs.python.org/ref/exec.html
[2] http://blog.ianbicking.org/templating-via-dict-wrappers.html
[3] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/464766


From paddy3118 at googlemail.com  Sun Jan 27 20:17:56 2008
From: paddy3118 at googlemail.com (Paddy)
Date: Sun, 27 Jan 2008 17:17:56 -0800 (PST)
Subject: Python Standardization: Wikipedia entry
References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com>
	
Message-ID: <0c9a1a2d-68a9-4f9c-b140-8823950a5ba1@k2g2000hse.googlegroups.com>

On Jan 28, 1:05 am, ajaksu  wrote:
> On Jan 27, 10:32 pm, Paddy  wrote:
>
> > I would value the opinion of fellow Pythoneers who have also
> > contributed to Wikipedia, on the issue of "Is Python Standardized".
> > Specifically in the context of this table:
> >  http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Gene...
> >   (Comparison of programming languages)
> > And this entry in the talk page
> >  http://en.wikipedia.org/wiki/Talk:Comparison_of_programming_languages...
> >   (Talk:Comparison of programming languages#Standardized Python?)
>
> > - Thanks.
>
> Hmmm. Seems to me that "Is X Standardized" in the given context means
> having a formal, published standard issued by some Standards
> organization. While you can discuss the meaning of some so-called
> standards (like W3C's 'recommendations', RFCs, etc.), Python, IMHO,
> doesn't fit the label. There is no "Standard" to reference that is
> implementation, documentation and core-dev's opinion independent to a
> reasonable degree.
>
> I guess MilesAgain gives the best arguments regarding this issue.
>
> Not-that-my-opinion-should-have-any-weight-ly y'rs
> Daniel

Thanks Daniel. I am very close to the issue and would like to step
back and c.l.p'ers opinion.


From bronger at physik.rwth-aachen.de  Wed Jan  2 02:01:13 2008
From: bronger at physik.rwth-aachen.de (Torsten Bronger)
Date: Wed, 02 Jan 2008 08:01:13 +0100
Subject: Tab indentions on different platforms?
References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com>
	
	<13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au>
	
	<13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au>
	<13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au>
	<87bq85rp2d.fsf@physik.rwth-aachen.de>
	<87abnoc13h.fsf@benfinney.id.au>
Message-ID: <87odc4hft2.fsf@physik.rwth-aachen.de>

Hall?chen!

Ben Finney writes:

> Torsten Bronger  writes:
>
>> [...] the width of a tab is nowhere defined. It really is a
>> matter of the editor's settings.
>
> RFC 678 "Standard File Formats"
> :
>
>          Horizontal Tab  
>
> [...]

As far as I can see, this excerpt of a net standard has been neither
normative nor influential on the behaviour of text editors.

>> I, for example, dislike too wide indenting. I use four columns in
>> Python and two in Delphi. However, there are Python projects
>> using eight spaces for each indentation level.
>
> How many columns to indent source code is an orthogonal question
> to how wide an ASCII TAB (U+0009) should be rendered. [...]

I don't know what you want to say with this.  Obviousy, is is
impossible to indent four columns with 8-columns tabs.  Anyway, my
sentence was supposed just to lead to the following:

>> If all Python code used tabs, everybody could use their own
>> preferences, for both reading and writing code, and
>> interoperability would be maintained nevertheless.
>
> Interoperability isn't the only criterion though. On the contrary,
> source code is primarily for reading by programmers, and only
> incidentally for reading by the compiler.

Well, I, the programmer, want code snippets from different versions
fit together as seemlessly as possible, and I want to use my editor
settings for every piece of Python code that I load into it.

Tsch?,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
                                      Jabber ID: bronger at jabber.org
               (See http://ime.webhop.org for further contact info.)


From justin.mailinglists at gmail.com  Wed Jan  2 21:56:25 2008
From: justin.mailinglists at gmail.com (Justin Ezequiel)
Date: Wed, 2 Jan 2008 18:56:25 -0800 (PST)
Subject: Python CGI - Presenting a zip file to user
References: 
Message-ID: 

On Jan 3, 7:50 am, jwwest  wrote:
> Hi all,
>
> I'm working on a cgi script that zips up files and presents the zip
> file to the user for download. It works fine except for the fact that
> I have to overwrite the file using the same filename because I'm
> unable to delete it after it's downloaded. The reason for this is
> because after sending "Location: urlofzipfile" the script stops
> processing and I can't call a file operation to delete the file. Thus
> I constantly have a tmp.zip file which contains the previously
> requested files.
>
> Can anyone think of a way around this? Is there a better way to create
> the zip file and present it for download "on-the-fly" than editing the
> Location header? I thought about using Content-Type, but was unable to
> think of a way to stream the file out.
>
> Any help is appreciated, much thanks!
>
> - James

import sys, cgi, zipfile, os
from StringIO import StringIO

try: # Windows only
    import msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
except ImportError: pass

HEADERS = '\r\n'.join(
    [
        "Content-type: %s;",
        "Content-Disposition: attachment; filename=%s",
        "Content-Title: %s",
        "Content-Length: %i",
        "\r\n", # empty line to end headers
        ]
    )

if __name__ == '__main__':
    os.chdir(r'C:\Documents and Settings\Justin Ezequiel\Desktop')
    files = [
        '4412_ADS_or_SQL_Server.pdf',
        'Script1.py',
        'html_files.zip',
        'New2.html',
        ]
    b = StringIO()
    z = zipfile.ZipFile(b, 'w', zipfile.ZIP_DEFLATED)
    for n in files:
        z.write(n, n)

    z.close()

    length = b.tell()
    b.seek(0)
    sys.stdout.write(
        HEADERS % ('application/zip', 'test.zip', 'test.zip', length)
        )
    sys.stdout.write(b.read())
    b.close()



From steve at REMOVE-THIS-cybersource.com.au  Fri Jan 25 07:43:20 2008
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: Fri, 25 Jan 2008 12:43:20 -0000
Subject: inode number in windows XP
References: <3331a284-b786-42d5-bbe8-a764d59af920@c4g2000hsg.googlegroups.com>
Message-ID: <13pjmb84dt1m4fc@corp.supernews.com>

On Fri, 25 Jan 2008 04:28:43 -0800, asit wrote:

> why this program shows ambiguous behavior ??


You should read this page, it will help you solve your problem:

http://catb.org/~esr/faqs/smart-questions.html



-- 
Steven


From lasses_weil at klapptsowieso.net  Tue Jan 29 13:46:37 2008
From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger)
Date: Tue, 29 Jan 2008 19:46:37 +0100
Subject: Python noob SOS (any [former?] Perlheads out there?)
In-Reply-To: 
References: 
Message-ID: <479f7492$0$27193$9b4e6d93@newsspool1.arcor-online.net>

kj wrote:
> Is there any good reading (to ease the transition) for Perl
> programmers trying to learn Python?
> 

www.diveintopython.org

While it is a bit dated by now (Python 2.2), that thing worked wonders 
for me. Shows you Python in action and presents a fair amount of its 
philosophy along the way.

Maybe(!) that helps a bit.

/W


From arnodel at googlemail.com  Wed Jan 23 13:12:22 2008
From: arnodel at googlemail.com (Arnaud Delobelle)
Date: Wed, 23 Jan 2008 10:12:22 -0800 (PST)
Subject: Just for fun: Countdown numbers game solver
References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com>
	<5aab67ce-6e57-438d-ae24-017177a3bb56@21g2000hsj.googlegroups.com> 
	
	<127ba57c-6555-4c22-aee3-dcc28eba666a@i7g2000prf.googlegroups.com>
	
Message-ID: <457550e3-f5e1-4fad-b553-c3e5e400dbb1@u10g2000prn.googlegroups.com>

On Jan 23, 3:45?pm, Terry Jones  wrote:
> Hi Arnaud and Dan

Hi Terry

> >>>>> "Arnaud" == Arnaud Delobelle  writes:
> >> What was wrong with the very fast(?) code you sent earlier?
>
> Arnaud> I thought it was a bit convoluted, wanted to try something I
> Arnaud> thought had more potential. ?I think the problem with the second
> Arnaud> one is that I repeat the same 'fold' too many times.
>
> and later:
>
> Arnaud> Yes, I've been doing this by writing an 'action' (see my code) that
> Arnaud> takes note of all reached results.
>
> These are both comments about pruning, if I understand you. In the first
> you weren't pruning enough and in the second you're planning to prune more.

Yes I think the first one is about pruning, I couldn't think of the
english word.

> I'm giving up thinking about this problem because I've realized that the
> pruning solution is fundamentally subjective. I.e., whether or not you
> consider two solutions to be the "same" depends on how hard you're willing
> to think about them (and argue that they're the same), or how smart you
> are.

FWIW, I have a clear idea of what the space of solutions is, and which
solutions I consider to be equivalent.  I'll explain it below.  I'm
not saying it's the right model, but it's the one within which I'm
thinking.

> I have a new version that does some things nicely, but in trying to do
> efficient pruning, I've realized that you can't satisfy everyone.
>
> Some examples for the problem with target 253, numbers = 100, 9, 7, 6, 3, 1
>
> Firstly, there are nice solutions that go way negative, like:
>
> ? 1 7 6 3 9 sub mul mul sub ? or ? 1 - 7 * 6 * (3 - 9)

I think it's best to forbid negatives.  Solutions always be written
without any negative intermediate answer.  E.g. 1-7*6*(3-9) can be
done as 1+7*6*(9-3).

>
> Here's a pruning example. Are these the "same"?
>
> ? 1 3 7 100 9 sub sub mul sub ?or ?1 - 3 * (7 - 100 - 9)

rather 1 - 3*(7 - (100 - 9))

> ? 1 3 7 9 100 sub add mul sub ?or ?1 - 3 * (7 - 9 - 100)

rather 1 - 3*(7 + (9 - 100))

Not allowing negatives means these are
   3*(100 - 9 - 7) + 1
or 3*(100 - (9 + 7)) + 1
or 3*(100 - 7 - 9) + 1

I don't consider these to be equivalent, because their equivalence
depends on understanding the meaning of subtraction and addition.
(I've also applied the 'big then small' rule explained below)

>
> I think many people would argue that that's really the "same" and that one
> of the two should not appear in the output. The same goes for your earlier
> example for 406. It's 4 * 100 + 2 x 3, and 2 x 3 + 100 * 4, and so on.

There is a simple rule that goes a long way: "big then small", i.e.
only allow a  b when a > b.
So the above is canonically written as 100*4 + 2*3.

>
> My latest program does all these prunings.
>
> But you can argue that you should push even further into eliminating things
> that are the same. You could probably make a pretty fast program that
> stores globally all the states it has passed through (what's on the stack,
> what numbers are yet to be used, what's the proposed op) and never does
> them again. But if you push that, you'll wind up saying that any two
> solutions that look like this:
>
> ? ....... 1 add
>
> e.g.
>
> ? 6 9 3 sub mul 7 mul 1 add ? or ?6 * (9 - 3) * 7 + 1
> ? 7 6 mul 9 3 sub mul 1 add ? or ?7 * 6 * (9 - 3) + 1
>
> are the same.

I honestly think this is outside the scope of this problem, which must
remain simple.  I'm not trying to convince you of anything, but I'll
just explain briefly what solutions I don't want to repeat.

I see a solution as a full ordered binary tree.  Each node has a
weight (which is the result of the calculation it represents) and the
left child of a node has to be at least as heavy as the right child.
Each parent node can be labeled + - * or /.
If a node x has two children y and z and is labeled , let me write
    x = (y  z)

so     6 9 3 sub mul 7 mul 1 add -> (((6 * (9 - 3)) * 7) + 1)
and    7 6 mul 9 3 sub mul 1 add -> (((7 * 6) * (9 - 3)) + 1)

are two distinct solutions according to my criterion.

But
       9 3 sub 6 mul 7 mul 1 add -> ((((9 - 3) * 6) * 7) + 1)

is not a solution because 9-3 < 6

To be perfectly honest (and expose my approach a little to your
argument) I added a three additional rules:

* Don't allow x - x
* Don't allow x * 1
* Don't allow x / 1

My aim was find and efficient way to generate all solutions exactly
once if there is no repeat in the list of starting numbers.  This is a
clearly defined problem and I wanted to find a nice way of solving
it.  I realised that the folding method was redundant in that respect
and this is what I wanted to fix (I have a fix, I think, but the
'proof' of it is only in my head and might be flawed).

If there are repeats in the list of starting numbers, I don't worry
about repeating solutions.

> If anyone wants the stack simulation code, send me an email.

I'd like to see it :)

--
Arnaud




From ickyelf at gmail.com  Sat Jan 19 14:15:21 2008
From: ickyelf at gmail.com (David Delony)
Date: Sat, 19 Jan 2008 19:15:21 GMT
Subject: Gui front-end to version control program
Message-ID: 

I spoke with Eric S. Raymond at a Linux user's group meeting a few days ago 
about the need for version control for end users.
I thought that Python might be a good candidate for this. 

Luckily, Guido was there as well. I talked this over with him and he
suggested using Google Documents sinceI usually collborate on text documents.

I want something that can work with any file, as Subversion does. I can't 
think of any 
GUI wrappers written in Python off the top of my head. I would like to use one
as a model and get my feet wet by contributing to it. I don't feel proficient
enough to lead a project yet. 


-- 
There's no place like ~!


From info at telenet.be  Tue Jan 29 21:00:39 2008
From: info at telenet.be (info at telenet.be)
Date: Wed, 30 Jan 2008 02:00:39 GMT
Subject: Telenet nieuwsgroepen mededeling: nieuwsserver adres
	aanpassen/Attention: modification de l'adresse du serveur de newsgroup
Message-ID: 

Beste klant,

Telenet heeft een migratie gedaan van haar nieuwsservers. 

Wat betekent dit concreet voor jou als gebruiker?

Er verandert niets aan de service, maar om verder gebruik te maken van de
Telenet nieuwsgroepen service moet je bij de instellingen van je nieuwslezer
het adres van de nieuwsserver veranderen van news.telenet.be of
newsbin.telenet.be in newsgroups.telenet.be. Verder dien je de authenticatie
op deze nieuwsserver uit te schakelen.

Met vriendelijke groeten,

Het Telenet team

----------------------------------------------------------------------------------------------------------
 
Cher client,
 
Telenet a effectue une migration de ses serveurs de newsgroup.

Pour continuer a utiliser les newsgroups de Telenet, modifiez dans la
configuration de lecteur de nouvelles l'adresse du serveur de newsgroup:
newsgroups.telenet.be a la place de news.telenet.be ou newsbin.telenet.be.
Ceci ne necessite pas que vous vous identifiez pour acceder a ce serveur de
newsgroup.
 
Cordialement,

L'equipe Telenet



From eliss.carmine at gmail.com  Mon Jan 14 22:48:34 2008
From: eliss.carmine at gmail.com (eliss)
Date: Mon, 14 Jan 2008 19:48:34 -0800 (PST)
Subject: reliable whois in python
Message-ID: 

Hi everyone,

I'm trying to write a python script to whois a few domains twice a day
so I get notified when they become available. I did it 2 ways, but
neither way is very reliable, so I'm asking here.

1) I tried just calling "whois %s" using popen, but I found that once
every few weeks, I get errors like:
connect: No route to host OR
fgets: Connection reset by peer
I don't think it's a connectivity issue because looking up the other
domains that day works, and just one domain will give an error. So
it's probably more like a networking issue? I don't know...

2) I tried using sockets to connect to the whois port of
whois.internic.net and then read the info, which works a little better
than 1). However, sometimes this is not reliable too and I get errors.

Does anyone have any ideas how I can do this better?

Thanks,

eliss


From bblais at bryant.edu  Tue Jan 29 17:55:18 2008
From: bblais at bryant.edu (Brian Blais)
Date: Tue, 29 Jan 2008 17:55:18 -0500
Subject: load movie frames in python?
Message-ID: <4697A1F5-6273-477D-8A6C-3BD34786CD64@bryant.edu>

Hello,

Is there a way to read frames of a movie in python?  Ideally,  
something as simple as:

for frame in movie('mymovie.mov'):
     pass


where frame is either a 2-D list, or a numpy array?  The movie format  
can be anything, because I can probably convert things, but most  
convenient would be avi, mov, and flv (for youtube videos).


		thanks,


			Brian Blais

-- 
Brian Blais
bblais at bryant.edu
http://web.bryant.edu/~bblais



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

From Russ.Paielli at gmail.com  Fri Jan  4 02:37:42 2008
From: Russ.Paielli at gmail.com (Russ P.)
Date: Thu, 3 Jan 2008 23:37:42 -0800 (PST)
Subject: C++ equivalent of comp.lang.python?
References: <60597295-1493-493c-969c-a14dd7da98a3@s19g2000prg.googlegroups.com>
Message-ID: <005550c8-00f6-42b2-b804-2d2baea0b60e@s8g2000prg.googlegroups.com>

On Jan 3, 9:39 am, brzr... at gmail.com wrote:
> Hopefully this isn't too OT.
>
> One thing I like about comp.lang.python is the breadth of topics
> discussed here.  People can ask about Python installation and
> configuration issues on specific platforms, compare third party
> libraries, ask for book recommendations, and discuss current Python
> projects.  Lurking here has greatly increased my understanding of
> Python over the last year or so.
>
> I also do a lot of C++ development, but I've never found a similar
> discussion group for that language.  comp.lang.c++ isn't what I'm
> looking for.  I find it hard to get practical advice on that group
> because its focus is so narrow.  I frequently see posters there
> redirect people to one of the OS-specific C++ groups, but most of my
> projects are cross-platform, so hanging out on one of those doesn't
> make sense either.  As an example, I was recently trying to get
> information about writing cross-platform code for dynamic linking, but
> I couldn't find anywhere appropriate to ask about it.
>
> For those of you who work in C++, where do you go to discuss it
> online?  I'm interested in any newsgroups, mailing lists, or web
> boards you can recommend.
>
> Thanks,
> Casey

Well, if the good folks at comp.lang.c++ can't even direct you to an
appropriate forum on C++, then I doubt the folks at comp.lang.python
can. I suggest you abandon C++ and try Python, Java, or Ada.


From MartinRinehart at gmail.com  Wed Jan  9 07:13:15 2008
From: MartinRinehart at gmail.com (MartinRinehart at gmail.com)
Date: Wed, 9 Jan 2008 04:13:15 -0800 (PST)
Subject: I'm searching for Python style guidelines
References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com>
	<1d895d6d-a649-439e-8223-0ae7d3a4eb40@l6g2000prm.googlegroups.com> 
	 
	<4fb7129f-3887-4e3b-a827-3255344047f3@c23g2000hsa.googlegroups.com> 
	
Message-ID: 



Matthew Woodcraft wrote:
> I think [the olpc guidlines are] mostly PEP 8, with some notes added.

Took a good look. You are absolutely correct.

PEP 8 is basically word processing text stuck between 
 and 
tags. OLPC is Wiki HTML. Good example of how the latter is a lot bigger than the former, with little extra content. From john.m.roach at gmail.com Wed Jan 9 11:48:46 2008 From: john.m.roach at gmail.com (John) Date: Wed, 9 Jan 2008 08:48:46 -0800 (PST) Subject: printing dots in simple program while waiting Message-ID: Ok, so this should be a really simple thing to do, but I haven't been able to get it on the first few tries and couldn't find anything after searching a bit. what i want to do is print a 'waiting' statement while a script is working-- the multithreading aspect isn't an issue, the printing on the same line is. i want to print something like: (1sec) working... (2sec) working.... (3sec) working..... where the 'working' line isn't being printed each second, but the dots are being added with time. something like: import time s = '.' print 'working' while True: print s time.sleep(1) however, this doesn't work since it prints: working . . . any suggestions? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 06:45:59 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 12:45:59 +0100 Subject: anti-spam policy for c.l.py? In-Reply-To: <08ed32c4-6230-4b14-9c31-4b94e0231cf2@c4g2000hsg.googlegroups.com> References: <08ed32c4-6230-4b14-9c31-4b94e0231cf2@c4g2000hsg.googlegroups.com> Message-ID: <478dee4e$0$28424$426a34cc@news.free.fr> _wolf a ?crit : > this list has been receiving increasing amounts of nasty OT spam > messages for some time. are there any plans to prevent such messages > from appearing on the list or to purge them retrospectively? Apart from checking posts headers and complaining about the relevant ISPs, there's not much you can do AFAIK. This is usenet, not a mailing-list. From gagsl-py2 at yahoo.com.ar Fri Jan 25 12:50:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 Jan 2008 09:50:22 -0800 (PST) Subject: inode number in windows XP References: <3331a284-b786-42d5-bbe8-a764d59af920@c4g2000hsg.googlegroups.com> Message-ID: On 25 ene, 10:28, asit wrote: > why this program shows ambiguous behavior ?? > > st=os.stat(file_name) > print "file size", "=>",st[stat.ST_SIZE] > print "inode number", "=>",st[stat.ST_INO] > print "device inode resides on", "=>",st[stat.ST_DEV] > print "number of links to this inode", "=>",st[stat.ST_NLINK] > > i ran this program in Winows XP SP2 in python 2.5. Using my recently repaired crystal ball, I see that you don't get what you expect for some of those fields. All files sharing the same inode, by example. The usual file systems used by Windows aren't built around the inode concept, they're different, so there is no "inode number" to report, among other things. From http://docs.python.org/lib/os-file-dir.html "On Windows, some items are filled with dummy values". Don't rely on anything but st_mode, st_size, and st_[cma]time, and perhaps a few more for fstat. -- Gabriel Genellina From asmodai at in-nomine.org Tue Jan 8 03:58:34 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 09:58:34 +0100 Subject: Strip lines from files In-Reply-To: <455957.93301.qm@web57611.mail.re1.yahoo.com> References: <455957.93301.qm@web57611.mail.re1.yahoo.com> Message-ID: <20080108085834.GG75977@nexus.in-nomine.org> -On [20080108 09:40], Francesco Pietra (chiendarret at yahoo.com) wrote: >A variant need has now emerged, to perform the same task from a very long >series of shorter files trp.pdb.1, trp.pdb.2 ,..... Could you see how to adapt >the above script to the new need? Look at sys.argv and pass the list of files to your script as a wildcard: ./myscript.py trp.pdb.* And iterate over every argv you have to strip the WAT. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ The wisdom of the wise, and the experience of ages, may be preserved by quotations... From fredrik at pythonware.com Fri Jan 11 07:14:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jan 2008 13:14:24 +0100 Subject: import gzip error (please help) In-Reply-To: References: Message-ID: syahreza.octadian wrote: > Please help, i have error message when i import gzip module. The error > like this below: > > bash-3.00$ python > Python 2.5 (r25:51908, Sep 20 2006, 03:46:40) > [GCC 3.4.6] on sunos5 > Type "help", "copyright", "credits" or "license" for more information. >>>> import gzip > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python2.5/gzip.py", line 9, in > import zlib > ImportError: ld.so.1: python: fatal: relocation error: file /usr/local/ > lib/python2.5/lib-dynload/zlib.so: symbol inflateCopy: referenced > symbol not found the core zlib library (libz.so) isn't installed on your machine. From lists at cheimes.de Thu Jan 24 09:28:44 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 24 Jan 2008 15:28:44 +0100 Subject: When is min(a, b) != min(b, a)? In-Reply-To: References: Message-ID: Antoon Pardon wrote: > That doesn't follow. The problem is not that x < nan returns False > because that is correct since x isn't smaller than nan. The problem > is cmp(x, nan) returning 1, because that indicates that x is greater > than nan and that isn't true. Please report the problem. cmp(), min() and max() don't treat NaNs right. I don't think that x < nan == False is the correct answer, too. But I've to check the IEEE 754 specs. IMHO < nan and > nan should raise an exception. Christian From lepto.python at gmail.com Sun Jan 6 21:50:01 2008 From: lepto.python at gmail.com (Oyster) Date: Sun, 6 Jan 2008 18:50:01 -0800 (PST) Subject: Why python says "unexpected parameter 'mini.py'" for my code? References: Message-ID: <6bbf668a-2713-4f65-8e89-2d51a5accc16@e25g2000prg.googlegroups.com> you need wx-c.so from wxnet.sourceforge.net on linux My source uses wx-c.dll, because I am in ms win2k On Jan 4, 10:30 pm, Nick Craig-Wood wrote: > oyster wrote: > > The following is my pure-python wxwidgets test. > > It is hardly pure python since it depends on wxWindows and ctypes... > > > It runs and give a frame, but soon python comes up to say > > "unexpected parameter > > 'mini.py'" and I have to close it. > > I cannot find the reason. Can somebody give me a hint to let it work > > well? Thanks > > I tried it but it doesn't work at all on linux. > > I suggest you use wxPython and stop re-inventing the wheel! > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick From python at rolfvandekrol.nl Tue Jan 22 08:02:01 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Tue, 22 Jan 2008 14:02:01 +0100 Subject: stdin, stdout, redmon In-Reply-To: References: <4794a5e3$0$9014$426a74cc@news.free.fr> <4794ab22$0$19179$426a74cc@news.free.fr> <4795ba80$0$17176$426a74cc@news.free.fr> Message-ID: <4795E949.6090508@rolfvandekrol.nl> Well, that's at least weird. I did test my code with Python 2.5 on Win XP, using the command prompt. But testing it with IDLE gives exactly the same error Bernard has. So apparently STDIN can't be accessed with IDLE. Rolf John Machin wrote: > > Excuse me, gentlemen, may I be your referee *before* you resort to > pistols at dawn? > > ===== IDLE ===== > IDLE 1.2.1 > >>>> import sys >>>> sys.stdin.readlines >>>> > > Traceback (most recent call last): > File "", line 1, in > sys.stdin.readlines > AttributeError: readlines > > > ===== Command Prompt ===== > C:\junk>python > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>> import sys >>>> sys.stdin.readlines >>>> > > > > HTH, > John > From arnodel at googlemail.com Tue Jan 1 04:32:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 1 Jan 2008 01:32:18 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <6aba9463-f0ea-43a2-b8de-9c7026c4d14e@e4g2000hsg.googlegroups.com> <75ea72e9-f69f-4b3a-98fe-ffc364fa7543@l6g2000prm.googlegroups.com> Message-ID: <8552dc15-0b82-4f5c-a44c-8f5c4b72f239@e4g2000hsg.googlegroups.com> On Jan 1, 5:26?am, NickC wrote: > On Jan 1, 3:22 am, Arnaud Delobelle wrote: > > > On Dec 31, 10:58 am, Odalrick wrote: > > > > I'm surprised noone has said anything about the why of default > > > mutables. I think it is becasue it isn't easy to do it an other way. > > > [...] > > > There is an easy enough way: evaluate default values when the function > > is called rather than when it is defined. ?This behaviour comes with > > its own caveats as well I imagine, and it's not 'as easy' to implement > > as the current one. > > As Odalrick notes, there is no way to give different calls to a > function their own copies of mutable default arguments without re- > evaluating the defaults every time the function is called. The > horrendous performance implications mean that that simply isn't going > to happen. So the status quo, where the defaults are calculated once > when the function is defined and the result cached in the function > object is unlikely to change. I'm in no way advocating a change, in fact I wouldn't like things to change. I was just saying that it was not difficult (technically) to alter the behaviour, but that this change wouldn't be desirable because it would make code more difficult to reason on. OTOH a very common idiom in python is def foo(x, y, z=None): if z is None: z = ['a', 'mutable', 'object'] # stuff that foo does This the current way to say "I want the default value of z to be reevaluated each time it is used". I use this much more often than def bar(x, y, z=ExpensiveImmutableCreation()) So I'm not so convinced with the performance argument at face value (though it's probably pertinent:) > > What's good about the current behaviour is that it is easy to reason > > with (once you know what happens), even though you almost have to get > > bitten once. ?But using this to have static variable is extremely ugly > > IMHO. > > The only thing it doesn't give you is a static variable that isn't > visible to the caller. Py3k's keyword-only arguments (PEP 3102) will > make those cases a little tidier, since it won't be possible to > accidentally replace the static variables by providing too many > positional arguments. I was always a bit puzzled by this PEP. If this is one of the underlying reasons for it, then I am even more puzzled. > I believe the suggestion of permitting static variables after the ** > entry in a function's parameter list was raised during the PEP 3102 > discussions, but never gained much traction over a '_cache={}' keyword- > only argument approach (and the latter has the distinct advantage of > being *much* easier to test, since you can override the cache from the > test code to ensure it is being handled correctly). Well I'm glad that didn't go through, argument lists in function definitions are complicated enough already! -- Arnaud From kirby.urner at gmail.com Wed Jan 9 18:05:25 2008 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: Wed, 9 Jan 2008 15:05:25 -0800 (PST) Subject: Collecting Rich Data Structures for students References: <8b4e7954-b666-4515-9ae2-821d979ebd7f@m34g2000hsf.googlegroups.com> Message-ID: On Jan 9, 8:15 am, Paddy wrote: > On Jan 9, 6:52 am, Paddy wrote: > > > > > On Jan 9, 2:19 am, "kirby.ur... at gmail.com" > > wrote: > > > > Greetings Pythoneers -- > > > > Some of us over on edu-sig, one of the community actives, > > > have been brainstorming around this Rich Data Structures > > > idea, by which we mean Python data structures already > > > populated with non-trivial data about various topics such > > > as: periodic table (proton, neutron counts); Monty Python > > > skit titles; some set of cities (lat, long coordinates); types > > > of sushi. > > > > Obviously some of these require levels of nesting, say > > > lists within dictionaries, more depth of required. > > > > Our motivation in collecting these repositories is to give > > > students of Python more immediate access to meaningful > > > data, not just meaningful programs. Sometimes all it takes > > > to win converts, to computers in general, is to demonstrate > > > their capacity to handle gobs of data adroitly. Too often, > > > a textbook will only provide trivial examples, which in the > > > print medium is all that makes sense. > > > > Some have offered XML repositories, which I can well > > > understand, but in this case we're looking specifically for > > > legal Python modules (py files), although they don't have > > > to be Latin-1 (e.g. the sushi types file might not have a > > > lot of romanji). > > > > If you have any examples you'd like to email me about, > > > kirby.ur... at gmail.com is a good address. > > > > Here's my little contribution to the mix:http://www.4dsolutions.net/ocn/python/gis.py > > > > Kirby Urner > > > 4D Solutions > > > Silicon Forest > > > Oregon > > > I would think there was more data out there formatted as Lisp S- > > expressions than Python data-structures. > > Wouldn't it be better to concentrate on 'wrapping' XML and CSV data- > > sources? > > > - Paddy. > > The more I think on it the more I am against this- data should be > stored in programming language agnostic forms but which are easily > made available to a large range of programming languages. > If the format is easily parsed by AWK then it is usually easy to parse > in a range of programming languages. > > - Paddy. It's OK to be against it, but as many have pointed out, it's often just one value adding step to go from plaintext or XML to something specifically Python. Sometimes we spare the students (whomever they may be) this added step and just hand them a dictionary of lists or whatever. We may not be teaching parsing in this class, but chemistry, and having the info in the Periodic Table in a Python data structure maybe simply be the most relevant place to start. Many lesson plans I've seen or am working on will use these .py data modules. Kirby From fredrik at pythonware.com Sun Jan 20 07:51:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jan 2008 13:51:08 +0100 Subject: Memory errors with imaplib In-Reply-To: <6012daff-0fd3-4835-a9ca-c18d2a2ac53c@v29g2000hsf.googlegroups.com> References: <6012daff-0fd3-4835-a9ca-c18d2a2ac53c@v29g2000hsf.googlegroups.com> Message-ID: Martey wrote: > I am trying to use imaplib to download messages, but I keep getting > memory errors when I try to download a large message (i.e. one with > attachments). Here is my test code (similar to the example in the > imaplib documentation): > /.../ > I am using Mac OS X 10.5 and Python 2.5.1 (downloaded from > python.org). I think it is possible that it is issue1092502>, but the workarounds suggested there do not seem to work > for me. Is this an actual Python bug, or am I doing something wrong? looks like a known bug in imaplib: http://bugs.python.org/issue1389051 "In a worst case scenario, you'll need some 13 gigabytes of virtual memory to read a 15 megabyte message..." From benjamin.zimmerman at gmail.com Fri Jan 25 00:14:22 2008 From: benjamin.zimmerman at gmail.com (benjamin.zimmerman at gmail.com) Date: Thu, 24 Jan 2008 21:14:22 -0800 (PST) Subject: Which is more pythonic? Message-ID: <56518bb9-1d56-47c3-8112-6e0778832c12@v29g2000hsf.googlegroups.com> I have a goal function that returns the fitness of a given solution. I need to wrap that function with a class or a function to keep track of the best solution I encounter. Which of the following would best serve my purpose and be the most pythonic? class Goal: def __init__(self, goal): self.goal = goal self.best = None self.best_score = None def __call__(self, solution): score = self.goal(solution) if self.best is None or score > self.best_score: self.best_score = score self.best = solution return score def save_best_goal(goal): def new_goal(solution): score = goal(solution) if new_goal.best is None or score > new_goal.best_score: new_goal.best = solution new_goal.best_score = score return score new_goal.best = new_goal.best_score = None return new_goal -Ben From gnewsg at gmail.com Sun Jan 13 22:38:47 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 13 Jan 2008 19:38:47 -0800 (PST) Subject: Threaded server Message-ID: Hi, I'm trying to run an asynchronous FTP server I wrote into a thread for being able to run a test suite against it. The code below is the threaded FTP server code I'm using: --- snippet --- class FTPd(threading.Thread): def __init__(self): self.active = False threading.Thread.__init__(self) def start(self, flag=None): assert not self.active self.flag = flag threading.Thread.start(self) def run(self): assert not self.active ftpd = ftpserver.FTPServer(address, ftp_handler) if self.flag: self.flag.set() self.active = True while self.active: ftpd.server_forever(timeout=1, count=1) ftpd.close() def stop(self): assert self.active self.active = False flag = threading.Event() ftpd = FTPd() ftpd.start(flag) flag.wait() # wait for it to start unittest.main() # run the test suite ftpd.stop() --- /snippet --- Sometimes I get a strange error when all the tests have finished, the server is stopped and Python is exiting: ---------------------------------------------------------------------- Ran 50 tests in 1.515s OK Exception exceptions.TypeError: "'NoneType' object is not callable" in > ignored Exception exceptions.TypeError: "'NoneType' object is not callable" in > ignored I sincerely don't know why that happens but it's likely because I'm not using threads properly. My concern is that this could be caused by a sort of race condition (e.g. Python tries to exit when ftpd.close call is not yet completed). I tried to put a lock in the close() method for waiting the run() method to be completed before returning but I didn't solve the problem. Another information, in case it could be useful, is that this seems to happen with Python 2.3 only. By using 2.4 and Python 2.5 I have no problems. In such cases which is the right way for doing things? Using setDaemon(True)? Could someone point me in the right direction? I've always used the asynchronous approach and dealing with threads is a real pain for me. Thanks in advance. -- Giampaolo From DustanGroups at gmail.com Sun Jan 27 18:26:19 2008 From: DustanGroups at gmail.com (Dustan) Date: Sun, 27 Jan 2008 15:26:19 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> Message-ID: <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> On Jan 27, 12:41 pm, Torsten Bronger wrote: > Hall?chen! > > > > Wildemar Wildenburger writes: > > Andr? wrote: > > >> Personally, I like the idea you suggest, with the modification > >> that I would use "." instead of "@", as in > > >> class Server(object): > >> def __init__(self, .host, .port, .protocol, .bufsize, .timeout): > >> pass > > > I like :) > > > However, you can probably cook up a decorator for this (not > > certain, I'm not a decorator Guru), which is not that much worse. > > > Still, I'd support that syntax (and the general idea.). > > Well, you save one or two lines per class. Not enough in my > opinion. Are you referring to the alternate syntax or to the decorator? Either way, you could be saving 4 or 5 or more lines, if you have enough arguments. From arnodel at googlemail.com Thu Jan 31 17:53:54 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 31 Jan 2008 14:53:54 -0800 (PST) Subject: helper function in a class' namespace References: <47a226bb$0$2982$ba620e4c@news.skynet.be> <47a22a17$0$8306$9b622d9e@news.freenet.de> Message-ID: <386f1e82-aaf0-4585-b4fb-ee705aa1681b@v17g2000hsa.googlegroups.com> On Jan 31, 8:05?pm, Stargaming wrote: [...] > > class A(object): > > ? ?def Helper(M) : > > ? ? ?return 'H>'+M > > ? ?def __init__(self,Msg) : > > ? ? ?print Helper(Msg) > > > doesn't work since Python is looking for a global function Helper (why?) > > Because in the scope of the ``__init__`` function, the name ``Helper`` is > not bound. It then jumps out to the global scope. But it is 'Helper' bound in the scope of the *definition* of __init__, hence you *could* write: >>> class A(object): ... def _helper(x): return '<<%s>>' % x ... def __init__(self, msg, _helper=_helper): ... print _helper(msg) ... del _helper ... >>> A('spam') <> <__main__.A object at 0x70170> Confusingly yours, -- Arnaud From CHanemann at cch.com.au Tue Jan 29 18:43:54 2008 From: CHanemann at cch.com.au (Christian Hanemann) Date: Wed, 30 Jan 2008 10:43:54 +1100 Subject: ImageFilter failing for mode = 1 Message-ID: Hello, I'm trying to sharpen some JPEGs after resizing and am being given a valueError as per the below: File "getGraphicDetails.py", line 32, in main enhancer = ImageEnhance.Sharpness(img) File "/usr/local/lib/python2.3/site-packages/PIL/ImageEnhance.py", line 89, in __init__ self.degenerate = image.filter(ImageFilter.SMOOTH) File "/usr/local/lib/python2.3/site-packages/PIL/Image.py", line 786, in filter return self._new(filter.filter(self.im)) File "/usr/local/lib/python2.3/site-packages/PIL/ImageFilter.py", line 55, in filter return apply(image.filter, self.filterargs) ValueError: image has wrong mode Does anyone know if I'm just using an old version of PIL and this has subsequently been addressed or if I'm using it incorrectly. It appears to die on the line: enhancer = ImageEnhance.Sharpness(img) If I put in an: If img.mode = "1": enhancer = ImageEnhance.Sharpness(img.convert("L")) it works fine, but I was wondering if the library should or does work without having to convert. Thankyou -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcroy.olsen at gmail.com Wed Jan 23 10:35:44 2008 From: marcroy.olsen at gmail.com (marcroy.olsen at gmail.com) Date: Wed, 23 Jan 2008 07:35:44 -0800 (PST) Subject: Lxml on mac References: <47975B09.8090705@web.de> Message-ID: On Jan 23, 4:19?pm, Stefan Behnel wrote: > marcroy.ol... at gmail.com wrote: > > What to one do if one what to use lxml(http://codespeak.net/lxml/ > > index.html) on a mac? > > Have you tried installing up-to-date versions of libxml2/libxslt and running > > ? ?easy_install lxml > > ? > > Stefan No not yet. That was my nest step. But do anybody know if there is an easy way to use schema validation in python(on a mac) ? From rupert.thurner at gmail.com Sat Jan 19 09:49:43 2008 From: rupert.thurner at gmail.com (rupert.thurner) Date: Sat, 19 Jan 2008 06:49:43 -0800 (PST) Subject: finding memory leak in edgewall trac 0.11 Message-ID: what would be a good means of finding where the 0.11 version of edgewall trac uses excessive memory. see http://groups.google.com/group/trac-dev/browse_thread/thread/116e519da54f16b for some details, where jonas suggested http://wingolog.org/archives/2007/11/27/reducing-the-footprint-of-python-applications as reading. tiran already gave some hints on http://bugs.python.org/issue1871, but also suggested to ask the general mailing list: Do you have classes with a __del__ method which may create reference cycles? The GC can't break cycles when a __del__ method is involved. Are you keeping references to tracebacks, exception objects (except Exception, err) or frames (sys._getframe()) many thanks, rupert. From deets at nospam.web.de Tue Jan 15 08:31:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 Jan 2008 14:31:39 +0100 Subject: "env" parameter to "popen" won't accept Unicode on Windows -minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net><5v2cudF1k5a1oU1@mid.individual.net><478c551a$0$36354$742ec2ed@news.sonic.net> <5v3dq9F1k2577U1@mid.uni-berlin.de> Message-ID: <5v3qtsF1khn11U1@mid.uni-berlin.de> Brian Smith wrote: > Diez B. Roggisch wrote: >> Sure thing, python will just magically convert unicode to the >> encoding the program YOU invoke will expect. Right after we >> introduced the >> >> solve_my_problem() >> >> built-in-function. Any other wishes? > > There's no reason to be rude. If you'd know John, you'd know there is. > Anyway, at least on Windows it makes perfect sense for people to expect > Unicode to be handled automatically. popen() knows that it is running on > Windows, and it knows what encoding Windows needs for its environment > (it's either UCS2 or UTF-16 for most Windows APIs). At least when it > receives a unicode string, it has enough information to apply the > conversion automatically, and doing so saves the caller from having to > figure out what exact encoding is to be used. For once, the distinction between windows and other platforms is debatable. I admit that subprocess contains already quite a few platform specific aspects, but it's purpose is to abstract these away as much as possible. However, I'm not sure that just because there are wide-char windows apis available automatically means that using UCS2/UTF-16 would succeed. A look into the python sources (PC/_subprocess.c) reveals that someone already thought about this, but it seems that just setting a CREATE_UNICODE_ENVIRONMENT in the CreateProcess-function should have been easy enough to do it if there weren't any troubles to expect. Additionally, passing unicode to env would also imply that os.environ should yield unicode as well. Not sure how much code _that_ breaks. Diez From gagsl-py2 at yahoo.com.ar Sun Jan 27 13:55:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 16:55:18 -0200 Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> <87dd811e-3095-41d0-80fd-7312338e5254@i3g2000hsf.googlegroups.com> <489b6fc5-e871-425e-b242-45be618fc9f4@n20g2000hsh.googlegroups.com> <87r6g4q7hq.fsf@mulj.homelinux.net> Message-ID: En Sun, 27 Jan 2008 12:51:51 -0200, Dox33 escribi?: > Yes, I know. > There are several ways to work around the problem. > (Look at the innitial code I provided in this discussion start) > Fact is, every time I'm getting a script from somewhere or someone, I > have to search and replace all the affected code. > Not very conveniant. > That's why I rather would have a correct working version. Add this on your sitecustomize.py module (or create one) import sys def raw_input(prompt=None): if prompt: sys.stdout.write(prompt) return original_raw_input() import __builtin__ original_raw_input = __builtin__.raw_input __builtin__.raw_input = raw_input It just replaces the builtin raw_input with a custom function. -- Gabriel Genellina From peter.schuller at infidyne.com Thu Jan 24 08:57:49 2008 From: peter.schuller at infidyne.com (Peter Schuller) Date: Thu, 24 Jan 2008 07:57:49 -0600 Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> Message-ID: >> Not necessarily. In part it is the name, in that __name__ will be >> different. But to the extent that calling code can potentially import >> them under differents names, it's identity. Because importing the same >> module under two names results in two distinct modules (two distinct >> module objects) that have no realation with each other. So for >> example, if a module has a single global protected by a mutex, there >> are suddenly two copies of that. In short: identity matters. > > That's not true. It doesn't matter if you Import a module several times > at different places and with different names, it's always the same module > object. Sorry, this is all my stupidity. I was being daft. When I said importing under different names, I meant exactly that. As in, applying hacks to import a module under a different name by doing it relative to a different root directory. This is however not what anyone is suggesting in this discussion. I got my wires crossed. I fully understand that "import x.y.z" or "import x.y.z as B", and so one do not affect the identity of the module. > Ok, there is one exception: the main script is loaded as __main__, but if > you import it using its own file name, you get a duplicate module. > You could confuse Python adding a package root to sys.path and doing > imports from inside that package and from the outside with different > names, but... just don't do that! Right :) > I don't really understand what your problem is exactly, but I think you > don't require any __import__ magic or arcane hacks. Perhaps the __path__ > package attribute may be useful to you. You can add arbitrary directories > to this list, which are searched for submodules of the package. This way > you can (partially) decouple the file structure from the logical package > structure. But I don't think it's a good thing... That sounds useful if I want to essentially put the contents of a directory somewhere else, without using a symlink. In this case my problem is more related to the "file == module" and "directory == module" semantics, since I want to break contents in a single module out into several files. > Isn't org.lib.animal a package, reflected as a directory on disk? That's > the same both for Java and Python. Monkey.py and Tiger.py would be modules > inside that directory, just like Monkey.java and Tiger.java. Aren't the > same thing? No, because in Java Monkey.java is a class. So we have class Monkey in package org.lib.animal. In Python we would have class Monkey in module org.lib.animal.monkey, which is redundant and does not reflect the intended hierarchy. I have to either live with this, or put Monkey in .../animal/__init__.py. Neither option is what I would want, ideally. Java does still suffer from the same problem since it forces "class == file" (well, "public class == file"). However it is less of a problem since you tend to want to keep a single class in a single file, while I have a lot more incentive to split up a module into different files (because you may have a lot of code hiding behind the public interface of a module). So essentially, Java and Python have the same problem, but certain aspects of Java happens to mitigate the effects of it. Languages like Ruby do not have the problem at all, because the relationship between files and modules is non-existent. -- / Peter Schuller PGP userID: 0xE9758B7D or 'Peter Schuller ' Key retrieval: Send an E-Mail to getpgpkey at scode.org E-Mail: peter.schuller at infidyne.com Web: http://www.scode.org From boblatest at yahoo.com Tue Jan 8 04:47:25 2008 From: boblatest at yahoo.com (Robert Latest) Date: 8 Jan 2008 09:47:25 GMT Subject: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> <5ugulaF1hqn2cU1@mid.uni-berlin.de> Message-ID: <5ugv5dF1i0edtU1@mid.dfncis.de> Marc 'BlackJack' Rintsch wrote: > Both processes have to make their communication ends unbuffered or line > buffered. Yeah, I figured something like that. > And do whatever is needed to output the numbers from ``slow`` > unbuffered or line buffered. Hm, "slow" of course is just a little test program I wrote for this purpose. In reality I want to call another program whose behavior I can't influence (well, technically I could because it's open-source, but let's assume it to be a black box for now). If 'slow' or some other program does buffered output, how come I can see its output line-by-line in the shell? robert From PurpleServerMonkey at gmail.com Sun Jan 27 20:23:33 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Sun, 27 Jan 2008 17:23:33 -0800 (PST) Subject: Struct.Pack and Binary files Message-ID: Having trouble working out an appropriate format string for packing a binary file. The below is something I use for ASCII files but now I need something equivalent for working with binary files i.e jpg, zips etc. fileHandle = open("test.txt") while loop: fileBuffer = fileHandle.read(512) format = "!hh%dc" % len(fileBuffer) outdata = struct.pack(format, *fileBuffer) clientSocket.sendto(outdata, DestAddress) I've reused the basic structure below for a binary file, the issue I'm having is working out the correct format string. At first I thought a float or double would have been the one to use but the interpreter complains about invalid types being passed. fileHandle = open("test.zip", "rb") while loop: fileBuffer = fileHandle.read(512) format = "!hh%dd" % len(fileBuffer) outdata = struct.pack(format, *fileBuffer) clientSocket.sendto(outdata, DestAddress) If someone could shed some light on the problem it would be appreciated, I'm clearly missing something fairly obvious. Thanks in advance. From bignose+hates-spam at benfinney.id.au Fri Jan 11 20:44:22 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Jan 2008 12:44:22 +1100 Subject: encrypting python modules References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <87sl14getd.fsf@benfinney.id.au> <5uqi86F6710oU1@mid.uni-berlin.de> Message-ID: <87k5mfhl6x.fsf@benfinney.id.au> Marc 'BlackJack' Rintsch writes: > On Sat, 12 Jan 2008 09:47:26 +1100, Ben Finney wrote: > > > Trying to make bits uncopyable and unmodifiable is like trying to > > make water not wet. > > Certainly not. I can put water into the freezer Turning it into ice, and making it not useable as water. So, to the extent you've made it not-wet, you've also made it not-water. To torture the analogy further, this would be equivalent to engraving the bits in stone and sealing the whole in a concrete slab. While still technically the bits can be extracted, the extent to which they are uncopyable and unmodifiable is exactly the extent to which they are useless as bits. As soon as they become available for use as digital bits in some way, they become available for copying and modifying again. -- \ "People demand freedom of speech to make up for the freedom of | `\ thought which they avoid." -- Soren Aabye Kierkegaard | _o__) (1813-1855) | Ben Finney From steven.p.clark at gmail.com Thu Jan 10 17:32:12 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Thu, 10 Jan 2008 17:32:12 -0500 Subject: Newbie question on Classes In-Reply-To: <8cf64cf7-d38c-4239-b188-b0b861407512@j78g2000hsd.googlegroups.com> References: <8cf64cf7-d38c-4239-b188-b0b861407512@j78g2000hsd.googlegroups.com> Message-ID: <663744510801101432s154dad96ib3b280da65a60d30@mail.gmail.com> > l = [] > l.append(man) > l.append(woman) > > # Print the state. > for item in l: > print item.state() > > Small, off-topic nitpick: please don't use "l" (lower-case el) as a variable name. >From http://www.python.org/dev/peps/pep-0008/: "Naming Conventions Names to Avoid Never use the characters `l' (lowercase letter el), `O' (uppercase letter oh), or `I' (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use `l', use `L' instead." From paddy3118 at googlemail.com Sat Jan 26 03:12:20 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 26 Jan 2008 00:12:20 -0800 (PST) Subject: Testing whether something is of type Exception References: <47991a8a$0$36353$742ec2ed@news.sonic.net> Message-ID: <09a2f59e-b6a8-40f7-ac80-c17792c47578@e25g2000prg.googlegroups.com> On Jan 24, 11:14 pm, John Nagle wrote: > How can I tell whether an object is of type Exception? Use it as if it is one and catch any exceptions :-) - Paddy. (Grabs coat, heads for the exit) From ggpolo at gmail.com Wed Jan 23 15:55:04 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jan 2008 18:55:04 -0200 Subject: Creating new types and invoking super Message-ID: Hello, Before starting, let me show some sample codes so I can explain: class A(object): def __init__(self): super(A, self).__init__() x = type("X", (A, ), {})() This works fine, but suppose I have several classes like A and I would like to create a decorator to call super. First I tried this: def init(func): def _init(inst): super(inst.__class__, inst).__init__() func(inst) return _init class A(object): @init def __init__(self): pass This works when I create a instance by doing A(), but I get "RuntimeError: maximum recursion depth exceeded" when I create a new type doing type("X", (A, ), {}) and then create an instance of it. To "solve" this problem, I changed the init function to this then: def init(func): def _init(inst): super(inst.__class__.__mro__[-2], inst).__init__() func(inst) return _init It works if A is a direct subclass of object, if it is not I have to adapt the index [-2]. So, is there a better way to do this ? -- -- Guilherme H. Polo Goncalves From JAMoore84 at gmail.com Sat Jan 26 12:02:17 2008 From: JAMoore84 at gmail.com (JAMoore84 at gmail.com) Date: Sat, 26 Jan 2008 09:02:17 -0800 (PST) Subject: Beginner String formatting question Message-ID: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> Hi all, I am trying to write a simple program that will accept an integral "time" input in the HHMMSS format and output a "HH:MM:SS" form. My code is as follows: ======================== import string def FormatTime(time): '''Converts an HHMMSS string to HH:MM:SS format.''' timeString = str(time) #converts the num to string hours = [timeString[0], timeString[1]] minutes = [timeString[2], timeString[3]] seconds = [timeString[4], timeString[5]] Ftime = "%s:%s:%s",(hours,minutes,seconds) clock = Ftime.join() return clock =========================== when I run it from IDLE, I get this: >>> Format.FormatTime(time) ['1', '1', ':', '2', '2', ':', '3', '3'] ['1', '1', ':', '2', '2', ':', '3', '3'] My questions- 1) Why is this function printing out twice? 2)It may be a formatting issue, but I want to have the output as "HH:MM:SS", rather than having it broken out into each cell. I thought the 'join' command would do this, but I must not be using it properly/understanding something. 3)as a side note, I've noticed that the parameter "time" passed in must be passed in as a string, otherwise I receive an error that "time" is unsubscriptable. Am I unable to pass in an int and then convert it to a string within the function with str()? I've been at this for a while, so I may not be able to see the forest through the trees at this point. I'd greatly appreciate any suggestions or instruction on these mistakes. Best, Jimmy From siona at chiark.greenend.org.uk Fri Jan 4 12:08:23 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 04 Jan 2008 17:08:23 +0000 (GMT) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: >BTW if you're using C++, why not simply use std::set? Because ... how to be polite about this? No, I can't. std::set is crap. The implementation is a sorted sequence -- if you're lucky, this is a heap or a C array, and you've got O(log n) performance. But the real killer is that requirement for a std::set is that T::operator< exists. Which means, for instance, that you can't have a set of complex numbers.... -- \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 __peter__ at web.de Fri Jan 11 07:32:36 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jan 2008 13:32:36 +0100 Subject: reading a specific column from file References: Message-ID: A.T.Hofkamp wrote: > On 2008-01-11, cesco wrote: >> Hi, >> >> I have a file containing four columns of data separated by tabs (\t) >> and I'd like to read a specific column from it (say the third). Is >> there any simple way to do this in Python? >> >> I've found quite interesting the linecache module but unfortunately >> that is (to my knowledge) only working on lines, not columns. >> >> Any suggestion? > > the csv module may do what you want. Here's an example: >>> print open("tmp.csv").read() alpha beta gamma delta one two three for >>> records = csv.reader(open("tmp.csv"), delimiter="\t") >>> [record[2] for record in records] ['gamma', 'three'] Peter From richardjones at optushome.com.au Mon Jan 7 15:51:45 2008 From: richardjones at optushome.com.au (Richard Jones) Date: Tue, 08 Jan 2008 07:51:45 +1100 Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Message-ID: <478290e1$0$32673$afc38c87@news.optusnet.com.au> Berco Beute wrote: > What I would like to know is what it was that boosted Python's > popularity in 2004 (see http://www.tiobe.com/tiobe_index/Python.html). > Equally interesting is the question why it dropped shortly after. They explain the discontinuity on the index page in the FAQ. Richard From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Jan 26 08:47:50 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 26 Jan 2008 14:47:50 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: <600s07F1m9jgbU1@mid.individual.net> over at thepond.com wrote: > Intel processors can only process machine language[...] There's no > way for a processor to understand any higher level language, even > assembler, since it is written with hexadecimal codes and basic > instructions like MOV, JMP, etc. The assembler compiler can > convert an assembler file to a binary executable, which the > processor can understand. This may be true, but I think it's not bad to assume that machine language and assembler are "almost the same" in this context, since the translation between them is non-ambiguous (It's just "recoding"; this is not the case with HLLs). > Both Linux and Windows compile down to binary files, which are > essentially 1's and 0's arranged in codes that are meaningful to > the processor. (Not really -- object code files are composed of header data and different segments, data and code, and only the code segments are really meaningful to the processor.) > Once a python py file is compiled into a pyc file, I can > disassemble it into assembler. But you _do_ know that pyc files are Python byte code, and you could only directly disassemble them to Python byte code directly? > Assembler is nothing but codes, which are combinations of 1's and > 0's. No, assembly language source is readable text like this (gcc): .LCFI4: movl $0, %eax popl %ecx popl %ebp leal -4(%ecx), %esp ret Machine language is binary codes, yes. > You can't read a pyc file in a hex editor, By definition, you can read every file in a hex editor ... > but you can read it in a disassembler. It doesn't make a lot of > sense to me right now, but if I was trying to trace through it > with a debugger, the debugger would disassemble it into > assembler, not python. Not at all. Again: It's Python byte code. Try experimenting with pdb. Regards, Bj?rn -- BOFH excuse #340: Well fix that in the next (upgrade, update, patch release, service pack). From snoylr at gmail.com Sat Jan 19 17:14:30 2008 From: snoylr at gmail.com (snoylr) Date: Sat, 19 Jan 2008 14:14:30 -0800 (PST) Subject: Naming a file Message-ID: <89bb0095-429f-404c-b7f6-ff0a554b07cc@i72g2000hsd.googlegroups.com> I have a variable called filename How do I create a file using the filename variable as the name of the file? For example if the variable is 105Markum What statement do I need to create a file name 105Markum.txt? From kw at codebykevin.com Thu Jan 10 10:42:21 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 10 Jan 2008 10:42:21 -0500 Subject: Problem with Tkinter.PhotoImage In-Reply-To: References: Message-ID: <47863CDD.9060200@codebykevin.com> C?dric Lucantis wrote: > Hi, > > I can only load gif images with Tkinter.PhotoImage and none with BitmapImage. > I tried png, jpg, bmp and xpm and always got this errors : > That's because Tk only supports the gif format natively. You need to install an additional photo library to support additional images (Tk has an Img extension, and Python Image Library is also very good). -- Kevin Walzer Code by Kevin http://www.codebykevin.com From mathewbrown at fastmail.fm Wed Jan 9 11:10:47 2008 From: mathewbrown at fastmail.fm (Mrown) Date: Wed, 9 Jan 2008 08:10:47 -0800 (PST) Subject: subprocess.Popen spawning cmd shells References: Message-ID: <2aa3bb72-7094-44cc-a8af-d7777916755c@e25g2000prg.googlegroups.com> On Jan 9, 5:17?pm, Mrown wrote: > Hi, > ? I'm currently writing a python program that relies on a CLI > program. ?What I'm currently doing is using subprocess.Popen on Python > 2.5.1. ?Here's the line that I'm currently running: > > ? ? ? ? ? ? child = subprocess.Popen(["c:\app.exe", node, "-w", > str(tmpTime * 1000), '-n', str(1), '-l'], stdin=subprocess.PIPE, > stdout=subprocess.PIPE, stderr=subprocess.PIPE) > > The problem is that although the above works, a CMD shell is spawned > and becomes visible for each time I run the above. ?I thought that by > redircting stdin, stdout and stderr, no CMD shell should pop-up. ?Is > something wrong in the way I'm using subprocess? ?Thanks for your help. To anyone interested, I found the solution by using the CREATE_NO_WINDOW creation flag. So this is what the code now looks like (and it doesn't spawn any shells): CREATE_NO_WINDOW = 0x8000000 child = subprocess.Popen(["c:\app.exe", node, "-w", str(tmpTime * 1000), '-n', str(1), '-l'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags = CREATE_NO_WINDOW) From steven at REMOVE.THIS.cybersource.com.au Wed Jan 23 01:38:30 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 06:38:30 -0000 Subject: subprocess and & (ampersand) References: Message-ID: On Tue, 22 Jan 2008 22:53:20 -0700, Steven Bethard wrote: > I'm having trouble using the subprocess module on Windows when my > command line includes special characters like "&" (ampersand):: > > >>> command = 'lynx.bat', '-dump', 'http://www.example.com/?x=1&y=2' > >>> kwargs = dict(stdin=subprocess.PIPE, > ... stdout=subprocess.PIPE, ... > stderr=subprocess.PIPE) > >>> proc = subprocess.Popen(command, **kwargs) proc.stderr.read() > "'y' is not recognized as an internal or external command,\r\noperable > program or batch file.\r\n" > > As you can see, Windows is interpreting that "&" as separating two > commands, instead of being part of the single argument as I intend it to > be above. Is there any workaround for this? How do I get "&" treated > like a regular character using the subprocess module? That's nothing to do with the subprocess module. As you say, it is Windows interpreting the ampersand as a special character, so you need to escape the character to the Windows shell. Under Windows, the escape character is ^, or you can put the string in double quotes: # untested command = 'lynx.bat -dump http://www.example.com/?x=1^&y=2' command = 'lynx.bat -dump "http://www.example.com/?x=1&y=2"' In Linux land, you would use a backslash or quotes. To find the answer to this question, I googled for "windows how to escape special characters shell" and found these two pages: http://www.microsoft.com/technet/archive/winntas/deploy/prodspecs/shellscr.mspx http://technet2.microsoft.com/WindowsServer/en/library/44500063-fdaf-4e4f-8dac-476c497a166f1033.mspx Hope this helps, -- Steven From 7146031596 at tmomail.net Wed Jan 30 14:56:24 2008 From: 7146031596 at tmomail.net (7146031596 at tmomail.net) Date: Wed, 30 Jan 2008 14:56:24 -0500 Subject: No subject Message-ID: <32288466.29282731201722984918.JavaMail.imb@mgwatl04.cns.mms.com> 17146031598 From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 11:05:41 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 17:05:41 +0100 Subject: Python help for a C++ programmer In-Reply-To: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> References: <0e2d5ad1-b685-4905-8190-a1469c0e136a@d4g2000prg.googlegroups.com> Message-ID: <478e2b2b$0$1716$426a74cc@news.free.fr> mlimber a ?crit : > I'm writing a text processing program to process some survey results. > I'm familiar with C++ and could write it in that, but I thought I'd > try out Python. I've got a handle on the file I/O and regular > expression processing, FWIW, and depending on your text format, there may be better solutions than regexps. > but I'm wondering about building my array of > classes (I'd probably use a struct in C++ since there are no methods, > just data). If you have no methods and you're sure you won't have no methods, then just use a dict (name-indexed record) or a tuple (position-indexed record). > I want something like (C++ code): > > struct Response > { > std::string name; > int age; > int iData[ 10 ]; > std::string sData; > }; > > // Prototype > void Process( const std::vector& ); > > int main() > { > std::vector responses; > > while( /* not end of file */ ) > { > Response r; > > // Fill struct from file > r.name = /* get the data from the file */; > r.age = /* ... */; > r.iData[0] = /* ... */; > // ... > r.sData = /* ... */; > responses.push_back( r ); > } > > // Do some processing on the responses > Process( responses ); > } > > What is the preferred way to do this sort of thing in Python? # assuming you're using a line-oriented format, and not # worrying about exception handling etc... def extract(line): data = dict() data['name'] = # get the name data['age'] = # get the age data['data'] = # etc... return data def process(responses): # code here if name == '__main__': import sys path = sys.argv[1] responses = [extract(line) for line in open(path)] process(response) If you have a very huge dataset, you may want to either use tuples instead of dicts (less overhead) and/or use a more stream-oriented approach using generators - if applyable of course (that is, if you don't need to extract all results before processing) HTH From fredrik at pythonware.com Mon Jan 7 14:30:23 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 07 Jan 2008 20:30:23 +0100 Subject: Does Python cache the startup module? In-Reply-To: References: Message-ID: Baz Walter wrote: > It's hard to supply an example for this, since it is local to the machine I am > using. The startup module would look something like this: would look, or does look? if it doesn't look like this, what else does it contain? > #!/usr/local/bin/python > > if __name__ == '__main__': > > import sys > from qt import QApplication, QWidget > > application = QApplication(sys.argv) > mainwindow = QWidget() > application.setMainWidget(mainwindow) > mainwindow.show() > sys.exit(application.exec_loop()) > > If I change the name 'mainwindow' to 'mainwidget', the widget it refers to does > not get destroyed; when I change it back again, it does get destroyed. > Otherwise, the program runs completely normally. I don't see any code in there that destroys the widget, and I also don't see any code in there that creates more than one instance of the main widget. what do you do to run the code, and how to you measure leakage? is the name "mainwidget" used for some other purpose in your application? From mikael at isy.liu.se Thu Jan 31 03:46:49 2008 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 31 Jan 2008 09:46:49 +0100 Subject: Sine Wave Curve Fit Question In-Reply-To: <47a0c8b5$0$2994$ba620e4c@news.skynet.be> References: <7eOdnXVrB-fQFD3anZ2dnUVZ8hednZ2d@giganews.com> <47a0c8b5$0$2994$ba620e4c@news.skynet.be> Message-ID: Helmut Jarausch wrote: > Your model is A*sin(omega*t+alpha) where A and alpha are sought. > Let T=(t_1,...,t_N)' and Y=(y_1,..,y_N)' your measurements (t_i,y_i) > ( ' denotes transposition ) > > First, A*sin(omega*t+alpha) = > A*cos(alpha)*sin(omega*t) + A*sin(alpha)*cos(omega*t) = > B*sin(omega*t) + D*cos(omega*t) > > by setting B=A*cos(alpha) and D=A*sin(alpha) > > Once, you have B and D, tan(alpha)= D/B A=sqrt(B^2+D^2) This is all very true, but the equation tan(alpha)=D/B may fool you. This may lead you to believe that alpha=arctan(D/B) is a solution, which is not always the case. The point (B,D) may be in any of the four quadrants of the plane. Assuming B!=0, the solutions to this equation fall into the two classes alpha = arctan(D/B) + 2*k*pi and alpha = arctan(D/B) + (2*k+1)*pi, where k is an integer. The sign of B tells you which class gives you the solution. If B is positive, the solutions are those in the first class. If B is negative, the solutions are instead those in the second class. Whithin the correct class, you may of course choose any alternative. Then we have the case B=0. Then the sign of D determines alpha. If D is positive, we have alpha=pi/2, and if D is negative, we have alpha=-pi/2. Last if both B and D are zero, any alpha will do. /MiO From ckimyt at gmail.com Mon Jan 7 08:46:26 2008 From: ckimyt at gmail.com (Mike) Date: Mon, 7 Jan 2008 05:46:26 -0800 (PST) Subject: How to refer to the current module? References: Message-ID: Sweet! Thanks! Mike On Jan 7, 8:30 am, "Guilherme Polo" wrote: > > globals() =) > From bellman at lysator.liu.se Fri Jan 25 17:33:07 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Fri, 25 Jan 2008 22:33:07 +0000 (UTC) Subject: read and readline hanging References: Message-ID: Olivier Lefevre wrote: >> 1. The subprocess has stopped producing output. > Indeed, if I do this interactively, I can tell after 3 lines that I've > gotten all there is to get right now and the fourth readline() call > hangs. Can you really? How do you know if the program has finished or if it is just taking a very long time to produce the next line in its response? Unless there is some way to differentiate between the last line all the other lines of a response, you can't really be sure. > But how can I find out *programmatically* that there is no more > input? It is possible to check if there is something more to read at the moment, but you can't check if the subprocess will produce more to read in the future. To check if there is something to read at this very moment, you can use any of the following methods: - select.select() - the FIONREAD ioctl (the ioctl() function lives in the fcntl module, and the FIONREAD constant is in the termios module) - set the underlying file descriptor in non-blocking mode: flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NDELAY) After that, reads on the pipe will raise an IOError exception with the errorcode EWOULDBLOCK. - start a thread that does blocking reads from the pipe, and puts the chunks it reads on a queue for your main thread to grab. For the last approach, you might be interrested in my asyncproc module, which does exactly that. You can download it from . However, none of these approaches absolves you from the necessity of knowing when one response ends. You still need to solve that problem. The proper way is to define a protocol between your program and the subprocess, in which you can clearly tell when you have reached the end of a response. Then you need to get the program you are calling to adher to that protocol, of course... The SMTP protocol is a good example of how this can look. In SMTP, each response to a command consists of a number of lines. Each line has a three-digit response code, an "end of response" flag, and a text message. The "end of response" flag is a space (" ") for the last line in the response, and a dash ("-") for all the other lines. The response to an EHLO command can look like this: 250-sellafield Hello localhost [127.0.0.1], pleased to meet you 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-EXPN 250-VERB 250-8BITMIME 250-SIZE 250-DSN 250-ETRN 250-DELIVERBY 250 HELP Since there is a space instead of a dash after the "250" code in the last line above, the SMTP client knows that there won't be any more lines in response to its command. If you can't get the program you are calling to follow some protocol like this, then you can only make guesses. Sometimes you can make fairly good guesses, and sometimes it will be more or less impossible... -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "Life IS pain, highness. Anyone who tells ! bellman @ lysator.liu.se differently is selling something." ! Make Love -- Nicht Wahr! From michael.pearmain at tangozebra.com Thu Jan 10 04:21:01 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Thu, 10 Jan 2008 01:21:01 -0800 (PST) Subject: Win32com and Excel Message-ID: <096bc326-3c91-4287-817f-79994a8c507d@k39g2000hsf.googlegroups.com> Hi, I currently have an excel table (1 table each time) that has differing number of rows and differing number of columns each time, for another program i use (SPSS) to import the data i need to know the cell range of this data table. I.e what the last row of data is and the last column that has data in it. Does anyone have any code that does something similar? My guess is i have to do something like thefollowing to enable python to read xl? import win32com.client working_dir = '//c:/temp/' xl = win32com.client.Dispatch("Excel.Application") xl.Visible = 1 #open MS Excel xl.Workbooks.Open('%s/working_output.xls' % (working_dir)) then code to find the cell ranges Any help here is much appreciated Mike From rndblnch at gmail.com Fri Jan 25 14:47:33 2008 From: rndblnch at gmail.com (rndblnch) Date: Fri, 25 Jan 2008 11:47:33 -0800 (PST) Subject: is possible to get order of keyword parameters ? References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> Message-ID: <5b6e2bc6-8136-4e3a-8bf2-bb6d689d6110@s8g2000prg.googlegroups.com> On Jan 25, 5:27 pm, Larry Bates wrote: > Keyword arguments are normally treaded as "order independent". > Why do you think you need to find the order? What problem do > you wish to solve? > > -Larry On Jan 25, 7:39 pm, Duncan Booth wrote: > The question remains, what use is there for this? my goal is to implement a kind of named tuple. idealy, it should behave like this: p = Point(x=12, y=13) print p.x, p.y but what requires to keep track of the order is the unpacking: x, y = p i can't figure out how to produce an iterable that returns the values in the right order. relying on a "natural" order of the key names is not possible: x, and y are alphabetically sorted but the following example should also work: size = Point(width=23, height=45) w, h = size if you have any suggestion to implement such a thing... thank you renaud From http Sun Jan 13 08:28:00 2008 From: http (Paul Rubin) Date: 13 Jan 2008 05:28:00 -0800 Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> <00cb6e9d-e8b6-4e65-be58-5a4472413c53@j78g2000hsd.googlegroups.com> Message-ID: <7xabn94zz3.fsf@ruckus.brouhaha.com> thebjorn writes: > Perhaps something like this? > > def chop(lst, length): > from itertools import islice > it = iter(lst) > z = [list(islice(it, length)) for i in xrange(1 + len(lst) // length)] > if len(z) > 1: > z[-2].extend(z.pop()) # the last item will be empty or contain "overflow" elements. > return z def chop(lst, length): def chop1(): t = len(lst) // length - 1 for i in xrange(t): yield lst[i*length: (i+1)*length] yield lst[t*length:] return list(chop1()) From stefan.behnel-n05pAM at web.de Wed Jan 30 14:04:04 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 30 Jan 2008 20:04:04 +0100 Subject: "Code Friendly" Blog? In-Reply-To: <876318a9-5806-4613-a7d5-9437860af3f7@v29g2000hsf.googlegroups.com> References: <876318a9-5806-4613-a7d5-9437860af3f7@v29g2000hsf.googlegroups.com> Message-ID: <47A0CA24.10101@web.de> Hai Vu wrote: > Why don't you try to use Code Colorizer: > http://www.chamisplace.com/colorizer/cc.asp Looks like it lacks support for one important language, though... Stefan From bignose+hates-spam at benfinney.id.au Wed Jan 9 17:57:17 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 10 Jan 2008 09:57:17 +1100 Subject: Natural-language datetime parsing and display References: <873at7lq0d.fsf@benfinney.id.au> Message-ID: <87bq7uk3oy.fsf@benfinney.id.au> "Daniel Fetchinson" writes: > > The OP was looking for presentation though. I know roundup has > > code for this if an independent library can't be found. > > Thanks for all the responses! > Indeed I was looking for presentation and not parsing, I'll take a > look at roundup. Yes, that's why I indicated that Chandler Desktop would be a good place to look. Roundup sounds like an equally good place to look. Hopefully, with a couple of options like that, you'll find something decent. It would be good to see a generic "natural-language datetime presentation" library in the Cheeseshop, since the functionality seems quite well-suited to a separate generic library. -- \ "The best mind-altering drug is truth." -- Jane Wagner, via | `\ Lily Tomlin | _o__) | Ben Finney From paul at boddie.org.uk Sat Jan 12 11:47:57 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 12 Jan 2008 08:47:57 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <13od12b23hfv772@corp.supernews.com> <5b035c91-72eb-4d88-b19b-e89470865c5b@i7g2000prf.googlegroups.com> <13ogbfasbcici1c@corp.supernews.com> Message-ID: <389f20bb-ccbf-43bd-b38b-e359a3f62c3a@f47g2000hsd.googlegroups.com> On 12 Jan, 04:03, Steven D'Aprano wrote: > > Given the way that people seem to use "interpreted" as a pejorative and a > synonym for "slow", I don't doubt it one bit. Especially in management, > where they might be making technical judgments on the basis of half- > remembered Comp Sci 101 lessons from fifteen years earlier and vague > buzzword-laden articles in trade magazines. Indeed. Still, there's reason to be upbeat about Python's potential here. The big question is this: what is everyone with any degree of concern about Python's performance doing to improve the situation? Sure, C (or actually C++) seems to win the shootout [1], but there are plenty of language implementations between g++ and CPython to suggest that the old choice of extension modules written in C vs. other code written in Python doesn't provide a complete map of the opportunities. Paul [1] http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=all From sjmachin at lexicon.net Sun Jan 13 16:50:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 13 Jan 2008 13:50:25 -0800 (PST) Subject: time.time or time.clock References: Message-ID: <8a6cee2f-3869-40df-8235-b47971f4b44f@f3g2000hsg.googlegroups.com> On Jan 14, 7:05 am, Ron Adam wrote: > I'm having some cross platform issues with timing loops. It seems > time.time is better for some computers/platforms and time.clock others, but Care to explain why it seems so? > it's not always clear which, so I came up with the following to try to > determine which. > > import time > > # Determine if time.time is better than time.clock > # The one with better resolution should be lower. > if time.clock() - time.clock() < time.time() - time.time(): > clock = time.clock > else: > clock = time.time > > Will this work most of the time, or is there something better? > Manual: """ clock( ) On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of ``processor time'', depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond. [snip] time( ) Return the time as a floating point number expressed in seconds since the epoch, in UTC. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non- decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls. """ AFAICT that was enough indication for most people to use time.clock on all platforms ... before the introduction of the timeit module; have you considered it? It looks like your method is right sometimes by accident. func() - func() will give a negative answer with a high resolution timer and a meaningless answer with a low resolution timer, where "high" and "low" are relative to the time taken for the function call, so you will pick the high resolution one most of the time because the meaningless answer is ZERO (no tick, no change). Some small fraction of the time the low resolution timer will have a tick between the two calls and you will get the wrong answer (-big < -small). In the case of two "low" resolution timers, both will give a meaningless answer and you will choose arbitrarily. HTH, John From martin at v.loewis.de Thu Jan 24 00:17:44 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 24 Jan 2008 06:17:44 +0100 Subject: os.system behavior when calling SQLPlus with spooling In-Reply-To: References: Message-ID: <47981f79$0$18719$9b622d9e@news.freenet.de> > I would prefer not to use os.system() since I want to analyze the > results. Can anyone suggest how I should go about executing sqlplus > in this case? You need to find out why it hangs. Perhaps sqlplus tries to read from its stdin, asking the user for input, yet your script doesn't provide any? You can use "strace -p " to find out what it's doing when it hangs. Regards, Martin From edloper at seas.upenn.edu Tue Jan 29 23:22:51 2008 From: edloper at seas.upenn.edu (Edward Loper) Date: Tue, 29 Jan 2008 23:22:51 -0500 Subject: epydoc 3.0 released Message-ID: <3131dfac0801292022y3fdb3129p20758d91b94a2853@mail.gmail.com> Announcing epydoc 3.0 ~~~~~~~~~~~~~~~~~~~~~ Webpage: http://epydoc.sourceforge.net/ Download: http://tinyurl.com/yoo6d7 Epydoc is a tool for generating API documentation for Python modules, based on their docstrings. A lightweight markup language called epytext can be used to format docstrings, and to add information about specific fields, such as parameters and instance variables. Epydoc also understands docstrings written in reStructuredText, Javadoc, and plaintext. For some examples of the documentation generated by epydoc, see: - The API documentation for epydoc. - The API documentation for the Python 2.5 standard library. - The API documentation for NLTK, the natural language toolkit. Improvements in Version 3.0 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Version 3.0 of epydoc adds support for extracting documentation information using both introspection (i.e., importing & inspecting the modules programmatically) and parsing (i.e., reading the source code of the modules); and for combining both sources of information. This is important because each source has its own advantages and disadvantages with respect to the other. See the epydoc FAQ for more information about the relative benefits of introspection and parsing, and why it's good to merge information from both sources: http://epydoc.sourceforge.net/faq.html#introspect_vs_parse Version 3.0 also adds the following features: * Support for variable docstrings. * Automatic generating of source code graphs, including class trees, package trees, uml class graphs, and import graphs. * Syntax highlighted source code, including links from identifiers back into the documentation. For more details about what's new in Epydoc 3.0, see: http://epydoc.sourceforge.net/whatsnew.html ---------------------------------------------------------------------- Edward Loper edloper at gradient.cis.upenn.edu http://www.cis.upenn.edu/~edloper/ ---------------------------------------------------------------------- From hexamorph at gmx.net Fri Jan 25 14:25:06 2008 From: hexamorph at gmx.net (Hexamorph) Date: Fri, 25 Jan 2008 20:25:06 +0100 Subject: Operator overloading In-Reply-To: <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> References: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com> <5vuob3F1nd2bhU1@mid.uni-berlin.de> <2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> Message-ID: <479A3792.3040504@gmx.net> MartinRinehart at gmail.com wrote: > > Diez B. Roggisch wrote: >> No, there is no way. You would change general interpreter behavior if >> you could set arbitrary operators for predefined types. >> >> Start grumping... > > Thank you, Diez. > > If I ever design a language, please remind me that complete, easy, > well-documented access to the working of the internals (and the > ability to change same) would be very, uh, what's the right word? > Pythonic? You mean you want the ability to change for example the + operator for ints to something like calculating the cosine instead of doing addition? That will break the whole system in general as other parts of the language (or modules, libraries and programs) rely on a certain inner behaviour. There are some languages in which you can do this (Lisp/Scheme for example) but messing with the internals is almost never done for good reasons. From mrmakent at cox.net Wed Jan 23 10:13:35 2008 From: mrmakent at cox.net (Mike Kent) Date: Wed, 23 Jan 2008 07:13:35 -0800 (PST) Subject: How avoid both a newline and a space between 2 print commands? References: Message-ID: On Jan 23, 9:03 am, "seber... at spawar.navy.mil" wrote: > print "foo" > print "bar" > > has a newline in between "foo" and "bar" > > print "foo", > print "bar" > > has a space in between "foo" and "bar" > > How prevent ANYTHING from going in between "foo" and "bar" ?? > > (Without defining a string variable.) > > Chris print "%s%s" % ("foo", "bar") ## If "%s%s" doesn't violate your condition of not defining a string variable, I'm not sure. From lotrpy at gmail.com Sun Jan 13 08:45:02 2008 From: lotrpy at gmail.com (lotrpy) Date: Sun, 13 Jan 2008 05:45:02 -0800 (PST) Subject: about sort a list with integer key References: <986e05f3-2fe9-4fe8-94e2-fef26713a78c@i72g2000hsd.googlegroups.com> <87fxx1nbwv.fsf@mulj.homelinux.net> Message-ID: On 1?13?, ??8?32?, Hrvoje Niksic wrote: > Use lambda when it works better for you, the speed difference is > marginal in practice anyway. itemgetter is not (and was never > intended to be) a general substitute for functions, as you've > discovered. > > The marginal speed difference between itemgetter and an explicit > lambda that does the subscripts is a consequence of itemgetter being > written in C, meaning it avoids the creation of a Python stack frame, > etc. Combining int(...) with this operation requires coding the key > function in Python, which removes itemgetter's advantage. In other > words, you cannot retain itemgetter's speed advantage with more > complex keys. If the sorting performance is a problem for you, please > give more details about what you're doing -- there might be better > ways to speed up the code. Fredrik and Hrvoje, thanks for the reply, here the sorting performance is not a big problem for me. the text file is just several hundred line, each line include several item separated by space. I'll run the script each week or month, just 1 second to get the result,so maybe stick to lambda here is just fine. From ask at me Sun Jan 20 22:08:18 2008 From: ask at me (alf) Date: Sun, 20 Jan 2008 21:08:18 -0600 Subject: auto import Message-ID: Hi, is there any way to tweak __import__ so it imports module with another arbitrary selected module included? For instance I have my mylibs.py module. Then when I import a oneofhundredssmallmodules.py module from other place the mylibs.py is automatically imported without a explicit import. The effect is the same like below: module oneofhundredssmallmodules.py: import * from mylibs In my software I hundreds of small modules constituting certain custom scripts. I need an ability to dynamically control what is imported into them before custom code kicks in. Andy From __peter__ at web.de Thu Jan 17 11:10:41 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jan 2008 17:10:41 +0100 Subject: class closure question References: Message-ID: Steven W. Orr wrote: > I want to indirectly change the value of a variable. > > #! /usr/bin/python > foo = [44] > bar = foo > bar[0] = 55 > print 'bar = ', bar > print 'foo = ', foo > > This works fine. > > bar = [55] > foo = [55] > > But I want to do the same with a class value. > > #! /usr/bin/python > S = None > dd = { 'class': [S] } > class C1(object): > def __init__(self): > print 'Hello from C1' > > def mkclass(base): > class zzz(base): > pass > return zzz > > dd['class'][0] = mkclass( C1 ) > print "dd['class'][0].__bases__ = ", dd['class'][0].__bases__ > print 'S = ', S > > The answer is not what I want: > > dd['class'][0].__bases__ = (,) > S = None > > The goal is for S to be set to the returned class from mkclass. > > Can someone help? What you want is not possible in Python. You can modify some objects (called "mutable") but rebinding a name has to be explicit. Peter From lefevrol at yahoo.com Mon Jan 28 14:52:54 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Mon, 28 Jan 2008 20:52:54 +0100 Subject: read and readline hanging In-Reply-To: <5vuv9iF1o6ambU2@mid.uni-berlin.de> References: <5vuv9iF1o6ambU2@mid.uni-berlin.de> Message-ID: >> But in python eventually stdout.readline() hangs. This is a real >> nuisance: why can't it just return None? > > Because that would be quite annoying because most of the time people want > blocking behavior. Just an afterthought: do people prefer the blocking behaviour because blocking until there's something to read is more economical of computer resources than polling for a non-null read (what I was trying to do, in effect)? The problem with polling is you need a minimum of 2 threads to do anything useful: it is quite inconvenient to block in the main thread. -- O.L. From socyl at 987jk.com.invalid Thu Jan 10 11:13:10 2008 From: socyl at 987jk.com.invalid (kj) Date: Thu, 10 Jan 2008 16:13:10 +0000 (UTC) Subject: ISO Python example projects (like in Perl Cookbook) Message-ID: I'm looking for "example implementations" of small projects in Python, similar to the ones given at the end of most chapters of The Perl Cookbook (2nd edition, isbn: 0596003137). (Unfortunately, the otherwise excellent Python Cookbook (2nd edition, isbn: 0596007973), by the same publisher (O'Reilly), does not have this great feature.) The subchapters devoted to these small projects (which are called "Program"s in the book), each consists of a description of the task, a discussion of the relevant design considerations, and one or more illustrative implementations. As such, these programs are larger and more complex than the typical "recipe" in the book, but are still short enough to be read and understood in a few minutes. I find the study of such small programs invaluable when learning a new language. Does anyone know of a source of similar material for Python? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From propanbutan at gmx.net Tue Jan 22 09:33:28 2008 From: propanbutan at gmx.net (propanbutan) Date: Tue, 22 Jan 2008 15:33:28 +0100 Subject: make exe from application with py2exe References: <6d553403-1275-459e-b2e0-9463cab39250@e10g2000prf.googlegroups.com> Message-ID: <20080122153328.37b4364c.propanbutan@gmx.net> vedrandekovic at gmail.com wrote: > Is there any idea how can i create (.exe) from application (.exe ) > with py2exe? yes. here [1], here [2] and maybe here [3]. bye. http://catb.org/~esr/faqs/smart-questions.html [1] http://www.google.com [2] http://www.py2exe.org [3] From dg.google.groups at thesamovar.net Mon Jan 21 04:01:07 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Mon, 21 Jan 2008 01:01:07 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> <7xlk6j7h0y.fsf@ruckus.brouhaha.com> Message-ID: <31257681-840c-4194-b2c2-8db28a82e272@e23g2000prf.googlegroups.com> Hi all, It's great how many different sorts of solutions (or almost solutions) this puzzle has generated. Speedwise, for reference my solution posted above takes about 40 seconds on my 1.8GHz laptop, and the less elegant version (on my webpage linked to in the original post) takes about 15 seconds. It seems to me like surely this problem can be more efficiently solved than that? My version isn't very Pythonic (it could almost be written in C++ the way I've done it) so I liked the idea of the first solution, but I don't think it can be fixed. I adapted it so that it doesn't use the same number more than once, but it still has some problems. Firstly, it only finds solution ((a op b) op c) op d etc. and won't find (for example (1+2)*(3+4). Secondly, it stores a dictionary value->how to get to value which is fine if you can re-use numbers because one way to get to a given value is as good as another, but sometimes you can get to the same number in two different ways using different numbers, so it misses solutions. Paul: 758 = 8+(5*((2+4)*25)) Arnaud: I haven't had time to play with your solution yet - how quick does it run? My fantasy is that there is a solution that isn't TOO slow where you can just look at the code and go 'Oh yes, of course that works!' and understand it immediately. Maybe that's too much to ask even of Python! ;-) From arnodel at googlemail.com Sun Jan 20 17:07:14 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 20 Jan 2008 14:07:14 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Message-ID: <891374fb-cf1d-4445-829d-0e10a8a1ed69@d21g2000prf.googlegroups.com> On Jan 20, 5:41?pm, dg.google.gro... at thesamovar.net wrote: > Ever since I learnt to program I've always loved writing solvers for > the Countdown numbers game problem in different languages, and so now > I'm wondering what the most elegant solution in Python is. > > If you don't know the game, it's simple: you're given six randomly > chosen positive integers, and a target (another randomly chosen > positive integer), and you have to make the target using only the > numbers you're given, and +,-,* and / (and any number of brackets you > like). You're not allowed fractions as intermediate values. So, given > 2, 3 and 5 say, and a target of 21, you could do (2+5)*3 = 21. > Neat problem! I couldn't help but have a go. I have no idea how efficient it is, I didn't think too much before I started typing :) def partitions(l): """"split(l) -> an iterator over all partitions of l into two lists There is no repetition provided that all elements of l are distinct.""" # Works only for lists of length < 8*size(int) due to xrange limitations for i in xrange(1, 2**len(l)-1, 2): partition = [], [] for x in l: i, r = divmod(i, 2) partition[r].append(x) yield partition def calc(l, filter=lambda *x:x): """calc(l, filter) -> an iterator over all expressions involving all numbers in l filter is a function that returns its two arguments with possible side-effects. """ if len(l) == 1: yield l[0], str(l[0]) else: for l1, l2 in partitions(l): for v1, s1 in calc(l1, filter): for v2, s2 in calc(l2, filter): yield filter(v1 + v2, '(%s+%s)' % (s1, s2)) yield filter(v1 * v2, '(%s*%s)' % (s1, s2)) if v1 > v2: yield filter(v1 - v2, '(%s-%s)' % (s1, s2)) elif v2 > v1: yield filter(v2 - v1, '(%s-%s)' % (s2, s1)) if not v1 % v2: yield filter(v1 / v2, '(%s/%s)' % (s1, s2)) elif not v2 % v1: yield filter(v2 / v1, '(%s/%s)' % (s2, s1)) def print_filter(target): """print_filter(target) -> filter that prints all expressions that equal target""" def filter(v, s): if v == target: print s return v, s return filter class ShortestFilter(object): def __init__(self, target): self.shortest = None self.target = target def __call__(self, v, s): if v == self.target: if not self.shortest or len(self.shortest) > len(s): self.shortest = s return v, s def countdown(numbers, target): """countown(numbers, target) -> None -- print all countdown solutions""" for dummy in calc(numbers, print_filter(target)): pass def best_countdown(numbers, target): """best_countdown(numbers, target) -> str -- return shortest solution""" filter = ShortestFilter(target) for dummy in calc(numbers, filter): pass return filter.shortest >>> countdown([7,8,50,8,1,3], 923) (((((50*8)-1)/3)*7)-8) (((((50*8)-1)*7)/3)-8) (((((8*50)-1)/3)*7)-8) (((((8*50)-1)*7)/3)-8) >>> print best_countdown([100,9,7,6,3,1], 234) (((1+(3*6))+7)*9) -- Arnaud From cwitts at gmail.com Fri Jan 11 07:28:26 2008 From: cwitts at gmail.com (Chris) Date: Fri, 11 Jan 2008 04:28:26 -0800 (PST) Subject: reading a specific column from file References: Message-ID: <336cbbb2-c7a8-42ad-9f3a-6696a616a700@v46g2000hsv.googlegroups.com> On Jan 11, 2:15 pm, cesco wrote: > Hi, > > I have a file containing four columns of data separated by tabs (\t) > and I'd like to read a specific column from it (say the third). Is > there any simple way to do this in Python? > > I've found quite interesting the linecache module but unfortunately > that is (to my knowledge) only working on lines, not columns. > > Any suggestion? > > Thanks and regards > Francesco for (i, each_line) in enumerate(open('input_file.txt','rb')): try: column_3 = each_line.split('\t')[2].strip() except IndexError: print 'Not enough columns on line %i of file.' % (i+1) continue do_something_with_column_3() From israelu at elbit.co.il Tue Jan 1 05:00:23 2008 From: israelu at elbit.co.il (iu2) Date: Tue, 1 Jan 2008 02:00:23 -0800 (PST) Subject: using super References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> <58c1aa27-98e4-4129-852c-f9a8477605db@i7g2000prf.googlegroups.com> Message-ID: <7220614d-311d-4dc6-b14f-39f0c091dbdb@q77g2000hsh.googlegroups.com> On Jan 1, 9:59?am, Michele Simionato wrote: > No PEP, this would never pass. There would be no way > to stop a method from calling its parent: you would > lose control of your classes, so I think this is a > bad idea. Not all classes, only classes the programmer chooses to have this behaviour. >Having said so, it is easy to implement > what you want with a metaclass: > > def callParent(*methodnames): > ? ? ?class Meta(type): > ? ? ? ? ?def __init__(cls, name, bases, dic): ... Thanks From sjmachin at lexicon.net Wed Jan 23 17:47:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 14:47:35 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com><5vphe6F1njt09U1@mid.uni-berlin.de><12d19814-b7b9-44b0-aee3-299befac7279@i12g2000prf.googlegroups.com> <66446d1e-189c-4c24-bd7a-83cbd66deb60@i12g2000prf.googlegroups.com> Message-ID: <7920ea6d-fdb0-4c83-826d-3e5829a6ec0f@t1g2000pra.googlegroups.com> On Jan 24, 7:57 am, "Reedick, Andrew" wrote: > > Why is it that so many Python people are regex adverse? Use the dashed > line as a regex. Convert the dashes to dots. Wrap the dots in > parentheses. Convert the whitespace chars to '\s'. Presto! Simpler, > cleaner code. Woo-hoo! Yesterday was HTML day, today is code review day. Yee-haa! > > import re > > state = 0 > header_line = '' > pattern = '' > f = open('a.txt', 'r') > for line in f: > if line[-1:] == '\n': > line = line[:-1] > > if state == 0: > header_line = line > state += 1 state = 1 > elif state == 1: > pattern = re.sub(r'-', r'.', line) > pattern = re.sub(r'\s', r'\\s', pattern) > pattern = re.sub(r'([.]+)', r'(\1)', pattern) Consider this: pattern = ' '.join('(.{%d})' % len(x) for x in line.split()) > print pattern > state += 1 state = 2 > > headers = re.match(pattern, header_line) > if headers: > print headers.groups() > else: > state = 2 assert state == 2 > m = re.match(pattern, line) > if m: > print m.groups() > > f.close() > From steven at REMOVE.THIS.cybersource.com.au Tue Jan 15 20:02:55 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Jan 2008 01:02:55 -0000 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> <87ir1wf1wi.fsf@mulj.homelinux.net> <87k5mbd8bv.fsf@benfinney.id.au> Message-ID: On Tue, 15 Jan 2008 14:02:43 -0800, Lie wrote: > I've been in this Python mailing list for a few days, and I've noticed > several things here: There are too many fundamentalist! > > Don't play stupid and all, don't be a fundamentalist. It might be true > that __init__ isn't a constructor and __new__ might be the constructor It is true. > (some people even claimed __new__ is also not a constructor). They did? I must have missed them. > From the base definition of a constructor: constructor is the creator of > an object. In this case, __new__ is technically the constructor while > __init__ is an initializer. Yes, that is correct, although I too have been known to use "constructor" to *informally* refer to __init__. It's a bad habit, and while technically wrong, not always unforgivably wrong. > However, it is also to be noted that __init__ is what makes an object > meaningful, and that makes it a constructor in a sense (while still > technically a constructor). Without initialization, an object is > meaningless, even if the definition of the initializer is to leave it as > it is. Nope, not at all. The following class does not call the initializer: class MyClass(object): class __metaclass__(type): def __call__(cls, *args, **kwargs): obj = cls.__new__(cls) print "There is no __init__." return obj def __new__(cls, *args, **kwargs): print "This is the constructor, see me construct an instance!" return object.__new__(cls) def __init__(self, *args, **kwargs): raise Exception("die die die!!!") Now use it: >>> c = MyClass() This is the constructor, see me construct an instance! There is no __init__. And call the initializer by hand: >>> c.__init__() Traceback (most recent call last): File "", line 1, in ? File "", line 7, in __init__ Exception: die die die!!! Here's a class with no constructor (or rather, a constructor that the user *can't get to*): class OldClass: def __new__(cls, *args, **kwargs): # this is not called raise Exception("die die die!!!") def __init__(self, *args, **kwargs): print "This is the initializer, see me initialize " \ "the already-constructed instance 'self'!" >>> c = OldClass() This is the initializer, see me initialize the already-constructed instance 'self'! For various reasons, Python splits the process of constructing and initializing instances into two stages. What other languages do is irrelevant. Perhaps Java and C++ don't need to distinguish between "constructor" and "initializer", but Python does. > Python creates object by doing something like this: a = anObject(arg1, > arg2, arg3) That's what the programmer does. Under the hood, Python does something different. > These arguments is then passed to __new__ and __init__ for their > arguments in its sake of creating and initializing the object. Then > anObject() returns an instance of anObject. Assuming the standard metaclass. > From an outsider's point of view, there is no difference between __new__ > and __init__ since they're "implementation details" No, they most certainly are not implementation details. ANY implementation of Python MUST use __new__ and __init__ or else it is not Python, it is a different language. The nature of how Python creates instances is part of the language specification, not the implementation. > (in other languages, > these are private functions[1] that is invisible to outsiders, Python > doesn't like privacy but the semantic of being implementation detail > still exist). For an outsider, there is absolutely no need to know that > __new__ and __init__ exists, they just need to know anObject()'s > arguments, which is the public view of the constructor and > initializer[2]. I don't understand your argument. If you are saying that people who don't care about the details of Python instance creation don't care about the details of Python instance creation, then you're right, but it's a rather pointless observation. Yes, people who don't care don't care. But people who want to: (1) Program successfully in Python; (2) Compare how Python works to other computer languages; (3) Do metaclass programming; or (4) Find out how Python creates instances will care about the details. Anybody asking for an explanation of __init__ (like this thread!) is asking about the details. Why on earth do you think it is a bad thing to answer the question accurately? [snip] > If you can't be convinced with this argument, then I'd give you another > that's a bit more Pythonic: > DUCK TYPING: If it looks like a duck, walks like a duck, and quacks like > a duck, it is a duck! > > From the class programmer's point of view, __init__ acts like an object > constructor in other languages, there is no significant difference > between __init__ and constructor in other languages. Fortunately, Python isn't those other languages. We're not discussing how Java creates instances, or C++, or VisualBasic. We're discussing Python, so any answer given that starts off "Well, in Java it works like this..." is almost certainly going to be useless to the Python programmer asking about Python. [snip] > In this sense, VB's New, C ++ > constructor, and C# constructor is equal to Python's __init__, thus the > Duck Typing spirit applies here. It isn't enough to quack like a duck. It also needs to walk like a duck and swim like a duck too. -- Steven From ganeshborse at gmail.com Thu Jan 31 05:41:42 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 31 Jan 2008 02:41:42 -0800 (PST) Subject: how to get string printed by PyErr_Print( )? References: <03c09680-cf9b-4e35-96d4-f28d11c40bbc@m77g2000hsc.googlegroups.com> Message-ID: <2a5a9cc1-683a-438d-9620-c67d5a72dc3c@s37g2000prg.googlegroups.com> On Jan 9, 8:01?pm, grbgooglefan wrote: > On Dec 19 2007, 5:55?pm, Christian Heimes wrote: > >grbgooglefanwrote: > > > PythonC API functionPyErr_Print( ) prints an error string onto stderr > > > if PyErr_Occurred() is true. > > > I don't want to print this to stderr because my Python+C code is > > > running daemon mode & won't have terminal / stderr. > > > So, I want to retrieve the string whichPyErr_Print( ) will print. > > > E.g.,PyErr_Print() printed following string when I tried to call > > > setTuple with one extra argument > > > Traceback (most recent call last): > > > ? File "", line 2, in isTacticSafe > > > IndexError: tuple assignment index out of range > > > I suggest a different approach. A daemon must have a stdin, stdout and > > stderr connected to a terminal. You can use freopen() to redirect stderr > > and stdout to a log file and fclose() to close stdin. > > >http://www.gnu.org/software/libc/manual/html_mono/libc.html#Opening-S... > > > Christian > > I do not want to redirect anything to file. Because I do not want to > avoid the disk access completely - for reading as well as writing. > I liked the 1st option suggested by Robert Kern. > > Can you please explain a little bit how can I replace sys.stderr with > StringIO or my char* buffer? > I have to show the error message of Python code compilation & > execution to the user on the GUI & therefore I want to capture the > error message directly instead of logging it to file. > > Thanks in advance for all your help.- Hide quoted text - > > - Show quoted text - Well, I managed to do it myself. Here is what I am doing now to do this. In Python-C/C++ world, if someone wants to do the same thing, may use this. Note: For this, am assigning the cStringIO object to sys.stderr once I do Py_Initialize & then use cStringIO.getvalue() everytime I get error. While importing cStringIO module with Python-2.3.3, I faced the problem of "undefined symbol:PyObject_SelfIter". I could resolve that also. I have put that note in the post which I had opened for that. /+++++++++++++++++++++++++++++++++++++++++++++++ PyObject *_pPyModule; PyObject *_pPyDictionary; PyObject *_pPyGetValFunc; PyObject *_pPyobStringIO; Init(){ // Py_Initialize should have been done by now..... PyObject *modStringIO = NULL; PyObject *obFuncStringIO = NULL; // Import cStringIO module modStringIO = PyImport_ImportModule("cStringIO"); if(PyErr_Occurred() || modStringIO == NULL){ printf("pyParserEvaluator::Init::PyImport cStringIO failed:"); PyErr_Print(); goto PY_INIT_ERR; } // get StringIO constructor obFuncStringIO = PyObject_GetAttrString(modStringIO, "StringIO"); if(PyErr_Occurred() || obFuncStringIO == NULL){ printf("pyParserEvaluator::Init: cant find cStringIO.StringIO:"); PyErr_Print(); goto PY_INIT_ERR; } // Construct cStringIO object _pPyobStringIO = PyObject_CallObject(obFuncStringIO, NULL); if(PyErr_Occurred() || _pPyobStringIO==NULL){ printf("pyParserEvaluator::Init: cStringIO.StringIO() failed:"); PyErr_Print(); goto PY_INIT_ERR; } // get getvalue() method in StringIO instance _pPyGetValFunc = PyObject_GetAttrString(_pPyobStringIO, "getvalue"); if(PyErr_Occurred() || _pPyGetValFunc==NULL){ printf("pyParserEvaluator::Init: cant find getvalue function:"); PyErr_Print(); goto PY_INIT_ERR; } // try assigning this object to sys.stderr ret = PySys_SetObject("stderr", _pPyobStringIO); if(ret != 0){ printf("failed to assign _pPyobStringIO to stderr\n"); goto PY_INIT_ERR; } return ret; PY_INIT_ERR: Py_XDECREF(modStringIO); Py_XDECREF(obFuncStringIO); Py_XDECREF(_pPyobStringIO); Py_XDECREF(_pPyGetValFunc); } int _getPythonErrorMessage() { // call getvalue() method in StringIO instance int ret = 0; PyObject *obResult=NULL; char *sresult = NULL; obResult = PyObject_CallObject(_pPyGetValFunc, NULL); if(PyErr_Occurred() || obResult==NULL){ printf("getvalue() failed\n"); ret = -1; goto CLEAN_AND_RETURN; } // did getvalue return a string? if(!PyString_Check(obResult)){ printf("getvalue() did not return error string\n"); ret = -1; goto CLEAN_AND_RETURN; } // retrieve error message string from this object if(NULL != (sresult = PyString_AsString(obResult))){ pErrorString = strdup(sresult); } else { ret = -1; goto CLEAN_AND_RETURN; } return(ret); CLEAN_AND_RETURN: Py_XDECREF(obResult); return(ret); } ================================================= From mutawafayez at yahoo.com Sat Jan 19 07:09:38 2008 From: mutawafayez at yahoo.com (small giant) Date: Sat, 19 Jan 2008 04:09:38 -0800 (PST) Subject: the God that never was Message-ID: <32cbed1b-1922-40b5-9e50-27a63676df35@d21g2000prf.googlegroups.com> Islam is the only religion which teaches the existence of a PERFECT God. A perfect God means that there is no sharer in His Nature and His Attributes: "Say: He is God, the One and Only; God, the Eternal, Absolute; He begetteth not, nor is He begotten; and there is none like unto Him." (Holy Qur'an, 112:1-4) There has appeared a man in Benoni. He is not qualified in theology, but is fondly cherishing the self-delusion that he is an apostle of Christ, appointed by God to convert Muslims to Christianity. Because he is a lawyer by profession, he is adept at juggling with words and quoting the Holy Qur'an totally out of context without knowing a word of Arabic. He wants Muslims to believe that Jesus was also a God, a belief that is abhorrent to us, because it is an antithesis of the Absolute perfection of Allah Subhaanahoo Wa Ta 'Aala! Thus intent upon reversing the process of Truth, which is: "And say: The Truth has come and falsehood vanished. Surely falsehood is ever bound to vanish." (Qur'an, 17:81). In this he will never succeed because the process of Truth is irreversible. TWO REASONS He has given two reasons to prove that Jesus is God, viz: (i) "When we say Jesus is deity (or even God for that matter), we do not make him the Father! He is one with the Father and therefore HE SHARES HIS NATURE", and (ii) "HE IS IN EVERY WAY LIKE THE FATHER but he is not the Father". In short, according to him, Jesus is God because He SHARES THE NATURE OF GOD, and HE IS IN EVERY WAY LIKE GOD. These two reasons given by him to prove the divinity of Jesus are so puerile that they speak volumes of his legal training. Numerous quotations from the Bible are given below to prove that Jesus neither SHARED THE NATURE OF GOD, nor is he IN EVERY WAY LIKE GOD. He can, therefore, NEVER be GOD. We have given the quotations from the Bible without comment, because the Bible speaks for itself! TO SAY THAT JESUS IS GOD OR SON OF GOD IS NOT ONLY A MOCKERY OF GODHOOD, BUT BLASPHEMY OF THE LOWEST ORDER AND AND INSULT TO THE INTELLIGENCE OF MEN! (Note: Unless otherwise stated, all quotations from the Bible are given from the Authorized Version. In our headings and subheadings we have referred to Jesus as "God" in inverted commas in order to show the ABSURDITY of the claim of this man that Jesus is God!) THE BIRTH OF "GOD" "God" was created from the seed of David: "Concerning his Son Jesus Christ our Lord, which was made of the SEED of David according to the flesh." (Romans, 1:3) "God" was the fruit of the loins of David: "Therefore being a prophet, and knowing that God had sworn with an oath to him, that of the fruit of his loins, according to the flesh, he would raise up Christ to sit on his throne." (Acts, 2:30) The Ancestors of "God": "The generations of Jesus Christ, the son of David, the son of Abraham." (Matthew, 1:1) The Sex of "God": "And when eight days were accomplished for the circumcising of the child, his name was called Jesus." (Luke, 2:21) How Mary Conceived and Delivered "God". Mary conceived Jesus like any other woman: "The days were accomplished that she should be delivered," (Luke, 2:6) which means that she went through all the normal stages of pregnancy. Nor was her delivery any different from other expectant mothers: "And she being with child cried, travelling in birth, and pained to be delivered." (Revelation, 12:2) "God" Sucked The Paps of a Woman: "And it came to pass, as he spake these things, a certain woman of the company lifted up her voice, and said unto him, Blessed is the womb that bare thee, and the paps which thou hast sucked." (Luke, 11:27) The Country of Origin of "God": "Jesus was born in Bethlehem of Judaea in the days of Herod the king. (Matthew, 2:1) The Occupation of "God": "Jesus was a carpenter by trade." (Mark, 6:3), "and the son of a carpenter." (Matthew, 13:55) The Transport of "God": "Behold, thy king cometh unto thee, meek, and sitting upon an ass." (Matthew, 21:5) "And Jesus, when he had found a young ass, sat thereon." (John, 12:14) The Wining and Dining of "God": "The Son of man came eating and drinking, and they say, behold a man gluttonous, and a winebibber, a friend of publicans and sinners." (Matthew, 11:9; Luke, 7:34) The Poverty of "God": "And Jesus saith unto him, the foxes have holes, and the birds of the air have nests; but the Son of man hath not where to lay his head." (Matthew, 8:20) The Meagre Possessions of "God": "Shoes of Jesus" (Luke, 3:16), "Garments and coat of Jesus" (John, 19:23) "God" Was a Devout Jew: "And in the morning, rising up a great while before day, he went out, and departed into a solitary place, and there prayed." (Mark, 1:35) "God" Was a Loyal Subject: Jesus was a good citizen, he was loyal to Caesar. He said: "Render therefore unto Caesar the things which are Caesar's; and unto God the things that are God's." (Matthew, 22:21) He paid his tax regularly. (Matthew, 17:24-27) THE FAMILY OF "GOD" "God" Was the Son of Joseph: "Philip findeth Nathanael, and saith unto him, we have found him, of whom Moses in the law, and the prophets, did write, Jesus of Nazareth, the son of Joseph" (John, 1:45) Brothers and Brothers-in-law of "God": "And when he was come into his own country, he taught them in their synagogue, insomuch that they were astonished, and said, whence hath this man this wisdom, and these mighty works? Is not this the carpenter's son? Is not his mother called Mary? and his brethren, James, and Joses, and Simon, and Judas? And his sisters, are they not all with us? Whence hath this man all these things? (Matthew, 13:54-56) THE DEVELOPMENT OF "GOD" Spiritual Development of "God": "And the child grew, and waxed strong in spirit, filled with wisdom." (Luke, 2:40) Mental, Physical and Moral Development of "God": "And Jesus increased in wisdom and stature, and in favor with God and man." (Luke, 2:52) "God" Was 12 Years Old When His Parents Took Him to Jerusalem: "Now his parents went to Jerusalem every year at the feast of the passover. And when he was twelve years old, they went up to Jerusalem after the custom of the feast." (Luke, 2:41-42) The Powerless "God" (Jesus) said: "I can of mine own self do nothing." (John, 5:30) "God" Was Ignorant of the Time. Jesus said: "But of that day and that hour knoweth no man, no, not the angels which are in heaven, neither the Son, but the Father." (Mark, 13:32) "God" Was Ignorant of the Season: "And on the morrow, when they were come from Bethany, he (Jesus) was hungry: and seeing a fig tree afar off having leaves, he came, if haply he might find anything thereon: and when he came to it, he found nothing but leaves; for the time of figs was not yet." (Mark, 11:12-13) "God" Was Unlettered: "Now about the midst of the feast Jesus went up into the temple, and taught. And the Jews marvelled, saying, How knoweth this man letters, having never learned?" (John, 7:14-15) "God" Learnt Through Experience: "Learned he obedience by the things which he sufered." (Hebrews, 5:8) THE TEMPTING OF "GOD" The Devil Tempted "God" For 40 Days: "And immediately the spirit driveth him into the wilderness. And he was there in the wilderness forty days, tempted of Satan." (Mark, 1:12-13) The Devil Tempted "God" Continuously: "And when the devil had ended all the temptation, he departed from him for a season." (Luke, 4:13) Like the Sinners, "God" Was Tempted In All Things: "But (he) was in all points tempted like as we are, yet without sin." (Hebrews, 4:15) True God Cannot be Tempted With Evil: "God cannot be tempted with evil, neither tempteth he any man." (James, 1:13) Only The Ungodly Are Tempted With Evil: "But every man is tempted, when he is drawn away of his own lust, and enticed." (James, 1:14) THE MISSION OF "GOD" The Confession and Repentance of "God": before the beginning of his public ministry: "Jesus was baptized by John the Baptist" (Matthew, 3:13), "which signified the confession of sins" (Matthew, 3:6), "and repentance from sins (Matthew, 3:11). "God" Did Not Come to Save the Sinners: "And when he was alone, they that were about him with the twelve asked of him the parable. And he said unto them, unto you it is given to know the mystery of the kingdom of God: but unto them that without, all these things are done in parables: That seeing they may see, and not perceive; and hearing they may hear, and not understand; lest at any time they should be converted, and their sins should be forgiven them." (Mark, 4:10-12) THE RACIAL "GOD" "God" Was a Tribal Jew: "The lion of the tribe of Juda." (Revelation, 5:5) "God" Came For The Jews Only: "But he answered and said, I am not sent but unto the lost sheep of the house of Israel." (Matthew, 15:24) Racial Discrimination of "God": "These twelve Jesus sent forth, and commanded them, saying, Go not into the way of the Gentiles, and into any city of the Samaritans enter ye not: But go rather to the lost sheep of the house of Israel." (Matthew, 10:5-6) According to "God", The Gentiles Are Dogs: "It is not meet to take the children's bread, and to cast it to dogs." (matthew, 15:26) The Kingdom of "God": And he (Jesus) shall reign over THE HOUSE OF JACOB for ever; and of his kingdom there shall be no end." (Luke, 1:33) The Titles of "God": "The king of the Jews" (Matthew, 2:2), "The king of Israel" (John, 1:49; 12:13) A "GOD" UNLIKE THE GOD A Hungry "God": "And when he had fasted forty days and forty nights, he was afterward an hungered." (Matthew 4:2), "Now in the morning as he returned into the city, he hungered." (Matthew, 21:18), "and on the morrow, when they were come from Bethany, he was hungry." (Mark, 11:12) A Thirsty "God": "(He) saith, I thirst." (John, 19:28) A Sleepy "God": "He was asleep." (Matthew, 8:24), "He fell asleep" (Luke, 8:23), "And he was in the hinder part of the ship, asleep on a pillow." (Mark, 4:38) A Weary "God": Jesus therefore, being wearied with his journey, sat thus on the well." (John, 4:6) A Groaning "God": "He groaned in the spirit, and was troubled." (John, 11:33), "Jesus therefore again groaning in himself cometh to the grave." (John, 11:38) A Weeping "God": "Jesus wept." (John, 11:35) A Sorrowing "God": "And (he) began to be sorrowful and very heavy." (Matthew 26:37). "Then saith he unto them, my soul is exceeding sorrowful, even unto death." (Matthew, 26:38) A Hysterical "God": "And (he) began to be soreamazed and to be very heavy." (Mark, 14:33) A Weak "God": "And there appeared an angel unto him from heaven, strengthening him." (Luke, 22:43) THE WARRING "GOD" The Strong-Arm Method of "God": "And he went into the temple, and began to cast out them that sold therein, and them that bought." (Luke, 19:45). "And the Jews' passover was at hand, and Jesus went up to Jerusalem, and found in the temple those that sold oxen and sheep and doves, and the changers of money sitting: and when he had made a scourge of small cords, he drove them all out of the temple, and the sheep, and the oxen; and poured out the changers' money, and overthrew the tables." (John, 2:13-15) The "God" of War: Jesus said: "Think not that I am come to send peace on earth: I came not to send peace, but a sword." (Matthew, 10:34) The Sabre-Rattling "God": Jesus said: "And he that hath no sword, let him sell his garment, and buy one." (Luke, 22:36) The "GOD" ON THE RUN "God" Was Panic-Stricken: "After these things Jesus walked in Galilee: for he would not walk in Jewry, because the Jews sought to kill him." (John, 7:1) "God" Walked in Fear of the Jews: "Then from that day forth they took counsel together for to put him to death. Jesus therefore walked no more openly among the Jews." (John, 11:53-54) "God" Has Shown a Clean Pair of Heels: "Therefore they sought again to take him: but he escaped out of their hand." (John, 10:39) "God" Fled in Disguise: "Then took they up stones to cast at him: but Jesus hid himself, and went out of the temple, going through the midst of them, and so passed by." (John, 8:59) THE CAPTURE OF "GOD" A Friend Betrayed the Secret Hiding Place of "God": "And Judas also, which betrayed him, knew the place: for Jesus off-times resorted thither with his disciples. Judas then, having received a band of man and officers from the chief priests and Pharisees, cometh thither with lanterns and torches and weapons." (John, 18:2-3) "God" Was Arrested, Bound and Led Away: "Then the band and the captain and officers of the Jews took Jesus, and bound him, and led him away." (John, 18:12-13) "God" Was Humiliated: "And the men that held Jesus mocked him, and smote him. And when they had blindfolded him, they struck him on the face." (Luke, 22:63-64). "Then did they spit in his face, and buffeted him; and others smote him with the palms of their hands." (Matthew, 26:67) "God" Was Defenseless: "One of the officers which stood by struck Jesus with the palm of his hand", he said: "Why smitest thou me?" (John, 18:22-23) "God" Was Condemned to Death: "And they all condemned him to be guilty of death." (Mark, 14:64). "They answered and said, he is guilty of death." (Matthew, 26:66) The Dumb and Docile "God": "He was led as a sheep to the slaughter; and like a lamb dumb before his shearer, so opened he not his mouth." (Acts, 8:32) THE SUPPOSED END OF "GOD" The Dying "God": "And Jesus cried with a loud voice, and gave up the ghost." (Mark, 15:37) The "God" That Was Supposed Dead and Defunct: "Christ died." (Romans, 5:6). "He was dead". (John, 19:33) The Supposed Corpse of "God": "he (Joseph of Arimathaea) went to Pilate, and begged the body of Jesus. Then Pilate commanded the body to be delivered." (Matthew, 27:58) The Shroud of "God": "And when Joseph had taken the body, he wrapped it in a clean linen cloth." (Matthew, 27:59) The Orbituary of The Late And Lamented "God": "Now when the centurion saw what was done, he glorified God, saying, certainly this was a righteous man." (Luke, 23:47) EPILOGUE According to this self-appointed apostle of Christ, Jesus is God because: (i) "HE SHARED THE NATURE OF GOD", and (ii) because "IN EVERY WAY HE IS LIKE GOD". But according to the quotations of the Bible given above, we find that Jesus did neither SHARE THE NATURE OF GOD nor is he IN EVERY WAY LIKE GOD. He is, therefore, definitely NOT God! The onus to prove that Jesus is God now rests with this Christian. Either he must prove that Jesus is God, or he must admit that he is a polytheist, i.e., a believer in more than one God. WITH ALL THE TRICKS AND VERBAL LEGERDEMAIN OF HIS PROFESSION, HE WILL NEVER BE ABLE TO PROVE THAT JESUS IS GOD!! He and his fellow-preachers in Christ, will never succeed in convincing the Muslims that Jesus was anything other than a natural man and a prophet of God, sent unto the house of Israel to bear the good news of the coming of the KINGDOM OF GOD, which prophecy was fulfilled with the advent of the Holy Prophet Muhammed (Sallal Laahu Alaihi Wa Sallam)! see this site for more information www.sultan.org From sipickles at hotmail.com Sat Jan 26 06:10:03 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Sat, 26 Jan 2008 11:10:03 +0000 Subject: Hashable Message-ID: Hi, The term 'hashable'. Am I right in thinking it means it can be indexed? like a string or a dict? Thanks Si -- Linux user #458601 - http://counter.li.org. From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 21:42:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 02:42:00 -0000 Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <13oga7o2i4fls5a@corp.supernews.com> On Fri, 11 Jan 2008 14:55:18 -0600, Reedick, Andrew wrote: > For those of us who still think in Perl, here's an easy to read ... > s = re.sub(r'_(.*?(_|$))', r':\1', s) "Easy to read"? Oh that's priceless. Andrew, you should consider writing comedy professionally! -- Steven From kyosohma at gmail.com Tue Jan 15 11:48:33 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 15 Jan 2008 08:48:33 -0800 (PST) Subject: A question about event handlers with wxPython References: <478c3bb2$0$5150$4c368faf@roadrunner.com> <2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com> <478ccbc3$0$11000$4c368faf@roadrunner.com> Message-ID: On Jan 15, 9:04 am, "Erik Lind" wrote: > > def HandleSomething(self, event): > > generating_control = event.GetEventObject() > > print generating_control > > > HTH, > > Thank you.That is what I was looking for, but as often seems the case, one > thing exposes another. Is there any way to listen for events without > specifically binding to a handler (it seems one cannot bind an event to two > handlers?)? One could do so with globals, but I'm trying to avoid that. > > For example, "press any button to stop" > > def HandleSomething(self, event): > ................. > while generating_control: == something: > run > else > stop I forgot to provide a link to a fairly straight-forward explanation of event propagation on the wxPython wiki: http://wiki.wxpython.org/EventPropagation Hope that helps! Mike From ajcppmod at gmail.com Thu Jan 10 12:10:00 2008 From: ajcppmod at gmail.com (ajcppmod at gmail.com) Date: Thu, 10 Jan 2008 09:10:00 -0800 (PST) Subject: ISO Python example projects (like in Perl Cookbook) References: <67f0df0e-ac6a-491c-b141-11fe8dadf4de@i29g2000prf.googlegroups.com> Message-ID: Have a look at Dive into Python by Mark Pilgrim. It is available for free here http://www.diveintopython.org/. Andy From steve at REMOVE-THIS-cybersource.com.au Wed Jan 30 21:25:52 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 31 Jan 2008 02:25:52 -0000 Subject: booleans, hash() and objects having the same value References: <9cdb261f-b81b-4eca-955a-a9b516eba9d2@s13g2000prd.googlegroups.com> Message-ID: <13q2cdg11ai9c88@corp.supernews.com> On Wed, 30 Jan 2008 17:14:32 -0800, Ryszard Szopa wrote: > Hi all, > > I've just read PEP 285 so I understand why bool inherits from int and > why, for example, ((False - True)*True)**False==1. And don't think that the choice was uncontroversial. > This was necessary for backwards compatibility "Necessary" is perhaps a little strong, but otherwise yes. > and to give the beast some ability to do moral reasoning. > For example, Python knows to value the whole truth more > than just a half-truth: > > In [95]: True > 0.5*True > Out[95]: True You're trying to be funny, yes? > Anyway, the thing that bothers me is the behavior of booleans when > passed as argument to the hash() function... That is, hash(True) == > hash(1) and hash(False) == hash(0). How do you feel about this? >>> hash(1.0) == hash(1) True >>> hash(0.0) == hash(0) True >>> hash(9907.0) == hash(9907) True It's the same thing: True is actually 1, just as 1.0 is, and so hash(True) is the same as hash(1), hash(1.0) and hash(1L). > This leads to a rather > counterintuitive interaction with dicts: [...] > Out[128]: {True: '1'} Yes, that's one of the disadvantages of having bools actually be ints, in the rare cases that you want bools to hash differently from ints, they don't. But that's no different from longs and ints hashing the same, or strings and unicode strings. > You may argue that this is a rather strange use case... However, you may > imagine that somebody would want a dict mapping from objects to their > representations, with 0, 1 and booleans among the objects, like in: > > In [123]: dict((el, repr(el)) for el in [0, 1, True, False]) Out[123]: > {0: 'False', 1: 'True'} Why bother with such a mapping? It already exists, and it is called repr(). Best of all, repr() shouldn't give a KeyError, and it can take mutable arguments. > In both cases, the result is rather unexpected, though after some > thinking, understandable (`==' tests the equality of values of objects, > True==1, and (from the documentation of hash) "Two objects with the same > value have the same hash value"). However, is this approach really > sound? Absolutely. As a general data type, the most sensible behaviour for hash tables is for dict[X] and dict[Y] to give the same result if X and Y are equal. > Wouldn't it be more sensible to have bool its own __hash__? Who cares what bools hash to? The real question is, should True be equal to 1 (and 1.0 and 1L) or not? The decision that it should was made a long time ago. It may or may not have been the best decision, but it's a decision and I doubt that it will be changed before Python 4000. Or possibly Python 5000. > PEP 285 doesn't mention anything about hashing (in fact, it doesn't > contain the string `hash' at all). Is it that nobody has noticed the > problem, it is a well known fact usually classified as a non-problem, or > maybe there are some serious reasons to keep 1 and True having the same > hash value? It's a non-problem in general. There might be highly specialized situations where you want 1.0 and 1 to map to different items, or 'xyz' and u'xyz', but being specialist they belong in your application code and not the language. Here's a start in implementing such a thing: class MyDict(dict): def __getitem__(self, key): key = (type(key), key) return super(MyDict, self).__getitem__(key) def __setitem__(self, key, value): key = (type(key), key) super(MyDict, self).__setitem__(key, value) >>> D = MyDict(); D[1] = "one"; D[1.0] = "one point oh" >>> D[1L] = "long one"; D[True] = "True" >>> D[1] 'one' >>> D[True] 'True' (I leave implementing the other necessary methods as an exercise.) > (Also, it is not completely clear what it means for two Python objects > to "have the same value". My first intuition would be that variables may > have a value, which usually is some Python object. I think that value should be interpreted rather fuzzily. I don't believe it is strongly defined: the concept of the value of an object depends on whatever the object wants it to be. For example, given an instance x with an attribute "foo", is x.foo part of the value of x, or is it something extra? Only the object x can make that decision. However, for standard objects like strings, ints, floats, etc. the value of the object corresponds to the intuitive ideas about strings, ints, floats etc. The value of the int 5 is 5, the value of the string "xyz" is "xyz", and so forth. For "well-behaved" objects, x and y have the same value when x == y returns True. Leave it to the objects to decide what their value is. It's easy to create ill-behaved objects: class Weird: def __eq__(self, other): if other is self: return False elif other is True: return True elif other == 1: return False else: import time return int(time.time()) % 2 == 0 but in general, you don't need to worry about such nonsense objects. > The second intuition > would be that objects with compatible (i.e. one inherits from the other) > types and ==-equal dicts have the same value. However, this is > _sometimes_ true. Python rarely cares about the type of objects, only the behaviour. Inheritance doesn't come into it, except as one possible way to get that behaviour: class MyInt: # DON'T inherit from int def __init__(self, value): if value == 'one': a, b = 0, 1 elif value == 'two': a, b = 1, 1 elif value == 'three': a, b = 1, 2 else: raise ValueError("can't count that high") self.data = (a, b) def __eq__(self, other): return other == sum(self.data) Instances of MyInt have the same value as the ints 1, 2, or 3 as appropriate. In all other ways though, MyInt and int behave very differently: for example, you can't add MyInts. -- Steven From ggpolo at gmail.com Tue Jan 22 18:55:32 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 22 Jan 2008 21:55:32 -0200 Subject: UDP Client/Server In-Reply-To: References: Message-ID: 2008/1/22, Martin Marcher : > Hello, > > I created a really simple udp server and protocol but I only get every 2nd > request (and thus answer just every second request). > > Maybe someone could shed some light, I'm lost in the dark(tm), sorry if this > is a bit oververbose but to me everything that happens here is black magic, > and I have no clue where the packages go. I can't think of a simpler > protocol than to just receive a fixed max UDP packet size and answer > immediately (read an "echo" server). > > thanks > martin > > > ### server > >>> from socket import * > >>> import SocketServer > >>> from SocketServer import BaseRequestHandler, UDPServer > >>> class FooReceiveServer(SocketServer.UDPServer): > ... def __init__(self): > ... SocketServer.UDPServer.__init__(self, ("localhost", 4321), > FooRequestHandler) > ... > >>> class FooRequestHandler(BaseRequestHandler): > ... def handle(self): > ... data, addr_info = self.request[1].recvfrom(65534) Your FooReceiveServer subclasses UDPServer, it already handled the recvfrom for you, so, this is wrong. > ... print data > ... print addr_info > ... self.request[1].sendto("response", addr_info) > ... > >>> f = FooReceiveServer() > >>> f.serve_forever() > request 0 > ('127.0.0.1', 32884) > request 1 > ('127.0.0.1', 32884) > request 2 > ('127.0.0.1', 32884) > request 2 > ('127.0.0.1', 32884) > request 2 > ('127.0.0.1', 32884) > > > > ### client > >>> target = ('127.0.0.1', 4321) > >>> from socket import * > >>> s = socket(AF_INET, SOCK_DGRAM) > >>> for i in range(10): > ... s.sendto("request " + str(i), target) > ... s.recv(65534) > ... > 9 > Traceback (most recent call last): > File "", line 3, in > KeyboardInterrupt > >>> s.sendto("request " + str(i), target) > 9 > >>> str(i) > '0' > >>> for i in range(10): > ... s.sendto("request " + str(i), target) > ... s.recv(65534) > ... > 9 > 'response' > 9 > 'response' > 9 > Traceback (most recent call last): > File "", line 3, in > KeyboardInterrupt > >>> #this was hanging, why? > ... > >>> s.sendto("request " + str(i), target) > 9 > >>> s.recv(65534) > 'response' > >>> s.sendto("request " + str(i), target) > 9 > >>> s.recv(65534) > Traceback (most recent call last): > File "", line 1, in > KeyboardInterrupt > >>> s.sendto("request " + str(i), target) > 9 > >>> s.sendto("request " + str(i), target) > 9 > >>> s.recv(65534) > 'response' > >>> s.recv(65534) > Traceback (most recent call last): > File "", line 1, in > KeyboardInterrupt > >>> s.sendto("request " + str(i), target) > 9 > >>> > > -- > http://noneisyours.marcher.name > http://feeds.feedburner.com/NoneIsYours > > You are not free to read this message, > by doing so, you have violated my licence > and are required to urinate publicly. Thank you. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From sjmachin at lexicon.net Fri Jan 11 05:00:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 11 Jan 2008 02:00:40 -0800 (PST) Subject: adding methods at runtime References: <940fcb28-764e-46ab-a627-aff513e009e1@j78g2000hsd.googlegroups.com> <5unou0F1ifu47U1@mid.uni-berlin.de> Message-ID: <46e3064b-bd95-4f8b-aa63-c5142031be85@d21g2000prg.googlegroups.com> On Jan 11, 10:44 am, Marc 'BlackJack' Rintsch wrote: > On Thu, 10 Jan 2008 14:55:18 -0800, zsl... at gmail.com wrote: > > Can I access the class attributes from a method added at runtime? (My > > experience says no.) > > I experimented with the following code: > > > [Code snipped] > > > So it seems to me, if you add a method to an instance, the method will > > not get "self" as parameter. > > You are not adding a method but a function. Take a look at > `types.MethodType()` to create a method from a function, instance, and > class. > Just in case gentle readers are wondering where to find the docs for types.MethodType, here's a hint: >>> import types, new; types.MethodType is new.instancemethod True >>> From peng.kyo at gmail.com Fri Jan 18 03:04:31 2008 From: peng.kyo at gmail.com (J. Peng) Date: Fri, 18 Jan 2008 16:04:31 +0800 Subject: too long float In-Reply-To: <13p0mfhjgriek01@corp.supernews.com> References: <13p0mfhjgriek01@corp.supernews.com> Message-ID: <18c1e5f20801180004g2e194480l2ea294f41bd5809e@mail.gmail.com> thanks all! On Jan 18, 2008 3:49 PM, Dennis Lee Bieber wrote: > On Fri, 18 Jan 2008 13:55:17 +0800, "J. Peng" > declaimed the following in comp.lang.python: > > > > > why this happened on my python? > > > > >>> a=3.9 > > >>> a > > 3.8999999999999999 > > > > I wanted 3.9 but got 3.89................ > > How to avoid it? thanks. > > > Avoid it? You don't... You alleviate the concern by understanding > that floating point is only precise if the value is a fraction of 2: 1, > 0.5, 0.25, 0.125... > > Computer Science recommends that one does NOT compare two floats for > equality -- instead one should compare the absolute value of the > difference of the two floats against some required epsilon (ie, how far > apart two floats can be and still be considered equal... > abs(f1 - f2) < 0.000001 > for example) > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > From hat at se-162.se.wtb.tue.nl Thu Jan 17 11:07:26 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 17 Jan 2008 17:07:26 +0100 Subject: How to create graphs an embed them in GUI? References: Message-ID: On 2008-01-17, Heiko Niedermeyer wrote: > As I'm learning Python from scratch, I don't care wether to use (=learn) > TKinter or PyQt or whatever, I just need some advice, which suits my > needs best. > It would be nice to have the programm working under win and linux > (shouldn't be a big Problem) and my requirements concerning the standard PyGTK is a 3rd option, and wxWindows + Python is a 4th option. TKinter is supplied with Python, which means everybody with Python also has TKinter. Main draw-backs are that it is quite old. Also, it has a peculiar way of getting stuff drawn at a canvas. PyQt is available free with some additional restriction (plz read the license) for the Linux system, I don't know whether you can also get a Win version under the same conditions (you couldn't when I looked the last time). PyGTK is said to be usable for both platforms. I know it works with Linux, and there exists a PyGTK installer for Win, but I hacve never used it. No recent experience with wxWindows. > My problem is, that I want to add graph (simple, line connected X,Y- > scatter plots) and if possible the 3D representation of atoms in a > molecule (-> coloured spheres in space). You should probably seperate both problems, in particular if you want to have the program do the layout for you. For 2D layout, Graphviz is one of the better known packages, run it as a child process. There are several graphviv/dot Python libraries available, search PyPI for them. For 3D, I don't know any programs. > I think it would take me years to program those by myself, so I would ne > ready to use packages, if available. > Long story short: Are there packages that could do this, and does it > matter which GUI I want to embed them in? If you want a GUI that understands how to layout chemical structures, you won't have many options (on the other hand, you never know, have you tried searching PyPI already?). On the other hand, once you have the coordinates, drawing them is kind of trivial in just about any GUI toolkit. (An alternative may be to have the user lay them out by dragging them with the mouse. Programming that is however probably a lot more work.) Sincerely, Albert From bearophileHUGS at lycos.com Mon Jan 28 18:48:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 28 Jan 2008 15:48:13 -0800 (PST) Subject: A question about osyco References: <606hucF1p0rptU1@mid.uni-berlin.de> Message-ID: <4e8bd7b3-29d2-4fcc-baad-7e6ecfe829c4@v4g2000hsf.googlegroups.com> Marc 'BlackJack' Rintsch: > Try calling the iterative one twice and measure the time of the second > call. IIRC psyco needs at least one call to analyze the function, so the > first call is not speed up. That's how Java HotSpot works, but Psyco is very different from HotSpot, and I think you are wrong. I don't exactly know the answer to the question of the OP, but I think the two functions are different: in the second function most time isn't spent in managing the xrange or in the assign, but in the sum between long ints, and Psyco can't speed up that operation (you need gmpy for that, and in certain tricky situations gmpy may even result slower, maybe when you use small numbers). Bye, bearophile From fredrik at pythonware.com Thu Jan 10 02:51:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 08:51:44 +0100 Subject: docstrings style question In-Reply-To: <13obcbumpitbe23@corp.supernews.com> References: <13obcbumpitbe23@corp.supernews.com> Message-ID: Steve Brown wrote: > I've got a series of modules which look like this: > > #************ > # > # Temperature Sense Test > # > #************ > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > > I don't like the duplicated information: But the comment is attractive, and > the docstring self.__doc__ is already in use in the test log. I've read that > all modules and classes should have docstrings, but I don't really have > anything else to say, and each module contains only one class. I don't think > that > > """Temperature Sense Test""" > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > would be a real improvement. > > What do you think? since you already seem to cater to your audience (clearly marked comments for people browsing the code, brief docstrings for the test log), I don't really see why you should change anything. > I've read that all modules and classes should have docstrings if nobody's going to read them, there's no reason to add them. don't treat generic style advice as dogma. From victorsubervi at gmail.com Mon Jan 28 10:21:55 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 28 Jan 2008 11:21:55 -0400 Subject: Unicode Problem Message-ID: <4dc0cfea0801280721h2e70c605p565b73bc6b6c4d87@mail.gmail.com> Hi; New to unicode. Got this error: Traceback (most recent call last): File "", line 1, in File "", line 29, in tagWords File "/usr/local/lib/python2.5/codecs.py", line 303, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 9: ordinal not in range(128) I think the problem comes from this code snippet: for line in sentences: print line tup = re.split(' ', line) for word in tup: for key, value in dictionary.items(): if key == word: word = word + '::' + value newLine.append(word) sentences.close() TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Jan 24 18:51:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jan 2008 00:51:47 +0100 Subject: creating .pyo with make In-Reply-To: <4798ddac$0$28813$426a74cc@news.free.fr> References: <4797c5d7$0$20781$426a34cc@news.free.fr> <4797c8d7$0$16956$426a74cc@news.free.fr> <5vq03cF1mod1jU1@mid.uni-berlin.de> <4798ddac$0$28813$426a74cc@news.free.fr> Message-ID: <5vsmknF1nnebqU2@mid.uni-berlin.de> Yann Leboulanger schrieb: > Diez B. Roggisch wrote: >> Yann Leboulanger schrieb: >>> Yann Leboulanger wrote: >>>> Hi, >>>> >>>> I use autoconf / automake to manage my python project, and I'l like >>>> make / make install to create / install .pyo files instead of .py >>>> files. >>>> >>>> Is there something I should add to my Makefile.am files to do that? >>>> Or should I do all that myself with py_compile module? >>>> >>>> Are there some examples somewhere with autotools? >>>> >>>> Thanks for your help >>> >>> Hehe replying to myself. It seems I just have to replace >>> project_DATA = $(srcdir)/*.py >>> by >>> project_PYTHON = $(srcdir)/*.py >>> >>> Then when I do make install, it installs .py, .pyc and .pyo. >>> Would it be possible to install only .pyo? Is it a good idea? >> >> There might be the occasional code that relies on doc-strings to work >> - seldomly, but possible. Which are obmitted by .pyo, but not of pyc. >> >> Apart from that, having only pyc-files (or pyo for that matter) sucks. >> Just today I had to delve into a ZOPE-application, setting breakpoints >> and getting things done. It would have been impossible or at least >> much more inconvenient to debug if I hadn't had the sources available >> (and put at a place where they actually get invoked from the >> interpreter, not lying around unrelated) >> >> Diez > > Source are available i ntarballs, but when I do make install I don't > care to install .py files. .pyo are enough to run the application. As I said - not installing them will make debugging for someone who knows how to deal with it just more inconvenient. And if you plan to release the code anyway - don't bother separating pyc/pyo from the py. Diez From musiccomposition at gmail.com Fri Jan 18 22:46:31 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 18 Jan 2008 19:46:31 -0800 (PST) Subject: Unique thread ID References: <217860be-8a5f-4187-9b54-8e7c94e768cd@v46g2000hsv.googlegroups.com> <97c1bc57-5caf-4fa5-96d7-f6847db9e18c@f10g2000hsf.googlegroups.com> Message-ID: <93fa9e1f-92c5-43de-af59-8db8c9b98174@u10g2000prn.googlegroups.com> On Jan 18, 8:31 pm, "Gabriel Genellina" wrote: > En Fri, 18 Jan 2008 22:41:47 -0300, Benjamin > escribi?: > > > On Jan 18, 2:31 am, Christian Heimes wrote: > >> Benjamin wrote: > >> > Is there a way to obtain a unique ID for the current thread? I have an > >> > object that I need to store local thread data in, and I don't want to > >> > use threading.local because each thread might have multiple instances > >> > of my object. > > >> threading.get_ident() but please use threading.local. Nobody is going to > >> stop you if you use a list or dict in threading.local. > > then, I have to figure out how to represent an instance of my object > > in threading.local. (The data also won't be garbage collect when my > > object is, will it?) I think the unique id is elegant in this case. > > I think you didn't get how threading.local works yet. It's a lot easier > than you imply. Just store your instances as attributes of a > threading.local object. You may use a list or dictionary if you want > multiple instances. > Read _threading_local.py, it contains a lot of examples. You're correct. I misread the documentation. I now understand how it works and am using it. Thanks for pointing me down the right path. > > -- > Gabriel Genellina From walterbyrd at iname.com Tue Jan 29 12:11:38 2008 From: walterbyrd at iname.com (walterbyrd) Date: Tue, 29 Jan 2008 09:11:38 -0800 (PST) Subject: Trying to understand Python web-development Message-ID: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com> I don't know much php either, but running a php app seems straight forward enough. Python seems to always use some sort of development environment vs production environment scheme. For development, you are supposed to run a local browser and load 127.0.0.1:5000 - or something like that. Then to run the same thing in a development environment, I have to configure some files, or touch all the files, restart the web-server, or something. Why is that? Python also seems to require some sort of "long running processes" I guess that the python interpretor has to running all of time. I am not really sure about what wsgi is supposed to accomplish. From solipsis at pitrou.net Tue Jan 8 04:46:34 2008 From: solipsis at pitrou.net (Antoine Pitrou) Date: Tue, 8 Jan 2008 09:46:34 +0000 (UTC) Subject: Passing contextual information when logging References: Message-ID: Hi Vinay, > I would welcome your views on whether the LoggerAdapter class is > suitable for adding to the logging package in Python 2.6/3.0. Does it > do what might reasonably be expected out of the box? I think it's quite suited to the problem, yes. One question : why does the exception() method call Logger.error() rather than Logger.exception() ? One suggestion : pass in a Logger object rather than a logger name to the LoggerAdapter constructor. (this also means that users could stack LoggerAdapter objects if they wanted to) Thanks Antoine. From andre.roberge at gmail.com Sun Jan 27 21:02:51 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 27 Jan 2008 18:02:51 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> Message-ID: On Jan 27, 9:47 pm, Steven D'Aprano wrote: > On Sun, 27 Jan 2008 19:13:27 -0500, Terry Reedy wrote: > > [snip] > > > class Test(object): > > @autoassign > > def __init__(self, _foo, _bar, baz): > > print 'baz =', baz > > [snip] > > > I think this version, with this name convention, is nice enough to > > possibly go in the stdlib if there were an appropriate place for it. > > Not sure where though. If there were a classtools module.... > > -1/2 > > I don't like the name convention. _name already has a perfectly good > convention: it's a private name, don't mess with it. That includes in > function/method signatures. With your convention, _foo is public. > > I suppose you could write __foo for a private name, and ___foo for a > *really* private name, relying on the decorator to strip one of the > underscores. But counting all those underscores is a PITA, and what > happens if you don't actually want that private name set as an instance > attribute? > > As nice as this feature would be, and I vote +2 on the functionality, I > wonder whether the amount of line noise in method definitions now will be > approaching Perlish levels? We've got default values, type annotations > (in Python3), *args and **kwargs, _ private names, and now we want to add > auto-assignment. > > If we do get syntax support, I vote +1 on &foo, +1/2 on @foo, -1 on .foo > and -1 on self.foo. (It's explicit, but it's long...). > > -- > Steven Here's a version that 1. does not require new syntax 2. does not *necessarily* override the "_" prefix convention 3. follows the "Explicit is better than implicit" convention when being called. (Note: I do not necessarily recommend the "self_" choice) ======== from functools import wraps from inspect import getargspec def autoassign(prefix): def _autoassign(_init_): @wraps(_init_) def __autoassign(self, *args, **kwargs): argnames, _, _, _ = getargspec(_init_) for name, value in zip(argnames[1:], args): if name.startswith(prefix): setattr(self, name[len(prefix):], value) _init_(self, *args, **kwargs) return __autoassign return _autoassign class Test(object): @autoassign('self_') def __init__(self, self_foo, self_bar, baz): print 'baz =', baz t = Test(1, 2, 3) print t.foo print t.bar print t.baz # raises an exception ============= Andr? From BjornSteinarFjeldPettersen at gmail.com Sun Jan 27 03:46:14 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 27 Jan 2008 00:46:14 -0800 (PST) Subject: Using a dict as if it were a module namespace References: <13podkpqqvef674@corp.supernews.com> Message-ID: <80e42440-e172-4c4d-8b83-9fcd43744be2@q77g2000hsh.googlegroups.com> On Jan 27, 8:45 am, Steven D'Aprano wrote: > I have a problem which I think could be solved by using a dict as a > namespace, in a similar way that exec and eval do. > > When using the timeit module, it is very inconvenient to have to define > functions as strings. A good alternative is to create the function as > normal, and import it: > > def myfunc(x, y): > return x+y > > timeit.Timer("myfunc(59, 60)", "from __main__ import myfunc").timeit() > > Not only is this an easy idiom to follow, but myfunc can live in another > module: just replace __main__ with the module name. > > Now, I'm trying to build a suite of tests to use with timeit. I have a > bunch of tests which I've created as dicts: > > test_suite= [dict(x=59, y=60), dict(x=-1, y=-2)] > > What I *think* I want to do is use the from ... import idiom to grab > arguments from the dicts as if they were modules, but this doesn't work: > > expr = "myfunc(x, y)" > for test in test_suite: > setup = "from __main__ import myfunc; from test import x, y" > t = timeit.Timer(expr, setup).timeit() > > Even if the Timer could see test, it is not a module and you can't import > from it. Naturally. > > Alternatives that I have found: > > (1) Import the test and grab the values needed from it: > > setup = """from __main__ import myfunc, test > x, y = test['x'], test['y']""" > > I don't like this one. It doesn't seem very elegant to me, and it gets > unwieldy as the complexity increases. Every item I need from test has to > be named twice, violating the principle Don't Repeat Yourself. If the > tests change, the setup string has to be explicitly changed also. > > (2) Mess with the global namespace: > > globals().update(t) > setup = "from __main__ import myfunc" > > I don't like this one. It looks hackish, and I worry about conflicts and > side-effects. If it works (and I haven't tested it) it relies on an > implementation detail of timeit.Timer.__init__, namely the line > "exec code in globals(), ns". Worst of all, it pollutes or even mangles > the global namespace of the calling code, not the code being tested. > > (3) Explicitly pass a namespace dict to the Timer class, possibly even > getting rid of setup altogether: > > test['myfunc'] = myfunc > t = timeit.Timer(expr, '', ns=test).timeit() > > This would be the most elegant solution, but at this time it is > completely hypothetical. Timer does not have that functionality. > > (4) Dump the test data straight into the setup string: > > setup = "from __main__ import myfunc; x = %(x)s; y = %(y)s" % t > > Again, unwieldy and against DRY. The additional disadvantage is that > there are many types of test data that can't be converted to and from > strings like that. > > What do others think? Have I missed something? What other alternatives > are there? > > -- > Steven You might have lost me, but wouldn't it be easier to do some variation on this test_suite = [ '(x=59, y=60)', # either have strings here... '(x=-1, y=-2)', ] for test in test_suite: # ... or convert the dicts to appropriate strings here... expr = 'myfunc' + test t = timeit.Timer(expr, 'from __main__ import myfunc').timeit() ... -- bjorn From sigpoggy at hotmail.com Sat Jan 26 02:08:34 2008 From: sigpoggy at hotmail.com (JimT) Date: Fri, 25 Jan 2008 23:08:34 -0800 Subject: wx.EVT_RIGHT_UP strangeness? Message-ID: <479adc74$0$5107$9a6e19ea@unlimited.newshosting.com> I'm playing with wxPython 2.8.7.1 on OS X 10.4.11 with MacPython 2.5 I ran the demo program found what may be a bug with the right mouse button up event. The demo is ShapedWindow.py. Everthing thing seems to work fine except that right clicking does not close the window. Tracing the program shows that the event never fires. Upon closer scrutiny I discovered if you bind the wx.EVT_RIGHT_DOWN event, the wx.EVT_RIGHT_UP now fires. I tried this in a couple programs and the behavior is consistent. Is this the way it is supposed to work? If not, am I the only one with this problem? From mr.cerutti at gmail.com Tue Jan 15 13:25:27 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Tue, 15 Jan 2008 13:25:27 -0500 Subject: Why this apparent assymetry in set operations? In-Reply-To: <5a3ace63-a8cf-4970-a95e-4243226fbac7@j20g2000hsi.googlegroups.com> References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> <5a3ace63-a8cf-4970-a95e-4243226fbac7@j20g2000hsi.googlegroups.com> Message-ID: <51302a8c0801151025g1ceca717i8f9995a9807d7074@mail.gmail.com> On Jan 15, 2008 12:06 PM, Chris M wrote: > On Jan 15, 11:51 am, "Neil Cerutti" wrote: > > > > So this is a bug in set_update or in set_ior. They can't both be > > right. > > > > It's not a bug. > > "Note, the non-operator versions of union(), intersection(), > difference(), and symmetric_difference(), issubset(), and issuperset() > methods will accept any iterable as an argument. In contrast, their > operator based counterparts require their arguments to be sets. This > precludes error-prone constructions like set('abc') & 'cbs' in favor > of the more readable set('abc').intersection('cbs')." Thanks. That neatly answers Skip's question, assuming he buys the putative error pronicity. The docs say the design is based on lessons learned from the sets module, so that also explains why it's different from the module version, as well. -- Neil Cerutti From dtgeadamo at yahoo.com Fri Jan 25 03:22:36 2008 From: dtgeadamo at yahoo.com (mistersexy) Date: Fri, 25 Jan 2008 00:22:36 -0800 (PST) Subject: Ideas for Python Programming Message-ID: <9daf42a0-90bf-4881-8c07-3851a2b3f564@c23g2000hsa.googlegroups.com> I have been programming in python for some time but I have become short of ideas. A software exhibition is coming up, and I plan to show python's worth 'cos it is quite underrated in this part of the world. Could anyone suggest any really good program ideas and information on how to implement them? I heartily welcome any good ideas. From Steven.Watanabe at autodesk.com Tue Jan 22 10:02:35 2008 From: Steven.Watanabe at autodesk.com (Steven Watanabe) Date: Tue, 22 Jan 2008 07:02:35 -0800 Subject: Don't want child process inheriting open sockets Message-ID: <800886C2A4A73E44BA0FE45152C023702503AD6561@ADSK-NAMSG-02.MGDADSK.autodesk.com> I'm using subprocess.Popen() to create a child process. The child process is inheriting the parent process' open sockets, but I don't want that. I believe that on Unix systems I could use the FD_CLOEXEC flag, but I'm running Windows. Any suggestions? -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Jan 11 17:29:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 11 Jan 2008 14:29:32 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> Message-ID: <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> On Jan 11, 2:57 pm, Paul Rubin wrote: > castiro... at gmail.com writes: > > Any ideas for a thread-safe list.removeall( X ): removing all > > occurrences of X within list L, when L might be modified concurrently? > > That way lies madness. Do something sensible instead. Put a lock > around the list, or put all mutators for the list into a single > thread, or whatever. Don't do what you're describing. This function just wants X out of the list. It doesn't matter if this happens before, during, or after something else; so long as it happens. From ajd at kring.com Tue Jan 22 23:37:15 2008 From: ajd at kring.com (Ajay Deshpande) Date: Wed, 23 Jan 2008 10:07:15 +0530 Subject: monitoring device status with python ... Message-ID: hi everyone: i am writing a program, which needs to keep monitoring whether a certain usb hard drive is connected/hot-plugged in or not. instead of repeatedly checking if its path exists or not, can i have the os let my program know that the device has been connected? i have read about the minihallib module but have not come across an elaborate example. can any of you point me to any examples (or alternatives)? id appreciate any help. regards, -ajay -------------- next part -------------- An HTML attachment was scrubbed... URL: From B.Ogryczak at addr.in.reply-to.invalid Sun Jan 20 10:39:35 2008 From: B.Ogryczak at addr.in.reply-to.invalid (Bart Ogryczak) Date: Sun, 20 Jan 2008 15:39:35 +0000 (UTC) Subject: Bug in __init__? References: Message-ID: On 2008-01-18, citizen Zbigniew Braniecki testified: > It's really a nice pitfall, I can hardly imagine anyone expecting this, AFAIR, it's described in Diving Into Python. It's quiet elegant way of creating cache. def calculate(x,_cache={}): try: return _cache[x] except KeyError: _cache[x] = result = _lotsa_slow_calculations(x) return result bart -- This signature is intentionally left blank. http://candajon.azorragarse.info/ http://azorragarse.candajon.info/ From fredrik at pythonware.com Thu Jan 3 17:21:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 23:21:27 +0100 Subject: choosing random dynamic port number In-Reply-To: <32e43bb70801031409o5d1dcd2at5a159339cd43ae52@mail.gmail.com> References: <32e43bb70801031409o5d1dcd2at5a159339cd43ae52@mail.gmail.com> Message-ID: Emin.shopper Martinian.shopper wrote: > Is there a good way to choose/assign random dynamic port numbers in python? > > I had in mind something like the following, but if multiple programs are > generating random port numbers, is there a way to check if a given port > number is already taken? > > def GenerateDynamicPortNumber(): > "Generate a random dynamic port number and return it." > # port numbers between 49152 to 65535 are dynamic port numbers > return 49152 + random.randrange(15000) def GenerateDynamicPortNumber(): return 0 (to get the actual number, use getsockname() on the socket after you've called "bind" on it) From fredrik at pythonware.com Tue Jan 8 05:57:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 Jan 2008 11:57:25 +0100 Subject: use fileinput to read a specific line In-Reply-To: References: Message-ID: Martin Marcher wrote: >> i need to read line 4 from a header file > > http://docs.python.org/lib/module-linecache.html I guess you missed the "using linecache will crash my computer due to memory loading, because i am working on 2000 files each is 8mb" part. From __peter__ at web.de Thu Jan 10 06:29:01 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jan 2008 12:29:01 +0100 Subject: Rebuild list of objects with redundancies on objects' attribute References: Message-ID: Nico Grubert wrote: > Hi there > > I have a list of dummy objects which have the attributes 'location', > 'name', 'gender'. > Now I want to rebuild this list in order to avoid redundancies on > objects with the same 'location'. > > Example: > > #------------------------------------------------------------------ > class Dummy: > pass > > a = Dummy() > a.location = 'tokio' > a.name = 'john' > a.gender = 'm' > > b = Dummy() > b.location = 'tokio' > b.name = 'peter' > b.gender = 'm' > > c = Dummy() > c.location = 'madrid' > c.name = 'susan' > c.gender = 'f' > > d = Dummy() > d.location = 'london' > d.name = 'alex' > d.gender = 'm' > > persons = [a, b, c, d] > > print "loc name gender" > print "---------------------" > for obj in persons: > print "%s - %s - %s" % (obj.location, obj.name, obj.gender) > > #------------------------------------------------------------------ > > The output reads like this: > > loc name gender > --------------------- > tokio john m > tokio peter m > madrid susan f > london alex m > > I want to create this list (where name and gender are lists): > loc name gender > ----------------------------- > tokio [john, peter] [m] > madrid [susan] [f] > london [alex] [m] > > How can I do this? Put the persons into a dictionary using the location as key from collections import defaultdict groups = defaultdict(list) for p in persons: groups[p.location].append(p) Below is a spoiler that uses itertools.groupby(), but you learn more if you try to work it out yourself ;) from itertools import groupby def location(p): return p.location persons.sort(key=location) print "loc name gender" print "---------------------" for loc, group in groupby(persons, key=location): group = list(group) genders = sorted(set(p.gender for p in group)) names = sorted(p.name for p in group) print "%s - %s - %s" % (loc, names, genders) Peter From dongie.agnir at gmail.com Wed Jan 9 14:11:39 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Wed, 9 Jan 2008 11:11:39 -0800 (PST) Subject: Python too slow? Message-ID: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> I'm pretty new to Python, and even newer to Image/Video processing, and trying to get started on a project similar to GRL Vienna's laser marker. I found some sample code here http://janto.blogspot.com/2006/01/motion-capture-in-python.html, but after running the code with the included sample input file, it seems quite slow (1-2 seconds from start to finish to do the 800 by 600 gif image). Is there a better way to do color tracking, or is Python just too slow as an interpreted language to do any effective color tracking? From casey at rodarmor.com Thu Jan 17 02:50:25 2008 From: casey at rodarmor.com (Casey Rodarmor) Date: Wed, 16 Jan 2008 23:50:25 -0800 Subject: Extending the readline module? Message-ID: Hi everyone, I'm writing a little curses-mode utility for renaming files using regexes, and I want to use GNU readline to get user input. However, it looks like the readline module doesn't support all of readline's functionality. I've looked around, and it looks like the best thing to do would be to try to extend the readline module myself to expose the functions I need. I'm exited to try to tackle the project, and it would be nice to get in touch with the maintainer of the module, so that I can get some advice and maybe try to get my additions included in the main branch. What is the best way to go about doing this? Best regards, Casey Rodarmor -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyrie at uh.cu Tue Jan 22 20:28:39 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 23 Jan 2008 01:28:39 +0000 Subject: translating Python to Assembler In-Reply-To: References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: <1201051719.479698475c99d@comuh.uh.cu> I second Wim's opinion. Learn python as a high level language, you won't regret it. About google, I'll give you a little gtip: > > For example a Google for "python.pdb" returns +python > > +pdb, so I get a ridiculous number of returns referring to the python > > debugger. I have mentioned this to Google several times, but I guess > > logic isn't one of their strong points. :-) Instead of searching 'python.pdb' try the query "filetype:pdb python", or even "python pdb" (quoted). The first one whould give you files with pdb extension and python in the name or contents, and the second one (quoted) should return pages with both words together, except for commas, spaces, dots, slashs, etc. However... one of the second query results is this thread in google groups... not a good sign. -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie Quoting Wim Vander Schelden : > Python modules and scripts are normally not even compiled, if they have > been, > its probably just the Python interpreter packaged with the scripts and > resources. > > My advice is that if you want to learn Python, is that you just read a book > about > it or read only resources. Learning Python from assembler is kind of... > strange. > > Not only are you skipping several generations of programming languages, > spanned > over a period of 40 years, but the approach to programming in Python is so > fundamentally different from assembler programming that there is simply no > reason > to start looking at if from this perspective. > > I truly hope you enjoy the world of high end programming languages, but > treat them > as such. Looking at them in a low-level representation or for a low-level > perspective > doesn't bear much fruits. > > Kind regards, > > Wim > > On 1/22/08, over at thepond.com wrote: > > > > My expertise, if any, is in assembler. I'm trying to understand Python > > scripts and modules by examining them after they have been > > disassembled in a Windows environment. > > > > I'm wondering if a Python symbols file is available. In the Windows > > environment, a symbol file normally has a PDB extension. It's a little > > unfortunate that Python also uses PDB for its debugger. Google, for > > whatever reason, wont accept queries with dots, hyphens, etc., in the > > query line. For example a Google for "python.pdb" returns +python > > +pdb, so I get a ridiculous number of returns referring to the python > > debugger. I have mentioned this to Google several times, but I guess > > logic isn't one of their strong points. :-) > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- "Al mundo nuevo corresponde la Universidad nueva" UNIVERSIDAD DE LA HABANA 280 aniversario From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 10:10:33 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 16:10:33 +0100 Subject: Basic inheritance question In-Reply-To: <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> Message-ID: <478e1e3e$0$18054$426a74cc@news.free.fr> Lie a ?crit : > On Jan 15, 9:00 pm, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Lie a ?crit : >> >> >> >>> On Jan 7, 2:46 am, Bruno Desthuilliers >>> wrote: >>>> Lie a ?crit : (snip) >>>>> No, seriously it isn't Java habits only, most other languages wouldn't >>>>> need explicit calling of class name. >>>> Where is the "explicit calling of class name" exactly ? >>> >>> Perhaps I was a bit tired when writing that (I wouldn't understand >>> what I wrote if I were you)... what I meant is most other languages >>> doesn't usually enforce us to explicitly state the containing class >>> name, which in python is generally called "self". >> >> 'self' (or whatever you name it) is not the "containing class name", > > Current instance is what I meant, thanks for pointing out the > incorrect term I used. > >> it's the first argument of the function - which usually happens to be >> the current instance when the function is used as a method. > > And that's the point, self (or anything you name it) is almost always > the current instance # this is a plain function. In this function, # 'obj' can be whatever that happens to have a (numeric) # 'stuff' attribute def func(obj, arg): return (obj.stuff + arg) / 2.0 # this is a class with an instance attribute 'stuff' class Foo(object): def __init__(self, bar): self.stuff = bar + 42 # this is another (mostly unrelated) class # with a class attribute 'stuff' class Bar(object): stuff = 42 # this is a dummy container class: class Dummy(object): pass # now let's play: import new d = Dummy() d.stuff = 84 print func(d, 1) d.baaz = new.instancemethod(func, d, type(d)) print d.baaz(2) f = Foo(33) print func(f, 3) Foo.baaz = func f.baaz(4) print func(Bar, 5) Bar.baaz = classmethod(func) Bar.baaz(6) > and that makes it functionally the same as Me and > this in VB and Java. Depends on the context, cf above !-) >>> Most other languages >>> 1) automatically assign the containing class' object >> s/containing class' object/current instance/ >> >>> in a keyword >>> (Java: this, VB: Me) behind the screen, > >> That's not very far from what a Python method object does - >> automatically assign the current instance to something. The difference >> is that Python uses functions to implement methods (instead of having >> two distinct contructs), so the only reliable way to "inject" the >> reference to the current instance is to pass it as an argument to the >> function (instead of making it pop from pure air). > > It isn't very far, but Python makes it obvious about the assignment > (not behind the screen). Exactly. And given both the simplicity of the solution and what it let you do, that's a *very* GoodThing(tm) IMHO. (snip) >>> and 2) automatically searches >>> variable name in both the local variable table and the containing >>> class variable table (so to refer to a class variable named var from a >>> method inside the class, we only need to write var, not self.var as in >>> python). >> This - as you know - cannot work well with Python's scoping rules and >> dynamicity. Anyway, implicit object reference is definitively a >> BadThing(tm) wrt/ readbility, specially with multiparadigm languages >> (like Python or C++). Why do you think soooo many C++ shops impose the >> m_something naming scheme ? > > Implicit object reference for the containing class has little harm, if > a class is so complex that there are more than 10 class-level > variable, then it is obvious that that class needs to be fragmented to > smaller classes. Not necessarily. There are general rules (like 'keep your classes small and focused', which I wholefully agree with), there are guidelines (like 'more than 10 member variables might smell like refactoring), and there's real life, where one very often faces classes that have much more than 10 member variables and still are as small and focused as possible. > Remembering less than 10 variable and avoiding naming > collision among just 10 variable is not hard (and 10 is really too > many, most classes should only use 2-4 variables), I really doubt you'll be able to write any working non-trivial software trying to strictly follow this rule. > especially if you > have a good IDE that employs Intellisense-like technology (IDLE has > it). IDLE is certainly not a "good IDE" in my book. > And it is always a Bad Thing(tm) to use the same name for two > variable in the class and in function (which is the main and only > source of possible ambiguity) in ANY language, even in Python. Ho, yes.... Like, this would be bad ? class Person(object): def __init__(self, firstname, lastname, birthdate, gender): self.firstname = firstname self.lastname = lastname self.birthdate = birthdate self.gender = gender C'mon, be serious. It's often hard enough to come with sensible names, why would one have to find synonyms too ? Try to come with something more readable than the above, and let us know. Seriously, this braindead rule about "not using the same name for an attribute and a local var" obviously comes from languages where the "this" ref is optional, and FWIW it's obviously the wrong solution to a real problem (the good solution being, of course, to use the fully qualified name for attributes so there's no possible ambiguity). >> Anyway, I actually know 3 languages (4 if C# works the same) that has >> this implicit 'this' (or whatever the name) 'feature', and at least 5 >> that don't. So I'm not sure that the "most other languages" qualifier >> really applies to point 2 !-) > > What's this 5 languages? Smalltalk, Python, PHP, javascript, Ruby. I don't remember how Scheme, CLOS and OCaml handle the case. > Are they a mainstream, high-level languages > or lesser known, low-level languages? C-family, Java, and Basic are > the Big Three of high-level programming language. None of C, C++, Java nor Basic qualify as "hi-level". C is the lowest possible level above assembly, C++ is often refered to as an "object oriented assembler", Java is way too static, crippled, verbose an unexpressive to qualify as "hi-level" (even if it suffers from some problems usually associated with higher level languages). I won't even comment on basic (is that really a language at all ?). >>> In VB, Me is extremely rarely used, >> I used to systematically use it - like I've always systematically used >> 'this' in C++ and Java. > > And that is what reduces readability. A proficient VB/C/Java > programmer There are quite a few proficient C/C++/Java programmers here. As far as I'm concerned, I would not pretend being one - I just have a good enough knowledge of C, Java and (alas) VB to be able to get up to speed in a reasonnable time frame. As a side note, the problem just doesn't exists in C, which has absolutely no support for OO. > would frown upon the extra, unneeded garbage as they > thought it was clear already that the variable refers to a class-level > variable. In C++, the canonical way to make this "clear" is to use the m_name convention. There must be some reason C++ programmers feel a need for this "extra, unneeded garbage" ?-) > It is a different story if, like Python, the use of self is > enforced by the language, the self wouldn't be viewed as extra > unnecessary garbage. >>> in Python, self is all >>> over the place. Well, there is positive and negative to both sides, >>> convenience in VB, and flexibility in Python. >> As far as I'm concerned, there's *no* positive point in implicit object >> reference, and there has never been (and before some paranoid nutcase >> around accuse me of overzealous biggotry : I already held this very same >> opinion years before I discovered Python). > > There is one major positive point: convenience and shorter code. > (isn't that two?) These are not rated as "positive" in my book. That's perhaps why Python is so far MFL ? > As I've pointed out, there is little harm in class-level variable's > implicit reference. Have some working experience on any non-trivial C++ project ? >>> Compare the following codes: >>> VB.NET: >>> Public Class A >>> Dim var >>> Public Function aFunction() >>> return var >> Add three levels of inheritence and a couple globals and you'll find out >> that readability count !-) > > It's the mental model that have to be adapted here, if the current > class is inheriting from another class, you've got to think it as > names from parent class as it is a native names, so you don't actually > need to know where the variable comes from In C++ (and VB IIRC), it might as well be a global So sorry but yes, I have to know where it comes from. > since knowing where it > comes from is breaking the encapsulation Nope, it's knowing what you're doing and how the piece of software at hand is working. And FWIW, while data hiding is one possible mean of encapsulation, it's by no way a synonym for encapsulation. > (which, in Python is very > weakly implemented, which favors flexibility in many cases[1]). > > [1] In Python, it is impossible to create a completely private > variable, which is the reason why the mental model of these other > languages doesn't fit Python. Never heard about the infamous '#define private public' hack in C++ ? And don't worry, there are also ways to get at so called 'private' vars in Java. >> In any non-trivial piece of C++ code, and unless the author either used >> the explicit 'this' reference or the 'm_xxx' naming convention, you'll >> have hard time figuring out where a given name comes from when browsing >> a function's code. > > If you're used to the implicit naming scheme it's easy to know where a > variable came from, if not the current scope, it's the class' scope You forgot the global scope. (snip) > As a final note: > I don't think implicit class reference is superior to explicit class > reference, neither do I think explicit class reference is superior to > implicit class reference. I think both have their own +s and -s. I > only pointed out that implicit do have its benefits, "benefit" here is a judgement call. It happens that neither I nor probably most of the people here share your judgement on this. Time for you to "import this" I'd say. > depending on the > language used (obviously Python wouldn't benefit from using implicit > behavior, due to it being extremely dynamic). Not only. This is also (and almost firstly as far as I'm concerned) a matter of readability. Anyway: this-dead-horse-been-beaten-to-hell-and-back... So if you *really* want to have the last word, I'll leave it to you !-) From nagle at animats.com Fri Jan 11 12:20:12 2008 From: nagle at animats.com (John Nagle) Date: Fri, 11 Jan 2008 09:20:12 -0800 Subject: Analyzing Python GC output - what is a "cell", and what information is available about it. In-Reply-To: References: <478707f2$0$36360$742ec2ed@news.sonic.net> Message-ID: <4787a42e$0$36403$742ec2ed@news.sonic.net> Duncan Booth wrote: > John Nagle wrote: > >> I'm printing out each entry in "gc.garbage" after a garbage collection in >> DEBUG_LEAK mode, and I'm seeing many entries like >> >> >> >> That's the output of "repr". Are "cell" objects created only from >> external C libraries, or can regular Python code generate them? Is there >> any way to find out what the 'function object' is from within Python? >> > Cell objects are created whenever you have a function that references a > variable in an outer scope. e.g. > > So in your case, cell.cell_contents.func_name might help. Tried that: print repr(item).encode('ascii','replace') print "Type:",type(item) try: print item.cell_contents except Exception, message: print "Unprintable:",message Type: Unprintable: 'cell' object has no attribute 'cell_contents' So it doesn't have a "cell_contents" attribute. Tried: print item.dir() got: 'cell' object has no attribute 'dir' Tried: print item.__dict__ got: 'cell' object has no attribute '__dict__' It looks like this is a low-level PyCellObject not generated from Python code. Any ideas? I'm using the M2Crypto and MySQLdb libraries, and suspect a reference count bug in one of those. John Nagle From erexsha at gmail.com Mon Jan 21 19:46:11 2008 From: erexsha at gmail.com (Arash Arfaee) Date: Mon, 21 Jan 2008 16:46:11 -0800 Subject: problem With Psyco on Wingide mac Message-ID: <266557d0801211646w1c9f7cd9r3a5bd19c360a57b0@mail.gmail.com> Hello All, I am trying to use psyco with wingide on mac. when I open Mac Python shell I can import psyco, but not inside the wingide. Even python shell on wingide cannot import psyco. Can anybody help me to solvethis problem? Thanks, Arash From ematus.tesis at gmail.com Fri Jan 4 08:11:13 2008 From: ematus.tesis at gmail.com (Eduardo Matus) Date: Fri, 4 Jan 2008 14:11:13 +0100 Subject: Scales question Message-ID: Hi all... I want to represent a point in 800 X 600 board in a 640 X 480 board..., for example (13, 50) in 640X480 to 800X600 so.. will be like this... Xscale = (13 * 800)/640 Xscale = 16.25 Yscale = (50 * 600)/480 Yscale = 62.5 what happend with the decimals??? I round up or down??? or there is another way to calculate this more accurate? Thks... -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigisbert.etra-id at grupoetra.com Thu Jan 3 02:27:43 2008 From: jigisbert.etra-id at grupoetra.com (Jose Ignacio Gisbert) Date: Thu, 3 Jan 2008 08:27:43 +0100 Subject: Manually installing PIL Message-ID: <001001c84dda$23d26760$2000a8c0@depid.local> Hello All, Does somebody install PIL manually??, I mean, copy directories manually without executing setup.py. I saw an identical message from Guirai, but I didn't see any response. Thanks in advance! Best Regards, Naxo -------------- next part -------------- An HTML attachment was scrubbed... URL: From Russ.Paielli at gmail.com Mon Jan 28 04:06:14 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jan 2008 01:06:14 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> <8763xe8vzd.fsf@benfinney.id.au> <87y7aa742r.fsf@benfinney.id.au> Message-ID: <4ba43e41-6218-4ccc-a738-9342758d6fb2@v46g2000hsv.googlegroups.com> On Jan 28, 12:21 am, Ben Finney wrote: > "Russ P." writes: > > OK, then how about a special function that could be called from > > inside the constructor (or anywhere else for that matter) to > > initialize a list of data members. For example, > > > self.__set__(host, port, protocol, bufsize, > > timeout) > > > This would be equivalent to > > > self.host = host > > self.port = port > > # etc. > > > I'm not sure if that is technically feasible, but it would cut down > > on repetition of names. > > It's much more attractive, because it doesn't change the function > signature. In fact, here's a variation that doesn't even need a > language change:: > > >>> class Foo(object): > ... def __init__(self, spam, eggs, beans): > ... self.__dict__.update(dict( > ... (name, value) for (name, value) in vars().items() > ... if name in ['spam', 'beans'])) > ... > >>> foo = Foo("some spam", "more eggs", "other beans") > >>> foo.spam > 'some spam' > >>> foo.eggs > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'Foo' object has no attribute 'eggs' > >>> foo.beans > 'other beans' > > -- > \ "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 If you can wrap that in a clean function that works for every class you might have something. From sgeiger at ncee.net Wed Jan 30 21:18:17 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 30 Jan 2008 20:18:17 -0600 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <47A11E78.7030003@tim.thechases.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> <47A11E78.7030003@tim.thechases.com> Message-ID: <47A12FE9.3020209@ncee.net> The answer is here: http://www.google.com/search?q=gene+expression+programming+python Tim Chase wrote: >> I do not understand why no one has answered the following question: >> >> Has anybody worked with Gene Expression Programming???? >> > > Well, my father's name is Gene, and he's expressed software wants > that I've implemented in Python...so yes, I guess I've done some > Gene Expression Programming... > > ;-P > > -tkc > > > -- 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 gneuner2/ at /comcast.net Sat Jan 12 21:16:22 2008 From: gneuner2/ at /comcast.net (George Neuner) Date: Sat, 12 Jan 2008 21:16:22 -0500 Subject: DEK's birthday References: <58762470-a68c-4fc5-af29-3d5fa06e8a4f@l1g2000hsa.googlegroups.com> Message-ID: On Sat, 12 Jan 2008 12:03:49 -0800 (PST), thermate2 at india.com wrote: >On Jan 10, 9:57?am, Jim wrote: >> DEK celebrates 70 today. >> >> I doubt he'll read this but I'll say it anyway: Happy Birthday! >> >> Jim Hefferon > >Donald Knuth is a son of a bitch who made a lot of money from tax >payer's grants. The computers he began with were built with tax >payer's money. > >His mother lived in the same newyork where the yank bastards staged >that fake drama > >letsroll911.org >stj911.org >scholarsfor911truth.org >nkusa.org >countercurrents.org >counterpunch.org > >and the bastard did not lift a finger, did not lift a pen in the >defense of the truth. > >may such bastard scholars burn in hell for ever and never know the >kingdom of heavan. > >Amen Why don't you play Hide And Go Fuck Yourself. From http Fri Jan 18 19:11:41 2008 From: http (Paul Rubin) Date: 18 Jan 2008 16:11:41 -0800 Subject: TopSort in Python? References: <0000161d@bossar.com.pl> <358cc5a3-300f-49ba-9857-2f0cd629a4df@i12g2000prf.googlegroups.com> Message-ID: <7x8x2meksi.fsf@ruckus.brouhaha.com> Paddy writes: > When I needed one I didn't know the name. I'm curious, how did you > know to look for the topological sort algorithm by name? It's a well known algorithm in computer science, described in any number of textbooks, for example probably http://projects.csail.mit.edu/clrs/ There is also a wikipedia article: http://en.wikipedia.org/wiki/topological_sorting From nodrogbrown at gmail.com Mon Jan 21 11:08:12 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Mon, 21 Jan 2008 08:08:12 -0800 (PST) Subject: eucledian dist calculations References: <87aff9a8-a9d8-4236-8a86-66aa58417792@i72g2000hsd.googlegroups.com> <13c59b0c-534a-4a4a-bad3-f6f51721ab78@n20g2000hsh.googlegroups.com> Message-ID: <8f7c5035-cb02-4ab2-83af-30c605194c17@l1g2000hsa.googlegroups.com> > > 1. 'temp' is not used > 2. Lose the superfluous parentheses in 'if' statements > 3. Put space around operators > 4. I've never used any of numpy & friends, but: > (a) Can't you replace the inner loop with something like this: > distance = abs(input_weight - weights[image, :]) > (b) I doubt that you need the .copy() > 5. Lose the hard-wired numbers like 30 and 100 > 6. Put it inside a function and *TEST* it > thanx John , will go thru those and do the cleanup gordon From nytrokiss at gmail.com Sun Jan 6 08:48:08 2008 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 6 Jan 2008 14:48:08 +0100 Subject: Killing worker threads In-Reply-To: References: Message-ID: <8a6b8e350801060548m6f39594che1207cc5bc4b6487@mail.gmail.com> You can use the stop method! On Jan 6, 2008 2:04 PM, tarun wrote: > Hello All, > > Can anyone help me with a simple code through which the main thread can > kill the worker thread it started. > > Thanks & Regards, > Tarun Devnani > > -- > 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 bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 03:57:05 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 09:57:05 +0100 Subject: python recursive function In-Reply-To: References: Message-ID: <47872f56$0$21435$426a74cc@news.free.fr> Gary Herron a ?crit : > Tom_chicollegeboy wrote: >> here is what I have to do: >> >> This question involves a game with teddy bears. The game starts when I >> give you some bears. You then start giving me back some bears, but you >> must follow these rules (where n is the number of bears that you >> have): >> > This sounds very much like a homework assignment, Indeed. > and so should probably > not be answered here. (Neither should it have been asked here.) If, > in your attempt to write this program, you have some questions about > Python, then I encourage to ask those questions here. Garry, you should have read the whole post before answering. The OP's attempt at solving the problem was below, along with the question. (snip) From ivan at 0x4849.net Fri Jan 11 12:46:29 2008 From: ivan at 0x4849.net (Ivan Novick) Date: Fri, 11 Jan 2008 09:46:29 -0800 (PST) Subject: reading a specific column from file References: Message-ID: <4fb9145b-6930-4d89-a4a3-ddd3504373aa@e23g2000prf.googlegroups.com> On Jan 11, 4:15 am, cesco wrote: > Hi, > > I have a file containing four columns of data separated by tabs (\t) > and I'd like to read a specific column from it (say the third). Is > there any simple way to do this in Python? You say you would like to "read" a specific column. I wonder if you meant read all the data and then just seperate out the 3rd column or if you really mean only do disk IO for the 3rd column of data and thereby making your read faster. The second seems more interesting but much harder and I wonder if any one has any ideas. As for the just filtering out the third column, you have been given many suggestions already. Regards, Ivan Novick http://www.0x4849.net From bret.wortman at gmail.com Wed Jan 23 08:58:05 2008 From: bret.wortman at gmail.com (Bret) Date: Wed, 23 Jan 2008 05:58:05 -0800 (PST) Subject: A global or module-level variable? References: <7637fd0b-961e-4730-abd8-96e85c907082@i72g2000hsd.googlegroups.com> <7xwsq1tyts.fsf@ruckus.brouhaha.com> Message-ID: <63002d69-7738-4cae-bfb5-b933f16591b8@t1g2000pra.googlegroups.com> On Jan 22, 1:00 pm, Paul Rubin wrote: > If you have to do it that way, use: Is there a better way? A more Pythonic way? From martin at v.loewis.de Sun Jan 13 12:51:06 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 13 Jan 2008 18:51:06 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801131928.54459.donn.ingle@gmail.com> References: <200801131550.50119.donn.ingle@gmail.com> <478A4408.2090805@v.loewis.de> <200801131928.54459.donn.ingle@gmail.com> Message-ID: <478A4F8A.5010108@v.loewis.de> > What happens if there is a filename that cannot be represented in it's > entirety? i.e. every character is 'replaced'. Does it simply vanish, or does > it appear as "?????????" ? :) The latter. I did open(u"\u20ac\u20ac","w") in an UTF-8 locale, then did "LANG=C ls", and it gave me ?????? (as the two characters use 6 bytes) > I spent an hour trying to find a single file on the web that did *not* have > (what seemed like) ascii characters in it and failed. Even urls on Japanese > websites use western characters ( a tcp/ip issue I suspect). Actually, an HTTP and URL issue. Non-ASCII URLs aren't really supported in the web. > I was hoping to > find a filename in Kanji (?) ending in .jpg or something so that I could > download it and see what my system (and Python) made of it. Use a text editor instead to create such a file. For example, create a new document, and save it as "????.txt" (which Google says means "casestudies.txt") Regards, Martin From gagsl-py2 at yahoo.com.ar Sun Jan 20 21:58:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 00:58:45 -0200 Subject: dynamic type variable References: <47940570.6080003@block.duxieweb.com> Message-ID: En Mon, 21 Jan 2008 00:37:36 -0200, J. Peng escribi?: > Python's variable is dynamic type,is it? No. Python has objects, and names that refer to those objects. Objects have a type, which can't change once the object is created. But a name may refer to different objects of different types at different times. See http://effbot.org/zone/python-objects.htm > But why this can't work? > >>>> 3 + 'a' > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > > So I see the number 3 can't be converted to string type automacially. Python never "converts" anything, except numeric types in expressions (2+3.0, sqrt(5L)) and sometimes string/unicode. -- Gabriel Genellina From lists at cheimes.de Thu Jan 17 01:59:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 17 Jan 2008 07:59:05 +0100 Subject: assigning values in python and perl In-Reply-To: <34e2dc93-9819-479f-a8d5-79d11350f0b3@s8g2000prg.googlegroups.com> References: <2d37f441-c01f-439b-9897-35b7e4dfa77b@h11g2000prf.googlegroups.com> <34e2dc93-9819-479f-a8d5-79d11350f0b3@s8g2000prg.googlegroups.com> Message-ID: George Sakkis wrote: > Posting a counter-example where the difference is clearly shown would > be more vastly useful than referring to a list of long obscure usenet > posts with practically no examples. C/C++ are not even mentioned in > that page. I am not claiming you are wrong, I just don't find > particularly this page particularly enlightening. I don't find a posting like "It's call-by-reference, but in fact it's doesn't behave like call-by-reference" helpful. The text explains Python's calling convention on a CS level. Please trust me that the explanation on the site is right. It was written by somebody who designed and wrote parts of Python. Christian From sylvain.thenault at logilab.fr Mon Jan 14 08:59:29 2008 From: sylvain.thenault at logilab.fr (Sylvain =?iso-8859-1?Q?Th=E9nault?=) Date: Mon, 14 Jan 2008 14:59:29 +0100 Subject: [ANN] pylint 0.14 / logilab-astng 0.17.2 Message-ID: <20080114135929.GD22982@logilab.fr> Hi there! I'm pleased to announce a new release of pylint [1] and logilab-astng [2]. I haven't personally found a lot of time to work on those projects since the latest releases but others contributors have and so I decided to publish releases including various contributions and other minor bug or crash fixes (some of which were pending for a while now). You're greatly encouraged to upgrade, see projects'changelog for more information about what changed. [1] http://www.logilab.org/projects/pylint [2] http://www.logilab.org/projects/logilab-astng Many thanks to every people who contributed! regards, -- Sylvain Th?nault LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science From khoard at gmail.com Sat Jan 19 08:48:23 2008 From: khoard at gmail.com (FireNWater) Date: Sat, 19 Jan 2008 05:48:23 -0800 (PST) Subject: Core Python Programming . . . References: <7xir1q29j5.fsf@ruckus.brouhaha.com> Message-ID: <0005f532-409b-4c4e-8483-b2e32bbc724a@q77g2000hsh.googlegroups.com> On Jan 18, 6:00 pm, Yu-Xi Lim wrote: > Mike Driscoll wrote: > > > 6-11 Conversion. > > (a) Create a program that will convert from an integer to an > > Internet Protocol (IP) address in the four-octet format of WWW.XXX.YYY.ZZZ > > (b) Update your program to be able to do the vice verse of the > > above. > > I think it's is asking to convert a 32-bit int to the dotted form. > > It's a little known fact, but IP addresses are valid in non-dotted > long-int form. Spammers commonly use this trick to disguise their IP > addresses in emails from scanners. I guess I'm not fully up to speed on what constitutes an IP address. Does the term 'octet' refer to an 8-bit (xFF) number? From paddy3118 at googlemail.com Fri Jan 18 04:21:57 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 18 Jan 2008 01:21:57 -0800 (PST) Subject: array and list References: <24f854eb-93a8-414d-a518-842bb2d185fb@s13g2000prd.googlegroups.com> Message-ID: On Jan 18, 8:18 am, "J. Peng" wrote: > > On Jan 18, 3:23 am, "J. Peng" wrote: > > >> what's the difference between an array and a list in python? > >> I see list has all features of array in C or perl. > >> so please tell me.thanks. > > > If you are new to Python, then where other languages may reach for an > > 'array', Python programs might organise data as lists. Lists are used > > much more than arrays in Python. you should find that is the case in > > tutorials/books too. > > >http://wiki.python.org/moin/PerlPhrasebook?highlight=%28perl%29 > > > - Paddy. > > Hi, > > From Core Python Programming book (btw I like this book) I know the > difference is that array can hold only one type (the C standard?), but > list can hold every type of object. But hmm, perl's array also can hold > every type of variables, why perl call it array and python call it list? Similar ideas, different names. It happens. I guess 'under the hood' Python (& Perl?), arrays might be more like an implementation of what the C programmer might call a linked list, but even then there are differences as most linked list examples given in C tutorials are lists of the same type of object,.... - Paddy. > Also, if I understand it correctly, python's tuple is called as 'list' > in perl, so I'm somewhat confused about them. > > > P.S. if you know Perl then try: > > Yes I know some Perl. I have registered module on CPAN. > > thanks! From nyamatongwe+thunder at gmail.com Thu Jan 31 18:39:16 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Thu, 31 Jan 2008 23:39:16 GMT Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> <13q2960err4db28@corp.supernews.com> Message-ID: Steve Holden wrote: > ... > Look guys, I thought we'd agreed that the PSU was no longer to be How did Steve manage to click send again after the para From jairtrejo at yahoo.com.mx Wed Jan 2 14:19:16 2008 From: jairtrejo at yahoo.com.mx (Jair Trejo) Date: Wed, 2 Jan 2008 13:19:16 -0600 (CST) Subject: Python-list Digest, Vol 52, Issue 19 In-Reply-To: Message-ID: <548872.65181.qm@web52202.mail.re2.yahoo.com> > > De: Fredrik Lundh > A: python-list at python.org > Fecha: Wed, 02 Jan 2008 15:39:11 +0100 > Asunto: Re: PyCairo, PIL and StringIO > > Jair Trejo wrote: > > > I'm doing some image processing in PIL, and I want > to > > display the results in a GTK window using PyCairo, > so > > I create a Cairo image surface from the PIL Image > like > > this: > > data > > mfile = StringIO.StringIO() > > final.save(mfile, format="PNG") > > ima = > > cairo.ImageSurface.create_from_png(mfile) > > mfile.close() > > return ima > > > > Where final is a PIL image. The problem is, I get > a > > IOError: error while reading from Input Stream. > > > > ?Any idea of why is this happening? > > "save" leaves the file pointer at an undefined > position (usually at the > end), so my guess is that you have to rewind the > file before you pass it > to the next function: > > final.save(mfile, format="PNG") > mfile.seek(0) # rewind > > also note that compressing and decompressing will > introduce unnecessary > overhead; chances are that you might get a lot > better performance if you > just shuffle the raw pixels. I haven't used PyCairo > myself, but from a > quick look at the ImageSurface documentation, > something like this should > work (untested): > > if final.mode != "RGB": > final = final.convert("RGB") > w, h = final.size > data = final.tostring() # get packed RGB buffer > ima = cairo.ImageSurface.create(data, > FORMAT_RGB24, w, h, w*3) > > (tweak as necessary) > > Thank, you, it worked! I tried rewinding the file, and it worked OK. But you were right about performance issues, so I tweaked your code and left it as: from array import array ... w,h = final.size data=array('c') data.fromstring(final.tostring()) ima=cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32,w,h,w*4) return ima Which is around 10 times faster. The problem is, it swaps the R and B bands. I could probably write my own Image.tostring(), but i found it more convenient to swap the channels before processing, and it worked just fine. ____________________________________________________________________________________ ?Capacidad ilimitada de almacenamiento en tu correo! No te preocupes m?s por el espacio de tu cuenta con Correo Yahoo!: http://correo.yahoo.com.mx/ From paddy3118 at googlemail.com Mon Jan 28 02:13:14 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 27 Jan 2008 23:13:14 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: Message-ID: On Jan 27, 5:06 pm, coldpizza wrote: > There is a pattern that occurs fairly often in constructors in Python > and other OOP languages. > > Let's take an example: > > class Server(object): > def __init__(self, host, port, protocol, bufsize, timeout): > self.host = host > self.port = port > self.protocol = protocol > self.bufsize = bufsize > self.maxthreads = maxthreads > self.timeout = timeout > > Imho, in the class above the assignment to instance fields does not > contain much programming logic and therefore can be safely 'abstracted > away' by the language itself with a syntax which would look something > like this: > > class Server(object): > def __init__(self, @host, @port, @protocol, @bufsize, @timeout): > pass > > This would be equivalent to the first example above, yet it does not > obfuscate the code in any way. Or does it? It does look much cleaner > to me. > > Of course, the ampersand is just an arbitrary choice and might have > bad connotations for those who read it as 'take address of' but @ has > some allusion to delegates which maybe is ok. > > I am not an experienced programmer and I am not sure if this is > necessarily a good idea, so I wanted to get some feedback from more > experienced Pythonistas before submitting it elsewhere. Is it not possible to write a function that queries its call stack when run to find the name of all arguments and locals() of the level above so you could write: class test(object): def __init__(self, x, y): arg2inst() and automatically assign self.x=x; self.y=y ? It could be extended so that... class test(object): def __init__(self, x, y): arg2inst("x") ... then only assigns x. Has anyone seen something like this in the cookbook? - Paddy. From http Mon Jan 14 18:15:28 2008 From: http (Paul Rubin) Date: 14 Jan 2008 15:15:28 -0800 Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> <7xsl105fvv.fsf@ruckus.brouhaha.com> <13onli9dk7mu926@corp.supernews.com> Message-ID: <7xhchgatin.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > map = {'a': Aclass, 'b': Bclass, 'c': Cclass} > class_ = map.get(astring, default=Zclass) > > The result I want is the class, not the result of calling the class > (which would be an instance). If I wanted the other semantics, I'd be > using defaultdict instead. I used default as a keyward arg name indicating the presence of a callable. I probably should have called it defaultfunc or something. x = d.get('a', f) # --> default value is f x = d.get('a', defaultfunc=f) # --> default value is result of f() . From mario at ruggier.org Thu Jan 3 09:33:42 2008 From: mario at ruggier.org (mario) Date: Thu, 3 Jan 2008 06:33:42 -0800 (PST) Subject: unicode(s, enc).encode(enc) == s ? References: <5e49e7e6-f2b3-4c9f-9dec-e5f01f12d59a@e4g2000hsg.googlegroups.com> <4773f0de$0$15825$9b622d9e@news.freenet.de> <7cb20641-ab33-4818-a911-80c684cb9792@q77g2000hsh.googlegroups.com> <4775AC6B.8070109@v.loewis.de> <1310677e-51ec-49f2-9709-196dcc4e1ac9@e4g2000hsg.googlegroups.com> <477BF54E.7090000@v.loewis.de> Message-ID: Thanks again. I will chunk my responses as your message has too much in it for me to process all at once... On Jan 2, 9:34 pm, "Martin v. L?wis" wrote: > > Thanks a lot Martin and Marc for the really great explanations! I was > > wondering if it would be reasonable to imagine a utility that will > > determine whether, for a given encoding, two byte strings would be > > equivalent. > > But that is much easier to answer: > > s1.decode(enc) == s2.decode(enc) > > Assuming Unicode's unification, for a single encoding, this should > produce correct results in all cases I'm aware of. > > If the you also have different encodings, you should add > > def normal_decode(s, enc): > return unicode.normalize("NFKD", s.decode(enc)) > > normal_decode(s1, enc) == normal_decode(s2, enc) > > This would flatten out compatibility characters, and ambiguities > left in Unicode itself. Hmmn, true, it would be that easy. I am now not sure why I needed that check, or how to use this version of it... I am always starting from one string, and decoding it... that may be lossy when that is re-encoded, and compared to original. However it is clear that the test above should always pass in this case, so doing it seems superfluos. Thanks for the unicodedata.normalize() tip. mario From teddyber at gmail.com Fri Jan 11 17:30:34 2008 From: teddyber at gmail.com (teddyber) Date: Fri, 11 Jan 2008 14:30:34 -0800 (PST) Subject: split parameter line with quotes References: Message-ID: <37fac828-20ec-4cb9-8ea7-a85cce7d3e91@k39g2000hsf.googlegroups.com> wow! that's perfect this shlex module! thanks for pointing this! On 11 jan, 20:36, Joshua Kugler wrote: > teddyber wrote: > > first i'm a newbie to python (but i searched the Internet i swear). > > i'm looking for some way to split up a string into a list of pairs > > 'key=value'. This code should be able to handle this particular > > example string : > > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > > i know i can do that with some regexp (i'm currently trying to learn > > that) but if there's some other way... > > Take a look at the shlex module. You might be able to fiddle with the shlex > object and convince it to split on the commas. But, to be honest, that > above would be a lot easier to parse if the dividing commas were spaces > instead. > > j From pavlovevidence at gmail.com Sat Jan 26 00:03:43 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 25 Jan 2008 21:03:43 -0800 (PST) Subject: Generational Interfaces Message-ID: <1b7b3b47-72f0-4a5d-9185-4903e75dba47@d70g2000hsb.googlegroups.com> While thinking about generational garbage collection, the thought of generational interfaces occurred to me. I'd thought I'd run it by you guys. I'm curious if there are any examples of this out there. I've opined on this chat room before that interfaces are more often cumbersome than helpful, especially in the early stages of a project where lots of refactoring is (or ought to be) happening. But as projects mature, interfaces do too, and that made me think interfaces could be generated automatically by monitoring the software over time. As an example, say I'm writing a flight simulator, and I have a abstract base class Airplane, that I want to have an interface someday, but I don't know what it is yet. So I define an AirplaneInterface = InterfaceTracker("Airplane") What this does is to open a sort of persistent database called Airplane (details aren't important now). The database tracks all objects that claim to implement the interface. So say the first airplane is a Piper Cherokee. I'd write a class like this: class PiperCherokeeX1(object): wingspan = 52.2 wingchord = 7.9 ... def __init__(self): self.x = 0.0 self.y = 0.0 self.z = 0.0 ... set_up_initial_state() ... AirplaneInterface.report(self) def move_stick(self,dx,dy): ... def move_thottle(self,ds): ... def move_rudder_pedals(self,ddr): ... def camera_matrix(self): return self._quat_to_matrix(self.q0,self.q1,self.q2,self.q3) def step(self,dt): ... The key here is the call to AirplaneInterface.report() at the end of __init__; this tells the interface tracker that, as of this call, this object is implementing the Aircraft interface. At this point, the interface tracker notes that PiperCherokeeX1 object has certain methods (move_stick, move_throttle, etc), certain class attributes, and certain instance attributes. And that's all it does-- at first. It just writes information into the database. As time passes, and development continues, methods and data are added, changed, reconfigured. For instance, I might split up move_stick() into move_stick_x() and move_stick_y() for some reason. Then I might get rid of these functions altogether in favor of a move_control(self,n,dx). And so on. I add more classes that implement the Aircraft interface, too. They look almost nothing like the original interface. However, through all that, the class attribute "wingspan" remains there. Until one day when the project is quite mature I add a new class, say Airbus380, that fails to define "wingspan". When this class calls AirplaneInterface.report(), it raises an InterfaceException. Basically, the InterfaceTracker decides, after some threshold of nearly universal usage of a certain method or attribute, that it has become a required part of the interface and starts raising exceptions when it's not there. Make sense? Details can vary, but that's the basic idea. In this way, you can combine some of the openness that helps in early development, but also have some of the benefits of stricter typing when things mature and turn out to be pretty strictly useful, without much effort. Thoughts? (Surely someone's thought to do this before.) Carl Banks From andymac at bullseye.apana.org.au Sat Jan 5 05:47:49 2008 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 05 Jan 2008 20:47:49 +1000 Subject: Memory Leaks and Heapy In-Reply-To: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> Message-ID: <477F6055.9050208@bullseye.andymac.org> Yaakov Nemoy wrote: > A couple of developers have mentioned that python might be fragmenting > its memory space, and is unable to free up those pages. How can I go > about testing for this, and are there any known problems like this? > If not, what else can I do to look for leaks? Marc-Andre brought up pymalloc, but it is worth clarifying a couple of issues related to its use: - pymalloc only manages allocations up to (and including) 256 bytes; allocations larger than this are passed to the platform malloc to allocate. - the work that was put in to allow return of empty arenas (in Python 2.5) was geared to handling the general case of applications that created huge volumes of objects (usually at start up) and then destroy most of them. There is no support that I'm aware of for any form of arena rationalisation in the case of sparsely occupied arenas. - it has been my experience that pymalloc is a significant benefit over the platform malloc for the Python interpreter, both in terms of performance and gross memory consumption. Prior to defaulting to using pymalloc (as of 2.3) CPython had run into issues with the platform malloc of just about every platform it had been ported to, heap fragmentation being particularly notable on Windows (though other platforms have also been subject to this). While pymalloc is highly tuned for the general case behaviour of the Python interpreter, just as platform malloc implementations have corner cases so does pymalloc. Be aware that ints and floats are managed via free lists with memory allocation directly by the platform malloc() - these objects are never seen by pymalloc, and neither type has support for relinquishing surplus memory. Be also aware that many C extensions don't use pymalloc even when they could. In addition to Marc-Andre's suggestions, I would suggest paying particular attention to the creation and retention of objects in your code - if something's no longer required, explicitly delete it. It is all too easy to lose sight of references to objects that hang around in ways that defeat the gc support. Watch out for things that might be sensitive to thread-ids for example. Careful algorithm planning can also be useful, leveraging object references to minimise duplicated data (and possibly get better performance). -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From rowen at cesmail.net Fri Jan 25 19:49:16 2008 From: rowen at cesmail.net (Russell E. Owen) Date: Fri, 25 Jan 2008 16:49:16 -0800 Subject: Problem with Tkinter scrollbar callback References: Message-ID: In article , "Ivan Van Laningham" wrote: > Hi All-- > That helps. Doing a get() on the scrollbar before a set(0.0,0.0) > returns a 4-tuple: (0.0, 0.0, 0.0, 0.0) ! I did the set(0.0,0.0) > and now the callback gets the correct number of arguments. > > However, I'm still getting the weird behaviour when clicking the > arrowheads--and the heads are all I want. They act like they've been > set to a keybounce timeout of about a millisecond. ... The arrow > click increments the number of cells in a table row (effectively), and > it shoots up from 5 to 26 columns almost instantly (that's the > internal max I set). Is the scroll bar's repeatinterval set to a reasonable value? -- Russell From grante at visi.com Sat Jan 5 12:28:34 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 05 Jan 2008 17:28:34 -0000 Subject: Question on os.tempnam() vulnerability References: <13nt81gftkfa32d@corp.supernews.com> <13nv5m68qeknk1f@corp.supernews.com> <477FA9B5.9050609@v.loewis.de> <13nvb525r3m6m39@corp.supernews.com> Message-ID: <13nvfi2nu3erpd5@corp.supernews.com> On 2008-01-05, Fredrik Lundh wrote: > Grant Edwards wrote: > >>> IOW, it's the same approach as on Unix. >> >> Not really. Under Unix you can safely create a temp file with >> a name that can be used to open the file. > > Unless I'm missing something, it's not possible to do this in a safe > way in the shared temp directory; you can do that only by creating a > file in a directory that's under full control of your user. Which is what I do. > And *that* approach works on Windows as well, of course. I was asking how to create a named temporary file under Windows without a race condition. I've re-read the tempfile module documentation a couple more times, and it finally dawned on me that I'd been misreading the following statement about tempfiles created by NamedTemporaryFile/mkstemp: "Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later)." I don't know how many times I've read that and missed the phrase "while the named temporary file is still open". I had always read that as saying that the tempfile couldn't be opened a second time under Windows. I know, that would make the availability of the path/name a moot point, but so many things under Windows don't make sense to me that I just let it slide. As Emily Litella used to say: "Oh. That's very different. Never mind." -- Grant Edwards grante Yow! It's hard being at an ARTIST!! visi.com From nanjundi at gmail.com Thu Jan 10 17:06:49 2008 From: nanjundi at gmail.com (Nanjundi) Date: Thu, 10 Jan 2008 14:06:49 -0800 (PST) Subject: Newbie question on Classes References: Message-ID: <8cf64cf7-d38c-4239-b188-b0b861407512@j78g2000hsd.googlegroups.com> On Jan 10, 4:46 pm, "Adrian Wood" wrote: > Hi al! I'm new to the list, and reasonably new to Python, so be gentle. > > Long story short, I'm having a hard time finding a way to call a > function on every object of a class at once. Example: > > I have a class Person, which has a function state(). This prints a > basic string about the Person (position, for example). In the program, > I have created two objects of class Person, called man and woman. > > I can call man.state() and then woman.state() or Person.state(man) and > Person.state(woman) to print the status of each. This takes time and > space however, and becomes unmanageable if we start talking about a > large number of objects, and unworkable if there is an unknown number. > What I'm after is a way to call the status of every instance of Man, > without knowing their exact names or number. > > I've gone through the relevant parts of the online docs, tried to find > information elsewhere online, and looked for code samples, but the > ionformation either isn't there, or just isn't clicking with me. I've > tried tracking the names of each object in a list, and even creating > each object within a list, but don't seem to be able to find the right > syntax to make it all work. > > I'd appreciate anyone who could help, especially if they could include > a short sample. My apologies if I'm not following the etiquette of the > group in some way my making this request. > > Thank you, > Adrian Hi Adrian, One easy way, is to append the objects to a list, as you have mentioned and call the state method in iteration. l = [] l.append(man) l.append(woman) # Print the state. for item in l: print item.state() (If I understood right, man and woman qualifies as "every instance of man") -N From guptaabhishek1983 at gmail.com Tue Jan 29 05:29:30 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Tue, 29 Jan 2008 02:29:30 -0800 (PST) Subject: Error in parsing XML for following test data Message-ID: Hello group, I am having problem parsing following data set from XML. Please provide hints on how to rectify this problem. I am using python2.4 version this is te test data that i am using -- """"""" 1!!!!!!!!!!!!!!!11 2@@@@@@@@@@@@@@@22 3###############33 4$$$$$$$$$$$$$$$44 5%%%%%%%%%%%%%%%55 6^^^^^^^^^^^^^^^66 7&&&&&&&&&&&&&&&77 8***************88 9(((((((((((((((99 10)))))))))))))))00 11----------------- 12================= 13+++++++++++++++++ 14||||||||||||||||| 15\\\\\\\\\\\\\\\\\ 16<<<<<<<<<<<<<<<<< 17>>>>>>>>>>>>>>>>> 18///////////////// 19????????????????? 20;;;;;;;;;;;;;;;;; 21::::::::::::::::: 22''''''''''''''''' 23""""""""""""""""" 24[[[[[[[[[[[[[[[[[ 25]]]]]]]]]]]]]]]]] 26{{{{{{{{{{{{{{{{{ 27}}}}}}}}}}}}}}}}} 28***************** 29+++++++++++++++++ 30----------------- 31````````````````` 32~~~~~~~~~~~~~~~~~ 33................. Special Characters #!/bin/bash #start TG app cd $1 exec ./start-infopsyM.py """"""" This is really a nasty data set. From bernard.chhun at gmail.com Thu Jan 31 16:00:03 2008 From: bernard.chhun at gmail.com (Bernard) Date: Thu, 31 Jan 2008 13:00:03 -0800 (PST) Subject: sending a handmade SOAP request References: <21d3ff54-d20f-45dd-951b-0508682fc472@e6g2000prf.googlegroups.com> Message-ID: <56762aa1-1160-4e4c-b0fa-6f38b455154f@i7g2000prf.googlegroups.com> On 31 jan, 15:23, Van Gale wrote: > Yes, it's quite easy to SOAP by hand. > > I use Oren Tirosh's ElementBuilder class (on top of lxml instead of > ElementTree) to build the SOAP request and the xpath capabilities in lxml > to pull out the data I need from the response. > > http://www.tothink.com/python/ElementBuilder/http://codespeak.net/lxml/ > > An incomplete example for contructing a request looks something like this: > > body = Element('soap:Envelope', > { 'xmlns:soap': nss['soap']}, > Element('soap:Header'), Element('soap:Body', > { 'xmlns:msgs': nss['msgs'] }, > Element('msgs:login', > Element('msgs:passport', > { 'xmlns:core': nss['core'] }, > Element('core:password', password), > Element('core:account', account))))) > > I use httplib2 for sending the HTTP requests: > > http://code.google.com/p/httplib2/ > > Incomplete example: > > headers['SOAPAction'] = action > headers['Content-length'] = str(len(etree.tostring(body))) > response, content = self._client.request( > self.ns_uri, "POST", > body=etree.tostring(body), headers=self._headers) > if response.status == 500 and not \ > (response["content-type"].startswith("text/xml") and \ > len(content) > 0): > raise HTTPError(response.status, content) > if response.status not in (200, 500): > raise HTTPError(response.status, content) > doc = etree.parse(StringIO(content)) > if response.status == 500: > faultstring = doc.findtext(".//faultstring") > raise HTTPError(response.status, faultstring) > > Now it's just a matter of using xpath expressions to dig into the "doc" > structure for the bits you need. oh my that is quite the handy answer Van Gal! I'll try it out right now. thanks a bunch man! From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 2 08:18:09 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 02 Jan 2008 14:18:09 +0100 Subject: wxpython application ( problem ? ) References: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> <5u1asvF1fgr5bU2@mid.uni-berlin.de> <7cb975f6-e9a6-4527-bd84-2041aede197f@j20g2000hsi.googlegroups.com> Message-ID: <5u1h8hF1fkosqU1@mid.individual.net> vedrandekovic at gmail.com wrote: > yes, so what's the problem? http://wxwidgets.org/manuals/stable/wx_wxthreadoverview.html | If you do decide to use threads in your application, it is | strongly recommended that no more than one thread calls GUI | functions. The thread sample shows that it is possible for many | different threads to call GUI functions at once (all the threads | created in the sample access GUI), but it is a very poor design | choice for anything except an example. The design which uses one | GUI thread and several worker threads which communicate with the | main one using events is much more robust and will undoubtedly | save you countless problems (example: under Win32 a thread can | only access GDI objects such as pens, brushes, &c created by | itself and not by the other threads). Regards, Bj?rn -- BOFH excuse #241: _Rosin_ core solder? But... From deets at nospam.web.de Sat Jan 12 16:23:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 12 Jan 2008 22:23:54 +0100 Subject: sqlite3 is it in the python default distro? In-Reply-To: References: Message-ID: <5uspfbF1hkm9bU1@mid.uni-berlin.de> Martin Marcher schrieb: > Hello, > > I can see that sqlite is in the standard lib documentation: > http://docs.python.org/lib/module-sqlite3.html > > however debian and ubuntu (and gentoo according to the packages info) seem > _not_ to include it. > > Now 2 question arise: > > a) Is sqlite included in the python default distribution Yes, since 2.5 > b) In real life can I consider (on linux) that an installation of python > includes the sqlite stuff? distutils is an example of a standard-module that gets ripped out of python by distros frequently, so that people need to install python-dev or such a package. So - yes, it happens that distros don't deliver the whole standard distribution. Now I'm not sure if that happens for sqlite, but if your own tests show so (reminder: python 2.5, accidentially using earlier versions that are installed won't work of course), then the answer is - no, you can't Diez From albert at spenarnc.xs4all.nl Mon Jan 28 04:50:48 2008 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 28 Jan 2008 09:50:48 GMT Subject: Transforming ascii file (pseduo database) into proper database References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> Message-ID: In article <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8 at e32g2000prn.googlegroups.com>, p. wrote: >I need to take a series of ascii files and transform the data >contained therein so that it can be inserted into an existing >database. The ascii files are just a series of lines, each line >containing fields separated by '|' character. Relations amongst the >data in the various files are denoted through an integer identifier, a >pseudo key if you will. Unfortunately, the relations in the ascii file >do not match up with those in the database in which i need to insert >the data, i.e., I need to transform the data from the files before >inserting into the database. Now, this would all be relatively simple >if not for the following fact: The ascii files are each around 800MB, >so pulling everything into memory and matching up the relations before >inserting the data into the database is impossible. In this case good old fashioned batch processing (line by line) may be appropriate. Read up on tools like sort and join. These tools are present on all Unix-like systems, and on windows in open-source toolkits. > >My questions are: >1. Has anyone done anything like this before, and if so, do you have >any advice? Puzzling question. Computers weren't invented for GUI's. They were invented for precisely this kind of thing. So, yes, it is a sure bet. >2. In the abstract, can anyone think of a way of amassing all the >related data for a specific identifier from all the individual files >without pulling all of the files into memory and without having to >repeatedly open, search, and close the files over and over again? As long as you don't use Excell, it is not up to it ;-) Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- like all pyramid schemes -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From pavlovevidence at gmail.com Fri Jan 25 19:48:38 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 25 Jan 2008 16:48:38 -0800 (PST) Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> <87k5lx5v19.fsf@benfinney.id.au> Message-ID: <22c3fd21-2fe3-4893-89f4-b23e1703d083@y5g2000hsf.googlegroups.com> On Jan 25, 6:45 pm, Ben Finney wrote: > "Gabriel Genellina" writes: > > You can also put, in animal/__init__.py: > > from monkey import Monkey > > and now you can refer to it as org.lib.animal.Monkey, but keep the > > implementation of Monkey class and all related stuff into > > .../animal/monkey.py > > This (as far as I can understand) is exactly the solution the original > poster desired to "shoot down", for reasons I still don't understand. Come on, the OP explained it quite clearly in his original post. Did you guys even read it? The module where org.lib.animal.Monkey is actually defined should be an implementation detail of the library, but simply importing Monkey into org.lib.animal doesn't quite make it one. If a user pickles a Monkey class, and then the OP decides to refactor the Monkey class into a new module (say org.lib.animal.primate.monkey), then the user would not be able to unpickle it. Because, you see, pickles record the module a class is defined in. So, now the user has to worry about where Monkey is actually defined. It is not an implementation detail. The solution is to modify the class's __module__ attribute as well as importing it, as I've already pointed out: from org.lib.animal.monkey import Monkey Monkey.__module__ = 'org.lib.animal' This should be enough to satisfy the OP's requirements, at least for classes, without softening the one-to-one module-to-file relationship, or using "hacks". In fact, I'd say this is good practice. Carl Banks From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 10 03:47:28 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 10 Jan 2008 09:47:28 +0100 Subject: Learning Python via a little word frequency program In-Reply-To: <2f65ede2-f491-435b-9a81-20ea7bd3cf5a@k2g2000hse.googlegroups.com> References: 4784bbea$0$17616$426a74cc@news.free.fr <2f65ede2-f491-435b-9a81-20ea7bd3cf5a@k2g2000hse.googlegroups.com> Message-ID: <4785db9a$0$23202$426a34cc@news.free.fr> Paul Hankin a ?crit : > On Jan 9, 12:19 pm, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Andrew Savige a ?crit : >>> and the -x hack above to >>> achieve a descending sort feels a bit odd to me, though I couldn't think >>> of a better way to do it. >> The "other" way would be to pass a custom comparison callback to sort, >> which would be both slower and more complicated. Your solution is IMHO >> the right thing to do here. > > Both list.sort and sorted have a parameter 'reverse' which does a > descending rather than ascending sort. Yes. But here the specs says that sort must be descending on first key (frequency) and ascending on the second (name), so you can't just use reverse sort. FWIW, a correct (and readable) solution - based on the 'key' param - has been given by Peter Otten, but it still requires a callback function, so while it avoids the '-x hack', it's still more expensive than a plain sort. From fredrik at pythonware.com Fri Jan 11 06:20:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jan 2008 12:20:50 +0100 Subject: Property with Arguments In-Reply-To: <3b8f3359-2889-42d5-9a5f-db2ee4268e8c@l1g2000hsa.googlegroups.com> References: <3b8f3359-2889-42d5-9a5f-db2ee4268e8c@l1g2000hsa.googlegroups.com> Message-ID: Lie wrote: > Is there a way to create a property with arguments? That's called method in Python, and has it's own syntax. You cannot assign to methods. > Or an index value like a list? Make the property that returns a list-like object (hooking __getitem__, __setitem__, etc). From Matthew_WARREN at bnpparibas.com Thu Jan 31 13:06:13 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Thu, 31 Jan 2008 18:06:13 +0000 Subject: Fw: Undeliverable Message In-Reply-To: Message-ID: > Heres the code > > def increment(digits,symbols): > ? ? ? ? overflow=True > ? ? ? ? digitpos=-1 > ? ? ? ? while overflow and -digitpos<=len(digits): > ? ? ? ? ? ? ? ? digitsymbolindex=symbols.index(digits[digitpos]) > ? ? ? ? ? ? ? ? if digitsymbolindex==len(symbols)-1: > ? ? ? ? ? ? ? ? ? ? ? ? overflow=True > ? ? ? ? ? ? ? ? ? ? ? ? digits[digitpos]=symbols[0] > ? ? ? ? ? ? ? ? ? ? ? ? digitpos=digitpos-1 > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? digits[digitpos]=symbols[digitsymbolindex+1] > ? ? ? ? ? ? ? ? ? ? ? ? overflow=False > ? ? ? ? return digits > > Now, this works. All good. It's nice and simple. ?I'm just wondering how > anyone else might approach it? >I (not an expert at all) have only minor comments and one question: >comments: >why keep setting overflow to True, if you do not touch it will not >change. good point. >digitpos -= 1 is easier to read in my mind it's just something ive done for years, so I read it perfectly fine. It's cause I was programming for ages before I first ever saw -= or += (bbc basic didnt have 'em ;P) >question: >Why first extract the indices and then compare (in your if statement), >and >why do you not just compare the symbols? I put the index into digitsymbolindex because it is used in more than one place in the code, and I'd rather have the result stored than recompute it possibly twice. have fun! Matt. -- 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 steve at REMOVE-THIS-cybersource.com.au Wed Jan 16 17:01:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Jan 2008 22:01:05 -0000 Subject: Creating unique combinations from lists References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> Message-ID: <13osvl1j4pvka15@corp.supernews.com> On Wed, 16 Jan 2008 11:15:16 -0800, breal wrote: > I could do nested for ... in loops, but was looking for a Pythonic way > to do this. Ideas? What makes you think nested loops aren't Pythonic? -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Jan 21 07:52:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 12:52:23 -0000 Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> <479451D9.3060207@block.duxieweb.com> Message-ID: <13p95c78aeitf55@corp.supernews.com> On Mon, 21 Jan 2008 17:32:42 +0800, J. Peng wrote: > Steven D'Aprano ??: >> On Mon, 21 Jan 2008 16:23:50 +0800, J. Peng wrote: >> >>> J. Peng ??: >>> >>>> k = (i.split())[3] >>>> y = (i.split())[1] >>> btw, why can't I write the above two into one statement? >>> >>> (k,y) = (i.split())[3,1] >> >> I don't know. What's "i"? >> >> I'm guessing "i" is a string (and what a horrible choice of a name for >> a string!) So i.split() will return a list. List indexing with multiple >> arguments isn't defined, which is why you can't write >> >> k, y = (i.split())[3,1] >> >> > Thanks. > Then one have to split the list twice.Given the list is large,it's maybe > not good for performance.Is it a more effective split way? Yes, split the string once and store it. words = "Nobody expects the Spanish Inquisition!" alist = words.split() k = alist[3] # "Spanish" y = alist[1] # "expects" -- Steven From haraldarminmassa at gmail.com Tue Jan 22 09:12:40 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Tue, 22 Jan 2008 06:12:40 -0800 (PST) Subject: building psycopg2 on windows using mingw, "cannot find -lpq" References: <5vk1sqF1mal8qU1@mid.uni-berlin.de> Message-ID: <42089805-0751-4ff9-a567-6b302c739077@h11g2000prf.googlegroups.com> > > The compile works, BUT linking fails: > > > 2.5\Release\psycopg\_psycopg.def -Lc:\python25\libs -Lc: > > \python25\PCBuild -Lc:/p > > ostgres/83RC2/lib -lpython25 -lpq -lws2_32 -ladvapi32 -o build > > > ?-Lc:/postgres/83RC2/lib > > Are you sure using forward slashes in the path works here? Not at all. But that commandline is generated by setup.py, not by me : ( and setup.py extracts the paths from pg_config so: I have no idea how to make it use backslash :( Thanks for the idea, Harald From martin at v.loewis.de Sun Jan 13 12:02:00 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 13 Jan 2008 18:02:00 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <200801131550.50119.donn.ingle@gmail.com> References: <200801131427.54672.donn.ingle@gmail.com> <478A0F5D.3030906@v.loewis.de> <200801131550.50119.donn.ingle@gmail.com> Message-ID: <478A4408.2090805@v.loewis.de> > Could it not be that the app doing the output (say konsole) could be > displaying a filename as best as it can (doing the ignore/replace) trick and > using whatever fonts it can reach) and this would disguise the situation? No. It may use replacement characters (i.e. a question mark, or an empty square box), but if you don't see such characters, then the terminal has successfully decoded the file names. Whether it also correctly decoded them is something for you to check (i.e. do they look right?) > I have been looking for somewhere online that I can download files obviously > in a non-ascii set (like japan someplace) but can't find anything easy. I > want to see exactly how my system (Kubuntu 7.10) handles things. So what does sys.getfilesystemencoding() say what encoding is used for filenames? Regards, Martin From srikrishnamohan at gmail.com Wed Jan 2 05:09:45 2008 From: srikrishnamohan at gmail.com (km) Date: Wed, 2 Jan 2008 15:39:45 +0530 Subject: Python Trajectory Module? In-Reply-To: <477AD5E8.3060007@gmail.com> References: <8ec8091e-8670-4d04-8198-c688c14576cf@p69g2000hsa.googlegroups.com> <477AD5E8.3060007@gmail.com> Message-ID: Hi have a look at these demos (includes trajectory etc) with VPython http://showmedo.com/videos/series?name=pythonThompsonVPythonSeries best wishes, KM ------------------------------------------------------------------------------------------------------------------------------ On Jan 2, 2008 5:38 AM, Stef Mientki wrote: > squishywaffle at gmail.com wrote: > > Greetings, > > > > I was wondering if there was a python Module/Library out there that > > handles some trajectory/physics stuff like moving an object along a > > straight path in an X,Y 2D (or 3D) plane or calculating parabolic > > arcs. I'd really settle for just the moving of an object along a > > straight line. > > > > I know it's not terribly difficult to implement this on your own, but > > I'd rather not re-invent the wheel if someone else already did a good > > job of it the first time. > > > > Thanks! > > > Depends on how detailed / graphical you've in mind. > You might be interested in this: > > > http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_animations_screenshots.html > > I've put a scanned version of my written notes about the trajectory > example. > No need for ODE in my very simple mind, because the functions describing > the solution are already known. > > If you want to view the demos / animations, > be sure to view the demo at the bottom first, > because it explains the philosophy behind the program. > Only 1 major feature is not described in this demo (because when I made > the demo I had no solution for it, now I think I have) > and that is : > an integrated help / instruction / assignment / fill-in forms / > judgement, specially for educational puposes. > > The program is not yet released, > because I'm now cleaning it up and debugging it (by making demos ;-) > cheers, > Stef > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nodrogbrown at gmail.com Mon Jan 21 01:07:31 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Sun, 20 Jan 2008 22:07:31 -0800 (PST) Subject: newbie doubt ..numpy array Message-ID: if this is too silly a qn pls forgive I was learning numpy.ndarrays thru the tutorial. myarr=numpy.array( [ [10, 20, 30, 40],[1,2,3,4],[5,6,7,8] ] ) if i want to access the element 3 i can do it by myarr[1, 2] but then myarr[1][2] will also give the same result..is there any reason why two types of indexing is allowed? gordon p.s(i tried to post to numpy grp but it is not appearing there!) From phd at phd.pp.ru Thu Jan 10 07:26:47 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 10 Jan 2008 15:26:47 +0300 Subject: SQLObject 0.7.10 Message-ID: <20080110122647.GB3070@phd.pp.ru> Hello! I'm pleased to announce the 0.7.10 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.10 News and changes: http://sqlobject.org/docs/News.html What's New ========== News since 0.7.9 ---------------- * With PySQLite2 do not use encode()/decode() from PySQLite1 - always use base64 for BLOBs. * MySQLConnection doesn't convert query strings to unicode (but allows to pass unicode query strings if the user build ones). DB URI parameter sqlobject_encoding is no longer used. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From paul.hankin at gmail.com Sat Jan 5 05:37:53 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 5 Jan 2008 02:37:53 -0800 (PST) Subject: Basic inheritance question References: Message-ID: On Jan 5, 10:31?am, MartinRineh... at gmail.com wrote: > ... > class code: > ? ? def __init__( self, start, stop ): > ? ? ? ? startLoc = start > ? ? ? ? stopLoc = stop > ... You've forgotten the explicit self. def __init__( self, start, stop ): self.startLoc = start self.stopLoc = stop -- Paul Hankin From rw at smsnet.pl Thu Jan 3 14:13:18 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 03 Jan 2008 20:13:18 +0100 Subject: urllib2 disable proxy References: <878x373o6c.fsf@merkury.smsnet.pl> Message-ID: <87odc2hgdt.fsf@merkury.smsnet.pl> Dimitrios Apostolou writes: > On Wed, 2 Jan 2008, Rob Wolfe wrote: > >> Dimitrios Apostolou writes: >> >>> Hello list, >>> >>> I've been looking for a way to explicitly disable the use of proxies with >>> urllib2, no matter what the environment dictates. Unfortunately I can't find >>> a way in the documentation, and reading the source leads me to believe that >>> something like the following does the job: >>> >>> req.set_proxy(None,None) >>> >>> Where req is a urllib2.Request instance. So is there an official way of doing >>> this? Perhaps it should be added in the documentation? >> >> I believe that the recommended way is to use `urllib2.ProxyHandler`. >> Take a look at: >> http://www.voidspace.org.uk/python/articles/urllib2.shtml > > Thanks for the pointer, I will use that way. However it seems rather > non-elegant way to do something so simple and I was hoping not to mess > with ProxyHandler, especially since I want *no* proxy... IMHO > something like the following would be more elegant: > > req.set_proxy('','http') > > or > > req.set_proxy(None,'http') > > > However these ways *don't* work. You think I should file a feature > request somewhere or send this to the python-dev list? Actually, I like this idea of handlers and openers and find it simple and _elegant_, so I can't second that request. Besides disabling proxies despite environmental settings is a special case, so imho using `instal_opener` is justified. Regards, Rob From paddy3118 at netscape.net Wed Jan 9 15:28:33 2008 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Wed, 09 Jan 2008 20:28:33 GMT Subject: alternating string replace: Extended input (Long). In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: cesco wrote: I created some more test strings and ran posters solutions against them. results attached. - Paddy. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: alternating_replacements.py URL: From martin at v.loewis.de Wed Jan 2 15:48:30 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Jan 2008 21:48:30 +0100 Subject: different encodings for unicode() and u''.encode(), bug? In-Reply-To: <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> Message-ID: <477BF89E.1010906@v.loewis.de> > Do not know what the implications of encoding according to "ANSI > codepage (CP_ACP)" are. Windows only seems clear, but why does it only > complain when decoding a non-empty string (or when encoding the empty > unicode string) ? It has no implications for this issue here. CP_ACP is a Microsoft invention of a specific encoding alias - the "ANSI code page" (as Microsoft calls it) is not a specific encoding where I could specify a mapping from bytes to characters, but instead a system-global indirection based on a langage default. For example, in the Western-European/U.S. version of Windows, the default for CP_ACP is cp1252 (local installation may change that default, system-wide). The issue likely has the cause that Piet also guessed: If the input is an empty string, no attempt to actually perform an encoding is done, but the output is assumed to be an empty string again. This is correct behavior for all codecs that Python supports in its default installation, at least for the direction bytes->unicode. For the reverse direction, such an optimization would be incorrect; consider u"".encode("utf-16"). HTH, Martin From hniksic at xemacs.org Thu Jan 17 10:45:01 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 17 Jan 2008 16:45:01 +0100 Subject: Is this a bug, or is it me? References: Message-ID: <87ir1so3r6.fsf@mulj.homelinux.net> cptnwillard at gmail.com writes: > Hello all, > For some reason, the following does not work : > > > class C: > TYPES = [None] > DICT = {} > for Type in TYPES: > DICT.update((E,Type) for E in [1]) > >>>> NameError: global name 'Type' is not defined > > > What do you think? Is this a bug? It works if you change the generator expression to a list comprehension, by adding [] around it. Feels like a bug to me, but there might be subtleties involved. From vriolk at gmail.com Tue Jan 15 14:43:54 2008 From: vriolk at gmail.com (coldpizza) Date: Tue, 15 Jan 2008 11:43:54 -0800 (PST) Subject: UTF-8 in basic CGI mode Message-ID: <241b96e8-8ea3-41c5-954f-4d47619baa18@d21g2000prf.googlegroups.com> Hi, I have a basic Python CGI web form that shows data from a SQLite3 database. It runs under the built-in CGIWebserver which looks like this: [code] import SimpleHTTPServer import SocketServer SocketServer.TCPServer(("", 80),SimpleHTTPServer.SimpleHTTPRequestHandler).serve_forever() [/code] The script runs Ok with ANSI characters, but when I try to process non- ASCII data I get an UnicodeDecodeError exception ('ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)). I have added the the 'u' prefix to all my literal strings, and I _have_ wrapped all my output statements into myString.encode('utf8', "replace"), but, apparently the UnicodeDecodeError exception occurs because of a string that I get back to the script through cgi.FieldStorage( ). I.e. I have the lines: form = cgi.FieldStorage( ) word= form['word'] which retrieve the 'word' value from a GET request. I am using this 'word' variable like this: print u'''''' % (word) and apparently this causes exceptions with non-ASCII strings. I've also tried this: print u'''''' % (word.encode('utf8')) but I still get the same UnicodeDecodeError.. What is the general good practice for working with UTF8? The standard Python CGI documentation has nothing on character sets. It looks insane to have to explicitly wrap every string with .encode('utf8'), but even this does not work. Could the problem be related to the encoding of the string returned by the cgi.fieldstorage()? My page is using UTF-8 encoding. What would be encoding for the data that comes from the browser after the form is submitted? Why does Python always try to use 'ascii'? I have checked all my strings and they are prefixed with 'u'. I have also tried replacing print statements with sys.stdout.write (DATA.encode('utf8')) but this did not help. Any clues? Thanks in advance. From joemystery123 at gmail.com Tue Jan 1 14:24:04 2008 From: joemystery123 at gmail.com (crybaby) Date: Tue, 1 Jan 2008 11:24:04 -0800 (PST) Subject: pexpect ssh login and ls | grep References: <3eb81375-3e4a-4e0f-a4e7-bbb1d6cd0f8c@s19g2000prg.googlegroups.com> <477a6eec$0$17448$bf4948fe@news.tele2.nl> <1c62b205-e2dd-4bb9-ac99-e14ce652afab@21g2000hsj.googlegroups.com> Message-ID: I did try to excute the ssh and shell ls grep command in all in one like so: ssh my at mycomp2 "ls mytest.log > /dev/null 2>&1; echo $?" This seem to work, but also throwing exceptions. Also, including ssh and shell command together would be a problem when I later add a pass phrase to ssh key. Can someone provide little insight on this? >>> import pexpect >>> child=pexpect.spawn('ssh my at mycomp2 "ls mytest.log > /dev/null 2>&1; echo $?"') >>> >>> child.expect([pexpect.TIMEOUT, '\$']) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/pexpect.py", line 1064, in expect return self.expect_list(compiled_pattern_list, timeout, searchwindowsize) File "/usr/lib/python2.4/site-packages/pexpect.py", line 1132, in expect_list raise EOF (str(e) + '\n' + str(self)) pexpect.EOF: End Of File (EOF) in read_nonblocking(). Exception style platform. version: 2.1 ($Revision: 395 $) command: /usr/bin/ssh args: ['/usr/bin/ssh', 'my at mycomp2', 'ls mytest.log > /dev/null 2>&1; echo $?'] patterns: pexpect.TIMEOUT \$ buffer (last 100 chars): before (last 100 chars): 0 after: pexpect.EOF match: None match_index: None exitstatus: 0 flag_eof: True pid: 3524 child_fd: 3 closed: False timeout: 30 delimiter: pexpect.EOF logfile: None maxread: 2000 ignorecase: False searchwindowsize: None delaybeforesend: 0.1 delayafterclose: 0.1 delayafterterminate: 0.1 >>> >>> result=child.before >>> result2=child.after >>> print result 0 >>> print result2 pexpect.EOF From goon12 at gmail.com Tue Jan 29 14:21:01 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 29 Jan 2008 14:21:01 -0500 Subject: noob stuck on reading double In-Reply-To: <6a2ccd190801291102m457f1fb9odca04ef24fb47ac3@mail.gmail.com> References: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk> <6a2ccd190801291059q1a18c70co8e9db881c6994f63@mail.gmail.com> <6a2ccd190801291102m457f1fb9odca04ef24fb47ac3@mail.gmail.com> Message-ID: <6a2ccd190801291121p68ba4c7bode9cd5831eca60d2@mail.gmail.com> Since you're unpacking it with the 'd' format character I am assuming a "doubleword" field is a double. You said you had 113 of them in the binary file. You should be doing something like this: file = open('data.bin', 'rb') file.seek(0) raw = file.read() unpacked = unpack('113d', raw) for i in range(0,113): print unpacked[i] file.close() From kyosohma at gmail.com Wed Jan 9 16:57:00 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 9 Jan 2008 13:57:00 -0800 (PST) Subject: getting absolute path ? References: Message-ID: On Jan 9, 3:22 pm, Stef Mientki wrote: > hello, > > I'm trying to convert the links in html pages to absolute links, > these pages can either be webpages or files on local harddisk (winXP). > Now I've struggling for a while, and this code works a lilttle: > > i = line.find ( 'href=' ) > if i < 0 : > i = line.find ( ' src=' ) > if i >= 0 : > ii = line.find ( '"', i+6 ) > file = line [ i+6 : ii ] > #print urlparse.urljoin ( p, file ) > if file.find ( 'http:' ) < 0 : > abspath = os.path.normpath ( os.path.join ( p, file ) ) > line = line.replace ( file, abspath ) > print line > > but it only covers files on local disk and just 1 link per line, > so I guess it's a lot of trouble to catch all cases. > Isn't there a convenient function for (OS independent preferable) ? > Googled for it, but can't find it. > > thanks, > Stef Mientki I googled a bit too. The Perl forums talk about using a regular expression. You can probably take that and translate it into the Python equivalent: http://forums.devshed.com/perl-programming-6/how-to-parse-relatives-links-to-absolute-links-8173.html I also found this, which appears to be an old c.l.py thread: http://www.dbforums.com/archive/index.php/t-320359.html You might have more luck if you google for "relative to absolute links". I would also take a look at how django or cherrypy creates their URLs. Mike From booboo at gforcecable.com Wed Jan 9 06:43:38 2008 From: booboo at gforcecable.com (Tom La Bone) Date: Wed, 9 Jan 2008 03:43:38 -0800 (PST) Subject: Update of Gnuplot.py Message-ID: <14710180.post@talk.nabble.com> Can someone suggest where to get a version of Gnuplot.py (for Windows) that has been updated to use numpy? Or, is there another interface available to use GnuPlot from Python? Thanks. Tom -- View this message in context: http://www.nabble.com/Update-of-Gnuplot.py-tp14710180p14710180.html Sent from the Python - python-list mailing list archive at Nabble.com. From michele.simionato at gmail.com Fri Jan 4 10:23:26 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 4 Jan 2008 07:23:26 -0800 (PST) Subject: python interfaces References: Message-ID: On Jan 4, 3:59 pm, hyperboreean wrote: > Hi, > Probably it has been asked before, but I'll still ask. > Why doesn't python provide interfaces trough its standard library? Or it > was ever proposed to be included in the language? > Zope's implementation seems pretty flexible and straightforward. > > Thanks. Python 3.0 will introduce Abstract Base Classes: http://www.python.org/dev/peps/pep-3119/ From asmodai at in-nomine.org Wed Jan 2 12:48:21 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 2 Jan 2008 18:48:21 +0100 Subject: XML-XSD Processing/Creation. In-Reply-To: References: Message-ID: <20080102174821.GF67953@nexus.in-nomine.org> -On [20080102 18:21], xkenneth (xkenneth at gmail.com) wrote: > So i'm working with the WITSML standard, which is a pretty >massive standard defined in XML for the transfer of oilfield data. I cannot answer (yet) the question of generating XML data from an XSD. But for writing out XML files I like to use either ElementTree or lxml. Very easy and straightforward use of XML from Python in my opinion. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Once sent from the Golden Hall... From Russ.Paielli at gmail.com Thu Jan 10 03:04:25 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 10 Jan 2008 00:04:25 -0800 (PST) Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: On Jan 9, 11:51 pm, Fredrik Lundh wrote: > Steve Brown wrote: > > I've got a series of modules which look like this: > > > #************ > > # > > # Temperature Sense Test > > # > > #************ > > class Test3(ar_test.AR_TEST): > > """Temperature Sense Test""" > > > I don't like the duplicated information: But the comment is attractive, and > > the docstring self.__doc__ is already in use in the test log. I've read that > > all modules and classes should have docstrings, but I don't really have > > anything else to say, and each module contains only one class. I don't think > > that > > > """Temperature Sense Test""" > > class Test3(ar_test.AR_TEST): > > """Temperature Sense Test""" > > > would be a real improvement. > > > What do you think? > > since you already seem to cater to your audience (clearly marked > comments for people browsing the code, brief docstrings for the test > log), I don't really see why you should change anything. > > > I've read that all modules and classes should have docstrings > > if nobody's going to read them, there's no reason to add them. don't > treat generic style advice as dogma. > > Well, trivial modules certainly don't need much documentation, but he didn't say they were trivial. I assumed there was more to them then he showed. From zbigniew.braniecki at gmail.com Fri Jan 18 12:09:47 2008 From: zbigniew.braniecki at gmail.com (Zbigniew Braniecki) Date: Fri, 18 Jan 2008 18:09:47 +0100 Subject: Bug in __init__? Message-ID: I found a bug in my code today, and spent an hour trying to locate it and then minimize the testcase. Once I did it, I'm still confused about the behavior and I could not find any reference to this behavior in docs. testcase: class A(): def add (self, el): self.lst.extend(el) def __init__ (self, val=[]): print val self.lst = val def test (): x = A() x.add(["foo1","foo2"]) b = A() So, what I would expect here is that I will create two instances of class A with empty self.lst property. Right? In fact (at least with my Python 2.5) gandalf at gandalf-desktop:~/projects/pyl10n$ ./scripts/test.py [] ['foo1', 'foo2'] This bug does not happen when I switch to __init__ (self, *args) and assign self.lst= args[0]. Any clue on what's going on here, and/if where I should report it? Greetings Zbigniew Braniecki From ganesh.borse at credit-suisse.com Thu Jan 10 20:31:26 2008 From: ganesh.borse at credit-suisse.com (Borse, Ganesh) Date: Fri, 11 Jan 2008 09:31:26 +0800 Subject: PyImport_ImportModule("cStringIO") failure with undefined symbol Message-ID: Hi, Can you please guide me for the following problem? The call to "PyImport_ImportModule("cStringIO");" is failing with an error of "undefined symbol: PyObject_SelfIter". Before importing this module, I am importing only the sys module. Py_SetProgramName("/usr/bin/python"); Py_Initialize(); char* argv[] = { "python","-v",""}; PySys_SetArgv(2,argv); PyRun_SimpleString("import sys"); PyObject *modStringIO = NULL; // Import cStringIO module modStringIO = PyImport_ImportModule("cStringIO"); Should I be importing any other additional module(s) to make this import work? Please help. I am trying to use the function GetPythonErrorMessage provided in this post: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9212ebc42e8438a7/f0bd5f5b15902b14?lnk=gst&q=PyErr_Print#f0bd5f5b15902b14 Thanks in advance for your help. Regards. ============================================================================== Please access the attached hyperlink for an important electronic communications disclaimer: http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html ============================================================================== From donn.ingle at gmail.com Sun Jan 13 05:24:10 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 12:24:10 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <4789D98A.80609@v.loewis.de> References: <200801130930.07852.donn.ingle@gmail.com> <4789D98A.80609@v.loewis.de> Message-ID: <200801131224.10263.donn.ingle@gmail.com> Martin, Thanks, food for thought indeed. > On Unix, yes. On Windows, NTFS and VFAT represent file names as Unicode > strings always, independent of locale. POSIX file names are byte > strings, and there isn't any good support for recording what their > encoding is. I get my filenames from two sources: 1. A wxPython treeview control (unicode build) 2. os.listdir() with a unicode path passed to it I have found that os.listdir() does not always return unicode objects when passed a unicode path. Sometimes "byte strings" are returned in the list, mixed-in with unicodes. I will try the technique given on:http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html#guessing-the-encoding Perhaps that will help. Re os.listdir(): > If you think you may have file names with mixed locales, and > the current locale might not match the file name's locale, you should > be using the byte string variant on Unix (which it seems you are already > doing). I gather you mean that I should get a unicode path, encode it to a byte string and then pass that to os.listdir Then, I suppose, I will have to decode each resulting byte string (via the detect routines mentioned in the link above) back into unicode - passing those I simply cannot interpret. > Then, if the locale's encoding cannot decode the file names, you have > several options > a) don't try to interpret the file names as character strings, i.e. > don't decode them. Not sure why you need the file names - if it's > only to open the files, and never to present the file name to the > user, not decoding them might be feasible So, you reckon I should stick to byte-strings for the low-level file open stuff? It's a little complicated by my using Python Imaging to access the font files. It hands it all over to Freetype and really leaves my sphere of savvy. I'll do some testing with PIL and byte-string filenames. I wish my memory was better, I'm pretty sure I've been down that road and all my results kept pushing me to stick to unicode objects as far as possible. > b) guess an encoding. For file names on Linux, UTF-8 is fairly common, > so it might be a reasonable guess. > c) accept lossy decoding, i.e. decode with some encoding, and use > "replace" as the error handler. You'll have to preserve the original > file names along with the decoded versions if you later also want to > operate on the original file. Okay, I'm getting your drift. > That's not true. Try open("\xff","w"), then try interpreting the file > name as UTF-8. Some byte strings are not meaningful UTF-8, hence that > approach cannot work. Okay. > That's correct, and there is no solution (not in Python, not in any > other programming language). You have to made trade-offs. For that, > you need to analyze precisely what your requirements are. I would say the requirements are: 1. To open font files from any source (locale.) 2. To display their filename on the gui and the console. 3. To fetch some text meta-info (family etc.) via PIL/Freetype and display same. 4. To write the path and filename to text files. 5. To make soft links (path + filename) to another path. So, there's a lot of unicode + unicode and os.path.join and so forth going on. > > I went through this exercise recently and had no joy. It seems the string > > I chose to use simply would not render - even under 'ignore' and > > 'replace'. > I don't understand what "would not render" means. I meant it would not print the name, but constantly throws ascii related errors. I don't know if the character will survive this email, but the text I was trying to display (under LANG=C) in a python script (not the immediate-mode interpreter) was: "M?gul". The second character is a capital O with an umlaut (double-dots I think) above it. For some reason I could not get that to display as "M?gul" or "Mgul". BTW, I just made that up - it means nothing (to me). I hope it's not a swear word in some other language :) > As for font files - I don't know what encoding the family is in, but > I would sure hope that the format specification of the font file format > would also specify what the encoding for the family name is, or that > there are at least established conventions. You'd think. It turns out that font file are anything but simple. I am doing my best to avoid being sucked-into the black hole of complexity they represent. I must stick to what PIL/Freetype can do. The internals of font-files are waaaaaay over my head. > >> I would avoid locale.getlocale. It's a pointless function (IMO). > As a consequence, it will return None if it doesn't know better. > If all you want is the charset of the locale, use > locale.getpreferredencoding(). Brilliant summary - thanks a lot for that. > You could just leave out the languages parameter, and trust gettext > to find some message catalog. Right - I'll give that a go. > > This would mean cutting-out a percentage of the external font files that > > can be used by the app. > See above. There are other ways to trade-off. Alternatively, you could > require that the program finds a richer locale, and bail out if the > locale is just "C". That's kind of what the OP is all about. If I make this a 'design decision' then it means I have a problem with the Debian packaging (and RPM?) rules that require a "C" locale support. I think I shall have to break the links between my setup.py and the rest of my app - so that setup.py will allow LANG=C but the app (when run) will not. > That doesn't help. For Turkish in particular, the UTF-8 locale is worse > than the ISO-8859-9 locale, as the lowercase I takes two bytes in UTF-8, > so tolower can't really work in the UTF-8 locale (but can in the > ISO-8859-9 locale). Wow. I still get cold chills -- but I assume that once the right encoding is known this sort of thing will be okay. Thanks again. It's coming together slowly. \d From vriolk at gmail.com Tue Jan 15 15:42:21 2008 From: vriolk at gmail.com (coldpizza) Date: Tue, 15 Jan 2008 12:42:21 -0800 (PST) Subject: UTF-8 in basic CGI mode Message-ID: <1f8a4051-27cb-48aa-a0ab-793f59ab3845@s13g2000prd.googlegroups.com> Hi, I have a basic Python CGI web form that shows data from a SQLite3 database. It runs under the built-in CGIWebserver which looks something like this: [code] from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler HTTPServer("8000", CGIHTTPRequestHandler).serve_forever( ) [/code] The script runs Ok with ANSI characters, but when I try to process non- ASCII data I get an UnicodeDecodeError exception ('ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)). I have added the the 'u' prefix to all my literal strings, and I _have_ wrapped all my output statements into myString.encode('utf8', "replace"), but, apparently the UnicodeDecodeError exception occurs because of a string that I get back to the script through cgi.FieldStorage( ). I.e. I have the lines: form = cgi.FieldStorage( ) word= form['word'] which retrieve the 'word' value from a GET request. I am using this 'word' variable like this: print u'''''' % (word) and apparently this causes exceptions with non-ASCII strings. I've also tried this: print u'''''' % (word.encode('utf8')) but I still get the same UnicodeDecodeError.. What is the general good practice for working with UTF8? The standard Python CGI documentation has nothing on character sets. It looks insane to have to explicitly wrap every string with .encode('utf8'), but even this does not work. Could the problem be related to the encoding of the string returned by the cgi.fieldstorage()? My page is using UTF-8 encoding. What would be encoding for the data that comes from the browser after the form is submitted? Why does Python always try to use 'ascii'? I have checked all my strings and they are prefixed with 'u'. I have also tried replacing print statements with sys.stdout.write (DATA.encode('utf8')) but this did not help. Any clues? From ruoyu0088 at gmail.com Fri Jan 11 04:52:16 2008 From: ruoyu0088 at gmail.com (HYRY) Date: Fri, 11 Jan 2008 01:52:16 -0800 (PST) Subject: python recursive function References: Message-ID: <01c6fa55-3836-4d92-aaf4-02fec7fa529c@l6g2000prm.googlegroups.com> > def bears (n): > if n==42: > return True > if n%5==0: > bears(n-42) > if n%2==0: > bears(n/2) > if n%3==0 or n%4==0: > one = (n%10) > two = ((n%100)/10) > if one!=0 and two!=0: > bears(n-(one*two)) > return False > > If a game hits 42 it should return True, otherwise False. If program > never hits 42 and return True, then it returns False. I figured out > base case, but I still get False when I enter bears(250). Any help > would be very appreciated! try this: def bears (n): if n==42: return True if n%5==0: if bears(n-42): return True if n%2==0: if bears(n/2): return True if n%3==0 or n%4==0: one = (n%10) two = ((n%100)/10) if one!=0 and two!=0: if bears(n-(one*two)): return True return False print bears(42) print bears(250) print bears(50) print bears(84) print bears(41) From fredrik at pythonware.com Fri Jan 4 09:00:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 15:00:44 +0100 Subject: Strange varargs issue In-Reply-To: References: Message-ID: Mike wrote: > __f.func(a) > TypeError: func() takes exactly 1 argument (2 given) > > How can this possibly be? The "caller" print statement obviously > shows "a" is singular. __f.func(a) is a method call, and methods always get the object itself as an extra initial argument. to fix this, add "self" to the method signature: class foobar(object): def func(self, arg): print 'foobar.func: %r' % arg see the tutorial for more info. > I'm not sure if this is a bug or if I'm just not understanding > something correctly. you are aware that blaming your mistakes on bugs in widely used code is somewhat rude, right? http://www.catb.org/~esr/faqs/smart-questions.html#id306617 From rong.xian at gmail.com Sun Jan 27 08:49:58 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 05:49:58 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <5vr1ekF1njt09U2@mid.uni-berlin.de> <84f39f37-4d18-47c1-9349-bf3f471b2bf5@s19g2000prg.googlegroups.com> <19efc1d4-d77d-4855-9647-7a4782b064eb@d21g2000prg.googlegroups.com> Message-ID: <1d551606-336a-4956-b7d6-71a3009aea09@y5g2000hsf.googlegroups.com> On 1?27?, ??7?04?, John Machin wrote: > On Jan 27, 9:18 pm, glacier wrote: > > > > > > > On 1?24?, ??4?44?, Marc 'BlackJack' Rintsch wrote: > > > > On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote: > > > > My second question is: is there any one who has tested very long mbcs > > > > decode? I tried to decode a long(20+MB) xml yesterday, which turns out > > > > to be very strange and cause SAX fail to parse the decoded string. > > > > That's because SAX wants bytes, not a decoded string. Don't decode it > > > yourself. > > > > > However, I use another text editor to convert the file to utf-8 and > > > > SAX will parse the content successfully. > > > > Because now you feed SAX with bytes instead of a unicode string. > > > > Ciao, > > > Marc 'BlackJack' Rintsch > > > Yepp. I feed SAX with the unicode string since SAX didn't support my > > encoding system(GBK). > > Let's go back to the beginning. What is "SAX"? Show us exactly what > command or code you used. > SAX is the package 'xml.sax' distributed with Python 2.5:) 1,I read text from a GBK encoded XML file then I skip the first line declare the encoding. 2,I converted the string to uncode by call decode('mbcs') 3,I used xml.sax.parseString to parse the string. ######################################################################## f = file('e:/temp/456.xml','rb') s = f.read() f.close() n = 0 for i in xrange(len(s)): if s[i]=='\n': n += 1 if n == 1: s = s[i+1:] break s = ''+s+'' s = s.decode('mbcs') xml.sax.parseString(s,handler,handler) ######################################################################## > How did you let this SAX know that the file was encoded in GBK? An > argument to SAX? An encoding declaration in the first few lines of the > file? Some other method? ... precise answer please. Or did you expect > that this SAX would guess correctly what the encoding was without > being told? I didn't tell the SAX the file is encoded in GBK since I used the 'parseString' method. > > What does "didn't support my encoding system" mean? Have you actually > tried pushing raw undecoded GBK at SAX using a suitable documented > method of telling SAX that the file is in fact encoded in GBK? If so, > what was the error message that you got? I mean SAX only support a limited number of encoding such as utf-8 utf-16 etc.,which didn't include GBK. > > How do you know that it's GBK, anyway? Have you considered these > possible scenarios: > (1) It's GBK but you are telling SAX that it's GB2312 > (2) It's GB18030 but you are telling SAX it's GBK > Frankly speaking, I cannot tell if the file contains any GB18030 characters...^______^ > HTH, > John- ??????? - > > - ??????? - From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 10 03:37:57 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 10 Jan 2008 09:37:57 +0100 Subject: Python too slow? In-Reply-To: <13oattm5ijqvf58@corp.supernews.com> References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> Message-ID: <4785d960$0$22237$426a74cc@news.free.fr> Ed Jensen a ?crit : > Bruno Desthuilliers wrote: >> And the reference implementation of Python (CPython) is not >> interpreted, it's compiled to byte-code, which is then executed by a VM >> (just like Java). > > Wow, this is pretty misleading. Ho yes ??? Why so, please ? Care to point to anything *wrong* in the above statement ? > Java is, indeed, compiled to bytecode; however, modern JVMs typically > compile the bytecode to native code and then execute the native code. Which is known as JIT compilation - and there are a couple attempts at it in Python too. Anyway, the JIT compiler is not part of the Java spec (while the byte-code/VM is), and its not garanteed to be there on each an every Java VM. > CPython strictly interprets bytecode; And ? > it does not compile the > bytecode to native code. And ? I fail to see how the existence of JIT compilers in some Java VM changes anything to the fact that both Java (by language specification) and CPython use the byte-code/VM scheme. From vriolk at gmail.com Thu Jan 17 04:38:03 2008 From: vriolk at gmail.com (coldpizza) Date: Thu, 17 Jan 2008 01:38:03 -0800 (PST) Subject: UTF-8 in basic CGI mode References: <1f8a4051-27cb-48aa-a0ab-793f59ab3845@s13g2000prd.googlegroups.com> Message-ID: Thanks, Sion, that makes sense! Would it be correct to assume that the encoding of strings retrieved by FieldStorage() would be the same as the encoding of the submitted web form (in my case utf-8)? Funny but I have the same form implemented in PSP (Python Server Pages), running under Apache with mod_python and it works transparently with no explicit charset translation required. On Jan 16, 4:31?pm, Sion Arrowsmith wrote: > coldpizza ? wrote: > >I am using this 'word' variable like this: > > >print u'''''' % (word) > > >and apparently this causes exceptions with non-ASCII strings. > > >I've also tried this: > >print u'''''' % > >(word.encode('utf8')) > >but I still get the same UnicodeDecodeError.. > > Your 'word' is a byte string (presumably UTF8 encoded). When python > is asked to insert a byte string into a unicode string (as you are > doing with the % operator, but the same applies to concatenation > with the + operator) it attempts to convert the byte string into > unicode. And the default encoding is 'ascii', and the ascii codec > takes a very strict view about what an ASCII character is -- and > that is that only characters below 128 are ASCII. > > To get it to work, you need to *decode* word. It is already UTF8 > (or something) encoded. Under most circumstances, use encode() to > turn unicode strings to byte strings, and decode() to go in the > other direction. > > -- > \S -- si... 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 martin at v.loewis.de Sat Jan 12 18:08:42 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jan 2008 00:08:42 +0100 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: References: Message-ID: <4789487A.1020209@v.loewis.de> > 2. If this returns "C" or anything without 'utf8' in it, then things start > to go downhill: > 2a. The app assumes unicode objects internally. i.e. Whenever there is > a "string like this" in a var it's supposed to be unicode. Whenever > something comes into the app (from a filename, a file's contents, the > command-line) it's assumed to be a byte-string that I decode("utf8") on > before placing it into my objects etc. That's a bug in the app. It shouldn't assume that environment variables are UTF-8. Instead, it should assume that they are in the locale's encoding, and compute that encoding with locale.getpreferredencoding. > 2b. Because of 2a and if the locale is not 'utf8 aware' (i.e. "C") I start > getting all the old 'ascii' unicode decode errors. This happens at every > string operation, at every print command and is almost impossible to fix. If you print non-ASCII strings to the terminal, and you can't be certain that the terminal supports the encoding in the string, and you can't reasonably deal with the exceptions, you should accept moji-bake, by specifying the "replace" error handler when converting strings to the terminal's encoding. > 3. I made the decision to check the locale and stop the app if the return > from getlocale is (None,None). I would avoid locale.getlocale. It's a pointless function (IMO). Also, what's the purpose of this test? > Does anyone have some ideas? Is there a universal "proper" locale that we > could set a system to *before* the Debian build stuff starts? What would > that be - en_US.utf8? Your program definitely, absolutely must work in the C locale. Of course, you cannot have any non-ASCII characters in that locale, so deal with it. If you have solved that, chances are high that it will work in other locales as well (but be sure to try Turkish, as that gives a surprising meaning to "I".lower()). Regards, Martin From kyosohma at gmail.com Fri Jan 18 17:20:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jan 2008 14:20:13 -0800 (PST) Subject: What is a shortcut to the Default home directory in Windows References: <1f85750e-a85a-4bb5-8f20-cbb5939f89a3@p69g2000hsa.googlegroups.com> Message-ID: <1fddf38d-e6a2-416f-a8f8-020560970ab5@z17g2000hsg.googlegroups.com> On Jan 18, 2:19 pm, Daniel Folkes wrote: > I am trying to write a file to the users file system. > > I need it to be in there home directory in WINDOWS. I know there is a > "shortcut" to home in Linux("~"), but is there an equivalent to that > in windows. Or to get to their "Documents and Settings" directory? > > Thanks in advance for the help. > > -Daniel Folkes I personally use Tim Golden's excellent win32 API wrapper, the winshell script. You can find it here: http://timgolden.me.uk/python/winshell.html Mike From bearophileHUGS at lycos.com Tue Jan 22 10:25:56 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 22 Jan 2008 07:25:56 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> Message-ID: Alan Isaac>What is the fastest way? (Ignore the import time.)< Maybe someday someone will realize such stuff belongs to the python STD lib... If you need a lazy generator without padding, that splits starting from the start, then this is the faster to me if n is close to 2: def xpartition(seq, n=2): return izip( *(iter(seq),)*n ) If you need the faster greedy version without padding then there are two answers, one for Psyco and one for Python without... :-) If you need padding or to start from the end then there are more answers... Bye, bearophile From David.Reksten at sweco.no Wed Jan 30 04:54:29 2008 From: David.Reksten at sweco.no (David.Reksten at sweco.no) Date: Wed, 30 Jan 2008 10:54:29 +0100 Subject: SV: Unicode literals to latin-1 In-Reply-To: <60avf7F1ps52dU3@mid.uni-berlin.de> References: <60avf7F1ps52dU3@mid.uni-berlin.de> Message-ID: <7C90895B4B6EE44AAF5F16CB1F48427162C41CE470@srv-mail-02.nettverk.int> On 30. januar 2008 10:48, Marc 'BlackJack' Rintsch wrote: >On Wed, 30 Jan 2008 09:57:55 +0100, David.Reksten wrote: > >> How can I convert a string read from a database containing unicode >> literals, such as "Fr\u00f8ya" to the latin-1 equivalent, "Fr?ya"? >> >> I have tried variations around >> "Fr\u00f8ya".decode('latin-1') >> but to no avail. > >In [388]: 'Fr\u00f8ya'.decode('unicode-escape') >Out[388]: u'Fr\xf8ya' > >In [389]: print 'Fr\u00f8ya'.decode('unicode-escape') >Fr?ya 'unicode-escape' did the trick! Thank you! .david From ajaksu at gmail.com Mon Jan 7 21:08:38 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 7 Jan 2008 18:08:38 -0800 (PST) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: <1d895d6d-a649-439e-8223-0ae7d3a4eb40@l6g2000prm.googlegroups.com> On Jan 7, 11:25 am, MartinRineh... at gmail.com wrote: > There's a lot of dumb stuff out there. "Algorithms should be coded > efficiently ..." Thanks, I'll keep that in mind. > > van Rossum's guidelines tend toward "pick something and stick to it" > which is OK if you have enough experience to pick something Pythonic. > I'm a relative newbie, not qualified to pick. > > Anything written somewhere that's thorough? Any code body that should > serve as a reference? I've done this search before and it was very interesting, doing it again gave me new results that also seem valuable. Here's most of them (where PCG = Python Coding Guidelines). Cogent project PCG http://jaynes.colorado.edu/PythonGuidelines.html (also http://jaynes.colorado.edu/PythonIdioms.html) Freevo Coding Standard http://doc.freevo.org/CodingStandard Mercurial Basic Coding Style http://www.selenic.com/mercurial/wiki/index.cgi/Basic_Coding_Style PyBlosxom Coding Style Guide http://pyblosxom.sourceforge.net/blog/static/development#coding MoinMoin Coding Style http://moinmoin.wikiwikiweb.de/CodingStyle Webware Style Guidelines http://www.webwareforpython.org/Docs/StyleGuidelines.html NOAA Enhanced Forecaster Tools PCG http://www-md.fsl.noaa.gov/eft/developer/PythonCodingStandards.html BioPython Coding Conventions http://biopython.org/wiki/Contributing#Coding_conventions Mnet PCG http://mnet.sourceforge.net/coding_standards.html Michael Foord's (aka Voidspace) PCG http://www.voidspace.org.uk/python/weblog/arch_d7_2006_04_01.shtml#e296 SQLObject Coding Style http://www.sqlobject.org/DeveloperGuide.html#style-guide WxPython PCG http://www.wxpython.org/codeguidelines.php Python coding style guide for Mailman http://barry.warsaw.us/software/STYLEGUIDE.txt VoiceCode PCG http://voicecode.iit.nrc.ca/VoiceCode/uploads/codingGuidelines.html Bazaar Coding Stile Guidelines http://doc.bazaar-vcs.org/bzr.dev/en/developer-guide/HACKING.html#coding-style-guidelines IPython Developer Guidelines http://ipython.scipy.org/moin/Developer_Zone/Developer_Guidelines OSAF Chandler PCG http://chandlerproject.org/Projects/ChandlerCodingStyleGuidelines (along with http://chandlerproject.org/Projects/ChandlerEpydocStyleGuide) Twisted Coding Standard http://twistedmatrix.com/trac/browser/trunk/doc/development/policy/coding-standard.xhtml?format=raw PyPy RPython and CPython Coding Guidelines http://codespeak.net/pypy/dist/pypy/doc/coding-guide.html Django PCG (and general contribution recommendations) http://www.djangoproject.com/documentation/contributing/#coding-style Docutils PCG http://docutils.sourceforge.net/docs/dev/policies.html#python-coding-conventions Trac Coding Style http://trac.edgewall.org/wiki/TracDev/CodingStyle OLPC PCG http://wiki.laptop.org/go/Python_Style_Guide Skeletonz Coding and Naming Conventions http://orangoo.com/skeletonz/Developer_guide/Coding_convention/ http://orangoo.com/skeletonz/Developer_guide/Naming_convention/ CherryPy Code Conventions http://www.cherrypy.org/wiki/CodeConventions More generic but still good (or great) insights: Software Carpentry on style http://www.swc.scipy.org/lec/style.html Zope's Coding Style http://wiki.zope.org/zope3/CodingStyle The docstrings PEP http://www.python.org/dev/peps/pep-0257/ The NiceStyle Triad?: Pyflakes http://divmod.org/trac/wiki/DivmodPyflakes PyChecker http://pychecker.sourceforge.net/ Pylint http://www.logilab.org/857 Do you think this could be a valuable addition to the Python wiki? HTH, Daniel From kyosohma at gmail.com Fri Jan 11 12:20:05 2008 From: kyosohma at gmail.com (Mike) Date: Fri, 11 Jan 2008 09:20:05 -0800 (PST) Subject: ISO books of official Python docs References: Message-ID: On Jan 9, 2:59 pm, Fredrik Lundh wrote: > Doug Morse wrote: > > Several of the O'Reilly & Assoc. books -- such as Python in a Nutshell, The > > Python Standard Library, etc -- are in large part reproductions of the > > official docs and references. > > if you're using "reproduction" to mean "copy", I think you owe both me > and Alex a big apology. > > I am a fan of your effbot blog and I've thought about buying your book before. Can you tell me how much of it is still valid for Python 2.5 since the book was released in 2001 and written with 2.0 in mind? Are you planning to update it at some point? It would be nice to have a complete library reference with a good index at times. Thank you, Mike From madhurrajn at gmail.com Fri Jan 18 04:23:09 2008 From: madhurrajn at gmail.com (Madhur) Date: Fri, 18 Jan 2008 01:23:09 -0800 (PST) Subject: Filtering two files with uncommon column Message-ID: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> I would like to know the best way of generating filter of two files based upon the following condition I have two files. Contents of the first file is File 1 abc def hij asd sss lmn hig pqr mno File 2 jih def asd poi iuu wer wer pqr jjj I would like have the output as Output File1 asd sss lmn File2 poi iuu wer Basically I want to compare the two files based on second column. If the second column matches on both the files do not print anything, else if there is no matc h in for the second column for first file in second file then print it under Fil e1 header, else if there is no match for the second column for second file in fi rst file print it under File2 header. Thankyou Madhur From over at thepond.com Tue Jan 22 17:29:54 2008 From: over at thepond.com (over at thepond.com) Date: Tue, 22 Jan 2008 22:29:54 GMT Subject: translating Python to Assembler Message-ID: <6ircp35hju5cb2iu9ip6rc7qjt9d585cde@4ax.com> My expertise, if any, is in assembler. I'm trying to understand Python scripts and modules by examining them after they have been disassembled in a Windows environment. I'm wondering if a Python symbols file is available. In the Windows environment, a symbol file normally has a PDB extension. It's a little unfortunate that Python also uses PDB for its debugger. Google, for whatever reason, wont accept queries with dots, hyphens, etc., in the query line. For example a Google for "python.pdb" returns +python +pdb, so I get a ridiculous number of returns referring to the python debugger. I have mentioned this to Google several times, but I guess logic isn't one of their strong points. :-) From paddy3118 at googlemail.com Wed Jan 9 01:47:19 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 8 Jan 2008 22:47:19 -0800 (PST) Subject: Congratulations to the CPython Developers on an outstanding codebase Message-ID: <2c04cf4b-fa6f-4e13-9cd4-3349215abc52@f47g2000hsd.googlegroups.com> It looks a bit like an add for Coverity, but under all that, they seem to have picked Python as one of the OS projects to test with their improved testing software because our developers were so good at working on any "bugs" reported by their earlier tool. Good job guys. http://scan.coverity.com/ - Paddy. P.S. I wonder, do any closed source programming languages have such bug reports available? From python.list at tim.thechases.com Tue Jan 8 08:15:57 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 08 Jan 2008 07:15:57 -0600 Subject: Look for a string on a file and get its line number In-Reply-To: <03a301c851e1$4f211a00$0203a8c0@MOUSE> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <03a301c851e1$4f211a00$0203a8c0@MOUSE> Message-ID: <4783778D.2050406@tim.thechases.com> >> I have to search for a string on a big file. Once this string >> is found, I would need to get the number of the line in which >> the string is located on the file. Do you know how if this is >> possible to do in python ? > > This should be reasonable: > >>>> for num, line in enumerate(open("/python25/readme.txt")): > if "Guido" in line: > print "Found Guido on line", num > break > > > Found Guido on line 1296 Just a small caveat here: enumerate() is zero-based, so you may actually want add one to the resulting number: s = "Guido" for num, line in enumerate(open("file.txt")): if s in line: print "Found %s on line %i" % (s, num + 1) break # optionally stop looking Or one could use a tool made for the job: grep -n Guido file.txt or if you only want the first match: sed -n '/Guido/{=;p;q}' file.txt -tkc From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 06:51:22 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 12:51:22 +0100 Subject: no pass-values calling? In-Reply-To: References: <13or6esikdrqa33@corp.supernews.com> Message-ID: <478def8f$0$28424$426a34cc@news.free.fr> J. Peng a ?crit : > On Jan 16, 2008 2:30 PM, Steven D'Aprano > wrote: >> On Wed, 16 Jan 2008 13:59:03 +0800, J. Peng wrote: >> >>> Hi, >>> >>> How to modify the array passed to the function? I tried something like >>> this: >>> >>>>>> a >>> [1, 2, 3] >>>>>> def mytest(x): >>> ... x=[4,5,6] >> >> This line does NOT modify the list [1, 2, 3]. What it does is create a >> new list, and assign it to the name "x". It doesn't change the existing >> list. >> > > Sounds strange. > In perl This is Python, not Perl. Please follow the links provided by Steven and read carefully. From bblais at bryant.edu Wed Jan 9 09:43:07 2008 From: bblais at bryant.edu (Brian Blais) Date: Wed, 9 Jan 2008 09:43:07 -0500 Subject: packaging questions Message-ID: Hello, I am trying to package a number of python files, and I plan to use Mercurial to do the version control. In more established projects that I see, I notice that there are a number of files, like Changelog, MANIFEST, INSTALL, etc... that would seem to be generated automatically. Also, within the python code, and the setup.py, there are properties like __version__ which one would like to have generated automatically as well, so that you aren't hand-editing a number of files. Is there a standard way of doing this? thanks, Brian Blais -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Fri Jan 11 06:16:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jan 2008 12:16:53 +0100 Subject: Why Python.exe is breaking with memory dump?? In-Reply-To: References: Message-ID: abhishek wrote: > Hi group i have created a simple .pyd using which i m able call C > function from python code. There are around 6 such functions. 4 of > them work great. But when i try to run other two python's exe breaks > giving memory dump. > > Any pros or cons on what led to such a situation.. Is it a problem in > my c code?? yes. check for reference counting errors, plus the usual C stuff: memory allocation errors, memory overwrites, bogus pointers, etc. From mccredie at gmail.com Fri Jan 18 12:55:56 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 18 Jan 2008 09:55:56 -0800 (PST) Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <54efb87e-5a54-42a4-adcc-3d05e03a4859@s8g2000prg.googlegroups.com> On Jan 18, 9:15 am, David Sanders wrote: > Hi, > > I am processing large files of numerical data. Each line is either a > single (positive) integer, or a pair of positive integers, where the > second represents the number of times that the first number is > repeated in the data -- this is to avoid generating huge raw files, > since one particular number is often repeated in the data generation > step. > > My question is how to process such files efficiently to obtain a > frequency histogram of the data (how many times each number occurs in > the data, taking into account the repetitions). My current code is as > follows: > > ------------------- > #!/usr/bin/env python > # Counts the occurrences of integers in a file and makes a histogram > of them > # Allows for a second field which gives the number of counts of each > datum > > import sys > args = sys.argv > num_args = len(args) > > if num_args < 2: > print "Syntaxis: count.py archivo" > sys.exit(); > > name = args[1] > file = open(name, "r") > > hist = {} # dictionary for histogram > num = 0 > > for line in file: > data = line.split() > first = int(data[0]) > > if len(data) == 1: > count = 1 > else: > count = int(data[1]) # more than one repetition > > if first in hist: # add the information to the histogram > hist[first]+=count > else: > hist[first]=count > > num+=count > > keys = hist.keys() > keys.sort() > > print "# i fraction hist[i]" > for i in keys: > print i, float(hist[i])/num, hist[i] > --------------------- > > The data files are large (~100 million lines), and this code takes a > long time to run (compared to just doing wc -l, for example). > > Am I doing something very inefficient? (Any general comments on my > pythonic (or otherwise) style are also appreciated!) Is > "line.split()" efficient, for example? > > Is a dictionary the right way to do this? In any given file, there is > an upper bound on the data, so it seems to me that some kind of array > (numpy?) would be more efficient, but the upper bound changes in each > file. My first suggestion is to wrap your code in a function. Functions run much faster in python than module level code, so that will give you a speed up right away. My second suggestion is to look into using defaultdict for your histogram. A dictionary is a very appropriate way to store this data. There has been some mention of a bag type, which would do exactly what you need, but unfortunately there is not a built in bag type (yet). I would write it something like this: from collections import defaultdict def get_hist(file_name): hist = defaultdict(int) f = open(filename,"r") for line in f: vals = line.split() val = int(vals[0]) try: # don't look to see if you will cause an error, # just cause it and then deal with it cnt = int(vals[1]) except IndexError: cnt = 1 hist[val] += cnt return hist HTH Matt From fredrik at pythonware.com Sat Jan 12 04:51:02 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Jan 2008 10:51:02 +0100 Subject: removeall() in list In-Reply-To: <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > I'm writing an NxN observer pattern, mostly for my own personal > exploration. Two threads -might- be calling 'Disconnect' at the same > time, and I can't even guarantee that the function runs properly. > > for emelem in [ e for e in emlist if e.func is func ]: > try: > emlist.remove( emelem ) > except ValueError: > pass so use a lock. it's a whopping two lines of code: creation: lock = threading.Lock() usage: with lock: for emelem in ... ... more here: http://effbot.org/zone/thread-synchronization.htm and btw, looping over a list to figure out what you want to remove from that list is a bit pointless. better just create a new list: with lock: # get rid of all func instances emlist = [e for e in emlist if e.func is not func] an alternative approach would be to replace emlist with a dictionary, keyed on func objects. that'll let you remove all items associated with a given function with a single atomic operation: del emdict[func] From mgierdal at gmail.com Fri Jan 18 11:10:45 2008 From: mgierdal at gmail.com (mgierdal at gmail.com) Date: Fri, 18 Jan 2008 08:10:45 -0800 (PST) Subject: how to resolve Windows pathnames into cygwin ones Message-ID: I am looking for a function to resolve 'F:/foo/bar' into '/cygdrive/f/ foo/bar'. I get the original dirpath from tkFileDialog.askdirectory in a Windows form and none of os.path.* functions seem to resolve it to a cygwin form. Rather they _append_ it to the current directory, resulting at best in a monster '/cygdrive/c/whatever/f/foo/bar'. It's all being developed under cygwin currently (so it is a kind of mixed environment), but I would like the fix to work correctly in any environment. Thanks, Marcin From paddy3118 at googlemail.com Thu Jan 24 10:26:27 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 07:26:27 -0800 (PST) Subject: piping into a python script References: Message-ID: On Jan 24, 3:17 pm, Donn Ingle wrote: > Hi, > (Gnu/Linux - Python 2.4/5) > Given these two examples: > 1. > ./fui.py *.py > 2. > ls *.py | ./fui.py > > How can I capture a list of the arguments? > I need to get all the strings (file or dir names) passed via the normal > command line and any that may come from a pipe. > > There is a third case: > 3. > ls *.jpg | ./fui.py *.png > Where I would be gathering strings from two places. > > I am trying to write a command-line friendly tool that can be used in > traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. > > I have tried: > 1. pipedIn = sys.stdin.readlines() > Works fine for example 2, but example 1 goes into a 'wait for input' mode > and that's no good. Is there a way to tell when no input is coming from a > pipe at all? > > 2. import fileinput > for line in fileinput.input(): > print (line) > But this opens each file and I don't want that. > > I have seen a lot of search results that don't quite answer this angle of > the question, so I'm trying on the list. > > \d Try the fileinput module. What you describe above is pretty close to the unix 'standard' but not quite. if we substitute the lp command instead of ./fui, the command normally takes a list of files to act on as its arguments, and anything piped in goes to its stdin where it is processed if it has an argument of - fileinput works that way but you may have problems with your: ls *.jpg | ./fui.py *.png Which might better be expressed as: ./fui.py `ls *.jpg` *.png which would work for ls and a python program using the fileinput module. - Paddy. From fetchinson at googlemail.com Tue Jan 8 16:31:11 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 8 Jan 2008 13:31:11 -0800 Subject: Newbie question: Classes In-Reply-To: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com> References: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com> Message-ID: > Basically, I have created a program using tkinter without using any class > structure, simply creating widgets and functions (and finding ways around > passing variables from function to function, using global variables etc). > The program has become rather large ( lines?) I am trying to now put it into > a class structure, because I hear it is easier to handle. > > So basically, I put all the stuff into a class, making the widgets in the > "def __init__(self, root)" (root being my Tk() ) and then I have had to put > a "self." in front of any instance of any variable or widget. Is this right? > it seems like nothing is any easier (except having variables locally). Is > this right? Should I be creating more classes for different things or what? Use the method that works best for you. If you like the procedural approach more then don't worry about being object oriented. The good thing is that python is multi-paradigm so if custom objects don't make your life easier then just forget about them :) From stefan.behnel-n05pAM at web.de Thu Jan 3 08:50:05 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 03 Jan 2008 14:50:05 +0100 Subject: ElementTree should parse string and file in the same way In-Reply-To: References: <4778A47B.9020201@web.de> <13njba091eipl6f@corp.supernews.com> <477C9804.40003@web.de> Message-ID: <477CE80D.3050508@web.de> Fredrik Lundh wrote: > Stefan Behnel wrote: > >>> My take on the API decision in question was always that a file is >>> inherently an XML *document*, while a string is inherently an XML >>> *fragment*. >> >> Not inherently, no. I know some people who do web processing with an XML >> document coming in as a string (from an HTTP request) /.../ > > in which case you probably want to stream the raw XML through the parser > *as it arrives*, to reduce latency (to do that, either parse from a > file-like object, or feed data directly to a parser instance, via the > consumer protocol). It depends on the abstraction the web framework provides. If it allows you to do that, especially in an event driven way, that's obviously the most efficient implementation (and both ElementTree and lxml support this use pattern just fine). However, some frameworks just pass the request content (such as a POSTed document) in a dictionary or as callback parameters, in which case there's little room for optimisation. > also, putting large documents in a *single* Python string can be quite > inefficient. it's often more efficient to use lists of string fragments. That's a pretty general statement. Do you mean in terms of reading from that string (which at least in lxml is a straight forward extraction of a char*/len pair which is passed into libxml2), constructing that string (possibly from partial strings, which temporarily *is* expensive) or just keeping the string in memory? At least lxml doesn't benefit from iterating over a list of strings and passing it to libxml2 step-by-step, compared to reading from a straight in-memory string. Here are some numbers: $$ cat listtest.py from lxml import etree # a list of strings is more memory expensive than a straight string doc_list = [""] + ["
test"] * 2000 + [""] # document construction temporarily ~doubles memory size doc = "".join(doc_list) def readlist(): tree = etree.fromstringlist(doc_list) def readdoc(): tree = etree.fromstring(doc) $$ python -m timeit -s 'from listtest import readlist,readdoc' 'readdoc()' 1000 loops, best of 3: 1.74 msec per loop $$ python -m timeit -s 'from listtest import readlist,readdoc' 'readlist()' 100 loops, best of 3: 2.46 msec per loop The performance difference stays somewhere around 20-30% even for larger documents. So, as expected, there's a trade-off between temporary memory size, long-term memory size and parser performance here. Stefan From boblatest at yahoo.com Tue Jan 8 05:10:20 2008 From: boblatest at yahoo.com (Robert Latest) Date: 8 Jan 2008 10:10:20 GMT Subject: popen question References: <5ugtigF1ia3o4U5@mid.dfncis.de> <5ugulaF1hqn2cU1@mid.uni-berlin.de> <5ugv5dF1i0edtU1@mid.dfncis.de> <87fxx8mycm.fsf@mulj.homelinux.net> Message-ID: <5uh0gcF1hoialU2@mid.dfncis.de> Hrvoje Niksic wrote: > stdio uses different buffering strategies depending on the output > type. When the output is a TTY, line buffering is used; when the > output goes to a pipe or file, it is fully buffered. Makes sense. > If you see lines one by one, you are in luck, and you can fix things > on the Python level simply by avoiding buffering in popen. If not, > you will need to resort to more advanced hackery (e.g. fixing stdio > using LD_PRELOAD). Do I really? After all, the shell itself doesn't hack stdio, does it? Anyway, I'm taking this over to comp.unix.programmer since it really isn't a python problem. Thanks, robert From ptmcg at austin.rr.com Mon Jan 7 13:33:14 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 7 Jan 2008 10:33:14 -0800 (PST) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> <0b11ce6b-3565-41b6-8e63-17cb941b8197@i7g2000prf.googlegroups.com> Message-ID: <105594e7-39bd-4e6a-9d21-71ba6b1fabfa@e10g2000prf.googlegroups.com> On Jan 7, 12:26?pm, MartinRineh... at gmail.com wrote: > Guilherme Polo wrote: > > foo = [ > > ? ? 'too long', > > ? ? 'too long too', > > ? ? ... > > ? ? ] > > OK, I'll put it there too, and it will be easy for us to read each > other's code (at least in this particular). While not required by any means, you will also find it handy to follow *every* entry in the list with a comma, even the last one in the list (this is legal Python). That is, in your example: foo = [ 'too long', 'too long too', 'too long too', 'last item', ] Later on when you want to reorder the items, then you can just copy/ paste whole lines, even if moving to or from the bottom of the list. This is also a good argument for putting the closing ']' on its own line, instead of on the same line as the last item. -- Paul From boblatest at yahoo.com Wed Jan 9 07:41:38 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 12:41:38 GMT Subject: How does unicode() work? References: <5ujt96F1i6h37U1@mid.dfncis.de> Message-ID: <5ujto2F1i6h37U2@mid.dfncis.de> Robert Latest wrote: > ...but it barfs when actually fed with iso8859-1 characters. Specifically, it says: UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 0: ordinal not in range(128) which doesn't make sense to me, because I specifically asked for the iso8859-1 decoder, not the 'ascii' one. robert From gagsl-py2 at yahoo.com.ar Sun Jan 27 14:15:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 Jan 2008 17:15:45 -0200 Subject: Replacing a package with another References: Message-ID: En Sat, 26 Jan 2008 12:10:03 -0200, J. Pablo Fern?ndez escribi?: > Is it possible to replace one package with another at runtime, that is, I > have package a.blah which I want instead of b.blah, so I can "inject" > functionality in an existing package? It might be done, just assign the replacement functions/classes to the existing module. This has the same warnings as the reload() function: already created objects maintain their original behavior, already imported names from modules maintain their original value, already bound names to default arguments maintain their original value, etc. So it is best to do it as early as possible, but anyway some effects can't be avoided: === a.py === default_tax_pct = 21 print "in a, default_tax_pct=",default_tax_pct def foo(): print "original foo" def tax(amount, pct=default_tax_pct): print amount, pct, amount*pct/100 === path_a.py === import a def foo(): print "other foo" print "patching a.foo", a.foo = foo print a.foo print "patching a.default_tax_pct", a.default_tax_pct = 15 print a.default_tax_pct === main.py === import a from a import default_tax_pct import patch_a print "in main, a.default_tax_pct", a.default_tax_pct print "in main, default_tax_pct", default_tax_pct print "calling a.foo:" a.foo() print "calling a.tax(100.0):" a.tax(100.0) === output === in a, default_tax_pct= 21 patching a.foo patching a.default_tax_pct 15 in main, a.default_tax_pct 15 in main, default_tax_pct 21 calling a.foo: other foo calling a.tax(100.0): 100.0 21 21.0 -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Wed Jan 9 15:26:05 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 09 Jan 2008 21:26:05 +0100 Subject: Python too slow? In-Reply-To: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> Message-ID: <47852dd8$0$27994$426a74cc@news.free.fr> dongie.agnir at gmail.com a ?crit : > I'm pretty new to Python, and even newer to Image/Video processing, > and trying to get started on a project similar to GRL Vienna's laser > marker. I found some sample code here http://janto.blogspot.com/2006/01/motion-capture-in-python.html, > but after running the code with the included sample input file, it > seems quite slow (1-2 seconds from start to finish to do the 800 by > 600 gif image). > > Is there a better way to do color tracking, Not having any experience with this domain, I can't comment on this. > or is Python just too slow > as an interpreted language Being "interpreted" is a quality of an implementation, not of a language. And the reference implementation of Python (CPython) is not interpreted, it's compiled to byte-code, which is then executed by a VM (just like Java). So while CPython may possibly be too slow for your application (it can indeed be somewhat slow for some tasks), the reasons are elsewhere (hint: how can a compiler safely optimize anything in a language so dynamic that even the class of an object can be changed at runtime ?) ... > to do any effective color tracking? From dstromberglists at gmail.com Mon Jan 14 12:41:35 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Mon, 14 Jan 2008 17:41:35 GMT Subject: bags? 2.5.x? Message-ID: Is there a particular reason why bags didn't go into 2.5.x or 3000? I keep wanting something like them - especially bags with something akin to set union, intersection and difference. From phillip.sitbon at gmail.com Fri Jan 11 19:37:29 2008 From: phillip.sitbon at gmail.com (Phillip Sitbon) Date: Fri, 11 Jan 2008 16:37:29 -0800 (PST) Subject: Python in IIS + WSGI Message-ID: <86d01390-fb1c-4806-a10b-92446c008b10@k2g2000hse.googlegroups.com> Recently (finally) updated the PyISAPIe project. Version 1.0.4 includes WSGI support (tested with current Django SVN and Trac 0.10) and a Django-native handler, as well as other examples of using it as a standalone web app. Also added some installation/usage docs on the project page. Comments/feedback welcome! http://pyisapie.sourceforege.net Cheers, Phillip From ajcppmod at gmail.com Wed Jan 9 08:16:58 2008 From: ajcppmod at gmail.com (ajcppmod at gmail.com) Date: Wed, 9 Jan 2008 05:16:58 -0800 (PST) Subject: flatten sequences in a dictionary Message-ID: Hi I wondering if someone could give me a pointer. I have a dictionary with the following structure: testDict = dict(foo=((1,2,3),(1,4,3)), bar=((3,2,1),(9,8,7,)), mumble=((1,2,3),)) I am trying to create a list of the the 3 element tuples using itertools (just for a bit of fun). I'm trying this: list(itertools.chain(testDict.itervalues()) but that's doesn't work. I think I need a way to convert the iterator returned by itervalues() into a sequence of iterables. Any clues? Thanks Andy From hkimball at eti-web.com Sun Jan 6 20:23:11 2008 From: hkimball at eti-web.com (hkimball at eti-web.com) Date: Sun, 6 Jan 2008 17:23:11 -0800 (PST) Subject: ctypes Message-ID: <5bc0722e-efe7-4067-9bf4-afee3f1c9a03@f3g2000hsg.googlegroups.com> I am having trouble with ctypes: i can load the third party dll, and gain access to the function but the function calls do not actually perform their intended purpose. I have tried this in both interactive mode and from a saved script. I know that is a somewhat vague description but any help would be greatly appreciated. thanks harold kimball From lists at cheimes.de Sat Jan 19 18:18:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 20 Jan 2008 00:18:09 +0100 Subject: Python 3000 and import __hello__ In-Reply-To: References: Message-ID: <47928531.7030806@cheimes.de> Brad wrote: > Just playing around with Python3000 a2 release on Windows XP 32-bit x86. > > import __hello__ > > doesn't print 'hello world...' as it does on 2.5 > > The import doesn't fail or generate errors... just no output. Perhaps > this is by design? I changed the __hello__ frozen module a while ago. The print was unreliable for some new unit tests. Christian From alan.nichols at staarinc.com Fri Jan 25 12:50:29 2008 From: alan.nichols at staarinc.com (Alan Nichols) Date: Fri, 25 Jan 2008 11:50:29 -0600 Subject: Windows issue -- method to control generation of bytecode files Message-ID: <000501c85f7a$c6b07100$54115300$@nichols@staarinc.com> Hello, I'm curious to know if there is a means available to control the location in which bytecode files are generated. It seems that for some types of user accounts (specifically regular users, not superusers or admins) MS Windows will not allow writes to the C:\Program Files directory. As a result, .py source files cannot be located in C:\Program Files because the .pyc files cannot be generated there. Up to now we have been installing the Python code in another directory; we'd like to move away from this if we can. Is anyone aware of a workaround that would address this issue? Skip Montonaro raised a suggestion in 2003 (PEP304) that looked promising but it never generated much interest. Thank you for your help, Alan Nichols -------------- next part -------------- An HTML attachment was scrubbed... URL: From ggpolo at gmail.com Mon Jan 7 06:31:52 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 09:31:52 -0200 Subject: python syntax In-Reply-To: <633886.19582.qm@web45510.mail.sp1.yahoo.com> References: <633886.19582.qm@web45510.mail.sp1.yahoo.com> Message-ID: 2008/1/7, mpho raborife : > Please help me get this syntax right: > > os.system("HCopy -T 1 -C" 'os.path.join(conf_dir, "/hcopy.conf")' "-S" > 'os.path.join(list_dir, "hcopy_list.txt")') > import os import subprocess subprocess.Popen(["HCopy", "-T", "1", "-C", os.path.join(conf_dir, "hcopy.conf"), "-S", os.path.join(list_dir, "hcopy_list.txt")]) > > > ________________________________ > Looking for last minute shopping deals? Find them fast with Yahoo! Search. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bruno.desthuilliers at gmail.com Sat Jan 12 11:52:16 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jan 2008 08:52:16 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> Message-ID: On 11 jan, 15:41, Hrvoje Niksic wrote: > Bruno Desthuilliers > writes: > > > fact 1: CPython compiles source code to byte-code. > > fact 2: CPython executes this byte-code. > > fact 3: Sun's JDK compiles source code to byte-code. > > fact 4: Sun's JDK executes this byte-code. > > > Care to prove me wrong on any of these points ? Don't bother: you > > can't. > > Fact 4 is misleading because it is only one option available to Sun's > JDK. Sun's JDK is also capable of transforming the byte-code to > native code and letting the processor execute that instead of the > original byte code, and that is where the most significant speed > increase comes from. Most importantly, it does so automatically, by > default, with no programmer intervention or configuration, and with > 100% compatibility, so it doesn't compare well to Python accelerators > like psyco. Then fact 1 is misleading too since Python handles the compilation automatically without programmer's intervention while Java requires someone to explicitely invoke the byte-code compiler. I just don't understand what's all that fuss with this simple and quite comparison of Java and Python. You can google this ng archives, you'll find hundreds of posts saying the same thing, and everyone so far seemed to be smart enough to understand that this had nothing to do with the byte-code specifications, VM implementation and presence or absence of a JIT compiler. Anyway, I do maintain that what I said is 100% correct, 100% accurate given the context, and 0% misleading unless you're clueless enough to not be able to parse a single english sentence (in which case I just can't help). As a matter of fact, this didn't seem to "mislead" the OP into thinking such a thing. Regards. From gagsl-py2 at yahoo.com.ar Thu Jan 24 01:51:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 Jan 2008 04:51:14 -0200 Subject: Function wrappers References: Message-ID: En Thu, 24 Jan 2008 00:16:01 -0200, escribi?: > def f( callback, *bar, **bkwar ): > def preg ( callfore, *far, **fkwar ): > return g( callback, callfore, bar, bkwar, far, fkwar ) > return preg > > Does anyone see a way to rewrite this, perhaps along the lines of > partial( partial, partial )? Ok to modify 'g' call. What's wrong with this? Why do you want to rewrite it? -- Gabriel Genellina From fredrik at pythonware.com Tue Jan 15 12:22:29 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jan 2008 18:22:29 +0100 Subject: ElementTree and namespaces in the header only In-Reply-To: <2c769fe0-8add-4aa1-9657-b8ee5f76cb91@k39g2000hsf.googlegroups.com> References: <2c769fe0-8add-4aa1-9657-b8ee5f76cb91@k39g2000hsf.googlegroups.com> Message-ID: Peter Bengtsson wrote: > root = Element('feed', xmlns='http://www.w3.org/2005/Atom') > root.set('xmlns:se', NS_URL) > entry = SubElement(root, 'entry') > SubElement(root, 'title').text = 'Title' > SubElement(entry, SEN('category')).text = 'Category' > But surely the xmlns:se attribute on the tag is > excessive since the namespace (by the URI) is already defined in the > tag. How do I set non-default namespace tags in elements > without the automatic xmlns:se attribute repeated each time? ET 1.2's standard serializer doesn't take explicitly set namespaces into account. If you want full control over namespace generation, you have to do it yourself: http://effbot.org/zone/element-namespaces.htm#explicitly-setting-namespace-attributes ET 1.3 provides a default_namespace option for this specific case (but you still have to use universal names for everything that should go into the default namespace). From pavlovevidence at gmail.com Sat Jan 12 01:32:53 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 12 Jan 2008 01:32:53 -0500 Subject: Magic function References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com> Message-ID: On Fri, 11 Jan 2008 08:29:18 -0800, dg.google.groups wrote: > Hi all, > > I'm part of a small team writing a Python package for a scientific > computing project. The idea is to make it easy to use for relatively > inexperienced programmers. As part of that aim, we're using what we're > calling 'magic functions', and I'm a little bit concerned that they are > dangerous code. I'm looking for advice on what the risks are (e.g. > possibility of introducing subtle bugs, code won't be compatible with > future versions of Python, etc.). > > Quick background: Part of the way our package works is that you create a > lot of objects, and then you create a new object which collects together > these objects and operates on them. We originally were writing things > like: > > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > bigobj = Bigobj(objects=[obj1,obj2]) > bigobj.run() > > This is fine, but we decided that for clarity of these programs, and to > make it easier for inexperienced programmers, we would like to be able > to write something like: > > obj1 = Obj(params1) > obj2 = Obj(params2) > ... > run() > > The idea is that the run() function inspects the stack, and looks for > object which are instances of class Obj, creates a Bigobj with those > objects and calls its run() method. > > So, any comments on that approach? 1. Even if you implement magic functions, don't get rid of the straightforward "hard way". Magic functions should be for convenience only. The user should be free to choose to do it the straightforward, explicit "hard way", and not rely on the magic. In your example, Bigobj should still be available to users, and should be documented at least as well as the magic run() function. The main reason for this (aside from the philosophical question) is that users often have different needs that you can anticipate, and your magic might not meet those unanticipated needs, forcing the user to resort to hacks and workarounds. 2. If your intention is to perform this operation on all Objs, then it might be a good idea to arrange your code so that Objs are already registered by the time the user gets them. One way to do this has already been mentioned: by having the Obj class track all its instances. Another way that might be preferable is to have Bigobj create Objs on behalf of the user. Here's a stripped down example: class Bigobj(object): def __init__(self): self.tracked_objs = set() def create_object(self,*args): obj = Obj(*args) self.tracked_objs.add(obj) return obj def run(self): for obj in self.tracked_objs: # do something with obj bigobj = Bigobj() obj1 = bigobj.create_object(params1) obj2 = bigobj.create_object(params2) # maybe do something with obj1 and obj2 here bigobj.run() Carl Banks From steven.bethard at gmail.com Wed Jan 23 02:03:31 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 23 Jan 2008 00:03:31 -0700 Subject: subprocess and & (ampersand) In-Reply-To: References: Message-ID: <-pidnVUyKPNZewvanZ2dnUVZ_tyknZ2d@comcast.com> Steven D'Aprano wrote: > On Tue, 22 Jan 2008 22:53:20 -0700, Steven Bethard wrote: > >> I'm having trouble using the subprocess module on Windows when my >> command line includes special characters like "&" (ampersand):: >> >> >>> command = 'lynx.bat', '-dump', 'http://www.example.com/?x=1&y=2' >> >>> kwargs = dict(stdin=subprocess.PIPE, >> ... stdout=subprocess.PIPE, ... >> stderr=subprocess.PIPE) >> >>> proc = subprocess.Popen(command, **kwargs) proc.stderr.read() >> "'y' is not recognized as an internal or external command,\r\noperable >> program or batch file.\r\n" >> >> As you can see, Windows is interpreting that "&" as separating two >> commands, instead of being part of the single argument as I intend it to >> be above. Is there any workaround for this? How do I get "&" treated >> like a regular character using the subprocess module? > > > That's nothing to do with the subprocess module. As you say, it is > Windows interpreting the ampersand as a special character, so you need to > escape the character to the Windows shell. > > Under Windows, the escape character is ^, or you can put the string in > double quotes: > > # untested > command = 'lynx.bat -dump http://www.example.com/?x=1^&y=2' > command = 'lynx.bat -dump "http://www.example.com/?x=1&y=2"' Sorry, I should have mentioned that I already tried that. You get the same result:: >>> command = 'lynx.bat', '-dump', 'http://www.example.com/?x=1^&y=2' >>> proc = subprocess.Popen(command, ... stdin=subprocess.PIPE, ... stdout=subprocess.PIPE, ... stderr=subprocess.PIPE) >>> proc.stderr.read() "'y' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n" In fact, the "^" doesn't seem to work at the command line either:: >lynx.bat -dump http://www.example.com/?x=1^&y=2 Can't Access `file://localhost/C:/PROGRA~1/lynx/1' Alert!: Unable to access document. lynx: Can't access startfile 'y' is not recognized as an internal or external command, operable program or batch file. Using quotes does work at the command line:: C:\PROGRA~1\lynx>lynx.bat -dump "http://www.example.com/?x=1&y=2" You have reached this web page by typing "example.com", "example.net", or "example.org" into your web browser. These domain names are reserved for use in documentation and are not available for registration. See [1]RFC 2606, Section 3. References 1. http://www.rfc-editor.org/rfc/rfc2606.txt But I get no output at all when using quotes with subprocess:: >>> command= 'lynx.bat', '-dump', '"http://www.example.com/?x=1^&y=2"' >>> proc = subprocess.Popen(command, ... stdin=subprocess.PIPE, ... stdout=subprocess.PIPE, ... stderr=subprocess.PIPE) >>> proc.stderr.read() '' Any other ideas? STeVe From jzgoda at o2.usun.pl Mon Jan 28 08:59:28 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 28 Jan 2008 14:59:28 +0100 Subject: Set ulimit when using subprocess.Popen? In-Reply-To: References: Message-ID: Rob Wolfe napisa?(a): > > Jarek Zgoda napisa?(a): >> Hi, all, >> >> anybody has an idea on how to set ulimit (-v in my case, linux) for >> process started using subprocess.Popen? > > What about: > > from subprocess import call > call('ulimit -v 1000 && ulimit -v && ls', shell=True) subprocess.Popen('ulimit -v 1024; ls', shell=True) works perfect. Unfortunately, the nature of ulimit impacts deadly my application when the limit is reached, so this knowledge is of no help in my 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 paddy3118 at googlemail.com Thu Jan 24 11:38:31 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 08:38:31 -0800 (PST) Subject: piping into a python script References: Message-ID: On Jan 24, 4:02 pm, Donn Ingle wrote: > > Try the fileinput module. > > I did give the fileinput module a go, but I can't find much info on it and > the help is ... well, it's python help ;) Try http://effbot.org/librarybook/fileinput.htm > > > in goes to its stdin where it is processed if it has an argument of - > > fileinput works that way > > Okay, I did think of the dash, but did not know how to handle it. Is it a > bash thing or will that dash get passed into the args? (I am using getopt > to parse the options and args) - gets passed in and fileinput handles it. > > > which would work for ls and a python program using the fileinput > > module. > > Any examples of fileinput (that do not open each file) would be great! > (I'll go searching now anyway) fileinput is set to process each file a line at a time unfortunately. > > Thanks, Your welcome :-) - Paddy. From dblubaugh at belcan.com Thu Jan 31 20:26:52 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Thu, 31 Jan 2008 20:26:52 -0500 Subject: PLEASE ACCEPT MY SINCERE APOLOGIES In-Reply-To: References: Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380239F7FB@AWMAIL04.belcan.com> 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.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 7:30 PM To: python-list at python.org Subject: Python-list Digest, Vol 53, Issue 2 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. From donn.ingle at gmail.com Fri Jan 25 09:40:56 2008 From: donn.ingle at gmail.com (Donn Ingle) Date: Fri, 25 Jan 2008 16:40:56 +0200 Subject: piping into a python script References: <4798D092.9000308@gmx.net> Message-ID: Hexamorph wrote: > It's a bit clumsy, but seems to do what I guess you want. Hey, thanks for that! I will have a go. \d From nytrokiss at gmail.com Wed Jan 30 04:59:12 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 30 Jan 2008 10:59:12 +0100 Subject: help using python on Vista In-Reply-To: References: Message-ID: <8a6b8e350801300159o4aedcacfme7fbb84c989fa4c3@mail.gmail.com> You need to go into folder options which is in the control panel and there under the view tab click Show hidden files and folders On Jan 30, 2008 9:36 AM, Safe Alattar wrote: > I have no issues using python on XP. However on Vista I cant get the > python gui (IDLE) to open! > > I did some research and found out that I need to unhide .idlerc but I > cannot find any hidden files by that name whatsoever. Please help me. Im > fairly new to python but I want to get this going. User friendly > instructions would be much appreciated. Thanks. > > -- > 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 terry at jon.es Wed Jan 2 20:06:56 2008 From: terry at jon.es (Terry Jones) Date: Thu, 3 Jan 2008 02:06:56 +0100 Subject: Two candies In-Reply-To: Your message at 16:33:11 on Wednesday, 2 January 2008 References: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com> <736e51b5-d7f6-4523-89f1-df62256ce7c0@s19g2000prg.googlegroups.com> Message-ID: <18300.13616.437878.199164@terry.local> >>>>> "Raymond" == Raymond Hettinger writes: Raymond> * in most apps (except for sparse arrays), the initialization time Raymond> for an array is dominated by the time spent actually doing Raymond> something useful with the array (iow, this is an odd place to be Raymond> optimizing) This brings to mind an old algorithms chestnut (exercise 2.12 in the 1st edition of Aho, Hopcroft & Ullman [1]): If the implementation of an algorithm uses (for simplicity's sake) a square array to represent its data, why are _all_ such algorithms not necessarily O(n^2) due simply to the initialization requirement (supposing a model of computation that counts assignments)? Terry [1] http://www.amazon.com/Analysis-Algorithms-Addison-Wesley-Information-Processing/dp/0201000296 From steven.bethard at gmail.com Wed Jan 23 14:06:19 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 23 Jan 2008 12:06:19 -0700 Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? In-Reply-To: References: Message-ID: Kristian Domke wrote: > I am trying to learn python at the moment studying an example program > (cftp.py from the twisted framework, if you want to know) > > There I found a line > > foo = (not f and 1) or 0 Equivalent to ``foo = int(not f)`` > In this case f may be None or a string. > > If I am not wrong here, one could simply write > > foo = not f No cast to int() here. STeVe From phil at riverbankcomputing.co.uk Thu Jan 3 07:02:00 2008 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 3 Jan 2008 12:02:00 +0000 Subject: PyObject_CallObject code dump after calling 4 times In-Reply-To: References: Message-ID: <200801031202.00450.phil@riverbankcomputing.co.uk> On Thursday 03 January 2008, grbgooglefan wrote: > I have a following C++ code which uses PyObject_CallObject to evaluate > expressions dynamically. This code sets the input parameters for the > function also dynamically. After calling this function 4 times (with > these shown values), PyObject_CallObject causes application to crash > in frame_dealloc. > 1) Can some one please help me understand why is this crash happening > in frame_dealloc & how to solve it? > 2) Is there anything wrong I am doing about incrementing or > decrementing the reference counts of the object passed to > PyObject_CallObject? Yes. > 3) Is it because of the big value (2299265.500000) I am trying to > convert from double to float using PyFloat_FromDouble? > > //========================= code reduced for readability > =============== > switch(ndtyp){ > case(INT_T): > { > printf("PyInt_FromLong val %d, var %s > \n",inputVar.nionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > val = PyInt_FromLong(inputVar.nionum); > break; > } > case(LONG_T): > { > printf("PyLong_FromLong val %ld, var %s > \n",inputVar.lionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > val = PyLong_FromLong(inputVar.lionum); > break; > } > case(FLOAT_T): > { > printf("PyFloat_FromDouble val %f, var %s > \n",inputVar.fionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > val = PyFloat_FromDouble(inputVar.fionum); > break; > } > case(DOUBLE_T): > { > printf("PyFloat_FromDouble val %f, var %s > \n",inputVar.dionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > val = PyFloat_FromDouble(inputVar.dionum); > break; > } > case(STRING_T): > { > printf("PyString_FromString val %s, var %s > \n",inputVar.ioString,pEvalFunc->pExprVarsArray[nCtr].szVarName); > val = PyString_FromString(inputVar.ioString); > break; > } > default: > printf("Unknown data type [%d] for %s\n",ndtyp,pEvalFunc- > > >pExprVarsArray[nCtr].szVarName); > > } > if(!val){ > ret = -1; > printf("Failed to convert %d %s to PyObject\n",ndtyp,pEvalFunc- > > >pExprVarsArray[nCtr].szVarName); fflush(stdout); > > Py_XDECREF(pTuple); > break; > } > PyTuple_SetItem(pTuple, nCtr, val); > Py_XDECREF(val); Don't do this - PyTuple_SetItem() steals a reference to val. > } > // all variables are set, call Python function > Py_XINCREF(pTuple); Why do this? > PyObject *pResult = PyObject_CallObject(pEvalFunc- > > >pPyEvalFunction,pTuple); > > Py_XDECREF(pTuple); Why do this? > if(PyErr_Occurred()){ > PyErr_Print(); > } else { > char* plevel = NULL; > if(NULL != (plevel = PyString_AsString(pResult))){ > ret = 0; > sprintf(szEvalResult,"%s",plevel); > } > } > Py_XDECREF(pResult); pTuple will now have the same number of references as when you started the above code, so you may want to Py_DECREF() it. Phil From littlesweetmelon at gmail.com Fri Jan 18 00:22:39 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Fri, 18 Jan 2008 13:22:39 +0800 Subject: [python] How to detect a remote webpage is accessible? (in HTTP) Message-ID: Howdy, all, I want to use python to detect the accessibility of website. Currently, I use urllib to obtain the remote webpage, and see whether it fails. But the problem is that the webpage may be very large; it takes too long time. Certainly, it is no need to download the entire page. Could you give me a good and fast solution? Thank you. -- ShenLei From bronger at physik.rwth-aachen.de Sun Jan 27 13:41:07 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 27 Jan 2008 19:41:07 +0100 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <873asjdscc.fsf@physik.rwth-aachen.de> Hall?chen! Wildemar Wildenburger writes: > Andr? wrote: > >> Personally, I like the idea you suggest, with the modification >> that I would use "." instead of "@", as in >> >> class Server(object): >> def __init__(self, .host, .port, .protocol, .bufsize, .timeout): >> pass > > I like :) > > However, you can probably cook up a decorator for this (not > certain, I'm not a decorator Guru), which is not that much worse. > > Still, I'd support that syntax (and the general idea.). Well, you save one or two lines per class. Not enough in my opinion. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From mail at timgolden.me.uk Tue Jan 15 04:05:58 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jan 2008 09:05:58 +0000 Subject: hide object property from dir() function? In-Reply-To: References: Message-ID: <478C7776.5090405@timgolden.me.uk> jerryji wrote: > Sorry for this newbie question, I was puzzled why the existing > property of an object is not shown in the dir() function output. The under-development version of Python (2.6) allows for a __dir__ magic method by which the class implementer can return whatever he wishes from a dir (). This is to help, for example, modules like my WMI one which makes heavy use of __getattr__ magic to proxy across Windows COM attributes. This, in turn, helps editors and IDEs which can provide popup lists of attributes etc. All that said, I don't believe it takes any automatic account of properties. TJG class X (object): def __init__ (self, a): self.a = a print dir (X (1)) def __dir__ (self): return ['x', 'y', 'z'] X.__dir__ = __dir__ print dir (X (2))
From duncan.booth at invalid.invalid Wed Jan 23 04:30:28 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jan 2008 09:30:28 GMT Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? References: Message-ID: Kristian Domke wrote: > foo = (not f and 1) or 0 > > In this case f may be None or a string. > > If I am not wrong here, one could simply write > > foo = not f > Yes, it sounds pretty silly, and not just on the level you spotted. The only difference between the two expressions is that the original sets foo to an integer whereas your version sets it to a bool. So the question of which is most appropriate actually comes down to what foo is being used for. Is there really some code which requires a numeric value of 1 when f is None or an empty string and a value of 0 for any other string? I can't think offhand of any obvious situations where you would want that. My guess is that foo is being used later as a condition in an 'if' statement. If you really do need an integer then in Python 2.5+ another way to write it would be: foo = 0 if f else 1 Also 'foo' is a silly name since it gives no indication at about the purpose of the expression, but I'm hoping that was just you paraphrasing the code you posted. Ok, I just looked at the code, it is indeed being used as a boolean, so self.useProgressBar = not f or self.useProgressBar = f is not None if you want to be more specific about checking for None. From bignose+hates-spam at benfinney.id.au Mon Jan 14 23:21:12 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 15:21:12 +1100 Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> <874pdgf2wo.fsf@benfinney.id.au> <44c962f1-184c-4f79-9ce8-84bd69f9ef64@f47g2000hsd.googlegroups.com> Message-ID: <87odbnd8hz.fsf@benfinney.id.au> George Sakkis writes: > On Jan 14, 5:39 pm, Ben Finney > wrote: > > > I think of NotImplemented as equivalent to None; it's useful as a > > sentinel value to set an attribute to in (e.g.) an abstract class. > > My guess would be that it is more of an implementation performance > decision than semantic. Checking 'if result is NotImplemented' is much > faster than guarding the call with a try/except NotImplementedError > block Even better is not to check at all, and just try to use the return value as normal. If it's the NotImplemented object, exceptions will soon be raised that explain the problem. EAFP, dotcha know. > Semantically though, 'return NotImplemented' looks odd compared to > 'raise NotImplementedError'. I use 'NotImplemented' as the default value for something that *shouldn't* be used as-is, because the *programmer* needs to do more work on the implementation. This either means an abstract base class, that must be inherited from to override the attribute; or a section of code that needs more work directly to complete it. I have never written 'return NotImplemented' except for the implementation of __cmp__ and friends. I can't think when that would be a good idea as compared to 'raise NotImplementedError("explanatory text")' (note: create an instance, don't just raise the class object). -- \ "To succeed in the world it is not enough to be stupid, you | `\ must also be well-mannered." -- Voltaire | _o__) | Ben Finney From sjmachin at lexicon.net Sat Jan 26 01:53:16 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 22:53:16 -0800 (PST) Subject: Doesn't know what it wants References: Message-ID: On Jan 26, 5:32 pm, Jeroen Ruigrok van der Werven wrote: > -On [20080126 06:26], Tim Rau (bladedpeng... at gmail.com) wrote: > > >Line 147 reads: > > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) > > I think it expects something like: > > # badly named variable, pick something better depending on context > temp = vec2d(0, 0) > cp.cpMomentForCircle(self.mass, .2, 0, temp) That *cannot* give a different result in Python. The called function will be presented with *exactly* the same object as the OP's code does. From fredrik at pythonware.com Sun Jan 27 13:35:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Jan 2008 19:35:53 +0100 Subject: ElementTree.fromstring(unicode_html) In-Reply-To: <58b4d6e5-da52-4247-9892-3fbcfd0f1979@m34g2000hsb.googlegroups.com> References: <58b4d6e5-da52-4247-9892-3fbcfd0f1979@m34g2000hsb.googlegroups.com> Message-ID: globophobe wrote: > In [1]: unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f > \u3044\r\n' > > I need to turn this into an elementtree, but some of the data is > japanese whereas the rest is html. This string contains a
. where?
is an element, not a character. "\r" and "\n" are characters, not elements. If you want to build a tree where "\r\n" is replaced with a
element, you can encode the string as UTF-8, use the replace method to insert the element, and then call fromstring. Alternatively, you can build the tree yourself: import xml.etree.ElementTree as ET unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f\u3044\r\n' parts = unicode_html.splitlines() elem = ET.Element("data") elem.text = parts[0] for part in parts[1:]: ET.SubElement(elem, "br").tail = part print ET.tostring(elem) From noel at webeok.org Tue Jan 15 16:09:14 2008 From: noel at webeok.org (noel at webeok.org) Date: Tue, 15 Jan 2008 13:09:14 -0800 (PST) Subject: Running Multiple Versions Message-ID: <795bedbb-e21e-49b8-856d-bce83a5fced3@f10g2000hsf.googlegroups.com> Hi, We are windows shop with some unix servers as well. We run 2.4.1 and want to begin migrating to 2.5.1. I am looking for information dealing with having more than one version of python on a server at one time. I believe this is called side-by-side and all that is needed to select a version on a windows box is to set the path to the desired version of python prior to launching the script. Does this sound correct? Is there doc online that describes this? For windows, has anyone come up with a way to have the script launch the correct version at load time - similar to the she-bang method used in unix? Thanks Noel From bearophileHUGS at lycos.com Wed Jan 9 14:54:02 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 9 Jan 2008 11:54:02 -0800 (PST) Subject: Converting a bidimensional list in a bidimensional array References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> Message-ID: <005679e9-c355-4e0a-872c-e0dae3181fd0@x69g2000hsx.googlegroups.com> Santiago Romero: > - Speed Performance: Do you think that changing from list to Array() > would improve speed? I'm going to do lots of tilemap[y][x] checks (I > mean, player jumping around the screen, checking if it's falling over > a non-zero tile, and so). First of all: if you have enough memory to use a python list, then I suggest you to use a list. That said, often the best way to know the speed is to write a little testing code. Often python lists are faster than array.array (maybe because python lists actually contain pyobjects). If you want an array.array to be faster than a list you can use Psyco. Bye, bearophile From over at thepond.com Sun Jan 27 03:58:01 2008 From: over at thepond.com (over at thepond.com) Date: Sun, 27 Jan 2008 08:58:01 GMT Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> Message-ID: On Fri, 25 Jan 2008 17:44:07 -0800 (PST), ajaksu wrote: >On Jan 25, 11:36 pm, ajaksu wrote: >> On Jan 25, 11:10 pm, o... at thepond.com wrote: >[...] > >Gaah, is this what's going on? > >ajaksu at Belkar:~$ cat error.txt >This is not assembler... > >ajaksu at Belkar:~$ ndisasm error.txt >00000000 54 push sp >00000001 686973 push word 0x7369 >00000004 206973 and [bx+di+0x73],ch >00000007 206E6F and [bp+0x6f],ch >0000000A 7420 jz 0x2c >0000000C 61 popa >0000000D 7373 jnc 0x82 >0000000F 656D gs insw >00000011 626C65 bound bp,[si+0x65] >00000014 722E jc 0x44 >00000016 2E db 0x2E >00000017 2E db 0x2E >00000018 0A db 0x0A > >:/ not sure what you're saying. Sure looks like assembler to me. Take the '54 push sp'. The 54 is an assembler opcode for push and the sp is the stack pointer, on which it is operating. From g.usar.t at hotmail.es Sat Jan 12 21:05:25 2008 From: g.usar.t at hotmail.es (gustarmas) Date: Sat, 12 Jan 2008 18:05:25 -0800 (PST) Subject: HONESTO AND VERY EASY MONEY!!!!!what to in a year and did so in less than a month Message-ID: <9e6c4fac-e250-4f92-86bd-5b44fa493ef6@l1g2000hsa.googlegroups.com> ! EUROS OR INVEST 30 $ 30 DOLLARS. EARN MONEY AND SO $ HONESTA AND QUICK! Fec A FRIEND (A) has: Monday, 26 OCTOBER 2007 HOLA Read this notice, surely you. This is a great opportunity, to the extent that participants are HONESTOS SOLIDARIOS And, since there is NO INTERMEDIATE only Direct contact between persons interested ... This is a way Honest attempt to improve our economic situation. It will take you About 5 minutes to read this article and you will see that you Interested. If you really want to know if this works, just look at eople how many p Is doing this ... If this does not convince you, nothing will not !!!!!... Let this opportunity pass. If you want to read it several times until Convince you ... I do not believe, but I am now convinced and Improving my ECONOMIC SITUATION !!!!!, which was quite Bad ... It has nothing to lose, but much to gain. You will notice that something is truly ingenious, it is you and Will earn a few euros or dollars and only need to invest! $ 30 euros or $ 30 dollars! ... And this is nothing compared to what Or report you could win if you take a little time and Sacrifice ... Remember that people only need SERIOUS, AND WITH GOOD HONESTAS INTENSIONES ...!! BUSINESS FOR MAKING THIS IS NOT MAKE THE ROMPA CHAIN !!... NOW YOU EXPLICO AS CONOCI ON THIS SYSTEM ... While sailing in a page news himself as what you You are doing now ... I found an article like this, Which read: "! YOU CAN WIN THOUSANDS OF DOLLARS IN FEW WEEKS WITH AN INVESTMENT OF $ 30 OR $ 30 EUROS DOLLARS !"... Then I thought: "How OH, NO, MORE ANOTHER SCAM?", But like most Us, "curiosity might more", then went on reading ... "You send $ 5 euros, or $ 5 dollars to each of the names And addresses mentioned in this article ... "After this, write your NAME AND ADDRESS at the end of the list, Replacing the # 6 and I sent this article or put in at least 200 NEWSGROUPS (there are thousands of these on the Internet )"... After thinking over and over again and consult with friends, I decided to try it, I thought that the only thing that could lose were 6 Mail stamps and $ 30 euros or dollars ... As many of us probably felt a little concerned about the Legality of this. Then I consulted the Local Mail and I Confirmed that, in fact it was legal !!!!... I was astonished and My immediate investing $ 30 euros ... INMAGINENSE THAT !!!!!... Several days Later, I began to receive mail MONEY !!... I was happy as a child with a new toy and very surprised !!!!!... And I thought that this would end in a few days and tried to forget the Matter, in any case had already recovered investment, but the money Still coming !!!!!... In my first week I made between $ 100 and $ 300 Euro. By the end of the second week, had a total of $ 5000 (thousand euros )!!!!!... NOT BELIEVE PODIA !!!!!... In the fourth Week, $ 25,000 (twenty five thousand euros) and were still coming !!!!!. In the fourth week, I had a total of $ 65000 euros and this continues Arriving each day, the faster (in my house is the opening pass Envelopes and I getting "NEWSGROUP"). THIS IS SERIOUSLY PUSO ... NOW PERMITEME EXPLICARTE THIS AND HOW IT WORKS THE MOST IMPORTANT, THE EXCELENTEMENTE WHY IT WORKS: Step # 1: Get 6 sheets of paper and write to each one of them "PLEASE INCLUIRME AT ITS LIST OF CORRESPONDENCE OR E-MAIL. "Then write Your NAME, ADDRESS AND EMAIL (E-MAIL). NOTE: This LEGAL is what makes the system since it is paying for the Service to be included on a mailing list. Now get 6 tickets for $ 5 euros, or $ 5 and enter the 5euros dollars or an envelope with the road, enveloping the ticket with the Sheet, so that the ticket is not through on !!... It is better that the role is of a dark color to prevent thefts Correlation. ????? SL SUMAMENTE IMPORTANT THAT !!!!! Otherwise Way, the people working in the mail, which could detect Deals with money and stay with the thousands of envelopes you go Coming ... What you are doing is creating a service and as such, it does FULLY LEGAL !!!!!... From now on, you are not mand?ndole five five EUROS OR DOLLARS someone without any reason, they pay five dollars or dollars for a SERVICE LEGITIMO !!!!! . You forward the 6 envelopes to the following addresses: 1) John Alexander Valverde del Carpio. Jr. Spring j-6, Campo Marte, Paucarpata, Arequipa, Peru. 2) Alexander Roldan Francisco Romero. Carrera 65 # 10 - 102, Barrio El Limonar Cali - Colombia. (3) Humberto Zapata Sotelo. Jr. Macar? No. 279 Urb. Zarumilla, St. Martin de Porres, Lima, Peru. Postcode Lima # 31. (4) Sergio Urquiaga Gallegos. Av. Alameda del Corregidor 1234 Dep. 102. Urb. Sirius - La Molina. Lima-Peru (5) Agramonte Osiris Ricardo Pena. John Paul Pina Street # 02, Villa Flores. San Juan de la Maguana, Dominican Republic. Postcode San Juan de la Maguana # 72000. (6) Gustavo Artigas Fernando Lafuente, neighborhood san martin street Paysand? esq. Island of Flores Maldonado Uruguay Step # 2: Now remove the # 1 on the list and move the other names Numbers up (# 6 becomes the # 5 and # 5 is Becomes the # 4 and so on) and add your NAME AND ADDRESS as # 6 on the list. Step # 3: Change anything he deems necessary in this article, but Tries to keep as close as possible to the original. Now enter or Publish your article in at least 200 NEWSGROUPS (200 Announcements). There are more than 24000000 of Newsgroups on the Internet. Just 200 as a minimum, but the more put this letter with your data Newgroups more, the better the chance of receiving money as aid. HOW TO MANAGE THE NEWSGROUPS (NEWSGROUPS) 1 .- You do not need to write this letter to all yours Own. Just put your cursor at the beginning of this letter, please Click with the left mouse button and let it pressed; download it Until the end of the letter and release the mouse button. The entire letter should be "shaded". Then make a "clicking" The Right mouse button anywhere in the shaded part and COPY COPY or selected. This will cause the entire letter is at the Temporary memory your computer. 2 .- Open a new file in NOTEPAD (Notebook) or WORD ... Make Click with the right mouse button (Right click) and select PASTE or PEGAR ... GRABE or SALVE file with the name you want and you It can be identified at any time ... Since then Will have this letter on your computer and you can add your name in the # 6 on the list following the instructions that appear more Above. 3 .- (saved) recorded Taking this letter on your computer, every time As you like, you can add or change anything without problems. FOR THOSE WHO USE INTERNET EXPLORER 4 .- Go to "NEWSGROUPS" (Newsgroups), and select "POST AND ARTICLE "or" WRITING NEW MESSAGE / DISCUSSION. " 5 .- Load, look, call or invoke the rule that kept Previously. 6 .- Select the entire contents of the file containing the Letter and copy it using the same procedure described Above ... Back to "NEWSGROUPS and choose NEWS TO 'O' NEW DISCUSSION, "in this way, you are creating the space for power PEGAR the contents of the letter. 7 .- Press the "POST" or "SEND MESSAGE". FOR WHICH MANEJAN NETSCAPE 4 .- Within the programme NETSCAPE, go to the window titled "WINDOW" and select "NetscapeNews" ... Then go to the menu "OPTIONS" and select "SHOW ALL NEWSGROUPS" ... Then you will see a List all of its Server Newsgroups ... Then Click on any Newsgroup ... This Newsgroup click Under "TO NEWS", which should be up in the extreme Left of the page ... Newsgroup This will take you to the box Messages. 5 .- Fill this space. This is the title everyone will see that when To travel through the list of a particular group. 6 .- Mark or select the entire contents of the file Contains the letter and copy it using the same procedure described Previously .... Back to Newsgroup, "TO NEWS" and you are creating And empastando this letter within your program or "POSTING. 7 .- Press "SEND", which is in the top left corner and You have completed your first Newsgroup. .....????? CONGRATULATIONS !!!!!..... .....????? THAT IS ALL !!!!!..... IF YOU ACHIEVE .....????? PUDE, YOU ALSO CAN !!!!!..... .....????? FORWARD !!!!!..... All you have to do is meterte in different Newsgroups (Newsgroups) or plaster and add your text. Once you have Practice, only takes about 30 seconds for each ANNOUNCEMENT. It is further recommended that when publishing the description of this Article, try to give a name to "catch" or call the lot Care, such as: "Go NEED MONEY FAST? ... READ THIS ARTICLE" "Go NEED MONEY TO PAY YOUR DEBT?", "BAJE ARCHIVE AND READ THIS HOW CAN RECEIVE MONEY BY MAIL, "and so on., And not:" WINS MILLION IN ONE WEEK, "that nobody takes seriously. REMEMBER: IF YOU GET MORE NEWSGROUPS, MORE MONEY AND ANSWERS RECEIVE !!!!!... BUT MUST ENTER IN AT LEAST 200 NEWSGROUPS ... AND NOW THIS !!!!!... Another way would be to use your CONDUCT OF E-MAIL and send All your contacts this message. It also can expand Chain. You will be receiving money from all over the world in places that neither Known in a few days !!!!!... Eventually you will want to rent a P. O. BOX. (Zip), the number of envelopes that will go Receiving !!!!!... (((ASEG?RATE THAT ALL ADDRESSES ARE CORRECT )))... Now the WHY of all this: Of 200 envoys, say that only Receive 5 replies (very low example). Then I made $ 25 euros, or $ 25 dollars with my name in the # 6 of this letter. Now, each One of the people who sent me $ 5 euros, or US $ 5, also Make a number of 200 Newsgroups or ads from the list and only 5 persons respond to each of the original 5, this makes $ 125 Euros or dollars more than I receive. Now, these 25 individuals put a Minimum of 200 listings with my name on the # 4 and only received 5 responses each. It would make another $ 625 euros or dollars Additional. Now, those 125 people put a minimum of 200 groups with my name In the # 3 and only get 5 replies each person, I Get an additional $ 3,125 euros or dollars !!!!!, OK. Here is the More fun part, each of those 625 people put their letters Other 200 groups or ad with my name on the # 2 and each 5 receives an answer, and this makes me get $ 30,625 euros or An additional $ !!!!!... These 3125 people send this message To a minimum of 200 listings, with my name on the # 1 and only 5 People respond to the 200 ads, this means that I get $ 78,125 euros or dollars !!!!!. From an investment of $ 30 euros or dollars, do not believe it is FABULOUS !!!!!?????. And as I said earlier, that only 5 people respond to 200 groups or advertisements (the actual average is 20 to 30 People !!!!!)... IF YOU WANT A calculation SACA !!!!!... IF ONLY 15 PEOPLE RESPONDIERAN ... DAR?A THIS AS A RESULT: Being in a position # 6 ...=$ 78.00 Being in a position # 5 ...=$ 768.00 Being in a position # 4 ...=$ 12.288.00 Being in a position # 2 ...=$ 184.552.00 ????? Now comes the good, do not be afraid !!!!!: In the # 1 ........ ((((( $ 2.764.800.00 ))))). !!!!! S?????, ALMOST THREE MILLION DOLLARS OR !!!!!... THE IMPOSSIBLE BELIEVE, TRUE !!!!!?????... BUT WITH SOME OF DEDICATION, AND TIME EFFORT WE CAN ACHIEVE !!!!!... Some people come to think ... "And if anyone answer me ?"... QUEEEEE !!!!!... What is the likelihood that this will happen? ... If Thousands and thousands of people HONESTAS (like us) looking for a How to have financial independence and pay their debts !!!!!... And Are willing to try. Because if I say "NO WORSE TO FIGHT WHICH ARE NOT !".... This is a fact that you may be interested: There are an estimated 20000 to 50000 new Internet users ALL DAILY (THROUGHOUT THE WORLD) ... REMEMBER TO DO SO HONESTA, CLEAN AND PROPER and operate safely !!!... *** In step: "! ONLY THE HONESTY AND INTEGRITY OF PARTICIPANTS CAN MAKE THAT THIS OPERATING SYSTEM. "As you may have Noticed, there is no middleman "MILAGROSO" multiply the Money ... That intermediary each of the individuals involved This "FLOW OF MONEY" ... So, the only way that this Not work, is that unscrupulous individuals publish article WITHOUT SEND MONEY those concerned. Now if they ALL OR MANY This evil act and it is logical that this wonderful idea will not work As it should be ... So APELO YOUR HONESTY AND INTEGRITY ... And remember, There is a divine law which says that: "THERE THAT GIVE TO RECEIVE" ... !!!!! BENDICIONES SUERTE !!!!!..... FOR ALL AND Reply to author Forward From http Fri Jan 11 00:11:08 2008 From: http (Paul Rubin) Date: 10 Jan 2008 21:11:08 -0800 Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <7xejcplzf7.fsf@ruckus.brouhaha.com> Mike Meyer writes: > data_out = [[] for _ in data_in] > ... > But I'm curious - what's the difference between the "foreach" you have > in mind and the standard python "for"? The "for" loop, like the list comprehension, pollutes the namespace with an index variable that's not used for anything. I prefer genexps: data_out = list([] for x in data_in) From http Thu Jan 10 21:28:45 2008 From: http (Paul Rubin) Date: 10 Jan 2008 18:28:45 -0800 Subject: Minimalistic Software Transactional Memory References: <13lm7nd85v7jk70@corp.supernews.com> <13lmemmsnjuhm04@corp.supernews.com> <6b14fcf9-9549-422b-b837-afa5b32cf7f2@n20g2000hsh.googlegroups.com> Message-ID: <7xbq7tccyq.fsf@ruckus.brouhaha.com> Fuzzyman writes: > STM isn't lock free - it just abstracts the locks away from the > 'user'. You still need to lock around committing the transaction. The idea is that readers don't need locks. They just look at the version number before they start reading and after they finish. If the number didn't change, the read was successful. If it changed, they have to retry. On multiprocessor systems this relies on an instruction like CMPXCHG for writers to increment the version number. Otherwise it requires a lock separate from the version number, and multiple operations on the lock. From Lie.1296 at gmail.com Mon Jan 21 12:26:35 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 21 Jan 2008 09:26:35 -0800 (PST) Subject: Basic inheritance question References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> <4781300a$0$17701$426a74cc@news.free.fr> <29e43764-0929-478c-9bfe-2dd8a0eedb8c@h11g2000prf.googlegroups.com> <478cbc40$0$25410$426a74cc@news.free.fr> <9d7489b8-732d-4078-9ac3-43584fed7486@u10g2000prn.googlegroups.com> <478e1e3e$0$18054$426a74cc@news.free.fr> <34aa1a1f-2034-471d-91ee-2a758dab555b@f47g2000hsd.googlegroups.com> <47949466$0$18516$426a34cc@news.free.fr> Message-ID: <4e3c42c8-a198-4897-86fd-98ab254bcb94@q77g2000hsh.googlegroups.com> > > Please stop taking my words to its letters. > > So we're supposed to actually guess what you really mean ??? That's what human does, otherwise you'll "Fail the Turing Test". > >> Personally, I've seen many C++ programs with complex class designs > >> where it definitely helps to consistently use "this->". I cannot > >> remember all local (and global) variables in bigger methods. > > > In that case, you have the _option_ to do it. > > Make no sens when maintaining code wrote by someone that didn't use this > 'option'. > > (snip) > > > > >>>> it's the first argument of the function - which usually happens to be > >>>> the current instance when the function is used as a method. > >>> And that's the point, self (or anything you name it) is almost always > >>> the current instance > >> # this is a plain function. In this function, > >> # 'obj' can be whatever that happens to have a (numeric) > >> # 'stuff' attribute > >> def func(obj, arg): > >> ? ?return (obj.stuff + arg) / 2.0 > > >> # this is a class with an instance attribute 'stuff' > >> class Foo(object): > >> ? ? def __init__(self, bar): > >> ? ? ? self.stuff = bar + 42 > > >> # this is another (mostly unrelated) class > >> # with a class attribute 'stuff' > >> class Bar(object): > >> ? ?stuff = 42 > > >> # this is a dummy container class: > >> class Dummy(object): pass > > >> # now let's play: > >> import new > > >> d = Dummy() > >> d.stuff = 84 > >> print func(d, 1) > > >> d.baaz = new.instancemethod(func, d, type(d)) > >> print d.baaz(2) > > >> f = Foo(33) > >> print func(f, 3) > >> Foo.baaz = func > >> f.baaz(4) > > >> print func(Bar, 5) > >> Bar.baaz = classmethod(func) > >> Bar.baaz(6) > > >>> ?and that makes it functionally the same as Me and > >>> this in VB and Java. > >> Depends on the context, cf above !-) > > > Please again, stop taking letters to the words, I don't meant them to > > be exactly the same, rather the same would meant that they generally > > can be considered equal, > > If you still think that way after having read the above code, then I > can't help. We obviously don't share the same mental model here. I don't get what you're trying to meant, in that piece of code self is used in the regular way, in a regular context. > > exceptions exists of course. And btw, I don't > > understand what you meant by your example, they seemed to be a > > completely OK program for me, > > Indeed it's ok (even if totally useless by itself). The point is that > 'self' (or whatever you name it) is just and only the first argument of > a function, period. And it is... but I still don't get what you meant > > even though it's a bit confusing to > > follow[2]. > > Nothing in it should be confusing to anyone having a decent knowledge of > Python's object model IMHO. > > > [2] btw, the reason it's a bit confusing to follow is one of my > > points: It is a Bad Thing(tm) to use the same name for different > > variables > > Where do I "use the same name for different variables" here ? It's not confusing in the way of object model, but in the way that you used meaningless names in overloaded manner. > > even in a language like Python that enforce explicit naming > > of classes > > Python doesn't "enforce" explicit name of classes - IIRC, there are ways > to instanciate anonymous class objects. But I definitively don't see how > this relate to this discussion. We're not talking about anonymous class objects here, and I'm sure you actually understand what I meant by "naming the class" from previous discussions. > Yes, I know, "please guess what I mean" !-) but sorry, there's no sens > discussing a technical point without using accurate and appropriate > technical naming of technical concepts invlved. Well, it's not my fault for being born as a non-native speaker of English, sometimes what I meant might goes a bit off from what I write. Anyway, human languages aren't designed to be fully unambiguous, so it is natural for human to provide a margin of errors when speaking to each other, well unless you're not a human... > >>>>> Most other languages > >>>>> 1) automatically assign the containing class' object > >>>> s/containing class' object/current instance/ > >>>>> in a keyword > >>>>> (Java: this, VB: Me) behind the screen, > >>>> That's not very far from what a Python method object does - > >>>> automatically assign the current instance to something. The difference > >>>> is that Python uses functions to implement methods (instead of having > >>>> two distinct contructs), so the only reliable way to "inject" the > >>>> reference to the current instance is to pass it as an argument to the > >>>> function (instead of making it pop from pure air). > >>> It isn't very far, but Python makes it obvious about the assignment > >>> (not behind the screen). > >> Exactly. And given both the simplicity of the solution and what it let > >> you do, that's a *very* GoodThing(tm) IMHO. > > > I agree, it's a Good Thing but it doesn't make the point less pointy, > > the difference between Me/this and self is just the explicit > > assignment. Other things that is possible because of the explicit > > assignment is just a "coincidence" of design choice. > > Are you sure ? As far as I'm concerned, I think that the design choice > somehow results from what it makes possible. It's correct, IF you see it traversing from the past, when many design choice is being made for any possible features that is required. If you dumped the past for a while, it is just a "coincidence" of design choice. > >>> And it is always a Bad Thing(tm) to use the same name for two > >>> variable in the class and in function (which is the main and only > >>> source of possible ambiguity) in ANY language, even in Python. > >> Ho, yes.... Like, this would be bad ? > > >> class Person(object): > >> ? ?def __init__(self, firstname, lastname, birthdate, gender): > >> ? ? ?self.firstname = firstname > >> ? ? ?self.lastname = lastname > >> ? ? ?self.birthdate = birthdate > >> ? ? ?self.gender = gender > > >> C'mon, be serious. It's often hard enough to come with sensible names, > >> why would one have to find synonyms too ? Try to come with something > >> more readable than the above, and let us know. Seriously, this braindead > >> rule about ?"not using the same name for an attribute and a local var" > >> obviously comes from languages where the "this" ref is optional, and > >> FWIW it's obviously the wrong solution to a real problem (the good > >> solution being, of course, to use the fully qualified name for > >> attributes so there's no possible ambiguity). > > > The code fragment you've given way above (about the Foo, Bar, bazz, > > and func) also suffers from the bad habits of using the same name for > > different variables. > > Where ? And how does this answer the question above ? > > And it's not a "braindead" rule > > The way you express it, and as far as i'm concerned, it is, definitively. Perhaps I forgot to say that always might still have exceptions. > > The example you've given IS the most readable form since the function > > is _simple_, consider a function that have complex codes, possibly > > calculations instead of simply assigning initial values I'm sure you'd > > slip up between the self.* variables and the * variables once or > > twice, > > *you* would perhaps have this problem. And you would indeed have this > problem in Java or C++. In Python, this problem just don't exist. No it exists in any language, the way to avoid it is by good class design. > > possibly becoming the source of hard-to-find bugs. > > Consistant and intelligible naming is quite another problem. And it's > too much dependant on the context, language, domain and whatnot for any > rule like your one above to be universally applyable. It is universally applicable, with some exceptions of course, such as in a field where there is no agreed naming convention yet. > > > And in languages that doesn't enforce explicit naming of classes, > > I still don't understand how all this relates to the naming of class > objects ? > > Oops, sorry: you meant "in languages that has implicit instance > reference available in methods" ? Python doesn't have it, so any rule > deriving from this "feature" is out of scope here. > > > ?when > > there is the two or more same names, the one with the smallest scope > > is picked, so in _simple_ functions, the trick of using full qualified > > names and overloaded local names is still possible and feasible. In > > complex functions, the trick fails even in Python, because even if > > Python and our full-concentration-brain is aware of the difference > > between self.* and *, our spreaded-concentration-brain that is > > scanning the code for the source of bugs might get stumbled on the > > confusing use of self.* and *. > > Here again, *you* may have this problem. I don't, since I always used > explicit instance reference. I don't have that much of a problem, I only pointed out that it is possible to miss the names overloading in quick scanning. The reason why you never get stumbled is possibly because your brain memorizes the names and doesn't even understand what a name actually meant. This halved the reason of spending some time to find a meaningful name. With your brainset, it is just possible to create a program fully with names like foo and bar and never get stumbled. In this case, it excels, but it's a poor man's way of trying to be smart. > >>>> Anyway, I actually know 3 languages (4 if C# works the same) that has > >>>> this implicit 'this' (or whatever the name) 'feature', and at least 5 > >>>> that don't. So I'm not sure that the "most other languages" qualifier > >>>> really applies to point 2 !-) > >>> What's this 5 languages? > >> Smalltalk, Python, PHP, javascript, Ruby. I don't remember how Scheme, > >> CLOS and OCaml handle the case. > > > Among all them, only Javascript is considerably mainstream. > > Is that a joke ? PHP is probably the most used language for web apps > (server side of course). And Python is certainly not an obscure unknown > geek-only language no more. But anyway: you were talking about "most > other languages" - not "most mainstream languages". Yes, I'm aware that Python and PHP indeed have larger user base than perhaps smalltalk and Ruby, but nevertheless they're middle sized. What's I'm talking about mainstream is large as in large, not medium. PHP's domain has lots of competition, ASP, JSP, CGI, etc and this market is very fragmented, even though server-side scripting plays important role in the Internet, the role of each language is lessened because of the fragmentation making none of them mainstream enough. Python is shaded by Java in the market for ultra portable (VM) language. And I'm not talking about Smalltalk and Ruby here. > >>> Are they a mainstream, high-level languages > >>> or lesser known, low-level languages? C-family, Java, and Basic are > >>> the Big Three of high-level programming language. > >> None of C, C++, Java nor Basic qualify as "hi-level". C is the lowest > >> possible level above assembly, C++ is often refered to as an "object > >> oriented assembler", Java is way too static, crippled, verbose an > >> unexpressive to qualify as "hi-level" (even if it suffers from some > >> problems usually associated with higher level languages). I won't even > >> comment on basic (is that really a language at all ?). > > > Your criteria on being high-level is simply just odd. > > > My criteria on being hi-level seems quite common: automatic memory > management, portability, "rich" builtin data types, functions as first > class citizens, lexical closures, strong introspection features, strong > metaprogramming support, etc... We're talking language-wise here, not the implementation, and those criteria are for implementations. It is the case where we blindfold our eyes against "the things behind" and see only the language from the front. Yeah, perhaps "the things behind" would have some effect to the front side, like it is possible to create C with automatic memory management with little change in the language itself, it's possible to have more built-in datatypes than the standard set without major change in language itself. These are the criteria for language-wise comparison. > > The rest of the > > world recognizes C-family, Java, and Basic as high-level languages. > > C was "hi-level" wrt/ assembler, indeed. And Java is "hi-level" wrt/ > C++. Ho, and _please_ don't get me started on basic !-) And the world is content with that. C is probably the lowest shade a high level language could be, but it is still a high-level. > > If I have to say it, Python is actually lower level than Basic. Language-wise, indeed it is. Implementation-wise, Python might be higher than Basic. > > While > > Java is just below Python and C and C++ is just below Java. Why do I > > consider Basic the highest-level? Because it is the cleanest to scan > > (no confusing symbols, i.e. no curly braces, no confusing use of > > parens (Python uses (), [], and {}, VB only use ()[3]), > > Basic != VB. There are quite a few other basics here. I'm aware of that, but VB is the one with the largest user base, and I think it could be used to represent the language as a whole. And VB.NET is one with possibly the highest shade of level among other Basics. > Now if you choose this criteria, you may want to learn some Lisp dialect. > > In what way C++ resembles an assembler? > C++ is some OO stuff bolted on a very close-to-the-metal language itself > designed to write operating systems, drivers and other low-level stuff. In what way is C++ close to the metal? It's very far actually, C- family don't have a one-to-one relationship with assembly or plain executable binary. > > Have you ever programmed in > > assembly? > > I did. And surely you'd realize that the level of C and assembly is very far, perhaps the furthest leap in programming language level. > > How hard is it to create a simple program in assembly? And > > how hard is it to create a complex program in C++ > Roughly the same, thanks to scoping rules, dependencies hell, lack of > automatic memory management and overcomplex features. By saying that you've revealed that you missed my point too far. There is no point to continue talking about A when you're talking about B. > > (which AFAIK is used > > by hundreds of mega projects including CPython)? > CPython - as the name implies - is written in C. And by saying that I'm sure you agree that even C, which is lower level than C++ is high-level enough to be used in large projects like CPython. I'm interested in seeing Python implemented in pure assembly, perhaps asmPython? > > And have you ever used Basic at all? > I did. And not only VB. > > Some programmers would instantly frown upon Basic, simply because they > > don't know that Basic is "just another language". > I've used at least four different variants of Basic. Then with such experience in Basic you should realize that Basic isn't much off from other languages. > >>>>> In VB, Me is extremely rarely used, > >>>> I used to systematically use it - like I've always systematically used > >>>> 'this' in C++ and Java. > >>> And that is what reduces readability. A proficient VB/C/Java > >>> programmer > >> There are quite a few proficient C/C++/Java programmers here. As far as > >> I'm concerned, I would not pretend being one - I just have a good enough > >> knowledge of C, Java and (alas) VB to be able to get up to speed in a > >> reasonnable time frame. > >> As a side note, the problem just doesn't exists in C, which has > >> absolutely no support for OO. > > When I said C, it might mean C and C-family, > When you say "C", it means "C" to everyone reading you. Depending on the context, it's easy to rule out which means what. > > so please stop > > misunderstanding me. > Please learn to express yourself clearly. If you say "X" when you mean > "Y", *you* are the one responsible for misunderstandings. This is human > communication 101 skill. Even computers are designed to tolerate errors in data transfer, then human is less intelligent than computers you say? > >>> would frown upon the extra, unneeded garbage as they > >>> thought it was clear already that the variable refers to a class-level > > >>> variable. > >> In C++, the canonical way to make this "clear" is to use the m_name > >> convention. There must be some reason C++ programmers feel a need for > >> this "extra, unneeded garbage" ?-) > > > In some cases, an extremely complex class that can't be fragmented any > > further, the m_ convention is surely useful, but in most cases you > > could skip them out. > > You "could" skip this convention, but it's really considered bad > practice by quite a lot of C++ programmers. Bad, because a lot of them are already accustomed to it and it have become a de facto "rules". > > And the canonical way to make this "clear" is not > > the m_ convention, it's the name itself. A well-designed class would > > choose names that is recognizable instantly from the name itself, even > > without the pseudo-name appended to it (or prepended). > > I await for your exemples. > > > btw you must have been memorizing names braindeadly, because the only > > way you could stumble on that is by memorizing names braindeadly. > > Names shouldn't be memorized, it should be inferred and memorized. For > > example, when you met a variable name firstname and lastname inside a > > class called Person, you'd immediately realize that it is Class Level > > variable because you know that the function you're currently working > > on use the name initialfirstname and initiallastname. > > Fine, I now have four names to handle, each of them being possibly an > argument, a local variable, a member variable or a global variable. Great. > > Sorry but I won't buy this. THAT'S the point. You are unable to infer that the name initialfirstname and initiallastname is a local variable, since it is quite impossible for something initial to be a member variable or global. If it is a global, it shouldn't be named initial, perhaps default, if it is member variable, it should be plain vanilla firstname and lastname. This is called inferring scope from name. > >>> As I've pointed out, there is little harm in class-level variable's > >>> implicit reference. > >> Have some working experience on any non-trivial C++ project ? > > > No > > I would have been surprised if you had answer otherwise. > > > (you could say I'm a student so I've never "worked"[1]). But I've > > done some medium-sized projects in other languages. > > > [1] If you understand the irony, you'd realized I was deliberately > > misunderstanding you > > Not sure. Don't cut my words apart, it's meant to be together or it lose its sense of humor. > > >>>>> Compare the following codes: > >>>>> VB.NET: > >>>>> Public Class A > >>>>> Dim var > >>>>> Public Function aFunction() > >>>>> return var > >>>> Add three levels of inheritence and a couple globals and you'll find out > >>>> that readability count !-) > >>> It's the mental model that have to be adapted here, if the current > >>> class is inheriting from another class, you've got to think it as > >>> names from parent class as it is a native names, so you don't actually > >>> need to know where the variable comes from > >> In C++ (and VB IIRC), it might as well be a global So sorry but yes, I > >> have to know where it comes from. > > > How many times would you use globals, it is a Bad Thing(tm) to use > > globals in the first case. > > It is, most of the time, indeed. > > The problem is that you rarely start a project from scratch - most of > the time, you have to work on legacy code. And you really seldom have > the possibility to do a major rewrite to fix all warts. But it is always possible to reduce the most critical of all of them. > > In some exceptional cases globals might be > > unavoidable, but it is trivial to work out that you have to reduce the > > amount of globals to a minimum, in almost any cases to a number you > > can use a hand to count with. > > That very nice, from a theoretical POV. That's alas just not how it > works in real life. A bit utopic, I agree, but it's always possible. > > And applying the hacks mentioned, why > > don't you use the m_ convention for globals, and retains the > > convenience of m_-free variables in your class variable. You use class > > variable much more often than globals, and in most projects class- > > level variable is used just as often as local-variable. > > The problem is not what *I* (would) do, but how is the existing code. > > >>> since knowing where it > >>> comes from is breaking the encapsulation > >> Nope, it's knowing what you're doing and how the piece of software at > >> hand is working. And FWIW, while data hiding is one possible mean of > >> encapsulation, it's by no way a synonym for encapsulation. > > > I agree that knowing an underlying class's implementation is useful > > (in fact, very useful) but what I'm talking is about should-ness, > > we > > shouldn't _need_ to know the underlying implementation, > > How can you hope to extend a class without _any_ knowledge of it's > implementation ? By knowing its interface is usually enough to extend a class. (USUALLY!) > >>> (which, in Python is very > >>> weakly implemented, which favors flexibility in many cases[1]). > >>> [1] In Python, it is impossible to create a completely private > >>> variable, which is the reason why the mental model of these other > >>> languages doesn't fit Python. > >> Never heard about the infamous '#define private public' hack in C++ ? > >> And don't worry, there are also ways to get at so called 'private' vars > >> in Java. > > > No, but it's violating the language's rule. > > Nope. It's just making use of some part of the language's rules. No, its a hack that should be illegal, a kind of abuse of rules. > > Python OTOH, provides > > formal ways to got to private vars. > > Python doesn't have "private vars" at all. THAT'S the point. Even __vars and _vars that are supposed to be (semantic-wise) the private variable of Python is accessible from outside while still using a formal ways of accessing it (instead of a hack) > > It's easy to keep track of globals, as you shouldn't have a > > lot of them even in a huge project. > > Can't you understand that starting a new project afresh is *not* the > common case ? But I'm sure even an old, dirty codes wouldn't usually have as much global as a twenty pages listing of globals. If they do, then just quit that job. > >>> As a final note: > >>> I don't think implicit class reference is superior to explicit class > >>> reference, neither > >> ... > > > I'm sure you don't believe it since I'm talking on implicit's side, > > but that's the fact, I just pointed you out that implicits do have its > > positive side (even if you don't consider them positive in _your_ > > book) but that doesn't meant I believe it is better than the other. > > > To clear things up: > > As a final note: > > I don't think implicit class reference is superior to explicit class > > reference, but I don't think the vice versa is true either. > > Once again : what classes have to do with this ? > > Seriously, how can you hope to be taken seriously when you're obviously > confusing such important concepts as instance and class ? I'm struggling with English as of now, so please make me more confused by having to choose the most proper terms, when it is easy to rule out what I meant. This is going to be my last two cents on this topic. I'm tired of this pointless discussion. We could like a language even though we have principal differences on how to see the language and how to think about it. From paddy3118 at googlemail.com Thu Jan 24 10:12:14 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 07:12:14 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: <32dfff9c-ec49-424d-8d56-0775f22740b2@i3g2000hsf.googlegroups.com> On Jan 24, 2:28 pm, Christian Heimes wrote: > Antoon Pardon wrote: > > That doesn't follow. The problem is not that x < nan returns False > > because that is correct since x isn't smaller than nan. The problem > > is cmp(x, nan) returning 1, because that indicates that x is greater > > than nan and that isn't true. > > Please report the problem. cmp(), min() and max() don't treat NaNs > right. I don't think that x < nan == False is the correct answer, too. > But I've to check the IEEE 754 specs. IMHO < nan and > nan should raise > an exception. > > Christian To a floating point interested layman such as I, treating not-a-number comparisons with floats should give the same result as comparing a fileobject (also not-a-number), with a float. Or does nan have /need a more domain specific interpretation? - Paddy. From jzgoda at o2.usun.pl Tue Jan 8 04:53:21 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 08 Jan 2008 10:53:21 +0100 Subject: Pet Store In-Reply-To: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com> References: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com> Message-ID: George Maggessy napisa?(a): > I'm an experience Java developer trying to learn Python. I just > finished the Python tutorial on python.org and I'm currently reading > the "Learning Python" book. However, if I could find something like a > simple web app with some best practices, such as those famous "Java > Pet Store" apps, I think that would help me to fill up some gaps in my > learning process. Does anybody know any app like that? TurboGears and Pylons both have "wiki" tutorials. Django has "poll" tutorial. There are plenty others on the web. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From bignose+hates-spam at benfinney.id.au Wed Jan 16 16:50:18 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 17 Jan 2008 08:50:18 +1100 Subject: import from question References: <4a172247-a416-426f-9285-112efe593f09@f47g2000hsd.googlegroups.com> <478d04d4$0$26042$88260bb3@free.teranews.com> <87tzleb2st.fsf@benfinney.id.au> <478E658A.9070003@tobiah.org> Message-ID: <87prw1bftx.fsf@benfinney.id.au> Tobiah writes: > Ben Finney wrote: > > Tobiah writes: > > > >> This is a little surprising. So "from mod import *" really copies > >> all of the scalars into new variables in the local namespace. > > > > No. Nothing is copied. All the objects (remembering that in Python, > > *everything* is an object) created by the code in module 'mod' are > > given names in the current namespace. > > Yeah, copied. Just as in: > > >>> a = 3 > >>> b = a > >>> a = 5 > >>> b > 3 > >>> Again, those aren't copies. There is only one instance of each value, referenced by multiple names. This is made clearer by using a mutable value: >>> a = [1, 2, 3] >>> b = a >>> c = b >>> a = [4, 5, 6] >>> a, b, c ([4, 5, 6], [1, 2, 3], [1, 2, 3]) >>> a.append("spam") >>> b.append("eggs") >>> a, b, c ([4, 5, 6, 'spam'], [1, 2, 3, 'eggs'], [1, 2, 3, 'eggs']) The value referenced by 'b' and 'c' is one instance; they don't have copies of the value. Assignment binds a reference to a value, it doesn't make a copy. A "copy" is what's implemented by the standard library 'copy' module, hence the name. -- \ "Whenever you read a good book, it's like the author is right | `\ there, in the room talking to you, which is why I don't like to | _o__) read good books." -- Jack Handey | Ben Finney From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 23 08:04:15 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 23 Jan 2008 14:04:15 +0100 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> Message-ID: <5vosafF1nn9odU2@mid.individual.net> Grant Edwards wrote: > Trying to find assembly language stuff to look at is futile. > Python doesn't get compiled into assembly language. So, how do processors execute Python scripts? :) > If you want to learn Python, then read a book on Python. ACK. Regards, Bj?rn -- BOFH excuse #198: Post-it Note Sludge leaked into the monitor. From python.leojay at gmail.com Sun Jan 6 10:00:02 2008 From: python.leojay at gmail.com (Leo Jay) Date: Sun, 6 Jan 2008 23:00:02 +0800 Subject: C++ equivalent of comp.lang.python? In-Reply-To: <60597295-1493-493c-969c-a14dd7da98a3@s19g2000prg.googlegroups.com> References: <60597295-1493-493c-969c-a14dd7da98a3@s19g2000prg.googlegroups.com> Message-ID: <4e307e0f0801060700v9beb978hc3dae8f063e79b3c@mail.gmail.com> On Jan 4, 2008 1:39 AM, wrote: > Hopefully this isn't too OT. > > One thing I like about comp.lang.python is the breadth of topics > discussed here. People can ask about Python installation and > configuration issues on specific platforms, compare third party > libraries, ask for book recommendations, and discuss current Python > projects. Lurking here has greatly increased my understanding of > Python over the last year or so. > > I also do a lot of C++ development, but I've never found a similar > discussion group for that language. comp.lang.c++ isn't what I'm > looking for. I find it hard to get practical advice on that group > because its focus is so narrow. I frequently see posters there > redirect people to one of the OS-specific C++ groups, but most of my > projects are cross-platform, so hanging out on one of those doesn't if you can't use the standard library or any existing third-party library to solve your problem, that's platform specific. so, find the right group and ask there. > make sense either. As an example, I was recently trying to get > information about writing cross-platform code for dynamic linking, but > I couldn't find anywhere appropriate to ask about it. as to dynamic linking, afaik, i don't think you can deal with it in a consistent way. you'd better find a third-party library or handle all platforms one by one manually. > > For those of you who work in C++, where do you go to discuss it > online? I'm interested in any newsgroups, mailing lists, or web > boards you can recommend. > -- Best Regards, Leo Jay From python at rcn.com Tue Jan 8 17:40:08 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 8 Jan 2008 14:40:08 -0800 (PST) Subject: stupid/style/list question References: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> Message-ID: <69b7aea8-a291-47da-906d-252ae6f33f09@q39g2000hsf.googlegroups.com> On Jan 8, 7:34 am, "Giampaolo Rodola'" wrote: > I was wondering... > To flush a list it is better doing "del mylist[:]" or "mylist = []"? > Is there a preferred way? If yes, why? To empty an existing list without replacing it, the choices are "del mylist[:]" and "mylist[:] = []". Of the two, I prefer the former because it reads more explicity (delete all of the items from the list"). In terms of performance, they are basically the same. To replace a list, "mylist = []" is the way to go. This is an affirmative statement that you are creating a new list. Raymond From python.list at tim.thechases.com Tue Jan 22 15:31:32 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 22 Jan 2008 14:31:32 -0600 Subject: question In-Reply-To: <6760762.631391201031899339.JavaMail.root@hrndva-web18-z01> References: <6760762.631391201031899339.JavaMail.root@hrndva-web18-z01> Message-ID: <479652A4.1090309@tim.thechases.com> > def albumInfo(theBand): > def Rush(): > return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > > def Enchant(): > return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > > The only problem with the code above though is that I > don't know how to call it, especially since if the user is > entering a string, how would I convert that string into a > function name? For example, if the user entered 'Rush', > how would I call the appropriate function --> > albumInfo(Rush()) > It looks like you're reaching for a dictionary idiom: album_info = { 'Rush': [ 'Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres', ], 'Enchant': [ 'A Blueprint of the World', 'Wounded', 'Time Lost', ], } You can then reference the bits: who = "Rush" #get this from the user? print "Albums by %s" % who for album_name in album_info[who]: print ' *', album_name This is much more flexible when it comes to adding groups and albums because you can load the contents of album_info dynamically from your favorite source (a file, DB, or teh intarweb) rather than editing & restarting your app every time. -tkc PS: to answer your original question, you can use the getattr() function, such as results = getattr(albumInfo, who)() but that's an ugly solution for the example you gave. From vedrandekovic at gmail.com Wed Jan 2 06:24:56 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Wed, 2 Jan 2008 03:24:56 -0800 (PST) Subject: wxpython application ( problem ? ) Message-ID: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> Hello, Here is sample of my simple script with wxpython and modules: subprocess,threading, directpython....... Code sample: import wx import wx.aui app=wx.App() frame=wx.Frame(None,title="New project") #There is also part with wx.aui frame.Show() app.MainLoop() After a few minutes wx application does destroy. Any ides why? From steven.bethard at gmail.com Tue Jan 22 13:27:48 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 22 Jan 2008 11:27:48 -0700 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <5vme8iF1mqjl6U1@mid.uni-berlin.de> References: <5vme8iF1mqjl6U1@mid.uni-berlin.de> Message-ID: <479635A4.8@gmail.com> Diez B. Roggisch wrote: > Jean-Paul Calderone wrote: > >> On Tue, 22 Jan 2008 15:15:43 +0100, "Diez B. Roggisch" >> wrote: >>> Jean-Paul Calderone wrote: >>> >>>> On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" >>>> wrote: >>>>> For a simple greenlet/tasklet/microthreading experiment I found myself >>>>> in the need to ask the question >>>>> >>>>> [snip] >>>> Why do you need a special case for generators? If you just pass the >>>> object in question to iter(), instead, then you'll either get back >>>> something that you can iterate over, or you'll get an exception for >>>> things that aren't iterable. >>> Because - as I said - I'm working on a micro-thread thingy, where the >>> scheduler needs to push returned generators to a stack and execute them. >>> Using send(), which rules out iter() anyway. >> Sorry, I still don't understand. Why is a generator different from any >> other iterator? > > Because you can use send(value) on it for example. Which you can't with > every other iterator. And that you can utizilize to create a little > framework of co-routines or however you like to call it that will yield > values when they want, or generators if they have nested co-routines the > scheduler needs to keep track of and invoke after another. So if you need the send() method, why not just check for that:: try: obj.send except AttributeError: # not a generator-like object else: # is a generator-like object Then anyone who wants to make an extended iterator and return it can expect it to work just like a real generator would. STeVe From vinay_sajip at yahoo.co.uk Tue Jan 8 09:23:58 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 8 Jan 2008 06:23:58 -0800 (PST) Subject: Passing contextual information when logging References: Message-ID: <5d681c92-7ac0-4627-baf6-60ee00b359e7@1g2000hsl.googlegroups.com> On 8 Jan, 09:46, Antoine Pitrou wrote: > One question : why does the exception() method call Logger.error() rather than > Logger.exception() ? exception() is a convenience method which adds the keyword argument exc_info=1 to append traceback information to the log. Both exception() and error() log at the ERROR level. > One suggestion : pass in a Logger object rather than a logger name to the > LoggerAdapter constructor. (this also means that users could stack LoggerAdapter > objects if they wanted to) Done, see http://dpaste.com/30253/ Regards, Vinay From george.sakkis at gmail.com Mon Jan 21 17:34:09 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 21 Jan 2008 14:34:09 -0800 (PST) Subject: Transforming ascii file (pseduo database) into proper database References: <9b6a9a56-2ea6-4dd6-9420-afe9a2fdc8d8@e32g2000prn.googlegroups.com> <7x8x2iyhrc.fsf@ruckus.brouhaha.com> Message-ID: On Jan 21, 4:45 pm, Paul Rubin wrote: > "p." writes: > > 1. Has anyone done anything like this before, and if so, do you have > > any advice? > > Sort all the files with an external sort utility (e.g. unix sort), so > that records with the same key are all brought together. Then you can > process the files sequentially. Seconded. Unix sort can do external sorting [1] so your program will work even if the files don't fit in memory. Once they are sorted, itertools (especially groupby) is your friend. George [1] http://en.wikipedia.org/wiki/External_sort From basilisk96 at gmail.com Mon Jan 14 21:01:38 2008 From: basilisk96 at gmail.com (Basilisk96) Date: Mon, 14 Jan 2008 18:01:38 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> <39e38974-9501-4342-bbc1-8c0e2e460790@v46g2000hsv.googlegroups.com> <57259893-67ce-4450-9984-7f499dde5182@v67g2000hse.googlegroups.com> Message-ID: On Jan 14, 7:53 am, Michele Simionato wrote: > I really need to publish this one day or another, since these > questions > about super keeps coming out: > > http://www.phyast.pitt.edu/~micheles/python/super.html Please do. It is a very enlightening discussion, and I'm sure a bunch of folks will benefit from it. And please update it (if necessary) to the current Python version. At the time of that writing, 2.3 must have been King, but oh my, how time flies :-) Cheers, -Basilisk96 From henry.baxter at gmail.com Fri Jan 25 16:37:38 2008 From: henry.baxter at gmail.com (Henry Baxter) Date: Fri, 25 Jan 2008 13:37:38 -0800 Subject: Index of maximum element in list Message-ID: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> I apologize if this has already been discussed - funnily enough my googling did bring up a previous thread about it on this mailing list, but despite the promising subject line, seemed to mainly be concerned with whether python-list should its own FAQ...so I assume this has been asked many times before, but my apologies I cannot find the answer. Here is what I have: def maxi(l): it -- Henry -------------- next part -------------- An HTML attachment was scrubbed... URL: From dongie.agnir at gmail.com Wed Jan 9 18:45:41 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Wed, 9 Jan 2008 15:45:41 -0800 (PST) Subject: Python too slow? References: 76bc64cc-541c-434f-aac5-96d1a2d231ee@c23g2000hsa.googlegroups.com <7115e305-429c-47d3-a942-8a0e2a0e846f@m34g2000hsf.googlegroups.com> Message-ID: Okay I profiled the code and here is the output: http://heightened.files.wordpress.com/2008/01/output.txt It seems that the function it spends the longest on is the red_points function that he uses to find the points. From steve at REMOVE-THIS-cybersource.com.au Fri Jan 25 22:09:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 26 Jan 2008 03:09:05 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: <13pl92h3um45rc1@corp.supernews.com> On Wed, 23 Jan 2008 08:49:20 +0100, Christian Heimes wrote: > It's even > possible to write code with Python assembly and compile the Python > assembly into byte code. Really? How do you do that? I thought it might be compile(), but apparently not. -- Steven From jatinpatni at gmail.com Wed Jan 9 07:44:37 2008 From: jatinpatni at gmail.com (jatin patni) Date: Wed, 9 Jan 2008 12:44:37 +0000 Subject: Problem in the program flow...please help? Message-ID: I am making a python application with a GUI using WXGlade which connects to a website and extracts some information, this takes around 5-20 seconds of time per website. I have a button(GUI) which when clicked, calls a function connect( ) which takes around 5-20 seconds to complete(As I mentioned Earlier) The problem is, during this time the other part of the code is rendered useless, I cannot access other parts of the code, for example a cancel( ) function to be called when cancel button is pressed, cannot be pressed until the previous function is completed and moreover the GUI hangs(stops responding). I am planning to explore Threading and Asynchronous data transfer, next. Please help me out if anyone has had a similar experience in the past. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sat Jan 26 05:25:22 2008 From: http (Paul Rubin) Date: 26 Jan 2008 02:25:22 -0800 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> <89fb4211-2b83-4479-935c-1b948672224a@v29g2000hsf.googlegroups.com> Message-ID: <7xy7acsx2l.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > def posmax(seq, key=None): > """Return the position of the first maximum item of a sequence. > It accepts the usual key parameter too.""" > if key: > return max(enumerate(seq), key=lambda k: key(k[1]))[0] > else: > return max(enumerate(seq), key=itemgetter(1))[0] def posmax(seq, key=lambda x:x): return max(enumerate(seq), key=lambda k: key(k[1]))[0] From bigblueswope at gmail.com Mon Jan 7 21:04:27 2008 From: bigblueswope at gmail.com (BJ Swope) Date: Mon, 7 Jan 2008 21:04:27 -0500 Subject: Open a List of Files Message-ID: given a list such as ['messages', 'recipients', 'viruses'] how would I iterate over the list and use the values as variables and open the variable names a files? I tried for outfile in ['messages', 'recipients', 'viruses']: filename = os.path.join(Host_Path, outfile) outfile = open(filename, 'w') But it's not working. -- We are all slave to our own paradigm. -- Joshua Williams If the letters PhD appear after a person's name, that person will remain outdoors even after it's started raining. -- Jeff Kay -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sat Jan 12 10:38:11 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 12 Jan 2008 07:38:11 -0800 (PST) Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> Message-ID: <05133da5-a1fb-4c24-acd0-23dbccea5813@j78g2000hsd.googlegroups.com> On Jan 12, 8:04 am, castiro... at gmail.com wrote: > On Jan 11, 5:26 pm, Paul Rubin wrote: > > > castiro... at gmail.com writes: > > > 1. Put a single thread in charge of the list, and communicate with it > > by message passing through Queues. To get X out of the list, you'd > > send the mutator thread a message asking for removal. The mutator > > thread would loop reading and processing messages from the queue, > > blocking when no requests are pending. This is sort of the preferred > > Python style and is pretty simple to get correct, but if there are > > many such objects you can end up with more threads than you really > > want. > > I've heard this called 'fire and forget'. You can insure that > mutations are honored one-at-a-time and in the order received. How > do you make a -read- operation; wait for queued mutations, that is > lock for a turn on the queue? Can you optionally read whatever the > state is, regardless of what's happened in the meantime? Thing is, > one thread needs its -own- preceding operations completed before a > reading operation. Brainstorm. First, isolation of problem: Terminates at 2000 or so, on my computer. import thread import time import random counter= 0 def simplecounter(): global counter ret= counter counter+= 1 time.sleep( random.uniform( 0, .001 ) ) return counter glist= [] def th3(): while 1: ret= simplecounter() glist.append( ret ) print ret, assert glist== range( 1, len( glist )+1 ) thread.start_new_thread( th3, () ) time.sleep(1) thread.start_new_thread( th3, () ) time.sleep( 1000 ) Second, the thoughts: 'with a.callbacklock():' looks best currently. '''multithreading ideas: 1. Put a single thread in charge a.k.a. fire and forget. - Lots of extra threads + But most are blocking most of the time + honored one-at-a-time, and in order received + ...optionally including read-access, blocking on to get return values a. synchronous callbacks, for read-access + multi-step, user-definitionized operations - one consumer can hang an entire object i. with a.callbacklock():? + only call acquire() from curr. thread, enqueue lock obj., released from producer thread "soon" using message-queue semantics b. mini-transaction, guarantees all and only consumer's ops occur in succession - can't do anything amidst an indivdual locking - no multi-step ops 2. Lock mutation and/or all operations a. Locker.op b. with Locker.withop - In Python, other programmers always have access to your data; nothing guarantees they'll use "with locker" + User-definitioning quite easy 3. @mutation decorator def mutation( func ): def newfunc( self, *a, **k ): self.lock.acquire() func( *a, **k ) self.lock.release() 4. List-only solution: Use a dictionary, map item to its index. To retrieve, sort on value, not key ''' From grflanagan at yahoo.co.uk Wed Jan 16 05:21:28 2008 From: grflanagan at yahoo.co.uk (grflanagan) Date: Wed, 16 Jan 2008 02:21:28 -0800 (PST) Subject: searching an XML doc References: <327368a7-694f-4f30-8f76-db0569ed4a5c@k2g2000hse.googlegroups.com> Message-ID: <2d290754-4a44-427f-9287-134210b217d5@q77g2000hsh.googlegroups.com> On Jan 15, 9:33 pm, Gowri wrote: > Hello, > > I've been reading about ElementTreee and ElementPath so I could use > them to find the right elements in the DOM. Unfortunately neither of > these seem to offer XPath like capabilities where I can find elements > based on tag, attribute values etc. Are there any libraries which can > give me XPath like functionality? > > Thanks in advance Create your query like: ns0 = '{http://a.b.com/phedex}' query = '%srequest/%sstatus' % (ns0, ns0) Also, although imperfect, some people have found this useful: http://gflanagan.net/site/python/utils/elementfilter/elementfilter.py.txt [CODE] test = ''' T1_RAL_MSS T2_London_ICHEP T2_Southgrid_Bristol /PrimaryDS1/ProcessedDS1/ Tier /PrimaryDS2/ ProcessedDS2/Tier/block ''' from xml.etree import ElementTree as ET root = ET.fromstring(test) ns0 = '{http://a.b.com/phedex}' from rattlebag.elementfilter import findall, data #http://gflanagan.net/site/python/utils/elementfilter/ elementfilter.py.txt query0 = '%(ns)srequest/%(ns)sstatus' % {'ns': ns0} query1 = '%(ns)srequest/%(ns)ssubscription[@type=="replicate"]/% (ns)sitems' % {'ns': ns0} query2 = '%(ns)srequest[@id==1234]/%(ns)sstatus/%(ns)sapproved' % {'ns': ns0} print 'With ElementPath: ' print root.findall(query0) print print 'With ElementFilter:' for query in [query0, query1, query2]: print print '+'*50 print 'query: ', query print for item in findall(root, query): print 'item: ', item print 'xml:' ET.dump(item) print '-'*50 print print 'approved: ', data(root, query2) [/CODE] [OUTPUT] With ElementPath: [] With ElementFilter: ++++++++++++++++++++++++++++++++++++++++++++++++++ query: {http://a.b.com/phedex}request/{http://a.b.com/phedex}status item: xml: T1_RAL_MSS T2_London_ICHEP T2_Southgrid_Bristol ++++++++++++++++++++++++++++++++++++++++++++++++++ query: {http://a.b.com/phedex}request/{http://a.b.com/ phedex}subscription[@type =="replicate"]/{http://a.b.com/phedex}items item: xml: /PrimaryDS1/ProcessedDS1/ Tier /PrimaryDS2/ ProcessedDS2/Tier /block ++++++++++++++++++++++++++++++++++++++++++++++++++ query: {http://a.b.com/phedex}request[@id==1234]/{http://a.b.com/ phedex}status/ {http://a.b.com/phedex}approved item: xml: T1_RAL_MSS item: xml: T2_London_ICHEP -------------------------------------------------- approved: ['T1_RAL_MSS', 'T2_London_ICHEP'] INFO End logging. [/OUTPUT] From jimis at gmx.net Thu Jan 3 12:23:21 2008 From: jimis at gmx.net (Dimitrios Apostolou) Date: Thu, 3 Jan 2008 19:23:21 +0200 (EET) Subject: urllib2 disable proxy In-Reply-To: <878x373o6c.fsf@merkury.smsnet.pl> References: <878x373o6c.fsf@merkury.smsnet.pl> Message-ID: On Wed, 2 Jan 2008, Rob Wolfe wrote: > Dimitrios Apostolou writes: > >> Hello list, >> >> I've been looking for a way to explicitly disable the use of proxies with >> urllib2, no matter what the environment dictates. Unfortunately I can't find >> a way in the documentation, and reading the source leads me to believe that >> something like the following does the job: >> >> req.set_proxy(None,None) >> >> Where req is a urllib2.Request instance. So is there an official way of doing >> this? Perhaps it should be added in the documentation? > > I believe that the recommended way is to use `urllib2.ProxyHandler`. > Take a look at: > http://www.voidspace.org.uk/python/articles/urllib2.shtml Thanks for the pointer, I will use that way. However it seems rather non-elegant way to do something so simple and I was hoping not to mess with ProxyHandler, especially since I want *no* proxy... IMHO something like the following would be more elegant: req.set_proxy('','http') or req.set_proxy(None,'http') However these ways *don't* work. You think I should file a feature request somewhere or send this to the python-dev list? Thank you for the help, Dimitris > > HTH, > Rob > -- > http://mail.python.org/mailman/listinfo/python-list > From mwilson at the-wire.com Mon Jan 21 08:44:54 2008 From: mwilson at the-wire.com (Mel) Date: Mon, 21 Jan 2008 08:44:54 -0500 Subject: problem with 'global' References: Message-ID: Duncan Booth wrote: > Mel wrote: > >> oyster wrote: >>> why the following 2 prg give different results? a.py is ok, but b.py >>> is 'undefiend a' >>> I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC >>> v.1310 32 bit (Intel)] on win32 >>> #a.py >>> def run(): >>> if 1==2: # note, it always False >>> global a >>> a=1 >>> >>> run() >>> a >>> >>> #b.py >>> def run(): >>> a=1 >>> >>> run() >>> a >> The docs seem to be in >> but don't look all that helpful. > > Why are you reading Python 2.4 docs? Try > http://docs.python.org/ref/global.html > > The first sentence (which hasn't changed since 2.4) describing the global > statement seems clear enough to me: "The global statement is a declaration > which holds for the entire current code block." I don't think that would stop the OP from thinking the global statement had to be executed. In the code example, it seems to have been stuck in a if 1==2: global a and it still worked. Mel. From harald.karner at a1.net Fri Jan 25 05:58:06 2008 From: harald.karner at a1.net (Harald Karner) Date: Fri, 25 Jan 2008 11:58:06 +0100 Subject: time.gmtime In-Reply-To: <293bb767-603b-4aef-b9c8-23af565b090f@s8g2000prg.googlegroups.com> References: <293bb767-603b-4aef-b9c8-23af565b090f@s8g2000prg.googlegroups.com> Message-ID: <1201258685.993333@nntpcache01.si.eunet.at> asit wrote: > we know that time.gmtime(secs) takes a parameter secs. what does this > secs suggest ??What is it's significance ?? >>> import time >>> help (time.gmtime) Help on built-in function gmtime in module time: gmtime(...) gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst) Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a. GMT). When 'seconds' is not passed in, convert the current time instead. >>> time.gmtime (0) (1970, 1, 1, 0, 0, 0, 3, 1, 0) >>> From aspineux at gmail.com Mon Jan 14 14:07:22 2008 From: aspineux at gmail.com (aspineux) Date: Mon, 14 Jan 2008 11:07:22 -0800 (PST) Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> Message-ID: <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> On Jan 14, 7:49 pm, "Chris Mellon" wrote: > On Jan 14, 2008 12:39 PM, aspineux wrote: > > > > > This append in both case > > > dict(a=1).get('a', f()) > > dict(a=1).setdefault('a', f()) > > > This should be nice if f() was called only if required. > > Think about the change to Python semantics that would be required for > this to be true, and then use collections.defaultdict instead. Yes, I missed 'get' and 'setdefault' are functions :-) Then why not some new semantic d.get('a', f()) --> d['a', f()] d.setdefault('a', f()) --> d['a'=f()] Is is a good idea enough to change the python semantic ? Or simply is it a good idea ? From mail at microcorp.co.za Fri Jan 18 02:23:55 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 18 Jan 2008 09:23:55 +0200 Subject: Interesting Thread Gotcha References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> Message-ID: <000001c859f0$05b796c0$03000080@hendrik> "Dan" wrote: > Would it be possible to have pychecker (or some such) warn that there > is an insufficient parameter count to start_new_thread? I guess that > would require knowing the type of thread. . . I think this is the hub of the thing - its not only start_new_thread, but the way that parameters are evaluated before being counted, generally. See my reply to Diez's post - Hendrik From benedict.verheyen at gmail.com Mon Jan 28 04:32:06 2008 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Mon, 28 Jan 2008 10:32:06 +0100 Subject: starting programs from python script on windows Message-ID: Hi, i want to automate starting programs on my windows machine and i want to do it with windows. This is a sample script: from subprocess import Popen, PIPE import time print " Starting app 1" time.sleep(1) try: p1 = Popen(["C:\Program Files\Microsoft Office\OFFICE11\OUTLOOK.EXE"], stdout=PIPE) except Exception, e: print "Error on startup app 1 %s " % str(e) print " Starting app 2" time.sleep(1) try: p2 = Popen(["C:\Windows\system32\cmd.exe"], stdout=PIPE) except Exception, e: print "Error on startup app 2 %s " % str(e) It start it from a batch file: SET PYTHONPATH=C:\Python25 rem - path to script to execute %PYTHONPATH%\python.exe C:\login.py This is the result: C:\>C:\Python25\python.exe C:\login.py Starting app 1 Starting app 2 Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. 1. I get an error message saying the process has tried to write to a non existing pipe. 2. Order of execution isn't respected: it prints the 2 messages and then it tries to start the programs. Outlook is started but the command prompt not. Anyway, if it works, i would like to start using python to drive the startup scripts of the users on the system. How can i use python to start several programs as i would otherwise do manually and keep the order i want? Thanks, Benedict From hniksic at xemacs.org Sun Jan 13 07:32:48 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 13 Jan 2008 13:32:48 +0100 Subject: about sort a list with integer key References: <986e05f3-2fe9-4fe8-94e2-fef26713a78c@i72g2000hsd.googlegroups.com> Message-ID: <87fxx1nbwv.fsf@mulj.homelinux.net> lotrpy writes: > if i want sort each line by the first part,(it's a integer, in fact). > don't know how to do it with itemgetter. > key = int(itemgetter(0)) is wrong, key = lambda x:int(x[0]) works. > but s.b. told me itemgetter execute more quickly . Use lambda when it works better for you, the speed difference is marginal in practice anyway. itemgetter is not (and was never intended to be) a general substitute for functions, as you've discovered. The marginal speed difference between itemgetter and an explicit lambda that does the subscripts is a consequence of itemgetter being written in C, meaning it avoids the creation of a Python stack frame, etc. Combining int(...) with this operation requires coding the key function in Python, which removes itemgetter's advantage. In other words, you cannot retain itemgetter's speed advantage with more complex keys. If the sorting performance is a problem for you, please give more details about what you're doing -- there might be better ways to speed up the code. From antroy at gmail.com Wed Jan 9 06:40:05 2008 From: antroy at gmail.com (Ant) Date: Wed, 9 Jan 2008 03:40:05 -0800 (PST) Subject: Learning Python via a little word frequency program References: Message-ID: <43a9a28c-0713-4789-b4f0-4e6ba0e8bbfd@u10g2000prn.googlegroups.com> > I'm interested to learn how more experienced Python folks would solve > this little problem. I think I'd do the following: from collections import defaultdict names = "freddy fred bill jock kevin andrew kevin kevin jock" freq = defaultdict(lambda: 0) for name in names.split(): freq[name] += 1 pairs = [(v, k) for k, v in freq.iteritems()] for v, k in reversed(sorted(pairs)): print "%-10s: %d" % (k, v) defaultdict makes the frequency accumulation neater. reversed(sorted(pairs)) avoids the little -v hack and makes it more obvious what you are doing. Of course this could also be achieved by doing pairs.sort() and pairs.reverse() before iterating over the pairs list. Cheers, -- Ant. From alitosis at gmail.com Wed Jan 30 22:28:37 2008 From: alitosis at gmail.com (alitosis at gmail.com) Date: Wed, 30 Jan 2008 19:28:37 -0800 (PST) Subject: writing Python in Emacs References: <160ed936-c8c0-432e-81c8-c62b8f164136@s13g2000prd.googlegroups.com> <87r6gc5wr5.fsf@merkury.smsnet.pl> Message-ID: <48499955-2c23-4acc-9252-ee2963bc233c@i12g2000prf.googlegroups.com> Rob Wolfe wrote: > The good news is that I managed to configure completion for Python > in Emacs using pymacs, python-mode.el, pycomplete.el and pycomplete.py. > For contents of my pycomplete.el, pycomplete.py and necessary > settings in .emacs see below. Thanks for that! I've been hoping something like this landed on my lap for years. From python at rolfvandekrol.nl Sat Jan 19 10:33:59 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Sat, 19 Jan 2008 16:33:59 +0100 Subject: python scripts with IIS In-Reply-To: <120794.61529.qm@web38414.mail.mud.yahoo.com> References: <120794.61529.qm@web38414.mail.mud.yahoo.com> Message-ID: <47921867.5040309@rolfvandekrol.nl> Adding the following lines before your print statement should do the trick. IIS complains about the headers, so adding headers should help. print "Content-Type: text/html" # HTML is following print # blank line, end of headers william paul wrote: > > Hello: > > I am trying to configure IIS to work with Python scripts: > > I've added in the Home Directory/Configuration the .py extention and > the path to the python.exe as: c:\Python24\python.exe %S %S > The python script has 1 line: > print "This is a test for python scripts with IIS" > > When I launch the file using IE I get the message: > > *CGI Error* > The specified CGI application misbehaved by not returning a complete > set of HTTP headers. The headers it did return are: > > This is a test for python scripts with IIS > > How can I remove the CGI error? > > Thank you > > William > > ------------------------------------------------------------------------ > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try > it now. > From lists at cheimes.de Sat Jan 19 16:31:38 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 19 Jan 2008 22:31:38 +0100 Subject: finding memory leak in edgewall trac 0.11 In-Reply-To: <20080119202909.GY61556@nexus.in-nomine.org> References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> Message-ID: <47926C3A.5060000@cheimes.de> Jeroen Ruigrok van der Werven wrote: > Hi Christian, > > -On [20080119 16:16], Christian Heimes (lists at cheimes.de) wrote: >> I forgot one important point in my reply. The GC module contains some >> useful methods for debugging. Check gc.garbage. It should be empty. > > Yeah, we're messing around with that stuff as well as many other ways of > trying to track issues, but it can really be looking for a needle in a > haystack to be honest. > There's so much output that, I guess, make sense only when you're semi-deep > into the Python internals to even make heads or tails out of it. =\ > And even third-party code is not helping much to reduce the clutter and > provide insight. Under normal circumstances gc.garbage should be an empty list. In general it's a bad sign if gc.garbage contains lots of objects. I found several potential leaks in trac: $ find -name \*.py | xargs grep __del__ ./trac/versioncontrol/svn_fs.py: def __del__(self): ./trac/versioncontrol/svn_fs.py: def __del__(self): ./trac/db/pool.py: def __del__(self): $ find -name \*.py | xargs grep frame ./trac/web/main.py: [...] ./trac/core.py: frame = sys._getframe(1) ./trac/core.py: locals_ = frame.f_locals I recommend that you either replace __del__ with a weak reference callback or to remove it. Referencing a frame, traceback or f_locals is going to leak, too. You *must* explicitly del every frame and locals variable. Christian From jitrowia at yahoo.com Fri Jan 25 22:48:44 2008 From: jitrowia at yahoo.com (jitrowia) Date: Sat, 26 Jan 2008 03:48:44 -0000 Subject: How can I use the up and down, left and right arrow keys to control a Python Pgm Message-ID: I was wondering what kind of python code I would need to enable me to use the up and down, left and right arrow keys to control software programming decisions within a Python Program. Any direction and advice would be greatly appreciated, Thank You, Rodney From john.rominsky at gmail.com Fri Jan 4 12:30:12 2008 From: john.rominsky at gmail.com (Rominsky) Date: Fri, 4 Jan 2008 09:30:12 -0800 (PST) Subject: matplotlib fill command on axes plot problem Message-ID: I am trying to use the fill command to draw a box around an object in an image. I can get the box drawn, but there seems to be a side effect. The fill command is adding white lines to the top and sometimes right side of my axes plots. I am using small images, 124x200, and after the fill command the axes plot is changed to 140x200, with the top 16 lines being all white. I am running it in interactive mode from the python command line. Here is code that reproduces the problem. from pylab import * im_array = zeros((124,200)) ion() figure() imshow(im_array) hold(True) x=40 y=40 fill([x-5,x+5,x+5,x-5],[y+5,y+5,y-5,y-5],ec='r', fill = False) hold(False) Any thoughts on what I might be doing wrong? From bignose+hates-spam at benfinney.id.au Thu Jan 17 23:05:23 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 18 Jan 2008 15:05:23 +1100 Subject: array and list References: Message-ID: <87bq7jbwxo.fsf@benfinney.id.au> "J. Peng" writes: > what's the difference between an array and a list in python? In Python, 'list' is a basic built-in type. Python has no 'array' type, though that term is often used to refer to the 'array' type defined in Numeric Python (which is not part of the standard library, so not really part of Python). > I see list has all features of array in C or perl. You may also want to compare and constrast Python 'list' and 'dict'. -- \ "When cryptography is outlawed, bayl bhgynjf jvyy unir | `\ cevinpl." -- Anonymous | _o__) | Ben Finney From Brett.Friermood at gmail.com Mon Jan 21 20:06:10 2008 From: Brett.Friermood at gmail.com (Brett.Friermood at gmail.com) Date: Mon, 21 Jan 2008 17:06:10 -0800 (PST) Subject: Curses and Threading Message-ID: <3924ad84-a513-4b25-b9af-cbd358f5d40a@i3g2000hsf.googlegroups.com> I am writing a program that uses curses and threading. I am working on displaying a clock in the upper right hand corner of the screen. I have only one thread at the moment, that gets the time and displays it in curses. To make it easier to debug right now, the program starts curses in a try: clause then starts the thread which runs for 10 iterations displaying the time every second. Then the thread exits, and the program is supposed to run the finally: clause to clean up the terminal. I also have set curs_set(0) so the cursor is invisible. What happens is that everything starts fine but the cursor is visible. It runs for the 10 seconds then quits without restoring the terminal to working order. I am trying this on a Fedora 4 computer have also tried it on a Fedora 8 one with same results. I have tried searching but Google doesn't find anything using both curses and threading. The only thing I can find regarding both is that curses seems to block when waiting for input, but I do not have any input yet. Below is what I have right now: #! /usr/bin/env python import curses import threading import time class cadtime(threading.Thread): def run(self): x=0 while x<10: cadtimevl=time.strftime("%d %b %H:%M: %S",time.localtime()) leng=len(cadtimevl) stdscr.addstr(0,width-leng-1,cadtimevl) stdscr.refresh() x=x+1 time.sleep(1) return try: stdscr=curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) curses.start_color() curses.curs_set(0) width=curses.COLS-1 cadtime().start() finally: curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin() I can't figure out why the cursor still shows and why they terminal is screwed up afterward because the finally: should catch any failures and reset the terminal. -Brett From mal at egenix.com Mon Jan 7 07:55:05 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 07 Jan 2008 13:55:05 +0100 Subject: Memory Leaks and Heapy In-Reply-To: <7f692fec0801041819r675e2137i293084baeae4954f@mail.gmail.com> References: <7f692fec0801040707r110fd9cayfd9dabf75322bbed@mail.gmail.com> <477E5A73.9070400@egenix.com> <7f692fec0801040823q14d16429y370ffceaf046a6f3@mail.gmail.com> <477E6525.3010805@egenix.com> <7f692fec0801041819r675e2137i293084baeae4954f@mail.gmail.com> Message-ID: <47822129.4050500@egenix.com> On 2008-01-05 03:19, Yaakov Nemoy wrote: > On Jan 4, 2008 11:56 AM, M.-A. Lemburg wrote: >>> The most common answer I heard was possible fragmentation, meaning >>> there are no or few completely empty blocks to be found. If there are >>> no 'leaks' in the VM, then it's probably related to how memory is >>> freed. >> You can check for this by using a special build of Python >> with disabled PyMalloc - Python will then use the standard >> OS malloc for all object allocations. It still uses free lists >> for a couple of object types, but those won't cause major >> leak problems. > > How do I go about setting this up? There's a configure option for this: --with(out)-pymalloc disable/enable specialized mallocs >> Alternatively, try to tune the PyMalloc implementation (see >> objmalloc.c), e.g. enable WITH_MEMORY_LIMITS. >> >>>> This could be caused by interned strings which are kept in a special >>>> pool dictionary to speed up string comparisons. >>> That's quite possible, a majority of the code is a huge number of SQL >>> connections and code. All string based. >> Note that strings are normally *not* interned. However, you can >> write code in a way that causes Python to intern more strings >> than needed, e.g. if you dynamically compile code in your app, >> which then causes all identifiers in the compiled code to be >> interned. >> >> The interned dictionary is not exposed in Python, but you can >> access it using a debugger via Objects/stringobject.c:interned. > > That's going a bit more low level detail than I think I can handle. > I'm not much for C programming, and i'll have a hard time sifting > through the noise to find the signal. Fair enough. Just wanted to give some more details as to where to look for things that look like leaks, but are in fact just results of internal feature of the Python interpreter. >>>> However, the first thing to check is whether any of the C extension >>>> modules you are using is leaking memory. Python itself is usually >>>> well tested for memory leaks, but this is less so for C extension >>>> modules and it's easy to mis a few Py_DECREFs (decrementing a >>>> Python object's reference count), causing objects to live forever. >>> I'll try to track it down, but AFAIK, most of the code is python, and >>> the only C code there would be is the MySQL container. How can I >>> debug the VM though, to determine where the leak lies? Heapy wasn't >>> able to tell me this, and this is the important aspect. I'm wondering >>> how most people go about determining the causes of leaks like these, >>> so I can provide some accurate bug information. >> Building Python in debug mode provides some help with this. >> You can then detect whether objects get properly freed. > > Again, what's the best way to go about doing this? Again, configure with: --with-pydebug build with Py_DEBUG defined >> Doing explicit garbage collection via the gc module also >> helps in narrowing down the leak. > > Adding an explicit gc.collect() statement at the end of the offending > function didn't do much to solve matters much. It slowed the rate > that garbage piled up, but it's not a solution. > > Thanks for all the help. You're welcome. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jan 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 t_spens at yahoo.com Wed Jan 23 18:46:40 2008 From: t_spens at yahoo.com (Tim Spens) Date: Wed, 23 Jan 2008 15:46:40 -0800 (PST) Subject: handling asynchronous callbacks from c++ in a python script Message-ID: <155356.55301.qm@web45109.mail.sp1.yahoo.com> I have a c++ program running that has boost python hooks for the c++ api. I'm running a python client that makes calls into the c++ api. The problem is there are c++ asynchronous callbacks that need to pass information to the python client. What I was hoping to do is call a python function from c++ that resides in the running "main()" python client while in the c++ callback handlers. Is this possible and if you can point me to an example or documentation on how to do this it would be much appreciated? NOTE: I've been asking on the c++-sig mailing list about this and David Abrahams (very well versed in boost python) said: "I'm not an expert on asynchronous python and this is really not a Boost.Python question. I suggest you ask on the regular Python mailing list. Sorry." ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From sergio.correia at gmail.com Tue Jan 15 11:15:33 2008 From: sergio.correia at gmail.com (Sergio Correia) Date: Tue, 15 Jan 2008 11:15:33 -0500 Subject: Why this apparent assymetry in set operations? In-Reply-To: References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: Both of you are correct. >>> x = set([1,2,3]) >>> y = set([4,5]) >>> x |= y >>> x set([1, 2, 3, 4, 5]) On Jan 15, 2008 11:07 AM, Skip Montanaro wrote: > > > Why is that? Doesn't the |= operator essentially map to an update() call? > > > > No, according to 3.7 Set Types, s | t maps to s.union(t). > > I was asking about the |= assignment operator which according to the > docs *does* map to the update method. > > Skip > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From musiccomposition at gmail.com Thu Jan 17 22:53:38 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 17 Jan 2008 19:53:38 -0800 (PST) Subject: How to create graphs an embed them in GUI? References: Message-ID: On Jan 17, 10:07 am, "A.T.Hofkamp" wrote: > On 2008-01-17, Heiko Niedermeyer wrote: > > > As I'm learning Python from scratch, I don't care wether to use (=learn) > > TKinter or PyQt or whatever, I just need some advice, which suits my > > needs best. > > It would be nice to have the programm working under win and linux > > (shouldn't be a big Problem) and my requirements concerning the standard > > PyGTK is a 3rd option, and wxWindows + Python is a 4th option. > > TKinter is supplied with Python, which means everybody with Python also has > TKinter. Main draw-backs are that it is quite old. Also, it has a peculiar way > of getting stuff drawn at a canvas. > > PyQt is available free with some additional restriction (plz read the > license) for the Linux system, I don't know whether you can also get a Win > version under the same conditions (you couldn't when I looked the last time). > PyGTK is said to be usable for both platforms. I know it works with Linux, and > there exists a PyGTK installer for Win, but I hacve never used it. PyQt 4+ is now available for MacOS, Windows, and X under GPL. I tried Tkinter and wxPython before settling on PyQt. It's more powerful than Tkinter and has a cleaner API than wxPython. > > No recent experience with wxWindows. > > > My problem is, that I want to add graph (simple, line connected X,Y- > > scatter plots) and if possible the 3D representation of atoms in a > > molecule (-> coloured spheres in space). Qwt (Q Widgets for Technical Applications) provides graphs widgets that plug into Qt. There are, of course, Python bindings (pyqwt). > > You should probably seperate both problems, in particular if you want to have > the program do the layout for you. For 2D layout, Graphviz is one of the better > known packages, run it as a child process. There are several graphviv/dot > Python libraries available, search PyPI for them. > > For 3D, I don't know any programs. > > > I think it would take me years to program those by myself, so I would ne > > ready to use packages, if available. > > Long story short: Are there packages that could do this, and does it > > matter which GUI I want to embed them in? > > If you want a GUI that understands how to layout chemical structures, you won't > have many options (on the other hand, you never know, have you tried searching > PyPI already?). > > On the other hand, once you have the coordinates, drawing them is kind of > trivial in just about any GUI toolkit. > > (An alternative may be to have the user lay them out by dragging them with the > mouse. Programming that is however probably a lot more work.) > > Sincerely, > Albert From fredrik at pythonware.com Wed Jan 9 11:21:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 17:21:07 +0100 Subject: sqlite fetchall breacking because decoding. In-Reply-To: <514759dc-faf7-4e34-bf6d-624a0cc540ae@e4g2000hsg.googlegroups.com> References: <514759dc-faf7-4e34-bf6d-624a0cc540ae@e4g2000hsg.googlegroups.com> Message-ID: tyoc wrote: > The database is not corrupt, I mean Im sure if I do a C program for > read and print the row, it will get it and just printit and not fail > like this well, the database *is* corrupt, since sqlite3 (both the engine and the Python binding) expects you to use a supported encoding for the data stored in the database: http://www.sqlite.org/datatype3.html http://docs.python.org/lib/node346.html the fact that you're able to use an API that doesn't care about encodings at all to violate the database requirements doesn't necessarily mean that an API that does the right thing is broken... if you're not able to fix your database, you have to plug in a custom text_factory handler. this should work: conn = sqlite3.Connect(...) conn.text_factory = str also see: http://docs.python.org/lib/sqlite3-Connection-Objects.html From george.sakkis at gmail.com Wed Jan 23 02:33:00 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 22 Jan 2008 23:33:00 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> On Jan 23, 1:39 am, Steven D'Aprano wrote: > Given the human psychology displayed involved, in the absence of > definitive evidence one way or another it is a far safer bet to assume > that people are unnecessarily asking for "the fastest" out of a misguided > and often ignorant belief that they need it, rather than the opposite. > People who actually need a faster solution usually know enough to preface > their comments with an explanation of why their existing solution is too > slow rather than just a context-free demand for "the fastest" solution. As I mentioned already, I consider the seeking of the most efficient solution a legitimate question, regardless of whether a "dumb" solution is fast enough for an application. Call it a "don't be sloppy" principle if you wish. It's the same reason I always use xrange() instead of range() for a loop, although in practice the difference is rarely measurable. > Fast code is like fast cars. There *are* people who really genuinely need > to have the fastest car available, but that number is dwarfed by the vast > legions of tossers trying to make up for their lack of self-esteem by > buying a car with a spoiler. Yeah, you're going to be traveling SO FAST > on the way to the mall that the car is at risk of getting airborne, sure, > we believe you. > > (The above sarcasm naturally doesn't apply to those who actually do need > to travel at 200mph in a school zone, like police, taxi drivers and stock > brokers.) Good example; it shows that there's more than the utilitarian point of view. People don't buy these cars because of an actual need but rather because of the brand, the (perceived) social value and other reasons. And since you like metaphors, here's another one: caring about efficient code only when you need it is like keeping notes for a course only for the material to be included in the final exams, skipping the more encyclopedic, general knowledge lectures. Sure, you may pass the class, even with a good grade, but for some people a class is more than a final grade. George From thynnus at gNOTmail.com Tue Jan 22 11:45:40 2008 From: thynnus at gNOTmail.com (Thynnus) Date: Tue, 22 Jan 2008 16:45:40 GMT Subject: stdin, stdout, redmon In-Reply-To: <4794a5e3$0$9014$426a74cc@news.free.fr> References: <4794a5e3$0$9014$426a74cc@news.free.fr> Message-ID: On 1/21/2008 9:02 AM, Bernard Desnoues wrote: > Hi, > > I've got a problem with the use of Redmon (redirection port monitor). I > intend to develop a virtual printer so that I can modify data sent to > the printer. FWIW: there is a nice update the RedMon (v1.7) called RedMon EE (v1.81) available at http://www.is-foehr.com/ that I have used and like a lot. From the developers website: Fixed issues and features [with respect to the orininal RedMon] * On Windows Terminal Server or Windows XP with fast user switching, the "Prompt for filename" dialog will appear on the current session. * "SaveAs" now shows XP style dialogs if running under XP * Support for PDF Security added - experimental -. * Support for setting the task priority - experimental - * Use of file-shares as output * Environment variables are passed to the AfterWorks Process now. * Environment variables are replaced in the program arguments. No workaround is needed. * RedMon EE comes with an RPC communication feature which could transfer output-files back to the client starting the print job on a print server. Error messages will be send to the client. * Redmon EE may start a process after the print job has finished (After works process). e.g. starting a presentation program to show the pdf generated by GhostScript. * additional debug messages may be written for error analysis. No special debug version is needed. * user interface has been rewritten. May be it's more friendly. Added some basic system information which may help if running in failures. * new feature: running on a print server. * cleanup of documentnames "Microsoft -" * define templates for output-file names with full environment variable substitution e.g. %homedrive%\%homedir%\%redmon-user%-%date%-%time%-%n.pdf * RedMon EE does not support for NT 3.5 and Windows 95/98 ! -Thynnus From israelu at elbit.co.il Tue Jan 15 06:07:47 2008 From: israelu at elbit.co.il (iu2) Date: Tue, 15 Jan 2008 03:07:47 -0800 (PST) Subject: print >> to a derived file References: Message-ID: <30e4d68b-8d0f-42b5-afe1-ac78dd35be97@k39g2000hsf.googlegroups.com> On Jan 15, 12:44?pm, "Ben Fisher" wrote: > This might have something to do with the class being derived from file. > > I've written it so that it doesn't derive from file, and it works. > > class File_and_console(): > ? ? ? ? def __init__(self, *args): > ? ? ? ? ? ? ? ? self.fileobj = open(*args) > ? ? ? ? def write(self, s): > ? ? ? ? ? ? ? ? self.fileobj.write(s) > ? ? ? ? ? ? ? ? print s, > > f = File_and_console('testout.tmp','w') > f.write('hello') > print >>f,'hello', > Thanks, but that's what I tried first. Then I though it would be nice if I could just inherit from 'file' and implement this with less code. From ian at neustyle.com Sun Jan 6 03:31:13 2008 From: ian at neustyle.com (Soviut) Date: Sun, 6 Jan 2008 00:31:13 -0800 (PST) Subject: list property fires get on append References: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com> Message-ID: On Jan 6, 3:03 am, Fredrik Lundh wrote: > i... at neustyle.com wrote: > > I've created a class that has a property which points at a private > > list. When I try to use the append() function on this list property, > > the fget method is fired rather than the fset method. If I directly > > set my property to a literal list, the set method fires. > > # this fires a get for some reason > > hierarchy.children.append( Hierarchy.Hierarchy()) > > that's the expected behaviour: you're *fetching* the "children" > attribute in order to modify it, you're not replacing it. > > reading up on Python's object model might be helpful. > > I figured that an append would be treated as a set since I'm adding to the list. But what you say makes sense, although I can't say I'm happy with the behaviour. Is there any way I can get the append to fire a set? I'm thinking of properties from my C# background where i believe that manipulation such this would be considered a set. From chaosgy at gmail.com Sat Jan 26 12:36:32 2008 From: chaosgy at gmail.com (chaosgy at gmail.com) Date: Sat, 26 Jan 2008 09:36:32 -0800 (PST) Subject: Beginner String formatting question References: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> Message-ID: <7d795bb4-665c-4a03-8d54-aef06e97f686@i29g2000prf.googlegroups.com> On 1?27?, ??1?02?, JAMoor... at gmail.com wrote: > Hi all, > > I am trying to write a simple program that will accept an integral > "time" input in the HHMMSS format and output a "HH:MM:SS" form. My > code is as follows: > ======================== > import string > > def FormatTime(time): > '''Converts an HHMMSS string to HH:MM:SS format.''' > > timeString = str(time) #converts the num to string > > hours = [timeString[0], timeString[1]] > minutes = [timeString[2], timeString[3]] > seconds = [timeString[4], timeString[5]] > > Ftime = "%s:%s:%s",(hours,minutes,seconds) > clock = Ftime.join() > > return clock > =========================== > > when I run it from IDLE, I get this: > > >>> Format.FormatTime(time) > > ['1', '1', ':', '2', '2', ':', '3', '3'] > ['1', '1', ':', '2', '2', ':', '3', '3'] > > My questions- > 1) Why is this function printing out twice? > 2)It may be a formatting issue, but I want to have the output as > "HH:MM:SS", rather than having it broken out into each cell. I > thought the 'join' command would do this, but I must not be using it > properly/understanding something. > 3)as a side note, I've noticed that the parameter "time" passed in > must be passed in as a string, otherwise I receive an error that > "time" is unsubscriptable. Am I unable to pass in an int and then > convert it to a string within the function with str()? > > I've been at this for a while, so I may not be able to see the forest > through the trees at this point. I'd greatly appreciate any > suggestions or instruction on these mistakes. > > Best, > > Jimmy import string def FormatTime(time): '''Converts an HHMMSS string to HH:MM:SS format.''' timeString = "%06d" % (time, ) #converts the num to string return timeString[:2] + ":" + timeString[2:4] + ":" + timeString[4:]; this works From thegooddale at gmail.com Thu Jan 31 00:15:05 2008 From: thegooddale at gmail.com (Yansky) Date: Wed, 30 Jan 2008 21:15:05 -0800 (PST) Subject: Online Debugging Message-ID: I'm trying to debug a script on my server and it's taking forever using print to find the error. I've tried to use the debugging examples on this page http://webpython.codepoint.net/debugging but they don't seem to be working for me. Is there an easier/better way to debug online scripts? I was hoping there might be something similar to php where it gives some error info and the line code. Cheers. From Christopher.Osthaus at ngc.com Thu Jan 17 11:06:05 2008 From: Christopher.Osthaus at ngc.com (Osthaus, Christopher (Mission Systems)) Date: Thu, 17 Jan 2008 10:06:05 -0600 Subject: Importing java within python Message-ID: Hi All, This is an easy one - I'm new to Python and working on a script where I need to use some java swing classes. I'm running Python on Windows. I've got an import statement that looks something like: from java.lang import System from javax.swing import JPasswordField from javax.swing import JOptionPane How do I get Python to recognize the java module? I assume I need to set one of my environment variables? I realize this is probably very obvious but I can't seem to figure it out :) Thanks everyone... -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun Jan 27 21:20:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jan 2008 21:20:22 -0500 Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> Message-ID: "Russ P." wrote in message news:9aec1b73-79f5-467b-a544-889107caa3b2 at q77g2000hsh.googlegroups.com... |> Perhaps this:http://www.python.org/dev/peps/pep-3107/might be relevant? | Thanks. If I read this correctly, this PEP is on track for Python 3.0. Wonderful! If you experiment with static analysis using annotations, I am sure many would be interested in the results. tjr From kay.schluehr at gmx.net Sun Jan 27 22:40:40 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 27 Jan 2008 19:40:40 -0800 (PST) Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> Message-ID: <7401a20c-d583-4690-92da-503e6651b223@b2g2000hsg.googlegroups.com> On Jan 28, 12:22 am, Arnaud Delobelle wrote: > On Jan 27, 11:00 pm, "Russ P." wrote: > > > On Jan 27, 2:49 pm, "Andr?" wrote: > > > Perhaps this:http://www.python.org/dev/peps/pep-3107/mightbe > > > relevant? > > > Andr? > > > Thanks. If I read this correctly, this PEP is on track for Python 3.0. > > Wonderful! > > Note that annotations do not provide explicit typing, AFAIK: > > def f(x:int) -> int: return x*2 > > is stricly equivalent to > > def f(x): return x*2 > f.__annotations__ = {'x':int, 'return':int} > > You still need to write a type-checking wrapper. Has anyone figured out how to match arguments passed into a "wrapper" function defined within a decorator onto the signature of f or onto f.__annotations__ respectively? > PEP 3107 mentions two > such tools: > *http://oakwinter.com/code/typecheck/ > *http://maxrepo.info/taxonomy/term/3,6/all > Neither require annotations. I like the design of the typecheck package. Everying is implemented in __init__.py ;) From jarausch at igpm.rwth-aachen.de Fri Jan 11 03:28:09 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Fri, 11 Jan 2008 09:28:09 +0100 Subject: module finalizer - is there such a beast? Message-ID: <5uonkrF1ios6tU1@mid.dfncis.de> Hi, when a module gets imported the statements not contained in function definitions or classes are executed. This can be thought of an initializer for the module. But how can I get control when the module gets unloaded either by Python's gc, Python's exit or by a module reload. Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From __peter__ at web.de Tue Jan 22 04:30:22 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 Jan 2008 10:30:22 +0100 Subject: Question on sort() key function References: <5vlopgF1mv4ekU1@mid.dfncis.de> <7xve5mfdmr.fsf@ruckus.brouhaha.com> <5vlqbjF1kl9cjU1@mid.dfncis.de> Message-ID: Robert Latest wrote: > Paul Rubin wrote: >> The attribute is on instances of File, not on the class itself. See >> if this works: >> >> flist.sort(key=lambda f: f.mod_date.toordinal) > > It doesn't throw an error any more, but neither does it sort the list. This, > however, works: > > ---------------------- > def by_date(f1, f2): > return f1.mod_date.toordinal() - f2.mod_date.toordinal() > > flist.sort(by_date) > ---------------------- > > So I'm sticking with it, although I sort of liked the key approach. > > robert This should work then: def date_key(f): return f.mod_date.toordinal() flist.sort(key=date_key) This can also be written as flist.sort(key=lambda f: f.mod_date.toordinal()) Peter From jpeng at block.duxieweb.com Mon Jan 21 03:03:37 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Mon, 21 Jan 2008 16:03:37 +0800 Subject: Sorting a list depending of the indexes of another sorted list In-Reply-To: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> Message-ID: <479451D9.3060207@block.duxieweb.com> I tried to write it below,it can work,:) v= """preference 10 host mx1.domain.com preference 30 host anotherhost.domain.com preference 20 host mx2.domain.com""" x=v.split("\n") li =[] for i in x: k = (i.split())[3] y = (i.split())[1] li.append((y,k)) li.sort() print li the output is: [('10', 'mx1.domain.com'), ('20', 'mx2.domain.com'), ('30', 'anotherhost.domain.com')] Santiago Romero ??: > Hi ... > > I have the following DNS MX records info: > > domain.com > preference 10 host mx1.domain.com > preference 30 host anotherhost.domain.com > preference 20 host mx2.domain.com > > I'm storing this info in 2 lists: > > preferences = [10, 30, 20] > hosts = [ "mx1.domain.com", "anotherhost.domain.com", > "mx2.domain.com"] > From paul at boddie.org.uk Wed Jan 23 07:57:48 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 23 Jan 2008 04:57:48 -0800 (PST) Subject: Problem with processing XML References: <13pbudgks88rcf3@corp.supernews.com> <47971EFF.8070701@web.de> Message-ID: <6c291c78-7a11-4d6f-be15-c916017ccf60@s13g2000prd.googlegroups.com> On 23 Jan, 12:03, Stefan Behnel wrote: > > I had a discussion with Java people lately and they were all for Ruby, Groovy > and similar languages, "because they have curly braces and are easy to learn > when you know Java". > > My take on that is: Python is easy to learn, full-stop. Well, that may be so, but it's somewhat beside the point in question. > It's the same for DOM: when you know DOM from (usually) the Java world, having > a DOM-API in Python keeps you from having to learn too many new things. But > when you get your nose kicked into ElementTree, having to learn new things > will actually help you in understanding that what you knew before did not > support your way of thinking. I'm not disputing the benefits of the ElementTree approach, but one has to recall that the DOM is probably the most widely used XML API out there (being the one most client-side developers are using) and together with the other standards (XPath and so on) isn't as bad as most people like to make out. Furthermore, I don't think it does Python much good to have people "acting all Ruby on Rails" and telling people to throw out everything they ever did in order to suck up the benefits, regardless of the magnitude of those benefits; it comes across as saying that "your experience counts for nothing compared to our superior skills". Not exactly the best way to keep people around. As I noted in my chronology, the kind of attitude projected by various people in the Python community at various times (and probably still perpetuated in the Ruby community) is that stuff originating from the W3C is bad like, for example, XSLT because "it's like Lisp but all in XML (yuck!)", and yet for many tasks the most elegant solution is actually XSLT because it's specifically designed for those very tasks. Fortunately or unfortunately, XSLT didn't make it into the standard library and thus isn't provided in a way which may or may not seem broken but, like the DOM stuff, if the support for standardised/ recognised technologies is perceived as deficient, and given the point above about glossing over what people themselves bring with them to solve a particular problem, then people are quite likely to gloss over Python than hear anyone's sermon about how great Python's other XML technologies are. > http://www.python.org/about/success/esr/ > > So, there is a learning curve, but it's much shorter than what you already > invested to learn 'the wrong thing'. It's what people on this list tend to > call their "unlearning curve". Well, maybe if someone helped the inquirer with his namespace problem he'd be getting along quite nicely with his "unlearning curve". Paul From aisaac at american.edu Tue Jan 22 11:10:53 2008 From: aisaac at american.edu (Alan Isaac) Date: Tue, 22 Jan 2008 16:10:53 GMT Subject: pairs from a list In-Reply-To: References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: Arnaud Delobelle wrote: > According to the docs [1], izip is defined to be equivalent to: > > def izip(*iterables): > iterables = map(iter, iterables) > while iterables: > result = [it.next() for it in iterables] > yield tuple(result) > > This guarantees that it.next() will be performed from left to right, > so there is no risk that e.g. pairs4([1, 2, 3, 4]) returns [(2, 1), > (4, 3)]. > > Is there anything else that I am overlooking? > > [1] http://docs.python.org/lib/itertools-functions.html fwiw, Alan Isaac From bruno.desthuilliers at gmail.com Wed Jan 9 18:10:55 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 9 Jan 2008 15:10:55 -0800 (PST) Subject: Python too slow? References: 76bc64cc-541c-434f-aac5-96d1a2d231ee@c23g2000hsa.googlegroups.com Message-ID: <7115e305-429c-47d3-a942-8a0e2a0e846f@m34g2000hsf.googlegroups.com> On 10 jan, 00:02, "bruno.desthuilli... at gmail.com" > (sorry, hit the wrong key - time to bed I guess...) > If none of the two above answers fits your needs, and no Python Guru > comes with a better answer, then I'm afraid you'll have to go for a > language with a faster implementation. Python is quite faster nowadays > than it used to be, and is usually fast enough for most day-to-day > programming tasks (a ... at least for my own day-to-day tasks) > but it's still not as highly optimized as some > Lisp implementations (to compare to another highly ... dynamic language). From tjreedy at udel.edu Thu Jan 31 19:18:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Jan 2008 19:18:57 -0500 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: "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. From timr at probo.com Sun Jan 13 18:36:57 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 13 Jan 2008 23:36:57 GMT Subject: paging in python shell References: Message-ID: "Alex K" wrote: > >Does anyone know if the python shell supports paging or if I should >look into iPython? Thank you so much. "Paging" is an overloaded term. What do you mean, exactly? Do you mean something like piping the output into "more"? The Python shell does that for the "help" command, but maybe you could post a more precise example of what you want. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From nick at craig-wood.com Wed Jan 9 09:30:06 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 09 Jan 2008 08:30:06 -0600 Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <87ejcri96v.fsf@mulj.homelinux.net> <87abnfi84i.fsf@mulj.homelinux.net> <5ujp20F1ehvg2U2@mid.dfncis.de> Message-ID: Fredrik Lundh wrote: > Nick Craig-Wood wrote: > > > Using keywords[:] stops the creation of another temporary list. > > in CPython, "list[:] = iter" actually creates a temporary list object on > the inside, in case "iter" isn't already a list or a tuple. > > (see the implementation of PySequence_Fast() for details). Ah, OK, thanks for the correction! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bladedpenguin at gmail.com Sat Jan 26 01:52:58 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 22:52:58 -0800 (PST) Subject: Doesn't know what it wants References: Message-ID: <0104616d-87be-4250-b3ef-7a77ac39664a@u10g2000prn.googlegroups.com> On Jan 26, 1:41 am, John Machin wrote: > On Jan 26, 4:20 pm, Tim Rau wrote: > > > > > Traceback (most recent call last): > > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > > \sandbox.py", line 242, in > > player = ship() > > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > > \sandbox.py", line 121, in __init__ > > self.phyInit() > > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > > \sandbox.py", line 147, in phyInit > > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) > > ArgumentError: argument 4: : expected > > vec2d instance instead of vec2d > > > As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't > > seems like it doesn't know what it wants, but I thought only teenagers > > did that, no programming languages. > > It possibly means that it is expecting an instance of a class whose > name is "vec2d" but you have given it an instance of some *other* > class whose name just happens to be "vec2d". > > > clearly, Im missing something. > > Yes, some information: > 1. what is vec2d, class or function? > 2. what do you believe vec2d((0, 0)) should return? > 3. what is this belief based on? > 4. what has it actually returned this time? > 5. what do you believe that cp.cpMomentForCircle expects as argument > 4? > 6. what is this belief based on? > > The ArgumentError exception is raised by ctypes "when a foreign > function call cannot convert one of the passed arguments". Based on > guessin'n'googlin' the cp thing is a set of Python bindings to a > library written in C++ ... have you considered asking the author of > the bindings? 1. vec2d is a class, designed to hold and manipulte 2d vectors 2. it should return a vector with x=0 and y=0 3. That's what it's done before. 4. trying it in the interpreter seems to show that it returns a vec2d with zero length. as it should. 5.cp.cpMomentForCircle seems to expect a vec2d. I'm baseing that on a functioning demo that uses the exact same line. I guess that the vec2d I've got is not the one it wants. How do I tell the difference? I'll go look at all the imports. From steve at holdenweb.com Wed Jan 23 22:54:48 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 23 Jan 2008 22:54:48 -0500 Subject: newbie question: On installation of additional packages to Python In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Tue, 22 Jan 2008 00:36:34 -0200, Nasser Abbasi escribi?: > >> I am running on windowz. I have downloaded and installed 2.5.1 Python. >> >> my question is on installing additional packages. >> >> What is the easiest way to do that? I read about python 'eggs' (like jar >> files for Java), and easyInstall script, and such. > > Once you have setuptools installed, it's as easy as executing: > easy_install packagename > The alternative is to find and download the package yourself, unzip in a > temporary directory, and execute: setup.py install > For most packages that's all that is required. > >> Is there some automated way to install Python packages? a >> manual/document I >> could read that describes step by step how to do that? Browsing the >> documentation, there does not seem to be something specific there (other >> than saying download this tar file and install it). >> >> I like how one can install additional packages in 'R' . In 'R' one can do >> all that from the user interface for R by a pull-down menu, then one >> selects >> a mirror site, then one can see all the packages available, then select >> the >> package to download, and the rest is done automatically. (The package is >> downloaded, installed, etc...) > > That's mainly what easy_install does, plus dependency checking. > So, the only step you are missing is how to install setuptools. This is simplicity itself: 1. In your web browser visit http://peak.telecommunity.com/dist/ez_setup.py 2. Save the Python. In Internet Explorer use "File | Save As", in Firefox use "File | Save Page As" 3. Run it from the command line (or possibly by double-clicking it in an explorer window, never tried that) You should now be able to run easy_install from the command line and install packages from the usual suspects. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gherron at islandtraining.com Fri Jan 11 03:30:46 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 11 Jan 2008 00:30:46 -0800 Subject: HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? In-Reply-To: <7243c2ac-fa22-4b5b-bd8c-34235123ab69@t1g2000pra.googlegroups.com> References: <7243c2ac-fa22-4b5b-bd8c-34235123ab69@t1g2000pra.googlegroups.com> Message-ID: <47872936.9070603@islandtraining.com> abhishek wrote: > Hi group any idea on HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? > > > Thank you > POINTERS? Heaps? Huh? Ummm, let me think -- those terms *do* sound vaguely familiar -- from sometime in the deep dark primitive past. Perhaps from back in my (shudder) C/C++ days -- ya, that's it. Thankfully, this is Python and the modern era -- we don't use no stinking POINTERS here. Seriously, this group deals with Python. There are no pointers in Python. Now please, what did you *really* mean to ask? Gary Herron From steven.bethard at gmail.com Tue Jan 15 13:58:41 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 15 Jan 2008 11:58:41 -0700 Subject: SyntaxError: 'import *' not allowed with 'from .' In-Reply-To: <9ac37212-7521-454d-a35f-afd6f7ec24f6@m34g2000hsf.googlegroups.com> References: <9ac37212-7521-454d-a35f-afd6f7ec24f6@m34g2000hsf.googlegroups.com> Message-ID: George Sakkis wrote: > Unless I missed it, PEP 328 doesn't mention anything about this. > What's the reason for not allowing "from .relative.module import *' ? Generally, there's a move away from all "import *" versions these days. For example, Python 3.0 removes the ability to use "import *" within a function: http://www.python.org/dev/peps/pep-3100/ I suspect the "import *" version is not enabled for relative imports because most of python-dev is against "import *" forms anywhere. STeVe From tommy.nordgren at comhem.se Fri Jan 11 19:48:40 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Sat, 12 Jan 2008 01:48:40 +0100 Subject: IDLE won't start in Python 2.5 for Windows In-Reply-To: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> References: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> Message-ID: <5C0D44EF-6B44-4024-85FA-82CF56DB738F@comhem.se> On 12 jan 2008, at 01.18, mikez302 wrote: > I have Python 2.5 and Windows XP SP2. For a while, IDLE worked, but > now it doesn't. The last time I was using it, I was changing some > keyboard shortcuts, then the window suddenly disappeared. Since then, > I haven't been able to start it. > > When I try to start it, I see pythonw.exe come up on my Task Manager > for about a second, then disappear. Other than that, I don't see any > hint as to what is happening. The Python command line works fine. > > I tried rebooting, repairing Python, uninstalling and reinstalling > Python, and upgrading to version 2.5.1, but I still haven't fixed the > problem. Is there anything else I can do to fix it? > > Elias > -- > http://mail.python.org/mailman/listinfo/python-list I suggest you try: 1) Cleaning the registry 2) Searching for IDLE preference files and delete them. Corrupt preference settings are a common cause for application misfunction on all Operating Systems. ------------------------------------------------------ "Home is not where you are born, but where your heart finds peace" - Tommy Nordgren, "The dying old crone" tommy.nordgren at comhem.se From ggpolo at gmail.com Wed Jan 23 19:11:15 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jan 2008 22:11:15 -0200 Subject: Creating new types and invoking super In-Reply-To: <9eeb9667-f362-4ce2-971a-42ef639c8f86@c4g2000hsg.googlegroups.com> References: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> <9eeb9667-f362-4ce2-971a-42ef639c8f86@c4g2000hsg.googlegroups.com> Message-ID: 2008/1/23, Arnaud Delobelle : > On Jan 23, 10:18 pm, "Guilherme Polo" wrote: > > 2008/1/23, Arnaud Delobelle : > > > > > The only way I can think of would be to create a metaclass, but I > > > don't think it's worth it. super(A, obj).__init__() isn't that bad! > > > > Metaclass doesn't apply here because metaclass is related to > > class-construction. This is related to instance initialization, and > > I'm creating the types as the user asks. > > Not completely clear to me what you want but here is a 'proof of > concept': > > ========== > > class callsuper(object): > def __init__(self, f): > self.f = f > def __get__(self, obj, cls=None): > def newfunc(*args, **kwargs): > super(self.cls, obj).__init__() > return self.f(obj, *args, **kwargs) > return newfunc > > class Type(type): > def __init__(self, name, bases, attrs): > for attrname, attr in attrs.iteritems(): > if isinstance(attr, callsuper): > attr.cls = self > > class A: > __metaclass__ = Type > def __init__(self): > print "init A" > > class B(A): > @callsuper > def __init__(self): > print "init B" > > ========== > > >>> b=B() > init A > init B > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for this concept, works better than mine :) -- -- Guilherme H. Polo Goncalves From robert.rawlins at thinkbluemedia.co.uk Mon Jan 28 12:46:14 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 28 Jan 2008 17:46:14 -0000 Subject: Get Available Functions In-Reply-To: <479E0A7A.9080305@tim.thechases.com> References: <020501c861ca$d604dc70$820e9550$@rawlins@thinkbluemedia.co.uk> <479E0A7A.9080305@tim.thechases.com> Message-ID: <022f01c861d5$ad6b7c50$084274f0$@rawlins@thinkbluemedia.co.uk> Thanks for that Tim, I'll have a play around with these functions later today and see what happens, hopefully it'll shed some light on this API for me. Thanks mate, I appreciate it. Rob -----Original Message----- From: Tim Chase [mailto:python.list at tim.thechases.com] Sent: 28 January 2008 17:02 To: Robert Rawlins - Think Blue Cc: python-list at python.org Subject: Re: Get Available Functions > I'm working with a python module which isn't part of the core > Python API and it also isn't very documented or supported, is > there any way that I can easily dump/view the available > classes and methods within the package from within python? Most of the time, the dir(), type() and help() functions can be your friend: >>> import somelib >>> dir(somelib) ['Foo', 'thing', 'whatever'] >>> type(somelib.Foo) >>> dir(somelib.Foo) ['method1', 'method2'] >>> type(somelib.thing) >>> print somelib.thing 'I didn't expect the Spanish Inquisition!' >>> type(somelib.whatever) >>> help(somelib.whatever) Help on function whatever in module somelib: whatever(param1, param2, *args, **kwargs) >>> I've had a couple cases where the underlying module was written in C (mod_python in particular...don't know if it still has this problem) where dir() wouldn't actually tell you about the object, but for most cases, dir() will get you pointed in the right dir-ection. :) -tkc From fredrik at pythonware.com Sun Jan 13 08:02:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 13 Jan 2008 14:02:13 +0100 Subject: Simple List division problem In-Reply-To: <00cb6e9d-e8b6-4e65-be58-5a4472413c53@j78g2000hsd.googlegroups.com> References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> <00cb6e9d-e8b6-4e65-be58-5a4472413c53@j78g2000hsd.googlegroups.com> Message-ID: thebjorn wrote: > Eh... oh, forgot that it was "pulling requirements out of thin air" week on c.l.python. > def chop(lst, length): > n = len(lst) / length > z = [lst[i:i+n] for i in xrange(0, len(lst), n)] > if len(z[-1]) < n and len(z) > 1: > z[-2].extend(z.pop(-1)) > return z > > gives >>>> chop([1], 3) > Traceback (most recent call last): > File "", line 1, in > File "beforemeth.py", line 9, in chop > if len(z[-1]) < n and len(z) > 1: > ValueError: xrange() arg 3 must not be zero well, it doesn't. there's no xrange on that line. > Perhaps something like this? > from itertools import islice or just use an if-statement, or the max function. but I guess those tools are too old and boring for c.l.python these days... From peter.maas at somewhere.com Sat Jan 5 15:29:49 2008 From: peter.maas at somewhere.com (Peter Maas) Date: Sat, 05 Jan 2008 21:29:49 +0100 Subject: python interfaces In-Reply-To: References: Message-ID: Sion Arrowsmith wrote: > hyperboreean wrote: >> Why doesn't python provide interfaces trough its standard library? > > Because they're pointless. Wrong. I'm using Eclipse with the Java Development Tools (JDT) who do a wonderful job using interfaces to perform lots of checking, warning and code generation *nearly in real time while I am editing my code*. Because JDT knows interfaces it knows what to do and to suggest. An interface is a software specification allowing you to use a software package without extensive code studies. This is a good thing. > Java interfaces are a hack around the complexities of multiple > inheritence. A hack is something applied subsequently to solve a software problem while avoiding large changes. Java interfaces originate from careful language design. You are free to dislike Java interfaces but calling them a hack is just plain wrong. Once software becomes really big interfaces are very useful to handle complexity. Ever wondered why the Zope people introduced interfaces in their Python code? > Interfaces used purely with the idea of type safety provide > precious little gain for the added clutter and inconvenience. An interface is a software specification allowing you to use a software package without extensive code studies. This is a good thing. Interfaces have nothing to do with multiple inheritance. They just tell you how to connect, how to plug in. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From grante at visi.com Mon Jan 21 11:04:25 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 21 Jan 2008 16:04:25 -0000 Subject: Memory errors with imaplib References: <6012daff-0fd3-4835-a9ca-c18d2a2ac53c@v29g2000hsf.googlegroups.com> <13p6pf5he8am89e@corp.supernews.com> <13p7jubq0hiqr55@corp.supernews.com> Message-ID: <13p9gk93fi8gh75@corp.supernews.com> On 2008-01-21, Christian Heimes wrote: > Grant Edwards wrote: > >> If the solution shown in the bug report is correct, I'd be >> more than happy to generate a patch. > > The solution seems fine but IMO it should be fixed in the ssl > socket and not in imaplib. I like to get it *fixed* and not > *worked around*. :) I've always been taught that you can't assume that a read on a socket (ssl or otherwise) will return the number of bytes you request. You've always got to code for the case where read() returns smaller chunks. Maybe I've been taught wrongly, but under Unix at least I've found that it's always a good practice to assume that network reads will often return smaller chunks than requested. -- Grant Edwards grante Yow! Are we on STRIKE yet? at visi.com From andre.roberge at gmail.com Sun Jan 27 22:18:29 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 27 Jan 2008 19:18:29 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> <7xhcgyodvy.fsf@ruckus.brouhaha.com> Message-ID: <9a9f7b3f-50ff-46f9-9c7e-5d635ff7bec3@n20g2000hsh.googlegroups.com> On Jan 27, 10:57 pm, Paul Rubin wrote: > Wildemar Wildenburger writes: > > class Server(object): > > def __init__(self, self.host, self.port, > > self.protocol, self.bufsize, self.timeout): > > pass > > ? > > That could temporarily bind those attributes but it shouldn't > persistently mutate the object. > > How about: > > class Server(object): > def __init__(self, host, port, protocol, bufsize, timeout): > self.(host, port, protocol, bufsize, timeout) = \ > host, port, protocol, bufsize, timeout > > That's fairly explicit yet cuts down the total amount of boilerplate. Not much; you're still repeating each variable name 3 times. I prefer the standard way of one definition per line over this notation myself. Andr? From cokofreedom at gmail.com Thu Jan 24 03:24:58 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 24 Jan 2008 00:24:58 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <7x8x2g8isi.fsf@ruckus.brouhaha.com> <13pfgdct573772d@corp.supernews.com> <04d0ed52-4b45-4c07-8ea6-ab3bb3f85225@e25g2000prg.googlegroups.com> <18aa66c3-78ba-45f6-aeb4-9dec0a37e074@t1g2000pra.googlegroups.com> Message-ID: <26a4c312-4969-412e-b368-1ffbead47fff@l32g2000hse.googlegroups.com> On Jan 24, 8:21 am, ryan k wrote: > On Jan 23, 6:30 pm, John Machin wrote: > > > On Jan 24, 9:50 am, ryan k wrote: > > > > Steven D'Aprano, you are a prick. > > > And your reasons for coming to that stridently expressed conclusion > > after reading a posting that was *not* addressed to you are .....? > > Because his tone is extremely condescending and quite frankly > annoying. From this post to others, his terse remarks scar this > community and fade its atmosphere of friendliness. And your response was any better because...? From andre.roberge at gmail.com Mon Jan 28 11:08:18 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 28 Jan 2008 08:08:18 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> Message-ID: On Jan 28, 11:45 am, Steven Bethard wrote: > Arnaud Delobelle wrote: > > Sligthly improved (not for performance! but signature-preserving and > > looks for default values) > > > from functools import wraps > > from inspect import getargspec > > from itertools import izip, chain > > > def autoassign(*names): > > def decorator(f): > > fargnames, _, _, fdefaults = getargspec(f) > > defaults = [(n,v) for (n,v) > > in izip(reversed(fargnames), reversed(fdefaults)) > > if n in names] > > @wraps(f) > > def decorated(self, *args, **kwargs): > > self.__dict__.update(defaults) > > for name, arg in chain(izip(fargnames, args), > > kwargs.iteritems()): > > if name in names: > > setattr(self, name, arg) > > return f(self, *args, **kwargs) > > return decorated > > return decorator > > > class Test(object): > > @autoassign('foo', 'bar') > > def __init__(self, foo, bar=3, baz=6): > > print 'baz =', baz > > > t = Test(1, 2, 6) > > u = Test(foo=8) > > > print t.foo # 1 > > print t.bar # 2 > > > print u.foo # 8 > > print u.bar # 3 (default) > > You should definitely post this to the cookbook: > > http://aspn.activestate.com/ASPN/Cookbook/Python > > STeVe If I may suggest, I would extend this so that autoassign's signature would be as follows: autoassign(all=True, include_only=None, exclude=None) Either one of include_only or exclude could be a list of function to which the automatic assignment would apply (or not). I was planning to write this up and submit it to the cookbook later this evening, but since the suggestion has been made, someone else can jump on it. ;-) Andr? From cwitts at gmail.com Fri Jan 4 08:58:35 2008 From: cwitts at gmail.com (Chris) Date: Fri, 4 Jan 2008 05:58:35 -0800 (PST) Subject: Strange varargs issue References: Message-ID: On Jan 4, 3:45 pm, Mike wrote: > I'm not sure if this is a bug or if I'm just not understanding > something correctly. I'm running the following (broken.py) on > ActivePython 2.5.1.1, based on Python 2.5.1 (r251:54863 5/1/2007) as > "python broken.py foo" (on Windows, of course): > > #!/bin/env python > > import sys > > class foobar(object): > def func(arg): > print 'foobar.func: %r' % arg > > __f = foobar() > > def caller(a): > print 'caller: %r' % a > __f.func(a) > > def main(): > rest = sys.argv[1:] > print 'main: %r' % rest > caller(*rest) > > if __name__ == '__main__': > main() > > ...and the result of running this ("python broken.py foo") is: > > main: ['foo'] > caller: 'foo' > Traceback (most recent call last): > File "broken.py", line 21, in > main() > File "broken.py", line 18, in main > caller(*rest) > File "broken.py", line 13, in caller > __f.func(a) > TypeError: func() takes exactly 1 argument (2 given) > > How can this possibly be? The "caller" print statement obviously > shows "a" is singular. > > Thanks in advance for any and all insight... > > Mike class foobar(object): def func(arg): print 'foobar.func: %r' % arg def caller(a): __f.func() >>> main: ['foo'] >>> caller: 'foo' >>> foobar.func: <__main__.foobar object at 0x00A45550> class foobar(object): def func(self, arg): print 'foobar.func: %r' % arg def caller(a): __f.func(a) >>> main: ['foo'] >>> caller: 'foo' >>> foobar.func: 'foo' You're already passing the object as an argument in the first case. From list-ener at strank.info Tue Jan 22 10:29:32 2008 From: list-ener at strank.info (Stefan Rank) Date: Tue, 22 Jan 2008 16:29:32 +0100 Subject: isgenerator(...) - anywhere to be found? In-Reply-To: <707d792b-e802-4c0e-854e-aac264d83c48@c4g2000hsg.googlegroups.com> References: <5vm8t3F1m1797U1@mid.uni-berlin.de> <707d792b-e802-4c0e-854e-aac264d83c48@c4g2000hsg.googlegroups.com> Message-ID: <47960BDC.3030809@strank.info> on 22.01.2008 16:09 Paul McGuire said the following: > On Jan 22, 7:46 am, Stefan Rank wrote: >> I also need to test for generator functions from time to time for which >> I use:: >> >> def _isaGeneratorFunction(func): >> '''Check the bitmask of `func` for the magic generator flag.''' >> return bool(func.func_code.co_flags & CO_GENERATOR) >> >> cheers, >> stefan > > Might want to catch AttributeError in this routine - not all func > arguments will have a func_code attribute. See below: > > class Z(object): > def __call__(*args): > for i in range(3): > yield 1 > > for i in Z()(): > print i > # prints 1 three times > > import types > print type(Z()()) == types.GeneratorType > # prints 'True' > > print Z()().func_code > # raises AttributeError, doesn't have a func_code attribute You are right about that for generator *objects*. But _isaGeneratorFunction tests for generator *functions* (the ones you call in order to get a generator object) and those must have a func_code. So in your example:: >>> from compiler.consts import CO_GENERATOR >>> Z().__call__.func_code.co_flags & CO_GENERATOR 32 >>> Z.__call__.func_code.co_flags & CO_GENERATOR 32 You have to use __call__ directly, you can't use the code-object-flag test on the callable class instance Z(), but I think that's just as well since this kind of test should not be necessary at all, except in rare code parts (such as Diez' microthreading experiments). cheers, stefan From ivanlan9 at gmail.com Tue Jan 29 13:03:20 2008 From: ivanlan9 at gmail.com (Ivan Van Laningham) Date: Tue, 29 Jan 2008 11:03:20 -0700 Subject: Problem with Tkinter scrollbar callback In-Reply-To: References: Message-ID: No Joy. Waits the 1 second, then clicks the button once per second until the limit's reached. Sigh. Metta, Ivan On Jan 29, 2008 10:20 AM, Russell E Owen wrote: > >Nope: > > > >'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '300'), > > > >And even after I set it, it looks funny: > > > >'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '1000'), > > > >And when I try it with the new repeatdelay (1000), the only thing that > >has changed is that it waits 1000 milliseconds before exhibiting the > >same uncontrolled growth as before. > > You need to change repeatinterval, not repeatdelay. > > As to "looking funny": that is the standard output format for > configure(). I think can get a more reasonable value using > "cget(repeatdelay)". > > -- Russell > > > > > >Metta, > >Ivan > > > >On Jan 25, 2008 5:49 PM, Russell E. Owen wrote: > >> In article , > >> "Ivan Van Laningham" wrote: > >> > >> > Hi All-- > >> > That helps. Doing a get() on the scrollbar before a set(0.0,0.0) > >> > returns a 4-tuple: (0.0, 0.0, 0.0, 0.0) ! I did the set(0.0,0.0) > >> > and now the callback gets the correct number of arguments. > >> > > >> > However, I'm still getting the weird behaviour when clicking the > >> > arrowheads--and the heads are all I want. They act like they've been > >> > set to a keybounce timeout of about a millisecond. ... The arrow > >> > click increments the number of cells in a table row (effectively), and > >> > it shoots up from 5 to 26 columns almost instantly (that's the > >> > internal max I set). > >> > >> Is the scroll bar's repeatinterval set to a reasonable value? > >> > >> -- Russell > >> > >> -- > >> 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 > > -- 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 deets at nospam.web.de Mon Jan 28 10:30:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jan 2008 16:30:29 +0100 Subject: sharing objects between classes References: Message-ID: <606aolF1pa0tfU2@mid.uni-berlin.de> Gerardo Herzig wrote: > Hi all. Im wondering the way to share a database connection between some > classes: > > So far, i came up with a simple class schema, where each class means > each different relation, i mean i have the follow classes > > class Database(object): > ## make the connection > self.conn = make_conn(....) > > class Table(object): > def get_fields: > .... > > And at this point i dont know how to use the Database.conn attribute, > since the get_fields method will perform a query over the given database. > At first, i just define the Table class as a inner class of Database, > but if i try a > class Database(object): > ## make the connection > def __init__(self): > self.conn = sql_connect(....) > self.table = Table('foo') > > class Table(object): ## inner class > def get_fields(self, name): > .... > > I get a "NameError: global name 'Table' is not defined". > > So, which would the right pattern to use here? Using a global module? I > dont know why, but i dont like that idea too much. > > Any comments will be appreciated! > Thanks! Take a look at the sources of e.g. SQLObject and how they do it (in SO, the concept is called "HUB") Essentially, you set a reference to a global connection object that itself isn't a simple global but useses threading.local to have one connection per thread. Then you can access that connection transparently. Diez From mmanns at gmx.net Sun Jan 13 16:31:15 2008 From: mmanns at gmx.net (Martin Manns) Date: Sun, 13 Jan 2008 22:31:15 +0100 Subject: Slicing wrapped numpy arrays Message-ID: Hi, I have created a class that wraps a numpy array of custom objects. I would like to be able to slice respective objects (without copying the array if possible). I have browsed the doc and found some hints at __getitem__. However, I still do not grasp how to do it. How do I implement __getitem__ correctly? from numpy import * class Cell(object): pass class Map(object): def __init__(self, dimensions): self.generate_map(dimensions) def generate_map(self, dimensions): map_range = xrange(reduce(lambda x,y: x*y, dimensions)) self.map = array([Cell() for i in map_range]) self.map = self.map.reshape(dimensions) mymap = Map((100, 100, 100)) mymap[10:20,15:20,:] # This line should work afterwards Thanks in advance Martin From paul.hankin at gmail.com Tue Jan 29 17:49:09 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 29 Jan 2008 14:49:09 -0800 (PST) Subject: Removal of element from list while traversing causes the next element to be skipped References: Message-ID: On Jan 29, 4:34?pm, William McBrine wrote: > Look at this -- from Python 2.5.1: > > >>> a = [1, 2, 3, 4, 5] > >>> for x in a: > > ... ? ? if x == 3: > ... ? ? ? ? a.remove(x) > ... ? ? print x > ... > 1 > 2 > 3 > 5 > > >>> a > [1, 2, 4, 5] > > Sure, the resulting list is correct. But 4 is never printed during the > loop! > > What I was really trying to do was this: > > apps = [name for name in os.listdir(ROOT) if > ? ? ? ? os.path.isdir(os.path.join(ROOT, name))] > > apptitles = {} > > for name in apps: > ? ? try: > ? ? ? ? app = __import__(name) > ? ? except: > ? ? ? ? apps.remove(name) > ? ? else: > ? ? ? ? apptitles[name] = getattr(app, 'TITLE', name.title()) > > which worked fine, until I actually had a directory with no module in it. > Then that directory was correctly removed from the list, but the _next_ > one was skipped, so its title was never assigned, which caused problems > later in the program. How about... for name in apps: try: app == __import__(name) apptitles[name] = getattr(app, 'TITLE', name.title()) except ImportError: pass # Remove apps with no title, ie those that didn't import. apps = [name for name in apps if apptitles.get(name)] Alternatives for the last line would be 'apps = filter(apptitles.get, apps)' or 'apps = apptitles.keys()'. -- Paul Hankin From jo at durchholz.org Tue Jan 1 11:14:45 2008 From: jo at durchholz.org (Joachim Durchholz) Date: Tue, 01 Jan 2008 17:14:45 +0100 Subject: Choosing a new language In-Reply-To: References: <20071228162351.f29a3ce4.coolzone@it.dk> Message-ID: > Xah Lee wrote: >> [...] PHP and Perl are practically identical in their >> high-levelness or expressiveness or field of application (and >> syntax), That must have been a very, very distant point of view with narrowly squinted eyes. Regards, Jo From donn.ingle at gmail.com Thu Jan 24 10:17:25 2008 From: donn.ingle at gmail.com (Donn Ingle) Date: Thu, 24 Jan 2008 17:17:25 +0200 Subject: piping into a python script Message-ID: Hi, (Gnu/Linux - Python 2.4/5) Given these two examples: 1. ./fui.py *.py 2. ls *.py | ./fui.py How can I capture a list of the arguments? I need to get all the strings (file or dir names) passed via the normal command line and any that may come from a pipe. There is a third case: 3. ls *.jpg | ./fui.py *.png Where I would be gathering strings from two places. I am trying to write a command-line friendly tool that can be used in traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. I have tried: 1. pipedIn = sys.stdin.readlines() Works fine for example 2, but example 1 goes into a 'wait for input' mode and that's no good. Is there a way to tell when no input is coming from a pipe at all? 2. import fileinput for line in fileinput.input(): print (line) But this opens each file and I don't want that. I have seen a lot of search results that don't quite answer this angle of the question, so I'm trying on the list. \d From gagsl-py2 at yahoo.com.ar Thu Jan 24 02:43:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 Jan 2008 05:43:22 -0200 Subject: Smart factory class References: Message-ID: En Thu, 24 Jan 2008 05:11:19 -0200, kramer31 escribi?: > Can anyone tell me if there is a way in python that I can implement a > factory function which takes as input a string ClassName and returns > an object of type ClassName? def InstanceFactory(classname): cls = globals()[classname] return cls() If the class resides in a different module: def InstanceFactory(modulename, classname): if '.' in modulename: raise ValueError, "can't handle dotted modules yet" mod = __import__(modulename) cls = getattr(mod, classname] return cls() I suppose you get the names from a configuration file or something - usually it's better to just pass the class instead of the class name. -- Gabriel Genellina From detlev at die-offenbachs.de Sat Jan 12 03:50:32 2008 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 12 Jan 2008 09:50:32 +0100 Subject: eric4 request for contribution Message-ID: Hi, I am in the progress of writing a refactoring plugin for eric4 using the rope refactoring library. Unfortunately, this library does not contain a nice icon to be shown in an About Rope dialog. Is there anybody around, who could contribute such an icon. Maybe it could look like the Python snake but instead of the snake a rope is shown. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From remco at gerlich.nl Wed Jan 23 09:18:22 2008 From: remco at gerlich.nl (Remco Gerlich) Date: Wed, 23 Jan 2008 15:18:22 +0100 Subject: How avoid both a newline and a space between 2 print commands? In-Reply-To: References: Message-ID: <7ae3ca10801230618m58823d19ied08079091e1a0f1@mail.gmail.com> Hi, Use import sys sys.stdout.write("foo") sys.stdout.write("bar") (and, possibly, sys.stdout.flush() to get the text to show up, it might wait for the end of a complete line otherwise). The alternative import sys print "foo", sys.stdout.softspace=0 print "bar" is just too hackish. In Python 3, this will be improved! Remco On Jan 23, 2008 3:03 PM, seberino at spawar.navy.mil wrote: > print "foo" > print "bar" > > has a newline in between "foo" and "bar" > > print "foo", > print "bar" > > has a space in between "foo" and "bar" > > How prevent ANYTHING from going in between "foo" and "bar" ?? > > (Without defining a string variable.) > > Chris > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From theller at ctypes.org Fri Jan 25 07:59:56 2008 From: theller at ctypes.org (Thomas Heller) Date: Fri, 25 Jan 2008 13:59:56 +0100 Subject: Windows AVIFile problems In-Reply-To: References: Message-ID: c d saunter schrieb: > Hi All, > > I'm trying to access individual video frames of an AVI file from within > Python 2.4 or 2.5 under Windows XP. > > I have found this example code here for that does exactly what I want, > using the windows avifile.dll but I am unable to find the AVIFile.h > header... > > http://mail.python.org/pipermail/image-sig/2002-February/001748.html > > An alternative is to call into avifile.dll dynamically using ctypes, > however under both Python 2.4 and 2.5 the following error happens: > >>>> from ctypes import * >>>> windll.AVIFile > > Traceback (most recent call last): > File "", line 1, in > windll.AVIFile > File "C:\Python25\lib\ctypes\__init__.py", line 415, in __getattr__ > dll = self._dlltype(name) > File "C:\Python25\lib\ctypes\__init__.py", line 340, in __init__ > self._handle = _dlopen(self._name, mode) > WindowsError: [Error 193] %1 is not a valid Win32 application > The dll is not corrupt. It is the 16-bit dll, possibly present for legacy 16-bit support. You must use the 32-bit dll, it seems it called avifil32.dll. Also I guess to get the AVIFILE.H header file, you need to install some MS SDK or the platform sdk. Thomas From rw at smsnet.pl Wed Jan 2 16:36:27 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 02 Jan 2008 22:36:27 +0100 Subject: urllib2 disable proxy References: Message-ID: <878x373o6c.fsf@merkury.smsnet.pl> Dimitrios Apostolou writes: > Hello list, > > I've been looking for a way to explicitly disable the use of proxies with > urllib2, no matter what the environment dictates. Unfortunately I can't find > a way in the documentation, and reading the source leads me to believe that > something like the following does the job: > > req.set_proxy(None,None) > > Where req is a urllib2.Request instance. So is there an official way of doing > this? Perhaps it should be added in the documentation? I believe that the recommended way is to use `urllib2.ProxyHandler`. Take a look at: http://www.voidspace.org.uk/python/articles/urllib2.shtml HTH, Rob From vinay_sajip at yahoo.co.uk Tue Jan 8 04:08:08 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 8 Jan 2008 01:08:08 -0800 (PST) Subject: Passing contextual information when logging Message-ID: Some users of the logging package have raised an issue regarding the difficulty of passing additional contextual information when logging. For example, the developer of a networked application may want to log, in addition to specifics related to to the network service being provided, information about the IP address of the remote machine and the username of the person logged into and using the service. Python 2.4 introduced an 'extra' keyword argument which was intended to hold a dict-like object containing additional information to be added to a LogRecord. The additional information would then be printed via placeholders in a format string. While this works, it is a little unwieldy to use in practice, because users need to provide the 'extra' parameter in every logging call. This has led people in some instances to create context-specific Logger instances (e.g. one logger for every connection). This has a drawback in that a logger name can only provide limited contextual information, and moreover, if the number of connections is effectively unbounded over time, the number of Logger instances will also grow in an unbounded way. (Logger instances are never garbage collected, because references to them are always held in the logging package. This alleviates a burden on users in that they never have to pass loggers around, but means that creating a lot of Logger instances will lead to a long-lived memory burden.) One solution is to create a generic wrapper around loggers to which a logger name and contextual information can be passed. The wrapper would delegate logging calls to the logger with the specified name, but would manipulate the arguments passed to the logging call to insert the contextual information. I have created such a wrapper class, called LoggerAdapter, which is in the example script located at http://dpaste.com/30230/ I would welcome your views on whether the LoggerAdapter class is suitable for adding to the logging package in Python 2.6/3.0. Does it do what might reasonably be expected out of the box? LoggerAdapters are, of course, garbage collected in the normal way and so impose no particular memory burden. Best regards, Vinay Sajip From phd at phd.pp.ru Thu Jan 10 07:38:10 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 10 Jan 2008 15:38:10 +0300 Subject: SQLObject 0.9.3 Message-ID: <20080110123810.GJ3070@phd.pp.ru> Hello! I'm pleased to announce the 0.9.3 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.3 News and changes: http://sqlobject.org/News.html What's New ========== Bug Fixes ~~~~~~~~~ * With PySQLite2 do not use encode()/decode() from PySQLite1 - always use base64 for BLOBs. * MySQLConnection doesn't convert query strings to unicode (but allows to pass unicode query strings if the user build ones). DB URI parameter sqlobject_encoding is no longer used. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From jr9445 at ATT.COM Mon Jan 7 12:09:50 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Mon, 7 Jan 2008 11:09:50 -0600 Subject: dictionary/hash and '1' versus 1 In-Reply-To: <13o06hleh4dkj45@corp.supernews.com> References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com><7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com><8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> <13o06hleh4dkj45@corp.supernews.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 Steven D'Aprano > Sent: Saturday, January 05, 2008 7:01 PM > To: python-list at python.org > Subject: Re: dictionary/hash and '1' versus 1 > > The problem with automatic conversions between strings and integers is > that it isn't clear what the user wants when they do something like > this: > > >>> x = '1' + 1 > > Should x be the string '11' or the int 2? Please justify your answer. > > > On the other hand, if the language includes separate operators for > addition and concatenation (say, + and &) then that sort of auto- > conversion is no longer ambiguous: > > >>> '2' + 3 > 5 > >>> '2' & 3 > '23' Bingo. Perl has specific operators to establish intent: > Perl -e "'1' + 1" > 2 > Perl -e "'1' . 1" > 11 '+' is the operator for addition '.' is the operator for string concatenation int and string comparisons also have specific operators: $a == $b # compare as integers: ==, >, <, <=, >= $a eq $b # compare as strings: eq, gt, lt, le, ge Which now morphs the conversation into the issue of how too much operator overloading creates confusion and/or ambiguity. ***** 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 pavlovevidence at gmail.com Thu Jan 24 03:01:02 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 24 Jan 2008 00:01:02 -0800 (PST) Subject: Module/package hierarchy and its separation from file structure References: Message-ID: <04ab182a-5ecd-4d1b-89c5-ac321048f6f1@x69g2000hsx.googlegroups.com> On Jan 23, 4:49 am, Peter Schuller wrote: > I do *not* want to simply break out X into org.lib.animal.x, and have > org.lib.animal import org.lib.animal.x.X as X. While this naively > solves the problem of being able to refer to X as org.lib.animal.X, > the solution is anything but consistent because the *identity* of X is > still org.lib.animal.x.X. Examples of way this breaks things: > > * X().__class__.__name__ gives unexpected results. > * Automatically generated documentation will document using the "real" > package name. > * Moving the *actual* classes around by way of this aliasing would > break things like pickled data structure as a result of the change > of actual identity, unless one *always* pre-emptively maintains > this shadow hierarchy (which is a problem in and of itself). You can reassign the class's module: from org.lib.animal.monkey import Monkey Monkey.__module__ = 'org.lib.animal' (Which, I must admit, is not a bad idea in some cases.) Carl Banks From jr9445 at ATT.COM Wed Jan 9 14:52:53 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 9 Jan 2008 13:52:53 -0600 Subject: problem of converting a list to dict In-Reply-To: References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> <962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.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 Fredrik Lundh > Sent: Wednesday, January 09, 2008 2:39 PM > To: python-list at python.org > Subject: Re: problem of converting a list to dict > > Louis.Soninhu at gmail.com wrote: > > >> to see what's going on on your machine, try printing "a" after the > >> split, but before you use it to populate the dictionary. > > > > 'print a' works > > so what does it tell you? > A bigger hint: a=i.split('=') print "'%s' splits into " % (i), a assert len(a) == 2 mydict[a[0]]=a[1] From israelu at elbit.co.il Wed Jan 16 17:47:44 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 16 Jan 2008 14:47:44 -0800 (PST) Subject: Hebrew in idle ans eclipse (Windows) Message-ID: Hi all, I'll realy appreciate your help in this: I read data from a database containg Hebrew words. When the application is run from IDLE a word looks like this, for example: \xe8\xe9\xe5 But when I run the same application from eclipse or the Windows shell I get the 'e's replaced with '8's: \x88\x89\x85 The IDLE way is the way I need, since using Hebrew words in the program text itself, as keys in a dict, for example, yield similar strings (with 'e's). When running from eclipse I get KeyError for this dict.. What do I need to do run my app like IDLE does? Thanks iu2 From tjreedy at udel.edu Mon Jan 28 23:01:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jan 2008 23:01:20 -0500 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net><60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net><7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com><13pqd16n4o3rufe@corp.supernews.com> Message-ID: "Andr?" wrote in message news:e82b9c41-935d-45c9-8d7b-6bd3fa7eaae5 at i3g2000hsf.googlegroups.com... |Here's a version that |1. does not require new syntax |2. does not *necessarily* override the "_" prefix convention 'self_' is way too bulky and intrusive. Putting '_' at the end of the word is nearly as easy to detect and conflicts with no convention I know of. tjr From lefevrol at yahoo.com Fri Jan 25 11:31:16 2008 From: lefevrol at yahoo.com (Olivier Lefevre) Date: Fri, 25 Jan 2008 17:31:16 +0100 Subject: read and readline hanging In-Reply-To: References: Message-ID: Hi Steve, Thanks for the answer. Yes this is tricky. I have done it in Java before, where you can, e.g., set up a thread to pump stuff out of both stderr and stdout continuously but my python is too rudimentary for that. There is a key difference anyway: in Java you can write while (br.readLine() != null) { } where br is the buffered reader in which you've wrapped the stdout of the child process and it will not hang. But in python eventually stdout.readline() hangs. This is a real nuisance: why can't it just return None? > 1. The subprocess has stopped producing output. Indeed, if I do this interactively, I can tell after 3 lines that I've gotten all there is to get right now and the fourth readline() call hangs. But how can I find out *programmatically* that there is no more input? > If you are only reading its standard output, are you sure that the > subprocess is flushing its buffers so you can recognize it's time to > provide more input? The subprocess in a purely passive position: it is an interpreter: I send it commands and I read the answers. The python side is in charge. > 2. The subprocess has blocked because it has filled its stderr buffer > and is waiting for something (i.e. your program) to read it. No, that's not it or it would hang immediately. I can get a few lines out of stdout and then I hang because I can't tell when it's time to stop pumping. But you are right that if there was something on stderr I would be in trouble. Regards, -- O.L. From mwm at mired.org Wed Jan 9 15:24:03 2008 From: mwm at mired.org (Mike Meyer) Date: Wed, 9 Jan 2008 15:24:03 -0500 Subject: Another dumb scope question for a closure. In-Reply-To: References: Message-ID: <20080109152403.433b113a@bhuda.mired.org> On Wed, 9 Jan 2008 13:47:30 -0500 (EST) "Steven W. Orr" wrote: > So sorry because I know I'm doing something wrong. > > 574 > cat c2.py > #! /usr/local/bin/python2.4 > > def inc(jj): > def dummy(): > jj = jj + 1 > return jj > return dummy > > h = inc(33) > print 'h() = ', h() > 575 > c2.py > h() = > Traceback (most recent call last): > File "./c2.py", line 10, in ? > print 'h() = ', h() > File "./c2.py", line 5, in dummy > jj = jj + 1 > UnboundLocalError: local variable 'jj' referenced before assignment > > I could have sworn I was allowed to do this. How do I fix it? Nope. This is one of the things that makes lisper's complain that Python doesn't have "real closures": you can't rebind names outside your own scope (except via global, which won't work here). Using a class is the canonical way to hold state. However, any of the standard hacks for working around binding issues work. For instance: >>> def inc(jj): ... def dummy(): ... box[0] = box[0] + 1 ... return box[0] ... box = [jj] ... return dummy ... >>> h = inc(33) >>> h() 34 http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From JAMoore84 at gmail.com Thu Jan 24 12:13:39 2008 From: JAMoore84 at gmail.com (JAMoore84 at gmail.com) Date: Thu, 24 Jan 2008 09:13:39 -0800 (PST) Subject: Beginner Pyserial Question References: <93223c7c-c891-424c-bc4f-00d61592663a@l32g2000hse.googlegroups.com> <13phgpma9fb3cb8@corp.supernews.com> Message-ID: <50bf1637-0954-4d35-9c16-76c3b9aabe05@y5g2000hsf.googlegroups.com> > My guess is that for whatever reason the 'first' serial port > (which is what you're asking for by specifying a 0 when > instantiating the Serial class) doesn't actually exist. Serial > device names under Windows are broken. I realize this. I tried connecting to different port "numbers", but I have not tried the serial.Serial(COM1). I wasn't sure if that worked, but I know a quick way to find out. > Try using the actual name of the com port (e.g. 'COM3' or > 'COM5') instead of 0. The com port used in Hyper Terminal is COM40. I have tried connecting to 39/40/41 to no avail. > Oh, if you end up having to use a com port higher than COM9, > that's broken in Windows as well, and you've got to sprinkle a > bunch of backslashes into the device name (I don't remember the > exact syntax). That might become an issue when I try to read COM40 for the GPS bluetooth transmission. This issue does not relate to why I cannot open smaller com ports, though. From radiosrfun at radiosrfun.com Sat Jan 12 02:01:09 2008 From: radiosrfun at radiosrfun.com (radiosrfun) Date: Sat, 12 Jan 2008 02:01:09 -0500 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> Message-ID: <478865b1$0$26840$ecde5a14@news.coretel.net> "ChairmanOfTheBored" wrote in message news:58ogo3pmecob8al6hvnb67rts0jo7j4qf1 at 4ax.com... > On Fri, 11 Jan 2008 18:25:53 -0800 (PST), thermate at india.com wrote: > >>The yank... > > > You're a goddamned retard. Go back to yanking your pathetic excuse for > a dick. American Bastards deserve to be raped? WTF? Boy - if that wasn't an admission to queerdom - I don't know what was! However - it would have to be oral - as I've heard those punks there - much by their own admission - have a milimeter peter - so in that case - they couldn't "rape" - let alone tickle - any of us "American Bastards". We "might" die - laughing our ass off though! American Bastards? Hahahahahaha............ thats funny! Come kiss this American Bastard's - ASS. You can call me an American Bastard, Prick - whatever - fact is - we're still better than you pukes will ever be. I WISH - that the President and Congress of this country would shut off ALL foreign aid. Maybe these sons of bitches would sing a different tune. We get hit by a massive hurricane - wiping out almost an entire state - we don't get a damned penny or offer of help from any one. Them dog eaters have a Tsunami, Tropical Storm - whatever fart Mother Nature gives them, we send them millions. FUCK THAT. And we have helped India - a lot. We're currently sending hundreds if not thousands of jobs there - thanks to the low life top level business people. Bring all those jobs back here - let them mother fuckers starve in poverty. From http Sun Jan 20 16:35:58 2008 From: http (Paul Rubin) Date: 20 Jan 2008 13:35:58 -0800 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> Message-ID: <7xprvwfadd.fsf@ruckus.brouhaha.com> dg.google.groups at thesamovar.net writes: > Unfortunately I realise I stated the problem imprecisely. You're only > allowed to use each number once (otherwise there's a trivial solution > for every problem, i.e. x/x + x/x + x/x + ... + x/x repeated y times > for target y given any source number x). Trying your program on 234 > from [100,9,7,6,3,1] gives you 9*9*3-9 using the 9 three times. Here is a pretty inefficient solution. It doesn't find 234 but it does find 253 twice: from operator import * def countdown(nums, ops, trace): n0 = nums[0] if len(nums) == 1: yield n0, str(n0) return for i,n in enumerate(nums[1:]): for f in ops: for r,t in countdown(nums[1:i] + nums[i+1:], [add, mul, sub], trace): if f != div or r != 0 and n0 % r == 0: yield f(n0, r), '%s(%s,%s)'% (f.__name__, n0, t) def search(nums, target): for x,t in countdown(nums, [add, mul, sub, div], []): if x == target: print x,t search([100,9,7,6,3,1], 253) From steve at holdenweb.com Thu Jan 31 13:10:26 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 13:10:26 -0500 Subject: Python for mobiles In-Reply-To: <03e0ad28-e72c-4582-8518-b5cb07d408df@e10g2000prf.googlegroups.com> References: <03e0ad28-e72c-4582-8518-b5cb07d408df@e10g2000prf.googlegroups.com> Message-ID: pavloutefkros at gmail.com wrote: > Hello, > > Is there any chance that i could compile python programs to java (.jar > [java bytecode]) so that i could run them with full support (no > interpreter) in a wireless device (talking about mobiles eg. nokia, > ericsson). > I am aware of jython, however i am not elegible of finding a proper > article claiming wheather this ability is provided or not. > > Thanks in advance! A better solution would surely be to get a Nokia S60 'phone, for which there is a native Python implementation. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From martin at v.loewis.de Wed Jan 23 04:19:28 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Jan 2008 10:19:28 +0100 Subject: python24 symbol file...pyhon24.pdb In-Reply-To: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> References: <2ipdp3pjhp408v197v1hnfo5kaf050gghf@4ax.com> Message-ID: <479706a0$0$13412$9b622d9e@news.freenet.de> > Also, is there source code available for python24 for Windoze? I have > seen reference to source code but not in a package for Windows. It's available from http://www.python.org/ftp/python/2.4/Python-2.4.tgz Regards, Martin From Lie.1296 at gmail.com Thu Jan 17 12:55:44 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 17 Jan 2008 09:55:44 -0800 (PST) Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com><20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net><87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> <87ir1wf1wi.fsf@mulj.homelinux.net> <87k5mbd8bv.fsf@benfinney.id.au> Message-ID: <95691ba1-f734-4f17-b329-29128b4c38a7@s13g2000prd.googlegroups.com> On Jan 16, 5:34?am, "Reedick, Andrew" wrote: > > >From the base definition of a constructor: constructor is the creator > > of an object. In this case, __new__ is technically the constructor > > while __init__ is an initializer. > > > However, it is also to be noted that __init__ is what makes an object > > meaningful, and that makes it a constructor in a sense (while still > > technically a constructor). Without initialization, an object is > > meaningless, even if the definition of the initializer is to leave it > > as it is. > > You don't need to have an __init__ defined. ?A subclass has to > explicitly call the parent's __init__ or the parent's __init__ is never > run. ? In other languages, constructor might be optional. In the case of non- existent constructor, compilers would add an empty constructor, but what's the difference (from programmer's POV) between Python ignoring __init__ and other languages adding empty constructor? That's just an implementation detail. > If the __init__ makes the object meaningful, then how meaningful > is an object without an __init__? ? It actually depends on the object, some objects might be pretty meaningless without being initialized (or its members altered from outside very carefully). Examples include a simple vector class. If the vector is not initialized, the x and y equals None, which is not a valid value for vector, which means the object is meaningless. > I'm pretty sure that an object > without an __init__ is still a viable, working object. I'm sure it is, although it's initial value might not be a valid value. > > If you can't be convinced with this argument, then I'd give you > > another that's a bit more Pythonic: > > DUCK TYPING: If it looks like a duck, walks like a duck, and quacks > > like a duck, it is a duck! > > But you don't need __init__ to be a duck! lol... > > >From the class programmer's point of view, __init__ acts like an > > object constructor in other languages, there is no significant > > difference between __init__ and constructor in other languages. > > How many times can you call an object's constructor in other languages? > __init__ can be called repeatedly. That's a very good argument to separate __init__ from a real constructor, but how many projects you do would require object recycling (which is the only reason I can think of for calling initializers more than once)? Object recycling should only be done on systems which lacks resources because it have big potential to introduce bugs caused by incomplete cleaning. > __init__ is the last straw that breaks the camel's back. ?Or rather, the > last method we see in the object creation process, and thus must be > 'guilty' of being a constructor. ?Only a fundamentalist would blame the > victim instead of the real criminal, __new__. It's not about blaming, rather they shared parts in the act. > We're splitting hairs. ?And I'm pretty sure that, aside from being a > spiffy thought experiment, no one cares as long as it works and makes > sense. ? =) I agree with that. From grante at visi.com Sun Jan 27 11:19:06 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 27 Jan 2008 16:19:06 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> <13pp2h2eugn8594@corp.supernews.com> <603npdF1oh17aU6@mid.uni-berlin.de> Message-ID: <13ppbnqcegh0993@corp.supernews.com> On 2008-01-27, Marc 'BlackJack' Rintsch wrote: >> I'm starting to wonder if it is possible for somebody to be >> simultaneously so self-assured and so ignorant, or if we're >> being trolled. > > I recently learned that this is called the Dunning-Kruger effect: > > The Dunning-Kruger effect is the phenomenon wherein people who have > little knowledge think that they know more than others who have much > more knowledge. > > [?] > > The phenomenon was demonstrated in a series of experiments performed by > Justin Kruger and David Dunning, then both of Cornell University. Their > results were published in the Journal of Personality and Social > Psychology in December 1999. I remember reading that paper about a year ago and it sure seemd to explain the behavior of a number of people I've known. Not only is it possible to be simultaneously self-assured and ignorant, that appears to be the normal way that the human mind works. ... must restist ... urge... to mention... Bush... Damn. -- Grant Edwards grante Yow! You can't hurt at me!! I have an ASSUMABLE visi.com MORTGAGE!! From jens at aggergren.dk Fri Jan 25 08:48:27 2008 From: jens at aggergren.dk (Jens) Date: Fri, 25 Jan 2008 05:48:27 -0800 (PST) Subject: Terse Syntax through External Methods Message-ID: Hello Everyone I'm newbie to Zope and i have a few questions regarding external methods. What i wan't to do is provide a terse syntax for converting urls to special tracking urls: turns the provided url into something like http://host/tracking?url=http%3A%2F%2Fmyurl%2F in the output. i've been trying to use a external procedure like this. ## Script (Python) "track_link" ##bind container=container ##bind context=context ##bind namespace=_ ##bind script=script ##bind subpath=traverse_subpath ##parameters=self,url ##title=track link ## return "%s%s" % (self.tracking_prefix, url_quote(url)) This doesn't work because because the method doesn't have access to the environment. Obviously I don't wan't to pass everything explicitly into the function as this would defeat the purpose of the exercise, namely to provide a terse syntax. I have a background in other languages so I might be missing something conceptually with regard Zope and DTML.. Is there a better was of doing this, perhaps without using external methods? Currently im doing the following which isn't very elegant: in content document ">link ... tracking: Appreciate any input you might have on this- From http Fri Jan 11 18:51:16 2008 From: http (Paul Rubin) Date: 11 Jan 2008 15:51:16 -0800 Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> Message-ID: <7xd4s7c45n.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > > 2. Associate a lock with the list. Anything wanting to access the > > list should acquire the lock, do its stuff, then release the lock. > > This gets confusing after a while. > > To keep it generic, how about: > > listA.op( insert, x ) > listA.op( remove, x ) Sure, there are various ways you can make the code look uniform. What gets messy is if you want to (say) operate on several lists at the same time, which means you need to hold multiple locks simultaneously, and some other thread is also trying to do the same thing. If you acquire the locks in the wrong order, you can get a situation where both threads deadlock forever. From nagle at animats.com Sat Jan 19 11:06:15 2008 From: nagle at animats.com (John Nagle) Date: Sat, 19 Jan 2008 08:06:15 -0800 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. In-Reply-To: <3b14e57b-9461-4e1c-9bde-fdde99f87617@z17g2000hsg.googlegroups.com> References: <478FAC5A.50206@animats.com> <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> <479046a5$0$36403$742ec2ed@news.sonic.net> <3b14e57b-9461-4e1c-9bde-fdde99f87617@z17g2000hsg.googlegroups.com> Message-ID: <47921ea4$0$36366$742ec2ed@news.sonic.net> Paul Boddie wrote: > Unlike your approach, pprocess employs the fork system call. Unfortunately, that's not portable. Python's "fork()" is "Availability: Macintosh, Unix." I would have preferred to use "fork()". John Nagle From nagle at animats.com Fri Jan 18 13:03:23 2008 From: nagle at animats.com (John Nagle) Date: Fri, 18 Jan 2008 10:03:23 -0800 Subject: [python] How to detect a remote webpage is accessible? (in HTTP) In-Reply-To: References: Message-ID: <4790e898$0$36384$742ec2ed@news.sonic.net> ?? wrote: > Howdy, all, > I want to use python to detect the accessibility of website. > Currently, I use urllib > to obtain the remote webpage, and see whether it fails. But the problem is that > the webpage may be very large; it takes too long time. Certainly, it > is no need to download > the entire page. Could you give me a good and fast solution? > Thank you. > -- > ShenLei If you can get through "urlopen", you've already received the HTTP headers. Just open, then use "info()" on the file descriptor to get the header info. Don't read the content at all. Setting the socket timeout will shorten the timeout when the requested domain won't respond at all. But if the remote host opens an HTTP connection, then sends nothing, the socket timeout is ineffective and you wait for a while. This is rare, but it happens. John Nagle From mail at timgolden.me.uk Wed Jan 23 06:49:58 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Jan 2008 11:49:58 +0000 Subject: wxpython In-Reply-To: <77cc3d61-5dd0-4878-b436-b6d07e40de4d@i7g2000prf.googlegroups.com> References: <77cc3d61-5dd0-4878-b436-b6d07e40de4d@i7g2000prf.googlegroups.com> Message-ID: <479729E6.4010409@timgolden.me.uk> joe jacob wrote: > I am trying to open a file containing non displayable characters like > contents an exe file. The is is with the below mentioned code: > > self.text_ctrl_1.SetValue(file_content) > > If the file_content contains non displayable characters I am getting > an error like this: > > Traceback (most recent call last): > File "C:\Documents and Settings\joe_jacob\Desktop\notepad.py", line > 102, in open_file > self.text_ctrl_1.SetValue(file_content) > File "D:\softwares\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx > \_controls.py", line 1708, in SetValue > return _controls_.TextCtrl_SetValue(*args, **kwargs) > File "D:\softwares\Python25\lib\encodings\cp1252.py", line 15, in > decode > return codecs.charmap_decode(input,errors,decoding_table) > UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position > 2: character maps to > > I am trying to create an encryption program so if I open any file even > if it is an exe file it should display in text ctrl. > > What is this problem with this ? How can I rectify this? If I may be permitted a bit of levity at your expense: you're asking how to display "non displayable" characters! The most serious answer I can give is: how do you *want* to display those characters? What do you *expect* to appear in the text control. wxPython is trying to interpret your byte stream as a Unicode text stream encoded as cp1252. But it's not, so it gives up in a heap. One solution is to pass the repr of file_content. Another solution is for you to prefilter the text, replacing non-printables by their hex value or by some marker. Not much in it, really. import random file_content = "".join ( chr (random.randint (0, 255)) for i in range (1000) ) munged_text = "".join ( c if 32 <= ord (c) <= 126 else hex (ord (c)) for c in file_content ) print repr (file_content) print munged_text TJG From arnodel at googlemail.com Thu Jan 31 17:16:39 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 31 Jan 2008 14:16:39 -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> Message-ID: <1ffed8a2-f00b-4913-802f-b2cc9fa0ab19@i12g2000prf.googlegroups.com> On Jan 31, 4:12?pm, erikcw wrote: > Hi, > > I have a list of numbers each with a +/- margin of error. ?I need to > identify which ones overlab each other. > > For example: > 55 +/- 3 > 20 +/- 2 > 17 +/- 4 > 60 +/- 3 > > #base, max, min > list = [ > (55, 58, 52), > (20, 22, 18), > (17, 21, 13), > (60, 63, 57), > ] > > In this example the range of list[0] overlaps the range of list[3] AND > list[1] overlaps list[2] > > 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. This is definitely the best way: ======================= lst = [ (55, 58, 52), (20, 22, 18), (17, 21, 13), (60, 63, 57), ] from itertools import chain def overlaps(lst): bounds = chain(*(((x[1],i), (x[2], i)) for i,x in enumerate(lst))) inside = {} for x, i in sorted(bounds): if inside.pop(i, None) is None: for j, y in inside.iteritems(): if y != x: yield i, j inside[i] = x ============================== >>> list(overlaps(lst)) [(1, 2), (3, 0)] -- Arnaud From sjmachin at lexicon.net Wed Jan 2 05:47:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 2 Jan 2008 02:47:01 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> Message-ID: On Jan 2, 8:44 pm, John Machin wrote: > (1) Try these at the Python interactive prompt: > > unicode('', 'latin1') Also use those 6 cases to check out the difference in behaviour between unicode(x, y) and x.decode(y) From patrickkidd.lists at gmail.com Fri Jan 11 00:26:07 2008 From: patrickkidd.lists at gmail.com (Patrick Stinson) Date: Thu, 10 Jan 2008 22:26:07 -0700 Subject: loading a script from text data Message-ID: <664bf2b80801102126r1cf800dan90bfe313a9e30d2c@mail.gmail.com> Is it possible to load a script from it's text data, and not from a file? I'm writing a scripting engine and need to run the scripts right from the editor. cheers! -- Patrick Kidd Stinson http://www.patrickkidd.com/ http://pkaudio.sourceforge.net/ http://pksampler.sourceforge.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From software at ginstrom.com Thu Jan 10 22:52:56 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Fri, 11 Jan 2008 12:52:56 +0900 Subject: for loop without variable In-Reply-To: References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com><87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <030401c85405$75f50260$030ba8c0@MOUSE> > On Behalf Of Marty > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) > > This caused me to wonder why Python does not have a "foreach" > statement (and also why has it not come up in this thread)? > I realize the topic has probably been beaten to death in > earlier thread(s), but does anyone have the short answer? data_out = [[] for item in data_in] Regards, Ryan Ginstrom From george.maggessy at gmail.com Tue Jan 8 01:14:36 2008 From: george.maggessy at gmail.com (George Maggessy) Date: Mon, 7 Jan 2008 22:14:36 -0800 (PST) Subject: User Group Message-ID: <41ef8ab8-6b1d-4fa0-84d3-ee29e2352222@l1g2000hsa.googlegroups.com> Hi Guys, Is there a python user group in the bay area? Cheers, George From ggpolo at gmail.com Mon Jan 7 08:45:23 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 11:45:23 -0200 Subject: Launching a wx GUI from within our python framework In-Reply-To: <0f4a1b94-9fc0-457f-81c3-b8986f5086cd@d70g2000hsb.googlegroups.com> References: <0f4a1b94-9fc0-457f-81c3-b8986f5086cd@d70g2000hsb.googlegroups.com> Message-ID: 2008/1/7, bg_ie at yahoo.com : > Hi, > > At my work we have a framework writen in python which allows us to > test our equipment. This framework is quite large and uses a Singelton > called frameworkExec which we pass around between objects in order to > share functionailty. For example, frameWorkExec stores an instance of > the BatteryManagement module which I use to set the voltage during > certain tests. > > I've just writen a gui using wx which I wish to use to calibrate our > voltage supply. I launch this app at the moment within python win as > follows - > > app = VoltageCalibrationApp(0) > app.MainLoop() > > class VoltageCalibrationApp(wx.App): > def OnInit(self): > > voltageCalibration = {} > voltageCalibration[0.0] = 1.2 > voltageCalibration[9.0] = 10.1 > voltageCalibration[22.0] = 22.7 > voltageCalibration[24.0] = 24.8 > voltageCalibration[30.0] = 31.1 > voltageCalibration[35.0] = 36.9 > > frame = VoltageCalibrationFrame(None, -1, 'Voltage Calibration', > voltageCalibration) > frame.Show(True) > frame.Centre() > return True > > I hope that by adding the code above into the framework, I will be > able to call this app as part of the framework before the execution of > certain tests, as follows - > > app = VoltageCalibrationApp(0) > app.MainLoop() > test1.run() > test2.run() > > As you can see in the VoltageCalibrationApp class, I am currently > hardcoding voltageCalibration. Rather than doing this, I wish to store > them in our singleton which is available at the scope at which I > create my VoltageCalibrationApp instance. But I can't figure our a way > of referencing my singleton with the OnInit function. Normally, you > would pass the reference via __init__ > > How can I do this? You can define the __init__ method in your wx.App subclass, something like this: class MyApp(wx.App): def __init__(self, thingYouWant, redirect=True, filename=None): self.thingyouwant = thingYouWant wx.App.__init__(self, redirect, filename) def OnInit(self): ... something that uses self.thingyouwant ... ... > > Thanks, > > Barry. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From sjmachin at lexicon.net Mon Jan 7 15:22:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 7 Jan 2008 12:22:31 -0800 (PST) Subject: Does Python cache the startup module? References: Message-ID: <3c346bb2-c84a-4268-9e7b-b0c601fe9710@s12g2000prg.googlegroups.com> On Jan 8, 6:21 am, Baz Walter wrote: > Guilherme Polo gmail.com> writes: > > > Uhm.. this didn't make much sense. If you say the module is cached, > > then supposing you did a minor edit, and then supposing because it is > > cached your application wouldn't detect the change, then I don't see > > the connection with memory leak. > > > Bring some concrete proof. > > Thanks for your reply. > > It's hard to supply an example for this, since it is local to the machine I am > using. The startup module would look something like this: > > #!/usr/local/bin/python > > if __name__ == '__main__': > > import sys > from qt import QApplication, QWidget > > application = QApplication(sys.argv) > mainwindow = QWidget() > application.setMainWidget(mainwindow) > mainwindow.show() > sys.exit(application.exec_loop()) > > If I change the name 'mainwindow' to 'mainwidget', the widget it refers to does > not get destroyed; when I change it back again, it does get destroyed. > Otherwise, the program runs completely normally. If you execute that stuff inside a function (see below) instead of in global scope, do you get the same effect? if __name__ == '__main__': import sys def main(): from qt import QApplication, QWidget application = QApplication(sys.argv) mainwindow = QWidget() application.setMainWidget(mainwindow) mainwindow.show() result = application.exec_loop()) return result sys.exit(main()) From steve at REMOVE-THIS-cybersource.com.au Sat Jan 5 03:01:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 05 Jan 2008 08:01:41 -0000 Subject: mail References: Message-ID: <13nueb5l2j44fa5@corp.supernews.com> On Fri, 04 Jan 2008 23:03:15 -0800, sanjeet wrote: > hi all, > I am facing problem to fetch mail from internet mail server. Plz help > me, how can do this? Yes. Everything you need to know to fix your problem can be found here: www.catb.org/~esr/faqs/smart-questions.html -- Steven From paddy3118 at googlemail.com Thu Jan 24 00:57:05 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 23 Jan 2008 21:57:05 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> <13pfdh31k2bp8eb@corp.supernews.com> <8f2a164c-5516-487f-802b-5651cb15b404@h11g2000prf.googlegroups.com> Message-ID: On 23 Jan, 22:39, George Sakkis wrote: > On Jan 23, 4:48 pm, Steven D'Aprano > cybersource.com.au> wrote: > > As for your other points, I think we're actually very much in agreement, > > except for your tolerance of random posters asking what I believe is an > > incoherent question: "what's the fastest way to do ...?". It seems to me > > you're willing to give them the benefit of the doubt that they've done > > their profiling and considered their trade-offs, or at the very worst are > > asking from purely intellectual curiosity. > > It depends on the specific problem and the context. For small well- > defined algorithmic type problems, I just assume it's intellectual > curiosity or that performance really matters. If the same question was > asked in the context of, say, a typical web application fetching data > from a database and rendering dynamic pages, I might have dismissed it > as YAGNI. > > George George, I tend to think that the more context an OP gives, the more thought they have given their problem. Often, to get a better answer you need to help the OP divulge context. I too like the intellectual challenge of exploring small problem, and from lurking on c.l.p I thought there would be lots of answers of that ilk, but this time I thought why not contribute in a different way? Reading c.l.p I am often reminded of good software practice memes in answers and think its part of what makes c.l.p. a rewarding experience. It may be hubris to think that a random reader might read my post and then follow my points before making a routine faster; but there you go :-) - Paddy. From robleachza at gmail.com Wed Jan 16 19:54:53 2008 From: robleachza at gmail.com (robleachza at gmail.com) Date: Wed, 16 Jan 2008 16:54:53 -0800 (PST) Subject: next line (data parsing) Message-ID: Hi there, I'm struggling to find a sensible way to process a large chuck of data--line by line, but also having the ability to move to subsequent 'next' lines within a for loop. I was hoping someone would be willing to share some insights to help point me in the right direction. This is not a file, so any file modules or methods available for files parsing wouldn't apply. I run a command on a remote host by using the pexpect (pxssh) module. I get the result back which are pages and pages of pre-formatted text. This is a pared down example (some will notice it's tivoli schedule output). ... Job Name Run Time Pri Start Time Dependencies Schedule HOST #ALL_LETTERS ( ) 00:01 10 22:00(01/16/08) LTR_CLEANUP (SITE1 LTR_DB_LETTER 00:01 10 Total 00:01 Schedule HOST #DAILY ( ) 00:44 10 18:00(01/16/08) DAILY_LTR (SITE3 RUN_LTR14_PROC 00:20 10 (SITE1 LTR14A_WRAPPER 00:06 10 SITE3#RUN_LTR14_PROC (SITE1 LTR14B_WRAPPER 00:04 10 SITE1#LTR14A_WRAPPER (SITE1 LTR14C_WRAPPER 00:03 10 SITE1#LTR14B_WRAPPER (SITE1 LTR14D_WRAPPER 00:02 10 SITE1#LTR14C_WRAPPER (SITE1 LTR14E_WRAPPER 00:01 10 SITE1#LTR14D_WRAPPER (SITE1 LTR14F_WRAPPER 00:03 10 SITE1#LTR14E_WRAPPER (SITE1 LTR14G_WRAPPER 00:03 10 SITE1#LTR14F_WRAPPER (SITE1 LTR14H_WRAPPER 00:02 10 SITE1#LTR14G_WRAPPER Total 00:44 Schedule HOST #CARDS ( ) 00:02 10 20:30(01/16/08) STR2_D (SITE7 DAILY_MEETING_FILE 00:01 10 (SITE3 BEHAVE_HALT_FILE 00:01 10 SITE7#DAILY_HOME_FILE Total 00:02 ... I can iterate over each line by setting a for loop on the data object; no problem. But basically my intension is to locate the line "Schedule HOST" and progressively move on to the 'next' line, parsing out the pieces I care about, until I then hit "Total", then I resume to the start of the for loop which locates the next "Schedule HOST". I realize this is a really basic problem, but I can't seem to articulate my intension well enough to find documentation or examples that have been helpful to me. I bought the Python cookbook yesterday which has gotten me a lot further in some areas, but still hasn't given me what I'm looking for. This is just a pet project to help me reduce some of the tedious aspects of my daily tasks, so I've been using this as means to discover Python. I appreciate any insights that would help set me in the right direction. Cheers, -Rob From fredrik at pythonware.com Sun Jan 6 08:48:36 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 06 Jan 2008 14:48:36 +0100 Subject: Killing worker threads In-Reply-To: References: Message-ID: tarun wrote: > Can anyone help me with a simple code through which the main thread can > kill the worker thread it started. it cannot. threads cannot be killed from the "outside". From deets at nospam.web.de Mon Jan 14 17:58:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 14 Jan 2008 23:58:24 +0100 Subject: Append zip files together, just get the binary data (in memory) In-Reply-To: <53f66038-ccc3-4c3d-97b2-fa5deb148809@d4g2000prg.googlegroups.com> References: <53f66038-ccc3-4c3d-97b2-fa5deb148809@d4g2000prg.googlegroups.com> Message-ID: <5v27oiF1kavhlU1@mid.uni-berlin.de> BerlinBrown schrieb: > Is it possible to just build the binary content of a zip file. I want > to create the content in memory (e.g. return binary data) and then get > those byte strings representing the zip file? Is that possible? > > Or could I possibly override functions in the zip class. > > 1. Create a zip file object (e.g. dont actually create the file). > 2. Append stuff to the zip file (e.g. a file) > 3. Zip that content into memory (but still not touching the > filesystem) > 4. Extract those byte strings for (an array?) later use. > > My goal is to concatenate multiple zip files into another binary file. Module StringIO is your friend. Diez From python.list at tim.thechases.com Fri Jan 25 08:04:01 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 25 Jan 2008 07:04:01 -0600 Subject: Minimum Requirements for Python In-Reply-To: References: Message-ID: <4799DE41.8000608@tim.thechases.com> > Can someone tell me the minimum requitements for Python as I can't > find it anwhere on the site. I have 3 PC's which are only 256mb RAM, > wanted to know if this was sufficenent. It runs just fine here on an old P133 laptop running OpenBSD with a mere 32 megs of memory. I wouldn't do numerical processing on it, or memory intensive tasks, but for most scripts, it's just fine. -tkc From musiccomposition at gmail.com Mon Jan 14 22:26:20 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 14 Jan 2008 19:26:20 -0800 (PST) Subject: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net> <5v2cudF1k5a1oU1@mid.individual.net> Message-ID: On Jan 14, 6:26 pm, Bjoern Schliessmann wrote: > John Nagle wrote: > > It turns out that the strings in the "env" parameter have to be > > ASCII, not Unicode, even though Windows fully supports Unicode in > > CreateProcess. > > Are you sure it supports Unicode, not UTF8 or UTF16? Probably using > something like u"thestring".encode("utf16") will help. Otherwise: bugs.python.org > > Regards, > > Bj?rn > > -- > BOFH excuse #31: > > cellular telephone interference From python at rcn.com Fri Jan 25 23:16:50 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 25 Jan 2008 20:16:50 -0800 (PST) Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> Message-ID: <1d73c5f5-2c9d-4c46-9205-289a5462fabb@v46g2000hsv.googlegroups.com> On Jan 25, 1:47?pm, Hexamorph wrote: > Henry Baxter wrote: > > Oops, gmail has keyboard shortcuts apparently, to continue: > > > def maxi(l): > > ? ? m = max(l) > > ? ? for i, v in enumerate(l): > > ? ? ? ? if m == v: > > ? ? ? ? ? ? return i > > What's about l.index(max(l)) ? from itertools import izip, count answer = max(izip(l, count()))[1] Raymond From bearophileHUGS at lycos.com Sun Jan 6 13:03:34 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 6 Jan 2008 10:03:34 -0800 (PST) Subject: Point Object References: <4673edc3-b76c-4c6e-98f0-4f2becee930e@j20g2000hsi.googlegroups.com> Message-ID: Pete: > Translate the hexadecimal form > into decimal and confirm that they match. No need to convert the IDs... Soviut: > You shouldn't have to compare the hex IDs. Just a simple comparison > operator will work: > > firstPoint = Point() > secondPoint = Point() > print(firstPoint == secondPoint) > > result: True Remember about __eq__ and "is": class Foo: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x f1 = Foo(1) f2 = Foo(2) f3 = Foo(2) f4 = f3 print f1 == f2, f1 is f2 # False False print f2 == f3, f2 is f3 # True False print f3 == f4, f3 is f4 # True True Bye, bearophile From sour.craig at gmail.com Fri Jan 11 11:21:18 2008 From: sour.craig at gmail.com (Craig Ward) Date: Fri, 11 Jan 2008 11:21:18 -0500 Subject: newbie question regarding int(input(:)) Message-ID: <275866c0801110821r46ac1174wea4c1ddad22b9d1d@mail.gmail.com> Hi experts! I am trying to write a menu script that will execute bash scripts. Everything is fine until the script executes and I want to see if there are any more options to run before quitting. Example: def menu(opt1 = "something", opt2 = "something else"): -- Computers are like air conditioners. They stop working when you open Windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From toby at tobiah.org Tue Jan 29 14:48:38 2008 From: toby at tobiah.org (Tobiah) Date: Tue, 29 Jan 2008 11:48:38 -0800 Subject: Removing Pubic Hair Methods In-Reply-To: References: Message-ID: <479f7759$0$25985$88260bb3@free.teranews.com> class genital: def pubic_hair(self): pass def remove(self): del(self.pubic_hair) "Removing pubic hair methods" xikom01 at yahoo.com.tw wrote: > Shaving is the most common removing pubic hair method. However, it is > not the only one. > > After you have decided you want to remove your pubic hair, you will > have to examine the different methods for removing pubic hair and > decide which one is the best for you. > > The following lines include a brief glance of the existing pubic hair > removal methods: > > 1. Shaving - razor shaving is the most popular removing pubic hair > method. One should shave his pubic hair area carefully and gently > using a proper razor and shaving cream. Make sure you wash and clean > your pubic hair area before and after the shave. > > 2. Hair removal creams - those can cause lots of pain and allergic > reactions. However, they are very effective in removing pubic hair. We > suggest you test in on a harmless spot like your back or the inside of > your elbow to check for possible allergic reactions. If your skin gets > red or itchy for a long period of time (more than 3 hours) do use it. > Again, wash you pubic hair area carefully after using this removing > pubic hair method. > > 3. Waxing - We strongly suggest avoiding using wax for removing pubic > hair. Most of the women can not stand the pain and the outcome is as > good as the other removing pubic hair methods. > > 4. Electrolysis - A permanent pubic hair removing methods using > electric shocks. It can be done in a hair salon or at home after > purchasing a personal device. This method is very expensive (It may > cost more than a thousand dollars). It also painful in most cases but > this method provides a permanent pubic hair removal. > > 5. Pulling - We got to know in our research quite a few women who > prefer pull their pubic hair out. It takes time, Its painful but it > involves a satisfaction. > > Now you can make the proper decision on the best removing pubic hair > method for you. Good luck. > > > http://www.dontplayplay.com/html/Bothsexes/20061002/47329.html > -- Posted via a free Usenet account from http://www.teranews.com From steve at holdenweb.com Wed Jan 30 21:51:53 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Jan 2008 21:51:53 -0500 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <13q2960err4db28@corp.supernews.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> <13q2960err4db28@corp.supernews.com> Message-ID: <47A137C9.507@holdenweb.com> Grant Edwards wrote: > On 2008-01-31, Daniel Fetchinson wrote: >>> I do not understand why no one has answered the following question: >>> >>> Has anybody worked with Gene Expression Programming???? >> Hmmmmm, maybe because nobody did? Just a thought. It can also be that >> everyone worked with it but everyone is part of a big conspiracy not >> to answer any of your emails just to make you act weird. > > That's it then, now we're going to have to kill you... > Look guys, I thought we'd agreed that the PSU was no longer to be From robert.kern at gmail.com Tue Jan 29 14:44:33 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 29 Jan 2008 13:44:33 -0600 Subject: Module/package hierarchy and its separation from file structure In-Reply-To: <0a285e6e-a3a9-4be9-ae59-4cb7547ffa3a@q21g2000hsa.googlegroups.com> References: <874pd49qjl.fsf@benfinney.id.au> <0a285e6e-a3a9-4be9-ae59-4cb7547ffa3a@q21g2000hsa.googlegroups.com> Message-ID: Carl Banks wrote: > On Jan 29, 7:48 am, Peter Schuller > wrote: >>> You can also put, in animal/__init__.py: >>> from monkey import Monkey >>> and now you can refer to it as org.lib.animal.Monkey, but keep the >>> implementation of Monkey class and all related stuff into >>> .../animal/monkey.py >> The problem is that we are now back to the identity problem. The class >> won't actually *BE* org.lib.animal.Monkey. > > The usage is the same; it works in all cases once you redefine > __module__. Who cares what it really is? The inspect module. [animals]$ ls animals [animals]$ rm animals/*.pyc [animals]$ ls animals [animals]$ ls animals __init__.py monkey.py [animals]$ cat animals/monkey.py class Monkey(object): pass [animals]$ cat animals/__init__.py from animals.monkey import Monkey Monkey.__module__ = 'animals' [animals]$ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from animals import Monkey >>> import inspect >>> inspect.getsource(Monkey) Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/inspect.py", line 629, in getsource lines, lnum = getsourcelines(object) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/inspect.py", line 618, in getsourcelines lines, lnum = findsource(object) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/inspect.py", line 494, in findsource raise IOError('could not find class definition') IOError: could not find class definition >>> -- 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 lists at cheimes.de Wed Jan 23 14:32:54 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 23 Jan 2008 20:32:54 +0100 Subject: math and numerical fixes (was: When is min(a, b) != min(b, a)?) In-Reply-To: References: Message-ID: <47979666.2020900@cheimes.de> Jason wrote: > Please note that NaN's are very funky and platform dependent. They > depend on their underlying platform's C library for creation and > display. On windows, "float('nan')" will cause an exception, as there > are no valid string representations of NAN that can be converted to > the special floating point value. Also, if you manage to create a nan > under Windows, it displays as "1.#QNAN". > > Infinite values are also problematic. In almost all cases, it is far > better to avoid infinite and NaN values. CC to Python Dev I've fixed that and enhanced the support for NaN and inf for 2.6 and 3.0. I'm working together with Mark on more NaN and inf related fixes and he has fixed some numerical issues in the cmath module. We both hope to get Python's math more sound and stable across platforms. So far I got float('nan'), float('inf') and float('-inf') working on all platforms. The math module got three new methods: isinf, isnan, copysign. Additionally the trunk-math branch contains code for inverse hyberbolic functions (acosh), log1p, Mark's fixes for complex math and more stuff. For example operations on NaNs now return a NaN on all platforms (except 1**NAN which is defined as 1 and 0**NAN which is defined as 0). In 2.5 it depends on the platform whether a function raises an exception or returns NaN. Mark had the nice idea to introduce a thread local or global flag for NaN support. Depending on a flag Python turns a NaN into an exception. The feature needs a proper PEP. Maybe Mark has time to write a PEP in time. Christian From bearophileHUGS at lycos.com Sat Jan 5 17:59:33 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 5 Jan 2008 14:59:33 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: Sion Arrowsmith: > Because ... how to be polite about this? No, I can't. std::set is > crap. The implementation is a sorted sequence What about using hash_map instead? You can use it with GCC too (but you have to use a trick if you want to use string keys). Bye, bearophile From rtw at freenet.co.uk Wed Jan 2 14:07:00 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Wed, 02 Jan 2008 13:07:00 -0600 Subject: Extracting files from an ISO image? References: <34a84caa-5387-40a2-a808-5e7bd325023e@w47g2000hsa.googlegroups.com> Message-ID: Ant wrote in news:34a84caa-5387-40a2-a808- 5e7bd325023e at w47g2000hsa.googlegroups.com in comp.lang.python: [snip] > > So I have two questions really: > > 1) Is there a module out there for extracting files from an ISO? There are command line programs that can do this: http://cdrecord.berlios.de/old/private/cdrecord.html This (with isoinfo.exe from the above) will list all files in an iso image file: CD = import subprocess subprocess.call( [ "isoinfo.exe", '-f', '-i', CD ] ) isoinfo.exe also has a switch to extract a file to stdout One problem you may have is daemon tools will mount cd images that aren't iso images, where as isoinfo appears to handle only genuine iso file systems. Rob. -- http://www.victim-prime.dsl.pipex.com/ From dannox at gmail.com Thu Jan 10 16:14:40 2008 From: dannox at gmail.com (whatazor) Date: Thu, 10 Jan 2008 13:14:40 -0800 (PST) Subject: outgoing traffic monitor Message-ID: <409e811c-ca36-4273-b407-32ec364af5ed@k39g2000hsf.googlegroups.com> Hi all, I have thread that call a module which upload a file in a remote repository. A possible approach to calculate the time is tomonitor outgoing traffic of that thread. How can I do in python. There are modules usefull for this kind of requests? thank you all, bye w From tjreedy at udel.edu Thu Jan 24 17:34:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jan 2008 17:34:05 -0500 Subject: Increment Variable Name References: <9e9714f6-24d8-46fe-908f-205d223574cd@p69g2000hsa.googlegroups.com> Message-ID: "Paul Hankin" wrote in message news:fdff5a3c-376c-41da-bc7c-| > Do you want to do this?: | > locals()['var'+str(1)] = "spam" | | As I recently learnt in this newsgroup, that's not guaranteed to work. | >From http://docs.python.org/lib/built-in-funcs.html | | Warning: The contents of this dictionary should not be modified; | changes may not affect the values of local variables used by the | interpreter. It currently works at module level, where locals() is globals(). But then, one might as well write globals()['var'+str(1)] = "spam". But in Python, one is almost certainly better to use a collection object than this idiom (indefinite multiple numbered variables) imported from languages which do not have them. From lists at cheimes.de Fri Jan 25 09:28:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 25 Jan 2008 15:28:10 +0100 Subject: del self? In-Reply-To: References: Message-ID: Simon Pickles wrote: > Hi, > > Just curious... What are the implications of a class member calling: > > del self A method like def spam(self): del self just removes self from the local namespace of the spam function and thus results in decreasing the reference count of self by one. A class ordinary doesn't implement a __del__ function. The C implementation of classes use different methods to remove a class from memory (tp_dealloc, tp_clear and more). Christian From tjreedy at udel.edu Sat Jan 26 22:34:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jan 2008 22:34:47 -0500 Subject: Operator overloading References: <1d7c86bc-7c74-468e-9a9b-fda1d2fd0740@m34g2000hsf.googlegroups.com><5vuob3F1nd2bhU1@mid.uni-berlin.de><2be68fc0-1188-4c21-aa79-a04dd8da5767@e25g2000prg.googlegroups.com> Message-ID: | > > Sure. Cosines are a monadic operation and the monadic '+' is a NOP, so | > > why shouldn't I define +45 to return cosine of 45, (presuming I needed | > > lots of cosines). I'd even let you define your own operators. Lots of | > > programmers really liked '++' and '--', for examples. One cannot change builtin types. One can subclass most of them and override most if not all the special methods. import math as m class trigint(int): def __pos__(self): return m.cos(m.pi*self/180.0) print +trigint(45) >>> 0.707106781187 Of course, for this case, def cosi(degrees): return m.pi*degrees/180.0 would probably be more sensible. There is and is no prospect of being able to add operators. Terry Jan Reedy From mr.cerutti at gmail.com Thu Jan 24 08:58:00 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 24 Jan 2008 08:58:00 -0500 Subject: Test driven development In-Reply-To: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> Message-ID: <51302a8c0801240558n7eb8d09at9df65163e6592393@mail.gmail.com> On 1/24/08, ajcppmod at gmail.com wrote: > Hi > > Sorry if this is a bit off topic but as unit testing is such a > cornerstone of python development I thought a few of you may be able > to share your knowledge/experiences. Test driven development, simplistically, means to write the tests before you write the code. > I like the concept of TDD but find it difficult to put into practice > most of the time. I think this primarily because I tend to like top- > down development and functional/object decomposition and TDD feels > more like a bottom-up approach. It should work with any unit of development, although it can be hard to usefully test high-level functionality that depends on currently unimplemented underware. > So my question is when approaching a project that you want to employ > test driven development on how and where do you start? And also if > anyone uses top-down design with TDD I would be interested in how you > do it (does it involve lots of mock objects/ is the first test you > write the last one to pass)? The system I've adopted is to use inline doctests for the simplest, tutorial-like examples, with "outline" unit tests composd to verify implementation details and to probe bounderies. Typically, I write a doctest, then the routine, and finally the unit tests. Top-down should work fine with test-driven, although your highest level tests will fail until your low-level tests pass. All the failing tests might be kind of depressing, though. Personally, I haven't really given top-down a fair shake, so I don't know which approach reveals my stupid design mistakes faster. -- Neil Cerutti From nodrogbrown at gmail.com Sat Jan 26 02:21:52 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Fri, 25 Jan 2008 23:21:52 -0800 (PST) Subject: getting values from cache Message-ID: <480b367b-e5c4-4018-a968-8c146555dbdd@v29g2000hsf.googlegroups.com> hi i am writing code to check a folder containing images and then process thir vals using PIL and do some calc to create a matrix of values .if the folder has any new imgs added the program will do all calc again and dump the values into a cachefile.If the folder contents remain unaltered the program should not do calc but load the vals from cachefile..it is assumed that malicious alterations are not made on the folder and so i wont be doing any thorogh check but just checking if contents of folder have changed..i do something like this def checkCache(self): filenameslist=getfilenameslist() # made by parsing folder before this try: f=open(cachefile) except IOError: #no cache found ,do all calc mynumpymatrix1,imgwdth,imght=docalculations() f2=open(cachefile,"w") #dump values as tuple pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f2) f2.close() else: #cache exists, need to check if folder contents changed oldfilenameslist,wd,ht, mynumpymatrix1=pickle.load(f) f.close() if(filenamelist==oldfilelist): #if oldfilenamelst same,it means folder hasn't changed #use the vals from cache..... else: #folder changed mynumpymatrix1,imgwdth,imght=docalculations() f3=open(cachefile,"w") pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f3) f3.close() this works and does what i need in my code..but i want to know if a more elegant solution is possible i am not worried about someone deliberately renaming files like aaaa.jpeg to aaa.jped and a.jpeg to deceive the checking since it is assumed that noone has permission to modify the folder except a trusted admin/code will be grateful for your suggestions tia From bborcic at gmail.com Fri Jan 25 06:25:03 2008 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 25 Jan 2008 12:25:03 +0100 Subject: sudoku solver in Python ... In-Reply-To: References: <43b2a56b-c8eb-4851-a9f6-10aa7e32e3ce@i29g2000prf.googlegroups.com> <222A1E46-A1C1-4793-A91E-9E0785463278@gmail.com> Message-ID: <4799c740$1_4@news.bluewin.ch> >> http://norvig.com/sudoku.html (...) > Below is the "winner" of my hacking for an as fast as > possible 110% pure python (no imports at all!) comprehensive sudoku > solver under 50 LOCs, back in 2006. Performance is comparable to the > solver you advertize - numbers are slightly better, but platform > differences could easily absorb that - More precise comparisons, after noting that on Norvig's pages there were contradictory performance numbers (obviously some 0 inserted or deleted). Running on my machine on the "top95" list of hard problems given on Norvig's page, my code takes about 7.5 ms/problem while Norvig's takes 42 ms/problem. So that's a 82% reduction of running time. Psyco.full() reduces the running time of my code to just about 4 ms/problem while it grows Norvig's to 47 ms/problem. BB > eg (not counting module > initialization and not using psyco) it takes 9.3 ms average on the "AI > escargot" problem linked to in Norvig's page, 5.6 ms/problem on some > standard "top1465" list of hard problems, and 3.4 ms/problem on the > first 1000 on some other "top50000" list of relatively hard problems. > This on my 2GHz Intel Centrino '05 laptop. Psyco reduces times by about > 50%. Dropping performance requirements by half allows reducing LOC count > in proportion. > > OTOH, the code although short is nearly unreadable, sorry; should > probably feature/comment it on some web page, like the two already > proposed in the thread. Will do if/for reviewer. Interface is calling > sudoku99(problem) with 'problem' a standard 81 character string with '0' > or '.' placeholder for unknowns. Returns same with values filled in. > > Beware that although in practice it solved all well-formed > human-solvable problems I could find, it is not guaranteed to deal > properly (or even terminate?) for underdetermined problems or determined > problems that would require exploring choicepoints with more than 2 > possibilities (if such exist). > > Cheers, Boris > > > > w2q = [[n/9,n/81*9+n%9+243,n%81+162,n%9*9+n/243*3+n/27%3+81] > for n in range(729)] > q2w = (z[1] for z in sorted((x,y) for y,s in enumerate(w2q) for x in s)) > q2w = map(set,zip(*9*[q2w])) > w2q2w = [set(w for q in qL for w in q2w[q] if w!=w0) for w0,qL in > enumerate(w2q)] > empty = set(range(729)).copy > > def sudoku99(problem) : > givens = set(9*j+int(k)-1 for j,k in enumerate(problem) if '0' ws=search(givens,[9]*len(q2w),empty()) > return ''.join(str(w%9+1) for w in sorted(ws)) > > def search(w0s,q2nw,free) : > while 1 : > while w0s: > w0 = w0s.pop() > for q in w2q[w0] : q2nw[q]=100 > wz = w2q2w[w0]&free > free-=wz > for w in wz : > for q in w2q[w] : > n = q2nw[q] = q2nw[q]-1 > if n<2 : > ww,=q2w[q]&free > w0s.add(ww) > if len(free)==81 : return free > thres = int((len(free)+52.85)/27.5) > ix,vmax = -1,0 > try : > while 1 : > ix=q2nw.index(2,ix+1) > for w0 in (q2w[ix]&free)-w0s : > v = len(w2q2w[w0]&free) > if v > vmax : > ixmax = ix > if v >=thres : break > vmax = v > w0s.add(w0) > else : continue > break > except : pass > w0,w1 = q2w[ixmax]&free > try : > w0s.clear() > w0s.add(w0) > return search(w0s,q2nw[:],free.copy()) > except ValueError : > w0s.clear() > w0s.add(w1) > From bj_666 at gmx.net Sun Jan 13 02:59:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Jan 2008 07:59:45 GMT Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> Message-ID: <5utunhF1jl8liU1@mid.uni-berlin.de> On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: > However, I am very surprised to learn that > > super_object.__getattr__(name)(*args, **kwargs) > > getattr(super_object, name)(*args, **kwargs) > > are not equivalent. This is quite odd, at least when with len() > and .__len__, str() and .__str__. Do you maybe know what's the > rationale behind not following that convention by getattr? I think you are confusing `__getattr__` and `__getattribute__` here! `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's different. Ciao, Marc 'BlackJack' Rintsch From info at thegrantinstitute.com Tue Jan 22 18:45:21 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 22 Jan 2008 15:45:21 -0800 Subject: Professional Grant Proposal Writing Workshop (April 2008: Vancouver, British Columbia) Message-ID: <20080122154521.4978BC0DD8845659@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From cokofreedom at gmail.com Thu Jan 17 09:42:42 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 17 Jan 2008 06:42:42 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> Message-ID: <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> On Jan 17, 2:52 pm, Chris wrote: > On Jan 17, 2:35 pm, cokofree... at gmail.com wrote: > > > > > On Jan 17, 1:21 pm, Sacred Heart wrote: > > > > Hi, > > > I'm new to Python and have come across a problem I don't know how to > > > solve, enter com.lang.python :) > > > > I'm writing some small apps to learn the language, and I like it a lot > > > so far. > > > > My problem I've stumbled upon is that I don't know how to do what I > > > want. I want to do a loop in a loop. I think. > > > > I've got two arrays with some random stuff in, like this. > > > > array1 = ['one','two','three','four'] > > > array2 = ['a','b','c','d'] > > > > I want to loop through array1 and add elements from array2 at the end, > > > so it looks like this: > > > > one a > > > two b > > > three c > > > four c > > > > I'm stuck. I know how to loop through the arrays separatly and print > > > them, but both at the same time? Hmmm. > > > > A push in the right direction, anyone? > > > > R, > > > SH > > > for i in zip(array1, array2): > > print i > > > Although I take it you meant four d, the issue with this method is > > that once you hit the end of one array the rest of the other one is > > ignored. > > You could always pre-pad the lists you are using before using the zip > function, kinda like > > def pad(*iterables): > max_length = 0 > for each_iterable in iterables: > if len(each_iterable) > max_length: max_length = > len(each_iterable) > for each_iterable in iterables: > each_iterable.extend([None for i in xrange(0,max_length- > len(each_iterable))]) > > pad(array1, array2, array3) > for i in zip(array1, array2, array3): > print i > > What you could also do is create an index to use for it. > > for i in xrange(0, length_of_longest_list): > try: print array1[i] > except IndexError: pass > try: print array2[i] > except IndexError: pass couldn't you just do something like if len(array1) is not len(array2): if len(array1) < len(array2): max_length = len(array2) - len(array1) array1.extend([None for i in xrange(0, max_length)]) elif len(array1) > len(array2): max_length = len(array1) - len(array2) array2.extend([None for i in xrange(0, max_length)]) for i in zip(array1, array2): print i Though my case only really works for these two, whereas yours can be used on more than two lists. :) From lists at cheimes.de Fri Jan 25 09:29:06 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 25 Jan 2008 15:29:06 +0100 Subject: psyco on mac In-Reply-To: <266557d0801181710p5eb54420h79def10af5135985@mail.gmail.com> References: <266557d0801181710p5eb54420h79def10af5135985@mail.gmail.com> Message-ID: Arash Arfaee wrote: > Hello, > > I have problem installing psyco on my mac. Can anybody help me? Psyco doesn't work on a PowerPC Mac. It requires a i4986 compatible CPU (aka x86 or IA32). Christian From stefan.behnel-n05pAM at web.de Wed Jan 23 10:19:37 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 16:19:37 +0100 Subject: Lxml on mac In-Reply-To: References: Message-ID: <47975B09.8090705@web.de> marcroy.olsen at gmail.com wrote: > What to one do if one what to use lxml(http://codespeak.net/lxml/ > index.html) on a mac? Have you tried installing up-to-date versions of libxml2/libxslt and running easy_install lxml ? Stefan From fredrik at pythonware.com Wed Jan 9 05:02:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 11:02:52 +0100 Subject: Open a List of Files In-Reply-To: <4f67337a-14ea-4552-8a5a-6de9703e58ff@d70g2000hsb.googlegroups.com> References: <874pdomrrd.fsf@mulj.homelinux.net> <4f67337a-14ea-4552-8a5a-6de9703e58ff@d70g2000hsb.googlegroups.com> Message-ID: Paul Hankin wrote: > This can be more cleanly written using locals() > > for fn in filenames: > locals()[fn] = open(os.path.join(host_path, fname + '.txt', 'wb') from the reference manual: locals() Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. examples: >>> def foo(): ... locals()["foo"] = 1 ... print foo ... >>> foo() >>> def foo(): ... foo = 1 ... locals()["foo"] = 2 ... print foo ... >>> foo() 1 From cptnwillard at gmail.com Fri Jan 18 14:01:29 2008 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Fri, 18 Jan 2008 11:01:29 -0800 (PST) Subject: Is this a bug, or is it me? References: <87myr4o3sg.fsf@mulj.homelinux.net> Message-ID: <8afa3779-6803-43ed-ae4d-d0a102eda00d@x69g2000hsx.googlegroups.com> I filed a bug report, and here is the short answer to my question: genexps are code blocks, and code blocks cannot see variables in class scopes. Congrats to Neil Cerutti who figured it out. Now here is another one for your enjoyment: class C: @staticmethod def f1(): pass F = { '1' : f1 } C().F['1']() >>> TypeError: 'staticmethod' object is not callable What do you think of this one? From iclark at mail.ewu.edu Wed Jan 16 11:12:42 2008 From: iclark at mail.ewu.edu (Ian Clark) Date: Wed, 16 Jan 2008 16:12:42 +0000 (UTC) Subject: error/warning color customization in interactive console? References: Message-ID: On 2008-01-16, yhvh wrote: > Is it possible to output error messages in a different color? > I'm using Terminal on Gnome. >>> print "\033[1;31mHello\033[0m There!" Some reading: http://en.wikipedia.org/wiki/ANSI_escape_code http://www.ioncannon.net/ruby/101/fun-with-ansi-escape-codes/ Also, you might look at sys.excepthook to colorize an uncaught exception, and PYTHONSTARTUP to load code automagically before an interactive session. Ian From jr9445 at ATT.COM Fri Jan 11 10:51:01 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 11 Jan 2008 09:51:01 -0600 Subject: python recursive function 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 Tom_chicollegeboy > Sent: Friday, January 11, 2008 3:30 AM > To: python-list at python.org > Subject: python recursive function > > Now, you are to write a program that, if I give you n bears, returns > true if it is at all possible for you to win the game. Your program > must use recursion to check all possible ways in which you can apply > the rules. > > if n==42: > return True > return False You have to check for all possible paths. Returning True/False is futile since the recursive chains will be returning a mix of true and false. Use a global variable to indicate if a solution is found. (Or pass the flag in using a list, since lists are passed by reference (if n == 42: found_it[0] = True; return.) There's also another teaching exercise in here. Do you follow the literal directions ('check all possible ways') and generate all possible paths? Or do you 'interpret' that to mean try all possible paths until you find a solution? (i.e. do you short circuit the recursion once you have a solution?) One of the most difficult things about programming is conveying the requirements from Human A to Human Programmer B. This is especially difficult since business people and techies speak different languages and, more importantly, think differently (different assumptions, different paradigms, different levels of hand-waving away of details, etc..) And don't get me started about the people in marketing... ***** 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 gnewsg at gmail.com Sat Jan 12 11:49:37 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 12 Jan 2008 08:49:37 -0800 (PST) Subject: How to get user home directory on Windows References: Message-ID: <0bb27916-5416-47b2-b58c-1eb82ccb6d3e@k2g2000hse.googlegroups.com> On 12 Gen, 17:44, Christian Heimes wrote: > Giampaolo Rodola' wrote: > > Is there a way to do that? > > home = os.path.expanduser("~") > > Christian That gives the home of the *current logged in user*. I need another thing. From stefan.behnel-n05pAM at web.de Wed Jan 23 11:49:44 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 17:49:44 +0100 Subject: Processing XML that's embedded in HTML In-Reply-To: References: <6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> <47972624.2050002@web.de> Message-ID: <47977028.3070106@web.de> Mike Driscoll wrote: > Both the normal parser example and the objectify example you gave me > give a traceback as follows: > > Traceback (most recent call last): > File "\\clippy\xml_parser2.py", line 70, in -toplevel- > for row in tree.iterfind("//Row"): > AttributeError: 'etree._ElementTree' object has no attribute > 'iterfind' > > > Is there some kind of newer version of lxml? Yep, lxml 2.0. It's currently in beta, but that doesn't say much. http://codespeak.net/lxml/dev/ Stefan From cokofreedom at gmail.com Wed Jan 9 08:08:03 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jan 2008 05:08:03 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> <2a90b41a-2e82-465a-8b97-50ead52dca5b@x69g2000hsx.googlegroups.com> Message-ID: <84bd2cda-30d7-44a8-bff2-3efaccf6fa08@e10g2000prf.googlegroups.com> Designed a pretty basic way that is "acceptable" on small strings. evenOrOdd = True s1 = "hi_cat_bye_dog_foo_bar_red" s2 = "" for i in s1: if i == '_': if evenOrOdd: s2 += ':' evenOrOdd = not evenOrOdd else: s2 += ',' evenOrOdd = not evenOrOdd else: s2 += i print s2 From martin at v.loewis.de Thu Jan 17 00:21:03 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 Jan 2008 06:21:03 +0100 Subject: Creating unique combinations from lists In-Reply-To: References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> <13osvl1j4pvka15@corp.supernews.com> <001640bd-7759-423b-ad74-275b27e5d5d6@v4g2000hsf.googlegroups.com> Message-ID: <478EE5BF.7020008@v.loewis.de> > The main emphasis was to show that there was a pattern unfolding that > should have been translated into more pythonic code than just > hard-coding nested loops. Practicality beats purity. That you would solve a more general problem in a more general way doesn't mean that you shouldn't solve the more specific problem (combinations from three sets) in a specific, easy-to-read way. Readability counts. I find your solution (with nested generators) *very* unpythonic. It is much more complicated than necessary to solve the problem at hand, and it doesn't get Pythonic just by using the latest language features. It may be a smart solution, but not a Pythonic one. Regards, Martin P.S. To solve the general problem, I like http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496807 From deets at nospam.web.de Tue Jan 15 06:03:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 Jan 2008 12:03:25 +0100 Subject: common problem - elegant solution sought References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <5v3i7tF1jvujbU1@mid.uni-berlin.de> Helmut Jarausch wrote: > Hi, > > I'm looking for an elegant solution of the following tiny but common > problem. > > I have a list of tuples (Unique_ID,Date) both of which are strings. > I want to delete the tuple (element) with a given Unique_ID, but > I don't known the corresponding Date. > > My straight forward solution is a bit lengthy, e.g. > > L=[("a","070501"),("b","080115"),("c","071231")] > pos=-1 > found=-1 > for (Key,Date) in L : > pos+= 1 > if Key == "b" : > found= pos > break > > if found >= 0 : > del L[found] > > print L > > Most probably there are much more elegant solutions. > Unfortunately, the index-list-method doesn't take an > additional function argument for the comparisons. > > Many thanks for your hints, Several solutions: - use a different datastructure, as others suggested - use a database. SQLite for example. - replace the list in-place like this: L[:] = [(k, d) for k, d in L if k != "b"] Diez From israelu at elbit.co.il Wed Jan 23 14:44:39 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 23 Jan 2008 11:44:39 -0800 (PST) Subject: Hebrew in idle ans eclipse (Windows) References: <478ee0c0$0$4589$9b622d9e@news.freenet.de> <86ea4c94-f4b3-4bc3-9b2a-bc9b5c182264@i12g2000prf.googlegroups.com> <478FBC1A.4080201@v.loewis.de> <47970642$0$13412$9b622d9e@news.freenet.de> Message-ID: <5831f555-f445-4cb5-9796-56b6df12c7f8@e10g2000prf.googlegroups.com> On Jan 23, 11:17 am, "Martin v. L?wis" wrote: > If you are claimaing that the program > > Apparently, they do the OEMtoANSI conversion when you run a console > application (i.e. python.exe), whereas they don't convert when running > a GUI application (pythonw.exe). > > I'm not quite sure how they find out whether the program is a console > application or not; the easiest thing to do might be to turn the > autoconversion off on the server. > > Regards, > Martin True! It's amazing, I've just written a little code that reads from the database and writes the data to a file. Then I ran the code with both python.exe and pythonw.exe and got the two kinds of results - the IDLE one and the eclipse one! From lepto.python at gmail.com Sun Jan 20 22:21:40 2008 From: lepto.python at gmail.com (oyster) Date: Mon, 21 Jan 2008 11:21:40 +0800 Subject: problem with 'global' Message-ID: <6a4f17690801201921v38a83770qcdceb9ec051a3c73@mail.gmail.com> why the following 2 prg give different results? a.py is ok, but b.py is 'undefiend a' I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 #a.py def run(): if 1==2: # note, it always False global a a=1 run() a #b.py def run(): a=1 run() a From kirby.urner at gmail.com Thu Jan 10 13:29:30 2008 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: Thu, 10 Jan 2008 10:29:30 -0800 (PST) Subject: Collecting Rich Data Structures for students References: <8b4e7954-b666-4515-9ae2-821d979ebd7f@m34g2000hsf.googlegroups.com> <13obk7gpdug6f5d@corp.supernews.com> Message-ID: On Jan 10, 1:01 am, Dennis Lee Bieber wrote: > On Wed, 9 Jan 2008 15:05:25 -0800 (PST), "kirby.ur... at gmail.com" > declaimed the following in comp.lang.python: > > > Sometimes we spare the students (whomever they may be) this added > > step and just hand them a dictionary of lists or whatever. We > > may not be teaching parsing in this class, but chemistry, and > > having the info in the Periodic Table in a Pythondatastructure > > maybe simply be the most relevant place to start. > > In this particular example, I'd probably suggest stuffing thedata > into an SQLite3 database file... Searching on name, symbol, weight, etc. > would be much easier then trying to dig through a nested dictionary. > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ That's not a bad idea. We might see people passing ZODBs around more too, as 'import zodb' in IDLE or whatever is increasingly the style, vs. some megabundle you have to install. Think of Zope as another site-package. The advantage of just passing .py files around, among XO users for example, is the periodicTable.py's contents are directly eyeballable as ascii/unicode text, vs. stuffed into a wrapper. I think what I'm getting from this fruitful discussion is the different role of amalgamator-distributors, and Sayid or Kate as classroom teachers, just trying to get on with the lesson and having no time for computer science topics. XML or YAML also make plenty of sense, for the more generic distributor type operations. Speaking only for myself, I appreciated some of the pointers to APIs. Over on edu-sig, we've been talking a lot about the 3rd party module for accessing imdb information -- not a screen scraper. Given xml-rpc, there's really no limit on the number of lightweight APIs we might see. How about CIA World Factbook? Too boring maybe, but it's already going out on the XOs, or some of them, just because it's relatively up to date. Could be imported as Python module too -- maybe that work has already been done? Kirby From gnewsg at gmail.com Mon Jan 14 07:56:52 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Mon, 14 Jan 2008 04:56:52 -0800 (PST) Subject: Threaded server References: Message-ID: <7decdf29-aab4-4fc6-93d8-7b2565e23f78@m34g2000hsf.googlegroups.com> On 14 Gen, 12:30, Nick Craig-Wood wrote: > Giampaolo Rodola' wrote: > > ?I'm trying to run an asynchronous FTP server I wrote into a thread for > > ?being able to run a test suite against it. > > ?The code below is the threaded FTP server code I'm using: > > > ?class FTPd(threading.Thread): > > > ? ? ?def __init__(self): > > ? ? ? ? ?self.active = False > > ? ? ? ? ?threading.Thread.__init__(self) > > > ? ? ?def start(self, flag=None): > > ? ? ? ? ?assert not self.active > > ? ? ? ? ?self.flag = flag > > ? ? ? ? ?threading.Thread.start(self) > > > ? ? ?def run(self): > > ? ? ? ? ?assert not self.active > > ? ? ? ? ?ftpd = ftpserver.FTPServer(address, ftp_handler) > > ? ? ? ? ?if self.flag: > > ? ? ? ? ? ? ?self.flag.set() > > ? ? ? ? ?self.active = True > > ? ? ? ? ?while self.active: > > ? ? ? ? ? ? ?ftpd.server_forever(timeout=1, count=1) > > ? ? ? ? ?ftpd.close() > > > ? ? ?def stop(self): > > ? ? ? ? ?assert self.active > > ? ? ? ? ?self.active = False > > > ?flag = threading.Event() > > ?ftpd = FTPd() > > ?ftpd.start(flag) > > ?flag.wait() ?# wait for it to start > > ?unittest.main() # run the test suite > > ?ftpd.stop() > > > ?Sometimes I get a strange error when all the tests have finished, the > > ?server is stopped and Python is exiting: > > > ?Ran 50 tests in 1.515s > > > ?OK > > ?Exception exceptions.TypeError: "'NoneType' object is not callable" in > > > ?thod FTPHandler.__del__ of > ?127.0.0.1:2 > > ?249 at 0xa4b080>> ignored > > ?Exception exceptions.TypeError: "'NoneType' object is not callable" in > > > ?thod FTPServer.__del__ of > ?127.0.0.1:543 > > ?21 at 0x9e1a30>> ignored > > > ?I sincerely don't know why that happens but it's likely because I'm > > ?not using threads properly. > > ?My concern is that this could be caused by a sort of race condition > > ?(e.g. Python tries to exit when ftpd.close call is not yet > > ?completed). > > It looks like when python is shutting down, it has removed an object > the ftphandler code relies on. > > I see you attempt to kill the ftp server with ftpd.stop(). ?That is > good, but you don't wait for the thread to finish (it might take up to > a second in ftpd.server_forever if I understand correctly). > > I expect if you put a self.join() at the end of the stop() method the > problem will go away. > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Tried it but the problem remains. The strange thing is that it sometimes happens, sometimes doesn't. From israelu at elbit.co.il Thu Jan 17 03:00:37 2008 From: israelu at elbit.co.il (iu2) Date: Thu, 17 Jan 2008 00:00:37 -0800 (PST) Subject: Hebrew in idle ans eclipse (Windows) References: <478ee0c0$0$4589$9b622d9e@news.freenet.de> Message-ID: <86ea4c94-f4b3-4bc3-9b2a-bc9b5c182264@i12g2000prf.googlegroups.com> On Jan 17, 6:59?am, "Martin v. L?wis" wrote: > > What do I need to do run my app like IDLE does? > > Can you please show the fragment of your program that prints > these strings? > > Regards, > Martin Hi, I use pymssql to get the data from a database, just like this (this is from the pymssql doc): import pymssql con = pymssql.connect(host='192.168.13.122',user='sa',password='',database='tempdb') cur = con.cursor() cur.execute('select firstname, lastname from [users]') lines = cur.fetchall() print lines or print lines[0] 'lines' is a list containing tuples of 2 values, for firstname and lastname. The names are Hebrew and their code looks different when I'm runnig it from IDLE than when running it from Windows shell or eclipse, as I described in my first post. Important: This doesn't happer when I read text from a file containing Hebrew text. In that case both IDLE and eclipse give the same reulst (the hebrew word itself is printed to the console) From sween119 at hotmail.com Sat Jan 12 09:29:24 2008 From: sween119 at hotmail.com (sween119 at hotmail.com) Date: Sat, 12 Jan 2008 06:29:24 -0800 (PST) Subject: Great Python books for the beginner References: Message-ID: On Jan 12, 2:03?am, Landon wrote: > Hi, I'm a freshman in college and I'm going to be taking an intro to > programming course next semester which mainly uses Python, so I > thought it might be a good time to pick up Python beyond the scope of > the class as well. The text book for this class is Python for the > Absolute Beginner or something similar to that name. > > I was wondering if anyone had any opinions on what other titles I > could look into since this one seems from a glance at reviews to be > teaching mainly through game programming (a topic I'm not too > interested in) or if this one is a quality book by itself. Hi Landon, I've found the O'reilly books to be useful I have the Python Pocket reference, which is helpful for me to remember the parameters surrounding commands and all that. I've been known to peruse the "Learning Python" book by the same publisher and I really like "Programming Python" (though it is thoroughly hefty and runs about $60USD) But has excellent documentation and if I may put a word in for to check out if you would be at all interested in starting game programming. -Sween From hniksic at xemacs.org Mon Jan 14 06:53:30 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 14 Jan 2008 12:53:30 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <87prw4fyej.fsf@benfinney.id.au> Message-ID: <87tzlgvd1h.fsf@mulj.homelinux.net> Ben Finney writes: > What one is "in reality" calling is the '__new__' method of the Person > class. That function, in turn, is creating a new Person instance, and > calling the '__init__' method of the newly-created instance. Finally, > the '__new__' method returns that instance back to the caller. This is also not entirely correct. __new__ doesn't call __init__; if it did, there would be no way to call __new__ without also calling __init__ (pickle, among other things, does that and needs to do that to correctly implement its logic). "In reality" executing Person(...) invokes the __call__ method of type(Person) (normally the standard metatype called "type") bound to the Person type object. This is where the logic to call __new__ followed by __init__ is implemented, in code that does something close to this: obj = mytype.__new__(*args, **kwds) if isinstance(obj, mytype): mytype.__init__(obj, *args, **kwds) return obj From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 17 09:44:29 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 17 Jan 2008 15:44:29 +0100 Subject: Loop in a loop? In-Reply-To: References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <478f699d$0$17578$426a74cc@news.free.fr> Sacred Heart a ?crit : > On Jan 17, 1:35 pm, cokofree... at gmail.com wrote: >> for i in zip(array1, array2): >> print i >> >> Although I take it you meant four d, the issue with this method is >> that once you hit the end of one array the rest of the other one is >> ignored. > > Yes, small typo there. > > Okey, so if my array1 is has 4 elements, and array2 has 6, it won't > loop trough the last 2 in array2? How do I make it do that? Please gentlemen: Python has no builtin type named 'array', so s/array/list/g Just pad your shortest list. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 15 06:19:48 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 15 Jan 2008 12:19:48 +0100 Subject: common problem - elegant solution sought In-Reply-To: <5v3gg1F1kkla5U1@mid.dfncis.de> References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <478c96b1$0$29652$426a34cc@news.free.fr> Helmut Jarausch a ?crit : > Hi, > > I'm looking for an elegant solution of the following tiny but common > problem. > > I have a list of tuples (Unique_ID,Date) both of which are strings. > I want to delete the tuple (element) with a given Unique_ID, but > I don't known the corresponding Date. If you don't care about ordering, you could use a dict: L=[("a","070501"),("b","080115"),("c","071231")] d = dict(L) del d['b'] L = d.items() But I guess you care about ordering !-) Anyway, you can still use a dict to find out the date part: L=[("a","070501"),("b","080115"),("c","071231")] d = dict(L) t = ('b', d['b']) L.remove(t) Or you could build an 'index' list to find out the appropriate index: L=[("a","070501"),("b","080115"),("c","071231")] index = [key for key, val in L] pos = index.index('b') del L[pos] > My straight forward solution is a bit lengthy, e.g. > > L=[("a","070501"),("b","080115"),("c","071231")] > pos=-1 > found=-1 > for (Key,Date) in L : > pos+= 1 > if Key == "b" : > found= pos > break > > if found >= 0 : > del L[found] > > print L You could have used the enumerate(seq) function here. And since you're breaking out once the element deleted, you could as well delete it from within the loop: for pos, (key, date) in enumerate(L): if key == 'b': del L[pos] break Benchmarking left as an exercice to the reader !-) Also note that the "best" solution may depend on your real use case and dataset. From workitharder at gmail.com Sat Jan 5 16:35:08 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 5 Jan 2008 13:35:08 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> Message-ID: <61faa305-38ad-42c4-9cd1-09851848cb14@l6g2000prm.googlegroups.com> On Jan 5, 8:14 am, c... at mailinator.com wrote: > On Jan 5, 5:07 pm, c... at mailinator.com wrote: > > > Hello, Paul and Arnaud. > > While I think about your answers: do you think there is any way to > > avoid shuffle? > > It may take unnecessary long on a long list most of whose elements > > have the property. > > Umm... > You provide nice answers in the case many elements are picked from the > same list. > Any ideas for the case when the picker is called many times on a > program, but never twice with the same list? Here's my stab: from random import randint, seed from time import time from sys import stdout seed(time()) iterations = 0#DEBUG def pick_random(seq, prop=bool): temp = list(seq) global iterations#DEBUG while temp: iterations += 1#DEBUG i = randint(0, len(temp) - 1) if prop(temp[i]): return temp[i] else: del temp[i] def generate_list(length): l = list() for x in xrange(length): l.append(randint(0,1) * randint(1,1000)) return l count = 0 for x in xrange(1000): count += 1 print pick_random(generate_list(1000)), print print "AVERAGE ITERATIONS:", float(iterations) / count The average number of iterations is 1/p where p is the chance of your property being true. It's independent of list size! Just remove the DEBUG lines and it's ready for use. --Buck From paddy3118 at googlemail.com Mon Jan 7 03:04:53 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 7 Jan 2008 00:04:53 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <33417662-8246-4950-9b86-265aa1c63c69@c23g2000hsa.googlegroups.com> Message-ID: On Jan 5, 6:37 am, Paddy wrote: > On Jan 4, 7:55 pm, c... at mailinator.com wrote: > > > > > Hello, > > This is a question for the best method (in terms of performance > > only) to choose a random element from a list among those that satisfy > > a certain property. > > > This is the setting: I need to pick from a list a random element > > that satisfies a given property. All or none of the elements may have > > the property. Most of the time, many of the elements will satisfy the > > property, and the property is a bit expensive to evaluate. Chance of > > having the property are uniform among elements. > > > A simple approach is: > > > import random > > def random_pick(a_list,property): > > '''Returns a random element from a list that has the property > > > Returns None if no element has the property > > ''' > > random.shuffle(a_list) > > for i in a_list: > > if property(i): return i > > > but that requires to shuffle the list every time. > > > A second approach, that works if we know that at least one element of > > the list has the property, is: > > > import random > > def random_pick(a_list,property): > > '''Returns a random element from a list that has the property > > > Loops forever if no element has the property > > ''' > > while 1: > > i=random.choice(a_list) > > if property(i): return i > > > which is more efficient (on average) if many elements of the list have > > the property and less efficient if only few elements of the list has > > the property (and goes crazy if no element has the property) > > > Yet another one: > > > import random > > def random_pick(a_list,property): > > '''Returns a random element from a list that has the property > > ''' > > b_list=[x for x in a_list if property(x)] > > try: > > return random.choice(b_list) > > finally: return None > > > but this one checks the property on all the elements, which is no > > good. > > > I don't need strong random numbers, so a simple solution like: > > import random > > globalRNG=random.Random() > > > def random_pick(a_list,property): > > '''Returns a random element from a list that has the property > > > Works only if len(a_list)+1 is prime: uses Fermat's little theorem > > ''' > > a=globalRNG(1,len(a_list)) > > ind=a > > for i in xrange(len(a_list)): > > x=a_list[a-1] > > if property(x):return x > > ind*=a > > > but this works only if len(a_list)+1 is prime!!! Now this one could be > > saved if there were an efficient method to find a prime number given > > than a number n but not very much greater... > > > Any other ideas? Thanks everybody > > Caching might help. > > If random_pick is called several times with the same list(s) then > cache the result of > [property(i) for i in a_list] against a_list. > > If random_pick is called several times with list(s) whith multiple > instances of list items then cache > property(i) against i for i in a_list . > > You could do both. > > You might investigate wether property(i) could be implemented using a > faster algorithm, maybe table lookup, or interpolation from initial > table lookup. > > - Paddy. Here's a caching decorator that you could apply to function property: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498245 - Paddy. From PatrickMinnesota at gmail.com Wed Jan 9 21:10:03 2008 From: PatrickMinnesota at gmail.com (PatrickMinnesota) Date: Wed, 9 Jan 2008 18:10:03 -0800 (PST) Subject: Pygame w/ GUI Message-ID: <3566c2f9-c138-45d3-bc2d-7b2a2b3f78c7@q39g2000hsf.googlegroups.com> I know this isn't strictly a Python question, but I'm betting some here might be able to give me a hint. I have a few graphical programs doing some 2D data visualization using simple Pygame code for pseudo real-time animation. It's running under windows XP right now, but eventually it'll need to be cross- platform. As it is right now, it probably is, I just haven't tried it anywhere but XP. Now I want to wrap some simple GUI functions around it. I'm looking for some buttons, a text field or two and file system selection of data files. I figure many have done this and there is a better solution than to use Pygame constructs to implement such things. My question: I'm not seeing much support in Pygame for that stuff. It seems I should build buttons and file browsing in some other toolkit. Is that true? Or am I just to early on in the Pygame docs to see solutions? If I should use something else, am I going to be able to use Tkinter or WxPython in conjunction with my Pygame code? Or is there something else I should be looking at? Oh, and I'm running Python 2.5.1 Thanks for any thoughts. From lists at cheimes.de Wed Jan 23 02:49:20 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 23 Jan 2008 08:49:20 +0100 Subject: translating Python to Assembler In-Reply-To: References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: Wim Vander Schelden wrote: > Python modules and scripts are normally not even compiled, if they have > been, > its probably just the Python interpreter packaged with the scripts and > resources. No, that is not correct. Python code is compiled to Python byte code and execute inside a virtual machine just like Java or C#. It's even possible to write code with Python assembly and compile the Python assembly into byte code. You most certainly meant: Python code is not compiled into machine code. Christian From lists at cheimes.de Mon Jan 28 10:50:36 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 28 Jan 2008 16:50:36 +0100 Subject: validate string is valid maths In-Reply-To: <13pru0etgp7joc1@corp.supernews.com> References: <13pru0etgp7joc1@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > def rationalise_signs(s): > while "++" in s or "+-" in s or "-+" in s or "--" in s: > s = s.replace("++", "+") > s = s.replace("--", "+") > s = s.replace("+-", "-") > s = s.replace("-+", "-") > return s I assume it's faster to check the length of the string s after each iteration and compare it to the last iteration. When the string hasn't changed break out of the loop. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 17 03:58:51 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 17 Jan 2008 09:58:51 +0100 Subject: Replace stop words (remove words from a string) In-Reply-To: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> Message-ID: <478f189d$0$24730$426a74cc@news.free.fr> BerlinBrown a ?crit : > if I have an array of "stop" words, and I want to replace those values > with something else; in a string, how would I go about doing this. I > have this code that splits the string and then does a difference but I > think there is an easier approach: > > E.g. > > mystr = > kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsldfsd; > you forgot the quotes > if I have an array stop_list = [ "[BAD]", "[BAD2]" ] s/array/list/ > I want to replace the values in that list with a zero length string. > > I had this before, but I don't want to use this approach; I don't want > to use the split. > > line_list = line.lower().split() > res = list(set(keywords_list).difference(set(ENTITY_IGNORE_LIST))) res = mystr for stop_word in stop_list: res = res.replace(stop_word, '') From adonisv at REMOVETHISearthlink.net Wed Jan 9 21:46:29 2008 From: adonisv at REMOVETHISearthlink.net (Adonis Vargas) Date: Wed, 09 Jan 2008 21:46:29 -0500 Subject: Pygame w/ GUI In-Reply-To: <3566c2f9-c138-45d3-bc2d-7b2a2b3f78c7@q39g2000hsf.googlegroups.com> References: <3566c2f9-c138-45d3-bc2d-7b2a2b3f78c7@q39g2000hsf.googlegroups.com> Message-ID: <13ob1o7t81b7e0c@corp.supernews.com> PatrickMinnesota wrote: > I know this isn't strictly a Python question, but I'm betting some > here might be able to give me a hint. > > I have a few graphical programs doing some 2D data visualization using > simple Pygame code for pseudo real-time animation. It's running > under windows XP right now, but eventually it'll need to be cross- > platform. As it is right now, it probably is, I just haven't tried it > anywhere but XP. > > Now I want to wrap some simple GUI functions around it. I'm looking > for some buttons, a text field or two and file system selection of > data files. I figure many have done this and there is a better > solution than to use Pygame constructs to implement such things. > > My question: I'm not seeing much support in Pygame for that stuff. > It seems I should build buttons and file browsing in some other > toolkit. Is that true? Or am I just to early on in the Pygame docs > to see solutions? > > If I should use something else, am I going to be able to use Tkinter > or WxPython in conjunction with my Pygame code? Or is there something > else I should be looking at? > > Oh, and I'm running Python 2.5.1 > > Thanks for any thoughts. I do not have experience using pygame, but you can look at: http://pyui.sourceforge.net/ Creates an user interface with pygame as a possible back end. Hope this helps. Adonis From paddy3118 at googlemail.com Sat Jan 26 02:53:49 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 25 Jan 2008 23:53:49 -0800 (PST) Subject: [OT]: The Python Fan Message-ID: http://www.brightcove.tv/title.jsp?title=1390821847 :-) - Paddy. From ajcppmod at gmail.com Thu Jan 24 07:37:24 2008 From: ajcppmod at gmail.com (ajcppmod at gmail.com) Date: Thu, 24 Jan 2008 04:37:24 -0800 (PST) Subject: Test driven development Message-ID: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> Hi Sorry if this is a bit off topic but as unit testing is such a cornerstone of python development I thought a few of you may be able to share your knowledge/experiences. I like the concept of TDD but find it difficult to put into practice most of the time. I think this primarily because I tend to like top- down development and functional/object decomposition and TDD feels more like a bottom-up approach. So my question is when approaching a project that you want to employ test driven development on how and where do you start? And also if anyone uses top-down design with TDD I would be interested in how you do it (does it involve lots of mock objects/ is the first test you write the last one to pass)? Thanks Andy From soren.skou.nielsen at gmail.com Thu Jan 10 03:44:19 2008 From: soren.skou.nielsen at gmail.com (Soren) Date: Thu, 10 Jan 2008 00:44:19 -0800 (PST) Subject: FindWindowById returns None..... ? References: Message-ID: <0a3d6bf8-110a-4b1c-a2df-d8495d0b1204@s19g2000prg.googlegroups.com> On Jan 10, 9:43 am, Soren wrote: > Hi, > > I'm trying to split my GUI into several files since its beginning to > become a bit large.. I've placed a panel class inside gui2.py, but it > needs some information from a panel in gui1.py... if I import gui1 in > gui2 and try to find the panel by its ID, (using the Id generated in > gui1) I get a None value returned?? using findwindowbyid in gui1 on > the same ID works fine.. > > I'm guessing i'm doing this the wrong way, can anyone comment on this? > > Thanks, > Soren Wops.. and I'm using wxPython :) From arnodel at googlemail.com Sun Jan 20 20:12:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 20 Jan 2008 17:12:18 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <80e1aed1-1d75-4409-bbc3-d48f9c3656ab@e6g2000prf.googlegroups.com> Message-ID: On Jan 21, 1:07?am, Arnaud Delobelle wrote: > On Jan 20, 5:41?pm, dg.google.gro... at thesamovar.net wrote: > > > Ever since I learnt to program I've always loved writing solvers for > > the Countdown numbers game problem in different languages > > Ok so here's a challenge I just thought of: > > What is (or are) the set of 6 starting numbers which are such that the > smallest target they can't reach is maximal? Update: 2, 4, 5, 8, 9, 25 can reach any target between 100 and 999. The question remains if we lift the upper limit of 999... Time to really go to bed :) -- Arnaud From steve at mhomer.au Thu Jan 10 21:09:26 2008 From: steve at mhomer.au (Steve Brown) Date: Fri, 11 Jan 2008 13:09:26 +1100 Subject: docstrings style question References: <13obcbumpitbe23@corp.supernews.com> Message-ID: <13odjunti9pfq7f@corp.supernews.com> What I'm trying to do with the tests is pare them back so that the code explicitly and concisely documents the tests. It is important that the comments and doc strings NOT contain information about how Temperature Sense works because that is outside the scope of the test. More generally, comments like this i++ #increments i indicate that the author thinks that the most complex thing present is the syntax, a comment like this: i++ #next voltage indicates that the author thinks the most complex thing present is the variable mapping. For the readers and maintainers of these tests, the most complex thing present is the syntax, not the test logic, so if I need to add more documentation, it will look like this: # Temperature Sense Test # Lines starting with # are comments # Variables are case sensitive # Tab characters will break this file -- and go from there. Steve "Martin Marcher" wrote in message news:mailman.397.1199959984.896.python-list at python.org... > Russ P. wrote: > From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 28 10:43:26 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 28 Jan 2008 16:43:26 +0100 Subject: "just like Java" (was :Re: translating Python to Assembler) In-Reply-To: <7f6f3a93-4301-4a75-83d3-13d9a7c57cda@h11g2000prf.googlegroups.com> References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <4799de28$0$12358$426a74cc@news.free.fr> <7f6f3a93-4301-4a75-83d3-13d9a7c57cda@h11g2000prf.googlegroups.com> Message-ID: <479df81c$0$24179$426a74cc@news.free.fr> Paul Boddie a ?crit : > On 25 Jan, 14:05, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Christian Heimes a ?crit : >> >>> No, that is not correct. Python code is compiled to Python byte code and >>> execute inside a virtual machine just like Java or C#. >> I'm surprised you've not been flamed to death by now - last time I >> happened to write a pretty similar thing, I got a couple nut case >> accusing me of being a liar trying to spread FUD about Java vs Python >> respective VMs inner working, and even some usually sensible regulars >> jumping in to label my saying as "misleading"... > > Well, it is important to make distinctions when people are wondering, > "If Python is 'so slow' and yet everyone tells me that the way it is > executed is 'just like Java', where does the difference in performance > come from?" Your responses seemed to focus more on waving that issue > away and leaving the whole topic in the realm of mystery. The result: > "Python is just like Java apparently, but it's slower and I don't know > why." I'm afraid you didn't read the whole post : """ So while CPython may possibly be too slow for your application (it can indeed be somewhat slow for some tasks), the reasons are elsewhere (hint: how can a compiler safely optimize anything in a language so dynamic that even the class of an object can be changed at runtime ?) .""" I may agree this might not have been stated explicitily enough, but this was about JIT optimizing compilers. Also, a couple posts later - FWIW, to answer the OP "how does it comes it slower if it's similar to Java" question : """ Java's declarative static typing allow agressive just-in-time optimizations - which is not the case in Python due to it's higly dynamic nature. """ From bj_666 at gmx.net Wed Jan 30 04:48:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jan 2008 09:48:23 GMT Subject: Unicode literals to latin-1 References: Message-ID: <60avf7F1ps52dU3@mid.uni-berlin.de> On Wed, 30 Jan 2008 09:57:55 +0100, David.Reksten wrote: > How can I convert a string read from a database containing unicode > literals, such as "Fr\u00f8ya" to the latin-1 equivalent, "Fr?ya"? > > I have tried variations around > "Fr\u00f8ya".decode('latin-1') > but to no avail. In [388]: 'Fr\u00f8ya'.decode('unicode-escape') Out[388]: u'Fr\xf8ya' In [389]: print 'Fr\u00f8ya'.decode('unicode-escape') Fr?ya Ciao, Marc 'BlackJack' Rintsch From lists at cheimes.de Sat Jan 19 10:14:26 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 19 Jan 2008 16:14:26 +0100 Subject: finding memory leak in edgewall trac 0.11 In-Reply-To: References: Message-ID: <479213D2.2020701@cheimes.de> rupert.thurner wrote: > what would be a good means of finding where the 0.11 version of > edgewall trac uses excessive memory. see > http://groups.google.com/group/trac-dev/browse_thread/thread/116e519da54f16b > for some details, where jonas suggested > http://wingolog.org/archives/2007/11/27/reducing-the-footprint-of-python-applications > as reading. > > tiran already gave some hints on http://bugs.python.org/issue1871, but > also suggested to ask the general mailing list: > > Do you have classes with a __del__ method which may create reference > cycles? The GC can't break cycles when a __del__ method is involved. > > Are you keeping references to tracebacks, exception objects (except > Exception, err) or frames (sys._getframe()) I forgot one important point in my reply. The GC module contains some useful methods for debugging. Check gc.garbage. It should be empty. http://docs.python.org/lib/module-gc.html Christian From dblubaugh at belcan.com Tue Jan 22 10:53:03 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 22 Jan 2008 10:53:03 -0500 Subject: Has Anyone Worked with Gene Expression Programming ??????????????????????????? Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38021A5D9F@AWMAIL04.belcan.com> To Anyone, Has anyone worked with Gene Expression Programming??? Specifically, has anyone out there worked with pygep software package??? I have a few questions!!!! David Blubaugh -------------- next part -------------- An HTML attachment was scrubbed... URL: From mark.e.tolonen at mailinator.com Sun Jan 27 12:55:14 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Sun, 27 Jan 2008 09:55:14 -0800 Subject: REALLY simple xml reader References: Message-ID: "Simon Pickles" wrote in message news:mailman.1148.1201455326.896.python-list at python.org... > Hi > > Can anyone suggest a really simple XML reader for python? I just want to > be able to do something like this: > > xmlDoc = xml.open("file.xml") > element = xmlDoc.GetElement("foo/bar") > > ... to read the value of: > > > 42 > > > > Thanks > > Simon > > -- > Linux user #458601 - http://counter.li.org. > > > >>> from xml.etree import ElementTree as ET >>> tree=ET.parse('file.xml') >>> tree.find('bar').text '42' >>> --Mark From george.sakkis at gmail.com Fri Jan 11 23:55:07 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jan 2008 20:55:07 -0800 (PST) Subject: Import and execfile() References: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> Message-ID: On Jan 11, 5:24 pm, Mike Meyer wrote: > On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis wrote: > > > I maintain a few configuration files in Python syntax (mainly nested > > dicts of ints and strings) and use execfile() to read them back to > > Python. This has been working great; it combines the convenience of > > pickle with the readability of Python. So far each configuration is > > contained in a single standalone file; different configurations are > > completely separate files. > > You know, I've been there before. It's kinda neat, but not something > you really want to put in the hands of most users. Well, I am almost the only user (of the config file, not the application) and the few others are developers too so that's not an issue in this case. > You can make the syntax cleaner by using classes to hold the values > instead of nested dicts, etc. That way you don't have to quote the > names of the values: > > class Foo: > bar = 1 > baz = 2 Actually I am using the dict() constructor instead of literals so it's as clean as with classes; IMO for nested options it's cleaner than nested classes: Env = dict( PORT = 6789, KEY = 123456789, EXE = '/usr/local/lib/myprog', LD_LIBRARY_PATH = ':'.join([ '/usr/lib', '/usr/local/lib', ]), OPTIONS = dict( n = None, min = 1, max = 15000, ) ) > > ====================== > > # some_config.py > > > # master_config.py is in the same directory as some_config.py > > from master_config import * > > > # override non-default options > > foo['bar']['baz] = 1 > > ... > > > ====================== > > # trying to set the configuration: > > CFG = {} > > execfile('path/to/some_config.py', CFG) > > > Traceback (most recent call last): > > ... > > ImportError: No module named master_config > > > I understand why this fails but I'm not sure how to tell execfile() to > > set the path accordingly. Any ideas ? > > Manipulate sys.path yourself? That's what Mitko suggested too, and indeed it works: import sys, os def setConfig(configfile): cfg = {} syspath = list(sys.path) try: sys.path.append(os.path.dirname(configfile)) execfile(configfile, cfg) finally: sys.path = syspath return cfg However this doesn't look very clean to me. Also it's not thread-safe; guarding it explicitly with a lock would make it even less clean. Ideally, I'd like to pass a new path to execfile without modifying the original (even for the few milliseconds that execfile() wlll probably take). With modules being singletons though, I don't think this is possible, or is it ? George From sgeiger at ncee.net Fri Jan 4 02:04:56 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Fri, 04 Jan 2008 01:04:56 -0600 Subject: linecache and glob In-Reply-To: <0e16ca26-9e34-4f97-83de-9ddc3693d085@i12g2000prf.googlegroups.com> References: <0e16ca26-9e34-4f97-83de-9ddc3693d085@i12g2000prf.googlegroups.com> Message-ID: <477DDA98.8070508@ncee.net> import linecache import glob # reading from one file print linecache.getline('notes/python.txt',4) 'http://www.python.org/doc/current/lib/\n' # reading from many files for filename in glob.glob('/etc/*'): print linecache.getline(filename,4) jo3c wrote: > hi everyone happy new year! > im a newbie to python > i have a question > by using linecache and glob > how do i read a specific line from a file in a batch and then insert > it into database? > > because it doesn't work! i can't use glob wildcard with linecache > > >>>> import linecache >>>> linecache.getline(glob.glob('/etc/*', 4) >>>> > > doens't work > > is there any better methods??? thank you very much in advance > > jo3c > -- 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 lloyd at paisite.com Sat Jan 12 14:24:32 2008 From: lloyd at paisite.com (lloyd at paisite.com) Date: Sat, 12 Jan 2008 14:24:32 -0500 (EST) Subject: =?UTF-8?Q?RE:=20Import=20and=20execfile()?= Message-ID: <45883.192.168.1.70.1200165872.webmail@192.168.1.70> Hello, > I maintain a few configuration files in Python syntax (mainly nested > dicts of ints and strings) and use execfile() to read them back to > Python. This has been working great; it combines the convenience of > pickle with the readability of Python. So far each configuration is > contained in a single standalone file; different configurations are > completely separate files. > Now I'd like to factor out the commonalities of the different > configurations in a master config and specify only the necessary > modifications and additions in each concrete config file. I tried the > simplest thing that could possibly work: I've been working with a similar problem; indeed, posted a question about it several weeks ago. I can't speak to the issue of factoring out commonalities, but I've been trying to find a really simple, elegant way to avoid the exec functions. My approaches have been variations in __import__() and loading as file, etc. Everything I've tried seems a bit kludgy. One issue, as I recall, was that __import__() became rather unreliable when you crossed directory boundaries. Question: Why do so many sources discourage the use of exec(), execfile(), etc.? Comment: The Karrigell Python web framework (http://karrigell.sourceforge.net/en/include.htm) has a truly elegant function for loading stuff like some_config.py called Include(). I haven't looked at the source, but it is very handy. I really wish it was basic Python function. All the best, Lloyd -------------- next part -------------- An HTML attachment was scrubbed... URL: From jpeng at block.duxieweb.com Sun Jan 20 23:21:19 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Mon, 21 Jan 2008 12:21:19 +0800 Subject: object scope In-Reply-To: <4794196A.2020901@block.duxieweb.com> References: <4794196A.2020901@block.duxieweb.com> Message-ID: <47941DBF.3070605@block.duxieweb.com> J. Peng ??: > Please see the code below,what's the scope for object "name"? > I thought it should be located in the while block, but it seems not > really,it can be accessed out of while (the db[name] statement).Thanks > in advance. > > sorry the before code seems be disordered,re-posted it. db = {} def newuser(): prompt = 'login desired: ' while 1: name = raw_input(prompt) if db.has_key(name): prompt = 'name taken, try another: ' continue else: break pwd = raw_input('passwd: ') db[name] = pwd From ryszard.szopa at gmail.com Sat Jan 12 17:23:52 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Sat, 12 Jan 2008 14:23:52 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> Message-ID: On Jan 12, 9:47 pm, Mike Meyer wrote: > The same way you call any object's methods if you know it's name": > > getattr(super_object, name)(*args, **kwargs) Thanks a lot for your answer! However, I am very surprised to learn that super_object.__getattr__(name)(*args, **kwargs) getattr(super_object, name)(*args, **kwargs) are not equivalent. This is quite odd, at least when with len() and .__len__, str() and .__str__. Do you maybe know what's the rationale behind not following that convention by getattr? Best regards, -- Richard From thegooddale at gmail.com Wed Jan 23 22:41:17 2008 From: thegooddale at gmail.com (Yansky) Date: Wed, 23 Jan 2008 19:41:17 -0800 (PST) Subject: Problems getting Python scripts to run on server Message-ID: <83ae0f82-e9af-433e-936d-d5b5600a315e@j20g2000hsi.googlegroups.com> Hi, I'm having a lot of problems getting any Python scripts to run on my website. I have put them in the cgi-bin directory and chmodded both the directory and files to 755. But when I try to access the script, I get a 404 error: http://forboden.com/cgi-bin/wp.py I also tried running them from another directory and giving the directory its own .htaccess file containing: Options +ExecCGI AddHandler cgi-script .py but again, they still wouldn't run. The odd thing is, its not that they don't run per se, but that I get a 404 error. When I tried the scripts in the other folder (the non cgi- bin folder), before I added a .htaccess file, I tried the scripts and sure enough it displayed the file source code. But when I added the .htaccess file, I got a 404 file not found error. I emailed my hosting company and they said: "Python is currently installed on the server and is running without any issues. The URL you have provided is not showing any errors on the server. I would advise checking over your scripting to ensure that the issue isn't there." Anyone have any ideas as to what's going wrong? From stefan.behnel-n05pAM at web.de Tue Jan 29 09:46:06 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 29 Jan 2008 15:46:06 +0100 Subject: Executing other python code In-Reply-To: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: <479F3C2E.6030104@web.de> Hi, Tim Rau wrote: > I'm working on a game, and I'd like players to be able to define thier > ships with scripts. Naturally, I don't want to give them the entire > program as thier romping ground. I would like to invoke a seperate > interpreter for these files, and give it a limited subset of the > functions in my game. What is the best way to achieve this effect? Depends. If you are concerned about security, this will be hard to achieve in Python. I imagine that this could be related to cheating prevention. If you are more concerned about namespace polution and making only a well defined API available to the scripts, go the module-import way and hand some API object over, either through an initialisation function or by injecting it into the module namespace, as Arnaud suggested. Stefan From hniksic at xemacs.org Thu Jan 17 01:55:29 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 17 Jan 2008 07:55:29 +0100 Subject: assigning values in python and perl References: Message-ID: <87tzlddjq6.fsf@mulj.homelinux.net> "J. Peng" writes: > $ cat t1.py > def test(x): > x = [4,5,6] > > a=[1,2,3] > test(a) > print a > > $ python t1.py > [1, 2, 3] > > $ cat t1.pl > sub test { > my $ref = shift; > @$ref = (4,5,6); > } @$ref = (4, 5, 6) intentionally assigns to the same list pointed to by the reference. That would be spelled as x[:] = [4, 5, 6] in Python. What Python does in your example is assign the same as Perl's $ref = [4, 5, 6]. So they're not so different after all. From bronger at physik.rwth-aachen.de Mon Jan 28 03:40:35 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 28 Jan 2008 09:40:35 +0100 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <873asjdscc.fsf@physik.rwth-aachen.de> <361ff5df-d74a-4c85-ae60-2bf1b44281b2@z17g2000hsg.googlegroups.com> <87lk6a8m8q.fsf@physik.rwth-aachen.de> <13pr24chv832660@corp.supernews.com> Message-ID: <87hcgy8hrw.fsf@physik.rwth-aachen.de> Hall?chen! Steven D'Aprano writes: > On Mon, 28 Jan 2008 08:04:05 +0100, Torsten Bronger wrote: > >>> Are you referring to the alternate syntax or to the decorator? Either >>> way, you could be saving 4 or 5 or more lines, if you have enough >>> arguments. >> >> Mostly, I write them in one or two lines, e.g. >> >> def __init__(self, id, kind, person, feedname): >> self.id, self.kind, self.person = id, kind, person > > It's not the number of lines that is important, but the amount of > redundant code, and the amount of redundant code is identical > whether you write it in one line or three. I doubt that there is redunancy. Don't be misled by the fact that the string "id" appears twice. The expession is minimal in both cases. The only difference is that in one case you have the string "id" twice, and in the other case you have a special syntax or even a new identifier. The information contents is the same. > The problem is that instance initialization frequently and > regularly breaks the principle "Don't Repeat Yourself". [...] I don't see why. It say "I want *this* parameter be turned into an instance variable of the same name". Why is this repeating myself? In my opinon, it would be repeating yourself if in *all* __init__s you want to have *all* parameters turned into instance variables of the same name. However, we all know that sometimes the names should be different, or you want to do some trivial transformation before the assignment. Granted that it's a frequent use case which may justify syntactic sugar, but the straightforward solution is so simple that I think a new syntax would make the language just slightly more complicated without simplifying anything really. > [...] > > Here's a thought... why assume that the convention is a prefix? What > about a suffix? > > @autoassign > def __init__(self, spam_, ham_, eggs): > pass > > [...] Since Python has very few reserved words, and they rarely > make good argument names, there should be far fewer conflicts with > an underscore suffix rather than a prefix. I use them rather frequently, and I see them regularly in the stdlib, so I think this would cause confusion. > I'd still prefer compiler support, preferably with a leading & as > syntax. Please, no! ;-) I like that Python tries to avoid hacker characters in the code in favour of english words. Please bear in mind that it is a frequent use case, so you will have it in virtually every __init__ in fresh Python code. I prefer to see instance variables be defined in an brain-friendly explicit way rather than single characters that hide it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From http Thu Jan 10 21:54:07 2008 From: http (Paul Rubin) Date: 10 Jan 2008 18:54:07 -0800 Subject: getting n items at a time from a generator References: Message-ID: <7x7iihcbsg.fsf@ruckus.brouhaha.com> Tim Roberts writes: > I have to say that I have found this to be a surprisingly common need as > well. Would this be an appropriate construct to add to itertools? I'm in favor. From tjreedy at udel.edu Thu Jan 24 17:13:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jan 2008 17:13:50 -0500 Subject: Reporting Python bugs (was: Can someone explain this unexpectedraw_input behavior?) References: <13ff90c7-60ee-4306-8459-890a2b2b178a@e25g2000prg.googlegroups.com> <8763xi7wme.fsf_-_@benfinney.id.au> Message-ID: "Ben Finney" wrote in message news:8763xi7wme.fsf_-_ at benfinney.id.au... | Mike Kent writes: | | > A bug issue has been opened in the Python Trac system for this. | | Wouldn't it be better to report it in the official Python bug tracker | , which is Roundup, not Trac? Has been by Skip: http://bugs.python.org/issue1927 From mikez302 at gmail.com Fri Jan 11 23:40:48 2008 From: mikez302 at gmail.com (mikez302) Date: Fri, 11 Jan 2008 20:40:48 -0800 (PST) Subject: IDLE won't start in Python 2.5 for Windows References: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> Message-ID: How would I go about cleaning the registry? What specifically should I look for? Should I use any registry cleaner programs? Where are the IDLE preference files stored? When I uninstalled Python, it seems like everything was gone except for a few personal .py and .pyc files. Elias From rschroev_nospam_ml at fastmail.fm Thu Jan 24 14:44:51 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 24 Jan 2008 19:44:51 GMT Subject: Test driven development In-Reply-To: <98f3ca4c-a7f0-4707-b09d-8012b86de96b@x69g2000hsx.googlegroups.com> References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> <53bae618-0a57-470e-b698-3f936ef7c0e7@s12g2000prg.googlegroups.com> <98f3ca4c-a7f0-4707-b09d-8012b86de96b@x69g2000hsx.googlegroups.com> Message-ID: Virgil Dupras schreef: > On Jan 24, 1:30 pm, Roel Schroeven > wrote: >> Virgil Dupras schreef: >> >>> I know what you mean by top-down vs. bottom-up and I used to have the >>> same dilemma, but now I would tend to agree with Albert. Your issue >>> with top-down or bottom-up is not relevant in TDD. The only thing that >>> is relevant is to reach your current milestone as soon as possible, >>> without caring about what you're going to do in the milestone after >>> that. >>> Not so long ago, I took the "bottom-up" approach to TDD, which was a >>> mistake because it leads to over-engineering (the end result is not so >>> bad since it's over-engineering that has good test coverage :) ) >> I don't regularly use TDD yet, and one of the reasons is that in many >> cases I'm unsure exactly how to use it in practice. I read "Test-driven >> development - A practical guide" (and I should re-read), but I feel it >> doesn't help my much in everyday situations. Somehow the examples in the >> book don't match very well with how I code (and I admit that perhaps the >> problem is more with me than with the book). >> >> One of the problems I have is something like what Andy describes: I need >> a function spam(), so I write tests for it. Then I start implementing >> the function and see that I need to write functions ham() and eggs(). >> Should I write unit tests for ham() and eggs(), or do I rely on the >> tests for spam()? If I don't write them, doesn't that make it more >> difficult to find out why the tests for spam() fail? >> >> Speaking about over-engineering, when I do TDD along the lines of the >> book I mentioned, I always feel that I'm over-engineering the tests. It >> all feels very unnatural though I'm convinced it shouldn't be like that. >> >> Can someone suggest other books to read about the subject, ideally >> something more focused on Python or C++ rather than Java? >> >> -- >> The saddest aspect of life right now is that science gathers knowledge >> faster than society gathers wisdom. >> -- Isaac Asimov >> >> Roel Schroeven > > I also have a book about TDD and it never was of much help either. All > techniques come from the initial workflow: Red - Green - Refactor. > > The problem you describe is a tricky problem. The way I feel it should > be solved is: > > - Write spam() (and its tests, of course). > - Then, at some point, in the re-factor phase, you split extract the > function ham() from spam(). Alright, do it and keep the tests as is > (all on spam()). > - Then at some other point, you extract eggs(). same thing. > - After a while (I don't know, 3 or 4 milestones), when it becomes > clear that ham() and eggs() are there to stay, start moving your tests > away from spam() by just mocking ham() and eggs() and just make sure > that spam() call them with the right arguments. The tests you had on > spam() that were relevant to ham() and eggs() are just performed > directly on them now. > > What I've been saying in my other message is: Don't do that too early, > because if it turns out that ham() and eggs() is not the optimal way > to do it, but foo() bar() and baz() is, it is *much* easier to do a > safe re-factoring with high level tests. That sounds reasonable. I'm getting the impression that reading that book led me to a too strict approach. I guess I just need to try somewhat harder to use TDD in my daily coding. Apart from books, are there other resources that can help beginners with TDD? Mailing lists, forums, newsgroups possibly? -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From lizm at rcsltd.co.uk Thu Jan 24 09:03:20 2008 From: lizm at rcsltd.co.uk (LizzyLiz) Date: Thu, 24 Jan 2008 06:03:20 -0800 (PST) Subject: csv to xls using python 2.1.3 References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> <4797763D.70604@websafe.com> Message-ID: On Jan 23, 5:15 pm, Larry Bates wrote: > FYI - Excel can read .CSV files directly and convert them to .XLS. > > -Larry Thanks Larry The customer wants 2 buttons - one for csv, one for xls. Kind regards Liz From cokofreedom at gmail.com Wed Jan 16 07:58:58 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 16 Jan 2008 04:58:58 -0800 (PST) Subject: no pass-values calling? References: <18c1e5f20801151909u4cdd227ah685741ea21734491@mail.gmail.com> Message-ID: On Jan 16, 1:21 pm, "Neil Cerutti" wrote: > On Jan 15, 2008 10:09 PM, J. Peng wrote: > > > Hello, > > > I saw this statement in Core Python Programming book, > > > All arguments of function calls are made by reference, meaning that > > any changes to these parameters within the function > > affect the original objects in the calling function. > > Yes, that's generally correct. But you must be careful about what is > meant by "changes to parameters". Assigning a new value to a parameter > name (inside the function, a parameter is just a local variable) does > not change the original object--it only rebinds the local variable to > a new object. > > In the following function, a is rebound with an assignment statement, > while b is mutated, i.e., changed, with an assignment statement. > > def f(a, b): > a = 12 > b.value = 14 > > Argument a will never be changed, while argument b will be. Python's > argument passing semantics are extremely simple. It's the assignment > statement that's tricky: some assignments mutate/change objects, and > some only rebind names. > > > Does this mean there is not pass-values calling to a function in > > python? only pass-reference calling? Thanks! > > Neither is quite true. Values are passed by binding parameter names to > their corresponding arguments. This is similar to pass-by-reference in > some cases (when the argument is mutated) but not in others (when the > argument is not mutated). Thinking of it as pass-by-reference may help > you to understand it, but bear in mind that Python's "references" may > be rebound to new objects, which is quite different from the usual > behavior of references. > > -- > Neil Cerutti So basically the scope is the reason for confusion a lot of the time? def some_name(): alist = [5] bint = 5 cstring = '5' ddictionary = {0:5} def other_name(alist, bint, cstring, ddictionary): alist = 4 bint = 4 cstring = '4' ddictionary = 4 print "other_name:", print alist, bint, cstring, ddictionary def another_name(alist, bint, cstring, ddictionary): alist[0] = 3 # bint cannot be changed it is immutable # cstring cannot be changed it is immutable ddictionary[0] = 3 print "another_name:", print alist, bint, cstring, ddictionary another_name(alist, bint, cstring, ddictionary) other_name(alist, bint, cstring, ddictionary) print "our entries are now:", print alist, bint, cstring, ddictionary From jokersmith at comcast.net Wed Jan 9 22:18:57 2008 From: jokersmith at comcast.net (Josh) Date: Wed, 9 Jan 2008 22:18:57 -0500 Subject: help with a problem from school?? Message-ID: Hello all I did a Google search and found this site and was hoping someone could help me with what I am sure is a simple question that I cannot figure out. Here goes: Given a simple straight through switch (SPST) with a supply of 14V, and the need to simulate its intended load of 14mA, what would you use to simulate this load? Please show your calculations used to support your answer. I appreciate anyone's help. Josh Smith jokersmith at comcast.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From bkamrani at gmail.com Tue Jan 15 20:21:02 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Tue, 15 Jan 2008 17:21:02 -0800 (PST) Subject: login to https (newbie) Message-ID: Hi Python gurus! Please help me how I can login to this page: https://www.boplats.se/user/login_hs.aspx?ReturnUrl=/HSS/Default.aspx I tried these two codes, but I don't seem to be successfull at all. (Both gave same result.) Many many thanks, /Ben ----------- import urllib2,urllib,cookielib urll = "https://www.boplats.se/user/login_hs.aspx?ReturnUrl=/HSS/ Default.aspx" cj = cookielib.CookieJar() opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj)) data = urllib.urlencode ( { "username" : "myuser" , "password" :"mypass" } ) fp = opener.open( urll,data ) print fp.read() ------------ OR th second code ------------ import urllib2 as __urllib2 import base64 as __base64 #-------------------------------------------------------------- def download_file(url, webuser = None, webpass = None): request = __urllib2.Request(url) if webuser: base64string = __base64.encodestring('%s:%s' % (webuser, webpass))[:-1] request.add_header("Authorization", "Basic %s" % base64string) htmlFile = __urllib2.urlopen(request) htmlData = htmlFile.read() htmlFile.close() return htmlData #-------------------------------------------------------------- if __name__ == "__main__": # Test #***************************** __url = "https://www.boplats.se/user/login_hs.aspx?ReturnUrl=/HSS/ Default.aspx" __webuser = "myuser" __webpass = "mypass" print download_file(__url, __webuser, __webpass) #***************************** From t_spens at yahoo.com Thu Jan 24 12:28:09 2008 From: t_spens at yahoo.com (Tim Spens) Date: Thu, 24 Jan 2008 09:28:09 -0800 (PST) Subject: Beginner Pyserial Question Message-ID: <862889.8569.qm@web45111.mail.sp1.yahoo.com> COM = 0 #for COM1 BAUD = 115200 class serial_port(): def __init__(self): self.start_time = None self.end_time = None self.asleep_duration = None self.device = serial.Serial() self.device.timeout = 1 self.device.baudrate = BAUD self.device.port = COM a_serial_port = serial_port() a_serial_port.device.open() ----- Original Message ---- From: "JAMoore84 at gmail.com" To: python-list at python.org Sent: Thursday, January 24, 2008 10:13:39 AM Subject: Re: Beginner Pyserial Question > My guess is that for whatever reason the 'first' serial port > (which is what you're asking for by specifying a 0 when > instantiating the Serial class) doesn't actually exist. Serial > device names under Windows are broken. I realize this. I tried connecting to different port "numbers", but I have not tried the serial.Serial(COM1). I wasn't sure if that worked, but I know a quick way to find out. > Try using the actual name of the com port (e.g. 'COM3' or > 'COM5') instead of 0. The com port used in Hyper Terminal is COM40. I have tried connecting to 39/40/41 to no avail. > Oh, if you end up having to use a com port higher than COM9, > that's broken in Windows as well, and you've got to sprinkle a > bunch of backslashes into the device name (I don't remember the > exact syntax). That might become an issue when I try to read COM40 for the GPS bluetooth transmission. This issue does not relate to why I cannot open smaller com ports, though. -- http://mail.python.org/mailman/listinfo/python-list ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From halcyon1981 at gmail.com Fri Jan 25 00:21:59 2008 From: halcyon1981 at gmail.com (David Erickson) Date: Thu, 24 Jan 2008 21:21:59 -0800 (PST) Subject: Email module, how to add header to the top of an email? References: <97c04812-3b66-4d84-9e92-21de72a3ca56@c23g2000hsa.googlegroups.com> Message-ID: <088eeaff-8251-49a4-9202-a9481f5e8aaa@x69g2000hsx.googlegroups.com> On Jan 24, 2:41 pm, Martin Marcher wrote: > On Thursday 24 January 2008 20:32 David Erickson wrote: > > > I have been using the Email module and Message class for awhile, > > however I have been unable to find a way to add a header to the top of > > the email similar to what is done with Received: headers... the > > add_header method only appends to the bottom. Is there someway this > > can be done? > > if by bottom you mean added as the "new last" header than you don't have to > care, afaik email headers do not have a notion of order > > e.g > > To: b... at example.com > From: al... at example.com > > is equal to > > From: al... at example.com > To: b... at example.com > > if by bottom you mean it's appended to the body...well that is a problem :) > > hth > martin Bottom of the headers... but I am looking to insert at the top, and re- ordering/inserting does matter depending on what type of header you are, received headers for example must be inserted at the top of the header list so you can watch the progression of the email. I was unable to find a clean way to do this via the API which seems very strange to me.. but perhaps I am just missing something? Thanks, -David From paddy3118 at googlemail.com Sat Jan 5 01:50:31 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 4 Jan 2008 22:50:31 -0800 (PST) Subject: Skill Resume Achievements, What Good Goes Here? References: Message-ID: On Jan 2, 3:59 pm, vbgunz wrote: > I spent some time working on a skill resume, the kind of resume > college students put together and realized, I am not in college and > everything I learned was self-taught. Of course I would like some real > world achievements but don't consider throw-away code an achievement > and am failing to really see any. I don't even wish to entertain the > thought of lying about anything. > > What are some achievements an employer may be looking for in someone > willing to start at ground level, entry level, intern, etc? What are > some real world achievements every n00b will need under his/her belt > in order to be taken seriously? You need to have written code that you expect others to either read or use. Others have pointed out the benefits of contributing to an open source project but code to be read might include code posted to newsgroups in answer to questions, or your blog entries. If you have no code fit to be read then what is a potential employer to do? (Personally, a college student showing an appreciation of doctests would impress). - Paddy. From paddy3118 at googlemail.com Wed Jan 9 01:52:22 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 8 Jan 2008 22:52:22 -0800 (PST) Subject: Collecting Rich Data Structures for students References: Message-ID: On Jan 9, 2:19 am, "kirby.ur... at gmail.com" wrote: > Greetings Pythoneers -- > > Some of us over on edu-sig, one of the community actives, > have been brainstorming around this Rich Data Structures > idea, by which we mean Python data structures already > populated with non-trivial data about various topics such > as: periodic table (proton, neutron counts); Monty Python > skit titles; some set of cities (lat, long coordinates); types > of sushi. > > Obviously some of these require levels of nesting, say > lists within dictionaries, more depth of required. > > Our motivation in collecting these repositories is to give > students of Python more immediate access to meaningful > data, not just meaningful programs. Sometimes all it takes > to win converts, to computers in general, is to demonstrate > their capacity to handle gobs of data adroitly. Too often, > a textbook will only provide trivial examples, which in the > print medium is all that makes sense. > > Some have offered XML repositories, which I can well > understand, but in this case we're looking specifically for > legal Python modules (py files), although they don't have > to be Latin-1 (e.g. the sushi types file might not have a > lot of romanji). > > If you have any examples you'd like to email me about, > kirby.ur... at gmail.com is a good address. > > Here's my little contribution to the mix:http://www.4dsolutions.net/ocn/python/gis.py > > Kirby Urner > 4D Solutions > Silicon Forest > Oregon I would think there was more data out there formatted as Lisp S- expressions than Python data-structures. Wouldn't it be better to concentrate on 'wrapping' XML and CSV data- sources? - Paddy. From asmodai at in-nomine.org Thu Jan 3 08:55:24 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 3 Jan 2008 14:55:24 +0100 Subject: Treating a unicode string as latin-1 In-Reply-To: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> References: <95013707-a1cd-402b-81da-6e54bcca4ae1@h11g2000prf.googlegroups.com> Message-ID: <20080103135524.GM67953@nexus.in-nomine.org> -On [20080103 14:36], Simon Willison (simon at simonwillison.net) wrote: >How can I tell Python "I know this says it's a unicode string, but I >need you to treat it like a bytestring"? Although it does not address the exact question it does raise the issue how you are using ElementTree. When I use the following: test.xml Bob\x92s Breakfast parse.py from xml.etree.ElementTree import ElementTree xmlfile = open('test.xml') tree = ElementTree() tree.parse(xmlfile) elem = tree.find('name') print type(elem.text) I get a string type back and not a unicode string. However, if you are mixing encodings within the same file, e.g. cp1252 in an UTF8 encoded file, then you are creating a ton of problems. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ When moved to complain about others, remember that karma is endless and it is loving that leads to love... From JAMoore84 at gmail.com Thu Jan 24 12:45:25 2008 From: JAMoore84 at gmail.com (JAMoore84 at gmail.com) Date: Thu, 24 Jan 2008 09:45:25 -0800 (PST) Subject: Beginner Pyserial Question References: <93223c7c-c891-424c-bc4f-00d61592663a@l32g2000hse.googlegroups.com> <13phgpma9fb3cb8@corp.supernews.com> <50bf1637-0954-4d35-9c16-76c3b9aabe05@y5g2000hsf.googlegroups.com> Message-ID: I've solved the problem- Thanks for steering me in the right direction. The problem is that your traditional "COM1" does not exist on this computer (Thanks Grant). A trip to the Device manager listed all the COM ports on the computer. After successfully connecting to COM7 (port = serial.Serial(6)), I realized the reason I couldn't connect to COM40 was because it was tied up with hyper terminal. after closing everything, I was able to issue a readline and collect data. Thanks for the help! jimmy From gowricp at gmail.com Fri Jan 11 20:54:03 2008 From: gowricp at gmail.com (Gowri) Date: Fri, 11 Jan 2008 17:54:03 -0800 (PST) Subject: converting JSON to string References: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> <13og5g06rvrtefa@corp.supernews.com> Message-ID: Hi Adonis, Thanks so much. Appreciate it :) From david.hotham at blueyonder.co.uk Mon Jan 28 16:31:05 2008 From: david.hotham at blueyonder.co.uk (david.hotham at blueyonder.co.uk) Date: Mon, 28 Jan 2008 13:31:05 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Message-ID: <92b67efe-c437-40bc-89fc-bbdd85d6e718@s19g2000prg.googlegroups.com> I also had a go at this problem for a bit of python practice, about 6 months ago. I tried a few optimizations and my experience was that with only 6 seeds, a hash table was very effective. So effective, in fact, that it made all other optimizations more or less pointless. Code below. Arguments are seeds first, then targets. Like this: C:\utils>countdown.py 7 8 50 8 1 3 923 made target! 50 * 8 = 400 400 - 1 = 399 399 / 3 = 133 133 * 7 = 931 931 - 8 = 923 Took 0.421 seconds from time import time from bisect import insort from sys import argv #------------------------------------------------------------------------------ # Hash table is a global variable #------------------------------------------------------------------------------ global hash_table #------------------------------------------------------------------------------ # countdown.py # # Python script to solve the Countdown numbers game # # Remarks on optimization: # # - Without the hash table, the following all proved beneficial: # - Keep a list of numbers used so far, and never create a number that # you've already used # - Make sure only to return unique pairs from the generate_pairs function # - Don't ever perform two consecutive substractions # - (Don't ever perform two consecutive divisions would also be valid, # though it's not something that happens a lot so the benefit is small) # # - These tricks work by avoiding performing the same search more than once # # - With only six seeds, it's possible to implement a perfect hash table that # remembers every list that we try to solve (and indeed this is what the # implementation here does) # # - With that hash table, the optimizations above become largely redundant, so # for the sake of simplicity I've removed them # # - Solving for larger numbers of seeds would require a smarter approach, as # it would soon become infeasible to maintain a complete hash table. Then # the tricks above might be useful again. # #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # Returns all useful combinations of two numbers, and a string representing # the operation used to get there. #------------------------------------------------------------------------------ def generate_combinations(higher_number, lower_number): #-------------------------------------------------------------------------- # Useful operations are: # - addition (always) # - subtraction (of the lower number from the higher number, so long as # they are not equal) # - multiplication (so long as not multiplying by one) # - division (if it's exact, and not by one) #-------------------------------------------------------------------------- yield "+", higher_number + lower_number if (higher_number != lower_number): yield "-", higher_number - lower_number if (lower_number != 1): yield "*", higher_number * lower_number if ((higher_number % lower_number) == 0): yield "/", higher_number / lower_number #------------------------------------------------------------------------------ # Returns all pairs from a list of seeds. # # Pairs always have the first number lower than or equal to the second number, # provided that the list is ordered on entry (as it should be). #------------------------------------------------------------------------------ def generate_pairs(seeds): for ii in xrange(len(seeds)): for higher_num in seeds[ii+1:]: yield seeds[ii], higher_num #------------------------------------------------------------------------------ # Solves a seed list. Takes pairs, combines them, and recursively calls # solve_list again with the new shorter list. # # Seeds should be sorted on entry. #------------------------------------------------------------------------------ def solve_list(seeds, target, depth, solution_so_far): #-------------------------------------------------------------------------- # Loop through possible pairs. #-------------------------------------------------------------------------- for lower_num, higher_num in generate_pairs(seeds): #---------------------------------------------------------------------- # Make a copy of the list, and remove this pair. # # Taking a copy appears to be quicker than using the original list and # then reinstating the chosen pair later. #---------------------------------------------------------------------- new_seeds = seeds[:] new_seeds.remove(lower_num) new_seeds.remove(higher_num) #---------------------------------------------------------------------- # Try out all possible combinations of our pair. #---------------------------------------------------------------------- for operation, combination in generate_combinations(higher_num, lower_num): #------------------------------------------------------------------ # If we hit our target, we're happy. # # Else if the list has gotten too short already, move on. # # Else make a new, shorter, list containing our new value. # # If we've already tried to solve the new list, there's no point in # trying again. # # Else try to solve the shorter list. #------------------------------------------------------------------ if combination == target: print "made target!" print "%s%d %s %d = %d\n" % (solution_so_far, higher_num, operation, lower_num, combination) return(0) elif (depth > 0): insort(new_seeds, combination) seeds_tuple = tuple(new_seeds) if (seeds_tuple in hash_table): pass else: hash_table[seeds_tuple] = 1 new_soln_so_far = ("%s%d %s %d = %d\n" % (solution_so_far, higher_num, operation, lower_num, combination)) if (solve_list(new_seeds, target, depth - 1, new_soln_so_far) == 0): #------------------------------------------------------ # Success! #------------------------------------------------------ return(0) #-------------------------------------------------------------- # Remove the value that we made out of our number pair, in # preparation for the next try. #-------------------------------------------------------------- new_seeds.remove(combination) #-------------------------------------------------------------------------- # Didn't solve it. #-------------------------------------------------------------------------- return(1) #------------------------------------------------------------------------------ # OK, let's go. Get the puzzle, and solve it. The last argument is the target # and the others are the seeds. #------------------------------------------------------------------------------ original_seeds = map(int, argv[1:-1]) target = int(argv[-1]) start_time = time() failed = 1; if target in original_seeds: print "Target is amongst seeds!" else: original_seeds.sort() #-------------------------------------------------------------------------- # First look for one-step solutions, then for two-step solutions, etc. # That way we always get a shortest solution first. #-------------------------------------------------------------------------- for depth in xrange(len(original_seeds)): hash_table = {} failed = solve_list(original_seeds, target, depth, "") if (failed == 0): break if (failed != 0): print "No solution!" print "Took %.3f seconds" % (time() - start_time) From David.Reksten at sweco.no Thu Jan 10 06:43:09 2008 From: David.Reksten at sweco.no (David.Reksten at sweco.no) Date: Thu, 10 Jan 2008 12:43:09 +0100 Subject: SV: Conventions for dummy name In-Reply-To: <87sl1613c8.fsf@physik.rwth-aachen.de> References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de><873at6k2qt.fsf_-_@benfinney.id.au> <87sl1613c8.fsf@physik.rwth-aachen.de> Message-ID: <6A539E6F80E48B40A81F5169256139D301D98242@srvmail02.nettverk.int> Torsten Bronger wrote: >Hall?chen! > >Ben Finney writes: > >> "Diez B. Roggisch" writes: >> >>> The underscore is used as "discarded" identifier. So maybe >>> >>> for _ in xrange(10): >>> ... >> >> The problem with the '_' name is that it is already well-known and >> long-used existing convention for an entirely unrelated purpose: >> in the 'gettext' i18n library, the '_' function to get the >> locally-translated version of a text string. > >Right, that's because I've used "__" where not all returning values >are interesing to me such as > >a, b, __ = function_that_returns_three_values(x, y) Variable name "dummy" serves the same purpose, such as: a, b, dummy = function_that_returns_three_values(x, y) According to http://linux.die.net/man/1/pylint it is also possible to use the option --dummy-variables-rgx= to further specify which variable not to report as unused. As far as I can tell, it defaults to '_|dummy'. .david From arnodel at googlemail.com Wed Jan 23 18:51:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 23 Jan 2008 15:51:10 -0800 (PST) Subject: Creating new types and invoking super References: <57f9e9a0-725a-4ad1-be22-1f14a2e1c453@q21g2000hsa.googlegroups.com> Message-ID: <9eeb9667-f362-4ce2-971a-42ef639c8f86@c4g2000hsg.googlegroups.com> On Jan 23, 10:18?pm, "Guilherme Polo" wrote: > 2008/1/23, Arnaud Delobelle : > > > The only way I can think of would be to create a metaclass, but I > > don't think it's worth it. ?super(A, obj).__init__() isn't that bad! > > Metaclass doesn't apply here because metaclass is related to > class-construction. This is related to instance initialization, and > I'm creating the types as the user asks. Not completely clear to me what you want but here is a 'proof of concept': ========== class callsuper(object): def __init__(self, f): self.f = f def __get__(self, obj, cls=None): def newfunc(*args, **kwargs): super(self.cls, obj).__init__() return self.f(obj, *args, **kwargs) return newfunc class Type(type): def __init__(self, name, bases, attrs): for attrname, attr in attrs.iteritems(): if isinstance(attr, callsuper): attr.cls = self class A: __metaclass__ = Type def __init__(self): print "init A" class B(A): @callsuper def __init__(self): print "init B" ========== >>> b=B() init A init B From arnodel at googlemail.com Wed Jan 9 15:52:24 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 9 Jan 2008 12:52:24 -0800 (PST) Subject: Another dumb scope question for a closure. References: Message-ID: On Jan 9, 8:24?pm, Mike Meyer wrote: > On Wed, 9 Jan 2008 13:47:30 -0500 (EST) "Steven W. Orr" wrote: > > > > > So sorry because I know I'm doing something wrong. > > > 574 > cat c2.py > > #! /usr/local/bin/python2.4 > > > def inc(jj): > > ? ? ?def dummy(): > > ? ? ? ? ?jj = jj + 1 > > ? ? ? ? ?return jj > > ? ? ?return dummy > > > h = inc(33) > > print 'h() = ', h() > > 575 > c2.py > > h() = > > Traceback (most recent call last): > > ? ?File "./c2.py", line 10, in ? > > ? ? ?print 'h() = ', h() > > ? ?File "./c2.py", line 5, in dummy > > ? ? ?jj = jj + 1 > > UnboundLocalError: local variable 'jj' referenced before assignment > > > I could have sworn I was allowed to do this. How do I fix it? > > Nope. This is one of the things that makes lisper's complain that > Python doesn't have "real closures": you can't rebind names outside > your own scope (except via global, which won't work here). Note that the 'nonlocal' keyword solves this problem in py3k: 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. >>> def inc(j): ... def f(): ... nonlocal j ... j += 1 ... return j ... return f ... >>> i = inc(3) >>> i() 4 >>> i() 5 >>> -- Arnaud From jzgoda at o2.usun.pl Wed Jan 23 04:12:07 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 23 Jan 2008 10:12:07 +0100 Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? In-Reply-To: References: Message-ID: Gary Herron napisa?(a): > However there *is* a (subtle) difference between > not f > and > (not f and 1) or 0 > > The first produces a boolean value, and the second produces an int > value, but since one is a subclass of the other, you'd have to write > quite perverse code care about the difference. Twisted sems to be perverted to the root. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From agnel.joel at gmail.com Sun Jan 6 01:01:19 2008 From: agnel.joel at gmail.com (Joel) Date: Sat, 5 Jan 2008 22:01:19 -0800 (PST) Subject: Boa constructor debugging - exec some code at breakpoint? Message-ID: <7f96223d-e5bd-4bbc-a242-75826eeb100a@d70g2000hsb.googlegroups.com> Hey there.. I'm using boa constructor to debug a python application. For my application, I need to insert break points and execute some piece of code interactively through shell or someother window when the breakpoint has been reached. Unfortunately the shell I think is a seperate process so whatever variables are set while executing in debugger dont appear in the shell when I try to print using print statement. Can anyone tell me how can I do this? Really appreciate any support, Thanks Joel P.S. Please CC a copy of reply to my email ID if possible. From gagsl-py2 at yahoo.com.ar Tue Jan 22 19:49:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 Jan 2008 22:49:30 -0200 Subject: Submitting with PAMIE References: <04c92035-4b27-467d-87b7-86665e09072f@e10g2000prf.googlegroups.com> Message-ID: En Tue, 22 Jan 2008 15:39:33 -0200, escribi?: > Hi I really need help. I've been looking around for an answer forever. > I need to submit a form with no name and also the submit button has no > name or value. How might I go about doing either of these. Thanks I think you'll have more luck in a specific forum like the PAMIE User Group at http://tech.groups.yahoo.com/group/Pamie_UsersGroup/ -- Gabriel Genellina From israelu at elbit.co.il Tue Jan 15 04:43:22 2008 From: israelu at elbit.co.il (iu2) Date: Tue, 15 Jan 2008 01:43:22 -0800 (PST) Subject: print >> to a derived file Message-ID: Hi, I'm trying to write data to both a file and the console, so I did: class File_and_console(file): def write(self, s): file.write(self, s) print s, >>> f = File_and_console('1.txt', 'w') >>> f.write('hello') hello >>> print >>f, 'world' >>> the 'write' method works, but 'print >>' doesn't, it writes only to the file. It doesn't actually call File_and_console.write Why? How can I fix it? Thanks iu2 From asmodai at in-nomine.org Wed Jan 2 07:42:18 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 2 Jan 2008 13:42:18 +0100 Subject: Extracting files from an ISO image? In-Reply-To: <34a84caa-5387-40a2-a808-5e7bd325023e@w47g2000hsa.googlegroups.com> References: <34a84caa-5387-40a2-a808-5e7bd325023e@w47g2000hsa.googlegroups.com> Message-ID: <20080102124218.GC67953@nexus.in-nomine.org> -On [20080102 13:11], Ant (antroy at gmail.com) wrote: >2) Is there a module out there for extracting icons from a Windows >exe? This might be a good start: http://groups.google.com/group/comp.lang.python/browse_thread/thread/be829b454c945a89 -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ When you meet a master in the street, do not speak, do not be silent. Then how will you greet him? From arnodel at googlemail.com Thu Jan 17 22:15:55 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 17 Jan 2008 19:15:55 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> <48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com> <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com> <478f8472$0$24708$426a74cc@news.free.fr> <7806d19b-0ce9-421a-b0bc-c196d82a2f3a@s12g2000prg.googlegroups.com> <657961e1-44ce-4fef-b3b7-5662878f28d8@f47g2000hsd.googlegroups.com> Message-ID: <5c1818a6-b96b-4dce-a2f4-1f9dfeda4c01@l32g2000hse.googlegroups.com> On Jan 17, 11:59?pm, Paul Hankin wrote: > Instead of counting the exceptions, we can limit the padding iterables > by using an iterator that returns len(iterables) - 1 padding > generators, use a sort of lazy chain, and then just izip. > > from itertools import izip, repeat > > def chain_next(xs, yg): > ? ? for x in xs: yield x > ? ? for y in yg.next(): yield y > > def izippad(*xs, **kw): > ? ? padder = repeat(kw.get('padding', None)) > ? ? padder_gen = repeat(padder, len(xs) - 1) > ? ? return izip(*[chain_next(x, padder_gen) for x in xs]) I have had the need for such a 'padded zip' before and my implementation was eerily similar: from itertools import repeat, chain, izip def repeatnext(iterator): val = iterator.next() while True: yield val def longzip(default, *iterables): defaultgen = repeat(default, len(iterables) - 1) return izip(*[chain(it, repeatnext(defaultgen)) for it in iterables]) -- Arnaud From sromero at gmail.com Mon Jan 21 02:41:13 2008 From: sromero at gmail.com (Santiago Romero) Date: Sun, 20 Jan 2008 23:41:13 -0800 (PST) Subject: Sorting a list depending of the indexes of another sorted list Message-ID: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> Hi ... I have the following DNS MX records info: domain.com preference 10 host mx1.domain.com preference 30 host anotherhost.domain.com preference 20 host mx2.domain.com I'm storing this info in 2 lists: preferences = [10, 30, 20] hosts = [ "mx1.domain.com", "anotherhost.domain.com", "mx2.domain.com"] (I was about to use a dict of preferences : domain, but it's possible to find 2 mx records with the same preference, so keys wouldnt be unique). I'm trying to sort both lists so that they end like this: preferences = [10, 20, 30] hosts = [ "mx1.domain.com", "mx2.domain.com", "anotherhost.domain.com" ] I want to sort hosts list depending on the numeric order of "preferences". And finally ... do you think there is a better python structure to store this data and sort it in a more easy way? Thanks. From donn.ingle at gmail.com Sun Jan 13 07:27:54 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 14:27:54 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <4789FE1C.9000002@v.loewis.de> References: <200801131351.59005.donn.ingle@gmail.com> <4789FE1C.9000002@v.loewis.de> Message-ID: <200801131427.54672.donn.ingle@gmail.com> > So on *your* system, today: what encoding are the filenames encoded in? > We are not talking about arbitrary files, right, but about font files? > What *actual* file names do these font files have? > > On my system, all font files have ASCII-only file names, even if they > are for non-ASCII characters. I guess I'm confused by that. I can ls them, so they appear and thus have characters displayed. I can open and cat them and thus the O/S can access them, but I don't know whether their characters are strictly in ascii-limits or drawn from a larger set like unicode. I mean, I have seen Japanese characters in filenames on my system, and that can't be ascii. You see, I have a large collection of fonts going back over 10 years and they came from usenet years ago and so have filenames mangled all to hell. I can't always *type* some of their names and have to use copy/paste to, for example, ls one of them. Again, it's working from ignorance (my own) : I assume filenames in different countries will be in character sets that I have never (nor will I ever) see. But I have to cover them somehow. > > Or is that a waste of time because os.listdir() has already tried > > something similar (and prob. better)? > "better" is a difficult notion here. Is it better to produce some > result, possibly incorrect, or is it better to give up? I think I see, combined with your previous advice - I will keep byte strings alongside unicode and where I can't get to the unicode for that string, I will keep an 'ignore' or 'replace' unicode, but I will still have the byte string and will access the file with that anyway. > If the user has set up his machine correctly: yes. Meaning, I am led to assume, the LANG variable primarily? \d From dg.google.groups at thesamovar.net Sun Jan 27 14:10:01 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Sun, 27 Jan 2008 11:10:01 -0800 (PST) Subject: explicit protocols and duck typing Message-ID: <5e28034f-a20f-4aa7-b299-9c9132ef2566@c4g2000hsg.googlegroups.com> Hi all, As I understand it, the idea behind duck typing is that you just take an object and if it has the methods you want to use you use it assuming it to be the right type of object. I'm interested in extending this idea a bit, but I feel the sort of thing I have in mind has already been thought of. So for example, in the program I'm writing a 'state variable' specifier can be either an integer or a string (the string name is mapped to an integer by another function getvarindex(name)). In this case, I can't do duck typing by seeing if the object has a method or not, because both of the types are built in types. I don't want to have to force the user to have objects like StateVariableSpecifier(name). Now at the moment, what I'm doing is accepting anything as a state variable specifier, and just passing it through the getvarindex function when I want to use it. This sort of specifies a protocol for state variable specifiers without making it explicit (like the sequence or mapping protocols built in to Python). What I'm wondering though is whether there is any value in making this more explicit? Say, have a class which makes explicit the various relationships involved, such as that the type of a state variable specifier can be correct or incorrect (it has to be an int or a string), that the value has to be correct (the integer has to be between 0 and n for some n, and the string has to be in a dict of names), and that there is a relationship between state variable specifiers (int, string) and the underlying data type (the index of the variable in an array). Making it more explicit seems like a good idea, the question is in what way to make it more explicit. I can make it explicit just by documenting the behaviour, or I can make it explicit by adding code that enforces certain ways of using things. For this simple example, it seems like just documenting it is the best route, but I have similar issues with other more complicated parts of the code. At the moment, a model for instance can be a Model object, an Equation object or a tuple of functions, but this could be subject to change in the future. The issue I want to address is the long term maintainability of the code when possibly many people might be contributing, the transparency for other users, and the ease of documenting it. Any opinions? Dan Goodman From steven at REMOVE.THIS.cybersource.com.au Wed Jan 9 21:10:56 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 10 Jan 2008 02:10:56 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: On Wed, 09 Jan 2008 21:26:05 +0100, Bruno Desthuilliers wrote: > hint: how can a compiler safely optimize anything in a language so > dynamic that even the class of an object can be changed at runtime ? Is that a trick question? By finding things to optimize that *can't* change at runtime. E.g. a keyhole optimizer that detects when you write something like this: def foo(): x = 1 + 2 return x and optimizes it to this: >>> import dis >>> dis.dis(foo) 2 0 LOAD_CONST 3 (3) 3 STORE_FAST 0 (x) 3 6 LOAD_FAST 0 (x) 9 RETURN_VALUE (Only in CPython version 2.5 or better.) Okay, okay, so constant folding isn't going to save you a lot of time (unless your constant is being re-calculated millions of times) but it's still an optimization. There are others, some have been done (e.g. optimize away the quadratic behaviour for string concatenation in some limited cases), some are possible but rejected by the BDFL (e.g. tail- call optimization), presumably there are some possible but not yet implemented or even discovered (which is the point of the PyPy project). You are correct that optimizing Python is hard. However, in many cases, the problem is not that Python is too slow, but the specific algorithm chosen by the programmer is slow, e.g. no compiler optimization is going to turn an O(n**2) algorithm into an O(1) algorithm. The Original Poster says it takes one or two seconds to process an 800x600 GIF. That sounds believable: on my PC, it takes about five seconds to loop over range(800*600) and do a tiny bit of processing. Something like Psycho might speed that up a lot, possibly by an order of magnitude or two. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Jan 17 21:59:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 18 Jan 2008 02:59:16 -0000 Subject: "Code Friendly" Blog? References: <0fd979c6-5a11-4989-9438-51a7b20ecd23@n20g2000hsh.googlegroups.com> Message-ID: <13p05g42jckem5d@corp.supernews.com> On Thu, 17 Jan 2008 16:18:37 -0800, Hai Vu wrote: > On Jan 17, 2:50 pm, Miki wrote: >> Hello, >> >> Posting code examples to blogger.com hosted blog is not fun (need to >> remember alway escape < and >). >> Is there any free blog hosting that is more "code friendly" (easy to >> post code snippets and such)? >> >> Thanks, >> -- >> Miki http://pythonwise.blogspot.com > > how about bracketing your code in the
 tags?

And how will that help with the problem the Original Poster asked about?



-- 
Steven



From lists at cheimes.de  Wed Jan  2 03:41:00 2008
From: lists at cheimes.de (Christian Heimes)
Date: Wed, 02 Jan 2008 09:41:00 +0100
Subject: os.tmpfile()
In-Reply-To: <32714577.240331199246555557.JavaMail.root@hrndva-web18-z01>
References: <32714577.240331199246555557.JavaMail.root@hrndva-web18-z01>
Message-ID: <477B4E1C.7040401@cheimes.de>

jyoung79 at kc.rr.com wrote:
> Can anyone elaborate on how 'os.tmpfile()' works?  I was thinking it would create some sort of temporary file I could quickly add text too and then when I was finished would automatically get rid of it.  Here's my questions:

Please don't use os.tmpfile(). It's not safe and exists only for legacy
reasons. The tempfile module contains methods to create safe temporary
files and directories.

Christian


From steve at holdenweb.com  Thu Jan 31 06:09:21 2008
From: steve at holdenweb.com (Steve Holden)
Date: Thu, 31 Jan 2008 06:09:21 -0500
Subject: Design question - Sharing of single object by multiple processes
In-Reply-To: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com>
References: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com>
Message-ID: <47A1AC61.7080007@holdenweb.com>

Mike D wrote:
> Hello, I've just picked up the Python language and am really enjoying it.
> 
> I've just signed up to this mailing list and I'm looking forward to 
> taking part in some discussions.
> 
> My first post is a question I've been pondering for the last couple of days:
> 
> For relatively static data (such as a list), is it possible to load a 
> single instance and have many python processes access it?
> 
First there's the problem of having multiple processes access any kind 
of shared resource. So your question makes me wonder whether you mean 
processes, or threads. Are you *sure* you mean processes?

> I want to have an object in memory. This object will be loaded on 
> application start up and will contain a list of objects. These will be 
> obtained from (most likely) the file system.
> 
So "application startup" is different from "process startup"? Your 
application is a group of co-operating processes? Really?

> My reasoning is: I want to prevent a file system or database fetch each 
> time as it seems unnecessary.
> 
It might also seem unnecessary to start the Python interpreter for each 
process, but you are going to have to ...

> Is this possible? In Java I'm pretty sure this could implemented with an 
> object factory and static methods. My understanding is that python 
> invokes a separate process for each request however.
> 
Your understanding is clearly informed by some information you have 
omitted to share with us.

> If possible, what would be a good way of providing a new structure as it 
> is updated.
> 
> If anyone could give me some advice or point me in the correct direction 
> I'd really appreciate it.
> 
> Thanks in advance,
> 
More answers, please. There are mechanisms such as Pyro (Python remote 
objects) that allow inter-process method calls, but I am far from 
convinced that's what you really want (or need, anyway). Perhaps yo 
could let us know a little more about what it really is you are trying 
to do, and convince me, at least, that this isn't just a case of 
premature optimization.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/


From JO3chiang at gmail.com  Mon Jan  7 20:33:01 2008
From: JO3chiang at gmail.com (jo3c)
Date: Mon, 7 Jan 2008 17:33:01 -0800 (PST)
Subject: Python's great, in a word
References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com>
Message-ID: <0bc9c789-64f4-4656-8c1b-b9343c117240@s19g2000prg.googlegroups.com>

On Jan 7, 9:09 pm, MartinRineh... at gmail.com wrote:
> I'm a Java guy who's been doing Python for a month now and I'm
> convinced that
>
> 1) a multi-paradigm language is inherently better than a mono-paradigm
> language
>
> 2) Python writes like a talented figure skater skates.
>
> Would you Python old-timers try to agree on a word or two that
> completes:
>
> The best thing about Python is _______.
>
> Please, no laundry lists, just a word or two. I'm thinking "fluid" or
> "grace" but I'm not sure I've done enough to choose.

skimpythong!!


From george.sakkis at gmail.com  Tue Jan 15 18:53:51 2008
From: george.sakkis at gmail.com (George Sakkis)
Date: Tue, 15 Jan 2008 15:53:51 -0800 (PST)
Subject: Data mapper - need to map an dictionary of values to a model
References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com>
Message-ID: <2d59f289-2def-43a8-93b7-f326b8f12066@z17g2000hsg.googlegroups.com>

On Jan 14, 7:56 pm, Luke  wrote:

> I am writing an order management console. I need to create an import
> system that is easy to extend. For now, I want to accept an dictionary
> of values and map them to my data model. The thing is, I need to do
> things to certain columns:
>
> - I need to filter some of the values (data comes in as YYYY-MM-
> DDTHH:MM:SS-(TIMEZONE-OFFSET) and it needs to map to Order.date as a
> YYYY-MM-DD field)
> - I need to map parts of an input column to more than one model param
> (for instance if I get a full name for input--like "John Smith"--I
> need a function to break it apart and map it to
> Order.shipping_first_name and Order.shipping_last_name)
> - Sometimes I need to do it the other way too... I need to map
> multiple input columns to one model param (If I get a shipping fee, a
> shipping tax, and a shipping discount, I need them added together and
> mapped to Order.shipping_fee)
>
> I have begun this process, but I'm finding it difficult to come up
> with a good system that is extensible and easy to understand. I won't
> always be the one writing the importers, so I'd like it to be pretty
> straight-forward. Any ideas?
>
> Oh, I should also mention that many times the data will map to several
> different models. For instance, the importer I'm writing first would
> map to 3 different models (Order, OrderItem, and OrderCharge)
>
> I am not looking for anybody to write any code for me. I'm simply
> asking for inspiration. What design patterns would you use here? Why?

The specific transformations you describe are simple to be coded
directly but unless you constrain the set of possible transformations
that can take place, I don't see how can this be generalized in any
useful way. It just seems too open-ended.

The only pattern I can see here is breaking down the overall
transformation to independent steps, just like the three you
described. Given some way to specify each separate transformation,
their combination can be factored out. To illustrate, here's a trivial
example (with dicts for both input and output):

class MultiTransformer(object):
    def __init__(self, *tranformers):
        self._tranformers = tranformers

    def __call__(self, input):
        output = {}
        for t in self._tranformers:
            output.update(t(input))
        return output

date_tranformer = lambda input: {'date' : input['date'][:10]}
name_tranformer = lambda input: dict(
                           zip(('first_name', 'last_name'),
                           input['name']))
fee_tranformer = lambda input: {'fee' : sum([input['fee'],
                                             input['tax'],
                                             input['discount']])}
tranformer = MultiTransformer(date_tranformer,
                              name_tranformer,
                              fee_tranformer)
print tranformer(dict(date='2007-12-22 03:18:99-EST',
                      name='John Smith',
                      fee=30450.99,
                      tax=459.15,
                      discount=985))
# output
#{'date': '2007-12-22', 'fee': 31895.140000000003,
  'first_name': #'J', 'last_name': 'o'}


You can see that the MultiTransformer doesn't buy you much by itself;
it just allows dividing the overall task to smaller bits that can be
documented, tested and reused separately. For anything more
sophisticated, you have to constrain what are the possible
transformations that can happen. I did something similar for
transforming CSV input rows (http://pypi.python.org/pypi/csvutils/) so
that it's easy to specify 1-to-{0,1} transformations but not 1-to-many
or many-to-1.

HTH,
George


From peng.kyo at gmail.com  Wed Jan 16 01:51:10 2008
From: peng.kyo at gmail.com (J. Peng)
Date: Wed, 16 Jan 2008 14:51:10 +0800
Subject: no pass-values calling?
In-Reply-To: 
References: 
	<13or6esikdrqa33@corp.supernews.com>
	
	
Message-ID: <18c1e5f20801152251q5fcb2dd5ne55db03b10750ddb@mail.gmail.com>

On Jan 16, 2008 2:30 PM, Steven D'Aprano
 wrote:
> On Wed, 16 Jan 2008 13:59:03 +0800, J. Peng wrote:
>
> > Hi,
> >
> > How to modify the array passed to the function? I tried something like
> > this:
> >
> >>>> a
> > [1, 2, 3]
> >>>> def mytest(x):
> > ...   x=[4,5,6]
>
>
> This line does NOT modify the list [1, 2, 3]. What it does is create a
> new list, and assign it to the name "x". It doesn't change the existing
> list.
>

Sounds strange.
In perl we can modify the variable's value like this way:

$ perl -le '
> $x=123;
> sub test {
>     $x=456;
> }
> test;
> print $x '
456


From gagsl-py2 at yahoo.com.ar  Tue Jan 29 18:06:23 2008
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Tue, 29 Jan 2008 21:06:23 -0200
Subject: object vs class oriented -- xotcl
References: 
	
	<2dfb6cd3-921a-4692-9627-d35bda40a93e@v29g2000hsf.googlegroups.com>
Message-ID: 

En Tue, 29 Jan 2008 16:22:24 -0200, William Pursell  
 escribi?:

> I'm fairly excited at the idea of being able to
> do per-object mixins in xotcl.  I guess it would
> look like this in python:
>
> BROKEN CODE:
> a = object()
> a.__class__.append( foo )
> a.__class__.append( bar )
>
> In python, if you want an object to me a member
> of 2 classes, it seems that you have no choice but
> to declare a new class that inherits from both.  eg:
>
> class foobar( foo, bar):
>   pass
> a = foobar()
>
> Is it possible to make an object be a member
> of 2 classes without defining such a class?  I
> believe "per object mixin" is the correct
> term for such an animal.  The first several google
> hits on that phrase all reference xotcl, so I'm
> not sure if that is an xotcl inspired vocabulary
> that isn't really standard.

No, an instance can be of only one class at a time. But you can generate  
dynamically the foobar class:
foobar = type("foobar", (foo,bar), {})
and provided `a` is an instance of any other user defined class (not bare  
object), this works:
a.__class__ = foobar
Or simply a = foobar()

If you are going to use this heavily, I suggest a "class cache" in order  
to avoid creating as many classes.

-- 
Gabriel Genellina



From services.wosg at gmail.com  Thu Jan 17 09:52:48 2008
From: services.wosg at gmail.com (WOSG Services)
Date: Thu, 17 Jan 2008 06:52:48 -0800 (PST)
Subject: Boost your business with Quality Web & Design Services at Bargain 
	Prices!
Message-ID: 

Web Outsourcing Services Group (WOSG) is a pioneering and China-based
service provider, committed to delivering quality web & design, SEO
and internet marketing services to clients around the world.

WOSG's strength lies in our skillful staff and lower rates in China.
We have over 60 strictly selected designers and programmers; many of
our designers come from China's top design and web companies, who
conduct design work for famous international brands like Sony, Nike,
Lenovo, L'Oreal etc. In addition, A dedicated Customer Service
Assistant will be assigned to each client as a single point of
contact. Our aim is to help our customers harness the power of
outsourcing and take advantage of China's quality brainpower via our
services.

The rates for our professional services start from as low as $9 per
hour. Quality services at bargain prices, Best value for money!

We can provide following services for your business:

Custom Website Design & Redesign
Graphic and Multimedia Design (Logo,Banner, Flash, etc)
Web Application Development
Search Engine Optimization & Internet Marketing

We have served many clients like you around the world. Although we
are
not the cheapest service provider on the internet, we do work hard to
balance quality and cost therefore maximizes your Return of
Investment.

You can learn more about us by downloading our flyer in PDF format
at:
http://www.WebOutsourcingServices.com/images/WOSG-Brochure-Sheet.pdf
You can also read our case study and browse our portfolio at
http://www.WebOutSourcingServices.com

Contact us via E-mail: Services at WebOutSourcingServices.com

Note: please don't reply this messeage since it is an automatic mail


From ggpolo at gmail.com  Wed Jan 16 14:56:06 2008
From: ggpolo at gmail.com (Guilherme Polo)
Date: Wed, 16 Jan 2008 17:56:06 -0200
Subject: paramiko
In-Reply-To: <685fabb3-c9e8-47ac-84f2-405b831bccad@v4g2000hsf.googlegroups.com>
References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp>
	
	<8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com>
	
	<8ceaad4c-c725-4093-a204-ab09162d4629@c23g2000hsa.googlegroups.com>
	
	<685fabb3-c9e8-47ac-84f2-405b831bccad@v4g2000hsf.googlegroups.com>
Message-ID: 

2008/1/16, Tarun Kapoor :
> On Jan 16, 12:22 pm, "Guilherme Polo"  wrote:
> > 2008/1/16, Tarun Kapoor :
> >
> >
> >
> > > On Jan 16, 11:38 am, "Guilherme Polo"  wrote:
> > > > 2008/1/16, Tarun Kapoor :
> >
> > > > >     # now, connect and use paramiko Transport to negotiate SSH2 across
> > > > > the connection
> > > > >     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > > > >     sock.connect((hostname, port))
> >
> > > > >     t = paramiko.Transport(sock)
> > > > >     t.start_client()
> > > > >     key = t.get_remote_server_key()
> >
> > > > >     event = threading.Event()
> > > > >     t.auth_password(username=username, password=password, event=event)
> > > > >     event.wait()
> >
> > > > >     if not t.is_authenticated():
> > > > >         print "not authenticated"
> >
> > > > > output:
> > > > > not authenticated
> >
> > > > This is a different problem I guess, now you are usin get_remote_server_key.
> > > > And why are you creating event after calling start_client without
> > > > specifying it ?
> >
> > > > > On Jan 16, 11:11 am, "Guilherme Polo"  wrote:
> > > > > > 2008/1/16, Tarun Kapoor :
> >
> > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to
> > > > > > > the remote server using an SFTP client I have just to make sure that
> > > > > > > username and password are working.. This is the code.
> >
> > > > > > >     # now, connect and use paramiko Transport to negotiate SSH2 across the
> > > > > > > connection
> >
> > > > > > >     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> >
> > > > > > >     sock.connect((hostname, port))
> >
> > > > > > >     t = paramiko.Transport(sock)
> >
> > > > > > >     event = threading.Event()
> >
> > > > > > >     t.start_client(event)
> >
> > > > > > >     event.wait(15)
> >
> > > > > > >     if not t.is_active():
> >
> > > > > > >         print 'SSH negotiation failed.'
> >
> > > > > > >         sys.exit(1)
> >
> > > > > > >     else:
> >
> > > > > > >         print "SSH negotiation sucessful"
> >
> > > > > > >     event.clear()
> >
> > > > > > >     t.auth_password(username=username, password=password,event=event)
> >
> > > > > > >     if not t.is_authenticated():
> >
> > > > > > >         print "not authenticated"
> >
> > > > > > > output:
> >
> > > > > > > SSH negotiation successful
> >
> > > > > > > not authenticated
> >
> > > > > > > Tarun
> >
> > > > > > > Waterstone Capital Management
> >
> > > > > > > 2 Carlson Parkway, Suite 260
> >
> > > > > > > Plymouth, MN 55447
> >
> > > > > > > Direct: 952-697-4123
> >
> > > > > > > Cell:    612-205-2587
> > > > > > >  Disclaimer This e-mail and any attachments is confidential and intended
> > > > > > > solely for the use of the individual(s) to whom it is addressed. Any views
> > > > > > > or opinions presented are solely those of the author and do not necessarily
> > > > > > > represent those of Waterstone Capital Management, L.P and affiliates. If you
> > > > > > > are not the intended recipient, be advised that you have received this
> > > > > > > e-mail in error and that any use, dissemination, printing, forwarding or
> > > > > > > copying of this email is strictly prohibited. Please contact the sender if
> > > > > > > you have received this e-mail in error. You should also be aware that
> > > > > > > e-mails are susceptible to interference and you should not assume that the
> > > > > > > contents of this e-mail originated from the sender above or that they have
> > > > > > > been accurately reproduced in their original form. Waterstone Capital
> > > > > > > Management, L.P. and affiliates accepts no responsibility for information,
> > > > > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt,
> > > > > > > please verify the authenticity with the sender.
> > > > > > > --
> > > > > > >http://mail.python.org/mailman/listinfo/python-list
> >
> > > > > > You are missing an event.wait() after t.auth_password.
> > > > > > Also, why are you passing this magic value "15" to event.wait() ? That
> > > > > > parameter is passed to class _Verbose to indicate if debug messages
> > > > > > should be displayed or not, so typical values would be 0/1 or
> > > > > > False/True.
> >
> > > > > > --
> > > > > > -- Guilherme H. Polo Goncalves
> >
> > > > > --
> > > > >http://mail.python.org/mailman/listinfo/python-list
> >
> > > > --
> > > > -- Guilherme H. Polo Goncalves
> >
> > > ok here is the problem... I don't know what is the correct way... The
> > > only demos i have from the paramiko library use a hostkeyfile. since i
> > > don't have that i thought i would use the get_remote_key to get the
> > > key and then connect it using the code in the demo.. But clearly
> > > nothing is working...I should not HAVE to use the key since i should
> > > be able to authenticate using the password...
> >
> > > Can you please suggest the right way to go ?
> >
> > You don't need to use key to authenticate using username and password,
> > indeed. And you don't. Your first email was almost correct, you just
> > needed to add event.wait() after t.auth_password. It worked here after
> > doing that change. You can check out my version:
> >
> > import sys
> > import socket
> > import paramiko
> > import threading
> >
> > if len(sys.argv) != 4:
> >     print "%s hostname user password" % sys.argv[0]
> >     sys.exit(1)
> >
> > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > sock.connect((sys.argv[1], 22))
> >
> > t = paramiko.Transport(sock)
> > event = threading.Event()
> > t.start_client(event)
> >
> > event.wait()
> >
> > if not t.is_active():
> >     print 'SSH negotiation failed.'
> >     sys.exit(1)
> > else:
> >     print "SSH negotiation sucessful"
> >
> > event.clear()
> > t.auth_password(username=sys.argv[2], password=sys.argv[3], event=event)
> > event.wait()
> > if not t.is_authenticated():
> >     print "Authentication failed."
> > else:
> >     print "Authenticated!"
> >
> > t.close()
> >
> >
> >
> > > Thanks for your time !
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
> >
> > --
> > -- Guilherme H. Polo Goncalves
>
> ok i tried the exact same code and here is the output
> SSH negotiation sucessful
> Authentication failed.
>
>
> I am positive that the username and paddword are correct. !

I believe paramiko supports only ssh2, so be sure to check if your
server is not running ssh1.

> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
-- Guilherme H. Polo Goncalves


From redawgts at gmail.com  Wed Jan  2 01:40:38 2008
From: redawgts at gmail.com (redawgts)
Date: Tue, 1 Jan 2008 22:40:38 -0800 (PST)
Subject: os.tmpfile()
References: 
Message-ID: <14af71a6-6847-42a5-b83c-24c3da41a51b@p69g2000hsa.googlegroups.com>

Try this:

>>> import os
>>> c = os.tmpfile()
>>> c.write('dude')
>>> c.seek(0)
>>> c.read()
'dude'


From bearophileHUGS at lycos.com  Wed Jan  2 16:28:47 2008
From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com)
Date: Wed, 2 Jan 2008 13:28:47 -0800 (PST)
Subject: Two candies
References: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com>
	
Message-ID: <736e51b5-d7f6-4523-89f1-df62256ce7c0@s19g2000prg.googlegroups.com>

First of all, thank you Raymond for your answer, and a happy new year
to you and to all the Python group :-)

Raymond:
>#3 is a fine choice.  It is memory efficient -- the repeat() itertool takes-up only a few bytes.  It doesn't need psyco, you already have to fast C routines talking to each other without having to go through the interpreter loop.<

In my code I have found otherwise, so to be more sure I have just done
few benchmarks on a Pentium3 CPU, 256 MB RAM, ActivePython 2.5.1.1, on
Win.

It may sound unfair, but I think it's useful to have some basic
reference timing, so I taken timings from a program written in D
language too (it's like a better C++ mixed with some Python and other
things), this is the D code:

import std.stdio, std.conv, std.string, std.c.stdlib, std.c.time;
void main(string[] args) {
    int n = toInt(args[1].replace("_", ""));
    auto t0 = clock();
    if (args[2].strip() == "1")
        auto a = new int[n];
    else
        auto a = cast(int*)calloc(n, int.sizeof);
    auto t1 = clock();
    writefln("%.2f s", (t1-t0)/cast(double)CLOCKS_PER_SEC);
}

As input it takes n and 1 or 2,
"Warm" timings:

     n      time-1  time-2
 1_000_000    0.04    0.04
10_000_000    0.44    0.42
30_000_000    1.32    1.26

In both cases the a array is initialized to all 0.
D "int" is 4 always bytes. The memory used by this little program is
essentially what you ask for, so it is 4 MB for n = 1 million, 40 MB
for n = 10 millions, and 120 MB for n = 30 millions (plus few other
small things, like the stack, etc. All the other extra memory is
probably less than 800 KB.).


This is the Python code, as input it takes n and 1, 2 or 3:

from array import array
from itertools import repeat
from time import clock
from sys import argv

def main():
    n = int(argv[1].replace("_", ""))
    choice = int(argv[2])
    assert choice in [1, 2, 3]

    if choice == 1:
        t0 = clock()
        a = array("l", xrange(n))
        t1 = clock()
    if choice == 2:
        t0 = clock()
        a = array("l", [0] * n)
        t1 = clock()
    if choice == 3:
        t0 = clock()
        a = array("l", repeat(0, n))
        t1 = clock()

    print round(t1 - t0, 2), "s"
    assert len(a) == n

main()


"Warm" timings:

Time (seconds):
     n         #1      #2      #3
 1_000_000   1.98    0.79    1.91
10_000_000  21.73    7.97   21.13
30_000_000  70.     28.55   65.3

Approximate peak MB RAM used:
     n        #1     #2      #3
 1_000_000     9   10.3     6.6
10_000_000    60   81      64
30_000_000   184  210+    200+

At runtime the Python interpreter plus other little things take some
memory, about 1.7 MB.
In the cases with the "+" sign the RAM was not enough, and I've had
swaps, so timings are probably different if you have more RAM (but I
think this benchmark is significant anyway, because IMHO an array of
integers of 120 MB isn't supposed to make your OS swap your 256 MB of
memory if you allocate it properly).
To me it seems that array("l",repeat(0,n)) eats lot of memory, and
it's quite slower than array("l",[0]*n) too. (I presume
array("l",repeat(0,n)) converts the python int 0 to the signed 4-byte
int over and over again...). So I belive still an allocate-like method
may be useful to the array object. It may allocate the data structure
with n=30 millions in probably less than 2 seconds. In the meantime
such arrays I presume I'll use an external numerical lib :-)

Bye,
bearophile


From python.list at tim.thechases.com  Wed Jan  9 15:12:24 2008
From: python.list at tim.thechases.com (Tim Chase)
Date: Wed, 09 Jan 2008 14:12:24 -0600
Subject: problem of converting a list to dict
In-Reply-To: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com>
References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com>
Message-ID: <47852AA8.4070206@tim.thechases.com>

> mylist=['','tom=boss','mike=manager','paul=employee','meaningless']
> 
> I'd like to remove the first and the last item as they are irrevalent,
> and convert it to the dict:
> {'tom':'boss','mike':'manager','paul':'employee'}
> 
> I tried this but it didn't work:
> 
> mydict={}
> for i in mylist[1:-1]:
> 	a=i.split('=')		# this will disect each item of mylist into a 2-item
> list
> 	mydict[a[0]]=a[1]
> 
> and I got this:
>   File "srch", line 19, in 
>     grab("a/tags1")
>   File "srch", line 15, in grab
>     mydict[mylist[0]]=mylist[1]
> IndexError: list index out of range

This can be rewritten a little more safely like

   mydict = dict(pair.split('=',1)
     for pair in mylist
     if '=' in pair)

Some of John Machin's caveats still apply:
(2) a[0] is empty or not what you expect (a person's name)
(3) a[1] is empty or not what you expect (a job title)
(consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = '
boss')
(4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...]

to which I'd add

(5) what happens if you have more than one equals-sign in your 
item?  ("bob=robert=manager" or "bob=manager=big-cheese")


#2 and #3 can be ameliorated a bit by

   import string
   mydict = dict(
     map(string.strip,pair.split('=',1))
     for pair in mylist
     if '=' in pair)

which at least whacks whitespace off either end of your keys and 
values.  #4 and #5 require a clearer definition of the problem.

-tkc




From cwitts at gmail.com  Fri Jan  4 02:27:55 2008
From: cwitts at gmail.com (Chris)
Date: Thu, 3 Jan 2008 23:27:55 -0800 (PST)
Subject: Problem reading csv files
References: <1788604d-5fed-435a-a9f3-f7e9f652b5a3@s12g2000prg.googlegroups.com>
Message-ID: <8e393f84-f0c1-4cd3-bd9e-a454cbebdd80@i29g2000prf.googlegroups.com>

On Jan 4, 6:24 am, Ramashish Baranwal 
wrote:
> Hi,
>
> I am trying to read a csv file using csv.reader. The file is created
> using Open Office and saved in Excel format.
>
> import csv
>
> reader = csv.reader(open('test.xls'))
> for row in reader:
>     print row
>
> It however throws the exception _csv.Error:
> : line contains NULL byte
>
> Any idea whats going wrong here?
>
> Thanks in advance,
> Ram

XLS != CSV
XLS is M$'s format for spreadsheets whereas CSV is essentially a text
document with comma-delimited fields.  If you open it up in OpenOffice
and go File -> Save As then in the 'Save as type:' drop-down list
select 'Text CSV (.csv)' and ofc change your code to point to the new
file.

If you want to retain it in XLS Format and rather parse that, take a
look at 'xlrd' and 'pyExcelerator'


From jgardner at jonathangardner.net  Thu Jan 24 16:30:37 2008
From: jgardner at jonathangardner.net (Jonathan Gardner)
Date: Thu, 24 Jan 2008 13:30:37 -0800 (PST)
Subject: Ignore exceptions
References: 
Message-ID: <8448fdcb-3ee5-4173-a841-0e844e54d9ba@e4g2000hsg.googlegroups.com>

On Jan 24, 12:13 pm, SMALLp  wrote:
> Hy. Is there any way to make interrupter ignore exceptions. I'm  working
> on bigger project and i used to put try catch blocks after writing and
> testing code what's boring and it's easy to make mistake. I remember of
> something like that in C++ but I cant find anythin like that for python.
>

Hello. Two points with exceptions.

* Only write try blocks when you are actually going to do something
interesting with the exception. Otherwise, let the exception bubble
up.

* If you have unwanted exceptions, fix the root cause of the exception
rather than try to hide the exception. The exception is saying
something is wrong and needs attention. Provide that attention.

I have seen too many people write code in Java that simply masks all
exceptions because they don't want to write the interface to their
functions that describes what exceptions are possible. I have seen
comments around this code saying, "This should always work." Of
course, it doesn't always work and when it doesn't work, they don't
know about it and they don't even know how to tell what went wrong.

The emotion driving this exception masking practice I see in the Java
world is laziness, not correctness. This is not the good form of
laziness (where you want to write good code so you end up doing less
work) but the bad form (where you don't want to work at all).

There is no need to mask exceptions in Python. In fact, it is more
work to mask exceptions, and you should feel bad about all the extra
typing you are doing.

Once again: All try blocks should do something interesting when they
catch an exception. No exception should be ignored or thrown away.

A few sample good uses of try/except blocks:

(1) Do something else if an expected exception occurs.

  try:
    # There is a good chance an exception will be thrown. If so, I
want to do something else.
    d['foo'] += 5
  except KeyError:
    d['foo'] = 5

(2) Show a friendly error message when an exception occurs over a
significant chunk of the program. (Useful for websites and GUI apps.)

  try:
    # There is a very complicated piece of code. Any of a million
exceptions could occur.
    ...
  except:
    # Show a nicely formatted error message with hints on how to debug
the error.
    ...

Here are some bad examples:

(BAD)

   try:
     # I don't know what is happening in here, but it always throws an
exception.
     # I don't want to think about it because it makes my brain hurt.
     ...
   except:
     pass

(WORSE) The alternate form--try N times, masking the error each time--
is equally bad.

  while True:
    try:
      # Something could go wrong. What could go wrong? Who cares?
      ...
      break
    except:
      # We'll just keep trying forever....
      pass


From Matthew_WARREN at bnpparibas.com  Mon Jan 28 11:31:50 2008
From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com)
Date: Mon, 28 Jan 2008 16:31:50 +0000
Subject: validate string is valid maths
In-Reply-To: <13pru0etgp7joc1@corp.supernews.com>
Message-ID: 


Ok, I was thinking along the same lines myself, replacing ++ etc.. until no
more replacements are made.

I hadnt considered creating a table of pairs and replacements though, or
realised that the same replace method would work in that case. handy :)

The dictionary is unordered; would differences in the order of replacements
being made effect the final outcome?

IE

*/*

replaced in order of */ then /* would give (using table below)

*/ => **
/* => **

But in the order /* then */

*/*


/* => */
*/ => *

I've tried testing, but I'm not certain wether repeated iterations over a
dict return different sequences of key,value pairs or wether I'll be
getting the same (but arbitrary) sequence each time even though they are
unordered, etc

So for testing, what could I do to guarantee the next iteration over the
dict will give keys/pairs in a different sequence to last time?


...actually, whenever I iterate over the dict say with for k,v in n.items()
I get exactly the same sequence each time.  For once I want to exploit the
dict's unorderedness and it's decided its going to be all ordered...

Matt.




                                                                                                                   
           Internet                                                                                                
           steve at REMOVE-THIS-cybersource.com.au                                                                    
                                                                                                                To 
                                                                        python-list                                
           Sent by:                                                                                             cc 
           python-list-bounces+matthew.warren=uk.bnpparibas.com@                                                   
           python.org                                                                                      Subject 
                                                                        Re: validate string is valid maths         
           28/01/2008 15:43                                                                                        
                                                                                                                   
                                                                                                                   
                                                                                                                   
                                                                                                                   
                                                                                                                   
                                                                                                                   




On Mon, 28 Jan 2008 15:10:54 +0000, Matthew_WARREN wrote:

> Hi pythoners.
>
> I am generating strings of length n, randomly from the symbols
>
> +-/*0123456789
>
> What would be the 'sensible' way of transforming the string, for example
> changing '3++++++8' into 3+8

That's easy: replace pairs of + into a single +, repeatedly until there's
nothing left to replace. And so forth. Here's an untested function. It's
probably not even close to optimal, but for playing around it is probably
fine.

def rationalise_signs(s):
    while "++" in s or "+-" in s or "-+" in s or "--" in s:
        s = s.replace("++", "+")
        s = s.replace("--", "+")
        s = s.replace("+-", "-")
        s = s.replace("-+", "-")
    return s




> or '3++--*-9' into '3+-9' such that  eval(string) will always return a
> number?
>
> in cases where multiple symbols conflict in meaning (as '3++--*-9' the
> earliest valid symbols in the sequence should be preserved

You have four symbols, so there are just 4*4=16 sets of two symbols.
Probably the easiest way is to just list them and their replacements out
in a table:

table = {"++": "+", "+-": "-", "+*": "+", "+/": "+",
    "-+": "-", "--": "+", "-*": "-", "-/": "-",
    "*+": "*", "**": "*", "*/": "*",
    "/+": "/", "/*": "/", "//": "/", }

Notice that both *- and /- don't get changed.



# Untested.
def rationalise_signs(s):
    prev = ''
    while s != prev:
        prev = s
        for key, value in table.items():
            s = s.replace(key, value)
    return s



--
Steven
--
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  Sat Jan 26 19:20:21 2008
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Sat, 26 Jan 2008 22:20:21 -0200
Subject: Text-based data inspector for Python?
References: 
	
	
Message-ID: 

En Fri, 25 Jan 2008 12:28:08 -0200, kj  escribi?:

> The one thing I couldn't
> find, and would greatly miss if not available, is the ability to
> set breakpoints by inserting a particular indication right in the
> code.  In the Perl debugger one can insert something like the
> following anywhere in the code:
>
>   $DB::single = 1;
>
> When such a line executes, the debugger immediately switches to
> single-step mode.  It's a very flexible technique, and I like it

I think that pdb.set_trace() does what you want.

-- 
Gabriel Genellina



From mwilson at the-wire.com  Thu Jan 17 19:27:20 2008
From: mwilson at the-wire.com (Mel)
Date: Thu, 17 Jan 2008 19:27:20 -0500
Subject: "Code Friendly" Blog?
References: 
	<0fd979c6-5a11-4989-9438-51a7b20ecd23@n20g2000hsh.googlegroups.com>
Message-ID: 

Hai Vu wrote:
> On Jan 17, 2:50 pm, Miki  wrote:
>> Hello,
>>
>> Posting code examples to blogger.com hosted blog is not fun (need to
>> remember alway escape < and >).
>> Is there any free blog hosting that is more "code friendly" (easy to
>> post code snippets and such)?
>>
>> Thanks,
>> --
>> Miki http://pythonwise.blogspot.com
> 
> how about bracketing your code in the 
 tags?
> 
> Something like this:
> 
> import sys, os, shutil
> 
> def getDir(fullPath):
>     dirName, fileName = os.path.split(fullPath)
>     return dirName
> 
That won't help the escape problem, though it will preserve vital Python whitespace. HTML has to be interpreting '<' characters to recognize the '
'. Mel. From ggpolo at gmail.com Mon Jan 7 08:54:18 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 11:54:18 -0200 Subject: code doesn't reference immutables? In-Reply-To: <5e6d3674-fddb-402f-9e5c-19afcd7fcc22@i7g2000prf.googlegroups.com> References: <5e6d3674-fddb-402f-9e5c-19afcd7fcc22@i7g2000prf.googlegroups.com> Message-ID: 2008/1/7, MartinRinehart at gmail.com : > >From the manual: > > "code objects are immutable and contain no references (directly or > indirectly) to mutable objects" (3.2) > > I thought my code worked with both mutable and immutable objects. > Whassup? > What was your intention quoting this half-phrase ? >From the same place, Python Reference Manual, 3.2: Code objects: Code objects represent byte-compiled executable Python code, or bytecode. The difference between a code object and a function object is that the function object contains an explicit reference to the function's globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From apatheticagnostic at gmail.com Fri Jan 18 11:44:26 2008 From: apatheticagnostic at gmail.com (apatheticagnostic) Date: Fri, 18 Jan 2008 08:44:26 -0800 (PST) Subject: how to resolve Windows pathnames into cygwin ones References: Message-ID: <2ba97fb6-6bef-44aa-937b-2aa9582e4341@e4g2000hsg.googlegroups.com> On Jan 18, 11:10 am, "mgier... at gmail.com" wrote: > I am looking for a function to resolve 'F:/foo/bar' into '/cygdrive/f/ > foo/bar'. I get the original dirpath from tkFileDialog.askdirectory in > a Windows form and none of os.path.* functions seem to resolve it to a > cygwin form. Rather they _append_ it to the current directory, > resulting at best in a monster '/cygdrive/c/whatever/f/foo/bar'. > It's all being developed under cygwin currently (so it is a kind of > mixed environment), but I would like the fix to work correctly in any > environment. > > Thanks, > Marcin Well, you could write it yourself.... (assuming path is a string, here's a first go at it...) def path_into_cygpath(path): drive, destination = path.split(':') newpath = '/cygdrive/' + drive.lower() + destination return newpath From bearophileHUGS at lycos.com Thu Jan 17 09:37:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 17 Jan 2008 06:37:15 -0800 (PST) Subject: Replace stop words (remove words from a string) References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> Message-ID: <2a0b933f-1c41-4b7c-b213-9781286d6e0a@c23g2000hsa.googlegroups.com> Raymond Hettinger: > Regular expressions should do the trick. > >>> stoppattern = '|'.join(map(re.escape, stoplist)) > >>> re.sub(stoppattern, '', mystr) If the stop words are many (and similar) then that RE can be optimized with a trie-based strategy, like this one called "List": http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm "List" is used by something more complex called "Optimizer" that's overkill for the OP problem: http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/Optimizer.pm I don't know if a Python module similar to "List" is available, I may write it :-) Bye, bearophile From gagsl-py2 at yahoo.com.ar Tue Jan 1 14:37:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Jan 2008 17:37:15 -0200 Subject: Newbie: Why doesn't this work References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> Message-ID: En Tue, 01 Jan 2008 16:57:41 -0200, escribi?: > Gabriel, if I understand it properly, it is necessary to define get/ > set/del/doc methods for each attribute for which I want to set the > "property" data descriptor (which triggers get/set/del/doc function > calls upon access to defined attribute). Yes. Not all of them, just what you need (by example, a read-only property doesn't require a set method; I think the get() docstring is used if no explicit doc is provided; most of the time I don't care to define del...) You don't "have" to define anything you don't need; moreover, you don't have to define a property if you don't actually need it. The very first example in the builtin functions documentation for "property" is a bad example: if all your property does is to wrap a stored attribute, forget about the property and use the attribute directly. > My question is: is it possible to set the "property" for any attribute > when I do not know what will be the name of the attribute in the > future? Uhm... I don't understand the question. Perhaps if you think of a concrete case...? -- Gabriel Genellina From donn.ingle at gmail.com Thu Jan 24 11:58:35 2008 From: donn.ingle at gmail.com (Donn Ingle) Date: Thu, 24 Jan 2008 18:58:35 +0200 Subject: piping into a python script References: Message-ID: Paddy wrote: > fileinput is set to process each file a line at a time unfortunately. Wow. So there seems to be no solution to my OP. I'm amazed, I would have thought a simple list of strings, one from stdin and one from the args, would be easy to get. I *really* don't want to open each file, that would be insane. Perhaps I shall have to forgo the stdin stuff then, after all. \d From lasses_weil at klapptsowieso.net Sun Jan 27 18:35:51 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 28 Jan 2008 00:35:51 +0100 Subject: Python Genetic Algorithm In-Reply-To: References: Message-ID: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net> Max wrote: > In GAs, you operate on a Population of solutions. Each Individual from > the Population is a potential solution to the problem you're > optimizing, and Individuals have what's called a chromosome - a > specification of what it contains. For example, common chromosomes are > bit strings, lists of ints/floats, permutations...etc. I'm stuck on > how to implement the different chromosomes. I have a Population class, > which is going to contain a list of Individuals. Each individual will > be of a certain chromosome. I envision the chromosomes as subclasses > of an abstract Individual class, perhaps all in the same module. I'm > just having trouble envisioning how this would be coded at the > population level. Presumably, when a population is created, a > parameter to its __init__ would be the chromosome type, but I don't > know how to take that in Python and use it to specify a certain class. > I'm not sure I'm following you here. So a "chromosome" is bit of functionality, right? So basically it is a function. So my advice would be to write these functions and store it to the "indivuals"-list like so: class Population(object): def __init__(self, *individuals): self.individuals = list(individuals) Then you can say: p = Population(indiv1, indiv2, indiv3) for individual in p.individual: individual(whatever_your_problem) (Don't know if this is the way GA's are supposed to work) You can also create callable classes (that is, classes that implement the __call__ method), and use instances of these as the individuals. For example you can create a Permutation class that returns a permutation (defined in it's __init__()) when it's __call__ method is called. (Am I making sense?) This is just generic advice, maybe this helps and maybe it doesn't at all. :) > I'm doing something similar with my crossover methods, by specifying > them as functions in a module called Crossover, importing that, and > defining > > crossover_function = getattr(Crossover, "%s_crossover" % xover) > > Where xover is a parameter defining the type of crossover to be used. > I'm hoping there's some similar trick to accomplish what I want to do > with chromosomes - or maybe I'm going about this completely the wrong > way, trying to get Python to do something it's not made for. Any help/ > feedback would be wonderful. > This isn't too bad, but for such things dictionaries are your Go-To datatype. Just have a dictionary of xover-functions handy and call the thusly: crossover_function = Crossover.function[xover] > Thanks, > Max Martin If that helps :) regards /W From victorsubervi at gmail.com Fri Jan 4 11:39:50 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 4 Jan 2008 12:39:50 -0400 Subject: How Does This Static Variable Work? In-Reply-To: <51302a8c0801040834w6e9bf720l37d90a2884b19253@mail.gmail.com> References: <4dc0cfea0801040717u9bc67ccr80447dc375502445@mail.gmail.com> <51302a8c0801040834w6e9bf720l37d90a2884b19253@mail.gmail.com> Message-ID: <4dc0cfea0801040839w21da20bbn24cdf518e5905a10@mail.gmail.com> Thanks. I'll study that. Victor On Jan 4, 2008 12:34 PM, Neil Cerutti wrote: > On Jan 4, 2008 10:17 AM, Victor Subervi wrote: > > > Hi; > > I read this example somewhere, but I don't understand it <:-) Can > > someone please explain how static variables work? Or recommend a good > > how-to? > > > > > > import random > > > > def randomwalk_static(last=[1]): # init the "static" var(s) > > > > rand = random.random() # init a candidate value > > > > Simulating C's static local variables is the (in)famous application for > this case of optimization in Python's design. > > Consult the following entry in the Python General Programming FAQ for > further information. > > > http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects > > -- > Neil Cerutti > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sinisterguy at gmail.com Fri Jan 11 15:29:24 2008 From: sinisterguy at gmail.com (lukas) Date: Fri, 11 Jan 2008 12:29:24 -0800 (PST) Subject: os.rename() problems on OS X Message-ID: <02de1e94-ff7b-4304-a7f6-0393fde975ae@q77g2000hsh.googlegroups.com> hello, i recently had the job of having to rename about 200 files. The source for the renaming was a bunch of names in a file. I know next to nothing when it comes to bash scripting (which would have seemed the obvious choice) so i used python. The files i was renaming were canon raw files (.CR2). my problem is that after i rename the files, OS X will no longer render the thumbnails for the files, and preview is no longer the default app for viewing them. Does anyone have an idea as to why this is? Thanks for the help :) -Lukas From johnthawk at excite.com Wed Jan 23 07:57:21 2008 From: johnthawk at excite.com (johnthawk at excite.com) Date: Wed, 23 Jan 2008 07:57:21 -0500 (EST) Subject: Icon in a gtk.Entry Message-ID: <20080123125721.28332B57EE@xprdmxin.myway.com> Hello all, I have two thing I wish to accomplish, First, put an icon in a gtk.Entry as in many search boxes. Second put a gtk.Checkbox in a gtk.ComboboxEntry. On the later I thought I could get a handle to the Combobox tree and then add a column and then column span column 1 back into column 0 , thus a gtk.ToggelRender would be visible in column 0. But I had no luck getting a handle to the Combobox tree. Any help would be greatly appreciated. Have a nice day. John _______________________________________________ Join Excite! - http://www.excite.com The most personalized portal on the Web! From george.sakkis at gmail.com Wed Jan 23 14:27:34 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 23 Jan 2008 11:27:34 -0800 (PST) Subject: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'? References: Message-ID: On Jan 23, 4:06 am, Gary Herron wrote: > However there *is* a (subtle) difference between > not f > and > (not f and 1) or 0 > > The first produces a boolean value, and the second produces an int > value, but since one is a subclass of the other, you'd have to write > quite perverse code care about the difference. Even if for some reason I did want the result to be int, I would write it as "int(not f)". George From http Thu Jan 31 11:24:44 2008 From: http (Paul Rubin) Date: 31 Jan 2008 08:24:44 -0800 Subject: How to identify which numbers in a list are within each others' range References: <6b4ac79b-6267-438d-8b28-aa4bba78a586@i3g2000hsf.googlegroups.com> Message-ID: <7x63xavu7n.fsf@ruckus.brouhaha.com> erikcw writes: > 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. This sounds like a homework problem, so the first thing I'll suggest is that you figure out exactly what it means for two of those intervals to overlap. That should let you write a simple program that gets the right answer, but that can run slowly if the number of lists gets large. The next thing to do after that is figure out how to speed it up, if necessary. But do the first part first. From massi_srb at msn.com Sun Jan 13 10:22:59 2008 From: massi_srb at msn.com (Massi) Date: Sun, 13 Jan 2008 07:22:59 -0800 (PST) Subject: wxpython-wx.CheckListBox: changing item bacgkground color Message-ID: <1c6feae5-1188-4e00-9ba5-b7d8a1b0302e@s19g2000prg.googlegroups.com> Hi everyone! In my application (under windows) I'm using a wx.checklistbox. I would like the background color of an item to become red whenever an EVT_LISTBOX_DCLICK occurs. Is there any simple way to achieve it? Thanks in advance. From lepto.python at gmail.com Mon Jan 14 21:25:22 2008 From: lepto.python at gmail.com (oyster) Date: Tue, 15 Jan 2008 10:25:22 +0800 Subject: jpype with JFreeChart, anyone interested to help? Message-ID: <6a4f17690801141825t74737c17h1e83285b487e17c8@mail.gmail.com> Thanx However I knew Chaco and matplotlib, and I use matplotlib during my school days. And as I have pointed out, they are for "plot", but not "chart". If you don't know the difference between plot and chart, you can have a look at at http://www.jfree.org/jfreechart, http://www.rmchart.com Yes, it is true we can use plot lib to draw chart, but that is tedious. 2008/1/15, python-list-request at python.org : > From: Peter Wang > To: python-list at python.org > Date: Mon, 14 Jan 2008 07:58:02 -0800 (PST) > Subject: Re: jpype with JFreeChart, anyone interested to help? > On Jan 14, 6:51 am, oyster wrote: > > As you may know, there is no beautiful and free chart(notplot, you > > can find the examples athttp://www.jfree.org/jfreechart,http://www.rmchart.com) module for python than runs on > > windows/linux/mac osx. > > Actually, may I humbly suggest two: > > Chaco: http://code.enthought.com/chaco/gallery/index.shtml > > matplotlib: http://matplotlib.sourceforge.net/ > > > -Peter > > > From gowricp at gmail.com Wed Jan 16 05:36:50 2008 From: gowricp at gmail.com (Gowri) Date: Wed, 16 Jan 2008 02:36:50 -0800 (PST) Subject: searching an XML doc References: <327368a7-694f-4f30-8f76-db0569ed4a5c@k2g2000hse.googlegroups.com> <2d290754-4a44-427f-9287-134210b217d5@q77g2000hsh.googlegroups.com> Message-ID: <7a48ed44-05f8-4943-b034-0073d0858156@21g2000hsj.googlegroups.com> Hi Gerard, I don't know what to say :) thank you so much for taking time to post all of this. truly appreciate it :) From jr9445 at ATT.COM Fri Jan 18 12:39:55 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 18 Jan 2008 11:39:55 -0600 Subject: How to use only a sub shell to execute many commands in python 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 raocheng > Sent: Friday, January 18, 2008 6:31 AM > To: python-list at python.org > Subject: How to use only a sub shell to execute many commands in python > > Please see the following code. > Suppose I have many shell commands to be executed. And I don't want to > fork a sub shell for each command(eg: status,output = > commands.getstatusoutput(cmd)) because it is too expensive. I want to > use only one sub shell to execute all these commands and want to get > each command's output. How can I accomplish this task ? Thanks in > advance. > > =========================================== > #!/usr/bin/env python > import os > fi, fo = os.popen2( > ''' > while read line > do > eval $line > done > ''', 't') > > #Suppose I have many commands to execute, but I don't want to fork a > sub shell for each command > cmds = ['date','uptime','pwd','ls -rltF','who'] > > for cmd in cmds: > #pseudocode > fi.executeCmd(cmd) > output = fo.readResult() > > print output Have each command write to a unique temp file. Create temp files in python cmd = 'date > /tmp/date_temp 2>&1 ; uptime > /tmp/uptime_temp 2>&1; ...' execute cmd for file in tempfiles: ... You can also get the return value of each command cmd = 'date > /tmp/date_temp 2>&1; echo $? >> /tmp/date_temp; uptime > /tmp/uptime_temp 2>&1; echo $? >> ...' ***** 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. GA622 From hniksic at xemacs.org Mon Jan 14 13:47:41 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 14 Jan 2008 19:47:41 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <873at0mkv7.fsf@mulj.homelinux.net> Message-ID: <87ve5wkzw2.fsf@mulj.homelinux.net> "Reedick, Andrew" writes: >> Only if by "construct" you mean "allocate". __init__ starts out >> with an empty object and brings it to a valid state, therefore >> "constructing" the object you end up with. That operation is >> exactly what other languages call a constructor. > > Nah. Most other languages combine the constructor and an init > function. Maybe so, but the standard term for what Python calls __init__ is still "constructor". > Also, how can a constructor require 'self' as an argument...? > __init__(self, ...) Think of it as the equivalent of Java's and C++'s "this", except it's explicit in the argument list. "Explicit is better than implicit" and all that. :-) From arnodel at googlemail.com Tue Jan 1 15:26:23 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 1 Jan 2008 12:26:23 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <6aba9463-f0ea-43a2-b8de-9c7026c4d14e@e4g2000hsg.googlegroups.com> <5c6a5515-a6ee-455d-83d4-48b2a2ae46c3@n20g2000hsh.googlegroups.com> <579f378d-d948-4c99-8507-a8c4e9a28096@i29g2000prf.googlegroups.com> <74a7edcf-f4ea-4835-b08e-499faaed8d81@i12g2000prf.googlegroups.com> Message-ID: <6cfa4965-ed8f-4d70-a688-170bf557b7d4@m34g2000hsf.googlegroups.com> On Jan 1, 6:48?pm, "Gabriel Genellina" wrote: > En Tue, 01 Jan 2008 15:45:00 -0200, bukzor ? > escribi?: [...] > >> I'm confused by what you mean by 'early binding'. Can you give a quick- > >> n-dirty example? > > Is an 'early bound' variable synonymous with a 'static' variable (in > > C)? > > No. It means, in which moment the name gets its value assigned. Usually ? > Python does "late binding", that is, names are resolved at the time the ? > code is executed, not when it's compiled or defined. > Consider this example: > > z = 1 > def foo(a) > ? ?print a+z > foo(3) # prints 4 > z = 20 > foo(3) # prints 23 > > The second time it prints 23, not 4, because the value for z is searched ? > when the code is executed, so the relevant value for z is 20. > Note that if you later assign a non-numeric value to z, foo(3) will fail. > > If you want to achieve the effect of "early binding", that is, you want to ? > "freeze" z to be always what it was at the time the function was defined, ? > you can do that using a default argument: > > z = 1 > def foo(a, z=z) > ? ?print a+z > z = None > foo(3) # prints 4 > > This way, foo(3) will always print 4, independently of the current value ? > of z. Moreover, you can `del z` and foo will continue to work. > > This is what I think Chris Mellon was refering to. This specific default ? > argument semantics allows one to achieve the effect of "early binding" in ? > a language which is mostly "late binding". If someone changes this, he has ? > to come with another way of faking early binding semantics at least as ? > simple as this, else we're solving an [inexistant for me] problem but ? > creating another one. > > -- > Gabriel Genellina Let me say again that I believe the current behaviour to be the correct one. But I don't think this 'early binding' is critical for this sort of example. There are lots of ways to solve the problem of having persistent state across function calls, for example: * using classes * using modules * or simply nested functions: def getfoo(z): def foo(a): print a + z return foo >>> z = 1 >>> foo = getfoo(z) >>> z = None >>> foo(3) 4 And with nonlocal, we could even modify z inside foo and this change would persist across calls. This will be a much cleaner solution than the current def bar(x, y, _hidden=[startvalue]). Also, note that it's easy to implement default arguments in pure python-without-default-arguments using a decorator: def default(**defaults): defaults = defaults.items() def decorator(f): def decorated(*args, **kwargs): for name, val in defaults: kwargs.setdefault(name, val) return f(*args, **kwargs) return decorated return decorator Here is your example: >>> z=1 >>> @default(z=z) ... def foo(a, z): ... print a + z ... >>> z=None >>> foo(3) 4 Another example, using mutables: >>> @default(history=[]) ... def bar(x, history): ... history.append(x) ... return list(history) ... >>> map(bar, 'spam') [['s'], ['s', 'p'], ['s', 'p', 'a'], ['s', 'p', 'a', 'm']] -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Sun Jan 20 17:18:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 20 Jan 2008 22:18:34 -0000 Subject: Looping through the gmail dot trick References: <3d7b05a70801200838m5bd27caft1b95805abd826bbf@mail.gmail.com> Message-ID: <13p7i5qaihgte12@corp.supernews.com> On Sun, 20 Jan 2008 21:13:03 +0000, Neil Hodgson wrote: > Martin Marcher: > >> are you saying that when i have 2 gmail addresses >> >> "foo.bar at gmail.com" and >> "foobar at gmail.com" >> >> they are actually treated the same? That is plain wrong and would break >> a lot of mail addresses as I have 2 that follow just this pattern and >> they are delivered correctly! > > This is a feature of some mail services such as Gmail, not of email > addresses generically. One use is to provide a set of addresses given > one base address. '+' works as well as '.' so when I sign up to service > monty I give them the address nyamatongwe+monty at gmail.com. Then when I > receive spam at nyamatongwe+monty, I know who to blame and what to > block. Technically, everything in the local part of the address (the bit before the @ sign) is supposed to be interpreted *only* by the host given in the domain (the bit after the @ sign). So if Gmail wants to interpret "foo.bar at gmail.com" and "foobar at gmail.com" the same, they can. Or for that matter, "raboof at gmail.com". Although that would be silly. Postfix, I think, interpets "foo+bar" the same as "foo". -- Steven From nagle at animats.com Mon Jan 14 19:26:51 2008 From: nagle at animats.com (John Nagle) Date: Mon, 14 Jan 2008 16:26:51 -0800 Subject: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug Message-ID: <478bfcb0$0$36378$742ec2ed@news.sonic.net> I passed a dict for the "env" variable to Popen with Unicode strings for the dictionary values. Got: File "D:\Python24\lib\subprocess.py", line 706, in _execute_child TypeError: environment can only contain strings It turns out that the strings in the "env" parameter have to be ASCII, not Unicode, even though Windows fully supports Unicode in CreateProcess. John Nagle From stefan.behnel-n05pAM at web.de Sun Jan 27 04:30:42 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 27 Jan 2008 10:30:42 +0100 Subject: Sorting Large File (Code/Performance) In-Reply-To: References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> <690cb460-fa8a-49a1-a6fa-69cdf480a918@i3g2000hsf.googlegroups.com> <7xir1hznuu.fsf@ruckus.brouhaha.com> Message-ID: <479C4F42.3010500@web.de> Gabriel Genellina wrote: > use the Windows sort command. It has been > there since MS-DOS ages, there is no need to download and install other > packages, and the documentation at > http://technet.microsoft.com/en-us/library/bb491004.aspx says: > > Limits on file size: > The sort command has no limit on file size. Sure, since no-one can ever try it with more than 640k, it's easy to state that there is no limit. :) Stefan From basilisk96 at gmail.com Tue Jan 8 22:11:24 2008 From: basilisk96 at gmail.com (Basilisk96) Date: Tue, 8 Jan 2008 19:11:24 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <5cf4c5bb-01b1-4ece-a09a-24c4491764b1@f47g2000hsd.googlegroups.com> On Jan 7, 8:09 am, MartinRineh... at gmail.com wrote: > I'm a Java guy who's been doing Python for a month now and I'm > convinced that > > 1) a multi-paradigm language is inherently better than a mono-paradigm > language > > 2) Python writes like a talented figure skater skates. > > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is _______. > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > "grace" but I'm not sure I've done enough to choose. Here's a new word - ...its humanicity factor. That definition, according to me, is: "its ability to let you *quickly* formulate and solve your problem in the way that YOU see it, not as the computer sees it." Did programmers stop writing programs on punch cards because they ran out of punch paper? Cheers, -Basilisk96 From halcyon1981 at gmail.com Thu Jan 24 14:32:02 2008 From: halcyon1981 at gmail.com (David Erickson) Date: Thu, 24 Jan 2008 11:32:02 -0800 (PST) Subject: Email module, how to add header to the top of an email? Message-ID: <97c04812-3b66-4d84-9e92-21de72a3ca56@c23g2000hsa.googlegroups.com> I have been using the Email module and Message class for awhile, however I have been unable to find a way to add a header to the top of the email similar to what is done with Received: headers... the add_header method only appends to the bottom. Is there someway this can be done? Thanks David From dima.hristov at gmail.com Mon Jan 21 06:53:06 2008 From: dima.hristov at gmail.com (DHR) Date: Mon, 21 Jan 2008 03:53:06 -0800 (PST) Subject: Q: paramiko/SSH/ how to get a remote host_key Message-ID: <8a2c59f7-93f4-47ec-b9b8-9d37c3dca945@v4g2000hsf.googlegroups.com> I'm trying to run the simpliest example form paramiko readme(Homepage: http://www.lag.net/paramiko/), and cannot find out how to get the remote SSH server host_key. This is the code. It is supposed to connect to a remote SSH host and execute an 'ls' command: import paramiko, base64 key = paramiko.RSAKey(data=base64.decodestring('AAA...')) client = paramiko.SSHClient() client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key) client.connect('227.112.168.273', username='uname', password='pass') stdin, stdout, stderr = client.exec_command('ls') for line in stdout: print '... ' + line.strip('\n') client.close() Now, if I understand it correctly I need to get somehow the host_key from the server and write it insted of the 'AAA...' thing. Is there a command to get the host_key from a remote SSH server? From mwm-keyword-python.b4bdba at mired.org Thu Jan 10 22:14:31 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Thu, 10 Jan 2008 22:14:31 -0500 Subject: Detecting OS platform in Python In-Reply-To: References: Message-ID: <20080110221431.63082666@bhuda.mired.org> On Thu, 10 Jan 2008 18:37:59 -0800 (PST) Devraj wrote: > Hi everyone, > > My Python program needs reliably detect which Operating System its > being run on, infact it even needs to know which distribution of say > Linux its running on. The reason being its a GTK application that > needs to adapt itself to be a Hildon application if run on devices > like the N800. I don't think it can be done. For most Unix system, os.uname() will give you the information you want: >>> os.uname() ('FreeBSD', 'bhuda.mired.org', '6.2-STABLE', 'FreeBSD 6.2-STABLE #6: Sun Jun 3 04:17:59 EDT 2007 mwm at bhuda.mired.org:/usr/src/sys/amd64/compile/BHUDA', 'amd64') (let's see - OS name, the system name, the release level, complete build information, down to the configuration file for the build and build number for that configuration, and the hardware type it was built for). For GNU/Linux systems, it won't, because it's a kernel facility, and kernels don't know what distribution they're part of: Linux student.mired.org 2.6.12-9-386 #1 Mon Oct 10 13:14:36 BST 2005 i686 GNU/Linux (kernel name, system name, kernel version and build information, platform, and operating system). GNU/Linux distributions are collections of lots of people software, so each has it's own way to state what "distribution" it is. I believe there's some sort of standard - except not everybody follows it. So you wind up using a series of heuristics to chase this information down. > I have been searching around for an answer to this, and did find some > messages on a lists that suggested the use of sys.platform to detect > platform, with counter posts saying that it didn't work on Windows > etc. Oh, you want it to work on Windows? Hmmm. [snotty comment about Windows deleted]. Does the underlying platform claim to be POSIX.2 compliant? If so, then os.uname() should work on it, but as indicated, that may well not be complete. On the other hand, trying to figure out what features you have available by guessing based on the platform type is generally the wrong way to approach this kind of problem - only in part because you wind up reduced to a series of heuristics to figure out the platform. And once you've done that, you could wind up being wrong. Generally, you're better of probing the platform to find out if it has the facilities you're looking for. For python, that generally means trying to import the modules you need, and catching failures; or possibly looking for attributes on modules if they adopt to the environment around them. I'm not a GTK programmer, and have never even heard of Hildon. Is there some associated module you could try and import that doesn't exist on the N800? I.e.: try: import gtk mygui = 'gtk' except ImportError: import Hildon mygui = 'Hildon' or maybe something like: import gtk mygui = 'gtk' if not hasattr(gtk, 'Hildon') else 'Hildon' http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From danielatdaveschool at gmail.com Wed Jan 16 00:53:20 2008 From: danielatdaveschool at gmail.com (danielatdaveschool at gmail.com) Date: Tue, 15 Jan 2008 21:53:20 -0800 (PST) Subject: Image to browser References: <8c014bd1-7040-4ba3-9206-e1567c4a391a@n20g2000hsh.googlegroups.com> <1d223aa2-1297-4b01-854a-2a502f5f0ed1@l1g2000hsa.googlegroups.com> Message-ID: <45a7516d-0014-4d6d-9d1f-385727c846ae@i7g2000prf.googlegroups.com> On Jan 16, 12:38 am, Justin Ezequiel wrote: > On Jan 16, 1:19 pm, danielatdavesch... at gmail.com wrote: > > > > > On Jan 16, 12:16 am, danielatdavesch... at gmail.com wrote: > > > > Im using mod_python and apache2 using psp for output of page, i open a > > > file and resize it with the following code > > > > <% > > > import Image, util > > > > fields = util.FieldStorage(req) > > > filename = fields.getlist('src')[0] > > > > path = '/var/www/content/' + filename > > > size = 128, 128 > > > > im = Image.open(path) > > > print im.resize(size, Image.ANTIALIAS) > > > %> > > > > so for one, I dont think print does much with psp as far as i can > > > tell, i cant even do a print 'hello world', it has to be a > > > req.write('hello world'), but i cant req.write the im.resize. The > > > manual for im.resize states that its return can go ahead and be > > > streamed via http but I get a blank page when im expecting to see > > > image characters dumped to my screen. Python doesn't throw up any > > > errors. Im not sure where else to look or what to do. > > > > Thanks for any help, > > > Daniel > > > its worth noting that ive tried using > > print "Content-Type: image/jpeg\n" > > before the print im.resize and still no luck > > If you're using the Image module from PIL then im.resize(...) returns > an Image instance. > I have not used mod_python and psp, but try the following: > > >>> import Image > >>> i = Image.open('server.JPG') > >>> r = i.resize((32,32)) > >>> from StringIO import StringIO > >>> b = StringIO() > >>> r.save(b, 'JPEG') > >>> b.seek(0) > >>> req.write("Content-Type: image/jpeg\r\n\r\n") > >>> req.write(b.read()) > > There's a r.tostring(...) method but I don't see how to make that > return a JPEG stream. brilliant, at least to me anyway, it works as long as i remove the req.write("content-type... now i have a lot to look up, i tried something similar to this before that i found on the web but no luck. i guess whats going on is it gets saved to this pseudo file thats just a string existing in memory, and then the pointer gets set to the begining of the string for the upcoming read() ? i dunno, but something else to learn about. I must admit i was hoping for something a little more elegant. Thanks for your help! From python at rolfvandekrol.nl Mon Jan 21 09:15:12 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Mon, 21 Jan 2008 15:15:12 +0100 Subject: stdin, stdout, redmon In-Reply-To: <4794a5e3$0$9014$426a74cc@news.free.fr> References: <4794a5e3$0$9014$426a74cc@news.free.fr> Message-ID: <4794A8F0.7020400@rolfvandekrol.nl> According to various tutorials this should work. |import sys data = sys.stdin.readlines() print "Counted", len(data), "lines."| Please use google before asking such questions. This was found with only one search for the terms 'python read stdin' Rolf Bernard Desnoues wrote: > Hi, > > I've got a problem with the use of Redmon (redirection port monitor). I > intend to develop a virtual printer so that I can modify data sent to > the printer. > Redmon send the data flow to the standard input and lauchs the Python > program which send modified data to the standard output (Windows XP and > Python 2.5 context). > I can manipulate the standard output. > > "import sys > sys.stdout.write(data)" > > it works. > But how to manipulate standard input so that I can store data in a > string or in an object file ? There's no "read" method. > > "a = sys.stdin.read()" doesn't work. > "f = open(sys.stdin)" doesn't work. > > I don't find anything in the documentation. How to do that ? > Thanks in advance. > > Bernard Desnoues > Librarian > Biblioth?que de g?ographie - Sorbonne From gagsl-py2 at yahoo.com.ar Mon Jan 21 00:45:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 03:45:30 -0200 Subject: object scope References: <13p8803q11tm32d@corp.supernews.com> <47942AB5.4040301@block.duxieweb.com> Message-ID: En Mon, 21 Jan 2008 03:16:37 -0200, J. Peng escribi?: > Dennis Lee Bieber ??: >> The scope of "name" is the entire function; lacking a "global name" >> statement, AND being on the left side of an assignment, it is a function >> local name. > > Thank you. Does python have so-called 'block scope' object? > or if you can,please show me the doc for python's object scope. See http://docs.python.org/ref/naming.html -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Mon Jan 28 02:52:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 28 Jan 2008 07:52:14 -0000 Subject: Using a dict as if it were a module namespace References: <13podkpqqvef674@corp.supernews.com> Message-ID: <13pr2def4b48uc6@corp.supernews.com> On Sun, 27 Jan 2008 11:16:00 -0700, Steven Bethard wrote: > Why not mess with the namespace inside the setup code? E.g.:: [snip] Ah, thanks, good thinking. It's not perfect, but it should be close enough for what I'm trying to do. -- Steven who still wishes you could explicitly pass a namespace to timeit.Timer... From arnodel at googlemail.com Fri Jan 4 18:12:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 4 Jan 2008 15:12:47 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> <13ntbv51tqcm7c@corp.supernews.com> Message-ID: <1b73b614-f71c-4985-988a-7852ef39715f@j78g2000hsd.googlegroups.com> On Jan 4, 10:15?pm, Steven D'Aprano wrote: > On Fri, 04 Jan 2008 09:29:50 -0800, bukzor wrote: > > Why cant you implement < for complex numbers? Maybe I'm being naive, but > > isn't this the normal definition? > > ? ? a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) > > No, it is not. Mathematically speaking, it is an order, and a very useful one. Only it's a partial order, which means that if a != b then they are not necessarily ordered (e.g. 1 and i). This is not ideal for sorting. What you need is a total order, where any two distinct elements are comparable. > Ordered comparisons are not defined for complex numbers. You can't define a total order which is compatible with addition and multiplication, but this restriction is not required to implement sets of complex numbers. Any total order will do, the easiest to pick being lexicographical as already pointed out, i.e. a+bi < c + di iff a < c or a == c and b < d > Which is bigger, 4+2j or 2+4j? 4+2j, lexicographically! -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 00:20:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 27 Jan 2008 05:20:55 -0000 Subject: how to make format operator % work with unicode as expected References: Message-ID: <13po55nc0q0s06@corp.supernews.com> On Sun, 27 Jan 2008 04:06:45 +0000, Peter Pei wrote: > I probably should mention that what I want is to make all parts of the > string aligned, and look like table. I am not looking for other ways to > make it table-alike, but only interested in making % work with unicode > -counting characters not bytes... % already works with unicode. Just give it unicode arguments: >>> print u"x y z %s 1 2 3" % u"Les mis?rables" x y z Les mis?rables 1 2 3 -- Steven From aquorang at yahoo.com Thu Jan 3 23:53:57 2008 From: aquorang at yahoo.com (aquorang at yahoo.com) Date: Thu, 3 Jan 2008 20:53:57 -0800 (PST) Subject: i want to share my secrets with u......... Message-ID: <5a30516f-6f56-4431-911c-f784e826ccf1@i7g2000prf.googlegroups.com> i want to share my secrets with u......... how to create miracles in your own life? http://www.freewebs.com/aquorang/ http://indianfriendfinder.com/go/g926592-pmem http://bigchurch.com/go/g926592-pmem From paddy3118 at googlemail.com Thu Jan 24 01:07:58 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 23 Jan 2008 22:07:58 -0800 (PST) Subject: Terminology: "script" versus "program" (was: Linux Journal Survey) References: <1666950d-e9a5-4b7c-a614-5bba90e5b4ca@y5g2000hsf.googlegroups.com> <87ir1j7r9k.fsf_-_@benfinney.id.au> Message-ID: On 24 Jan, 04:59, Ben Finney wrote: > George Sakkis writes: > > 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. > > I agree entirely. > > The term "script" has the strong connotation of a limited-purpose > program designed to solve a problem expressed almost entirely as a > simple series of steps. Languages that are often used to write such > scripts are usually referred to as "scripting languages", which > becomes a denigration because such a language need not have support > for much else. > > In contrast, the term "program" (and hence "programming language") > implies support for a much broader set of practices and solutions. > > This term seems quite prevalent among the Python core developers, > unfortunately. The 'distutils' module even has the term 'script' used > in its interface, to refer to the programs that are to be distributed. > > -- > \ "Money is always to be found when men are to be sent to the | > `\ frontiers to be destroyed: when the object is to preserve them, | > _o__) it is no longer so." -- Voltaire, _Dictionnaire Philosophique_ | > Ben Finney Hi George, Ben, In the past I have taken the high ground by arguing that the usual tasks associated with scripting are very important and that languages like Python/Ruby can script as well as write substantial programs in the non-scripting sense. Therefore, if their language of choice does not encompass scripting then it is a lesser language. 'They' may look down on scripting but a lot of that is a mixture of ignorance and envy :-) - Paddy. From arnodel at googlemail.com Tue Jan 22 15:20:56 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 12:20:56 -0800 (PST) Subject: question References: Message-ID: <89b4586c-1d1f-4118-9092-62cdf2a8a7f7@e4g2000hsg.googlegroups.com> On Jan 22, 7:58?pm, wrote: > I'm still learning Python and was wanting to get some thoughts on this. ?I apologize if this sounds ridiculous... ?I'm mainly asking it to gain some knowledge of what works better. ?The main question I have is if I had a lot of lists to choose from, what's the best way to write the code so I'm not wasting a lot of memory? ?I've attempted to list a few examples below to hopefully be a little clearer about my question. > > Lets say I was going to be pulling different data, depending on what the user entered. ?I was thinking I could create a function which contained various functions inside: > > def albumInfo(theBand): > ? ? def Rush(): > ? ? ? ? return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > > ? ? def Enchant(): > ? ? ? ? return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > > ? ? ... > > The only problem with the code above though is that I don't know how to call it, especially since if the user is entering a string, how would I convert that string into a function name? ?For example, if the user entered 'Rush', how would I call the appropriate function --> ?albumInfo(Rush()) > > But if I could somehow make that code work, is it a good way to do it? ?I'm assuming if the user entered 'Rush' that only the list in the Rush() function would be stored, ignoring the other functions inside the albumInfo() function? > > I then thought maybe just using a simple if/else statement might work like so: > > def albumInfo(theBand): > ? ? if theBand == 'Rush': > ? ? ? ? return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > ? ? elif theBand == 'Enchant': > ? ? ? ? return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > ? ? ... > > Does anyone think this would be more efficient? > > I'm not familiar with how 'classes' work yet (still reading through my 'Core Python' book) but was curious if using a 'class' would be better suited for something like this? ?Since the user could possibly choose from 100 or more choices, I'd like to come up with something that's efficient as well as easy to read in the code. ?If anyone has time I'd love to hear your thoughts. > > Thanks. > > Jay What you want is a dictionary: albumInfo = { 'Rush': 'Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'], 'Enchant': ['A Blueprint of the World', 'Wounded', 'Time Lost'], ... } then to find the info just do: >>> albumInfo['Enchant'] ['A Blueprint of the World', 'Wounded', 'Time Lost'] It also makes it easy to add a new album on the fly: >>> albumInfo["Lark's tongue in Aspic"] = [ ... ] Hope that helps. -- Arnaud From roger.miller at nova-sol.com Thu Jan 24 17:55:43 2008 From: roger.miller at nova-sol.com (Roger Miller) Date: Thu, 24 Jan 2008 14:55:43 -0800 (PST) Subject: Ignore exceptions References: <8448fdcb-3ee5-4173-a841-0e844e54d9ba@e4g2000hsg.googlegroups.com> Message-ID: <244a3456-84d3-4328-b30a-59fae999bada@u10g2000prn.googlegroups.com> On Jan 24, 11:30 am, Jonathan Gardner wrote: > .... > A few sample good uses of try/except blocks: > > (1) Do something else if an expected exception occurs. > ... > (2) Show a friendly error message when an exception occurs over a > significant chunk of the program. (Useful for websites and GUI apps.) > ... I'd add (3) Clean-up handlers. These don't actually handle the problem, they just free resources, close files, etc. before re-raising the exception for someone else to worry about. From jimgardener at gmail.com Tue Jan 8 10:32:21 2008 From: jimgardener at gmail.com (jimgardener) Date: Tue, 8 Jan 2008 07:32:21 -0800 (PST) Subject: copy a numpy array Message-ID: hi, (i posted this to numpy discussion grp couple of days back ..but it fails to appear..)since it is needed for my work i would appreciate if anyone can help me with this question i have two ndarrays of 1000 elements each and want to copy all elements from srcarray to destarray srcarray=numpy.array( [3973334.8381791776,........,382999.6748692277] ) arrsize=1000 destarray=zeros(arrsize) i copied all items from src to dest by using destarray[0:arrsize]=srcarray[0:arrsize] i don't know if this is the right way to do the copying. is there a better(efficient?) way ? jim From kyosohma at gmail.com Thu Jan 24 15:27:27 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 24 Jan 2008 12:27:27 -0800 (PST) Subject: Ignore exceptions References: Message-ID: <3b926cf2-a07a-48b8-8941-c2701517ab86@k2g2000hse.googlegroups.com> On Jan 24, 2:13 pm, SMALLp wrote: > Hy. Is there any way to make interrupter ignore exceptions. I'm working > on bigger project and i used to put try catch blocks after writing and > testing code what's boring and it's easy to make mistake. I remember of > something like that in C++ but I cant find anythin like that for python. > > SMALLp See the try statement: http://docs.python.org/ref/try.html http://www.network-theory.co.uk/docs/pytut/HandlingExceptions.html http://docs.python.org/api/exceptionHandling.html Mike From tom at nextstate.net Mon Jan 7 10:08:28 2008 From: tom at nextstate.net (Tom Brown) Date: Mon, 07 Jan 2008 07:08:28 -0800 Subject: dealing with binary files In-Reply-To: References: <47822DA4.9020401@fmed.uba.ar> Message-ID: <1199718508.4558.30.camel@chi> On Mon, 2008-01-07 at 11:57 -0200, Guilherme Polo wrote: > 2008/1/7, Gerardo Herzig : > > Hi all. Im trying to read a binary data from an postgres WAL archive. > > If i make a > > xfile = open('filename', 'rb').xreadlines() > > line = xfile.next() > > > > i see this sort of thing: > > ']\xd0\x03\x00\x01\x00\x00\x00\r\x00\x00\x00\x00\x00\x00JM//DI+,D\x00\x00\x00\x01$\x00\x00\x00\x7f\x06\x00\x00y\r\t\x00\x02\x0f\t\x00\x00\x00\x10\x00)\x00\x01\x00\x12\x08 > > \x00^\xc2\x0c\x00\x08\x00\x00\x003001({\xe8\x10\r\x00\x00\x00\xe4\xff\xffI\x10?l\x01@\x00\x00\x00$\x00\x00\x00\x00\n' > > > > This file suppose to have some information about database activity, but > > at this point i cant do more than this, because i cant figure out what > > to do in order to have some 'readable' text. > > > > Im guessing is some C code, im reading the struct module to see if it > > helps, but im not into C programming, and im lost at the start of my > > problem. > > You are looking at the correct module, struct. But in order to > understand or even correctly extract data from a binary file, you need > to know its structure. There should be some document describing the > Postgre WAL file format. > "The log record headers are described in access/xlog.h" http://www.postgresql.org/docs/8.2/interactive/wal-internals.html From mr.cerutti at gmail.com Wed Jan 9 08:42:57 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 9 Jan 2008 08:42:57 -0500 Subject: alternating string replace In-Reply-To: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <51302a8c0801090542t3b9e6b0dm95ba7ddb42d067cf@mail.gmail.com> On Jan 9, 2008 5:34 AM, cesco wrote: > Hi, > > say I have a string like the following: > s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' > so that I get a new string like the following: > s2 = 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... > > Thanks in advance Hum, hum... If I had a hammer... from pyparsing import * word = Word(alphas) sep = Literal('_').suppress() pair = Group(word + sep + word) pairs = delimitedList(pair, '_') print ','.join(':'.join(t) for t in pairs.parseString('hi_cat_bye_dog').asList()) -- Neil Cerutti From matt at tplus1.com Fri Jan 18 19:43:20 2008 From: matt at tplus1.com (Matthew Wilson) Date: Sat, 19 Jan 2008 00:43:20 GMT Subject: I don't understand what is happening in this threading code Message-ID: In this code, I tried to kill my thread object by setting a variable on it to False. Inside the run method of my thread object, it checks a different variable. I've already rewritten this code to use semaphores, but I'm just curious what is going on. Here's the code: import logging, threading, time logging.basicConfig(level=logging.DEBUG, format="%(threadName)s: %(message)s") class Waiter(threading.Thread): def __init__(self, hot_food): super(Waiter, self).__init__() self.should_keep_running = True self.hot_food = hot_food def run(self): while self.should_keep_running: logging.debug("Inside run, the id of should_keep_running is %s." % id(self.should_keep_running)) self.hot_food.acquire() def cook_food(hot_food): i = 5 while i >= 0: logging.debug("I am cooking food...") time.sleep(1) hot_food.release() logging.debug("Andiamo!") i -= 1 def main(): hot_food = threading.Semaphore(value=0) chef = threading.Thread(name="chef", target=cook_food, args=(hot_food, )) chef.start() w = Waiter(hot_food) logging.debug("Initially, the id of w.should_keep_running is %s." % id(w.should_keep_running)) w.start() logging.debug("After start, the id of w.should_keep_running is %s." % id(w.should_keep_running)) # Wait for the chef to finish work. chef.join() # Now try to kill off the waiter by setting a variable inside the waiter. w.should_keep_running = False logging.debug("Now, the id of w.should_keep_running is %s." % id(w.should_keep_running)) if __name__ == "__main__": main() And here's what I get when I execute it. I have to suspend the process with CTRL=Z and then kill -9 it. $ python foo.py MainThread: Initially, the id of w.should_keep_running is 135527852. MainThread: After start, the id of w.should_keep_running is 135527852. chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! chef: I am cooking food... Thread-1: Inside run, the id of should_keep_running is 135527852. chef: Andiamo! Thread-1: Inside run, the id of should_keep_running is 135527852. MainThread: Now, the id of w.should_keep_running is 135527840. [1]+ Stopped python foo.py $ kill -9 %1 [1]+ Stopped python foo.py The memory address of should_keep_running seems to change when I set it from True to False, and inside the run method, I keep checking the old location. I am totally baffled what this means. Like I said earlier, I already rewrote this code to use semaphores, but I just want to know what is going on here. Any explanation is welcome. TIA Matt From paddy3118 at googlemail.com Mon Jan 7 14:54:27 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 7 Jan 2008 11:54:27 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com><7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com><8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com><13o06hleh4dkj45@corp.supernews.com> Message-ID: On Jan 7, 7:26 pm, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of Paddy > > Sent: Monday, January 07, 2008 12:52 PM > > To: python-l... at python.org > > Subject: Re: dictionary/hash and '1' versus 1 > > > Or how using different operators for similar operations on different > > types causes confusion. > > i.e. == versus eq; > versus gt > > If Perl had, for example, a complex number 'base' type would that need > > yet another set of operators? > > The real question is: what's the simplest way to implement complex > numbers without sacrificing understanding, accuracy, and convenience? I > would say, no new operators. Imaginary numbers are numbers and should > use numeric operations which means overloaded match operators. > > As background: In order to keep things simple, Perl's string operators > are string-like. Math operators are math. > '2' * 5 = 10 > '2' x 5 = '22222' ('x' is a char, so think strings) > ==, >, >=, <, <= > eq, gt, ge, lt, le (string abbreviations for equal, greater > than, etc.) > '1' + 1 = 2 > '1' . 1 = 11 (Think period at the end of a sentence, which > implies stringing strings together.) > > > Well enough Perl vs Python. The thing is, that when writing in another > > programming language you have to use its idioms or you end up fighting > > the language in attempt to make it work like another language you are > > more familiar with. In Python strings won't ever automatically change > > to numbers. > > Agreed. However looking towards the future (new versions of > Perl/Python, new languages, new paradigms) is it worth asking whether > it's better/clearer/easier/more_accurate to > a) type cast the data: a + b (a and b must be of the same type) > > a.1) explicitly type cast the data: str(a) + str(b) > (if a and b are different types) > b) type cast by operator: '1' + 1 = 2; '1' . 1 = '11' > c) go really old school with: concat('1', 1); add('1', 1) > > IMO, since Python is strongly but dynamically typed, a) is the 'worst' > solution. If you forget to type cast, you're boned, since you probably > won't find the problem until the code block is actually executed and an > exception is thrown. You could defensively type cast everything, but > that can clutter the code, and cluttered code is harder to understand > and keep bug free. With b) or c), the compiler will type cast as you > intended. Again, just my opinion. > > Anyway, it's little things like '1' + 1 that will probably prevent > programming syntax from ever being similar to naturally spoken language. > I guess it comes down to the differences in fundamental principles of Perl and Python. Perl is developed to "Do what I mean", whereas Python would be more like "Do as I say". Perl strives to be more like a spoken language, Python strives to have a core set of powerful & composable ideas. On your specific example I'd guess that both schemes work well its just that I am more comfortable with Pythons one set of more overloaded operators and vice-versa for yourself, leading us both to have problems when we switch between Perl and Python :-) - Paddy. From sromero at gmail.com Wed Jan 9 12:55:28 2008 From: sromero at gmail.com (Santiago Romero) Date: Wed, 9 Jan 2008 09:55:28 -0800 (PST) Subject: printing dots in simple program while waiting References: Message-ID: <4e3bde5c-7efb-4f0a-af33-973dff850e0c@l6g2000prm.googlegroups.com> On 9 ene, 17:48, John wrote: > i want to print something like: > > (1sec) working... > (2sec) working.... > (3sec) working..... > > where the 'working' line isn't being printed each second, but the dots > are being added with time. > > something like: > > import time > s = '.' > print 'working' > while True: > print s > time.sleep(1) > > however, this doesn't work since it prints: > > working > . > . Change > print s to > print s, (With the ending ",", which sends NO linefeed to stdout) Bye :) From lists at cheimes.de Sat Jan 19 18:18:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 20 Jan 2008 00:18:09 +0100 Subject: Python 3000 and import __hello__ In-Reply-To: References: Message-ID: <47928531.7030806@cheimes.de> Brad wrote: > Just playing around with Python3000 a2 release on Windows XP 32-bit x86. > > import __hello__ > > doesn't print 'hello world...' as it does on 2.5 > > The import doesn't fail or generate errors... just no output. Perhaps > this is by design? I changed the __hello__ frozen module a while ago. The print was unreliable for some new unit tests. Christian From cokofreedom at gmail.com Thu Jan 17 11:08:13 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 17 Jan 2008 08:08:13 -0800 (PST) Subject: Is this a bug, or is it me? References: <87myr4o3sg.fsf@mulj.homelinux.net> Message-ID: On Jan 17, 4:59 pm, "Neil Cerutti" wrote: > On Jan 17, 2008 10:44 AM, Hrvoje Niksic wrote: > > > "Neil Cerutti" writes: > > > > You cannot access a class's class variables in it's class-statement > > > scope, since the name of the type is not bound until after the class > > > statement is completed. > > > But they are still available as locals, so you can access them using > > their names, like this: > > > >>> class C: > > ... a = 1 > > ... b = 2 > > ... print a+b > > ... > > 3 > > Thanks! I had never tried that before. That actually solved my default > method argument problem. > > > > > The question is, why doesn't the OP's code snippet work? It seems > > that the generator expression can't read the surrounding locals(). > > But when you change the generator expression to a list comprehension > > using a pair of [] around it, it starts working. Compare: > > > class C(object): > > d = {} > > for a in 1, 2, 3: > > ignore = list((a, b) for b in (4, 5, 6)) > > > Traceback (most recent call last): > > File "", line 1, in > > File "", line 4, in C > > File "", line 4, in > > NameError: global name 'a' is not defined > > > with: > > > class C(object): > > d = {} > > for a in 1, 2, 3: > > ignore = [(a, b) for b in (4, 5, 6)] > > > It seems that generator expressions and list comprehensions have > > subtly different scoping rules. Whether this is a bug or not is a > > good question. > > Generator expressions, unlike list comprehensions, have their own > scope so that they don't "leak" names to the enclosing scope. The > Python rule forbidding access to the locals of enclosing scopes is > preventing the class names from working in the generator expression. > > -- > Neil Cerutti Ah, that explains why my random suggestion worked but was not helpful :) I feel like I am learning a lot today! From DustanGroups at gmail.com Thu Jan 31 17:57:07 2008 From: DustanGroups at gmail.com (Dustan) Date: Thu, 31 Jan 2008 14:57:07 -0800 (PST) Subject: Dictionary Keys question References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com> <58d1bc12-206f-4cec-ad86-928d16e962f5@i3g2000hsf.googlegroups.com> <8d69e9e8-c892-4c65-ac54-c184ce303a2e@i3g2000hsf.googlegroups.com> <87zlumjex9.fsf@benfinney.id.au> Message-ID: On Jan 31, 7:35 am, Ben Finney wrote: > Dustan writes: > > On Jan 30, 7:02 pm, FireNWater wrote: > > > Thank you for the explanation. . . I think I now have a (foggy) > > > understanding of hash tables. It seems to be a way to create order > > > (an index) out of disorder (random numbers or characters) behind > > > the scenes. . > > > The key thing to realize is, quite simply, don't rely on order in a > > dictionary. > > The poster to which you replied is using "order" as contrasted with > "disorder". Clearly dictionaries *do* have order that can be relied > upon. He was referring to the index. So was I, as in: Don't rely on the index, because the size of the dictionary can vary, and therefore, the index can vary, and therefore, the programmer must recognize that the order of looping can vary. If you're referring to the actual order of looping, then I and every good Python Guru (of which I am not one) disagrees with you. If not, then you're confusing the different meanings of "order" in this context. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 25 07:55:40 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 25 Jan 2008 13:55:40 +0100 Subject: object vs class oriented -- xotcl In-Reply-To: <13pi0mmk525f325@corp.supernews.com> References: <13pi0mmk525f325@corp.supernews.com> Message-ID: <4799dbf0$0$16980$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Thu, 24 Jan 2008 12:35:44 -0800, William Pursell wrote: > >> The ability to have an object change class is >> certainly (to me) a novel idea. Can I do it in Python? > > Yes, mostly. Example: > (snip) > > If you actually play around with this, you'll soon find the limitations. > For instance: > >>>> s.__class__ = int > Traceback (most recent call last): > File "", line 1, in > TypeError: __class__ assignment: only for heap types > Other limitations may appear with frameworks relying on metaprogramming features for their inner working so users don't have to worry about boilerplate - something you'll often find in recent web frameworks, orms etc... Mostly, the point with dynamically changing the class of an object (whether or not your in the above situation) is that you must ensure consistant state by yourself, which sometimes happens to be far less trivial than it seems at first look. I once tried to implement the State pattern this way (in real-life code), and while it worked, it ended being more complicated (and brittle) than implementing it the canonical way. So while it *may* be a good solution, I'd advise you to carefully check the concrete use case before using this feature. From aafshar at gmail.com Wed Jan 2 05:56:54 2008 From: aafshar at gmail.com (Ali) Date: Wed, 2 Jan 2008 02:56:54 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <13ndpflarf19i9c@corp.supernews.com> Message-ID: <8e29e3f8-831b-4b4f-8d8b-2fd681b51b37@e23g2000prf.googlegroups.com> On Dec 30 2007, 12:27 am, Steven D'Aprano wrote: > In the absence of a better solution, I'm very comfortable with keeping > the behaviour as is. Unfortunately, there's no good solution in Python to > providing functions with local storage that persists across calls to the > function: ... (4) Instances handle this pretty well, just s/functions/methods/. From PatrickMinnesota at gmail.com Wed Jan 2 14:08:28 2008 From: PatrickMinnesota at gmail.com (PatrickMinnesota) Date: Wed, 2 Jan 2008 11:08:28 -0800 (PST) Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <13nn9k48n7ohr95@corp.supernews.com> <69337707-ff18-4b39-af0a-78cf0a14b667@1g2000hsl.googlegroups.com> Message-ID: <4715e05f-456b-4274-9718-b6c009af7698@1g2000hsl.googlegroups.com> On Jan 2, 9:33 am, Aaron Watters wrote: > > I must admit I feel a hint of amusement though at your comment above, when > > it's sent from precisely the sort of setup you appear bemused by - since > > you appear to have already bought into it without realising ! :-D > > Ok, so if we include yahoo mail and gmail in "cloud computing" then I > guess > usenet is also cloud computing. How about ftp? ssh? nfs? Oh I get > it. It's > another meaningless marketing buzz phrase. > > I mean, really, I've been using web-mail and various varieties of > remote > storage for over a decade. What is *new* about the concept? (I see > some > hints above, but it's mixed in with a lot of other stuff...) > > -- Aaron Watters > > ===http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=fud Aaron - I would say that the biggest difference between what people have been doing for decades and what is now being referred to as 'cloud computing' is the applications. The idea of the cloud is that the application, like a word processor for instance, is not running or installed on your computer. It's running on Google's servers, or Zoho's servers etc. Your data is also stored on their servers. So yeah, it's kind of like the old diskless X-Terminal setup and is totally contrary to how companies like Microsoft would like the world to work. The other main difference seems to be that 'cloud computing' runs under a different revenue model than traditional applications like Microsoft Office. Google Apps, in it's most basic form is free and so are most of the others. They are monetizing in a different way than Microsoft does when it sells you Office for $500 or whatever. From jarausch at igpm.rwth-aachen.de Wed Jan 30 07:32:00 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 30 Jan 2008 13:32:00 +0100 Subject: Tkinter - incremental input ? Message-ID: <60b922F1pnj4bU1@mid.dfncis.de> Hi, I don't want to reinvent the wheel but I cannot find it so far. Many editors have a so-called incremental search feature. As you type characters, elements of a set of strings which fit so far are displayed or at least, the first one of these is displayed. Now I want to do something similar in Tkinter - an Entry widget which displays possible 'completions' e.g. given the list of names (...,'Hardy','Helmut',..) As soon as enter the character 'H' the string 'Hardy' would be displayed in the Entry widget - but the cursor is still at position 2 (given 'H' is a position 1) Furthermore, as soon as I enter 'e', it would change the text to 'Helmut', and so on. While I can bind '' to a callback, I haven't figured out how to get (and later on set) the cursor within the Entry widget. In other words I need to know at which character position the last character was entered. Currently I can only see the brute force method: keeping track of all cursor positioning means like , , the '<-' and '->' keys and mouse clicks. Is there an easier method? Many thanks for a hint or even a pointer to an example, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From MartinRinehart at gmail.com Mon Jan 7 08:32:34 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Mon, 7 Jan 2008 05:32:34 -0800 (PST) Subject: code doesn't reference immutables? Message-ID: <5e6d3674-fddb-402f-9e5c-19afcd7fcc22@i7g2000prf.googlegroups.com> >From the manual: "code objects are immutable and contain no references (directly or indirectly) to mutable objects" (3.2) I thought my code worked with both mutable and immutable objects. Whassup? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 14 19:26:53 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 15 Jan 2008 01:26:53 +0100 Subject: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net> Message-ID: <5v2cudF1k5a1oU1@mid.individual.net> John Nagle wrote: > It turns out that the strings in the "env" parameter have to be > ASCII, not Unicode, even though Windows fully supports Unicode in > CreateProcess. Are you sure it supports Unicode, not UTF8 or UTF16? Probably using something like u"thestring".encode("utf16") will help. Regards, Bj?rn -- BOFH excuse #31: cellular telephone interference From http Fri Jan 18 12:58:57 2008 From: http (Paul Rubin) Date: 18 Jan 2008 09:58:57 -0800 Subject: Efficient processing of large nuumeric data file References: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com> Message-ID: <7xve5ruiam.fsf@ruckus.brouhaha.com> David Sanders writes: > The data files are large (~100 million lines), and this code takes a > long time to run (compared to just doing wc -l, for example). wc is written in carefully optimized C and will almost certainly run faster than any python program. > Am I doing something very inefficient? (Any general comments on my > pythonic (or otherwise) style are also appreciated!) Is > "line.split()" efficient, for example? Your implementation's efficiency is not too bad. Stylistically it's not quite fluent but there's nothing to really criticize--you may develop a more concise style with experience, or maybe not. One small optimization you could make is to use collections.defaultdict to hold the counters instead of a regular dict, so you can get rid of the test for whether a key is in the dict. Keep an eye on your program's memory consumption as it runs. The overhead of a pair of python ints and a dictionary cell to hold them is some dozens of bytes at minimum. If you have a lot of distinct keys and not enough memory to hold them all in the large dict, your system may be thrashing. If that is happening, the two basic solutions are 1) buy more memory; or, 2) divide the input into smaller pieces, attack them separately, and merge the results. If I were writing this program and didn't have to run it too often, I'd probably use the unix "sort" utility to sort the input (that utility does an external disk sort if the input is large enough to require it) then make a single pass over the sorted list to count up each group of keys (see itertools.groupby for a convenient way to do that). From mr.cerutti at gmail.com Wed Jan 16 08:14:23 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Wed, 16 Jan 2008 08:14:23 -0500 Subject: no pass-values calling? In-Reply-To: References: <18c1e5f20801151909u4cdd227ah685741ea21734491@mail.gmail.com> Message-ID: <51302a8c0801160514m6c8f9b3dm2e98094e44daec68@mail.gmail.com> On Jan 16, 2008 7:58 AM, wrote: > On Jan 16, 1:21 pm, "Neil Cerutti" wrote: > > In the following function, a is rebound with an assignment statement, > > while b is mutated, i.e., changed, with an assignment statement. > > > > def f(a, b): > > a = 12 > > b.value = 14 > > > > Argument a will never be changed, while argument b will be. Python's > > argument passing semantics are extremely simple. It's the assignment > > statement that's tricky: some assignments mutate/change objects, and > > some only rebind names. > > So basically the scope is the reason for confusion a lot of the time? No, my hypothesis is that Python's assignment statement semantics are the tricky part--once you understand them, the utter simplicity of Python's argument passing semantics will be evident. -- Neil Cerutti From arne.k.h at gmail.com Wed Jan 23 11:06:10 2008 From: arne.k.h at gmail.com (Arne) Date: Wed, 23 Jan 2008 08:06:10 -0800 (PST) Subject: Trouble writing to database: RSS-reader References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> <4794e0f9$0$4429$426a74cc@news.free.fr> <739742b0-7d3d-4039-b793-ccefae4be721@1g2000hsl.googlegroups.com> Message-ID: On Jan 21, 11:25?pm, "Gabriel Genellina" wrote: > En Mon, 21 Jan 2008 18:38:48 -0200, Arne escribi?: > > > > > On 21 Jan, 19:15, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > >> This should not prevent you from learning how to properly parse XML > >> (hint: with an XML parser). XML is *not* a line-oriented format, so you > >> just can't get nowhere trying to parse it this way. > > >> HTH > > > Do you think i should use xml.dom.minidom for this? I've never used > > it, and I don't know how to use it, but I've heard it's useful. > > > So, I shouldn't use this techinicke (probably wrong spelled) trying to > > parse XML? Should i rather use minidom? > > > Thank you for for answering, I've learnt a lot from both of you, > > Desthuilliers and Genellina! :) > > Try ElementTree instead; there is an implementation included with Python ? > 2.5, documentation ?athttp://effbot.org/zone/element.htmand another ? > implementation available athttp://codespeak.net/lxml/ > > import xml.etree.cElementTree as ET > import urllib2 > > rssurl = 'http://www.jabber.org/news/rss.xml' > rssdata = urllib2.urlopen(rssurl).read() > rssdata = rssdata.replace('&', '&') # ouch! > > tree = ET.fromstring(rssdata) > for item in tree.getiterator('item'): > ? ?print item.find('link').text > ? ?print item.find('title').text > ? ?print item.find('description').text > ? ?print > > Note that this particular RSS feed is NOT a well formed XML document - I ? > had to replace the & with & to make the parser happy. > > -- > Gabriel Genellina This look very interesting! But it looks like that no documents is well-formed! I've tried several RSS-feeds, but they are eighter "undefined entity" or "not well-formed". This is not how it should be, right? :) From sromero at gmail.com Mon Jan 21 02:45:01 2008 From: sromero at gmail.com (Santiago Romero) Date: Sun, 20 Jan 2008 23:45:01 -0800 (PST) Subject: How to use py2exe ... Message-ID: Hi... I'm a Linux user, and I would like some windows-friends to test a game I'm writing with python+pygame without they needing to install python, pygame, and so on. I've heard about py2exe and pygame2exe, but I'm not sure on how to use them to create: a.- standalone exe files with a single .py program. Example: myprogram.py or b.- exe files containing all my source code + data directories (png files, data files, and so). Example: main.py, doc/README, src/*.py and data/* The problem is I'm not sure on how to use py2exe and pygame2exe to build the executables... And finally, a question: if I want to provide source code separately ... can I include .pyc files instead of .py files? From paul at boddie.org.uk Wed Jan 9 05:40:16 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 9 Jan 2008 02:40:16 -0800 (PST) Subject: how to open a file in some application using Tkinter i am using TKINTER to create GUI application i want to know how to open a word document in open office or any other applicatio References: Message-ID: <7b989c2e-7b7e-46be-b290-0c9203afcb46@f47g2000hsd.googlegroups.com> On 9 Jan, 09:24, Fredrik Lundh wrote: > [Opening files in applications] > on windows, you can use the "os.startfile" function: > > import os > os.startfile("mydocument.doc") > > (this is the same as double-clicking on a document in the file explorer) > > on other platforms, use os.system() and specify what application to run: > > import os > os.system("someapp mydocument.doc") Or try the desktop module which uses os.startfile on Windows, but employs mechanisms appropriate for other desktop environments elsewhere: http://www.python.org/pypi/desktop This code should do the trick: import desktop desktop.open("mydocument.doc") This assumes that your desktop environment knows how to handle .doc files, of course. Paul From LinkExchange.AB at gmail.com Sat Jan 19 10:56:43 2008 From: LinkExchange.AB at gmail.com (LinkExchange.AB at gmail.com) Date: Sat, 19 Jan 2008 07:56:43 -0800 (PST) Subject: Ruby Programming Message-ID: <5b554594-158f-4efe-9cd2-1fb66d150781@d4g2000prg.googlegroups.com> iTechArt has specialized in Ruby on Rails (ROR) development and provides a complete software outsourcing services for web development solutions based on Ruby. We suggest use Ruby framework for developing database-backed web applications with Ajax on front-end because it's a great fit for practically any type of web application: collaboration, community, e-commerce, content management and statistics. Ruby development environment and technologies: * Ruby On Rails development framework * MySQL, PostgreSQL, SQLite, Oracle, MS SQL Server, DB2 * RadRails IDE, ActionWebservice for Ruby * Linux, Apache, lighttpd * OOP and software development * Search engines optimization http://www.itechart.com/Pages/Subsections/RubyDevelopment.aspx From kent at kentsjohnson.com Mon Jan 21 17:50:18 2008 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 21 Jan 2008 22:50:18 GMT Subject: Prioritization function needed (recursive help!) In-Reply-To: <51180fda-304d-4f7e-812a-32032585675b@e23g2000prf.googlegroups.com> References: <51180fda-304d-4f7e-812a-32032585675b@e23g2000prf.googlegroups.com> Message-ID: <479521A1.4080105@kentsjohnson.com> rh0dium wrote: > Hi all, > > I need some help on writing a recursive priority function > > Given a list = [ A, B, C, D] > > Where the following constraints are in place: > > A depends on [B, C] > C depends on [B] > > Figure out real order that prioritizes these. You need a topological sort. http://en.wikipedia.org/wiki/Topological_sort Two Python implementations: http://pypi.python.org/pypi/topsort/0.9 http://www.bitformation.com/art/python_toposort.html Kent From erexsha at gmail.com Fri Jan 18 20:10:39 2008 From: erexsha at gmail.com (Arash Arfaee) Date: Fri, 18 Jan 2008 17:10:39 -0800 Subject: psyco on mac Message-ID: <266557d0801181710p5eb54420h79def10af5135985@mail.gmail.com> Hello, I have problem installing psyco on my mac. Can anybody help me? Thanks, Arash From nick at craig-wood.com Fri Jan 25 04:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 25 Jan 2008 03:30:03 -0600 Subject: piping into a python script References: <5vrovvF1njt09U6@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Thu, 24 Jan 2008 17:17:25 +0200, Donn Ingle wrote: > > > Given these two examples: > > 1. > > ./fui.py *.py > > 2. > > ls *.py | ./fui.py > > > > How can I capture a list of the arguments? > > I need to get all the strings (file or dir names) passed via the normal > > command line and any that may come from a pipe. > > > > There is a third case: > > 3. > > ls *.jpg | ./fui.py *.png > > Where I would be gathering strings from two places. > > > > I am trying to write a command-line friendly tool that can be used in > > traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. > > > > I have tried: > > 1. pipedIn = sys.stdin.readlines() > > Works fine for example 2, but example 1 goes into a 'wait for input' mode > > and that's no good. Is there a way to tell when no input is coming from a > > pipe at all? > > Usually Linux tools that can get the data from command line or files treat > a single - as file name special with the meaning of: read from stdin. > > So the interface if `fui.py` would be: > > 1. ./fui.py *.a > 2. ls *.a | ./fui.py - > 3. ls *.a | ./fui.py *.b - Did anyone mention the (standard library) fileinput module? (I missed the start of this thread.) http://docs.python.org/lib/module-fileinput.html 11.2 fileinput -- Iterate over lines from multiple input streams This module implements a helper class and functions to quickly write a loop over standard input or a list of files. The typical use is: import fileinput for line in fileinput.input(): process(line) This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From timr at probo.com Tue Jan 22 01:14:10 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 22 Jan 2008 06:14:10 GMT Subject: py2exe and modules question References: Message-ID: <312bp39rg1h896jrufcmhjicrrvs455t4n@4ax.com> azrael wrote: > >I'm working on an application and i'm having some questions. I am >working with python 2.5, numpy and PIL. does anyone know if there are >some problems while compiling the source because of the modules.. It >has to be closed source. What does that mean to you? >I didn't try Py2exe but I heard about it. Is there any other and >better way to compile the source. It isn't really "compiled". What all of the Python-to-executable apps do is bundle up your script, all of its modules, the Python interpreter DLL, and any DLLs they might need, and shove them in a single file (.zip, in the py2exe case). The parts get extracted for execution. The distribution will still contain the .pyc files, and there are tools that can decompile a .pyc without much trouble. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ggpolo at gmail.com Mon Jan 7 13:48:28 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 7 Jan 2008 16:48:28 -0200 Subject: any() and all() shorthand In-Reply-To: References: Message-ID: 2008/1/7, castironpi at gmail.com : > any( iterab ) and all( iterab ) > > as shorthand for reduce( operator.or_, iterab ) and > reduce( operator.and_, iterab ). > > What do you think? > -- > http://mail.python.org/mailman/listinfo/python-list > You are too late, any and all are built-in into python 2.5 -- -- Guilherme H. Polo Goncalves From boblatest at yahoo.com Wed Jan 9 06:21:36 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 11:21:36 GMT Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <87ejcri96v.fsf@mulj.homelinux.net> <87abnfi84i.fsf@mulj.homelinux.net> Message-ID: <5ujp20F1ehvg2U2@mid.dfncis.de> Hrvoje Niksic wrote: > keywords[:] = (s for s in keywords if s) Looks good but is so far beyond my own comprehension that I don't dare include it in my code ;-) robert From n.s.buttar at gmail.com Sun Jan 27 13:40:40 2008 From: n.s.buttar at gmail.com (Navtej Singh) Date: Mon, 28 Jan 2008 00:10:40 +0530 Subject: REALLY simple xml reader In-Reply-To: References: Message-ID: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> check the implementation of XMLNode class here http://hsivonen.iki.fi/group-feed/flickrapi.py HTH N On Jan 27, 2008 11:05 PM, Simon Pickles wrote: > Hi > > Can anyone suggest a really simple XML reader for python? I just want to > be able to do something like this: > > xmlDoc = xml.open("file.xml") > element = xmlDoc.GetElement("foo/bar") > > ... to read the value of: > > > 42 > > > > Thanks > > Simon > > -- > Linux user #458601 - http://counter.li.org. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From Lie.1296 at gmail.com Tue Jan 15 17:02:43 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 15 Jan 2008 14:02:43 -0800 (PST) Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <87lk6sf3ry.fsf@benfinney.id.au> <87ir1wf1wi.fsf@mulj.homelinux.net> <87k5mbd8bv.fsf@benfinney.id.au> Message-ID: I've been in this Python mailing list for a few days, and I've noticed several things here: There are too many fundamentalist! Don't play stupid and all, don't be a fundamentalist. It might be true that __init__ isn't a constructor and __new__ might be the constructor (some people even claimed __new__ is also not a constructor). >From the base definition of a constructor: constructor is the creator of an object. In this case, __new__ is technically the constructor while __init__ is an initializer. However, it is also to be noted that __init__ is what makes an object meaningful, and that makes it a constructor in a sense (while still technically a constructor). Without initialization, an object is meaningless, even if the definition of the initializer is to leave it as it is. Python creates object by doing something like this: a = anObject(arg1, arg2, arg3) These arguments is then passed to __new__ and __init__ for their arguments in its sake of creating and initializing the object. Then anObject() returns an instance of anObject. >From an outsider's point of view, there is no difference between __new__ and __init__ since they're "implementation details" (in other languages, these are private functions[1] that is invisible to outsiders, Python doesn't like privacy but the semantic of being implementation detail still exist). For an outsider, there is absolutely no need to know that __new__ and __init__ exists, they just need to know anObject()'s arguments, which is the public view of the constructor and initializer[2]. [1] Well, for fundamentalists: constructors aren't usually private though, usually they're Friend or Protected Friend which prohibits outsiders from calling it but allow other classes inheriting from it to call them. [2] In this sense, from outsider's POV anObject() is the constructor. If you can't be convinced with this argument, then I'd give you another that's a bit more Pythonic: DUCK TYPING: If it looks like a duck, walks like a duck, and quacks like a duck, it is a duck! >From the class programmer's point of view, __init__ acts like an object constructor in other languages, there is no significant difference between __init__ and constructor in other languages. The fact that __init__ works with side-effect as opposed to returning the object is not a significant point and can be considered as an implementation difference (I'm not aware of any major programming language that returns an instance of itself in its return value [except for Python]). For example, in VB.NET, there is no doubt that Sub New() is a constructor, despite New() works only by side effect, and returning anything results in an error (since it is a Sub or a method in Python's dictionary). Not only VB, C++ and C# also use side effect in its constructors and doesn't return a value. In this sense, VB's New, C ++ constructor, and C# constructor is equal to Python's __init__, thus the Duck Typing spirit applies here. From brzrkr0 at gmail.com Thu Jan 3 12:39:41 2008 From: brzrkr0 at gmail.com (brzrkr0 at gmail.com) Date: Thu, 3 Jan 2008 09:39:41 -0800 (PST) Subject: C++ equivalent of comp.lang.python? Message-ID: <60597295-1493-493c-969c-a14dd7da98a3@s19g2000prg.googlegroups.com> Hopefully this isn't too OT. One thing I like about comp.lang.python is the breadth of topics discussed here. People can ask about Python installation and configuration issues on specific platforms, compare third party libraries, ask for book recommendations, and discuss current Python projects. Lurking here has greatly increased my understanding of Python over the last year or so. I also do a lot of C++ development, but I've never found a similar discussion group for that language. comp.lang.c++ isn't what I'm looking for. I find it hard to get practical advice on that group because its focus is so narrow. I frequently see posters there redirect people to one of the OS-specific C++ groups, but most of my projects are cross-platform, so hanging out on one of those doesn't make sense either. As an example, I was recently trying to get information about writing cross-platform code for dynamic linking, but I couldn't find anywhere appropriate to ask about it. For those of you who work in C++, where do you go to discuss it online? I'm interested in any newsgroups, mailing lists, or web boards you can recommend. Thanks, Casey From marcroy.olsen at gmail.com Tue Jan 29 03:45:54 2008 From: marcroy.olsen at gmail.com (marcroy.olsen at gmail.com) Date: Tue, 29 Jan 2008 00:45:54 -0800 (PST) Subject: Intra-package References?? (again) Message-ID: Hi Python list, I have been struggleling with this before, but have never been able to find a good solution. The thing I dont understand is, I follow the guide here: http://docs.python.org/tut/node8.html#SECTION008420000000000000000 And have the same setup as the packages howto here:http:// docs.python.org/tut/node8.html#SECTION008400000000000000000 But when I want to use Intra-package References, I need to put the path to the packages explicit like this: #sys.path.append('/path/to/pack/') Before I can make import like this: #from Sound.Effects import echo from within the karaoke.py (just to stay with the tut) If I print the sys.path from the same file, I can see that #/path/to/pack/Sound/Filters/ is in the path. Is there something that I completely is missing or could someone please show me how, by example, how I use Intra-package References. Best regards Marc From jr9445 at ATT.COM Fri Jan 11 13:01:13 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 11 Jan 2008 12:01:13 -0600 Subject: reading a specific column from file In-Reply-To: <4fb9145b-6930-4d89-a4a3-ddd3504373aa@e23g2000prf.googlegroups.com> References: <4fb9145b-6930-4d89-a4a3-ddd3504373aa@e23g2000prf.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 Ivan Novick > Sent: Friday, January 11, 2008 12:46 PM > To: python-list at python.org > Subject: Re: reading a specific column from file > > > You say you would like to "read" a specific column. I wonder if you > meant read all the data and then just seperate out the 3rd column or > if you really mean only do disk IO for the 3rd column of data and > thereby making your read faster. The second seems more interesting > but much harder and I wonder if any one has any ideas. Do what databases do. If the columns are stored with a fixed size on disk, then you can simply compute the offset and seek to it. If the columns are of variable size, then you need to store (and maintain) the offsets in some kind of index. ***** 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 azam.farooq3 at gmail.com Thu Jan 24 03:43:11 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Thu, 24 Jan 2008 00:43:11 -0800 (PST) Subject: ENMAC Mobile Phones, iPods EQ100 www.enmac.com.hk Message-ID: <1bd560ad-b579-49e5-abeb-2111d2843aa6@e25g2000prg.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 sjmachin at lexicon.net Wed Jan 23 15:02:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 12:02:57 -0800 (PST) Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> <12d19814-b7b9-44b0-aee3-299befac7279@i12g2000prf.googlegroups.com> Message-ID: <66446d1e-189c-4c24-bd7a-83cbd66deb60@i12g2000prf.googlegroups.com> On Jan 24, 6:57 am, ryan k wrote: > So yea i will just have to count dashes. Read my lips: *you* counting dashes is dumb. Writing your code so that *code* is counting dashes each time it opens the file is smart. From mr.cerutti at gmail.com Mon Jan 14 13:43:47 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Mon, 14 Jan 2008 13:43:47 -0500 Subject: __init__ explanation please In-Reply-To: References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> <87myr8v3p4.fsf@mulj.homelinux.net> <873at0mkv7.fsf@mulj.homelinux.net> Message-ID: <51302a8c0801141043s7d11c0b7t3c25e7662cf4dfd7@mail.gmail.com> On Jan 14, 2008 12:08 PM, 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 Hrvoje Niksic > > Sent: Monday, January 14, 2008 11:29 AM > > Only if by "construct" you mean "allocate". __init__ starts out with > > an empty object and brings it to a valid state, therefore > > "constructing" the object you end up with. That operation is exactly > > what other languages call a constructor. > > Nah. Most other languages combine the constructor and an init function. > Normally with c++ I'll have the constructor call an Init() function so I > can re-initialize the object as needed. Python has explicitly split the > two. > Besides, the Python docs say that __new__ is the constructor and > __init__ may or may not be called after the instance is created: The documentation of __new__ carefully refrains from calling __new__ a constructor. Both __new__ and __init__ mention the object constructor expression, e.g., "list()". > __init__( self[, ...]) > Called when the instance is created. > ... > As a special constraint on constructors, no value may be > returned; Once again, the documentation is referring to constructor expressions. As you noted, __init__ may return a value when not called by a constructor expression. C++'s constructor initialization lists are the closest thing to Python's __new__. They can perform tasks for which Python might need __new__. For example, a class member that's a reference must be initialized in the initialization list, because it cannot be set once the body of the constructor begins. -- Neil Cerutti From jr9445 at ATT.COM Wed Jan 9 15:34:26 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 9 Jan 2008 14:34:26 -0600 Subject: problem of converting a list to dict In-Reply-To: References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com><962fbe61-bf37-4796-97ae-55af89a8d7f8@k39g2000hsf.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 John Machin > Sent: Wednesday, January 09, 2008 3:02 PM > To: python-list at python.org > Subject: Re: problem of converting a list to dict > > On Jan 10, 6:52 am, "Reedick, Andrew" wrote: > > > > A bigger hint: > > a=i.split('=') > > print "'%s' splits into " % (i), a > > consider: > (1) using %r instead of '%s' Eh, personal preference depending on how sure you are of the data's type. > (2) omitting the redundant space after 'into' Some of us coming in from other languages and still aren't used to the comma adding an unwanted space after everything. I've been tempted to root around in Python's source code to fix the problem. > (3) losing the redundant () around i For me, the () is there for readability. Python's sprintf syntax is odd to begin with, and something like print "'%s' splits into " % i, a, b, c means either 1) you really do want to append b and c after the sprintf, or print "'%s' splits into " % (a), b, c 2) that the formatting string is missing a few things print "'%s' splits into " % (a, b, c) ## Ooops! forgot to change it to "%s %5.2d %6.3f" ***** 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. GA622 From steve at REMOVE-THIS-cybersource.com.au Mon Jan 21 17:09:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 22:09:29 -0000 Subject: Bug in __init__? References: <88580064-3590-471e-8036-a631dd5a38b4@i3g2000hsf.googlegroups.com> <50ed76e4-f865-4821-935f-310c96b0ecb9@e23g2000prf.googlegroups.com> Message-ID: <13pa60pgj3hur7d@corp.supernews.com> On Mon, 21 Jan 2008 17:38:10 -0200, Gabriel Genellina wrote: > En Mon, 21 Jan 2008 05:59:38 -0200, escribi?: > >> Is there no way of adding a possible warning message (that obviously >> could be turned off) to warn users of possible problems linked to using >> mutable types as parameters? >> >> Seems to me this could save users a few minutes/hours of headaches and >> headscratching. (The biggest issue affecting new programmers these >> days!) > > Most objects are mutable, such warning would happen so often that would > become useless. Not at all, for two reasons: (1) Using mutable defaults in function definitions is relatively unusual. Defaults like None, 0, 1 are far more common. (2) We can copy the behaviour of the warnings module. Possibly even use the warnings module. By default warnings are only shown once per session. > The only immutable objects are numbers, strings, tuples, None and a few > esoteric types; all other instances, including instances of all user > defined classes, are mutable unless explicitely their attributes are > read-only. It is true that Python doesn't have a cheap way of recognising mutable instances except by trying to mutate them. However, there is a case for having it issue a warning the first time in a session it spots a default list or dict, which would catch 99% of cases that newbies use a mutable default. Newbies being newbies, 30% of them will completely ignore the warning and bitch about the "bug", but that's better than the 80% that we have now :-) -- Steven From bearophileHUGS at lycos.com Sat Jan 26 05:02:31 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 26 Jan 2008 02:02:31 -0800 (PST) Subject: Generational Interfaces References: <1b7b3b47-72f0-4a5d-9185-4903e75dba47@d70g2000hsb.googlegroups.com> Message-ID: <833108f1-d5fa-4e10-b458-344551ec35bd@d4g2000prg.googlegroups.com> I think they can be called "soft interfaces" or "heuristic interfaces", it's an example of machine learning. I think it's not easy to apply such idea to a statically typed language, but probably it can be done on Java. I presume in the future GUI will learn more about the usage patterns of their users, data structures of long- running programs will adapt to their average usage in each specific point of the program, and maybe class interfaces too will become smarter, as you say :-) I think your idea can be implemented in Python too, so you just have to try to use it in some project of yours developed with some Agile programming style, so you can tell us if it's nice to use :-) Bye, bearophile From lizm at rcsltd.co.uk Thu Jan 24 08:59:52 2008 From: lizm at rcsltd.co.uk (LizzyLiz) Date: Thu, 24 Jan 2008 05:59:52 -0800 (PST) Subject: csv to xls using python 2.1.3 References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> Message-ID: Unfortunately we have to stick with python 2.1.3 for this project. From dzizes451 at gmail.com Wed Jan 30 12:32:02 2008 From: dzizes451 at gmail.com (dzizes) Date: Wed, 30 Jan 2008 09:32:02 -0800 (PST) Subject: Python plugins for netbeans 6 IDE? In-Reply-To: <46F5F8FE.2020208@sbcglobal.net> References: <46F5F8FE.2020208@sbcglobal.net> Message-ID: <15186891.post@talk.nabble.com> Did you managed to work out NetBeans and Python? Ken McDonald wrote: > > Do any such exist? And do you find them worthwhile? I couldn't see any > browsing the netbeans pages, but that doesn't mean they're not out > there... > > Thanks, > Ken > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Python-plugins-for-netbeans-6-IDE--tp12843005p15186891.html Sent from the Python - python-list mailing list archive at Nabble.com. From gherron at islandtraining.com Thu Jan 17 03:47:13 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 17 Jan 2008 00:47:13 -0800 Subject: Replace stop words (remove words from a string) In-Reply-To: <01be01c858e4$c6b8b280$542a1780$@com> References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> <01be01c858e4$c6b8b280$542a1780$@com> Message-ID: <478F1611.4080001@islandtraining.com> Karthik wrote: > How about - > > for s in stoplist: > string.replace(mystr, s, "") > That will work, but the string module is long outdated. Better to use string methods: for s in stoplist: mystr.replace(s, "") Gary Herron > Hope this should work. > > -----Original Message----- > From: python-list-bounces+karthik3186=gmail.com at python.org > [mailto:python-list-bounces+karthik3186=gmail.com at python.org] On Behalf Of > BerlinBrown > Sent: Thursday, January 17, 2008 1:55 PM > To: python-list at python.org > Subject: Replace stop words (remove words from a string) > > if I have an array of "stop" words, and I want to replace those values > with something else; in a string, how would I go about doing this. I > have this code that splits the string and then does a difference but I > think there is an easier approach: > > E.g. > > mystr = > kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsldf > sd; > > if I have an array stop_list = [ "[BAD]", "[BAD2]" ] > > I want to replace the values in that list with a zero length string. > > I had this before, but I don't want to use this approach; I don't want > to use the split. > > line_list = line.lower().split() > res = list(set(keywords_list).difference(set(ENTITY_IGNORE_LIST))) > > > From bignose+hates-spam at benfinney.id.au Sun Jan 27 22:33:42 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 28 Jan 2008 14:33:42 +1100 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <8763xe8vzd.fsf@benfinney.id.au> "Russ P." writes: > On Jan 27, 5:13 pm, Wildemar Wildenburger > wrote: > > class Server(object): > > def __init__(self, self.host, self.port, > > self.protocol, self.bufsize, self.timeout): > > pass > > > > ? > > That makes sense to me. Not to me. 'self' is a name that doesn't exist until *after* that 'def' statement is completed; in any other statement, that would mean 'self.foo' in the same statement would raise a NameError. Special-casing it for a function declaration complicates the language for little gain: the rules of what is valid when become more complicated. Special cases aren't special enough to break the rules. -- \ "I took a course in speed waiting. Now I can wait an hour in | `\ only ten minutes." -- Steven Wright | _o__) | Ben Finney From fredrik at pythonware.com Wed Jan 9 15:59:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 21:59:34 +0100 Subject: ISO books of official Python docs In-Reply-To: References: Message-ID: Doug Morse wrote: > Several of the O'Reilly & Assoc. books -- such as Python in a Nutshell, The > Python Standard Library, etc -- are in large part reproductions of the > official docs and references. if you're using "reproduction" to mean "copy", I think you owe both me and Alex a big apology. From gagsl-py2 at yahoo.com.ar Wed Jan 30 08:24:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jan 2008 05:24:14 -0800 (PST) Subject: Removing hidden files and folders with python ... References: Message-ID: <001c398a-d48a-431b-95b1-da407da96122@i3g2000hsf.googlegroups.com> On 30 ene, 06:21, Konrad M?hler wrote: > I try to delete a whole directory-tree using shutil.rmtree(...) > But there are always the hidden files and folders (e.g. from the svn > .svn) left. > > How can I delete -all- files and folders (also the hidden) with python? I assume you use Windows. You have to reset the "readonly", "system" and "hidden" directory attributes. os.chmod can reset the first one, but for the others you have to use ctypes or the pywin32 package to call the SetFileAttributes function. Of course there is system too: os.system("attrib -r -h -s filename") You could use rmtree once, apply the above on the remaining files and directories -if any- and try rmtree again. -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Tue Jan 15 16:38:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 15 Jan 2008 21:38:32 -0000 Subject: Why this apparent assymetry in set operations? References: <18316.52462.481389.962217@montanaro.dyndns.org> <51302a8c0801150726k273a10qd333211e34c2e646@mail.gmail.com> Message-ID: <13oq9uo2rjruhb6@corp.supernews.com> On Tue, 15 Jan 2008 11:25:25 -0500, Colin J. Williams wrote: > I'm sorry, there appears to be a bug: # tSet.py > import sets > s1= sets.Set([1, 2, 3]) > s1.union_update([3, 4,5]) > print(s1) > s2= sets.Set([6, 7, 8]) > s1 |+ s2 # This fails: > exceptions.TypeError: bad operand type for unary +: 'Set' And so it should fail. Did you mean |= instead of |+ ? -- Steven From mani.sabri at gmail.com Tue Jan 29 02:06:49 2008 From: mani.sabri at gmail.com (mani) Date: Mon, 28 Jan 2008 23:06:49 -0800 (PST) Subject: Embeding python with mingw on win32 and python 2.4.4 References: <563a8060-8d79-4bc8-8306-9a5d77bfae5e@i72g2000hsd.googlegroups.com> Message-ID: <1eb2d4eb-e229-4230-a0e6-13dacf3a644e@s13g2000prd.googlegroups.com> It's me answering my self. I found the solution in http://groups.google.com/group/comp.lang.python/browse_thread/thread/4d80df2e53dfa127/de87533c05d8021c?lnk=gst&q=Py_Initialize+undefined+reference#de87533c05d8021c It was the problem of gcc arguments order. From faber at linuxnj.com Sat Jan 12 10:29:30 2008 From: faber at linuxnj.com (Faber J. Fedor) Date: Sat, 12 Jan 2008 10:29:30 -0500 Subject: where do my python files go in linux? In-Reply-To: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> Message-ID: <20080112152930.GA28685@neptune.faber.nom> On 12/01/08 12:02 +0100, Jorgen Bodde wrote: > Hi All, > > I am trying to make a debian package. I am following the tutorial by > Horst Jens (http://showmedo.com/videos/video?name=linuxJensMakingDeb&fromSeriesID=37) > and it is very informative. However one thing my app has and his > doesn't, is multiple python files which need to be executed. For > example > > {dir}/app > app.py > > app.py calls a lot of modules in {dir}/app. Horst says the python file > goes in /usr/bin/app.py which is ok with me, but I have multiple > python files, and I decided to use an app.sh script to call my python > files. In the /usr/bin I do not see subdirs so I assume that is not > really desirable. > > Question 1. Where do I put the bulk of python scripts in a normal > linux environment? I would think you'd create a directory /usr/bin/app and then symlink /usr/bin/app.py to /usr/bin/app/app.py. > Question 2. Should I use *.pyc rather then *.py files to speed up > executing as the user cannot write to /usr/bin or any other dir in the > system and everytime my app runs it will recompile it That would make sense. > Thanks for any advice or maybe a good tutorial how to set up files in > a linux environment http://www.pathname.com/fhs/ (couldn't find a more recent version, sorry.) -- Regards, Faber Fedor President Linux New Jersey, Inc. 908-320-0357 800-706-0701 http://www.linuxnj.com -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From __peter__ at web.de Mon Jan 7 09:40:40 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 7 Jan 2008 15:40:40 +0100 Subject: introspection question References: Message-ID: Alex K wrote: > What would be the simplest way of enumerating all methods and members > (including inherited) of a given object? Thank you. inspect.getmembers() Peter From kyosohma at gmail.com Wed Jan 2 10:49:20 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 2 Jan 2008 07:49:20 -0800 (PST) Subject: how to get playtime ( playback time ) of movie files? References: <7ab948ea-0ea9-47ab-80ff-73a95a4d958d@d21g2000prf.googlegroups.com> Message-ID: On Jan 2, 6:39 am, "Geon." wrote: > hi.. i want get playtime of movie files ( avi , mpeg , wav , mov > etc... ) > > how to get ?? > > please help me .. Take a look at PyMedia: http://pymedia.org/ Mike From nick at craig-wood.com Mon Jan 14 06:30:04 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 14 Jan 2008 05:30:04 -0600 Subject: where do my python files go in linux? References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> Message-ID: Jeroen Ruigrok van der Werven wrote: > -On [20080112 12:03], Jorgen Bodde (jorgen.maillist at gmail.com) wrote: > >app.py calls a lot of modules in {dir}/app. Horst says the python file > >goes in /usr/bin/app.py which is ok with me, but I have multiple > >python files, and I decided to use an app.sh script to call my python > >files. In the /usr/bin I do not see subdirs so I assume that is not > >really desirable. > > Personally I'd be loathe to put app.py in /usr/bin. This directory is normally > reserved for OS-specific binaries. For personal/system-extended stuff I'd use > /usr/local/bin or whatever your system mandates. I'd agree with that, except for the fact that he is making a .deb to be installed by the package manager. In Debian... /usr/bin is for stuff installed by the package manager which becomes effectively part of the OS. The package manager tracks every file it installes to ensure ovewrites can't happen etc... /usr/local/bin is for stuff installed from source, not using the package manager. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From kar1107 at gmail.com Sat Jan 26 04:03:40 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Sat, 26 Jan 2008 01:03:40 -0800 (PST) Subject: finding child cpu usage of a running child References: Message-ID: <4489d6b7-2462-4740-88ea-4fdd2739a84e@q39g2000hsf.googlegroups.com> On Jan 25, 11:59 pm, Paddy wrote: > On Jan 26, 5:43 am, Karthik Gurusamy wrote: > > > > > Hi, > > > Wondering if there is a way to measure a child process's cpu usage > > (sys and user) when the child is still running. I see os.times() > > working fine in my system (Linux 2.6.9-42.7.ELsmp), but it gives valid > > data only after the child has exited. When the child is alive, > > os.times() data for child is zero for both child-sys and child-user > > cpu. > > > My script (process P1) launches child process P2 (using > > popen2.Popen3). P2 is a long running process (big compilation). Every > > minute or so, from P1, I want to measure how much cpu P2 has consumed > > and based on that I can make some estimate on the completion time of > > P2 (I have a rough idea how much total cpu P2 needs to complete). > > > I understand it may be too expensive to update this information to the > > parent process when any of the child/grand-child completes; but > > wondering if any there is any way to get this info; the expensive > > operations is on-demand only when the request is made. > > > Thanks, > > Karthik > > I had a similar requirement in December and found: > http://lilypond.org/~janneke/software/ > > proc-time.c and proc-time.py poll /proc/.... files whilst command > is running to get stats. Great, thanks. From proc-time.py looks like all I want are the fields 13 to 16 of /proc//stat. And I see them updated in real time (probably the kernel does it on a periodic interrupt). Thanks, Karthik > > Enjoy, - Paddy. From paul at boddie.org.uk Fri Jan 25 18:17:24 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 25 Jan 2008 15:17:24 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> Message-ID: <45a8d4a7-d24d-461e-9783-59a7d697a041@q77g2000hsh.googlegroups.com> On 25 Jan, 22:06, "Lorenzo E. Danielsson" wrote: > > What you need then is something like SVGAlib (http;//svgalib.org). Only > really old people like myself know that it exists. I've never heard of > any Python bindings for it, but that might be where you come in. I > haven't looked at SVGAlib for years, and I'm not sure about the state of > the video drivers. I suggest you look at that first. I believe that SVGAlib was superseded by GGI and other projects, and I recall that SVGAlib was considered to be something of a nightware with respect to how it handles various resources. Certainly, I haven't been very impressed by the behaviour of software using it. > You could also look at GGI (http://ggi-project.org). GGI has different > output targets. IIRC, one of them is directfb. To tell you the truth > I've never really used GGI. There seems to be a python wrapper for GGI, > although it is fairly old. Maybe you could look at the code for some ideas. I've had to build software using GGI, and the biggest problem has been getting packages for it. That said, it seemed to work fairly acceptably once built and installed. Meanwhile, some people favour Allegro [1] for this kind of work, and I've been confronted with newly developed software which uses Allegro, so it's arguably in a different maintenance state than something like SVGAlib or GGI. > You should also be able to compile SDL to be able to use directfb as a > target. If your libSDL handles it, then that should apply to wrapper > libraries as well, including pygame. I've never tried running SDL apps > this way, but if it works well, that would probably be your 'best' option. I'd agree with these sentiments; SDL seems to be the best supported technology of this kind in the Python universe, and one of the most widely deployed in general; I've felt quite comfortable building software against it. It would be very interesting to see whether a framebuffer-based SDL could support Pygame, and I imagine that the Pygame mailing list might already have some answers in its archives on this topic. Paul [1] http://www.talula.demon.co.uk/allegro/ From nagle at animats.com Fri Jan 18 01:32:25 2008 From: nagle at animats.com (John Nagle) Date: Thu, 17 Jan 2008 22:32:25 -0800 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. In-Reply-To: <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> References: <478FAC5A.50206@animats.com> <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> Message-ID: <479046a5$0$36403$742ec2ed@news.sonic.net> Irmen de Jong wrote: > Christian Heimes wrote: >> John Nagle wrote: >>> It's possible to use "pickle" for interprocess communication over >>> pipes, but it's not straightforward. >> >> IIRC the processing module uses pickle for IPC. Maybe you can get some >> idea by reading its code? >> >> http://pypi.python.org/pypi/processing/0.40 >> "Processing" is useful, but it uses named pipes and sockets, not ordinary pipes. Also, it has C code, so all the usual build and version problems apply. > So does Pyro: http://pyro.sourceforge.net/ > > However Pyro uses TCP-IP sockets for communication. > > It uses a small header that contains the size of the message and a few > other things, and then the (binary by default) pickle stream. I'd thought I might have to add another layer of encapsulation to delimit "pickled" sections, but it turns out that's not necessary. So it doesn't take much code to do this, and it's all Python. I may release this little module. John Nagle From martin at librador.com Tue Jan 8 12:35:31 2008 From: martin at librador.com (Martin Vilcans) Date: Tue, 8 Jan 2008 19:35:31 +0200 Subject: I'm searching for Python style guidelines In-Reply-To: References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: On 1/7/08, Guilherme Polo wrote: > 2008/1/7, MartinRinehart at gmail.com : > > Anything written somewhere that's thorough? Any code body that should > > serve as a reference? > > PEP 8 > http://www.python.org/dev/peps/pep-0008/ The problem with PEP 8 is that even code in the standard libraries doesn't follow the recommendations regarding the naming of functions for example. The recommendation is to_separate_words_with_underscore, but some code uses lowerCamelCase instead. I tended to dislike the underscore convention, but after forcing myself to use it for a while I'm starting to appreciate its beauty. -- martin at librador.com http://www.librador.com From mr.cerutti at gmail.com Tue Jan 8 13:10:01 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Tue, 8 Jan 2008 13:10:01 -0500 Subject: I'm searching for Python style guidelines In-Reply-To: References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: <51302a8c0801081010x5f5110fn23594d83592b0036@mail.gmail.com> On Jan 8, 2008 12:35 PM, Martin Vilcans wrote: > On 1/7/08, Guilherme Polo wrote: > > 2008/1/7, MartinRinehart at gmail.com : > > > Anything written somewhere that's thorough? Any code body that should > > > serve as a reference? > > > > PEP 8 > > http://www.python.org/dev/peps/pep-0008/ > > The problem with PEP 8 is that even code in the standard libraries > doesn't follow the recommendations regarding the naming of functions > for example. The recommendation is to_separate_words_with_underscore, > but some code uses lowerCamelCase instead. > > I tended to dislike the underscore convention, but after forcing > myself to use it for a while I'm starting to appreciate its beauty. Conventions get broken when there's a good reason, e.g., elegant looking "deque" instead of clumsy looking "Deque". -- Neil Cerutti From Lie.1296 at gmail.com Mon Jan 14 14:09:43 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 14 Jan 2008 11:09:43 -0800 (PST) Subject: How to get user home directory on Windows References: <478ab8a1$0$20930$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <64437192-cb78-4659-a06b-febe1b8ea9b5@u10g2000prn.googlegroups.com> On Jan 14, 8:21?am, "Martin P. Hellwig" wrote: > Giampaolo Rodola' wrote: > > Hi all, > > I'm trying to use the pywin32 extension to find out the user's home > > directory but currently I didn't find a solution yet. > > What I'd need to do is not getting the home directory of the currently > > logged in user but something like: > > >>>> get_homedir("frank") > > "C:\home\users\frank" > >>>> get_homedir("josh") > > "C:\home\users\josh" > > > Is there a way to do that? > > I tried to search through the Pywin32 documentation with no luck. > > In addition I'm not practiced with the Windows API at all. > > Well, windows, to my knowledge, uses the same base path for all profiles > (this is not true for the My Documents folder which can differ). So what > you could do is get the location from the ALLUSERPROFILE environment > variable, go one folder higher and iterate through that. > Ignoring the folders for the 'pseudo' users: 'All Users', 'Default > User', 'LocalService' and 'NetworkService'. > > hth > -- > mph There is one problem with that, sometimes the folders for the users are not the same with the user name, usually because of deleting user name without deleting the profile, then recreate a user with similar name. It doesn't happens everytime, but it could. Possibly it is possible to get the SID of the user name (using the way described in Tim Golden's Microsoft Link' post), then find the user directory from the registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft \Windows NT\CurrentVersion\ProfileList\[PUT SID HERE]\Profile Image Path From siona at chiark.greenend.org.uk Wed Jan 16 09:31:05 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 16 Jan 2008 14:31:05 +0000 (GMT) Subject: UTF-8 in basic CGI mode References: <1f8a4051-27cb-48aa-a0ab-793f59ab3845@s13g2000prd.googlegroups.com> Message-ID: coldpizza wrote: >I am using this 'word' variable like this: > >print u'''''' % (word) > >and apparently this causes exceptions with non-ASCII strings. > >I've also tried this: >print u'''''' % >(word.encode('utf8')) >but I still get the same UnicodeDecodeError.. Your 'word' is a byte string (presumably UTF8 encoded). When python is asked to insert a byte string into a unicode string (as you are doing with the % operator, but the same applies to concatenation with the + operator) it attempts to convert the byte string into unicode. And the default encoding is 'ascii', and the ascii codec takes a very strict view about what an ASCII character is -- and that is that only characters below 128 are ASCII. To get it to work, you need to *decode* word. It is already UTF8 (or something) encoded. Under most circumstances, use encode() to turn unicode strings to byte strings, and decode() to go in the other direction. -- \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 vangale at gmail.com Thu Jan 31 15:23:51 2008 From: vangale at gmail.com (Van Gale) Date: Thu, 31 Jan 2008 14:23:51 -0600 Subject: sending a handmade SOAP request References: <21d3ff54-d20f-45dd-951b-0508682fc472@e6g2000prf.googlegroups.com> Message-ID: On Thu, 31 Jan 2008 11:03:26 -0800, Bernard wrote: > Hey y'all, > > Is there a way to POST a handmade SOAP request *without* using any > libraries like SOAPpy? Yes, it's quite easy to SOAP by hand. I use Oren Tirosh's ElementBuilder class (on top of lxml instead of ElementTree) to build the SOAP request and the xpath capabilities in lxml to pull out the data I need from the response. http://www.tothink.com/python/ElementBuilder/ http://codespeak.net/lxml/ An incomplete example for contructing a request looks something like this: body = Element('soap:Envelope', { 'xmlns:soap': nss['soap']}, Element('soap:Header'), Element('soap:Body', { 'xmlns:msgs': nss['msgs'] }, Element('msgs:login', Element('msgs:passport', { 'xmlns:core': nss['core'] }, Element('core:password', password), Element('core:account', account))))) I use httplib2 for sending the HTTP requests: http://code.google.com/p/httplib2/ Incomplete example: headers['SOAPAction'] = action headers['Content-length'] = str(len(etree.tostring(body))) response, content = self._client.request( self.ns_uri, "POST", body=etree.tostring(body), headers=self._headers) if response.status == 500 and not \ (response["content-type"].startswith("text/xml") and \ len(content) > 0): raise HTTPError(response.status, content) if response.status not in (200, 500): raise HTTPError(response.status, content) doc = etree.parse(StringIO(content)) if response.status == 500: faultstring = doc.findtext(".//faultstring") raise HTTPError(response.status, faultstring) Now it's just a matter of using xpath expressions to dig into the "doc" structure for the bits you need. From python.list at tim.thechases.com Wed Jan 30 09:06:28 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 30 Jan 2008 08:06:28 -0600 Subject: find nearest time in datetime list In-Reply-To: <47a07fa6$1_1@news.bluewin.ch> References: <47a07fa6$1_1@news.bluewin.ch> Message-ID: <47A08464.10901@tim.thechases.com> Boris Borcic wrote: > min(DTlist,key=lambda date : abs(dt-date)) In Python2.4: Traceback (most recent call last): File "", line 1, in ? TypeError: min() takes no keyword arguments Looks like min() only started taking keywords (key) from Python2.5 forward. But the min() solution is good if you're running 2.5 -tkc From stephen at theboulets.net Wed Jan 9 00:42:21 2008 From: stephen at theboulets.net (Stephen_B) Date: Tue, 8 Jan 2008 21:42:21 -0800 (PST) Subject: Default location of python on OS X References: <1519661f-97bd-4fdd-b2d5-a46dd9a81c81@e25g2000prg.googlegroups.com> Message-ID: On Jan 8, 11:33 pm, Tommy Nordgren wrote: > > I still have a "/Library/Python/2.3" and a "/Library/Python/2.5". > > > Thanks. > > > Stephen > Leopard INCLUDES Python 2.5, there is no need to install it. Thanks -- that made the decision easy. I didn't need all those MacPythons. Stephen From gdamjan at gmail.com Fri Jan 11 11:23:55 2008 From: gdamjan at gmail.com (Damjan) Date: Fri, 11 Jan 2008 17:23:55 +0100 Subject: virtualpython / workingenv / virtualenv ... shouldn't this be part of python Message-ID: <4787981c$0$90268$14726298@news.sunsite.dk> There are several attempts to allow python to work with per user (or even per session) 'site-packages' like virtualpython / workingenv / virtualenv. But they all have their own shortcomings and quirks. My question is, shoudn't it be enough to set PYTHONPATH and everything automagically to work then? Is there some work done on this for python 3.0 or 2.6 perhaps? -- damjan From hexamorph at gmx.net Fri Jan 25 17:09:38 2008 From: hexamorph at gmx.net (Hexamorph) Date: Fri, 25 Jan 2008 23:09:38 +0100 Subject: looking for a light weighted library/tool to write simple GUI above the text based application In-Reply-To: <479A4F71.9060501@gmail.com> References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> <8117ff57-9953-4b7f-9b13-8984388c9fed@s13g2000prd.googlegroups.com> <479A4F71.9060501@gmail.com> Message-ID: <479A5E22.30703@gmx.net> Lorenzo E. Danielsson wrote: > petr.jakes.tpc at gmail.com wrote: >> I think I was not specific/clear enough in my first posting. I know >> the curses library ( http://pyncurses.sourceforge.net ). It AFIK >> provides TUI (short for: Text User Interface or Textual User >> Interface). My needs are GUI, I mean "a nice VGA pictures" on the VGA >> LCD 10" display. >> >> Petr > > What you need then is something like SVGAlib (http;//svgalib.org). Only > really old people like myself know that it exists. I've never heard of > any Python bindings for it, but that might be where you come in. I > haven't looked at SVGAlib for years, and I'm not sure about the state of > the video drivers. I don't think that there's a Python binding for it. Svgalib never has gained enough popularity for anybody to write such bindings. However, as long as the video card supports VGA or VESA it should work. Another possibility might be using Xvesa (KDrive) which is a really tiny self-containing X server for VGA/SVGA/FBdev. With this you can atleast use simple GUI toolkits like Athena or TK or even use Xlib directly (if you don't fear that adventure) See: http://www.xfree86.org/current/Xvesa.1.html http://www.pps.jussieu.fr/~jch/software/kdrive.html HTH From Scott.Daniels at Acm.Org Tue Jan 1 13:12:40 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 01 Jan 2008 10:12:40 -0800 Subject: using super In-Reply-To: <4649f96c-10af-4dd1-864c-f0690cec1980@p69g2000hsa.googlegroups.com> References: <13nhtvb4pfpha84@corp.supernews.com> <13ni4e4t4n9uk10@corp.supernews.com> <13nk5l6oah7mh9b@corp.supernews.com> <4649f96c-10af-4dd1-864c-f0690cec1980@p69g2000hsa.googlegroups.com> Message-ID: <13nl0cg1sj0mpea@corp.supernews.com> iu2 wrote: > On Jan 1, 12:32 pm, Steven D'Aprano cybersource.com.au> wrote: >> import read_my_mind_and_do_what_I_want >> first. (Module expected in Python 9.7, due out in 2058.) > > That's because it seems to you like some esoteric feature. > To me it seems natural with OO. And the language should not bend to the sense of "natural" of one with a minor commitment to building that language. If this really is a great idea, implement it, put it out, support it and respond to the rigors of real use. You'll not convince me, but you needn't. Too many people want to go to a PEP (or even skip that step) once they have an idea they think might be good. The lesson I take from the histories of Ada and C++ are that "the less in the language the better." It is not enough that a language be chock-a-block with good ideas; each idea in the language must be compelling enough to counter-balance the mass that adding that idea adds. >> "Special cases aren't special enough to break the rules." > > I thought about this mechanism each time I had to call a base class > method. Lisp has it, out of the box. May be it's not so special... We accept this seems natural to you. You don't seem to understand why others might not think so. I fear this is the kind of thing that separates programmers into two classes: the smart ones that can set up the chains, and the others to whom you say "don't worry your pretty little head about it; it all happens auto-magically." Python is remarkably free of such things, and I am loathe to give that up. The value reduced auto-magic is that the users of the language can learn smoothly, rather than climbing steep mountains of understanding. Since you are relatively new to the language (I presume so, since you left self out of several method definitions), see how the language works on its terms first, before suggesting how to make it more like some other language you like. The explicit super call inside a method, and the disposition of its results makes experimentation with different ways to use the result tempting. There is a temptation to play with the arguments as well, that runs afoul of the vagaries of multiple inheritance, that is the reason that I said "if they don't want to understand super, then just explicitly name the superclass." --Scott David Daniels Scott.Daniels at Acm.Org From kar1107 at gmail.com Tue Jan 1 03:25:25 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 1 Jan 2008 00:25:25 -0800 (PST) Subject: pexpect ssh login and ls | grep References: <3eb81375-3e4a-4e0f-a4e7-bbb1d6cd0f8c@s19g2000prg.googlegroups.com> Message-ID: On Dec 31 2007, 6:46 pm, crybaby wrote: > 1) what are these characters: > \x1b]0; > ~\x07\x1b[?1034h > > in line '\x1b]0;my at mycomp2:~\x07\x1b[?1034h[my at mycomp2 ~]'? These are probably escape sequences in your shell prompt string. Typically they are interpreted by the terminal, like xterm, to update title bar. > > 2) Also, how come I don't get 0 or 2(excuting ls command exit code) > from result.split('\r\n')[0] or result.split('\r\n')[1] ? I don't think your expect worked fine to capture the desired output. > > This is what I get:>>> import pexpect > >>> child=pexpect.spawn('ssh my at mycomp2') > >>> child.sendline("ls mytest.log > /dev/null 2>&1; echo $?") > 41 > >>> child.before > >>> print child.before > None > >>> print child.after > None before/after makes sense only after an expect. At this point there is only a sendline; not expect. So the above None output is expected. > >>> child.expect([pexpect.TIMEOUT, '\$ ']) > 1 1 implies it matched the second pattern. You want to use raw strings. r'\$' or else the re sent down is a plain $ which re interprets as end of buffer. Most important here is your prompt doesn't end with a $ (it's something like [my at mycomp2 ~]). Thus make it, child.expect(r'.*]') Try the ls command and rest of the statements. Karthik > >>> result=child.before > >>> print result.split('\r\n')[1] > [my at mycomp2 ~] > >>> print result.split('\r\n')[0] > > Last login: Mon Dec 31 20:52:09 2007 from com1>>> print result.split('\r\n') > > ['Last login: Mon Dec 31 20:52:09 2007 from com1\r', > '\x1b]0;my at mycomp2:~\x07\x1b[?1034h[my at mycomp2 ~]'] From bearophileHUGS at lycos.com Tue Jan 15 14:27:04 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 15 Jan 2008 11:27:04 -0800 (PST) Subject: Data mapper - need to map an dictionary of values to a model References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com> <05398cdb-4c75-499b-bb52-d5de627a0906@j20g2000hsi.googlegroups.com> <49753620-df70-4f1a-95bc-7b23667d9edc@s13g2000prd.googlegroups.com> Message-ID: <5da17900-4404-407a-a406-b25a01035a96@l32g2000hse.googlegroups.com> Luke: > I'm not familiar with this pattern. I will search around, but if you > have any links or you would like to elaborate, that would be > wonderful. :) It's not a pattern, it's a little thing: def line_filter(filein, params): for line in filein: if good(line, params): yield extract(line, params) That equals to this too: def line_filter(filein, params): return (extract(line, params) for line in filein if good(line, params)) But probably that's not enough to solve your problem, so other people can give you a better answer. Bye, bearophile From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 11 04:15:32 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 11 Jan 2008 10:15:32 +0100 Subject: Python too slow? In-Reply-To: References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> Message-ID: <478733a9$0$18055$426a34cc@news.free.fr> Ross Ridge a ?crit : > Bruno Desthuilliers wrote: >> And the reference implementation of Python (CPython) is not >> interpreted, it's compiled to byte-code, which is then executed by a VM >> (just like Java). > > Ed Jensen a ?crit : >> Wow, this is pretty misleading. > > Bruno Desthuilliers wrote: >> Ho yes ??? Why so, please ? Care to point to anything *wrong* in the >> above statement ? > > Python's byte-code interpreter is not "just like" Java's virtual machine. of course it's not "just like" - different languages, different byte-codes, different implementations. What is "just like" is the byte-code/VM scheme. Thought this was obvious to anyone able to parse a simple sentence. > You're deliberately trying to mislead people into thinking Python performs > similarily to Java. I don't know what you're smoking, but you should perhaps stop - because this seems to drive you into parano?d delirium. From arnodel at googlemail.com Tue Jan 29 08:07:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 29 Jan 2008 05:07:17 -0800 (PST) Subject: extending Python - passing nested lists References: Message-ID: <3ddeaf07-3f4b-4d68-a176-9205fa4d234b@k39g2000hsf.googlegroups.com> On Jan 29, 12:48?pm, Christian Meesters wrote: > Think, that I'm still at the wrong track. Point is that I cannot find any > examples and don't know where to start here. > Perhaps my problem boils down to two questions: > I'd like to pass lists (in some cases nested ones) from Python to C and > convert those Python-lists to C-arrays (e. g. of doubles). My second wish > is to return a C-array of longs to a Python list. > > My approach so far: > > static PyObject *_foo(PyObject *self, PyObject *args) { > ? double *v; > ? if (!PyArg_Parse(args, "(d)", &v)) > ? ? return NULL; > ? // then I can't access v like v[1] ... I'm not a C API guru and I may not understand properly what info you are looking for but from http://docs.python.org/api/sequence.html: PyObject* PySequence_GetItem( PyObject *o, Py_ssize_t i) Return value: New reference. Return the ith element of o, or NULL on failure. This is the equivalent of the Python expression "o[i]". > ? > ? // then return *v > ? return with something like PyBuildValue (but didn't get so far) This allows you to create a list (from http://docs.python.org/api/listObjects.html): PyObject* PyList_New( Py_ssize_t len) Return value: New reference. Return a new list of length len on success, or NULL on failure. Note: If length is greater than zero, the returned list object's items are set to NULL. Thus you cannot use abstract API functions such as PySequence_SetItem() or expose the object to Python code before setting all items to a real object with PyList_SetItem(). ...and this allows you to populate it (from http://docs.python.org/api/listObjects.html): int PyList_Append( PyObject *list, PyObject *item) Append the object item at the end of list list. Return 0 if successful; return -1 and set an exception if unsuccessful. Analogous to list.append(item). > > } > > Can somebody give me a hint here, please? Passing simple arguments to and > fro (e. g. single integer values) is no problem, but lists of unknown size? HTH -- Arnaud From bj_666 at gmx.net Thu Jan 10 18:44:01 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Jan 2008 23:44:01 GMT Subject: adding methods at runtime References: <940fcb28-764e-46ab-a627-aff513e009e1@j78g2000hsd.googlegroups.com> Message-ID: <5unou0F1ifu47U1@mid.uni-berlin.de> On Thu, 10 Jan 2008 14:55:18 -0800, zslevi at gmail.com wrote: > Can I access the class attributes from a method added at runtime? (My > experience says no.) > I experimented with the following code: > > [Code snipped] > > So it seems to me, if you add a method to an instance, the method will > not get "self" as parameter. You are not adding a method but a function. Take a look at `types.MethodType()` to create a method from a function, instance, and class. Ciao, Marc 'BlackJack' Rintsch From robert.kern at gmail.com Wed Jan 23 16:29:50 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 23 Jan 2008 15:29:50 -0600 Subject: When is min(a, b) != min(b, a)? In-Reply-To: References: <13p9hdmh7c08abe@corp.supernews.com> Message-ID: Russell E. Owen wrote: > In article , > Christian Heimes wrote: > >> Grant Edwards wrote: >>> In many applications (e.g. process control) propogating NaN >>> values are way too useful to avoid. Avoiding NaN would make a >>> lot of code far more complicated than would using them. >> NaNs are very useful for experienced power users but they are very >> confusing for newbies or developers without a numerical background. >> >> It's very easy to create an inf or nan in Python: >> >> inf = 1E+5000 >> ninf = -inf >> nan = inf * 0. >> >> 1E5000 creates a nan because it is *much* bigger than DBL_MAX (around >> 1E+308). In fact it is even larger than LDBL_MAX (around 1E+4932). > > Isn't it safer to use float("inf"), float("-inf") and float("nan") to > create the necessary items? In currently-released versions of Python, these are not portable. float(some_string) just passes the string to the platform's conversion function. There is no standard defining what to do with "nan" or "inf". On Linux, these work as intended, but on Windows, they are errors. Christian is working on a branch to standardize these forms for Python 2.6. See "math and numerical fixes" in this thread. -- 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 i.shoba3 at gmail.com Wed Jan 16 11:34:52 2008 From: i.shoba3 at gmail.com (i.shoba3 at gmail.com) Date: Wed, 16 Jan 2008 08:34:52 -0800 (PST) Subject: Internet Message-ID: Internet You are using internet %%%%%%%%%%%%%%%%%%%% http://padmagirl.blogspot.com %%%%%%%%%%%%%%%%%%%%% From cptnwillard at gmail.com Thu Jan 17 10:22:12 2008 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Thu, 17 Jan 2008 07:22:12 -0800 (PST) Subject: Is this a bug, or is it me? References: <4044206c-9fd8-4dc1-8fe9-61edb314b9f5@k39g2000hsf.googlegroups.com> Message-ID: On Jan 17, 4:14 pm, cokofree... at gmail.com wrote: > > Do not use those names...really poor choice... This is not the way it looks it my code. I simplified it, with generic names, in order to point out something that does not work... The only question here is why? From jr9445 at ATT.COM Wed Jan 16 14:33:27 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 16 Jan 2008 13:33:27 -0600 Subject: Creating unique combinations from lists In-Reply-To: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.googlegroups.com> References: <895788b0-e8ac-4714-bb74-65584a4e669e@f3g2000hsg.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 breal > Sent: Wednesday, January 16, 2008 2:15 PM > To: python-list at python.org > Subject: Creating unique combinations from lists > > I have three lists... for instance > > a = ['big', 'small', 'medium']; > b = ['old', 'new']; > c = ['blue', 'green']; > > I want to take those and end up with all of the combinations they > create like the following lists > ['big', 'old', 'blue'] > ['small', 'old', 'blue'] > ['medium', 'old', 'blue'] > ['big', 'old', 'green'] > ['small', 'old', 'green'] > ['medium', 'small', 'green'] > ['big', 'new', 'blue'] > ['small', 'new', 'blue'] > ['medium', 'new', 'blue'] > ['big', 'new', 'green'] > ['small', 'new', 'green'] > ['medium', 'new', 'green' ] > > I could do nested for ... in loops, but was looking for a Pythonic way > to do this. Ideas? http://www.python.org/dev/peps/pep-0202/ From martin at v.loewis.de Wed Jan 16 23:59:44 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 Jan 2008 05:59:44 +0100 Subject: Hebrew in idle ans eclipse (Windows) In-Reply-To: References: Message-ID: <478ee0c0$0$4589$9b622d9e@news.freenet.de> > What do I need to do run my app like IDLE does? Can you please show the fragment of your program that prints these strings? Regards, Martin From rupert.thurner at gmail.com Thu Jan 24 11:08:49 2008 From: rupert.thurner at gmail.com (rupert.thurner) Date: Thu, 24 Jan 2008 08:08:49 -0800 (PST) Subject: finding memory leak in edgewall trac 0.11 References: <479213D2.2020701@cheimes.de> <20080119202909.GY61556@nexus.in-nomine.org> <0c6fc35d-91d2-4767-968d-e6eb56096eba@z17g2000hsg.googlegroups.com> <4f9304e4-3847-41ee-8064-b881f7b9e073@f47g2000hsd.googlegroups.com> Message-ID: <8c32936d-00fe-46f6-ac10-33321d5a84ce@d21g2000prf.googlegroups.com> On Jan 20, 2:59?pm, Christian Heimes wrote: > rupert.thurner wrote: > > i forgot to mention that i cannot see any explicit sys._getframe(), or > > __del__ in the genshi code, while the ones intrac-core seemed to be > > there in 0.10.4. > > Does the code keep a reference to a traceback object or an attribute of > a traceback object? > > Christian if there is no other possibility but doing it with sys.exc_traceback, sys.last_traceback, sys.exc_info, the answer is no for genshi. From steve at holdenweb.com Thu Jan 31 17:00:44 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 17:00:44 -0500 Subject: Design question - Sharing of single object by multiple processes In-Reply-To: <2b54d4370801311208s4af458cdp8cea665a04c3bd7a@mail.gmail.com> References: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> <47A1AC61.7080007@holdenweb.com> <2b54d4370801311206j457ef51cm33d2a2420b11e688@mail.gmail.com> <2b54d4370801311208s4af458cdp8cea665a04c3bd7a@mail.gmail.com> Message-ID: Mike D wrote: > Steve, > > Thanks for the response. My question really comes down to, as you > suggested, premature optimization. > > It is more for my own understanding than a current practical use. > > If an object is loaded into memory and other threads(or processes) can > recieve a pointer to this location, would this not be more efficient > than to load a new one for every unique request? Wouldn't a method such > as this prevent bottle necks in a read heavy environment? > In theory, yes. In practice there are problems, since modern operating systems are explicitly designed to place barriers between the address spaces of different processes. Even supposing you could access another Python process's space freely you would then have issues like: * does a reference from a foreign process add to an object's reference count? * if so, what happens if the foreign process terminates without decrementing the reference count * otherwise waht happens if the owning process disposes of the object while the foreign process stil wants to refer to it. I don't wish to be unkind, but these are well-known issues of inter-process information sharing, and while superficial solutions can seem easy, the more you think about and work on them the more obvious it becomes that these are hard problems in the general case. Which will hopefully at least encourage you that you are addressing the real issues of computing, even though there's a lot to do. > [...] regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From __peter__ at web.de Tue Jan 22 14:58:37 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 Jan 2008 20:58:37 +0100 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <7xir1mplls.fsf@ruckus.brouhaha.com> Message-ID: Arnaud Delobelle wrote: > On Jan 22, 4:10?pm, Alan Isaac wrote: > >> >> >> fwiw, >> Alan Isaac > > Thanks. So I guess I shouldn't take the code snippet I quoted as a > specification of izip but rather as an illustration. You can be bolder here as the izip() docs explicitly state """ Note, the left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using "izip(*[iter(s)]*n)". """ and the bug report with Raymond Hettinger saying """ Left the evaluation order as an unspecified, implementation specific detail. """ is about zip(), not izip(). Peter From teddyber at gmail.com Fri Jan 11 14:47:07 2008 From: teddyber at gmail.com (teddyber) Date: Fri, 11 Jan 2008 11:47:07 -0800 (PST) Subject: split parameter line with quotes References: Message-ID: <2515c260-680f-4d27-9f0d-a7bf1dd1f8cf@21g2000hsj.googlegroups.com> On 11 jan, 20:28, Nanjundi wrote: > On Jan 11, 1:50 pm, teddyber wrote: > > > Hello, > > > first i'm a newbie to python (but i searched the Internet i swear). > > i'm looking for some way to split up a string into a list of pairs > > 'key=value'. This code should be able to handle this particular > > example string : > > > qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, > > 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess > > > i know i can do that with some regexp (i'm currently trying to learn > > that) but if there's some other way... > > > thanks > > This is unconventional and using eval is not SAFE too.>>> s = 'qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,3des",maxbuf=1024,charset="utf-8",algorithm="md5-sess"' > >>> d = eval(' dict(%s)' % s) > >>> d.items() thanks for that. The problem is i don't have charset="utf-8" but charset=utf-8. Sometimes " sometimes not! > > [('algorithm', 'md5-sess'), ('maxbuf', 1024), ('charset', 'utf-8'), > ('cipher', 'rc4-40,rc4-56,rc4,des,3des'), ('qop', 'auth,auth-int,auth- > conf')]>>> for k,v in d.iteritems(): print k, '=', v > > ... > algorithm = md5-sess > maxbuf = 1024 > charset = utf-8 > cipher = rc4-40,rc4-56,rc4,des,3des > qop = auth,auth-int,auth-conf > > For safe eval, take a look athttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 > > -N From fredrik at pythonware.com Wed Jan 9 07:14:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 13:14:26 +0100 Subject: Learning Python via a little word frequency program In-Reply-To: <226043.88503.qm@web56404.mail.re3.yahoo.com> References: <226043.88503.qm@web56404.mail.re3.yahoo.com> Message-ID: Andrew Savige wrote: > Neat. Is there any way to use sorted() with multiple sort keys? ... sure! just return the "composite key" as a tuple: # sort on descending count, ascending name deco = sorted(freq.items(), key=lambda x: (-x[1], x[0])) (when comparing tuples, Python first compares the first item from each tuple. if they're equal, it continues with the second item, and so on). From fredrik at pythonware.com Sat Jan 5 12:07:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 05 Jan 2008 18:07:31 +0100 Subject: Question on os.tempnam() vulnerability In-Reply-To: <13nvb525r3m6m39@corp.supernews.com> References: <13nt81gftkfa32d@corp.supernews.com> <13nv5m68qeknk1f@corp.supernews.com> <477FA9B5.9050609@v.loewis.de> <13nvb525r3m6m39@corp.supernews.com> Message-ID: Grant Edwards wrote: >> IOW, it's the same approach as on Unix. > > Not really. Under Unix you can safely create a temp file with > a name that can be used to open the file. Unless I'm missing something, it's not possible to do this in a safe way in the shared temp directory; you can do that only by creating a file in a directory that's under full control of your user. And *that* approach works on Windows as well, of course. From elind at spamcop.net Tue Jan 15 10:04:21 2008 From: elind at spamcop.net (Erik Lind) Date: Tue, 15 Jan 2008 10:04:21 -0500 Subject: A question about event handlers with wxPython References: <478c3bb2$0$5150$4c368faf@roadrunner.com> <2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com> Message-ID: <478ccbc3$0$11000$4c368faf@roadrunner.com> > def HandleSomething(self, event): > generating_control = event.GetEventObject() > print generating_control > > HTH, Thank you.That is what I was looking for, but as often seems the case, one thing exposes another. Is there any way to listen for events without specifically binding to a handler (it seems one cannot bind an event to two handlers?)? One could do so with globals, but I'm trying to avoid that. For example, "press any button to stop" def HandleSomething(self, event): ................. while generating_control: == something: run else stop From amoghhooshdar at gmail.com Fri Jan 25 06:22:00 2008 From: amoghhooshdar at gmail.com (Amogh Hooshdar) Date: Fri, 25 Jan 2008 16:52:00 +0530 Subject: any library for SOAP 1.1 or SOAP 1.2? Message-ID: <78c462ad0801250322y12d211c1uf53023bc04bbb9bc@mail.gmail.com> Hi, I wish to know which python library is popular for SOAP related programming, especially for sending SOAP requests and parsing SOAP responses. I can't find any such library in the Python standard library but I could find ZSI and soap.py libraries. However, ZSI does not support SOAP 1.2. Does anyone know about a library that supports SOAP 1.2 also? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jan 21 13:24:09 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 21 Jan 2008 19:24:09 +0100 Subject: Trouble writing to database: RSS-reader In-Reply-To: <13p9n6ea0nui559@corp.supernews.com> References: <91a5e7ec-b921-4340-b66e-35569c766489@u10g2000prn.googlegroups.com> <13p9n6ea0nui559@corp.supernews.com> Message-ID: <4794e301$0$4429$426a74cc@news.free.fr> Dennis Lee Bieber a ?crit : > On Mon, 21 Jan 2008 08:12:43 -0800 (PST), Arne > declaimed the following in comp.lang.python: > >> The problem is that i cant find the data in the database! If i watch >> my program while im running it, i can see that it sucsessfuly >> downloads the .xml-file from the web and saves it in the buffer. >> > Did you COMMIT the transaction with the database? Did you READ the code ?-) NB : Yes, he did. The problem*s* are elsewhere. From asmodai at in-nomine.org Tue Jan 8 03:59:50 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 09:59:50 +0100 Subject: Look for a string on a file and get its line number In-Reply-To: <9889cbd0-c19e-4b76-8c41-aa621a188661@e4g2000hsg.googlegroups.com> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <9889cbd0-c19e-4b76-8c41-aa621a188661@e4g2000hsg.googlegroups.com> Message-ID: <20080108085949.GH75977@nexus.in-nomine.org> -On [20080108 09:51], John Machin (sjmachin at lexicon.net) wrote: >Make that >= > >| >>> 'fubar'.find('fu') Or even just: if 'my-string' in line: ... Same caveat emptor applies though. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ We're walking this earth. We're walking this shining earth... From jairtrejo at yahoo.com.mx Tue Jan 1 20:14:51 2008 From: jairtrejo at yahoo.com.mx (Jair Trejo) Date: Tue, 1 Jan 2008 19:14:51 -0600 (CST) Subject: PyCairo, PIL and StringIO In-Reply-To: Message-ID: <366566.9612.qm@web52211.mail.re2.yahoo.com> I'm doing some image processing in PIL, and I want to display the results in a GTK window using PyCairo, so I create a Cairo image surface from the PIL Image like this: mfile = StringIO.StringIO() final.save(mfile, format="PNG") ima = cairo.ImageSurface.create_from_png(mfile) mfile.close() return ima Where final is a PIL image. The problem is, I get a IOError: error while reading from Input Stream. ?Any idea of why is this happening? I tried saving to a temporary file, i.e., replace the above code with: final.save('final.png') ima = cairo.ImageSurface.create_from_png('final.png') Instead of a StringIO object, and it works just fine. ____________________________________________________________________________________ ?Capacidad ilimitada de almacenamiento en tu correo! No te preocupes m?s por el espacio de tu cuenta con Correo Yahoo!: http://correo.yahoo.com.mx/ From grante at visi.com Mon Jan 28 12:15:31 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 28 Jan 2008 17:15:31 -0000 Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <600s07F1m9jgbU1@mid.individual.net> <6067h9F1otsbrU1@mid.individual.net> Message-ID: <13ps3djqrl4ap5b@corp.supernews.com> >> The script is essentially gone. I'd like to know how to read >> the pyc files, but that's getting away from my point that >> there is a link between python scripts and assembler. At this >> point, I admit the code above is NOT assembler, but sooner or >> later it will be converted to machine code by the interpreter No it won't. In any of the "normal" implementations, bytecodes are not converted to machine code by the interpreter. Rather, the interpreter simulates a machine that runs the byte codes. >> and the OS and that can be disassembled as assembler. No it can't. The result of feeding bytecodes to the VM isn't output of machine code. It's changes in state of _data_ structures that are independate of the processor's instruction set. > Yes. But the interpreter doesn't convert the entire file to machine > language. It reads one instruction after another and, amongst other > things, outputs corresponding machine code which "does" what's > intended by the byte code instruction. No, it doesn't output corresponding machine code (that's what some Java JIT implementations do, but I'm not aware of any Python implementations that do that). The virtual machine interpreter just does the action specified by the bytecode. -- Grant Edwards grante Yow! Nipples, dimples, at knuckles, NICKLES, visi.com wrinkles, pimples!! From imvmifvm at gmail.com Tue Jan 1 03:25:37 2008 From: imvmifvm at gmail.com (imvmifvm at gmail.com) Date: Tue, 1 Jan 2008 08:25:37 +0000 (UTC) Subject: M I-5'Per secution ' the BB C, televis ion an d rad io Message-ID: -=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-= -= the BBC, television and radio. -= -=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-= The first incident in June 1990 was when a BBC newsreader made what. seemed to be a reaction. to something which had happened in my home, and out of context of what they were reading. My first reaction was. disbelief; nothing of the sort had ever happened before,. the idea that such a thing could occur had not crossed my. mind, yet there was no doubt of what had just taken. place. My disbelief eroded as this recurred time after time. Besides the news, offenders. included shows such as Crimewatch (!), Newsnight, and "entertainment" shows. There seems to. be very little moral understanding among the people who make. these programmes; they just assume they will never. be caught, so they carry on without a thought for the illegality or amorality of what they do. The only time I. ever heard a word raised in doubt was. by Paxman being interviewed by someone else (I think by Clive Anderson) back in 1990; referring to the "watching" he said it. troubled him, and when asked by the host what you could do about. it, replied "Well, you could just switch it off" (meaning the. surveillance monitor in the studio). He. clearly didn't let his doubts stand in the way of continued surreptitious spying from his own or other. people's shows, though. Now you're convinced this is. a troll, aren't you? This story has been the subject of much debate on the. uk.* Usenet newsgroups for over a year, and some readers believe. it to be an invention (it has even been suggested that a group of psychology students are responsible!), others. think it symptomatic of a derangement of the author, and a few give it. credence. Quite a few people do know part or all. of the story already, so this text will fill in the. gaps in their knowledge. For the rest, what may persuade you of the third possibility is that some of the incidents. detailed are checkable against any archives. of radio and TV programmes that exist; that the incidents involve named people (even. if those hiding in the shadows have not made their. identity or affiliations evident), and those people may be persuaded to come out with the truth;. and that the campaign of harassment is continuing today both in the UK and on the. American continent, in a. none-too-secret fashion; by its nature the significant risk of exposure. increases with time. On several occasions people said to my face that harassment from the. TV was happening. On the first day I worked in. Oxford, I spent the evening in the local pub with the company's technical director. Ian, and Phil, another employee. Ian made a few references to me and said to. Phil, as if in an aside, "Is he the bloke who's been. on TV?" to which Phil replied, "Yes, I think. so". I. made a number of efforts to find the bugs, without success; last year we employed professional. counter-surveillance people to scan for bugs (see later) again without result. In. autumn 1990 I disposed of my TV and watched virtually no. television for the next three years. But harassment from TV stations has gone. on for over six years and continues to this day. This is something that many people. obviously know is happening; yet the TV staff have the morality of. paedophiles, that because they're getting away with it they. feel no wrong. Other people who were involved in the. abuse in 1990 were DJs on BBC radio stations,. notably disc jockeys from Radio 1 and other stations (see the following section). Again, since they don't have sense in. the first place they can't be expect to have the moral sense not to be part of. criminal harassment. 343 From petr.jakes.tpc at gmail.com Tue Jan 1 13:57:41 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Tue, 1 Jan 2008 10:57:41 -0800 (PST) Subject: Newbie: Why doesn't this work References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> Message-ID: Hi all, I am trying to understand new-style classes in Python and I have found your postings here. Gabriel, if I understand it properly, it is necessary to define get/ set/del/doc methods for each attribute for which I want to set the "property" data descriptor (which triggers get/set/del/doc function calls upon access to defined attribute). My question is: is it possible to set the "property" for any attribute when I do not know what will be the name of the attribute in the future? Thanks for your reply Petr Jakes From anne.nospam01 at wangnick.de Mon Jan 7 16:54:08 2008 From: anne.nospam01 at wangnick.de (anne.nospam01 at wangnick.de) Date: Mon, 7 Jan 2008 13:54:08 -0800 (PST) Subject: What is the encoding of __file__? Message-ID: <736ae822-54a9-4ee6-91fe-92c2c6eb43db@21g2000hsj.googlegroups.com> Dear all, can someone quickly tell me what the encoding of __file__ is? I can't find it in the documentation. BTW, I'm using Python 2.5.1 on WIndows XP and Vista. Kind regards, Sebastian From haraldarminmassa at gmail.com Mon Jan 21 04:57:32 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Mon, 21 Jan 2008 01:57:32 -0800 (PST) Subject: building psycopg2 on windows using mingw, "cannot find -lpq" Message-ID: The compile works, BUT linking fails: 2.5\Release\psycopg\_psycopg.def -Lc:\python25\libs -Lc: \python25\PCBuild -Lc:/p ostgres/83RC2/lib -lpython25 -lpq -lws2_32 -ladvapi32 -o build \lib.win32-2.5\psy copg2\_psycopg.pyd c:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot find -lpq collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 if I google for the error "ld.exe: cannot find -lpq" there is allways the information that the lib-dir of libpq is missing; but : -Lc:/postgres/83RC2/lib is clearly in the commandline, and within c:/postgres/83RC2/lib there is one libqp.lib What am I missing? any hints? Best wishes, Harald (complete output: c:\mingw\bin\gcc.exe -mno-cygwin -shared -s build \temp.win32-2.5\Release\psycopg \psycopgmodule.o build\temp.win32-2.5\Release\psycopg\pqpath.o build \temp.win32- 2.5\Release\psycopg\typecast.o build\temp.win32-2.5\Release\psycopg \microprotoco ls.o build\temp.win32-2.5\Release\psycopg\microprotocols_proto.o build \temp.win3 2-2.5\Release\psycopg\connection_type.o build\temp.win32-2.5\Release \psycopg\con nection_int.o build\temp.win32-2.5\Release\psycopg\cursor_type.o build \temp.win3 2-2.5\Release\psycopg\cursor_int.o build\temp.win32-2.5\Release\psycopg \lobject_ type.o build\temp.win32-2.5\Release\psycopg\lobject_int.o build \temp.win32-2.5\R elease\psycopg\adapter_qstring.o build\temp.win32-2.5\Release\psycopg \adapter_pb oolean.o build\temp.win32-2.5\Release\psycopg\adapter_binary.o build \temp.win32- 2.5\Release\psycopg\adapter_asis.o build\temp.win32-2.5\Release\psycopg \adapter_ list.o build\temp.win32-2.5\Release\psycopg\adapter_datetime.o build \temp.win32- 2.5\Release\psycopg\_psycopg.def -Lc:\python25\libs -Lc: \python25\PCBuild -Lc:/p ostgres/83RC2/lib -lpython25 -lpq -lws2_32 -ladvapi32 -o build \lib.win32-2.5\psy copg2\_psycopg.pyd c:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot find -lpq collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 ) From bearophileHUGS at lycos.com Wed Jan 2 07:39:19 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 2 Jan 2008 04:39:19 -0800 (PST) Subject: Two candies Message-ID: <78662711-83fe-47ae-9dfa-d55d710bcdac@i3g2000hsf.googlegroups.com> Two little things I may like added. 1) A fast and memory efficient way to create an array.array at a certain size. At the moment I can see some ways to do it: from array import array from itertools import repeat a = array("l", xrange(n)) #1 a = array("l", [0]*n)) #2 a = array("l", repeat(0, n)) #3 - #1 doesn't initialize it to a constant, and to me it seems not memory efficient. - #2 is faster, but I think it requires twice the memory (so it's not good when a has to be quite large). - #3 interacts badly with Psyco (Psyco doesn't digest itertools at all), and it seems not memory efficient. So a simple syntax can be added, like a method a.allocate(item, n), that takes an item and the length of the array to create: a = array("l") a.allocate(0, n) (Note: I know about external numerical packages). In alternative Psyco may be improved a bit, so the #3 syntax may become the standard (efficient in memory and space) one. --------------------------- 2) When I use MatchObjects I have to look at the docs to remember the difference between group() and groups() etc. So I suggest to add a __getitem__ method to MatchObject, so this: mo[3] Equals to: mo.group(3) Bye, bearophile From suray.sathish at gmail.com Sat Jan 26 08:40:07 2008 From: suray.sathish at gmail.com (suray.sathish at gmail.com) Date: Sat, 26 Jan 2008 05:40:07 -0800 (PST) Subject: trisha nake out Message-ID: <6c7f46b7-ae42-4484-a660-cf23ec300dab@s8g2000prg.googlegroups.com> trisha nake out asin hot photos namitha bathing videos ____________________________ http://www.geocities.com/terfavet/ http://www.geocities.com/terfavet/ http://www.geocities.com/terfavet/ From fredrik at pythonware.com Wed Jan 9 14:01:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 20:01:24 +0100 Subject: Another dumb scope question for a closure. In-Reply-To: References: Message-ID: Steven W. Orr wrote: > So sorry because I know I'm doing something wrong. > > 574 > cat c2.py > #! /usr/local/bin/python2.4 > > def inc(jj): > def dummy(): > jj = jj + 1 > return jj > return dummy > > h = inc(33) > print 'h() = ', h() > 575 > c2.py > h() = > Traceback (most recent call last): > File "./c2.py", line 10, in ? > print 'h() = ', h() > File "./c2.py", line 5, in dummy > jj = jj + 1 > UnboundLocalError: local variable 'jj' referenced before assignment http://docs.python.org/ref/naming.html has the answer: "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block." > I could have sworn I was allowed to do this. How do I fix it? use a class to hold state, like everyone else does? From mr.cerutti at gmail.com Fri Jan 4 15:57:49 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 4 Jan 2008 15:57:49 -0500 Subject: MRO Error on Multiple Inheritance? In-Reply-To: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> References: <763e9fbd-b60e-4de8-9f3e-6fea84409d3f@h11g2000prf.googlegroups.com> Message-ID: <51302a8c0801041257n5aa792cdr26eec78250f2a537@mail.gmail.com> On Jan 4, 2008 3:03 PM, Ming wrote: > I'm working through Wesley Chun's CPP2e and got this error on 13.11.1, > pp 548 where his interpreter snippet shows no problems: > > ActivePython 2.5.1.1 (ActiveState Software Inc.) b > Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [ > win32 > Type "help", "copyright", "credits" or "license" f > >>> class A(object): pass > ... > >>> class B(A): pass > ... > >>> class C(B): pass > ... > >>> class D(A, B): pass > ... > Traceback (most recent call last): > File "", line 1, in > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases A, B The mro of new-style classes changed between Python 2.2 and 2.3. Perhaps Mr. Chun's code was written for 2.2. See http://www.python.org/download/releases/2.3/mro/ -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Jan 22 13:48:03 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 19:48:03 +0100 Subject: Beginners question about debugging (import) In-Reply-To: References: Message-ID: <5vms34F1muqaaU1@mid.uni-berlin.de> Albert van der Horst schrieb: > I'm starting with Python. First with some interactive things, > working through the tutorial, > then with definitions in a file called sudoku.py. > Of course I make lots of mistakes, so I have to include that file > time and again. > > I discovered (the hard way) that the second time you invoke > from sudoku.py import * > nothing happens. > > There is reload. But it only seems to work with > import sudoku > > Now I find myself typing ``sudoku.'' all the time: > > x=sudoku.sudoku() > y=sudoku.create_set_of_sets() > sudoku.symbols > > Is there a more convenient way? > > (This is a howto question, rather difficult to get answered > from the documentation.) import sudoku as s However, I find it easier to just create a test.py and run that from the shell. For the exact reason that reload has it's caveats and in the end, more complex testing-code isn't really feasible anyway. If you need to, drop into the interactive prompt using python -i test.py Diez From aawood at gmail.com Thu Jan 10 17:24:03 2008 From: aawood at gmail.com (Adrian Wood) Date: Thu, 10 Jan 2008 22:24:03 +0000 Subject: Fwd: Python-list Digest, Vol 52, Issue 128 In-Reply-To: References: Message-ID: <25e4147e0801101424m4e932775l2217cf03327b53c5@mail.gmail.com> Fredrik Lundh wrote: > > Adrian Wood wrote: > > > > I can call man.state() and then woman.state() or Person.state(man) and > > Person.state(woman) to print the status of each. This takes time and > > space however, and becomes unmanageable if we start talking about a > > large number of objects, and unworkable if there is an unknown number. > > What I'm after is a way to call the status of every instance of Man, > > without knowing their exact names or number. > > > > I've gone through the relevant parts of the online docs, tried to find > > information elsewhere online, and looked for code samples, but the > > ionformation either isn't there, or just isn't clicking with me. I've > > tried tracking the names of each object in a list, and even creating > > each object within a list, but don't seem to be able to find the right > > syntax to make it all work. > > For a start, how about: > > class Person: > ... your class ... > > persons = [] > > man = Person() > persons.add(man) > > woman = Person() > persons.add(woman) > > for p in persons: > print p, p.state() It didn't like using .add for some reason, but once I swapped out all instances of that for .append that worked a treat! Thank you very much, I'll check out your other suggestions later once I feel comfortable with what I have so far. From williampaul28 at yahoo.com Sat Jan 19 14:53:52 2008 From: williampaul28 at yahoo.com (william paul) Date: Sat, 19 Jan 2008 11:53:52 -0800 (PST) Subject: python scripts with IIS Message-ID: <277841.5689.qm@web38406.mail.mud.yahoo.com> Thank you, William ----- Original Message ---- From: Rolf van de Krol To: python-list at python.org Sent: Saturday, January 19, 2008 5:33:59 PM Subject: Re: python scripts with IIS Adding the following lines before your print statement should do the trick. IIS complains about the headers, so adding headers should help. print "Content-Type: text/html" # HTML is following print # blank line, end of headers william paul wrote: > > Hello: > > I am trying to configure IIS to work with Python scripts: > > I've added in the Home Directory/Configuration the .py extention and > the path to the python.exe as: c:\Python24\python.exe %S %S > The python script has 1 line: > print "This is a test for python scripts with IIS" > > When I launch the file using IE I get the message: > > *CGI Error* > The specified CGI application misbehaved by not returning a complete > set of HTTP headers. The headers it did return are: > > This is a test for python scripts with IIS > > How can I remove the CGI error? > > Thank you > > William > > ------------------------------------------------------------------------ > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try > it now. > -- http://mail.python.org/mailman/listinfo/python-list ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Jan 25 22:08:42 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 19:08:42 -0800 (PST) Subject: ElementTree.fromstring(unicode_html) References: <58b4d6e5-da52-4247-9892-3fbcfd0f1979@m34g2000hsb.googlegroups.com> Message-ID: <56204596-13dc-4a18-b844-dec882b247e1@d21g2000prf.googlegroups.com> On Jan 26, 1:11 pm, globophobe wrote: > This is likely an easy problem; however, I couldn't think of > appropriate keywords for google: > > Basically, I have some raw data that needs to be preprocessed before > it is saved to the database e.g. > > In [1]: unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f > \u3044\r\n' > > I need to turn this into an elementtree, but some of the data is > japanese whereas the rest is html. This string contains a
. >>> import unicodedata as ucd >>> s = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f\u3044\r\n' >>> [ucd.name(c) if ord(c) >= 128 else c for c in s] ['HIRAGANA LETTER SA', 'HIRAGANA LETTER MU', 'HIRAGANA LETTER I', 'FULLWIDTH SOLIDUS', u'\r', u'\n', 'HIRAGANA LETTER TU', 'HIRAGANA LETTER ME', 'HIRAGANA LETTER TA', 'HIRAGANA LETTER I', u'\r', u'\n'] >>> Where in there is the
?? From paddy3118 at googlemail.com Wed Jan 9 11:09:53 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 08:09:53 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> <5cf4c5bb-01b1-4ece-a09a-24c4491764b1@f47g2000hsd.googlegroups.com> <7486a4ff-e801-4036-86d3-2ad0aaf542df@v29g2000hsf.googlegroups.com> Message-ID: <8d49b1db-becd-4838-b2ce-a600e8ffa072@z17g2000hsg.googlegroups.com> On Jan 9, 1:02 pm, MartinRineh... at gmail.com wrote: > Thanks to all for many helpful suggestions. > > Python, by the way, is verbose when compared to APL. (Seehttp://catpad.net/michael/apl/if you don't believe this.) You need to > stick in an adverb (maybe "gracefully concise") as standalone > "concise" is owned by APL. > > Basilisk96 wrote: > > Did programmers stop writing programs on punch cards because they ran > > out of punch paper? > > If you drive on the NYS Thruway, you still get a punch card when you > enter. You turn it in when you pay your toll. I didn't reread my blog post! I meant Python is *succinct* with definition: http://www.askoxford.com/concise_oed/succinct?view=uk "Briefly and clearly expressed". (I should engage brain before typing). - Paddy. From deets at nospam.web.de Thu Jan 3 04:44:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jan 2008 10:44:38 +0100 Subject: Cloning Environments References: Message-ID: <5u3p46F1g2f9sU1@mid.uni-berlin.de> gamename wrote: > Hi, > > I have several machines running Linux (mostly fedora6) and Windows > (mostly XP). I'm thinking of using easy_install to create as uniform > an environment as possible for all of them. Cloning the environment, > to put it another way. > > Is there a good example somewhere showing how to do this? I'm new to > easy_install and relatively new to python. You might be interested in workingenv.py/virtualenv.py Diez From lasses_weil at klapptsowieso.net Mon Jan 28 17:34:07 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 28 Jan 2008 23:34:07 +0100 Subject: Python Genetic Algorithm In-Reply-To: References: <479d1559$0$9100$9b4e6d93@newsspool2.arcor-online.net><13pqbvn8ckilnfc@corp.supernews.com> <479dc95e$0$9103$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <479e585f$0$5950$9b4e6d93@newsspool3.arcor-online.net> Blubaugh, David A. wrote: > Have you ever worked with Gene Expression Programming???? > No. Why? /W From sipickles at hotmail.com Sun Jan 27 12:35:16 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Sun, 27 Jan 2008 17:35:16 +0000 Subject: REALLY simple xml reader Message-ID: Hi Can anyone suggest a really simple XML reader for python? I just want to be able to do something like this: xmlDoc = xml.open("file.xml") element = xmlDoc.GetElement("foo/bar") ... to read the value of: 42 Thanks Simon -- Linux user #458601 - http://counter.li.org. From steveo at syslang.net Thu Jan 17 10:22:14 2008 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 17 Jan 2008 10:22:14 -0500 (EST) Subject: class closure question Message-ID: I want to indirectly change the value of a variable. #! /usr/bin/python foo = [44] bar = foo bar[0] = 55 print 'bar = ', bar print 'foo = ', foo This works fine. bar = [55] foo = [55] But I want to do the same with a class value. #! /usr/bin/python S = None dd = { 'class': [S] } class C1(object): def __init__(self): print 'Hello from C1' def mkclass(base): class zzz(base): pass return zzz dd['class'][0] = mkclass( C1 ) print "dd['class'][0].__bases__ = ", dd['class'][0].__bases__ print 'S = ', S The answer is not what I want: dd['class'][0].__bases__ = (,) S = None The goal is for S to be set to the returned class from mkclass. Can someone help? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From khoard at gmail.com Wed Jan 23 12:17:52 2008 From: khoard at gmail.com (FireNWater) Date: Wed, 23 Jan 2008 09:17:52 -0800 (PST) Subject: Core Python Programming . . . References: <7xir1q29j5.fsf@ruckus.brouhaha.com> <40385ed1-6594-403e-934d-3d54a294101e@e25g2000prg.googlegroups.com> Message-ID: On Jan 22, 5:00 pm, wesley chun wrote: > > > 6-11 Conversion. > > > (a) Create a program that will convert from an integer to an > > > Internet Protocol (IP) address in the four-octet format of WWW.XXX.YYY.ZZZ > > > (b) Update your program to be able to do the vice verse of the above. > > > I think it's is asking to convert a 32-bit int to the dotted form. > > > It's a little known fact, but IP addresses are valid in non-dotted > > long-int form. Spammers commonly use this trick to disguise their IP > > addresses in emails from scanners. > > that is correct. don't read too much into it. i'm not trying to > validate anything or any format, use old or new technology. it is > simply to exercise your skills with numbers (specifically 32-bit/4- > byte integers), string manipulation, and bitwise operations. if you > wish to use different sizes of numbers, forms of addressing, IPv6, > etc., that's up to you. don't forget about part (b), which is to take > an IP address and turn it into a 32-bit integer. > > enjoy! > -- wesley > > ps. since you're on p. 248, there is also a typo in the piece of code > right above this exercise, Example 6.4, which is tied to exercise > 6-7. "'fac_list'" should really be "`fac_list`", or even better, > "repr(fac_list)". see the Errata at the book's websitehttp://corepython.com > for more details. > > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, cahttp://cyberwebconsulting.com Well, I think I may be way off on this one. . . here's what I came up with. . . . def int_to_IP(int): '''Function accepts an integer and returns a string in the format WWW.XXX.YYY.ZZZ''' string = str(int) return (string[0]*3 + '.' + string[1]*3 + '.' + string[2]*3 + '.' + string[3]*3) number = int(raw_input('Enter the number(4 digits): ')) print (int_to_IP(number)) From paddy3118 at googlemail.com Thu Jan 10 01:03:42 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 22:03:42 -0800 (PST) Subject: Collecting Rich Data Structures for students References: <8b4e7954-b666-4515-9ae2-821d979ebd7f@m34g2000hsf.googlegroups.com> Message-ID: On Jan 9, 11:05 pm, "kirby.ur... at gmail.com" wrote: > On Jan 9, 8:15 am, Paddy wrote: > > > > > On Jan 9, 6:52 am, Paddy wrote: > > > > On Jan 9, 2:19 am, "kirby.ur... at gmail.com" > > > wrote: > > > > > Greetings Pythoneers -- > > > > > Some of us over on edu-sig, one of the community actives, > > > > have been brainstorming around this Rich Data Structures > > > > idea, by which we mean Python data structures already > > > > populated with non-trivial data about various topics such > > > > as: periodic table (proton, neutron counts); Monty Python > > > > skit titles; some set of cities (lat, long coordinates); types > > > > of sushi. > > > > > Obviously some of these require levels of nesting, say > > > > lists within dictionaries, more depth of required. > > > > > Our motivation in collecting these repositories is to give > > > > students of Python more immediate access to meaningful > > > > data, not just meaningful programs. Sometimes all it takes > > > > to win converts, to computers in general, is to demonstrate > > > > their capacity to handle gobs of data adroitly. Too often, > > > > a textbook will only provide trivial examples, which in the > > > > print medium is all that makes sense. > > > > > Some have offered XML repositories, which I can well > > > > understand, but in this case we're looking specifically for > > > > legal Python modules (py files), although they don't have > > > > to be Latin-1 (e.g. the sushi types file might not have a > > > > lot of romanji). > > > > > If you have any examples you'd like to email me about, > > > > kirby.ur... at gmail.com is a good address. > > > > > Here's my little contribution to the mix:http://www.4dsolutions.net/ocn/python/gis.py > > > > > Kirby Urner > > > > 4D Solutions > > > > Silicon Forest > > > > Oregon > > > > I would think there was more data out there formatted as Lisp S- > > > expressions than Python data-structures. > > > Wouldn't it be better to concentrate on 'wrapping' XML and CSV data- > > > sources? > > > > - Paddy. > > > The more I think on it the more I am against this- data should be > > stored in programming language agnostic forms but which are easily > > made available to a large range of programming languages. > > If the format is easily parsed by AWK then it is usually easy to parse > > in a range of programming languages. > > > - Paddy. > > It's OK to be against it, but as many have pointed out, it's often > just one value adding step to go from plaintext or XML to something > specifically Python. > > Sometimes we spare the students (whomever they may be) this added > step and just hand them a dictionary of lists or whatever. We > may not be teaching parsing in this class, but chemistry, and > having the info in the Periodic Table in a Python data structure > maybe simply be the most relevant place to start. > > Many lesson plans I've seen or am working on will use these .py > data modules. > > Kirby Then I'd favour the simple wrappings of bearophile and Frederik Lundhs replies where it is easy to extract the original datamaybe for updating , or for use in another language. - Paddy. From hniksic at xemacs.org Wed Jan 16 02:22:41 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 16 Jan 2008 08:22:41 +0100 Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> <13orb15pqgk4h96@corp.supernews.com> Message-ID: <87abn6fd4u.fsf@mulj.homelinux.net> "J. Peng" writes: > we create a new list and assign it to x for future use. How to > destroy the before list [1,2,3]? does python destroy it > automatically? Yes, Python detects that the older list is no longer in use (if that is indeed the case), and destroys it automatically. If you're curious how that works, take a look at http://en.wikipedia.org/wiki/Reference_counting From fredrik at pythonware.com Fri Jan 11 07:27:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jan 2008 13:27:53 +0100 Subject: reading a specific column from file In-Reply-To: References: Message-ID: cesco wrote: > I have a file containing four columns of data separated by tabs (\t) > and I'd like to read a specific column from it (say the third). Is > there any simple way to do this in Python? use the "split" method and plain old indexing: for line in open("file.txt"): columns = line.split("\t") print columns[2] # indexing starts at zero also see the "csv" module, which can read all sorts of comma/semicolon/tab-separated spreadsheet-style files. > I've found quite interesting the linecache module the "linecache" module seems to be quite popular on comp.lang.python these days, but it's designed for a very specific purpose (displaying Python code in tracebacks), and is a really lousy way to read text files in the general case. please unlearn. From chris.arndt at web.de Sat Jan 5 09:46:57 2008 From: chris.arndt at web.de (Christopher Arndt) Date: Sat, 5 Jan 2008 06:46:57 -0800 (PST) Subject: =?ISO-8859-1?Q?ANN:_n=E4chstes_Treffen_von_pyCologne_am_9.1.2008_18:?= =?ISO-8859-1?Q?30_Uhr?= Message-ID: Hallo liebe Pythonfreunde, das n?chste Treffen von pyCologne, der Python User Group K?ln, findet statt: Datum: Mittwoch, den 9.1.2008 Uhrzeit: 18:30 Uhr c.t. Ort: Pool 0.14, Benutzerrechenzentrum (RRZK-B) der Universit?t K?ln, Berrenrather Str. 136, 50937 K?ln Das Programm f?r das n?chste Treffen lautet: * Vortrag ?ber MoinMoin (Reimar Bauer) * Vortrag ?ber das Publisher/Subscriber-Pattern (Observer-Pattern) (Christopher Arndt) * Diskussion: Weitere Vorgehensweise und Verwendung des pyCologne Logos Ab ca. 20:30 Uhr werden wir den Abend gem?tlich in einem nahe gelegenen Restaurant/Kneipe ausklingen lassen. Weitere Information zu pyCologne, inkl. Wegbeschreibung, Fotos und Protokollen vergangener Treffen usw., findet ihr auf unserer Seite im deutschen Python Wiki: http://wiki.python.de/pyCologne Bis bald, Christopher Arndt From azam.farooq3 at gmail.com Thu Jan 31 02:51:19 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Wed, 30 Jan 2008 23:51:19 -0800 (PST) Subject: Do You Want a GSM Mobile with Amazing Features? Please click here Message-ID: <209fc8f2-058b-4a69-88a7-a8bdd4566b0f@v4g2000hsf.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 mrmakent at cox.net Wed Jan 23 15:27:56 2008 From: mrmakent at cox.net (Mike Kent) Date: Wed, 23 Jan 2008 12:27:56 -0800 (PST) Subject: Can someone explain this unexpected raw_input behavior? Message-ID: It's often useful for debugging to print something to stderr, and to route the error output to a file using '2>filename' on the command line. However, when I try that with a python script, all prompt output from raw_input goes to stderr. Consider the following test program: === Start test.py === import sys def main(): print "Hello world" raw_input("Press ENTER") print "Goodbye world" if __name__ == "__main__": main() === End test.py === If I run it with the command line 'python2.5 test.py', I get the following output: Hello world Press ENTER <=== This appeared,the program paused, I press ENTER, and the program continued Goodbye world However, if I run it with the command line 'python2.5 test.py 2>/dev/ null' (I'm routing stderr output to /dev/null), I instead get: Hello world <=== No output appeared, the program paused, I press ENTER, and the program continued Goodbye world This indicates to me that the prompt output of raw_input is being sent to stderr. I did check the source code for raw_input, and it appears to be sending it to stdout as expected. I get this behavior on multiple OS platforms, with multiple versions of Python. I am building python on these platforms myself, but to my knowledge, I am not doing anything special which could account for this behavior. Any suggestions or pointers on how to get the expected behavior out of raw_input? From gherron at islandtraining.com Sat Jan 26 12:53:27 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 26 Jan 2008 09:53:27 -0800 Subject: Beginner String formatting question In-Reply-To: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> References: <68769e37-7787-414f-abd3-a447341e9f7d@v17g2000hsa.googlegroups.com> Message-ID: <479B7397.7070906@islandtraining.com> JAMoore84 at gmail.com wrote: > Hi all, > > I am trying to write a simple program that will accept an integral > "time" input in the HHMMSS format and output a "HH:MM:SS" form. My > code is as follows: > ======================== > import string > > def FormatTime(time): > '''Converts an HHMMSS string to HH:MM:SS format.''' > > timeString = str(time) #converts the num to string > > hours = [timeString[0], timeString[1]] > minutes = [timeString[2], timeString[3]] > seconds = [timeString[4], timeString[5]] > > Ftime = "%s:%s:%s",(hours,minutes,seconds) > clock = Ftime.join() > > return clock > =========================== > > when I run it from IDLE, I get this: > > >>>> Format.FormatTime(time) >>>> > ['1', '1', ':', '2', '2', ':', '3', '3'] > ['1', '1', ':', '2', '2', ':', '3', '3'] > The code you posted did not produce the output you are showing. You'll have to be more careful with your posting if you expect to get a useful answer. Beyond that, there are a bundle of errors in the code that will prevent it from working: If you want to carve a string into substrings, use this kind of syntax hours = timeString[0:2] minutes = timeString[2:4] seconds = timeString{4:6] If you want to combine small strings into longer strings you've got several choices: output = hours + ':' + ... or output = "%s:%s:%s" % (hours, ...) #NOTICE the % operator between the format string and value tuple Since both of those produce a string as output, you have no need of a join, BUT if you do decide to produce a list of strings that you want to join into a longer string, you need to use join correctly: parts = [hours,minutes,seconds] output = ':'.join(parts) Another error: If your time starts with an hour that is just a single digit, then your string will be only 5 digits long (there will be no leading zero). In that case, all the extraction of individual fields based on indexing into the string will be off by one. > My questions- > 1) Why is this function printing out twice? > Show us your real code. > 2)It may be a formatting issue, but I want to have the output as > "HH:MM:SS", rather than having it broken out into each cell. I > thought the 'join' command would do this, but I must not be using it > properly/understanding something. > See the example above. > 3)as a side note, I've noticed that the parameter "time" passed in > must be passed in as a string, otherwise I receive an error that > "time" is unsubscriptable. Am I unable to pass in an int and then > convert it to a string within the function with str()? > Of course you can pass any type into a function. Then you have to write the program to operate correctly on whatever the input type is. > I've been at this for a while, so I may not be able to see the forest > through the trees at this point. I'd greatly appreciate any > suggestions or instruction on these mistakes. > My guess is that's why the code you show does not match the output you present. > Best, > > Jimmy > Gary Herron From mario at ruggier.org Wed Jan 2 05:57:17 2008 From: mario at ruggier.org (mario) Date: Wed, 2 Jan 2008 02:57:17 -0800 (PST) Subject: different encodings for unicode() and u''.encode(), bug? References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com> <477B4B88.6070207@v.loewis.de> <391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com> Message-ID: <323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> On Jan 2, 10:44 am, John Machin wrote: > > Two things for you to do: > > (1) Try these at the Python interactive prompt: > > unicode('', 'latin1') > unicode('', 'mbcs') > unicode('', 'raboof') > unicode('abc', 'latin1') > unicode('abc', 'mbcs') > unicode('abc', 'raboof') $ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> unicode('', 'mbcs') u'' >>> unicode('abc', 'mbcs') Traceback (most recent call last): File "", line 1, in LookupError: unknown encoding: mbcs >>> Hmmn, strange. Same behaviour for "raboof". > (2) Read what the manual (Library Reference -> codecs module -> > standard encodings) has to say about mbcs. Page at http://docs.python.org/lib/standard-encodings.html says that mbcs "purpose": Windows only: Encode operand according to the ANSI codepage (CP_ACP) Do not know what the implications of encoding according to "ANSI codepage (CP_ACP)" are. Windows only seems clear, but why does it only complain when decoding a non-empty string (or when encoding the empty unicode string) ? mario From deets at nospam.web.de Tue Jan 22 09:15:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jan 2008 15:15:43 +0100 Subject: isgenerator(...) - anywhere to be found? References: Message-ID: <5vmc4fF1n9pk6U1@mid.uni-berlin.de> Jean-Paul Calderone wrote: > On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" > wrote: >>For a simple greenlet/tasklet/microthreading experiment I found myself in >>the need to ask the question >> >>isgenerator(v) >> >>but didn't find any implementation in the usual suspects - builtins or >>inspect. >> >>I was able to help myself out with a simple (out of my head, hope its >> >>def isgenerator(v): >> def _g(): yield >> return type(v) == type(_g()) >> >>But I wonder why there is no such method already available? >> > > Why do you need a special case for generators? If you just pass the > object in question to iter(), instead, then you'll either get back > something that you can iterate over, or you'll get an exception for > things that aren't iterable. Because - as I said - I'm working on a micro-thread thingy, where the scheduler needs to push returned generators to a stack and execute them. Using send(), which rules out iter() anyway. Diez From bladedpenguin at gmail.com Sat Jan 26 01:45:07 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 22:45:07 -0800 (PST) Subject: Doesn't know what it wants References: Message-ID: <11ab7fac-2dec-496f-bb1a-4eeafd3b00ec@v46g2000hsv.googlegroups.com> On Jan 26, 1:32 am, Jeroen Ruigrok van der Werven wrote: > -On [20080126 06:26], Tim Rau (bladedpeng... at gmail.com) wrote: > > >Line 147 reads: > > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) > > I think it expects something like: > > # badly named variable, pick something better depending on context > temp = vec2d(0, 0) > cp.cpMomentForCircle(self.mass, .2, 0, temp) > > I am curious about your use of double braces for vec2d though. Why ((0,0)) and > not (0, 0)? the double parens are a tuple being passed as an argument. vec2d is not a constructor that cares whether it gets a tuple or a pair of ints. I choose tuple for consistency with the rest of my code. Isn't what it gets the value returned by the constructor, no matter whether you assign it to an intermediate value first? I tried it, and the result is the same. From jim.hefferon at gmail.com Sat Jan 12 07:22:18 2008 From: jim.hefferon at gmail.com (Jim) Date: Sat, 12 Jan 2008 04:22:18 -0800 (PST) Subject: Great Python books for the beginner References: Message-ID: Look at http://www.python.org/doc/ . The tutorial is quite good. Jim From asmodai at in-nomine.org Fri Jan 18 01:56:36 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 18 Jan 2008 07:56:36 +0100 Subject: [OT] "Code Friendly" Blog? In-Reply-To: References: Message-ID: <20080118065636.GQ61556@nexus.in-nomine.org> -On [20080117 23:56], Miki (miki.tebeka at gmail.com) wrote: >Is there any free blog hosting that is more "code friendly" (easy to >post code snippets and such)? I personally use a Wordpress installation on my own machine with an additional plugin for syntax highlighting. http://wordpress.org/extend/plugins/wp-syntax/ IIRC it uses
 for highlighting Python for example.
It works quite well.

If you can host stuff yourself you might even like to check out
http://textpress.pocoo.org/ - a beginning Python solution. :)

-- 
Jeroen Ruigrok van der Werven  / asmodai
????? ?????? ??? ?? ??????
http://www.in-nomine.org/ | http://www.rangaku.org/
Buried deep are the Souls that are waiting for you...


From IanJSparks at gmail.com  Thu Jan 10 11:50:36 2008
From: IanJSparks at gmail.com (IanJSparks)
Date: Thu, 10 Jan 2008 08:50:36 -0800 (PST)
Subject: PIL rotate : Rotate By Shear / Paeth Rotation?
Message-ID: 

I've been doing some image rotation with PIL and comparing the images
with imagemagick's convert -rotate output.

Imagemagick uses an RBS / Paeth rotation algorithm that appears to
give better results than PIL's rotate method.

However, I love PIL and don't want to have to shell out to imagemagick
or use it's python bindings if I can stay with my beloved Python
Imaging Library.

Has anyone implemented RBS using PIL? Anyone looked at doing it and
backed away?



From http  Mon Jan 21 22:47:43 2008
From: http (Paul Rubin)
Date: 21 Jan 2008 19:47:43 -0800
Subject: pairs from a list
References: <4idlj.14026$k15.6829@trnddc06>
Message-ID: <7xir1mplls.fsf@ruckus.brouhaha.com>

Alan Isaac  writes:
> (Of course the print statement is just illustrative.)
> What is the fastest way? (Ignore the import time.)

You have to try a bunch of different ways and time them.  One
idea (untested):

    def pairs(seq):
       while True:
           yield (seq.next(), seq.next())


From sjmachin at lexicon.net  Sun Jan 13 00:46:22 2008
From: sjmachin at lexicon.net (John Machin)
Date: Sat, 12 Jan 2008 21:46:22 -0800 (PST)
Subject: Elementary string-formatting
References: 
Message-ID: 

On Jan 13, 3:15 pm, Odysseus  wrote:
[snip]
>
> P.S. Is there a preferable technique for forcing floating-point division
> of two integers to that used above, multiplying by "100.0" first? What
> about if I just wanted a ratio: is "float(n / m)" better than "1.0 * n /
> m"?

> Odysseus

You obviously haven't tried float(n / m), or you wouldn't be asking.
Go ahead and try it.

"Preferable" depends on whether you want legibility or speed.

Most legible and slowest first:
1. float(n) / float(m)
2. n / float(m)
3. 1.0 * n / m
# Rationale so far: function calls are slow
4. If you have a lot of this to do, and you really care about the
speed and m (the denominator) is constant throughout, do fm = float(m)
once, and then in your loop do n / fm for each n -- and make sure you
run properly constructed benchmarks ...

Recommendation: go with (2) until you find you've got a program with
a real speed problem (and then it probably won't be caused by this
choice).

HTH,
John


From scrdhrt at gmail.com  Fri Jan 18 05:13:29 2008
From: scrdhrt at gmail.com (Sacred Heart)
Date: Fri, 18 Jan 2008 02:13:29 -0800 (PST)
Subject: Python Tutorial.
References: <2537f4eb-c047-4eae-9d26-93c7498b5840@f47g2000hsd.googlegroups.com>
Message-ID: <04e2e0f1-9b35-48d0-a87c-647e139d9fe5@y5g2000hsf.googlegroups.com>

On Jan 17, 11:30 pm, Rizwan  wrote:
> Hiya,
>
> I found one good website for python tutorial. just thought to share
> with community.
>
> Hope you all also like it..
>
>  http://python.objectis.net
>
> -MR

Thanks, looks like a nice collection of links. I've bookmarked the
page.

R,
SH


From grahn+nntp at snipabacken.dyndns.org  Thu Jan 17 04:36:45 2008
From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn)
Date: 17 Jan 2008 09:36:45 GMT
Subject: Great Python books for the beginner
References: 
	<1a4d8dae-4722-4a10-a638-ac1b2d85227a@i72g2000hsd.googlegroups.com>
	
	<5e57822c-bd98-41fb-971b-1c8ad7ca5df0@s8g2000prg.googlegroups.com>
Message-ID: 

On Sat, 12 Jan 2008 13:12:19 -0800 (PST), bruno.desthuilliers at gmail.com  wrote:
> On 12 jan, 21:04, Landon  wrote:
>> One thing I wonder about is the examples these books use to teach the
>> concepts. I found myself really attached to K&R because the end of
>> section projects were utilities that I would find be able to find
>> useful in day to day work such as a version of wc and a program that
>> would take collapse all consecutive whitespace in a document into one
>> space. I could just use the projects from K&R, but I imagine a Python
>> book would have a better selection that highlight Python's abilities.
>
> It wouldn't make any sens to port the K&R stuff to Python - different
> languages, different uses, different problems... I mean, C is a low-
> level language, mostly useful for low-level system programming, while
> Python is a very high level language mostly useful for application
> programming and Q&D scripting.

I tend to ignore exercises, sadly, but back in the days before Perl,
and on Unix, it was useful to write small utilities like that in C.
Maybe the K&R exercises reflect that.

(And the 'K' in K&R became the 'k' in awk, so these people were
clearly very interested in this application area -- and interested
in easier ways to do it than by C programming.)

  Unix bigot mode: it seems to me to be harder and more tedious to
  learn programming in a GUI environment like Windows. On Unix small
  home-grown filter-like programs are useful: you have a good shell to
  run them in, and you have a wealth of other utilities to connect
  them to via pipes.

/Jorgen

-- 
  // Jorgen Grahn           R'lyeh wgah'nagl fhtagn!


From berteun at NO_SPAMdds.nl  Wed Jan 30 18:09:16 2008
From: berteun at NO_SPAMdds.nl (Berteun Damman)
Date: Wed, 30 Jan 2008 23:09:16 +0000 (UTC)
Subject: Dictionary Keys question
References: <5a3ebdee-16aa-4d69-8b9c-2fb9762bbe1c@y5g2000hsf.googlegroups.com>
Message-ID: 

On Wed, 30 Jan 2008 14:47:36 -0800 (PST), FireNWater  wrote:
> I'm curious why the different outputs of this code.  If I make the
> dictionary with letters as the keys, they are not listed in the
> dictionary in alphabetical order, but if I use the integers then the
> keys are in numerical order.
>
> I know that the order of the keys is not important in a dictionary,
> but I was just curious about what causes the differences.  Thanks!!

I don't know the exact way Python's hash function works, but I can take
a guess. I'm sorry if I explain something you already know.

A hash is for quickly looking up data. Yet, you don't want to waste too
much memory. So there is a limit number of spaces allocated, in which to
store objects. This number of spaces can be thought of as a list. Then,
if you put something into the dict, Python computes the 'hash' of this
object, which basically forms the index in the list where to store it.
So every object should be mapped onto some index within the list. (If
you retrieve it, the hash is computed again, and the value on that index
is looked up, like list indexing, these are fast operations.)

Say, if you have 100 spaces, and someone puts in integer in the list,
the hashfunction used might be % 100. So the first 100 integers would
always be placed at consecutive places. For strings however, a more
complicated hash-function would be used, which takes into account more
characters, so strings don't end up in order.

For integers, if you put in integers that are spread very widely apart,
they won't end up in order either (see the mod 100 example, 104 will
come before 10).

If you replace the list2 in your example by:
list2 = [10000 * x for x in range(1,9)]

You will see that this one doesn't end up in order either. So, there's
no exception for integers when it comes to the order, yet the particular
properties of the hash function will cause sequential integers to end up
in order under some circumstances.

Berteun

PS:
What happens if two values map onto the same space is of course an
obvious question, and the trick is choosing your hashfunction so this
occurs not very often on average. If it happens there are several
strategies. Wikipedia probably has an explanation of how hash-functions
can work in such a case.


From srikrishnamohan at gmail.com  Wed Jan 23 09:57:09 2008
From: srikrishnamohan at gmail.com (km)
Date: Wed, 23 Jan 2008 20:27:09 +0530
Subject: A GUI framework for running simulations
In-Reply-To: 
References: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com>
	
Message-ID: 

Hi,

check SimPy module
 and then
http://www.showmedo.com/videos/series?name=pythonThompsonVPythonSeries

KM

On Jan 23, 2008 8:10 PM, Guilherme Polo  wrote:

> 2008/1/23, ram.rachum at gmail.com :
> > Hello! I am currently working on writing a simulation engine for
> > special relativity physics. I'm writing it in Python, of course. I'm
> > doing fine with the engine, but I want a GUI framework in which I
> > could use it conveniently, and test different setups on it. I'm not so
> > strong with GUI programming. I looked at Tkinter, I looked at
> > WxPython, I looked at PythonCard. It all looks pretty daunting.
> >
> > My question is, does there exist a GUI package that is intended
> > specifically for simulations? I saw a program called Golly, which is a
> > simulation for Conway's Game of Life. Its GUI had most of the features
> > I needed. For example, you can load a setup, there are "play" and
> > "stop" buttons, you can change a setup and save it, etc.
> >
>
> Golly uses wxWidgets, and if you are planning to use Python then you
> would be using wxPython.
>
> > So does anyone know of a general GUI framework for running
> > simulations?
>
> All them serves this purpose. The main part of your gui application
> will be a custom widget that you will need to do yourself.
>
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
>
> --
> -- Guilherme H. Polo Goncalves
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From lists at cheimes.de  Fri Jan 11 11:45:01 2008
From: lists at cheimes.de (Christian Heimes)
Date: Fri, 11 Jan 2008 17:45:01 +0100
Subject: virtualpython / workingenv / virtualenv ... shouldn't this be
	part of   python
In-Reply-To: <4787981c$0$90268$14726298@news.sunsite.dk>
References: <4787981c$0$90268$14726298@news.sunsite.dk>
Message-ID: 

Damjan wrote:
> My question is, shoudn't it be enough to set PYTHONPATH and everything
> automagically to work then? Is there some work done on this for python 3.0
> or 2.6 perhaps?

I'm working on a PEP for a per user site dir for 2.6 and 3.0

Christian



From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Wed Jan  9 07:27:55 2008
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Wed, 09 Jan 2008 13:27:55 +0100
Subject: Learning Python via a little word frequency program
In-Reply-To: <43a9a28c-0713-4789-b4f0-4e6ba0e8bbfd@u10g2000prn.googlegroups.com>
References: 
	<43a9a28c-0713-4789-b4f0-4e6ba0e8bbfd@u10g2000prn.googlegroups.com>
Message-ID: <4784bdcb$0$1225$426a34cc@news.free.fr>

Ant a ?crit :
>> I'm interested to learn how more experienced Python folks would solve
>> this little problem.
> 
> I think I'd do the following:
> 
> from collections import defaultdict
> 
> names = "freddy fred bill jock kevin andrew kevin kevin jock"
> freq = defaultdict(lambda: 0)
> 
> for name in names.split():
>     freq[name] += 1
> 
> pairs = [(v, k) for k, v in freq.iteritems()]
> 
> for v, k in reversed(sorted(pairs)):
>     print "%-10s: %d" % (k, v)
> 
> 
> defaultdict makes the frequency accumulation neater.
> 
> reversed(sorted(pairs)) avoids the little -v hack and makes it more
> obvious what you are doing.

But fails to implement the specs (emphasis is mine):
"""
   produce a frequency table of names, sorted descending by frequency.
   *then ascending by name*. For the above data, the output should be:

     kevin     : 3
     jock      : 2
     andrew    : 1
     bill      : 1
     fred      : 1
     freddy    : 1
"""

With your solution, you get:

kevin     : 3
jock      : 2
freddy    : 1
fred      : 1
bill      : 1
andrew    : 1




From bj_666 at gmx.net  Fri Jan 11 20:08:22 2008
From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch)
Date: 12 Jan 2008 01:08:22 GMT
Subject: encrypting python modules
References: <47873a78$0$85785$e4fe514c@news.xs4all.nl>
	<87sl14getd.fsf@benfinney.id.au>
Message-ID: <5uqi86F6710oU1@mid.uni-berlin.de>

On Sat, 12 Jan 2008 09:47:26 +1100, Ben Finney wrote:

> Trying to make bits uncopyable and unmodifiable is like trying to make
> water not wet.

Certainly not.  I can put water into the freezer, but I have no idea how
to make bits uncopyable and unmodifiable while still delivering them to
the clients for execution.  ;-)

Ciao,
	Marc 'BlackJack' Rintsch


From gagsl-py2 at yahoo.com.ar  Tue Jan 22 00:24:40 2008
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Tue, 22 Jan 2008 03:24:40 -0200
Subject: read files
References: 
	<7xbq7e5wxt.fsf@ruckus.brouhaha.com>
Message-ID: 

En Tue, 22 Jan 2008 02:03:10 -0200, Paul Rubin  
<"http://phr.cx"@NOSPAM.invalid> escribi?:

> "J. Peng"  writes:
>>         print line,
>
> Do you really want all the lines crunched together like that?  If not,
> leave off the comma.

Remember that Python *keeps* the end-of-line charater at the end of each  
line; if you leave out the comma, you'll print them doubly spaced.

-- 
Gabriel Genellina



From joemystery123 at gmail.com  Tue Jan  1 12:51:15 2008
From: joemystery123 at gmail.com (crybaby)
Date: Tue, 1 Jan 2008 09:51:15 -0800 (PST)
Subject: pexpect ssh login and ls | grep
References: <3eb81375-3e4a-4e0f-a4e7-bbb1d6cd0f8c@s19g2000prg.googlegroups.com>
	<477a6eec$0$17448$bf4948fe@news.tele2.nl>
Message-ID: <1c62b205-e2dd-4bb9-ac99-e14ce652afab@21g2000hsj.googlegroups.com>

I don't get 0 or 2(excuting ls command exit code)
from result.split('\r\n')[0] or result.split('\r\n')[1].  I have to
try another method.

Regular shell ssh login:

[joe at com1 ~]$ ssh my at mycomp2
Last login: Mon Dec 31 20:51:09 2007 from com1
[my at mycomp2 ~]$

Pexpect Login:
>>> import pexpect
>>> child=pexpect.spawn("ssh my at mycomp2")
>>> child.sendline("ls mytest.log > /dev/null 2>&1; echo $? ")
42
>>> child.expect([pexpect.TIMEOUT, r"\$"])
1
>>> result1=child.before
>>> result2=child.after
>>> print result1
Last login: Tue Jan  1 11:22:05 2008 from com1
[my at mycomp2 ~]
>>> print result2
$
>>> print result1.split('\r\n')[1]
[my at mycomp2 ~]
>>> print result1.split('\r\n')[0]
Last login: Tue Jan  1 11:22:05 2008 from com1

thanks.


From http  Fri Jan 18 14:55:42 2008
From: http (Paul Rubin)
Date: 18 Jan 2008 11:55:42 -0800
Subject: Core Python Programming . . .
References: 
Message-ID: <7xir1q29j5.fsf@ruckus.brouhaha.com>

FireNWater  writes:
> 1) convert a 4-digit Integer (WXYZ) to an IP address (WWW.XXX.YYY.ZZZ)
> 
> or
> 
> 2) convert an 8-digit Integer (WWWXXXYYYZZZ) to (WWW.XXX.YYY.ZZZ)
> 
> Thanks for anyone with the clue!!!

Without being able to see the exercise I suspect it's turn a 4-byte
string (i.e. 32 bits) into an IP address (int8.int8.int8.int8).
Or, it might be turn a 32-bit int into such an address.


From ricaraoz at gmail.com  Thu Jan 31 07:39:16 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Thu, 31 Jan 2008 09:39:16 -0300
Subject: REALLY simple xml reader
In-Reply-To: <60do34F1q1qmlU1@mid.uni-berlin.de>
References: 	<1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com>			
	<60do34F1q1qmlU1@mid.uni-berlin.de>
Message-ID: <47A1C174.7060302@bigfoot.com>

Diez B. Roggisch wrote:
> Ricardo Ar?oz schrieb:
>> Thanks Ivan, it seems a elegant API, and easy to use.
>> I tried to play a little with it but unfortunately could not get it off
>> the ground. I kept getting
>>>>> root = et.fromstring(doc)
>> Traceback (most recent call last):
>>   File "", line 1, in 
>>   File "E:\Python25\lib\xml\etree\ElementTree.py", line 963, in XML
>>     parser.feed(text)
>>   File "E:\Python25\lib\xml\etree\ElementTree.py", line 1245, in feed
>>     self._parser.Parse(data, 0)
>> ExpatError: XML or text declaration not at start of entity: line 2, column 0
> 
> That's a problem in your XML not being XML. Has nothing to do with 
> element-tree - as one sees from the error-message "ExpatError". If you 
> show it to us, we might see why.
> 

Sure,

doc = """


expenses: january 2002

  
    31.19
    200213
    Walking Store
    shoes
  

  
    1549.58
    200217
    Bob's Bolts
  

  
    40
    200218
    pocket money
  

  
    25
    200218
  

  
    188.20
    200218
    Boston Endodontics
    cavity
  

  
    10.58
    2002110
    Exxon Saugus
    gasoline
  

  
    909.56
    2002114
    Honda North
    car repairs
  

  
    24.30
    2002115
    Johnny Rockets
    lunch
  

"""
I thought this was proper XML as it comes straight out from an O'Reilly
XML book.

Cheers


From brad at 16systems.com  Sun Jan  6 17:37:03 2008
From: brad at 16systems.com (Brad)
Date: Sun, 06 Jan 2008 17:37:03 -0500
Subject: Patches to Python 2.5.1
Message-ID: 

I was just looking through the 2.5.1 source code. I noticed a few 
mis-spellings in the comments. No big deal really. Can patches be 
submitted that correct the spelling errors or should they just be 
pointed out to some mailing list?

Thanks,
Brad


From vriolk at gmail.com  Sun Jan 27 12:06:09 2008
From: vriolk at gmail.com (coldpizza)
Date: Sun, 27 Jan 2008 09:06:09 -0800 (PST)
Subject: py3k feature proposal: field auto-assignment in constructors
Message-ID: 

There is a pattern that occurs fairly often in constructors in Python
and other OOP languages.

Let's take an example:

class Server(object):
    def __init__(self, host, port, protocol, bufsize, timeout):
        self.host = host
        self.port = port
        self.protocol = protocol
        self.bufsize = bufsize
        self.maxthreads = maxthreads
        self.timeout = timeout

Imho, in the class above the assignment to instance fields does not
contain much programming logic and therefore can be safely 'abstracted
away' by the language itself with a syntax which would look something
like this:

class Server(object):
    def __init__(self, @host, @port, @protocol, @bufsize, @timeout):
        pass

This would be equivalent to the first example above, yet it does not
obfuscate the code in any way. Or does it? It does look much cleaner
to me.

Of course, the ampersand is just an arbitrary choice and might have
bad connotations for those who read it as 'take address of' but @ has
some allusion to delegates which maybe is ok.

I am not an experienced programmer and I am not sure if this is
necessarily a good idea, so I wanted to get some feedback from more
experienced Pythonistas before submitting it elsewhere.




From steve at REMOVE-THIS-cybersource.com.au  Sat Jan 12 00:17:59 2008
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: Sat, 12 Jan 2008 05:17:59 -0000
Subject: Magic function
References: <1395e14d-7093-46cb-88e8-281bdad6defc@e10g2000prf.googlegroups.com>
	<13og1lgcespv6c2@corp.supernews.com>
	
	<13oga52q3f2gg1c@corp.supernews.com>
	
Message-ID: <13ogjc7bt5175dd@corp.supernews.com>

On Fri, 11 Jan 2008 19:36:24 -0800, Michael Tobis wrote:

> On Jan 11, 8:40 pm, Steven D'Aprano  cybersource.com.au> wrote:
> 
>> Read the OP's post again. His (her?) users aren't expected to create
>> the toolkit, merely to use it. To create good toolkits you need both a
>> master programmer and an expert in the field. It is an advantage if
>> they are the same person. But to use such a good toolkit, you shouldn't
>> need to be a master programmer.
> 
> It appears we are in agreement, then.
> 
> But that leaves me in a position where I can't understand your
> complaint. There's no reason I can see for the sort of compromise you
> ask for.

What compromise do you think I'm asking for?

I'm suggesting that the scientists be given a brief, introductory 
education in *how to use their tool*, namely, Python.

Instead of creating some sort of magic function that "just works" (except 
when it doesn't) by doing some sort of implicit "grab every object of 
type Obj() you can find and do processing on that", stick to the more 
reliable and safer technique of having the programmer explicitly provide 
the objects she wants to work with.


> Clean abstractions benefit from their cleanliness.

An automatic "run()" that uses a bunch of stuff you can't see as input is 
not a clean abstraction. "Do What I Mean" functions have a long and 
inglorious history of not doing what the user meant.

There's a fundamental difference between (say) Python's automatic garbage 
collection and what the OP is suggesting. Explicitly deleting variables 
is almost always the sort of trivial incantation you rightly decry. The 
computer can tell when a variable is no longer reachable, and therefore 
is safe to delete. But the computer can't safely tell when the user wants 
to use a variable as input to a function. The user needs to explicitly 
tell the computer what is input and what isn't.

The OP is suggesting taking that decision out of the hands of the user, 
and making every variable of type Obj automatically input. If you think 
that's a good idea, consider a programming tool kit with a function sum() 
which inspects every variable you have and adds up every one that is a 
number.



> It's not clear that this is the sort of application where cutting
> corners makes sense, so I don't see how your advice is justified.

Sorry, are you suggesting that training the scientists to use their tools 
is cutting corners? Because I'd call the OP's suggestion to use magic 
functions a dangerous, ill-conceived cut corner.


-- 
Steven


From gherron at islandtraining.com  Sat Jan 12 15:52:05 2008
From: gherron at islandtraining.com (Gary Herron)
Date: Sat, 12 Jan 2008 12:52:05 -0800
Subject: sqlite3 is it in the python default distro?
In-Reply-To: 
References: 
Message-ID: <47892875.1080207@islandtraining.com>

Martin Marcher wrote:
> Hello,
>
> I can see that sqlite is in the standard lib documentation:
> http://docs.python.org/lib/module-sqlite3.html
>
> however debian and ubuntu (and gentoo according to the packages info) seem
> _not_ to include it. 
>
> Now 2 question arise:
>
> a) Is sqlite included in the python default distribution
> b) In real life can I consider (on linux) that an installation of python
> includes the sqlite stuff?
>
> thanks
> martin
>
>   
As I understand it, Python2.5 includes the *module* which can be
imported to access an sqlite installation, but it does not include the
sqlite installation itself.   That should be installed separately.   (I
suppose a distro of Linux could package them together, but I don't  know
of one that does, and such is not the intent of Python.)

Gary Herron



From goon12 at gmail.com  Tue Jan 29 13:59:27 2008
From: goon12 at gmail.com (Joe Riopel)
Date: Tue, 29 Jan 2008 13:59:27 -0500
Subject: noob stuck on reading double
In-Reply-To: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk>
References: <92129CEDFB679043810C974BC1D6962C061A35C37C@ILS133.uopnet.plymouth.ac.uk>
Message-ID: <6a2ccd190801291059q1a18c70co8e9db881c6994f63@mail.gmail.com>

On Jan 29, 2008 1:35 PM, Hannah Drayson  wrote:
> It imports as a string of rubbish...
> i.e.
>
> 
> >>> text = f.read()
> >>> print text
> ?F?C??y??>?
> @??I at g[??B8~??????Q???Q???Q???Q???Q???Q???Q???Q???Q???Q????=N@???????????????????/???8@@@@?Q at E??/??T at N#????S@?????Q???Q???Q???Q???Q???????????R[???Q???????
> >>> unpack('d', text)
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/struct.py", line 87, in unpack
>     return o.unpack(s)
> struct.error: unpack requires a string argument of length 8

When reading the file, try using
file = open('data.bin', 'rb')
file.seek(0)
raw = file.read()

Do the unpack on "raw".

From deets at nospam.web.de  Tue Jan 22 09:17:14 2008
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Tue, 22 Jan 2008 15:17:14 +0100
Subject: isgenerator(...) - anywhere to be found?
References: <5vm8t3F1m1797U1@mid.uni-berlin.de>
	
Message-ID: <5vmc7aF1n9pk6U2@mid.uni-berlin.de>

Stefan Rank wrote:

> on 22.01.2008 14:20 Diez B. Roggisch said the following:
>> 
>> def isgenerator(v):
>>     def _g(): yield
>>     return type(v) == type(_g())
>> 
>> But I wonder why there is no such method already available?
> 
> 
> This tests for generator objects, and you could also use::
> 
>    return type(v) is types.GeneratorType
> 
> I think that this is pretty direct already.

Not as nice as it could be, but certainly way less hackish than my approach.
Thanks!

> I also need to test for generator functions from time to time for which
> I use::
> 
>    def _isaGeneratorFunction(func):
>        '''Check the bitmask of `func` for the magic generator flag.'''
>        return bool(func.func_code.co_flags & CO_GENERATOR)

Not sure if that's not a bit too much on the dark magic side.. but good to
know that it exists.

Diez


From florencio.cano at gmail.com  Thu Jan 10 15:32:18 2008
From: florencio.cano at gmail.com (Florencio Cano)
Date: Thu, 10 Jan 2008 21:32:18 +0100
Subject: XML+Logs to Latex. XSLT?
In-Reply-To: 
References: 
	
Message-ID: 

2008/1/10, Fredrik Lundh :
> Florencio Cano wrote:
>
> > I'm thinking about implementing a script in Python to do this task. I
> > have a XML log and logs from other programs. My aim is to do a report
> > about all this information. I'm thinking in using Python to transform
> > the plain logs to XML and combine them with the XML document I have
> > and later use some kind of XSLT to transform the whole XML document to
> > Latex. What do you think about that? I have not worked with XSLT
> > before and I don't know if this would be a correct use.
> > How will you do the job?
>
> why not do it all in Python?

Yes. For sure. I though XSLT was something like XML not other
"language" and that Python will have any library that uses XSLT to do
transformation...but, what you suggest is:

- First process the XML document with Python (sax?) and do the first
Latex document.
- Second process each log with Python and insert the information in
the Latex document created in first step.

Do you think this approach is the best? Fastest, clearest, more
maintenable? Is this the way you will do it? It seems good for me but
I would like to do this properly.

-- 
Florencio Cano Gabarda


From tijotomjoy at gmail.com  Thu Jan 10 23:51:50 2008
From: tijotomjoy at gmail.com (tijo)
Date: Thu, 10 Jan 2008 20:51:50 -0800 (PST)
Subject: Help needed
References: 
	<0da27dc1-785a-4796-a5a3-6ba1a0290cab@e25g2000prg.googlegroups.com>
Message-ID: <66390246-aada-40fe-b8d3-4816771b950f@i3g2000hsf.googlegroups.com>

Hi mate
i created the socket and the connection with tcp and udp i dont know
how to check the bytes send and time
could you help me with this

cheers
tijo


From gherron at islandtraining.com  Sat Jan 12 14:31:56 2008
From: gherron at islandtraining.com (Gary Herron)
Date: Sat, 12 Jan 2008 11:31:56 -0800
Subject: Simple List division problem
In-Reply-To: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com>
References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com>
Message-ID: <478915AC.8000205@islandtraining.com>

marcstuart wrote:
> How do I divide a list into a set group of sublist's- if the list is
> not evenly dividable ?
> consider this example:
>
> x = [1,2,3,4,5,6,7,8,9,10]
> y = 3      # number of lists I want to break x into
> z = y/x
>
>
> what I would like to get is 3 sublists
>
> print z[0] = [1,2,3]
> print z[2] = [4,5,6]
> print z[3] = [7,8,9,10]
>
> obviously not even, one list will have 4 elements, the other 2 will
> have 3.,
> the overriding logic, is that I will get 3 lists and find a way for
> python to try to break it evenly, if not one list can have a greater
> amount of elements
>
> Would I use itertools ? How would I do this ?
>
> Thanks
>   

Calculate the size of a normal sublist, and the amount of extra that
goes with the last sublist.
Then extract y-1 normal sized sublists and one possibly larger sublist.

>>> x = [1,2,3,4,5,6,7,8,9,10]
>>> y = 3
>>> s = len(x)/y
>>> s                        # size of normal sublists
3
>>> e = len(x) - y*s  # extra elements for last sublist
>>> e
1
>>> z = [x[s*i:s*i+s] for i in range(y-1)] + [x[-s-e:]] #extract y-1
normal + 1 larger sublists
>>> z
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]

Done!

Gary Herron







From sromero at gmail.com  Tue Jan  8 10:05:21 2008
From: sromero at gmail.com (Santiago Romero)
Date: Tue, 8 Jan 2008 07:05:21 -0800 (PST)
Subject: Converting a bidimensional list in a bidimensional array
Message-ID: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com>


 Hi :)

 First of all, I must apologize for my poor english :)

 I'm starting with python and pygame and for testing (and learning)
purposes I wrote an small "Map Editor" for a small game project I'm
going to start next month.

 The tilemap editor is working fine, but reading Guido's Van Rossum
PYTHON TUTORIAL I found that my game map is "wasting" memory by using
about 16 bytes for each item in it, because every item in a python
list takes 16 bytes in memory. In the same tutorial, I found
references to the "array()" function of the "array" module.

 I'm trying to change my current working source code so that it works
with an array instead of using a list, but I'm not managing to do it.

 My tilemap is something like (think on 0=empty, 1=floor, 2=rock, and
so...):

[
[0 ,0, 0, 0, 0, 0, 0, 0 ,0],
[0 ,0, 0, 0, 0, 0, 0, 0 ,0],
[2 ,0, 0, 0, 0, 2, 2, 0 ,0],
(...)
[2 ,2, 0, 0, 2, 2, 2, 0 ,0],
[1 ,1, 1, 1, 1, 1, 1, 1 ,1],
]

 This is how I create the tilemap (and the clipboard, a copy of my
tilemap):

    def __init__( self, bw, bh, tiles ):
      self.width, self.height = bw, bh
      self.tilemap = []
      self.clipboard = []
      (...)
      for i in range(bh):
         self.tilemap.append([0] * bw)
         self.clipboard.append([0] * bw)


 And that's how I'm using it (the functions I'm having trouble to
convert to use the array):

   #-------------------------------------
   def CopyToClipboard( self ):
      for j in range( self.height ):
         self.clipboard[j][:] = self.tilemap[j][:]

   #-------------------------------------
   def Draw( self, clear=1 ):
      screen = pygame.display.get_surface()
      if clear: self.Clear()

      for j in range(self.GetHeight()):
         for i in range(self.GetWidth()):
            self.DrawBlock( i, j )

   #-------------------------------------
   def DrawBlock( self, x, y ):
      screen = pygame.display.get_surface()
      xd = (x * self.TileWidth()) + self.originx;
      yd = (y * self.TileHeight()) + self.originy;
      b = self.tilemap[y][x]
      self.tileset.tiles[b].Draw( screen, xd, yd )

   #-------------------------------------
   def ResizeWidth( self, new ):
      bw, bh = self.GetWidth(), self.GetHeight()

      if new > bw:
         for j in range(bh):
            for i in range(new-bw):
               self.tilemap[j].append( 0 )
               self.clipboard[j].append( 0 )
         self.SetWidth( new )

      elif new < bw:
         for j in range(bh):
            for i in range(bw-new):
               del self.tilemap[j][-1]
               del self.clipboard[j][-1]
         self.SetWidth( new )

   #-------------------------------------
   def ResizeHeight( self, new ):
      bw, bh = self.GetWidth(), self.GetHeight()

      if new > bh:
         for i in range(new-bh):
            self.tilemap.append([0] * bw)
            self.clipboard.append([0] * bw)
         self.SetHeight( new )

      elif new < bh:
         for i in range(1,bh-new):
             del self.tilemap[-1]
         self.SetHeight( new )



In fact, I'm even unable to create the array correctly:


 I've tried:

      self.tilemap = array('H', [])

      for i in range(bh):
         self.tilemap.append([0] * bw)

 and:

      for i in range(bh):

         for j in range(bw):
            self.tilemap[i].append(0)


 But I receive errors like (either defining or using the array):

 b = self.tilemap[y][x]
TypeError: 'int' object is unsubscriptable

 or:

self.tilemap.append( [0] * bw )
TypeError: an integer is required



 So ... please ... any idea on how to convert my "python object" array
of lists to a bidimensional array and how to use it to index [y][x]
elements, or even resize it with the ResizeWidth() and Height()
functions?

 Thanks everybody.


PS: Please, think that I come from C/C++ so I still have some "C ways
of doing things" while there are better/faster ways to do the same in
Python. Feel free also to correct any "C-Style" programming way that
you can find in my source code above... :-)


From geraint.williams at gmail.com  Sun Jan  6 18:09:13 2008
From: geraint.williams at gmail.com (GHZ)
Date: Sun, 6 Jan 2008 15:09:13 -0800 (PST)
Subject: Noob question
References: <17e045f1-7891-4afc-a98b-42dffdc45dd4@41g2000hsy.googlegroups.com>
Message-ID: 

Had the same issue.  What you want is: reload()


From robert.kern at gmail.com  Sat Jan  5 06:05:44 2008
From: robert.kern at gmail.com (Robert Kern)
Date: Sat, 05 Jan 2008 05:05:44 -0600
Subject: Fortran to Python
In-Reply-To: <20080105103643.GT82115@nexus.in-nomine.org>
References: 	<13nstth7a3km06c@corp.supernews.com>
	<20080105103643.GT82115@nexus.in-nomine.org>
Message-ID: 

Jeroen Ruigrok van der Werven wrote:
> -On [20080104 19:21], Dennis Lee Bieber (wlfraed at ix.netcom.com) wrote:
>> 	If the FORTRAN is using single precision reals, I'd expect a
>> slow-down in Python just on that alone, as Python uses doubles as the
>> only float type. There is also the overhead of object access for each.
> 
> In this case it uses complex*16 and real*8. Is a real*8 a single precision
> real?

Double precision. These map to the Python complex and float types exactly.

-- 
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 ggpolo at gmail.com  Mon Jan  7 14:29:03 2008
From: ggpolo at gmail.com (Guilherme Polo)
Date: Mon, 7 Jan 2008 17:29:03 -0200
Subject: any() and all() shorthand
In-Reply-To: <2e589a86-02cf-4903-98aa-c28be2b0b48f@1g2000hsl.googlegroups.com>
References: 
	
	<2e589a86-02cf-4903-98aa-c28be2b0b48f@1g2000hsl.googlegroups.com>
Message-ID: 

2008/1/7, castironpi at gmail.com :
> > You are too late, any and all are built-in into python 2.5
>
> Hi, excellent.  Now how about something more generic, possibly:
>
> [ x.y() for x or _next_ in c ]
>
> where the context of _next_ is limited in complexity, and/or can only
> occur in a generator?

Would you care to explain what that syntax supposedly means ? By
_next_ you mean something like the next method in generators ? _next_
executes if x is false ? so whatever _next_ returns is named as x, so
you can call x.y() ? I really didn't get your new syntax inside that
list comprehension, neither its uses.

> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
-- Guilherme H. Polo Goncalves


From dpsanders at gmail.com  Fri Jan 18 12:15:58 2008
From: dpsanders at gmail.com (David Sanders)
Date: Fri, 18 Jan 2008 09:15:58 -0800 (PST)
Subject: Efficient processing of large nuumeric data file
Message-ID: <6cc07f0a-e425-46f7-ae3d-c02ccf6be1fc@u10g2000prn.googlegroups.com>

Hi,

I am processing large files of numerical data.  Each line is either a
single (positive) integer, or a pair of positive integers, where the
second represents the number of times that the first number is
repeated in the data -- this is to avoid generating huge raw files,
since one particular number is often repeated in the data generation
step.

My question is how to process such files efficiently to obtain a
frequency histogram of the data (how many times each number occurs in
the data, taking into account the repetitions).  My current code is as
follows:

-------------------
#!/usr/bin/env python
# Counts the occurrences of integers in a file and makes a histogram
of them
# Allows for a second field which gives the number of counts of each
datum

import sys
args = sys.argv
num_args = len(args)

if num_args < 2:
	print "Syntaxis: count.py archivo"
	sys.exit();

name = args[1]
file = open(name, "r")

hist = {}   # dictionary for histogram
num = 0

for line in file:
	data = line.split()
	first = int(data[0])

	if len(data) == 1:
		count = 1
	else:
		count = int(data[1])    # more than one repetition

	if first in hist:       # add the information to the histogram
		hist[first]+=count
	else:
		hist[first]=count

	num+=count

keys = hist.keys()
keys.sort()

print "# i  fraction   hist[i]"
for i in keys:
	print i, float(hist[i])/num, hist[i]
---------------------

The data files are large (~100 million lines), and this code takes a
long time to run (compared to just doing wc -l, for example).

Am I doing something very inefficient?  (Any general comments on my
pythonic (or otherwise) style are also appreciated!)  Is
"line.split()" efficient, for example?

Is a dictionary the right way to do this?  In any given file, there is
an upper bound on the data, so it seems to me that some kind of array
(numpy?) would be more efficient, but the upper bound changes in each
file.

Thanks and best wishes,
David.


From kyosohma at gmail.com  Wed Jan 16 14:06:45 2008
From: kyosohma at gmail.com (Mike Driscoll)
Date: Wed, 16 Jan 2008 11:06:45 -0800 (PST)
Subject: A question about event handlers with wxPython
References: <478c3bb2$0$5150$4c368faf@roadrunner.com>
	<2e49bc15-379e-43b9-a3fc-bb8eebb87717@e23g2000prf.googlegroups.com>
	<478ccbc3$0$11000$4c368faf@roadrunner.com>
	
	<478d15b4$0$18437$4c368faf@roadrunner.com>
	<0571a7cd-f7f6-44b4-a4d5-e427de93590a@c4g2000hsg.googlegroups.com>
	<478e5251$0$22656$4c368faf@roadrunner.com>
Message-ID: <71dd1ea4-80a1-4a3d-99ae-e9a9c175790b@q77g2000hsh.googlegroups.com>

On Jan 16, 12:45 pm, "Erik Lind"  wrote:
> "Mike Driscoll"  wrote in message
>
> news:0571a7cd-f7f6-44b4-a4d5-e427de93590a at c4g2000hsg.googlegroups.com...
>
> > On Jan 15, 2:20 pm, "Erik Lind"  wrote:
> >> That all looks cool. I will experiment more. I'm a bit slow on this as
> >> only
> >> two weeks old so far.
>
> >> Thanks for the patience
>
> > No problem. I'm pretty slow with some toolkits too...such as
> > SQLAlchemy. Ugh.
>
> > Mike
>
> BTW,
>
> The wxPython group that you mentioned....is thathttp://wxforum.shadonet.com/   ?

I think those are C++ users using the pure C++ wx. I meant the
following:

http://wxpython.org/maillist.php

Mike


From colinlandrum at gmail.com  Wed Jan  2 03:39:21 2008
From: colinlandrum at gmail.com (hubritic)
Date: Wed, 2 Jan 2008 00:39:21 -0800 (PST)
Subject: pyparsing question
References: <8df809a0-1950-4250-a968-2d366f64cdb4@d21g2000prf.googlegroups.com>
	<1115f571-ecd9-4660-9813-b71ae636ac56@d4g2000prg.googlegroups.com>
Message-ID: 

On Jan 1, 4:18 pm, John Machin  wrote:
> On Jan 2, 10:32 am, hubritic  wrote:
>
> > The data I have has a fixed number of characters per field, so I could
> > split it up that way, but wouldn't that defeat the purpose of using a
> > parser?
>
> The purpose of a parser is to parse. Data in fixed columns does not
> need parsing.
>
> >  I am determined to become proficient with pyparsing so I am
> > using it even when it could be considered overkill; thus, it has gone
> > past mere utility now, this is a matter of principle!
>
> An extremely misguided "principle".  Would you use an AK47 on the
> flies around your barbecue? A better principle is to choose the best
> tool for the job.

Your principle is no doubt the saner one for the real world, but your
example of AK47 is a bit off.
We generally know enough about an AK47 to know that it is not
something to kill flies with. Consider, though, if
someone unfamiliar with the concept of guns and mayhem got an AK47 for
xmas and was only told that it was
really good for killing things. He would try it out and would discover
that indeed it kills all sorts of things.
So he might try killing flies. Then he would discover the limitations;
those already familiar with guns would wonder
why he would waste his time.


From pavlovevidence at gmail.com  Sun Jan  6 11:36:57 2008
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sun, 6 Jan 2008 11:36:57 -0500
Subject: list property fires get on append
References: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com>
	
	
Message-ID: <930rlf.mc3.ln@127.0.0.1>

On Sun, 06 Jan 2008 00:31:13 -0800, Soviut wrote:
> I figured that an append would be treated as a set since I'm adding to
> the list.  But what you say makes sense, although I can't say I'm happy
> with the behaviour.  Is there any way I can get the append to fire a
> set?  I'm thinking of properties from my C# background where i believe
> that manipulation such this would be considered a set.

You'd have to have to hook into the container object itself to detect the 
modification.  This might be pretty workable for you since it's an 
internal object.  Basically, instead of using a list, use a special list-
like object that notifies it's owner when it changes.  Here's a simple 
example to point you in the right direction:


class NotifierList(list):
     def __init__(self,*args,**kwargs):
         super(NotifierList,self).__init__(*args,**kwargs)
         self.watchers = []
     def add_watcher(self,watcher):
         self.watchers.append(watcher)
     def _notify_watchers(self):
         for watcher in self.watchers:
             watcher.object_changed(self)
     def append(self,value):
         super(NotifierList,self).append(value)
         self._notify_watchers()
     # override all other mutating calls, including __setitem__
     # left as exercise


class Hierarchy(object):
    def __init__(self):
        self.children = NotifierList()
        self.children.add_watcher(self)
    def object_changed(self,obj):
        print "self.children modified"
    # no need to make children a property then
    # unless you want to trap rebinding it to new object also


A couple other minor suggestions:

print is a statement, not a function.  You should write

print "GETTING"

not

print("GETTING")

The latter works, but it will cease to work if you want to print more 
than one thing.  Note that print is scheduled to become a function in 
Python 3.0, but for now it's a statement.

Based on the name of your class and typical usage, I'm guessing that you 
probably want _children to be an instance attribute rather than a class 
attribute, so I redid it that way, but .)


P.S. Is calling a method called "firing" in C#?


Carl Banks


From cokofreedom at gmail.com  Mon Jan 21 05:09:09 2008
From: cokofreedom at gmail.com (cokofreedom at gmail.com)
Date: Mon, 21 Jan 2008 02:09:09 -0800 (PST)
Subject: Default attribute values pattern
References: 
	
	<4794697f$0$16980$426a74cc@news.free.fr>
Message-ID: <41f8394c-342c-42dc-9bf2-a737b572aff9@c4g2000hsg.googlegroups.com>

> Grab(argdict, key, default) is argdict.pop(key, default)

"pop() raises a KeyError when no default value is given and the key is
not found."

> def grab(kw, key, default=None):
>    try:
>      return kw.pop(key)
>    except KeyError:
>      return default

So Bruno's technique seems to me to be the correct one as it catches
the KeyError.


From browerg at verizon.net  Wed Jan 16 18:02:17 2008
From: browerg at verizon.net (browerg at verizon.net)
Date: Wed, 16 Jan 2008 17:02:17 -0600 (CST)
Subject: scope question in a switch mixin
Message-ID: <3170329.6449001200524538128.JavaMail.root@vms061.mailsrvcs.net>

John,
Thanks for writing, and I'm sorry it's taken so long to get back to you. Python is fun for me -- dinner guests and my boss got in the way.

>> The code ... is the result of noodling around with switches as a learning tool. I've played with python for a few years, but I'm self-taught, so . . .
>> My question is, why are modules imported at the top of the program not visible to the functions Switch builds? There is
>> no problem when the import is in the function, but I thought initially that imports at the top would be in its globals.

>John wrote:
>The global namespace of the to-be-exec'ed code is the dictionary that 
>you supply. That dictionary doesn't contain "math".

Thank you for the guidance about namespaces and exec.

>It's a long time since exec has been documented as a *function*. Why? 
>Because it isn't:

. . . and the code snip.

>What book/tutorial did you get that from?

Hey, I'm not going to pass that off on anyone. As usual, self-education means missing a lot. 

I'm exploring your suggestions and working on my code. 

Thanks again.

George



From peanut.sam at googlemail.com  Thu Jan  3 23:17:39 2008
From: peanut.sam at googlemail.com (Sam Garson)
Date: Fri, 4 Jan 2008 04:17:39 +0000
Subject: Im back...
Message-ID: <4e1ac4910801032017t775cc499w6d9d600f3725221a@mail.gmail.com>

Hi there same project I am afraid...

I want to put the text from the selection of a listbox into a Label when the
the selection is clicked.

I have it so it is put in, but it is put in when I click on the
*next*selection...as in it defines the variable when I click on the
desired the
selection, but it puts it into the label when i click on the *next* item.
It is best if you  have a look. Here is the whole program

[start python code; possibly wrapped by browser]


#!/user/bin/python

from Tkinter import *

def insert():
    name = ent.get()
    box.insert(0, name)
    ent.delete(0, END)

def DeleteCurrent(event):
    box.delete(ANCHOR)

def putLabel(event):
    selection = box.get(ANCHOR)
    v.set(str(selection))

root = Tk()

ent = Entry(root, fg = '#3a3a3a', bg = 'white', relief = 'groove')
ent.grid(row = 0, padx = 3, pady = 3)

button = Button(root, text = "Remember", command = insert, relief =
'groove', fg = '#3a3a3a')
button.grid(row = 0, column = 1, padx = 3, pady = 3)

box = Listbox(root, bg = '#ebe9ed', relief = 'groove', height = 15)
box.selectmode = BROWSE
box.grid(row = 2, columnspan = 2, sticky = W+E, padx = 3)
box.bind("", DeleteCurrent)
box.bind("", putLabel)

v = StringVar()

current = Label(root, textvariable = v)
current.grid(row = 3, columnspan = 2, sticky = W+E, padx = 3)


root.mainloop()


[end python code]

how do i make it so it puts it into the variable *when* i click it? Any help
will be greatly appreciated!


Thanks,

Sam
-- 
I intend to live forever - so far, so good.

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

From paul at boddie.org.uk  Sat Jan 19 11:11:32 2008
From: paul at boddie.org.uk (Paul Boddie)
Date: Sat, 19 Jan 2008 08:11:32 -0800 (PST)
Subject: Using "pickle" for interprocess communication - some notes and 
	things that ought to be documented.
References: <478FAC5A.50206@animats.com>
	 
	<478ff1e6$0$85790$e4fe514c@news.xs4all.nl>
	<479046a5$0$36403$742ec2ed@news.sonic.net> 
	<3b14e57b-9461-4e1c-9bde-fdde99f87617@z17g2000hsg.googlegroups.com> 
	<47921ea4$0$36366$742ec2ed@news.sonic.net>
Message-ID: <96402e46-ea4f-46e6-88e8-fa2e60ab3221@i3g2000hsf.googlegroups.com>

On 19 Jan, 17:06, John Nagle  wrote:
> Paul Boddie wrote:
> > Unlike your approach, pprocess employs the fork system call.
>
>      Unfortunately, that's not portable.  Python's "fork()" is
> "Availability: Macintosh, Unix."  I would have preferred
> to use "fork()".

There was a discussion some time ago about providing a fork
implementation on Windows, since Cygwin attempts/attempted to provide
such support [1] and there's a Perl module which pretends to provide
fork (using threads if I recall correctly), but I'm not sure whether
anyone really believed that it was workable. I believe that on modern
releases of Windows it was the ZwCreateProcess function which was
supposed to be usable for this purpose, but you then apparently have
to add a bunch of other things to initialise the new process
appropriately.

Of course, for the purposes of pprocess - providing a multiprocess
solution which should be as easy to use as spawning threads whilst
having some shared, immutable state hanging around that you don't want
to think too hard about - having fork is essential, but if you're
obviously willing to split your program up into different components
then any of the distributed object technologies would be good enough.

Paul

[1] http://www.cygwin.com/ml/cygwin/2002-01/msg01826.html


From bignose+hates-spam at benfinney.id.au  Wed Jan 23 22:23:01 2008
From: bignose+hates-spam at benfinney.id.au (Ben Finney)
Date: Thu, 24 Jan 2008 14:23:01 +1100
Subject: Can someone explain this unexpected raw_input behavior?
References: 
	
	
Message-ID: <87myqv7vqi.fsf@benfinney.id.au>

Mike Kent  writes:

> Consider an interactive program, that asks the user several
> questions, and displays paragraphs of information based on those
> questions. The paragraphs are output using print, and the questions
> are asked via raw_input.

Okay so far.

> You want to do some simple debugging of the program by printing some
> debugging statements via 'print >>sys.stderr', and you don't want
> the debug output mixed in with the normal output on the screen, so
> you try to route the debugging output to a file by adding
> '2>filename' to the end of the command line.

This issue isn't specific to Python. "Program stops to ask questions
from the user" is not compatible with "Can safely redirect output of
the program to a file".

Either one, or both, of those requirements will have to be
compromised, or dropped completely.

-- 
 \                           "Holy hole in a donut, Batman!"  -- Robin |
  `\                                                                   |
_o__)                                                                  |
Ben Finney


From peanut.sam at googlemail.com  Wed Jan  9 08:09:06 2008
From: peanut.sam at googlemail.com (Sam Garson)
Date: Wed, 9 Jan 2008 13:09:06 +0000
Subject: Newbie question: Classes
In-Reply-To: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com>
References: <4e1ac4910801081136k142b1fbo8d635145b2ce1d8d@mail.gmail.com>
Message-ID: <4e1ac4910801090509k4be7eff3g9d8ac1f113e26e44@mail.gmail.com>

OK i've kind of got that. The only thing left is calling the class.

"
class Remember:

    def __init__(self, master):

        self.ent = Entry(self, ...

root = Tk()

app = Remember(root)
"
I get the error "Remember instance has no attribute 'tk' "...???




On Jan 8, 2008 7:36 PM, Sam Garson  wrote:

> Hello all
>
> Basically, I have created a program using tkinter without using any class
> structure, simply creating widgets and functions (and finding ways around
> passing variables from function to function, using global variables etc).
> The program has become rather large ( lines?) I am trying to now put it into
> a class structure, because I hear it is easier to handle.
>
> So basically, I put all the stuff into a class, making the widgets in the
> "def __init__(self, root)" (root being my Tk() ) and then I have had to put
> a "self." in front of any instance of any variable or widget. Is this right?
> it seems like nothing is any easier (except having variables locally). Is
> this right? Should I be creating more classes for different things or what?
>
> I can upload the .py if you want.
>
> Thanks,
>
> Sam
>
> --
> I intend to live forever - so far, so good.
>
> SaM




-- 
I intend to live forever - so far, so good.

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

From dblubaugh at belcan.com  Wed Jan 30 19:40:24 2008
From: dblubaugh at belcan.com (Blubaugh, David A.)
Date: Wed, 30 Jan 2008 19:40:24 -0500
Subject: Why the HELL has nobody answered my question
	!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
In-Reply-To: 
References: 
Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com>

I do not understand why no one has answered the following question:

Has anybody worked with Gene Expression Programming????   


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: Wednesday, January 30, 2008 6:10 PM
To: python-list at python.org
Subject: Python-list Digest, Vol 52, Issue 437

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.




From steve at REMOVE-THIS-cybersource.com.au  Fri Jan 25 06:35:32 2008
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: Fri, 25 Jan 2008 11:35:32 -0000
Subject: global/local variables
References: 
	<13pia51grjfo2ed@corp.supernews.com>
	<4d161c89-7e33-4ddc-851f-bc9beb537229@q21g2000hsa.googlegroups.com>
	<13pjekb7r9jja4c@corp.supernews.com>
	<8d7caad9-fcc3-4bb5-bd7b-dd71e6bd6099@d4g2000prg.googlegroups.com>
Message-ID: <13pjic4h1fag948@corp.supernews.com>

On Fri, 25 Jan 2008 03:28:05 -0800, Tim Rau wrote:

>> Because you don't assign to allThings, and therefore it is treated as
>> global.
>>
>>
> Hmm.... so I can't assign to globals in a  local environment? How do I
> make it see that I'm assigning to a global?

I thought somebody had already mentioned this... possibly even me... 

You can declare a name as global by using the global statement:

def foo():
    global x
    x += 1


-- 
Steven


From MartinRinehart at gmail.com  Fri Jan 11 14:50:52 2008
From: MartinRinehart at gmail.com (MartinRinehart at gmail.com)
Date: Fri, 11 Jan 2008 11:50:52 -0800 (PST)
Subject: Newbie wants to get visual
Message-ID: <63e25138-2a02-471f-b42b-f3af2c69b6a8@f47g2000hsd.googlegroups.com>

I'm ready to start coding the parser for my Decaf (beginners)
language. I think that a "visual" parser (one that shows what it's
doing as it does it) would be nice. (And I think that it would help
the parser author by saving the requirement for a bazillion print
statements while debugging the tool.)

Can someone point me toward the easiest possible way to get GUI? I've
got the Rappin/Dunn book re wxPython, but suspect that this may be
overkill for what I want. If I could do something that would work in a
browser window, that would be wonderful.


From sjmachin at lexicon.net  Wed Jan  9 13:25:20 2008
From: sjmachin at lexicon.net (John Machin)
Date: Wed, 9 Jan 2008 10:25:20 -0800 (PST)
Subject: How does unicode() work?
References: <5ujt96F1i6h37U1@mid.dfncis.de>  
	<1199888091.3474.9.camel@dot.uniqsys.com>  
	
Message-ID: 

On Jan 10, 1:55 am, Carsten Haese  wrote:
> On Wed, 2008-01-09 at 15:33 +0100, Fredrik Lundh wrote:
> > When mixing Unicode with byte strings, Python attempts to decode the
> > byte string, not encode the Unicode string.
>
> Ah, I did not realize that. I never mix Unicode and byte strings in the
> first place, and now I know why. Thanks for clearing that up.
>

When mixing unicode strings with byte strings, Python attempts to
decode the str object to unicode, not encode the unicode object to
str. This is fine, especially when compared with the alternative, so
long as the str object is (loosely) ASCII. If the str object contains
a byte such that ord(byte) > 127, an exception will be raised.

When mixing floats with ints, Python attempts to decode the int to
float, not encode the float to int. This is fine, especially when
compared with the alternative, so long as the int is not humungous. If
the int is huge, you will lose precision without any warning or any
exception being raised.

Do you avoid mixing ints and floats?


From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Thu Jan 17 11:38:58 2008
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Thu, 17 Jan 2008 17:38:58 +0100
Subject: Loop in a loop?
In-Reply-To: <55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com>
References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com>
	
	<48f718e4-8f4b-4061-ad6c-6d7b68d9b832@s19g2000prg.googlegroups.com>
	<55afd820-699d-44e3-b92b-ec2855decebe@i29g2000prf.googlegroups.com>
Message-ID: <478f8472$0$24708$426a74cc@news.free.fr>

cokofreedom at gmail.com a ?crit :
(snip)
> couldn't you just do something like
> 
> if len(array1) is not len(array2):

*never* use the identity operator to test equality ! The fact that 
CPython memoize small integers is an implementation detail, *not* a part 
of the language specification.

>     if len(array1) < len(array2):
>         max_length = len(array2) - len(array1)
>         array1.extend([None for i in xrange(0, max_length)])
>     elif len(array1) > len(array2):
>         max_length = len(array1) - len(array2)
>         array2.extend([None for i in xrange(0, max_length)])


Never heard of the builtin max() function ?-)

def pad(*lists, **kw):
    padding = kw.get('padding', None)
    lists_lens = [len(alist) for alist in lists]
    padlen = max(lists_lens)
    return [
             alist + ([padding] * (padlen - list_len))
             for list_len, alist in zip(lists_lens, lists)
           ]

for i in zip(*pad(range(3), range(5, 10))):
    print i


Now there are very certainly smart solutions using itertools, but the 
one I cooked is way too ugly so I'll leave this to itertools masters !-)


From steve at holdenweb.com  Thu Jan 31 17:03:03 2008
From: steve at holdenweb.com (Steve Holden)
Date: Thu, 31 Jan 2008 17:03:03 -0500
Subject: best(fastest) way to send and get lists from files
In-Reply-To: <4A1A35F8C85B294296F1911569C1137D034B5B57@MAIL2.AD.Brown.Edu>
References: <4A1A35F8C85B294296F1911569C1137D034B5B57@MAIL2.AD.Brown.Edu>
Message-ID: 

Abrahams, Max wrote:
> I've looked into pickle, dump, load, save, readlines(), etc.
> 
> Which is the best method? Fastest? My lists tend to be around a thousand to a million items.
> 
> Binary and text files are both okay, text would be preferred in general unless there's a significant speed boost from something binary.
> 
> thanks

benchmarks are the only reliable way to get this information for your 
particular tasks.

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  Thu Jan 24 06:50:21 2008
From: python.list at tim.thechases.com (Tim Chase)
Date: Thu, 24 Jan 2008 05:50:21 -0600
Subject: Designing website
In-Reply-To: <248758f0-6d8b-4e91-9c3c-a6a0314bebcb@q77g2000hsh.googlegroups.com>
References: <248758f0-6d8b-4e91-9c3c-a6a0314bebcb@q77g2000hsh.googlegroups.com>
Message-ID: <47987B7D.9080101@tim.thechases.com>

> I am planning to design a website using windows, apache, mysql,
> python.

You don't mention what sort of website...low-volume or
high-volume, basic text or graphic-intensive, simple design or
complex web-application logic.  Each of these factors into one's
choice.

> But I came to know that python cgi is very slow. I came across
> mod_python also but no good documentation are available for learning
> mod_python. Suggest me a good solution for this as I don't know other
> languages like PHP; I prefer python.

If you're coming from CGI development and planning a small app,
I'll give a plug for the WebStack[1] framework which basically
reduces just about every option out there (CGI, mod_python,
built-in BaseHTTPServer, and several othes) to a common API.

However, I'd also recommend looking into one of the more powerful
frameworks that abstracts away the server interface a bit more.
I'm personally a Django[2] guy, but for some folks CherryPy[3],
Pylons[4], TurboGears[5] or Zope[6] fills the bill.

They do the grunt work of interfacing with your web-server
(whether through mod_python, FastCGI or WSGI, or possibly other
options such as a Twisted[7] internal server) as well as make a
lot of other web-development aspects easier through separation of
concerns.  In most, business logic is kept separate from
presentation logic which are both kept separate from the data
layer.  This allows developers to focus on a particular aspect at
a time.

There are also deployment issues.  If you have your own server,
it's not a big deal.  However, if you're looking for cheap
low-end shared hosting, the resources made available on such a
machine are usually a bit constrained for these more powerful
schemes.  Sadly, this does make PHP look inviting for deployment
on low-end hosting services despite its warty language.

HTH,

-tkc

[1] http://www.boddie.org.uk/python/WebStack.html
[2] http://www.djangoproject.com
[3] http://www.cherrypy.org
[4] http://pylonshq.com
[5] http://turbogears.org
[6] http://zope.org
[7] http://twistedmatrix.com








From aspineux at gmail.com  Mon Jan 14 13:39:56 2008
From: aspineux at gmail.com (aspineux)
Date: Mon, 14 Jan 2008 10:39:56 -0800 (PST)
Subject: short path evaluation, why is f() called here: dict(a=1).get('a', 
	f())
Message-ID: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com>


This append in both case

dict(a=1).get('a', f())
dict(a=1).setdefault('a', f())

This should be nice if f() was called only if required.

Regards.



From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Tue Jan 29 12:53:48 2008
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Tue, 29 Jan 2008 18:53:48 +0100
Subject: Trying to understand Python web-development
In-Reply-To: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com>
References: <64da9d27-5c05-4bc0-9d01-20fcfe82c25d@e25g2000prg.googlegroups.com>
Message-ID: <479f6824$0$25381$426a74cc@news.free.fr>

walterbyrd a ?crit :
> I don't know much php either, but running a php app seems straight
> forward enough.

Mmm... As long as the whole system is already installed and connfigured, 
*and* matches your app's expectations, kind of, yes.

> Python seems to always use some sort of development environment vs
> production environment scheme.

s/Python/some frameworks/

> For development, you are supposed to
> run a local browser and load 127.0.0.1:5000 - or something like that.
> Then to run the same thing in a development environment,

I suppose you meant "in a production environment" ?

> I have to
> configure some files, or touch all the files, restart the web-server,
> or something. Why is that?

Developping directly on a production server is defiinitively a no-no, 
whatever the language. So you *always* develop un a development 
environment. In PHP, this imply having a running HTTP server - usually 
Apache - correctly configured. Some Python frameworks, OTHO, ship with 
their own lightweight Python-based http server, which usually makes 
things far easier. Since quite a lot of web programmers already have 
Apache running on port 80, the framework's own server usually runs (by 
default) on another port. Also, most of the time, on the production 
server, you choose some other more appropriate deployement solution - 
which may or not include Apache - depending on the context. So the nice 
point here is that:
1/ you have way more freedom wrt/ possible deployment solutions
2/ you don't have to replicate the whole damn thing (if ever possible) 
on your local machine to develop the app.

Of course, the actions to be taken when updating your app on the 
production server greatly depends on the deployment solution.

> Python also seems to require some sort of "long running processes" I
> guess that the python interpretor has to running all of time.

s/Python/some frameworks/

You can write web apps in Python using plain cgi, you know. It's just 
very inefficient due to how cgi works - to make a long story short: the 
system has to launch a new process for each request calling your script, 
and you have to rebuild the whole damn world each time your script is 
called. Note that PHP suffers at least from the second problem, which 
can make it somewhat inefficient for some kind of applications.

The point of long running processes is that most of the world is only 
built at startup and stays here between requests.

> I am not really sure about what wsgi is supposed to accomplish.

First and mainly, allow Python-based web apps to be independant from the 
deployment solution, by adding an indirection level. Instead of having

[yourapp]<-->[http_server]

which only work for the http server you targeted, you have

[yourapp]<-->[wsgi]<-->[http_server.wsgi_adapter]<-->[http_server]

which works for any http server for which a specific wsg adapter exists.

There are also some other benefits since, the way wsgi works, the [wsgi] 
part of the above schema can include quite a lot of other things, 
sometimes without your application being aware of it (you may want to 
look for 'wsgi middleware' for more on this).


HTH


From mr.cerutti at gmail.com  Thu Jan 17 10:59:06 2008
From: mr.cerutti at gmail.com (Neil Cerutti)
Date: Thu, 17 Jan 2008 10:59:06 -0500
Subject: Is this a bug, or is it me?
In-Reply-To: <87myr4o3sg.fsf@mulj.homelinux.net>
References: 
	
	<87myr4o3sg.fsf@mulj.homelinux.net>
Message-ID: <51302a8c0801170759xdba420jcc17cd22f679ee01@mail.gmail.com>

On Jan 17, 2008 10:44 AM, Hrvoje Niksic  wrote:
> "Neil Cerutti"  writes:
>
> > You cannot access a class's class variables in it's class-statement
> > scope, since the name of the type is not bound until after the class
> > statement is completed.
>
> But they are still available as locals, so you can access them using
> their names, like this:
>
> >>> class C:
> ...   a = 1
> ...   b = 2
> ...   print a+b
> ...
> 3

Thanks! I had never tried that before. That actually solved my default
method argument problem.

> The question is, why doesn't the OP's code snippet work?  It seems
> that the generator expression can't read the surrounding locals().
> But when you change the generator expression to a list comprehension
> using a pair of [] around it, it starts working.  Compare:
>
> class C(object):
>     d = {}
>     for a in 1, 2, 3:
>         ignore = list((a, b) for b in (4, 5, 6))
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 4, in C
>   File "", line 4, in 
> NameError: global name 'a' is not defined
>
> with:
>
> class C(object):
>     d = {}
>     for a in 1, 2, 3:
>         ignore = [(a, b) for b in (4, 5, 6)]
>
> It seems that generator expressions and list comprehensions have
> subtly different scoping rules.  Whether this is a bug or not is a
> good question.

Generator expressions, unlike list comprehensions, have their own
scope so that they don't "leak" names to the enclosing scope. The
Python rule forbidding access to the locals of enclosing scopes is
preventing the class names from working in the generator expression.

-- 
Neil Cerutti 


From jr9445 at ATT.COM  Fri Jan  4 10:50:03 2008
From: jr9445 at ATT.COM (Reedick, Andrew)
Date: Fri, 4 Jan 2008 09:50:03 -0600
Subject: dictionary/hash and '1' versus 1
In-Reply-To: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com>
References: 
	<7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com>
Message-ID: 

> From: Stephen Hansen [mailto:apt.shansen at gmail.com] 
> Sent: Thursday, January 03, 2008 7:39 PM
> To: Reedick, Andrew
> Cc: python-list at python.org
> Subject: Re: dictionary/hash and '1' versus 1
>
>
>
> Well one important thing to learn while learning Python is that while the  
> language is dynamically typed-- it is also /strongly/ typed. Every piece
> of data has an explicit type and it doesn't change unless you change it.

	Meh, mixing dynamic and strong typing is a mixed blessing.  You don't find out that you screwed up the data types until the code block is actually executed.  Reminds me of Nostradamus.  He may have predicted the future[1], but the predictions are so vague/convoluted that you can only figure out the predictions in hindsight.


> It relies on duck typing a lot, and doesn't care if you mix and match 
> (even partially) compatible types as long as the operations are there,
> but one type will always be distinct and remain that type until you
> explicitly convert it.
>
> A single integer is distinctly different from a sequence of characters in
> some encoding that may just happen to contain representations of a
> number.... so they'll hash differently :)

	Depends on the context.  The machine encoding may be different, but in human terms they "should" be the same.  Perl managed to achieve an impressive blend of presenting data as human friendly or as machine bits when it made sense to do so.  So much so, that Perl is probably the only language I've used that will do what you mean instead of what you say.  Nice, but frightening in some ways.


> One type will basically never implicitly convert into another type.
>
> To me, this sounds like the function should have converted the type 
> explicitly on return. Or maybe you need to convert it explicitly on
> receipt.

	Type casting is easy, IFF you remember to do so.  The problem was that I missed the fact that one (important) function was returning a string instead of an int, and since Python supports heterogenous data structures, the human has to remember to keep the key's data type homongenous.
	That and Perl does so much automatic type conversion in such a sensible way, that I stopped worrying about mixing data types, which is making the Python transition a tad more error prone.  Because of Perl, I almost consider automatic type casting to be the next "you don't have to manage your own memory" that people loved about Java.  =O


> But if you are in a use-case where you really don't care and only 
> want to hash strings, you can create a dict subclass easily that
> overrides __setitem__ to always str() the input. Check out the
> UserDict class.

	UserDict looks like it could be useful.  Thanks for the info.


> A similar method lets you make 'case-insensitive' dicts, for example.
>
> Were such a thing to happen automagically, you could get some 
> weird situations, such as "assert (key in dict) == (key in dict.keys())" 
> failing.

	I'm assuming that you would just need to overload the 'in' operator and .keys() method to be case insensitive also.




[1]  No, he didn't.


*****

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 bborcic at gmail.com  Mon Jan 28 11:46:14 2008
From: bborcic at gmail.com (Boris Borcic)
Date: Mon, 28 Jan 2008 17:46:14 +0100
Subject: optional static typing for Python
In-Reply-To: <69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com>
References: 
	<479da584$0$25625$426a74cc@news.free.fr>
	<69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com>
Message-ID: <479e0709_5@news.bluewin.ch>

Wish you'd opted out of typing all that static.

BB

Russ P. wrote:
(...)
> 
> What is that supposed to mean?
> 
> Oh, I almost forgot. I'm supposed to sit here and be polite while
> clueless dolts make wise cracks. Sorry, but I haven't yet mastered
> that level of self-control.
> 
> I would just like to thank you for reminding me about what losers hang
> out perpetually on sites like this one, thinking they are in some kind
> of real "community." Being reminded of that will help prevent me from
> becoming such a loser myself. No, I didn't say that all the "regulars"
> here are losers, but you most certainly are.
> 
> Do you have a job? How about a life? Have you ever been "with" a
> woman? How in the world is it that every time I come to this site, I
> see your sorry ass hanging around yet again? I can't even imagine how
> "pointless" your life must be if you have that much time to spend
> "hanging around" on comp.lang.python -- and being an a--hole to boot.
> 
> Yeah, Lord have mercy -- on losers like you.
> 
> And thanks for reminding me to quit wasting so much time here. I've
> been doing way too much of that lately.


From paul at boddie.org.uk  Fri Jan 25 09:45:45 2008
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 25 Jan 2008 06:45:45 -0800 (PST)
Subject: "just like Java" (was :Re: translating Python to Assembler)
References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com>
	 
	
	<4799de28$0$12358$426a74cc@news.free.fr>
Message-ID: <7f6f3a93-4301-4a75-83d3-13d9a7c57cda@h11g2000prf.googlegroups.com>

On 25 Jan, 14:05, Bruno Desthuilliers  wrote:
> Christian Heimes a ?crit :
>
> > No, that is not correct. Python code is compiled to Python byte code and
> > execute inside a virtual machine just like Java or C#.
>
> I'm surprised you've not been flamed to death by now - last time I
> happened to write a pretty similar thing, I got a couple nut case
> accusing me of being a liar trying to spread FUD about Java vs Python
> respective VMs inner working, and even some usually sensible regulars
> jumping in to label my saying as "misleading"...

Well, it is important to make distinctions when people are wondering,
"If Python is 'so slow' and yet everyone tells me that the way it is
executed is 'just like Java', where does the difference in performance
come from?" Your responses seemed to focus more on waving that issue
away and leaving the whole topic in the realm of mystery. The result:
"Python is just like Java apparently, but it's slower and I don't know
why."

It's true in one sense that the statement "Python modules and scripts
are normally not even compiled" is incorrect, since modules at least
are compiled to another representation. However, if we grant the
author of that statement the benefit of his ambiguity, we can also
grant his statement a degree of tolerance by observing that modules
are not compiled to native code, which is the only experience some
people have with compilation and its results.

As was pointed out in that previous discussion, CPython instructions
are arguably less well-suited than Java instructions for translation
to CPU instructions. This alone should make people wonder about how
close CPython and the more prominent Java virtual machines are, as
well as the considerations which led the Java virtual machine
architecture to be designed in the way that it was.

Paul


From tarun.kap at gmail.com  Wed Jan 16 15:14:36 2008
From: tarun.kap at gmail.com (Tarun Kapoor)
Date: Wed, 16 Jan 2008 12:14:36 -0800 (PST)
Subject: paramiko
References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> 
	
	<8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com>
	
	<8ceaad4c-c725-4093-a204-ab09162d4629@c23g2000hsa.googlegroups.com>
	
	<685fabb3-c9e8-47ac-84f2-405b831bccad@v4g2000hsf.googlegroups.com>
	
Message-ID: <3019696f-cf50-43e2-8534-2ef4ae4de5d9@y5g2000hsf.googlegroups.com>

On Jan 16, 1:56 pm, "Guilherme Polo"  wrote:
> 2008/1/16, Tarun Kapoor :
>
>
>
> > On Jan 16, 12:22 pm, "Guilherme Polo"  wrote:
> > > 2008/1/16, Tarun Kapoor :
>
> > > > On Jan 16, 11:38 am, "Guilherme Polo"  wrote:
> > > > > 2008/1/16, Tarun Kapoor :
>
> > > > > >     # now, connect and use paramiko Transport to negotiate SSH2 across
> > > > > > the connection
> > > > > >     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > > > > >     sock.connect((hostname, port))
>
> > > > > >     t = paramiko.Transport(sock)
> > > > > >     t.start_client()
> > > > > >     key = t.get_remote_server_key()
>
> > > > > >     event = threading.Event()
> > > > > >     t.auth_password(username=username, password=password, event=event)
> > > > > >     event.wait()
>
> > > > > >     if not t.is_authenticated():
> > > > > >         print "not authenticated"
>
> > > > > > output:
> > > > > > not authenticated
>
> > > > > This is a different problem I guess, now you are usin get_remote_server_key.
> > > > > And why are you creating event after calling start_client without
> > > > > specifying it ?
>
> > > > > > On Jan 16, 11:11 am, "Guilherme Polo"  wrote:
> > > > > > > 2008/1/16, Tarun Kapoor :
>
> > > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to
> > > > > > > > the remote server using an SFTP client I have just to make sure that
> > > > > > > > username and password are working.. This is the code.
>
> > > > > > > >     # now, connect and use paramiko Transport to negotiate SSH2 across the
> > > > > > > > connection
>
> > > > > > > >     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>
> > > > > > > >     sock.connect((hostname, port))
>
> > > > > > > >     t = paramiko.Transport(sock)
>
> > > > > > > >     event = threading.Event()
>
> > > > > > > >     t.start_client(event)
>
> > > > > > > >     event.wait(15)
>
> > > > > > > >     if not t.is_active():
>
> > > > > > > >         print 'SSH negotiation failed.'
>
> > > > > > > >         sys.exit(1)
>
> > > > > > > >     else:
>
> > > > > > > >         print "SSH negotiation sucessful"
>
> > > > > > > >     event.clear()
>
> > > > > > > >     t.auth_password(username=username, password=password,event=event)
>
> > > > > > > >     if not t.is_authenticated():
>
> > > > > > > >         print "not authenticated"
>
> > > > > > > > output:
>
> > > > > > > > SSH negotiation successful
>
> > > > > > > > not authenticated
>
> > > > > > > > Tarun
>
> > > > > > > > Waterstone Capital Management
>
> > > > > > > > 2 Carlson Parkway, Suite 260
>
> > > > > > > > Plymouth, MN 55447
>
> > > > > > > > Direct: 952-697-4123
>
> > > > > > > > Cell:    612-205-2587
> > > > > > > >  Disclaimer This e-mail and any attachments is confidential and intended
> > > > > > > > solely for the use of the individual(s) to whom it is addressed. Any views
> > > > > > > > or opinions presented are solely those of the author and do not necessarily
> > > > > > > > represent those of Waterstone Capital Management, L.P and affiliates. If you
> > > > > > > > are not the intended recipient, be advised that you have received this
> > > > > > > > e-mail in error and that any use, dissemination, printing, forwarding or
> > > > > > > > copying of this email is strictly prohibited. Please contact the sender if
> > > > > > > > you have received this e-mail in error. You should also be aware that
> > > > > > > > e-mails are susceptible to interference and you should not assume that the
> > > > > > > > contents of this e-mail originated from the sender above or that they have
> > > > > > > > been accurately reproduced in their original form. Waterstone Capital
> > > > > > > > Management, L.P. and affiliates accepts no responsibility for information,
> > > > > > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt,
> > > > > > > > please verify the authenticity with the sender.
> > > > > > > > --
> > > > > > > >http://mail.python.org/mailman/listinfo/python-list
>
> > > > > > > You are missing an event.wait() after t.auth_password.
> > > > > > > Also, why are you passing this magic value "15" to event.wait() ? That
> > > > > > > parameter is passed to class _Verbose to indicate if debug messages
> > > > > > > should be displayed or not, so typical values would be 0/1 or
> > > > > > > False/True.
>
> > > > > > > --
> > > > > > > -- Guilherme H. Polo Goncalves
>
> > > > > > --
> > > > > >http://mail.python.org/mailman/listinfo/python-list
>
> > > > > --
> > > > > -- Guilherme H. Polo Goncalves
>
> > > > ok here is the problem... I don't know what is the correct way... The
> > > > only demos i have from the paramiko library use a hostkeyfile. since i
> > > > don't have that i thought i would use the get_remote_key to get the
> > > > key and then connect it using the code in the demo.. But clearly
> > > > nothing is working...I should not HAVE to use the key since i should
> > > > be able to authenticate using the password...
>
> > > > Can you please suggest the right way to go ?
>
> > > You don't need to use key to authenticate using username and password,
> > > indeed. And you don't. Your first email was almost correct, you just
> > > needed to add event.wait() after t.auth_password. It worked here after
> > > doing that change. You can check out my version:
>
> > > import sys
> > > import socket
> > > import paramiko
> > > import threading
>
> > > if len(sys.argv) != 4:
> > >     print "%s hostname user password" % sys.argv[0]
> > >     sys.exit(1)
>
> > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > > sock.connect((sys.argv[1], 22))
>
> > > t = paramiko.Transport(sock)
> > > event = threading.Event()
> > > t.start_client(event)
>
> > > event.wait()
>
> > > if not t.is_active():
> > >     print 'SSH negotiation failed.'
> > >     sys.exit(1)
> > > else:
> > >     print "SSH negotiation sucessful"
>
> > > event.clear()
> > > t.auth_password(username=sys.argv[2], password=sys.argv[3], event=event)
> > > event.wait()
> > > if not t.is_authenticated():
> > >     print "Authentication failed."
> > > else:
> > >     print "Authenticated!"
>
> > > t.close()
>
> > > > Thanks for your time !
> > > > --
> > > >http://mail.python.org/mailman/listinfo/python-list
>
> > > --
> > > -- Guilherme H. Polo Goncalves
>
> > ok i tried the exact same code and here is the output
> > SSH negotiation sucessful
> > Authentication failed.
>
> > I am positive that the username and paddword are correct. !
>
> I believe paramiko supports only ssh2, so be sure to check if your
> server is not running ssh1.
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> -- Guilherme H. Polo Goncalves


The server is running SSH2.
Can you think of any other ideas to troubleshoot ?



From odysseus1479-at at yahoo-dot.ca  Sun Jan 13 04:40:55 2008
From: odysseus1479-at at yahoo-dot.ca (Odysseus)
Date: Sun, 13 Jan 2008 09:40:55 GMT
Subject: Elementary string-formatting
References: 
	
Message-ID: 

In article 
,
 John Machin  wrote:


> 
> You obviously haven't tried float(n / m), or you wouldn't be asking.

True, it was a very silly idea.

> Most legible and slowest first:
> 1. float(n) / float(m)
> 2. n / float(m)
> 3. 1.0 * n / m

> Recommendation: go with (2) until you find you've got a program with
> a real speed problem (and then it probably won't be caused by this
> choice).

I had actually used n / float(m) at one point; somehow the above struck 
me as an improvement while I was writing the message. Thanks for the 
reality check.

-- 
Odysseus


From fredrik at pythonware.com  Sun Jan  6 03:03:59 2008
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Sun, 06 Jan 2008 09:03:59 +0100
Subject: list property fires get on append
In-Reply-To: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com>
References: <62b85f94-c664-43ba-a35d-1470ee341206@v4g2000hsf.googlegroups.com>
Message-ID: 

ian at neustyle.com wrote:

> I've created a class that has a property which points at a private
> list.  When I try to use the append() function on this list property,
> the fget method is fired rather than the fset method.  If I directly
> set my property to a literal list, the set method fires.

> # this fires a get for some reason
> hierarchy.children.append( Hierarchy.Hierarchy())

that's the expected behaviour: you're *fetching* the "children" 
attribute in order to modify it, you're not replacing it.

reading up on Python's object model might be helpful.





From ashok.raavi at gmail.com  Tue Jan 29 08:33:25 2008
From: ashok.raavi at gmail.com (ashok raavi)
Date: Tue, 29 Jan 2008 19:03:25 +0530
Subject: [HELP] SMTPlib not sending my mail
In-Reply-To: <1201596148.7850.2.camel@lars-laptop.ez.no>
References: 
	
	<1201596148.7850.2.camel@lars-laptop.ez.no>
Message-ID: <2aa122da0801290533x7e30467csfbc60fe976d3855e@mail.gmail.com>

i  checked it after your mail..

it is giving the following warning: no entropy for TLS key generation:
disabling TLS support

which was addressed here "
http://www.howtoforge.com/forums/showthread.php?t=781"

after adding the line "tlsmgr unix - - n 1000? 1 tlsmgr"  to
/etc/postfix/master.cf it started working.

Thank you.


On 1/29/08, Lars Johansen  wrote:
>
> have you checked your mail server logs ?
>
> tir, 29.01.2008 kl. 00.24 -0800, skrev ashok.raavi:
> > Hi,
> >
> > I am also facing the same problem, smtplib used to send mail a while
> > back but it stopped sending mails.
> >
> > when i run this in interpreter
> > >>> import smtplib
> > >>> s = smtplib.SMTP("localhost")
> > >>> s.sendmail(from, to, "message")
> > {}
> > >>>
> >
> > though it is not giving any error, it is not sending mail.
> >
> > Any help is appreciated.
> >
> > ornto wrote:
> > > Hi, I'm trying to create an application which checks a
> > > dynamic web site and on certain events sends an email to me.
> > > My problem though is with the email task. By now I made this
> > >   simple test code:
> > >
> > > #prova invio email
> > > smtpserver = smtplib.SMTP(mailserver)
> > > messaggio= "Messaggio di prova"
> > > print mail
> > > print messaggio
> > > smtpresult=smtpserver.sendmail("Watcher",mail,messaggio)
> > > if smtpresult:
> > >      print smtpresult
> > > smtpserver.quit()
> > >
> > > "mailserver" and "mail" values are loaded from a ini file
> > > and they're correct.
> > > The call to smtpserver gives back no errors (smtpresult
> > > remains empty).
> > > The running enviroment gives no error.
> > > So, it looks like that the program works alloright, sending
> > > the mail- BUT, I receive no mail! I've tried to change the
> > > smtp server with another one which still works with my isp,
> > > with no luck. If I try a smtp which doesn't give me access,
> > > I correctly receive an error from the program.
> > > What might be the problem?
>
>


-- 
ashok raavi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at REMOVE-THIS-cybersource.com.au  Mon Jan 14 06:09:26 2008
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: Mon, 14 Jan 2008 11:09:26 -0000
Subject: encrypting python modules
References: <47873a78$0$85785$e4fe514c@news.xs4all.nl>
	<13og1dbe4qcfs2b@corp.supernews.com>
	<478b220e$0$85788$e4fe514c@news.xs4all.nl>
Message-ID: <13omgn69naf1se8@corp.supernews.com>

On Mon, 14 Jan 2008 09:49:49 +0100, Paul Sijben wrote:

>> How often do these things *actually* happen?
>> 
>> Of those that actually do it, how many are clueless enough that when
>> they run into problems they blame you for it? (And remember that you
>> won't even find out about the non-clueless ones.)
>> 
>> 
> This is a rethorical question, right?

No, it's a serious question. You distribute Python code, and you're 
worried that your users will modify the source code and then neglect to 
mention it when they report bugs which they introduced.

Before you build an elephant-proof fence around your house, it is quite 
reasonable to ask whether or not there are actually elephants in your 
neighbourhood.



-- 
Steven


From d.l.goldsmith at gmail.com  Tue Jan  8 13:25:35 2008
From: d.l.goldsmith at gmail.com (dgoldsmith_89)
Date: Tue, 8 Jan 2008 10:25:35 -0800 (PST)
Subject: Open source English dictionary to use programmatically w/ python
References: 
	 
	 
	
Message-ID: <0d2c14d8-b7f8-40be-b13c-05b9dadaaa65@i7g2000prf.googlegroups.com>

On Jan 7, 3:50 pm, "mensana... at aol.com"  wrote:
> On Jan 7, 5:10 pm, dgoldsmith_89  wrote:
>
>
>
> > On Jan 7, 2:54 pm, "mensana... at aol.com"  wrote:
>
> > > On Jan 7, 4:37 pm, dgoldsmith_89  wrote:
>
> > > > Can anyone point me to a downloadable open source English dictionary
> > > > suitable for programmatic use with python: I'm programming a puzzle
> > > > generator, and I need to be able to generate more or less complete
> > > > lists of English words, alphabetized.  Thanks!  DG
>
> > >www.puzzlers.orghasnumerousword lists & dictionarys in text
> > > format that can be downloaded. I recommend you insert them into
> > > some form of database. I have most of them in an Access db and
> > > it's 95 MB. That's a worse case as I also have some value-added
> > > stuff, the OSPD alone would be a lot smaller.
>
> > > 
>
> > Sorry for my ignorance: I can query an Access DB w/ standard SQL
> > queries (and this is how I would access it w/ Python)?
>
> Yes, if you have the appropriate way to link to the DB.
> I use Windows and ODBC from Win32. I don't know what you
> would use on a Mac.
>
> As Paul McGuire said, you could easily do this with SqlLite3.
> Personnaly, I always use Access since my job requires it
> and I find it much more convenient. I often use Crosstab
> tables which I think SqlLite3 doesn't support. Typically,
> I'll write complex queries in Access and simple select SQL
> statements in Python to grab them.
>
> Here's my anagram locator. (the [signature] is an example
> of the value-added I mentioned).
>
> ##  I took a somewhat different approach. Instead of in a file,
> ##  I've got my word list (562456 words) in an MS-Access database.
> ##  And instead of calculating the signature on the fly, I did it
> ##  once and added the signature as a second field:
> ##
> ##  TABLE CONS_alpha_only_signature_unique
> ##  --------------------------------------
> ##  CONS       text      75
> ##  signature  text      26
> ##
> ##  The signature is a 26 character string where each character is
> ##  the count of occurences of the matching letter. Luckily, in
> ##  only a single case was there more than 9 occurences of any
> ##  given letter, which turned not to be a word but a series of
> ##  words concatenated so I just deleted it from the database
> ##  (lots of crap in the original word list I used).
> ##
> ##  Example:
> ##
> ##  CONS     signature
> ##  aah      20000001000000000000000000 # 'a' occurs twice & 'h' once
> ##  aahed    20011001000000000000000000
> ##  aahing   20000011100001000000000000
> ##  aahs     20000001000000000010000000
> ##  aaii     20000000200000000000000000
> ##  aaker    20001000001000000100000000
> ##  aal      20000000000100000000000000
> ##  aalborg  21000010000100100100000000
> ##  aalesund
> 20011000000101000010100000
> ##
> ##  Any words with identical signatures must be anagrams.
> ##
> ##  Once this was been set up, I wrote a whole bunch of queries
> ##  to use this table. I use the normal Access drag and drop
> ##  design, but the SQL can be extracted from each, so I can
> ##  simply open the query from Python or I can grab the SQL
> ##  and build it inside the program. The example
> ##
> ##    signatures_anagrams_select_signature
> ##
> ##  is hard coded for criteria 9 & 10 and should be cast inside
> ##  Python so the criteria can be changed dynamically.
> ##
> ##
> ##  QUERY signatures_anagrams_longest
> ##  ---------------------------------
> ##  SELECT   Len([CONS]) AS Expr1,
> ##           Count(Cons_alpha_only_signature_unique.CONS) AS
> CountOfCONS,
> ##           Cons_alpha_only_signature_unique.signature
> ##  FROM     Cons_alpha_only_signature_unique
> ##  GROUP BY Len([CONS]),
> ##           Cons_alpha_only_signature_unique.signature
> ##  HAVING   (((Count(Cons_alpha_only_signature_unique.CONS))>1))
> ##  ORDER BY Len([CONS]) DESC ,
> ##           Count(Cons_alpha_only_signature_unique.CONS) DESC;
> ##
> ##  This is why I don't use SQLite3, must have crosstab queries.
> ##
> ##  QUERY signatures_anagram_summary
> ##  --------------------------------
> ##  TRANSFORM Count(signatures_anagrams_longest.signature) AS
> CountOfsignature
> ##  SELECT    signatures_anagrams_longest.Expr1 AS [length of word]
> ##  FROM      signatures_anagrams_longest
> ##  GROUP BY  signatures_anagrams_longest.Expr1
> ##  PIVOT     signatures_anagrams_longest.CountOfCONS;
> ##
> ##
> ##  QUERY signatures_anagrams_select_signature
> ##  ------------------------------------------
> ##  SELECT   Len([CONS]) AS Expr1,
> ##           Count(Cons_alpha_only_signature_unique.CONS) AS
> CountOfCONS,
> ##           Cons_alpha_only_signature_unique.signature
> ##  FROM     Cons_alpha_only_signature_unique
> ##  GROUP BY Len([CONS]),
> ##           Cons_alpha_only_signature_unique.signature
> ##  HAVING   (((Len([CONS]))=9) AND
> ##            ((Count(Cons_alpha_only_signature_unique.CONS))=10))
> ##  ORDER BY Len([CONS]) DESC ,
> ##           Count(Cons_alpha_only_signature_unique.CONS) DESC;
> ##
> ##  QUERY signatures_lookup_by_anagram_select_signature
> ##  ---------------------------------------------------
> ##  SELECT     signatures_anagrams_select_signature.Expr1,
> ##             signatures_anagrams_select_signature.CountOfCONS,
> ##             Cons_alpha_only_signature_unique.CONS,
> ##             Cons_alpha_only_signature_unique.signature
> ##  FROM       signatures_anagrams_select_signature
> ##  INNER JOIN Cons_alpha_only_signature_unique
> ##  ON         signatures_anagrams_select_signature.signature
> ##             = Cons_alpha_only_signature_unique.signature;
> ##
> ##
> ##  Now it's a simple matter to use the ODBC from Win32 to extract
> ##  the query output into Python.
>
> import dbi
> import odbc
>
> con = odbc.odbc("words")
> cursor = con.cursor()
>
> ##  This first section grabs the anagram summary. Note that
> ##  queries act just like tables (as long as they don't have
> ##  internal dependencies. I read somewhere you can get the
> ##  field names, but here I put them in by hand.
>
> ##cursor.execute("SELECT * FROM signature_anagram_summary")
> ##
> ##results = cursor.fetchall()
> ##
> ##for i in results:
> ##  for j in i:
> ##    print '%4s' % (str(j)),
> ##  print
>
> ##  (if this wraps, each line is 116 characters)
> ##        2    3    4    5    6    7    8    9   10   11   12   13
> 14   15   16   17   18   23
> ##   2  259 None None None None None None None None None None None
> None None None None None None
> ##   3  487  348  218  150  102 None None None None None None None
> None None None None None None
> ##   4 1343  718  398  236  142  101   51   26   25    9    8    3
> 2 None None None None None
> ##   5 3182 1424  777  419  274  163  106   83   53   23   20   10
> 6    4    5    1    3    1
> ##   6 5887 2314 1051  545  302  170  114   54   43   21   15    6
> 5    4    4    2 None None
> ##   7 7321 2251  886  390  151   76   49   37   14    7    5    1
> 1    1 None None None None
> ##   8 6993 1505  452  166   47   23    8    6    4    2    2 None
> None None None None None None
> ##   9 5127  830  197   47   17    6 None None    1 None None None
> None None None None None None
> ##  10 2975  328   66    8    2 None None None None None None None
> None None None None None None
> ##  11 1579  100    5    4    2 None None None None None None None
> None None None None None None
> ##  12  781   39    2    1 None None None None None None None None
> None None None None None None
> ##  13  326   11    2 None None None None None None None None None
> None None None None None None
> ##  14  166    2 None None None None None None None None None None
> None None None None None None
> ##  15   91 None    1 None None None None None None None None None
> None None None None None None
> ##  16   60 None None None None None None None None None None None
> None None None None None None
> ##  17   35 None None None None None None None None None None None
> None None None None None None
> ##  18   24 None None None None None None None None None None None
> None None None None None None
> ##  19   11 None None None None None None None None None None None
> None None None None None None
> ##  20    6 None None None None None None None None None None None
> None None None None None None
> ##  21    6 None None None None None None None None None None None
> None None None None None None
> ##  22    4 None None None None None None None None None None None
> None None None None None None
>
> ##  From the query we have the word size as row header and size of
> ##  anagram set as column header. The data value is the count of
> ##  how many different anagram sets match the row/column header.
> ##
> ##  For example, there are 7321 different 7-letter signatures that
> ##  have 2 anagram sets. There is 1 5-letter signature having a
> ##  23 member anagram set.
> ##
> ##  We can then pick any of these, say the single 10 member anagram
> ##  set of 9-letter words, and query out out the anagrams:
>
> cursor.execute("SELECT * FROM
> signatures_lookup_by_anagram_select_signature")
> results = cursor.fetchall()
> for i in results:
>   for j in i:
>     print j,
>   print
>
> ##  9 10 anoretics 10101000100001100111000000
> ##  9 10 atroscine 10101000100001100111000000
> ##  9 10 certosina 10101000100001100111000000
> ##  9 10 creations 10101000100001100111000000
> ##  9 10 narcotise 10101000100001100111000000
> ##  9 10 ostracine 10101000100001100111000000
> ##  9 10 reactions 10101000100001100111000000
> ##  9 10 secration 10101000100001100111000000
> ##  9 10 tinoceras 10101000100001100111000000
> ##  9 10 tricosane 10101000100001100111000000
>
> ## Nifty, eh?
>
>
>
> > DG

Yes, nifty.  Thanks for all the help, all!

DG


From inq1ltd at inqvista.com  Wed Jan  9 12:30:00 2008
From: inq1ltd at inqvista.com (jim-on-linux)
Date: Wed, 09 Jan 2008 12:30:00 -0500
Subject: user friendly datetime features
In-Reply-To: 
References: 
Message-ID: <200801091230.00894.inq1ltd@inqvista.com>



Why not build your own module?  You can use it where and when you need 
it.

jim-on-linux
http://www.inqvista.com



On Tuesday 08 January 2008 20:19, Daniel Fetchinson wrote:
> Many times a more user friendly date format is convenient than the
> pure date and time.
> For example for a date that is yesterday I would like to see
> "yesterday" instead of the date itself. And for a date that was 2
> days ago I would like to see "2 days ago" but for something that
> was 4 days ago I would like to see the actual date. This is often
> seen in web applications, I'm sure you all know what I'm talking
> about.
>
> I'm guessing this feature is needed so often in so many projects
> that it has been implemented already by several people. Does anyone
> know of such a stand alone module?


From mwm-keyword-python.b4bdba at mired.org  Sat Jan 12 15:25:53 2008
From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer)
Date: Sat, 12 Jan 2008 15:25:53 -0500
Subject: where do my python files go in linux?
In-Reply-To: <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com>
References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com>
	<20080112113759.GJ75977@nexus.in-nomine.org>
	<11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com>
Message-ID: <20080112152553.638cfa3d@bhuda.mired.org>

On Sat, 12 Jan 2008 16:13:08 +0100 "Jorgen Bodde"  wrote:
> > Normally you'd split up the bulk of the code into a module which gets
> > installed into site-packages and a piece of stand-alone front-end code which
> > imports the module and executes whatever you need to do and gets installed
> > into a typical PATH directory.
> I would agree but it is not a site package I am trying to distribute,
> but a wxPython application. I would not think my app belongs in the
> python site packages dir.

I suspect that's because your app is "simple", in that it only has one
command. Many apps have multiple commands that share the same set of
libraries. So putting a package for that app in site-packages makes a
lot of sense. If your app-specific library is properly designed and
documented, users may be able to build further commands for the system
as well.

On the issue of .pyc files - don't distribute them. Instead, arrange
for the install package to run the compileall.py script (in the
standard library) on your libraries. .pyc files are *not* guaranteed
to be platform independent (even though the latest rpm tools seem to
claim otherwise), so if you build them for your platform, they may
well be unusable after being installed.

     		http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.


From bignose+hates-spam at benfinney.id.au  Mon Jan 28 03:21:48 2008
From: bignose+hates-spam at benfinney.id.au (Ben Finney)
Date: Mon, 28 Jan 2008 19:21:48 +1100
Subject: py3k feature proposal: field auto-assignment in constructors
References: 
	<0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com>
	<87d4rm93l1.fsf@benfinney.id.au>
	<479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net>
	
	<8763xe8vzd.fsf@benfinney.id.au>
	
Message-ID: <87y7aa742r.fsf@benfinney.id.au>

"Russ P."  writes:

> OK, then how about a special function that could be called from
> inside the constructor (or anywhere else for that matter) to
> initialize a list of data members. For example,
> 
> self.__set__(host, port, protocol, bufsize,
>     timeout)
> 
> This would be equivalent to
> 
> self.host = host
> self.port = port
> # etc.
> 
> I'm not sure if that is technically feasible, but it would cut down
> on repetition of names.

It's much more attractive, because it doesn't change the function
signature. In fact, here's a variation that doesn't even need a
language change::

    >>> class Foo(object):
    ...     def __init__(self, spam, eggs, beans):
    ...         self.__dict__.update(dict(
    ...             (name, value) for (name, value) in vars().items()
    ...             if name in ['spam', 'beans']))
    ... 
    >>> foo = Foo("some spam", "more eggs", "other beans")
    >>> foo.spam
    'some spam'
    >>> foo.eggs
    Traceback (most recent call last):
      File "", line 1, in ?
    AttributeError: 'Foo' object has no attribute 'eggs'
    >>> foo.beans
    'other beans'

-- 
 \       "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 bret.wortman at gmail.com  Tue Jan 22 14:52:30 2008
From: bret.wortman at gmail.com (Bret)
Date: Tue, 22 Jan 2008 11:52:30 -0800 (PST)
Subject: A global or module-level variable?
Message-ID: <7637fd0b-961e-4730-abd8-96e85c907082@i72g2000hsd.googlegroups.com>

This has to be easier than I'm making it....

I've got a module, remote.py, which contains a number of classes, all
of whom open a port for communication.  I'd like to have a way to
coordinate these port numbers akin to this:

So I have this in the __init__.py file for a package called cstore:

nextport=42000

def getNextPort():
    nextport += 1
    return nextport

:
Then, in the class where I wish to use this (in cstore.remote.py):
:


class Spam():

    def __init__(self, **kwargs):
        self._port = cstore.getNextPort()

I can't seem to make this work, though.  As given here, I get an
"UnboundLocalError:local variable 'nextport' referenced before
assignment".  When I try prefixing the names inside __init__.py with
"cstore.", I get an error that the global name "cstore" is not
defined.

I've been looking at this long enough that my eyes are blurring.  Any
ideas?

BTW, the driving force here is that I'm going to need to wrap this in
some thread synchronization.  For now, though, I'm just trying to get
the basics working.

Thanks!


Bret


From http  Sun Jan 27 20:56:46 2008
From: http (Paul Rubin)
Date: 27 Jan 2008 17:56:46 -0800
Subject: optional static typing for Python
References: 
	<0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com>
Message-ID: <7xbq76pva9.fsf@ruckus.brouhaha.com>

Paddy  writes:
> I would rather advocate such random test generation methods as being
> more appropriate for testing software in safety critical systems when
> the programming language is dynamic.

That method totally failed to find the Pentium FDIV bug, and they use
static proof checkers like ACL2 now.


From george.sakkis at gmail.com  Thu Jan 17 01:25:38 2008
From: george.sakkis at gmail.com (George Sakkis)
Date: Wed, 16 Jan 2008 22:25:38 -0800 (PST)
Subject: assigning values in python and perl
References:  
	<2d37f441-c01f-439b-9897-35b7e4dfa77b@h11g2000prf.googlegroups.com> 
	
Message-ID: <34e2dc93-9819-479f-a8d5-79d11350f0b3@s8g2000prg.googlegroups.com>

On Jan 17, 1:03 am, Christian Heimes  wrote:

> George Sakkis wrote:
> > Python's parameter passing is like passing a pointer in C/C++.
>
> [snip]
>
> It's not (I repeat NOT) like passing a pointer in C. Please readhttp://effbot.org/zone/call-by-object.htm
>
> Christian

Posting a counter-example where the difference is clearly shown would
be more vastly useful than referring to a list of long obscure usenet
posts with practically no examples. C/C++ are not even mentioned in
that page. I am not claiming you are wrong, I just don't find
particularly this page particularly enlightening.

George


From David.Reksten at sweco.no  Thu Jan 10 07:39:52 2008
From: David.Reksten at sweco.no (David.Reksten at sweco.no)
Date: Thu, 10 Jan 2008 13:39:52 +0100
Subject: SV: Conventions for dummy name
In-Reply-To: <87odbt27ph.fsf@physik.rwth-aachen.de>
References: <5ul1tuF1i0qr1U1@mid.uni-berlin.de><873at6k2qt.fsf_-_@benfinney.id.au><87sl1613c8.fsf@physik.rwth-aachen.de>
	<87odbt27ph.fsf@physik.rwth-aachen.de>
Message-ID: <6A539E6F80E48B40A81F5169256139D301D982B8@srvmail02.nettverk.int>

Torsten Bronger writes:
>David.Reksten at sweco.no writes:
>
>> Torsten Bronger wrote:
>>
>>> [...]
>>>
>>> Right, that's because I've used "__" where not all returning
>>> values are interesing to me such as
>>>
>>> a, b, __ = function_that_returns_three_values(x, y)
>>
>> Variable name "dummy" serves the same purpose, such as:
>>
>>     a, b, dummy = function_that_returns_three_values(x, y)
>
>Granted, but my rationale is that "__" is less visible in the source
>code, so there is more emphasis on the actually interesting
>variables.

I guess it's a matter of preference. Personally, I find "dummy" to be more
explicit, and hence more readable for those that that will read my code
later. YMMV.

Regards,
.david


From jpeng at block.duxieweb.com  Mon Jan 21 04:32:42 2008
From: jpeng at block.duxieweb.com (J. Peng)
Date: Mon, 21 Jan 2008 17:32:42 +0800
Subject: Sorting a list depending of the indexes of another sorted list
In-Reply-To: 
References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com>	<479451D9.3060207@block.duxieweb.com>	
	
Message-ID: <479466BA.7080206@block.duxieweb.com>

Steven D'Aprano ??:
> On Mon, 21 Jan 2008 16:23:50 +0800, J. Peng wrote:
> 
>> J. Peng ??:
>>
>>>    k = (i.split())[3]
>>>    y = (i.split())[1]
>> btw, why can't I write the above two into one statement?
>>
>> (k,y) = (i.split())[3,1]
> 
> I don't know. What's "i"?
> 
> I'm guessing "i" is a string (and what a horrible choice of a name for a 
> string!) So i.split() will return a list. List indexing with multiple 
> arguments isn't defined, which is why you can't write 
> 
> k, y = (i.split())[3,1]
> 

Thanks.
Then one have to split the list twice.Given the list is large,it's maybe 
not good for performance.Is it a more effective split way?


From mnordhoff at mattnordhoff.com  Sun Jan 13 05:26:49 2008
From: mnordhoff at mattnordhoff.com (Matt Nordhoff)
Date: Sun, 13 Jan 2008 05:26:49 -0500
Subject: Elementary string-formatting
In-Reply-To: 
References: 
Message-ID: <4789E769.4020404@mattnordhoff.com>

Odysseus wrote:
> Hello, group: I've just begun some introductory tutorials in Python. 
> Taking off from the "word play" exercise at
> 
> 
> 
> I've written a mini-program to tabulate the number of characters in each 
> word in a file. Once the data have been collected in a list, the output 
> is produced by a while loop that steps through it by incrementing an 
> index "i", saying
> 
> print '%2u %6u %4.2f' % \
> (i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0])

This isn't very important, but instead of keeping track of the index
yourself, you can use enumerate():

>>> mylist = ['a', 'b', 'c']
>>> for i, item in enumerate(mylist):
...     print i, item
...
0 a
1 b
2 c
>>>

Err, it doesn't look like you can make it start at 1 though.


-- 


From fredrik at pythonware.com  Sun Jan 13 07:31:05 2008
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Sun, 13 Jan 2008 13:31:05 +0100
Subject: __init__  explanation please
In-Reply-To: <20080113104641.GN75977@nexus.in-nomine.org>
References: <47895d25$0$30708$4c368faf@roadrunner.com>
	<20080113104641.GN75977@nexus.in-nomine.org>
Message-ID: 

Jeroen Ruigrok van der Werven wrote:

> I personally tend to see __init__ or __new__ as equivalent to what other
> languages call a constructor.
> 
> (And I am sure some people might disagree with that. ;))

given that they do different things, I'm not sure it's that helpful to 
describe them *both* as constructors.





From george.sakkis at gmail.com  Mon Jan 14 15:17:40 2008
From: george.sakkis at gmail.com (George Sakkis)
Date: Mon, 14 Jan 2008 12:17:40 -0800 (PST)
Subject: Dynamical scoping
Message-ID: <1a3243ef-13f6-40d6-97eb-198b8742ac3d@d4g2000prg.googlegroups.com>

What's the best way to simulate dynamically scoped variables ala
Lisp ? The use case is an open-ended set of objects that need to
access the same piece of information (e.g. a  dict, a ConfigParser
object, a logger etc.). I know that the "proper" OO and functional way
is to pass the information explicitly but that's less maintenable in
the long run. Also this is in a web environment so the information
can't be really global (though within-thread global should be fine).
Is there some standard pattern for this scenario ?

George


From levilista at gmail.com  Thu Jan 10 13:36:48 2008
From: levilista at gmail.com (zslevi@gmail.com)
Date: Thu, 10 Jan 2008 10:36:48 -0800 (PST)
Subject: What is "lambda x=x : ... " ?
References: <3435be4a-afad-4f0c-9474-f1893784e7a7@k39g2000hsf.googlegroups.com>
Message-ID: <9d596a40-6cf3-4139-b1f9-5e5d766c4462@s12g2000prg.googlegroups.com>

I've figured it out, it is default argument.
print  y()
gives 13 as result.

It's a bit evil though.
I hope this post will be useful some newbie like i'm now someday :)

On Jan 10, 7:25 pm, "zsl... at gmail.com"  wrote:
> I'm reading this page:http://www.ps.uni-sb.de/~duchier/python/continuations.html
> and I've found a strange usage of lambda:
>
> ####################
> Now, CPS would transform the baz function above into:
>
> def baz(x,y,c):
>         mul(2,x,lambda v,y=y,c=c: add(v,y,c))
>
> ###################
>
> What does "y=y" and "c=c" mean in the lambda function?
> I thought it bounds the outer variables, so I experimented a little
> bit:
>
> #################
> x = 3
> y = lambda x=x : x+10
>
> print y(2)
> ##################
>
> It prints 12, so it doesn't bind the variable in the outer scope.



From qgallet at gmail.com  Thu Jan 17 09:05:56 2008
From: qgallet at gmail.com (Quentin Gallet-Gilles)
Date: Thu, 17 Jan 2008 15:05:56 +0100
Subject: Loop in a loop?
In-Reply-To: 
References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com>
	
	
Message-ID: <8b943f2b0801170605x548d4678r3cf9e6129c1188e5@mail.gmail.com>

On Jan 17, 2008 2:38 PM, Sacred Heart  wrote:

> On Jan 17, 1:35 pm, cokofree... at gmail.com wrote:
> > for i in zip(array1, array2):
> >     print i
> >
> > Although I take it you meant four d, the issue with this method is
> > that once you hit the end of one array the rest of the other one is
> > ignored.
>
> Yes, small typo there.
>
> Okey, so if my array1 is has 4 elements, and array2 has 6, it won't
> loop trough the last 2 in array2? How do I make it do that?
>
>
In that case, you can use map(). It pads the shortest list with None.

>>> array1 = ['one','two','three','four', 'five', 'six']
>>> array2 = ['a','b','c','d']
>>> map(None, array1, array2)
[('one', 'a'), ('two', 'b'), ('three', 'c'), ('four', 'd'), ('five', None),
('six', None)]

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

From deets at nospam.web.de  Thu Jan 24 18:48:53 2008
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 25 Jan 2008 00:48:53 +0100
Subject: global/local variables
In-Reply-To: 
References: 
Message-ID: <5vsmf9F1nnebqU1@mid.uni-berlin.de>

Tim Rau schrieb:
> What makes python decide whether a particular variable is global or
> local? I've got a list and a integer, both defined at top level, no
> indentation, right next to each other:
> 
> allThings = []
> nextID = 0
> 
> and yet, in the middle of a function, python sees one and doesn't see
> the other:
> 
> class ship(thing):
> ###snip###
>     def step(self):
> ###snip###
>         if keys[K_up]
>             for n in range(0,2):  #sparks/newton second is
> proportional to framerate
>                 divergence = 5.0
>                 p = self.body.getRelPointPos((-0.15,0,0))
>                 v = self.body.vectorToWorld((-100+ random.uniform(-
> divergence,divergence) ,random.uniform(-divergence,divergence),0))
>                 allThings.append(particle(p,v))
>                 allThings[len(allThings)-1].id = nextID
>                 nextID += 1
> 
> 
> I don't think it's important, but the function is defined before the
> two globals. What gives?

The difference is that you assign to nextID in your function. Statements 
of the form


foo = expression

will make foo a function-local variable.

If you want it to be a module-global, you need to do

global foo

foo = expression

If you do this:


bar = 10

def f():
    print bar

you don't assign to a variable, but only read. So if it's not found 
locally, it will be looked up globally.

Diez


From boblatest at yahoo.com  Tue Jan 22 04:12:19 2008
From: boblatest at yahoo.com (Robert Latest)
Date: 22 Jan 2008 09:12:19 GMT
Subject: Question on sort() key function
References: <5vlopgF1mv4ekU1@mid.dfncis.de>
	<7xve5mfdmr.fsf@ruckus.brouhaha.com>
Message-ID: <5vlqbjF1kl9cjU1@mid.dfncis.de>

Paul Rubin wrote:
> The attribute is on instances of File, not on the class itself.  See
> if this works:
>
>    flist.sort(key=lambda f: f.mod_date.toordinal)

It doesn't throw an error any more, but neither does it sort the list. This, 
however, works:

----------------------
def by_date(f1, f2):
	return f1.mod_date.toordinal() - f2.mod_date.toordinal()

flist.sort(by_date)
----------------------

So I'm sticking with it, although I sort of liked the key approach.

robert


From k.shaposhnikov at gmail.com  Tue Jan 22 09:10:40 2008
From: k.shaposhnikov at gmail.com (Konstantin Shaposhnikov)
Date: Tue, 22 Jan 2008 06:10:40 -0800 (PST)
Subject: stdin, stdout, redmon
References: <4794a5e3$0$9014$426a74cc@news.free.fr>
	 
	<4794ab22$0$19179$426a74cc@news.free.fr>
	 
	<4795ba80$0$17176$426a74cc@news.free.fr>
	
	
	<372ff091-2739-4178-bc36-4f8aaffe2972@e23g2000prf.googlegroups.com>
Message-ID: 

Sorry, I meant:

Alternatively you can use following command

  cat file | python script.py

instead of

  cat file | script.py




On Jan 22, 1:54 pm, Konstantin Shaposhnikov 
wrote:
> Hi,
>
> This is Windows bug that is described here:http://support.microsoft.com/default.aspx?kbid=321788
>
> This article also contains solution: you need to add registry value:
>
> HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies
> \Explorer
> InheritConsoleHandles = 1 (REG_DWORD type)
>
> Do not forget to launch new console (cmd.exe) after editing registry.
>
> Alternatively you can use following command
>
>   cat file | python script.py
>
> instead of
>
>   cat file | python script.py
>
> Regards,
> Konstantin
>
> On Jan 22, 1:02 pm, Rolf van de Krol  wrote:
>
> > Well, that's at least weird. I did test my code with Python 2.5 on Win
> > XP, using the command prompt. But testing it with IDLE gives exactly the
> > same error Bernard has. So apparently STDIN can't be accessed with IDLE.
>
> > Rolf
>
> > John Machin wrote:
>
> > > Excuse me, gentlemen, may I be your referee *before* you resort to
> > > pistols at dawn?
>
> > > ===== IDLE =====
> > > IDLE 1.2.1
>
> > >>>> import sys
> > >>>> sys.stdin.readlines
>
> > > Traceback (most recent call last):
> > >   File "", line 1, in 
> > >     sys.stdin.readlines
> > > AttributeError: readlines
>
> > > ===== Command Prompt =====
> > > C:\junk>python
> > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
> > > (Intel)] on win32
> > > Type "help", "copyright", "credits" or "license" for more information.
>
> > >>>> import sys
> > >>>> sys.stdin.readlines
>
> > > 
>
> > > HTH,
> > > John



From kyosohma at gmail.com  Mon Jan  7 14:13:29 2008
From: kyosohma at gmail.com (kyosohma at gmail.com)
Date: Mon, 7 Jan 2008 11:13:29 -0800 (PST)
Subject: Does Python cache the startup module?
References: 
Message-ID: 

On Jan 7, 12:30 pm, Baz Walter  wrote:
> Hello
>
> I remember reading somewhere (probably this list) that python may cache the
> module that starts a program (e.g. 'main.py'). I'm asking because I have found
> that this can sometimes cause problems when making small edits to the module.
> For instance, in my current module I changed the name of the main gui widget.
> When I ran the program, the program started to leak memory like a sieve. I then
> changed the name back again, and the problem went away. This looks very much
> like some sort of weird caching behaviour to me.
>
> I've tried deleting the .pyc file and even re-booting, but I can't make the
> problem go away!
>
> Can anyone confirm that this caching happens? And if so, is it documented
> anywhere?
>
> TIA

You can run a dir() in the GUI IDLE or the command line IDLE and see
what's currently "cached", so to speak. In the GUI IDLE, you can
"flush" it out by going to the Shell menu and choosing Restart Shell.

It should only display the following after a restart:

>>> dir()
['__builtins__', '__doc__', '__name__']


HTH

Mike



From gagsl-py2 at yahoo.com.ar  Wed Jan 30 09:01:13 2008
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 30 Jan 2008 06:01:13 -0800 (PST)
Subject: comparing two lists, ndiff performance
References: 
Message-ID: <4382b56f-76e7-4779-a3fc-43eafef365a6@i72g2000hsd.googlegroups.com>

On 29 ene, 22:47, Zbigniew Braniecki 
wrote:

> The new one is of course much better and cleaner (the old one is
> bloated), but I'm wondering if there is a faster way to compare two
> lists and find out what was added, what was removed, what was changed.
> I can simply iterate through two lists because I need to keep an order
> (so it's important that the removed line is after the 3 line which was
> not changed etc.)
>
> ndiff plays well here, but it seems to be extremely slow (1000
> iterations of diffToObject takes 10 sec, 7sec of this is in ndiff).

ndiff does a quadratic process: first determines matching lines using
a SequenceMatcher, then looks for near-matching lines and for each
pair, compares them using another SequenceMatcher.
You don't appear to be interested in what changed inside a line, just
that it changed, so a simple SequenceMatcher would be enough.
Output from SequenceMatcher is quite different than ndiff, but you'd
have to reimplement the _compareLists method only.

--
Gabriel Genellina


From jimgardener at gmail.com  Sun Jan  6 02:55:04 2008
From: jimgardener at gmail.com (jimgardener at gmail.com)
Date: Sat, 5 Jan 2008 23:55:04 -0800 (PST)
Subject: how to use bool
References: 
	<05c5df8b-15c4-47e6-8c14-72c57a84a0ea@y5g2000hsf.googlegroups.com> 
	<2c516040-0193-4de3-bf7d-b61e739cdc2d@l57g2000hsa.googlegroups.com>
Message-ID: <8bdb4424-0265-4393-8cf3-fe6a84e62458@v4g2000hsf.googlegroups.com>

hi bukzor & everyone who replied

thanks for the detailed replies
will try to write that way
thanx a lot
jim



bukzor wrote:
> On Jan 4, 8:51 am, bukzor  wrote:
>
> #exercise of the class and error handling
> m = myclass()
> try:
>     m.mymethod()
>     print "Completed successfully!"
> except SthingError, ste:
>     print "STHINGERROR:"
>     print ste
> except Exception, e: print e
>
> print
> print "This time no error handling:"
> m.mymethod()


From jzgoda at o2.usun.pl  Thu Jan 31 04:40:09 2008
From: jzgoda at o2.usun.pl (Jarek Zgoda)
Date: Thu, 31 Jan 2008 10:40:09 +0100
Subject: Updating documents in PyLucene
In-Reply-To: 
References: 
Message-ID: <47A19779.40001@o2.usun.pl>

gefafwisp at gmail.com napisa?(a):

> The way that Lucene (and by extension, PyLucene) seems to work is that
> updates to documents are implemented by the user as a document
> addition (of the new version) and subsequent deletion (of the old
> version).

I'd switch the operations, first delete then add. Solr does this that
way and I decided to follow.

> My problem is that I'd like to update a number of documents which have
> their Store flag set to NO - they're indexed, but not stored. I don't
> have the original text content of these documents available anywhere
> else - is there any way for me to get this un-stored indexed data from
> the old document into the new?

I think the answer is "no", there has to be some way of identifying
records that have to be deleted. If you do not store any document UID,
you are out of luck.

Anyway, you may get some hints on lucene mailing list.

-- 
Jarek Zgoda
Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101

"We read Knuth so you don't have to." (Tim Peters)


From mail at timgolden.me.uk  Wed Jan 23 09:53:40 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 23 Jan 2008 14:53:40 +0000
Subject: csv to xls using python 2.1.3
In-Reply-To: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com>
References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com>
Message-ID: <479754F4.2050205@timgolden.me.uk>

LizzyLiz wrote:
> Hi
> 
> I need to convert a .csv file to .xls file using python 2.1.3 which
> means I can't use pyExcelerator!  Does anyone know how I can do this?
> 
> Many thanks
> LizzyLiz

Use win32com.client to start Excel, tell it to .Open the .csv
file and then tell it to .SaveAs an Excel workbook.

TJG


From sjmachin at lexicon.net  Sun Jan 27 17:20:03 2008
From: sjmachin at lexicon.net (John Machin)
Date: Sun, 27 Jan 2008 14:20:03 -0800 (PST)
Subject: translating Python to Assembler
References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com>
	<13pdiaqsdicf9eb@corp.supernews.com> 
	<5vosafF1nn9odU2@mid.individual.net>
	 
	
	
	<92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> 
	
	
	
Message-ID: <6a087729-fd47-4344-ba58-208c3e8f5f05@t1g2000pra.googlegroups.com>

On Jan 27, 10:23 pm, o... at thepond.com wrote:
> >> >ajaksu at Belkar:~$ ndisasm error.txt
> >> >00000000  54                push sp
> >> >00000001  686973            push word 0x7369
> >> >00000004  206973            and [bx+di+0x73],ch
> >> >00000007  206E6F            and [bp+0x6f],ch
> >> >0000000A  7420              jz 0x2c
> >> >0000000C  61                popa
> >> >0000000D  7373              jnc 0x82
> >> >0000000F  656D              gs insw
> >> >00000011  626C65            bound bp,[si+0x65]
> >> >00000014  722E              jc 0x44
> >> >00000016  2E                db 0x2E
> >> >00000017  2E                db 0x2E
> >> >00000018  0A                db 0x0A
>
> >> >:/
>
> >> not sure what you're saying. Sure looks like assembler to me. Take the
> >> '54   push sp'. The 54 is an assembler opcode for push and the sp is
> >> the stack pointer, on which it is operating.
>
> >go troll somewhere else (you obviously don't know anything about
> >assembler and don't want to learn anything about Python).
>
> >-- bjorn
>
> before you start mouthing off, maybe you should learn assembler. If
> you're really serious, go to the Intel site and get it from the horses
> mouth. The Intel manual on assembler lists the mneumonics as well as
> the opcodes for each instruction. It's not called the Intel Machine
> Code and Assembler Language Manual. It's the bible on assembly
> language, written by Intel.
>
> If you're not so serious, here's a URL explaining it, along with an
> excerpt from the article:
>
> http://en.wikipedia.org/wiki/X86_assembly_language
>
> Each x86 assembly instruction is represented by a mnemonic, which in
> turn directly translates to a series of bytes which represent that
> instruction, called an opcode. For example, the NOP instruction
> translates to 0x90 and the HLT instruction translates to 0xF4. Some
> opcodes have no mnemonics named after them and are undocumented.
> However processors in the x86-family may interpret undocumented
> opcodes differently and hence might render a program useless. In some
> cases, invalid opcodes also generate processor exceptions.
>
> As far as this line from your code above:
>
> 00000001  686973            push word 0x7369
>
> 68 of 686973 is the opcode for PUSH. Go on, look it up. The 6973 is
> obviously the word address, 0x7369. Or, do you think that's
> coincidence?
>
> Don't fucking tell me about assembler, you asshole. I can read
> disassembled code in my sleep.

What was originally posted was:
"""
ajaksu at Belkar:~$ cat error.txt
This is not assembler...

ajaksu at Belkar:~$ ndisasm error.txt
00000000  54                push sp
00000001  686973            push word 0x7369
00000004  206973            and [bx+di+0x73],ch
[snip]
"""

Read it again -- he's "disassembled" the text "This is not
assembler..."

54 -> "T"
686973 -> "his"
206973 -> " is"

but you say "68 of 686973 is the opcode for PUSH. Go on, look it up.
The 6973 is obviously the word address, 0x7369. Or, do you think
that's coincidence?"

You are a genius of a kind encountered only very rarely. Care to share
with us your decryption of the Voynich manuscript?


From bj_666 at gmx.net  Wed Jan 23 05:55:03 2008
From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch)
Date: 23 Jan 2008 10:55:03 GMT
Subject: Module/package hierarchy and its separation from file structure
References: 
Message-ID: <5voko7F1ni1rjU1@mid.uni-berlin.de>

On Wed, 23 Jan 2008 03:49:56 -0600, Peter Schuller wrote:

> Let me just shoot down one possible suggestion right away, to show you
> what I am trying to accomplish:
> 
> I do *not* want to simply break out X into org.lib.animal.x, and have
> org.lib.animal import org.lib.animal.x.X as X.

Then you shoot down the idiomatic answer I guess.  That's what most people
do.

Ciao,
	Marc 'BlackJack' Rintsch


From jazle at localhost.com  Tue Jan 15 20:17:32 2008
From: jazle at localhost.com (Jaimy Azle)
Date: Wed, 16 Jan 2008 08:17:32 +0700
Subject: Python too slow?
References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com>
	<4785d960$0$22237$426a74cc@news.free.fr>
	
	<478733a9$0$18055$426a34cc@news.free.fr>
	
	<47877a9c$0$2437$426a34cc@news.free.fr>
	<877iiga0hb.fsf@mulj.homelinux.net>
	
	
	
Message-ID: 

"Paul Boddie"  wrote:
>>
>> perhaps in the future another sillly point could be added also, Java has
>> Jython, while Python doesn't have some thing like PyJava or... perhaps 
>> Py-va
>> (Python based Java Language).
>
> You could compile Java to CPython bytecode or, in the case of a little
> experiment I did some time ago, translate Java bytecode to CPython
> bytecode: the CPython virtual machine operates at a higher level and
> can support the Java instructions fairly easily, whereas a fair amount
> of work is required to support CPython instructions on the Java
> virtual machine. I found that the biggest obstacle was probably
> treating Java packages like Python packages - something which
> admittedly isn't completely necessary, but which would make the thing
> more usable at the prompt. Ultimately, I had little need for Java-
> based software and thus wasn't motivated into continuing the work,
> although Python 2.5 and beyond do provide some conveniences which
> might make some aspects of the implementation more bearable.
>

Wow, serious... what you've done was really, really cool... :)

I was expect there are nobody willing to do to have python runs Java 
Language (such as PyPy) over CPython. Perhaps your javaclass does not work 
just like as PyPy, but really... it is damned cool to get CPython execute 
java byte-code, congratulations...

Salam,

-Jaimy. 




From ejensen at visi.com  Fri Jan 11 11:27:56 2008
From: ejensen at visi.com (Ed Jensen)
Date: Fri, 11 Jan 2008 16:27:56 -0000
Subject: Python too slow?
References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com>
	<47852dd8$0$27994$426a74cc@news.free.fr>
	<13oattm5ijqvf58@corp.supernews.com>
	<4785d960$0$22237$426a74cc@news.free.fr>
	<13od12b23hfv772@corp.supernews.com>
	
	<13od4lm3cepf0ac@corp.supernews.com>
	<47873143$0$21435$426a74cc@news.free.fr>
Message-ID: <13of68cn8hnk2f3@corp.supernews.com>

Bruno Desthuilliers  wrote:
> I don't think you're going to make you some friends here insulting 
> Fredrik. I don't know who Ed Jensen is, but we are quite a lot here to 
> know and respect Mr Lundh for his contributions to Python as both a 
> language and a community.

I'll keep in mind that some people around these parts are untouchable
and have a free pass to be insulting and childish.

Thanks for the tip.


From nagle at animats.com  Fri Jan 11 01:13:36 2008
From: nagle at animats.com (John Nagle)
Date: Thu, 10 Jan 2008 22:13:36 -0800
Subject: Analyzing Python GC output - what is a "cell", and what information
	is available about it.
Message-ID: <478707f2$0$36360$742ec2ed@news.sonic.net>

I'm printing out each entry in "gc.garbage" after a garbage collection in
DEBUG_LEAK mode, and I'm seeing many entries like



That's the output of "repr".   Are "cell" objects created only from
external C libraries, or can regular Python code generate them?  Is there
any way to find out what the 'function object' is from within Python?

(I'm looking for a possible memory leak, obviously.)

				John Nagle


From eegunnar at yahoo.com  Wed Jan  9 17:25:36 2008
From: eegunnar at yahoo.com (erik gartz)
Date: Wed, 9 Jan 2008 14:25:36 -0800 (PST)
Subject: for loop without variable
Message-ID: 

Hi. I'd like to be able to write a loop such as:
for i in range(10):
    pass
but without the i variable. The reason for this is I'm using pylint
and it complains about the unused variable i. I can achieve the above
with more lines of code like:
i = 0
while (i != 10):
    i += 1
Is there a concise way to accomplish this without adding extra lines
of codes? Thanks in advance for your help.


From goon12 at gmail.com  Tue Jan 29 21:12:46 2008
From: goon12 at gmail.com (Joe Riopel)
Date: Tue, 29 Jan 2008 18:12:46 -0800
Subject: Removal of element from list while traversing causes the next
	element to be skipped
In-Reply-To: <1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com>
References: 
	<1d4edf65-ae5f-4037-b88d-7cec8916f223@k2g2000hse.googlegroups.com>
Message-ID: <6a2ccd190801291812k76e4d817o3a3390363b30a046@mail.gmail.com>

On Jan 29, 2008 9:23 AM, attn.steven.kuo at gmail.com
 wrote:
> If you're going to delete elements from
> a list while iterating over it, then do
> it in reverse order:

how about
>>> li = [1,2,3,4,5]
>>> filter(lambda x: x != 3, li)
[1, 2, 4, 5]
>>>


From nstjelja at gmail.com  Wed Jan  9 00:55:30 2008
From: nstjelja at gmail.com (Nikola Stjelja)
Date: Wed, 9 Jan 2008 06:55:30 +0100
Subject: Pet Store
In-Reply-To: <44713824-c8c9-4a4c-af7e-042260068c0c@x69g2000hsx.googlegroups.com>
References: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com>
	<5ugv69F1hqn2cU3@mid.uni-berlin.de>
	<44713824-c8c9-4a4c-af7e-042260068c0c@x69g2000hsx.googlegroups.com>
Message-ID: <2d24984a0801082155l1c6447if1f6bd90822c3a85@mail.gmail.com>

On Jan 8, 2008 7:32 PM, George Maggessy  wrote:

> Yeap. It is. I'm looking for something like that app. Smth that I
> could base my future developments on.
>
> On Jan 8, 1:47 am, Marc 'BlackJack' Rintsch  wrote:
> > On Mon, 07 Jan 2008 22:21:53 -0800, George Maggessy wrote:
> > > I'm an experience Java developer trying to learn Python. I just
> > > finished the Python tutorial on python.org and I'm currently reading
> > > the "Learning Python" book. However, if I could find something like a
> > > simple web app with some best practices, such as those famous "Java
> > > Pet Store" apps, I think that would help me to fill up some gaps in my
> > > learning process. Does anybody know any app like that?
> >
> > Isn't that a web application using Java web frameworks?  So you are
> > looking for a Python web framework with a "Pet Store" tutorial?
> >
> > Ciao,
> >         Marc 'BlackJack' Rintsch
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

If you are looking for a good , well documented , easy to use but powerfull
web framework you deffinitely need to use Django.

-- 
Please visit this site and play my RPG!

http://www.1km1kt.net/rpg/Marinci.php
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From kyosohma at gmail.com  Wed Jan 23 11:15:55 2008
From: kyosohma at gmail.com (Mike Driscoll)
Date: Wed, 23 Jan 2008 08:15:55 -0800 (PST)
Subject: Processing XML that's embedded in HTML
References: 
	 
	<6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> 
	<47972624.2050002@web.de>
Message-ID: 

Stefan,

> I would really encourage you to use the normal parser here instead of iterparse().
>
>   from lxml import etree
>   parser = etree.HTMLParser()
>
>   # parse the HTML/XML melange
>   tree = etree.parse(filename, parser)
>
>   # if you want, you can construct a pure XML document
>   row_root = etree.Element("newroot")
>   for row in tree.iterfind("//Row"):
>       row_root.append(row)
>
> In your specific case, I'd encourage using lxml.objectify:
>
> http://codespeak.net/lxml/dev/objectify.html
>
> It will allow you to do this (untested):
>
>   from lxml import etree, objectify
>   parser = etree.HTMLParser()
>   lookup = objectify.ObjectifyElementClassLookup()
>   parser.setElementClassLookup(lookup)
>
>   tree = etree.parse(filename, parser)
>
>   for row in tree.iterfind("//Row"):
>       print row.relationship, row.StartDate, row.Priority * 2.7
>
> Stefan

Both the normal parser example and the objectify example you gave me
give a traceback as follows:

Traceback (most recent call last):
  File "\\clippy\xml_parser2.py", line 70, in -toplevel-
    for row in tree.iterfind("//Row"):
AttributeError: 'etree._ElementTree' object has no attribute
'iterfind'


Is there some kind of newer version of lxml?

Mike


From gslindstrom at gmail.com  Mon Jan  7 15:51:07 2008
From: gslindstrom at gmail.com (Greg Lindstrom)
Date: Mon, 7 Jan 2008 14:51:07 -0600
Subject: Tutorials at PyCon 2008 (US)
Message-ID: 

Hello Everyone-

I'd like to announce the tutorials sessions for PyCon 2008 (US).  As you may
know, this year PyCon is being held in Chicago, Illinois March 14-16 with
the Thursday before (the 13th) being "Tutorial Thursday".  We are expecting
nearly 600 Python enthusiasts to meet up for the conference and have 29
tutorial sessions scheduled on Thursday in three sessions; morning,
afternoon, and evening.  There is an extra fee to attend a tutorial, but the
sessions are 3 hours long (with a break) and are taught by some of the
smartest cookies in the Python community.  Pop on over to
http://us.pycon.org/2008/about/ for more information

Here's a list of the sessions currently offered (we may cancel a session if
there are fewer than 10 people registered, but that doesn't happen very
often). In particular, note that there are 4 different introduction to
Python tutorials aimed at different audiences.

*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 and Michael Baye)
   - Python plotting with matplotlib and
pylab(John Hunter)
   - SWIG Master Class
(David Beazley)
   - Secrets of the Framework
Creators(Feihong
Hsu)
   - 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 and Michael Baye)
   - 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 martin at v.loewis.de  Sun Jan 27 15:32:09 2008
From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=)
Date: Sun, 27 Jan 2008 21:32:09 +0100
Subject: Some questions about decode/encode
In-Reply-To: <6035alF1oh17aU3@mid.uni-berlin.de>
References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com>	<5vr1ekF1njt09U2@mid.uni-berlin.de>	<84f39f37-4d18-47c1-9349-bf3f471b2bf5@s19g2000prg.googlegroups.com>
	<6035alF1oh17aU3@mid.uni-berlin.de>
Message-ID: <479CEA49.6010007@v.loewis.de>

>> Is there any way to solve this better?
>> I mean if I shouldn't convert the GBK string to unicode string, what
>> should I do to make SAX work?
> 
> Decode it and then encode it to utf-8 before feeding it to the parser.

The tricky part is that you also need to change the encoding declaration
in doing so, but in this case, it should be fairly simple:

unicode_doc = original_doc.decode("gbk")
unicode_doc = unicode_doc.replace('gbk','utf-8',1)
utf8_doc = unicode_doc.encode("utf-8")

This assumes that the string "gbk" occurs in the encoding declaration
as



If the encoding name has a different spelling (e.g. GBK), you need to
cater for that as well. You might want to try replacing the entire
XML declaration (i.e. everything between ), or just the
encoding= parameter. Notice that the encoding declaration may include
' instead of ", and may have additional spaces, e.g.



HTH,
Martin


From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Mon Jan 28 11:03:28 2008
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Mon, 28 Jan 2008 17:03:28 +0100
Subject: [OT] "just like Java" (was :Re: translating Python to Assembler)
In-Reply-To: 
References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com>			<4799de28$0$12358$426a74cc@news.free.fr>
	
Message-ID: <479dfccf$0$19716$426a74cc@news.free.fr>

Jeroen Ruigrok van der Werven a ?crit :
> -On [20080125 14:07], Bruno Desthuilliers (bruno.42.desthuilliers at wtf.websiteburo.oops.com) wrote:
>> I'm surprised you've not been flamed to death by now - last time I 
>> happened to write a pretty similar thing, I got a couple nut case 
>> accusing me of being a liar trying to spread FUD about Java vs Python 
>> respective VMs inner working, and even some usually sensible regulars 
>> jumping in to label my saying as "misleading"...
> 
> I think your attitude in responding did not help much Bruno, if you want a
> honest answer.

Possibly, yes. Note that being personnally insulted for stating 
something both technically correct *and* (as is the case here) commonly 
stated here doesn't help either.


From paddy3118 at googlemail.com  Sat Jan 26 03:04:10 2008
From: paddy3118 at googlemail.com (Paddy)
Date: Sat, 26 Jan 2008 00:04:10 -0800 (PST)
Subject: Generational Interfaces
References: <1b7b3b47-72f0-4a5d-9185-4903e75dba47@d70g2000hsb.googlegroups.com>
Message-ID: 

On Jan 26, 5:03 am, Carl Banks  wrote:
> While thinking about generational garbage collection, the thought of
> generational interfaces occurred to me.  I'd thought I'd run it by you
> guys.  I'm curious if there are any examples of this out there.
>
> I've opined on this chat room before that interfaces are more often
> cumbersome than helpful, especially in the early stages of a project
> where lots of refactoring is (or ought to be) happening.  But as
> projects mature, interfaces do too, and that made me think interfaces
> could be generated automatically by monitoring the software over time.
>
> As an example, say I'm writing a flight simulator, and I have a
> abstract base class Airplane, that I want to have an interface
> someday, but I don't know what it is yet.  So I define an
>
> AirplaneInterface = InterfaceTracker("Airplane")
>
> What this does is to open a sort of persistent database called
> Airplane (details aren't important now).  The database tracks all
> objects that claim to implement the interface.
>
> So say the first airplane is a Piper Cherokee.  I'd write a class like
> this:
>
> class PiperCherokeeX1(object):
>     wingspan = 52.2
>     wingchord = 7.9
>     ...
>     def __init__(self):
>         self.x = 0.0
>         self.y = 0.0
>         self.z = 0.0
>         ...
>         set_up_initial_state()
>         ...
>         AirplaneInterface.report(self)
>     def move_stick(self,dx,dy):
>         ...
>     def move_thottle(self,ds):
>         ...
>     def move_rudder_pedals(self,ddr):
>         ...
>     def camera_matrix(self):
>         return self._quat_to_matrix(self.q0,self.q1,self.q2,self.q3)
>     def step(self,dt):
>         ...
>
> The key here is the call to AirplaneInterface.report() at the end of
> __init__; this tells the interface tracker that, as of this call, this
> object is implementing the Aircraft interface.
>
> At this point, the interface tracker notes that PiperCherokeeX1 object
> has certain methods (move_stick, move_throttle, etc), certain class
> attributes, and certain instance attributes.  And that's all it does--
> at first.  It just writes information into the database.
>
> As time passes, and development continues, methods and data are added,
> changed, reconfigured.  For instance, I might split up move_stick()
> into move_stick_x() and move_stick_y() for some reason.  Then I might
> get rid of these functions altogether in favor of a
> move_control(self,n,dx).  And so on.  I add more classes that
> implement the Aircraft interface, too.  They look almost nothing like
> the original interface.
>
> However, through all that, the class attribute "wingspan" remains
> there.  Until one day when the project is quite mature I add a new
> class, say Airbus380, that fails to define "wingspan".  When this
> class calls AirplaneInterface.report(), it raises an
> InterfaceException.
>
> Basically, the InterfaceTracker decides, after some threshold of
> nearly universal usage of a certain method or attribute, that it has
> become a required part of the interface and starts raising exceptions
> when it's not there.
>
> Make sense?  Details can vary, but that's the basic idea.  In this
> way, you can combine some of the openness that helps in early
> development, but also have some of the benefits of stricter typing
> when things mature and turn out to be pretty strictly useful, without
> much effort.
>
> Thoughts?  (Surely someone's thought to do this before.)
>
> Carl Banks

I thought a major use of an interface is to allow separate development
that comes together at the interface. If so then such fluid interface
changing would scupper separate development.

- Paddy.


From mario at ruggier.org  Wed Jan  2 07:16:16 2008
From: mario at ruggier.org (mario)
Date: Wed, 2 Jan 2008 04:16:16 -0800 (PST)
Subject: different encodings for unicode() and u''.encode(), bug?
References: <16a8f0b2-3190-44b5-9982-c5b14ad549ea@l6g2000prm.googlegroups.com>
	<477B4B88.6070207@v.loewis.de>
	<391a5357-7dd9-46f6-a5aa-ba5a08579fa2@e10g2000prf.googlegroups.com>
	 
	<323e052e-5298-49bd-bed4-7a8669ad6c04@v32g2000hsa.googlegroups.com> 
	<4af890f4-acbc-467c-995d-0593b0ef08ee@e6g2000prf.googlegroups.com>
Message-ID: <593794bb-370d-44af-9c3a-706222fa1140@i29g2000prf.googlegroups.com>

On Jan 2, 12:28 pm, John Machin  wrote:
> On Jan 2, 9:57 pm, mario  wrote:
>
> > Do not know what the implications of encoding according to "ANSI
> > codepage (CP_ACP)" are.
>
> Neither do I. YAGNI (especially on darwin) so don't lose any sleep
> over it.
>
> > Windows only seems clear, but why does it only
> > complain when decoding a non-empty string (or when encoding the empty
> > unicode string) ?
>
> My presumption: because it doesn't need a codec to decode '' into u'';
> no failed codec look-up, so no complaint. Any realistic app will try
> to decode a non-empty string sooner or later.

Yes, I suspect I will never need it ;)

Incidentally, the situation is that in a script that tries to guess a
file's encoding, it bombed on the file ".svn/empty-file" -- but why it
was going so far with an empty string was really due to a bug
elsewhere in the script, trivially fixed. Still, I was curious about
this non-symmetric behaviour for the empty string by some encodings.

Anyhow, thanks a lot to both of you for the great feedback!

mario


From http  Sun Jan 27 21:57:53 2008
From: http (Paul Rubin)
Date: 27 Jan 2008 18:57:53 -0800
Subject: py3k feature proposal: field auto-assignment in constructors
References: 
	<0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com>
	<87d4rm93l1.fsf@benfinney.id.au>
	<479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net>
Message-ID: <7xhcgyodvy.fsf@ruckus.brouhaha.com>

Wildemar Wildenburger  writes:
> class Server(object):
>      def __init__(self, self.host, self.port,
>                   self.protocol, self.bufsize, self.timeout):
>          pass
> ?

That could temporarily bind those attributes but it shouldn't
persistently mutate the object.

How about:

    class Server(object):
         def __init__(self, host, port, protocol, bufsize, timeout):
            self.(host, port, protocol, bufsize, timeout) = \
                  host, port, protocol, bufsize, timeout

That's fairly explicit yet cuts down the total amount of boilerplate.


From eproust at gmail.com  Sun Jan 20 11:50:19 2008
From: eproust at gmail.com (pythonewbie)
Date: Sun, 20 Jan 2008 08:50:19 -0800 (PST)
Subject: Linux/Win32 func. to get Python instdir (not exedir) + 
	site-packages => extensions mgmt
References:  
	
Message-ID: 

On 20 jan, 12:20, Christian Heimes  wrote:
> pythonewbie wrote:
> > I am stucked on creating a function to get the Python install
> > directory (and site-packages directory) with a 100% reliable method...
>
> Only one method is 100% reliable:
>
> try:
>     import yourextension
> except ImportError:
>     available = False
> else:
>     available = True
>
> Christian

Hi Christian,

OK thanks, interesting to detect if an extension is available or not.

But for different reasons I also want to get the absolute path of
Python install directory (not only the executable under Linux) and
site-packages directory.

How could I proceed ?


From mnordhoff at mattnordhoff.com  Mon Jan 14 09:06:04 2008
From: mnordhoff at mattnordhoff.com (Matt Nordhoff)
Date: Mon, 14 Jan 2008 09:06:04 -0500
Subject: ucs2 or ucs4?
In-Reply-To: 
References: 
Message-ID: <478B6C4C.3030809@mattnordhoff.com>

Neal Becker wrote:
> How do I tell if my python-2.5 is build with ucs2 or ucs4?

You can also check sys.maxunicode.

>>> import sys
>>> sys.maxunicode

If it's 1114111, you're UCS-4. If it's something much lower, you're UCS-2.
-- 


From deets at nospam.web.de  Fri Jan  4 12:41:02 2008
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 04 Jan 2008 18:41:02 +0100
Subject: Details about pythons set implementation
In-Reply-To: 
References: 
	<87bq818wbt.fsf@mulj.homelinux.net>
	
	
Message-ID: <5u79deF1gf91rU1@mid.uni-berlin.de>

bukzor schrieb:
> On Jan 4, 9:08 am, Sion Arrowsmith 
> wrote:
>> Hrvoje Niksic   wrote:
>>
>>> BTW if you're using C++, why not simply use std::set?
>> Because ... how to be polite about this? No, I can't. std::set is
>> crap. The implementation is a sorted sequence -- if you're lucky,
>> this is a heap or a C array, and you've got O(log n) performance.
>> But the real killer is that requirement for a std::set is that
>> T::operator< exists. Which means, for instance, that you can't
>> have a set of complex numbers....
>>
>> --
>> \S -- si... 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
> 
> Why cant you implement < for complex numbers? Maybe I'm being naive,
> but isn't this the normal definition?
>     a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2)
> 
> How do you implement a set without sorting?
> 
> Are you expecting better than O(log n)?

Of course, hashing does O(1) (most of the time, with a sane hash of course.)

Diez


From suyashjape at gmail.com  Sat Jan 12 03:21:56 2008
From: suyashjape at gmail.com (suyash jape)
Date: Sat, 12 Jan 2008 13:51:56 +0530
Subject: How to POST call and retrieve result page
In-Reply-To: <20080111115703.16dbabd7@mbook.mired.org>
References: <16314edc0801110114t346bca6ek71660132de60b91e@mail.gmail.com>
	<20080111115703.16dbabd7@mbook.mired.org>
Message-ID: <16314edc0801120021l913a100l2a514998d8856627@mail.gmail.com>

Hi

/search.php fills the text box values. But /search.php has two form action
elements

1) 
AND 2) I did GET and POST to both results.php page , which gives *'String could not be parsed as XML'* exception. Should data passed be in some XML format or normal query ? POST on blast_results.php also does not work. I guess i am not able to identify the variable names to be passed.For/search.php i found the variables.But couldnt in the other forms. Thanks for your help.. Suyash On Jan 11, 2008 10:27 PM, Mike Meyer wrote: > On Fri, 11 Jan 2008 14:44:19 +0530 "suyash jape" > wrote: > > > Hi all > > i want to access a web page through python script, fillup the necessary > > fields, > > and press submit button (which does POST call) and retrieve the result > page > > and retrieve some values from it. > > > > Here is the script i have written till now. > > > > >import urllib2 > > > # create array of name/value pairs > > > self.params = urllib.urlencode({'seqname': 'BioSequence', 'sequence': > > 'ATACATTATCCAAACATAAAAAGCATGGCTT'}) > > > > > > # send http-post > > > request = urllib.urlopen("http://www.hydrazome.metazome.net/search.php > ", > > params) > > > > > > # read back each line of reply > > > line = request.read() > > >print line > > > > This script fills up the correct values in the search.php page.But i am > not > > sure if it is doing the POST (submit call). > > Beacause in 'line' varialble, i am getting the search.php page.Not the > > result page which is blast_results.php. > > > > How to retrieve the result page? > > Sounds like you're not POSTing to the right page. > > The form on .../search.php lets you fill in values, but those values > are not necessarily POSTed to search.php. In particular, the form element > has an action attribute that has a URL to which the values on the page > should be posted. If that points to .../blast_results.php, then that's > the page you need to pass to urlopen with your data. > > -- > Mike Meyer < mwm at mired.org> > http://www.mired.org/consulting.html > Independent Network/Unix/Perforce consultant, email for more information. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From azam.farooq3 at gmail.com Wed Jan 30 01:04:05 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Tue, 29 Jan 2008 22:04:05 -0800 (PST) Subject: Do You Want a GSM Mobile with Amazing Features? Please click here Message-ID: <5f454014-6362-45f3-a940-a3ca04dc2178@c23g2000hsa.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 nytrokiss at gmail.com Tue Jan 22 19:31:51 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 23 Jan 2008 01:31:51 +0100 Subject: translating Python to Assembler In-Reply-To: References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: <8a6b8e350801221631n409fe89ci9b4a7113b6d8bd88@mail.gmail.com> The reason you were finding a Python Debugger when looking for the PDB files is because PDB is Python DeBugger! Also why would you be looking for a PDB file if you can read the C source! On Jan 22, 2008 11:55 PM, Wim Vander Schelden wrote: > Python modules and scripts are normally not even compiled, if they have > been, > its probably just the Python interpreter packaged with the scripts and > resources. > > My advice is that if you want to learn Python, is that you just read a book > about > it or read only resources. Learning Python from assembler is kind of... > strange. > > Not only are you skipping several generations of programming languages, > spanned > over a period of 40 years, but the approach to programming in Python is so > fundamentally different from assembler programming that there is simply no > reason > to start looking at if from this perspective. > > I truly hope you enjoy the world of high end programming languages, but > treat them > as such. Looking at them in a low-level representation or for a low-level > perspective > doesn't bear much fruits. > > Kind regards, > > Wim > > > > On 1/22/08, over at thepond.com wrote: > > My expertise, if any, is in assembler. I'm trying to understand Python > > scripts and modules by examining them after they have been > > disassembled in a Windows environment. > > > > I'm wondering if a Python symbols file is available. In the Windows > > environment, a symbol file normally has a PDB extension. It's a little > > unfortunate that Python also uses PDB for its debugger. Google, for > > whatever reason, wont accept queries with dots, hyphens, etc., in the > > query line. For example a Google for "python.pdb" returns +python > > +pdb, so I get a ridiculous number of returns referring to the python > > debugger. I have mentioned this to Google several times, but I guess > > logic isn't one of their strong points. :-) > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com From donn.ingle at gmail.com Sun Jan 13 15:57:53 2008 From: donn.ingle at gmail.com (Donn) Date: Sun, 13 Jan 2008 22:57:53 +0200 Subject: LANG, locale, unicode, setup.py and Debian packaging In-Reply-To: <478A77F0.4000502@v.loewis.de> References: <200801132048.08966.donn.ingle@gmail.com> <478A77F0.4000502@v.loewis.de> Message-ID: <200801132257.53214.donn.ingle@gmail.com> > Now you are mixing two important concepts - the *contents* > of the file with the *name* of the file. Then I suspect the error may be due to the contents having been written in utf8 from previous runs. Phew! It's bedtime on my end, so I'll try it again when I get a chance during the week. Thanks muchly. \d -- snappy repartee: What you'd say if you had another chance. Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From donn.ingle at gmail.com Thu Jan 24 14:44:15 2008 From: donn.ingle at gmail.com (Donn) Date: Thu, 24 Jan 2008 21:44:15 +0200 Subject: piping into a python script In-Reply-To: References: <200801241903.20082.donn.ingle@gmail.com> Message-ID: <200801242144.15722.donn.ingle@gmail.com> Thanks for the tips, I'll decode and try 'em all out. > Ah yes, Groo. Ever wonder who would win if Groo and Forrest Gump fought > each other? Heh ;) I reckon they'd both die laughing. Be fun to watch -- if anyone else survived! \d -- "A computer without Windows is like chocolate cake without mustard." -- Anonymous Coward /. Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From paul at boddie.org.uk Wed Jan 23 09:07:43 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 23 Jan 2008 06:07:43 -0800 (PST) Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? References: Message-ID: On 23 Jan, 14:20, kliu wrote: > > Thank u for your reply. but what I really need is the mapping between > each DOM nodes and the corresponding original source segment. At the risk of promoting unfashionable DOM technologies, you can at least serialise fragments of the DOM in libxml2dom [1]: import libxml2dom d = libxml2dom.parseURI("http://www.diveintopython.org/", html=1) print d.xpath("//p")[7].toString() Storage and retrieval of the original line and offset information may be supported by libxml2, but such information isn't exposed by libxml2dom. Paul [1] http://www.python.org/pypi/libxml2dom From monkeydance at mailinator.com Mon Jan 7 05:55:25 2008 From: monkeydance at mailinator.com (monkeydance at mailinator.com) Date: Mon, 7 Jan 2008 02:55:25 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! Message-ID: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> See http://www.tiobe.com/index.htm?tiobe_index. Marc From python.list at tim.thechases.com Tue Jan 29 11:38:15 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 29 Jan 2008 10:38:15 -0600 Subject: MySQLdb In-Reply-To: <1fac15ec-26e5-4fbb-bb01-252ed8561d3b@d70g2000hsb.googlegroups.com> References: <1fac15ec-26e5-4fbb-bb01-252ed8561d3b@d70g2000hsb.googlegroups.com> Message-ID: <479F5677.8040909@tim.thechases.com> > i have problem manipulating mySQL data. When i add values in a Table, > i can recieve them instantly but when i check the table from another > script, the new values dont exist. Depending on your transaction settings (both on your mysql connection object in code, and the engine used for the table(s) in mysql's DB), you may have to commit your transaction to make it visible in other connections. This helps prevent partial transactions from being visible when they're in inconsistent states. -tkc From ryszard.szopa at gmail.com Sun Jan 13 07:51:20 2008 From: ryszard.szopa at gmail.com (Richard Szopa) Date: Sun, 13 Jan 2008 04:51:20 -0800 (PST) Subject: super, decorators and gettattribute References: <433c5592-926e-49ac-a819-0d79ff573e5b@j78g2000hsd.googlegroups.com> <5utunhF1jl8liU1@mid.uni-berlin.de> Message-ID: <3232ed12-57b2-49b1-9fb1-4992b3329042@j78g2000hsd.googlegroups.com> On Jan 13, 8:59 am, Marc 'BlackJack' Rintsch wrote: > On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: > > However, I am very surprised to learn that > > > super_object.__getattr__(name)(*args, **kwargs) > > > getattr(super_object, name)(*args, **kwargs) > > > are not equivalent. This is quite odd, at least when with len() > > and .__len__, str() and .__str__. Do you maybe know what's the > > rationale behind not following that convention by getattr? > > I think you are confusing `__getattr__` and `__getattribute__` here! > `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's > different. Well, in my code calling super_object.__getattr__(name)(*args, **kwargs) and getattr(super_object, name)(*args, **kwargs) gives *different* effects (namely, the latter works, while the former doesn't). That kinda suggests that they don't map to each other :-). And that makes me feel confused. Cheers, -- Richard From lists at cheimes.de Thu Jan 17 15:55:52 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 17 Jan 2008 21:55:52 +0100 Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. In-Reply-To: <478FAC5A.50206@animats.com> References: <478FAC5A.50206@animats.com> Message-ID: John Nagle wrote: > It's possible to use "pickle" for interprocess communication over > pipes, but it's not straightforward. IIRC the processing module uses pickle for IPC. Maybe you can get some idea by reading its code? http://pypi.python.org/pypi/processing/0.40 Christian From bj_666 at gmx.net Mon Jan 28 05:05:42 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Jan 2008 10:05:42 GMT Subject: read and readline hanging References: <5vuv9iF1o6ambU2@mid.uni-berlin.de> Message-ID: <605nnmF1oc8dvU2@mid.uni-berlin.de> On Sun, 27 Jan 2008 19:58:27 +0100, Olivier Lefevre wrote: >>> But how can I find out *programmatically* that there is no more >>> input? >> >> You can't. > > How do people handle this, then? Reading from a process that will > block if you ask too much yet won't let you know how much there is > to read right now has to be some kind of FAQ. It's impossible to handle if the external process does not tell you somehow if there's still data ahead or if it is finished. Then there's only the closing of the file on the process' side that tells you the definitive end of the data. >> This doesn't answer if the interpreter doesn't flush its output buffer >> after every line. > > I think it must otherwise you might get incomplete answers or no > answers at the interactive prompt and that never happens. It may > not flush its buffer after every line but it must flush them at > the end of an answer. The buffering behavior at the interactive prompt is very often different from connections via pipes. If stdout of a process is connected to a terminal the standard C library chooses line buffering but if it is connected to a pipe or redirected to a file it chooses block buffering instead. In such cases the `pexpect` module might be a solution. Ciao, Marc 'BlackJack' Rintsch From quentel.pierre at wanadoo.fr Mon Jan 14 16:05:28 2008 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Mon, 14 Jan 2008 13:05:28 -0800 (PST) Subject: Simple List division problem References: <239ec362-fa22-4fd9-a749-b523c85b047c@k39g2000hsf.googlegroups.com> Message-ID: <413a62d1-6487-485b-ba15-4cf72bad164a@s12g2000prg.googlegroups.com> On 12 jan, 19:37, marcstuart wrote: > How do I divide a list into a set group of sublist's- if the list is > not evenly dividable ? > consider this example: > > x = [1,2,3,4,5,6,7,8,9,10] > y = 3 # number of lists I want to break x into > z = y/x > > what I would like to get is 3 sublists > > print z[0] = [1,2,3] > print z[2] = [4,5,6] > print z[3] = [7,8,9,10] > > obviously not even, one list will have 4 elements, the other 2 will > have 3., > the overriding logic, is that I will get 3 lists and find a way for > python to try to break it evenly, if not one list can have a greater > amount of elements > > Would I use itertools ? How would I do this ? > > Thanks Hi, If you want to split the list in 4, do you want [1,2],[3,4],[5,6],[7,8,9,10] : all extra items in the last sublist or [1,2],[3,4],[5,6,7],[8,9,10] : one extra item in each of the last sublists ? Assuming you want the second version : ======================= def split_list(lst,nb): # ln = length of smaller sublists # extra = number of longer sublists (they have ln+1 items) ln,extra = divmod(len(lst),nb) pos = ln*(nb-extra) # position where larger sublists begin return [ lst[i*ln:(i+1)*ln] for i in xrange(nb-extra) ] \ + [lst[pos+i*(ln+1):pos+(i+1)*(ln+1)] for i in xrange(extra)] ====================== x = range(1,11) print split_list(x,1) >>>[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] print split_list(x,2) >>>[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] print split_list(x,3) >>>[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] print split_list(x,4) >>>[[1, 2], [3, 4], [5, 6, 7], [8, 9, 10]] print split_list(x,5) >>>[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] print split_list(x,10) >>>[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] From bernhard.merkle at googlemail.com Thu Jan 3 08:04:22 2008 From: bernhard.merkle at googlemail.com (Bernhard Merkle) Date: Thu, 3 Jan 2008 05:04:22 -0800 (PST) Subject: reassign to builtin possible !? Message-ID: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> Hi there, I am reading Learning Python 3e from Mark Lutz and just found out that reassigning to builtins is possible. What is the reason, why Python allows this ? IMO this is very risky and can lead to hard to find errors. (see also Learning Python 3e, Chapter 16, Page 315) >>> True True >>> False False >>> True = 1 >>> True 1 >>> True = 0 >>> True 0 TIA, Berni From jwwest at gmail.com Thu Jan 3 00:35:17 2008 From: jwwest at gmail.com (jwwest) Date: Wed, 2 Jan 2008 21:35:17 -0800 (PST) Subject: Python CGI - Presenting a zip file to user References: Message-ID: <475074c1-ef0d-4551-834c-5a16781de3f8@m34g2000hsf.googlegroups.com> On Jan 2, 8:56 pm, Justin Ezequiel wrote: > On Jan 3, 7:50 am, jwwest wrote: > > > > > Hi all, > > > I'm working on a cgi script that zips up files and presents the zip > > file to the user for download. It works fine except for the fact that > > I have to overwrite the file using the same filename because I'm > > unable to delete it after it's downloaded. The reason for this is > > because after sending "Location: urlofzipfile" the script stops > > processing and I can't call a file operation to delete the file. Thus > > I constantly have a tmp.zip file which contains the previously > > requested files. > > > Can anyone think of a way around this? Is there a better way to create > > the zip file and present it for download "on-the-fly" than editing the > > Location header? I thought about using Content-Type, but was unable to > > think of a way to stream the file out. > > > Any help is appreciated, much thanks! > > > - James > > import sys, cgi, zipfile, os > from StringIO import StringIO > > try: # Windows only > import msvcrt > msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) > except ImportError: pass > > HEADERS = '\r\n'.join( > [ > "Content-type: %s;", > "Content-Disposition: attachment; filename=%s", > "Content-Title: %s", > "Content-Length: %i", > "\r\n", # empty line to end headers > ] > ) > > if __name__ == '__main__': > os.chdir(r'C:\Documents and Settings\Justin Ezequiel\Desktop') > files = [ > '4412_ADS_or_SQL_Server.pdf', > 'Script1.py', > 'html_files.zip', > 'New2.html', > ] > b = StringIO() > z = zipfile.ZipFile(b, 'w', zipfile.ZIP_DEFLATED) > for n in files: > z.write(n, n) > > z.close() > > length = b.tell() > b.seek(0) > sys.stdout.write( > HEADERS % ('application/zip', 'test.zip', 'test.zip', length) > ) > sys.stdout.write(b.read()) > b.close() Thanks! That worked like an absolute charm. Just a question though. I'm curious as to why you have to use the msvcrt bit on Windows. If I were to port my app to *NIX, would I need to do anything similar? - James From matthias.blaesing at rwth-aachen.de Sat Jan 19 17:20:47 2008 From: matthias.blaesing at rwth-aachen.de (Matthias =?iso-8859-1?q?Bl=E4sing?=) Date: 19 Jan 2008 22:20:47 GMT Subject: Naming a file References: <89bb0095-429f-404c-b7f6-ff0a554b07cc@i72g2000hsd.googlegroups.com> Message-ID: Am Sat, 19 Jan 2008 14:14:30 -0800 schrieb snoylr: > For example if the variable is 105Markum > > What statement do I need to create a file name 105Markum.txt? filename_base = '105Markum' filename = '%s.txt' % filename_base f = open(filename, 'w') f.write( References: <489729.25110.qm@web57603.mail.re1.yahoo.com> Message-ID: <14660373.post@talk.nabble.com> Francesco Pietra wrote: > > Please, how to adapt the following script (to delete blank lines) to > delete > lines containing a specific word, or words? > > f=open("output.pdb", "r") > for line in f: > line=line.rstrip() > if line: > print line > f.close() > > If python in Linux accepts lines beginning with # as comment lines, please > also > a script to comment lines containing a specific word, or words, and back, > to > remove #. > Well the simplest way in python using the stream for data or configuration or something IMHO would be to use a filter, list comprehension or generator expression: # filter (puts it all in memory) lines = filter(lambda line: not line.lstrip().startswith('#'), open("output.pdb", "r")) # list comprehension (puts it all in memory) lines = [line for line in open("output.pdb", "r") if not line.lstrip().startswith('#')] # generator expression (iterable, has .next(), not kept in memory) lines = (line for line in open("output.pdb", "r") if not line.lstrip().startswith('#')) Check out http://rgruet.free.fr/PQR25/PQR2.5.html http://rgruet.free.fr/PQR25/PQR2.5.html for some quick hints. -- View this message in context: http://www.nabble.com/Delete-lines-containing-a-specific-word-tp14651102p14660373.html Sent from the Python - python-list mailing list archive at Nabble.com. -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jan 15 17:23:17 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 15 Jan 2008 23:23:17 +0100 Subject: "env" parameter to "popen" won't accept Unicode on Windows -minor Unicode bug References: <478bfcb0$0$36378$742ec2ed@news.sonic.net><5v2cudF1k5a1oU1@mid.individual.net><478c551a$0$36354$742ec2ed@news.sonic.net> <5v3dq9F1k2577U1@mid.uni-berlin.de> <5v3qtsF1khn11U1@mid.uni-berlin.de> <478d2569$0$36379$742ec2ed@news.sonic.net> Message-ID: <5v4q2lF1kkdliU1@mid.individual.net> John Nagle wrote: > The problem is that only the NT-derived Microsoft systems > talk Unicode. The DOS/Win16/Win9x family did not. But they did > have CreateProcess. So the current code will handle Win9x, but not > Unicode. Please explain, I don't understand. If you try using Windows system functions in older Windows versions, u"mystring" will fail, too. Those functions need byte strings, not Unicode string instances. The latter have to be encoded to byte strings to pass them. Regards, Bj?rn -- BOFH excuse #70: nesting roaches shorted out the ether cable From arnodel at googlemail.com Mon Jan 28 07:09:48 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 28 Jan 2008 04:09:48 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> <13pqd16n4o3rufe@corp.supernews.com> Message-ID: <19678691-f12e-4111-80b1-eae66f8d6e84@s19g2000prg.googlegroups.com> On Jan 28, 4:47 am, "Gabriel Genellina" wrote: > En Sun, 27 Jan 2008 23:51:28 -0200, Arnaud Delobelle > escribi?: > > > Nice! I've got a slight variation without magic argument names: > > > class Test(object): > > @autoassign('foo', 'bar') > > def __init__(self, baz): > > print 'baz =', baz [...] > I would like a signature-preserving version. The help system, pydoc, the > inspect module, and likely any other introspection tool see those > decorated methods with a different signature than the original one. > Even if one writes a signature-preserving decorator (maybe along the lines > of this article by M. Simionato [1]), names like "self_foo", "self_bar" > are ugly. Furthermore, argument names are part of the public interfase, > but here they're tied to the implementation: what if later I want to keep > a reference to baz? I must change the argument name to self_baz, breaking > all users of the code. Sligthly improved (not for performance! but signature-preserving and looks for default values) from functools import wraps from inspect import getargspec from itertools import izip, chain def autoassign(*names): def decorator(f): fargnames, _, _, fdefaults = getargspec(f) defaults = [(n,v) for (n,v) in izip(reversed(fargnames), reversed(fdefaults)) if n in names] @wraps(f) def decorated(self, *args, **kwargs): self.__dict__.update(defaults) for name, arg in chain(izip(fargnames, args), kwargs.iteritems()): if name in names: setattr(self, name, arg) return f(self, *args, **kwargs) return decorated return decorator class Test(object): @autoassign('foo', 'bar') def __init__(self, foo, bar=3, baz=6): print 'baz =', baz t = Test(1, 2, 6) u = Test(foo=8) print t.foo # 1 print t.bar # 2 print u.foo # 8 print u.bar # 3 (default) -- Arnaud print t.baz # AttributeError From jpcc at nowhere.org Tue Jan 22 14:45:51 2008 From: jpcc at nowhere.org (John Carlyle-Clarke) Date: Tue, 22 Jan 2008 19:45:51 +0000 Subject: Problem with processing XML In-Reply-To: <1839ec4e-045e-4ce2-a3ea-78ed83a8c288@u10g2000prn.googlegroups.com> References: <13pbudgks88rcf3@corp.supernews.com> <1839ec4e-045e-4ce2-a3ea-78ed83a8c288@u10g2000prn.googlegroups.com> Message-ID: <13pchvlg6d59q3b@corp.supernews.com> Paul McGuire wrote: > > Here is a pyparsing hack for your problem. Thanks Paul! This looks like an interesting approach, and once I get my head around the syntax, I'll give it a proper whirl. From __peter__ at web.de Wed Jan 23 08:09:38 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Jan 2008 14:09:38 +0100 Subject: Removing objects References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> Message-ID: bladedpenguin wrote: > So, in general, is it more efficient to use a dictionary or to override > the __eq__ function? Rule of thumb: If you want to add/remove arbitrary objects from a collection a dictionary (or set) is always faster than a list. You may still have to override the __eq__() and __hash__() methods whenever you have distinct objects that can be equal. Caveat: don't use dictionaries if the result of obj1 == obj2 # items in the dict can change during the lifetime of the collection. Peter From vedrandekovic at gmail.com Tue Jan 22 09:27:00 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Tue, 22 Jan 2008 06:27:00 -0800 (PST) Subject: make exe from application with py2exe Message-ID: <6d553403-1275-459e-b2e0-9463cab39250@e10g2000prf.googlegroups.com> Hello, Is there any idea how can i create (.exe) from application (.exe ) with py2exe? Regards, Vedran From sjmachin at lexicon.net Sat Jan 26 02:52:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Jan 2008 23:52:54 -0800 (PST) Subject: Doesn't know what it wants References: <13plo358k5rf059@corp.supernews.com> Message-ID: On Jan 26, 6:25 pm, Steven D'Aprano wrote: > On Fri, 25 Jan 2008 22:53:16 -0800, John Machin wrote: > > On Jan 26, 5:32 pm, Jeroen Ruigrok van der Werven > nomine.org> wrote: > >> -On [20080126 06:26], Tim Rau (bladedpeng... at gmail.com) wrote: > > >> >Line 147 reads: > >> > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0))) > > >> I think it expects something like: > > >> # badly named variable, pick something better depending on context > >> temp = vec2d(0, 0) > >> cp.cpMomentForCircle(self.mass, .2, 0, temp) > > > That *cannot* give a different result in Python. The called function > > will be presented with *exactly* the same object as the OP's code does. > > Not quite. Look carefully at the difference. > > The OP's code calls vec2d with a single tuple argument (0,0). Jeroen's > version calls vec2d with two int arguments, 0 and 0. > > We don't know whether vec2d will treat those two things the same or not. That was Jeroen's 2nd problem; I was addressing his first problem (thinking that introducing a temp variable would work some magic). Google is your friend: """ class vec2d(ctypes.Structure): """2d vector class, supports vector and scalar operators, and also provides a bunch of high level functions """ __slots__ = ['x', 'y'] def __init__(self, x_or_pair, y = None): if y == None: self.x = x_or_pair[0] self.y = x_or_pair[1] else: self.x = x_or_pair self.y = y """ From stanc at al.com.au Sun Jan 20 21:14:41 2008 From: stanc at al.com.au (Astan Chee) Date: Mon, 21 Jan 2008 13:14:41 +1100 Subject: Bittorent client with google talk interface In-Reply-To: <4793FA6D.7090507@al.com.au> References: <4793FA6D.7090507@al.com.au> Message-ID: <47940011.9090401@al.com.au> Hi, I dont know where to send this but I'll try here. I recently took the newest version of ABCTorrent and its code and added some features to it that I find very useful. Basically it is like a webUI except it connect to google's google talk and you can issue commands from it. Kinda like a command line bittorrent client. So when you start up the client, you can enter your google talk account information and using another google talk account (from somewhere else) send commands (system and torrent related). I've also added some proxy support for it since Im constantly behind proxies (but not at work or school). I use windows XP and wxPython 2.6.3.3 and python 2.5 so I dont know how it will behave in newer versions of things. There are also new modules that it requires (win32api) for file operations that you might need before compiling this. The main script to run this all is the abc.py script. Also I havent done much brushing up with the GUI so it wont look like the fastest ship around. Any suggestions or changes for further improvement? Also for anyone who is developing or has used this before and tinkered with it Im pretty sure Im doing something wrong calling the interface from the code because it (wx) sporadically crashes; Im not sure what to do since I dont know how to call it properly. Does anyone have any idea? Cheers Astan The file can be downloaded here: http://gtalktorrent.googlecode.com/files/3.1.0.zip -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Wed Jan 2 23:35:37 2008 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2008 20:35:37 -0800 Subject: cloud computing (and python)? References: <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <13nn9k48n7ohr95@corp.supernews.com> <69337707-ff18-4b39-af0a-78cf0a14b667@1g2000hsl.googlegroups.com> Message-ID: In article <69337707-ff18-4b39-af0a-78cf0a14b667 at 1g2000hsl.googlegroups.com>, Aaron Watters wrote: > >Ok, so if we include yahoo mail and gmail in "cloud computing" then I >guess usenet is also cloud computing. Usenet actually is a good example of cloud computing, but only at the article distribution level. Netnews clients are *not* examples of cloud computing (except maybe Google Groups). The question is whether there exists an API and infrastructure that supports distributed computing and storage. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From bronger at physik.rwth-aachen.de Tue Jan 1 20:31:06 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 02 Jan 2008 02:31:06 +0100 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au> Message-ID: <87bq85rp2d.fsf@physik.rwth-aachen.de> Hall?chen! Ben Finney writes: > Steven D'Aprano writes: > >> [...] >> >> There's a very good reason to buck the trend whenever practical: >> tabs have the considerable benefit that they decouple the >> presentation of the code from the structure of the code. > > Huh? I can only interpret this to mean that you think it's a good > thing for a text file one is *directly editing* to be rendered in > such a way that one cannot tell quite what one is really editing. No. It's more like the old battle visual vs. semantic markup in markup languages. Both markup is unambiguous. After all, the width of a tab is nowhere defined. It really is a matter of the editor's settings. I, for example, dislike too wide indenting. I use four columns in Python and two in Delphi. However, there are Python projects using eight spaces for each indentation level. If all Python code used tabs, eveybody could use their own preferences, for both reading and writing code, and interoperability would be maintained nevertheless. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From sakradevanamindra at gmail.com Thu Jan 24 15:14:06 2008 From: sakradevanamindra at gmail.com (Shoryuken) Date: Thu, 24 Jan 2008 12:14:06 -0800 (PST) Subject: a newbie regex question Message-ID: Given a regular expression pattern, for example, \([A-Z].+[a-z]\), print out all strings that match the pattern in a file Anyone tell me a way to do it? I know it's easy, but i'm completely new to python thanks alot From half.italian at gmail.com Wed Jan 16 17:53:30 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 16 Jan 2008 14:53:30 -0800 (PST) Subject: read_nonblocking error in pxssh References: <12fda1ac-192b-4dcf-9ff0-249d5e260a2e@f10g2000hsf.googlegroups.com> Message-ID: <0ae8654f-737b-4934-9915-c0c3d018b83c@s19g2000prg.googlegroups.com> Just glanced at the docs, but it might be worth a shot... try: > >>> import pxssh > >>> s=pxssh.pxssh() > >>> s.login("myhost","root","mypass", auto_prompt_reset=False) Maybe??? Otherwise, I have used and modified this script with great success: (ssh_session.py) http://www.koders.com/python/fidA430838E5789710E4DCF34C414AD75EB4EEE63CF.aspx Good luck. ~Sean On Jan 16, 9:24?am, jrpfinch wrote: > I'm attempting to use the pxssh to execute commands on a remote > machine and do stuff with the output. ?Both machines are running SSH > Version Sun_SSH_1.0, protocol versions 1.5/2.0 and Intel Solaris 9. > > I am hitting a problem with read_nonblocking in the pexpect module as > follows: > > >>> import pxssh > >>> s=pxssh.pxssh() > >>> s.login("myhost","root","mypass") > > Trying command: ssh -q -l root gerard > Expect returned i=2 > Expect returned i=1 > Traceback (most recent call last): > ? File "", line 1, in > ? File "pxssh.py", line 244, in login > ? ? if not self.synch_original_prompt(): > ? File "pxssh.py", line 134, in synch_original_prompt > ? ? self.read_nonblocking(size=10000,timeout=10) # GAS: Clear out the > cache before getting the prompt > ? File "/opt/python2.5.1/lib/python2.5/site-packages/pexpect.py", line > 824, in read_nonblocking > ? ? raise TIMEOUT ('Timeout exceeded in read_nonblocking().') > pexpect.TIMEOUT: Timeout exceeded in read_nonblocking(). > > Running the ssh command from the shell yields: > > bash-2.05# ssh -q -l root myhost > root at myhost's password: > Last login: Wed Jan 16 17:10:32 2008 from x.x.x.x > Sun Microsystems Inc. ? SunOS 5.9 ? ? ? Generic January 2003 > Sun Microsystems Inc. ? SunOS 5.9 ? ? ? Generic January 2003 > root at myhost:/ # > > I would be grateful if anyone could make a suggestion as to where I go > next? ?Is read_nonblocking(), the correct method to be using here? > Are there any options in pxssh I need to explore (I've tried ssh -t, > but this means the password entry fails with raise ExceptionPxssh > ('password refused')). > > Many thanks > > Jon From jamon.ben at gmail.com Tue Jan 15 05:44:33 2008 From: jamon.ben at gmail.com (Ben Fisher) Date: Tue, 15 Jan 2008 05:44:33 -0500 Subject: print >> to a derived file In-Reply-To: References: Message-ID: <741fd030801150244q79a211fbh430590ccc2590c68@mail.gmail.com> This might have something to do with the class being derived from file. I've written it so that it doesn't derive from file, and it works. class File_and_console(): def __init__(self, *args): self.fileobj = open(*args) def write(self, s): self.fileobj.write(s) print s, f = File_and_console('testout.tmp','w') f.write('hello') print >>f,'hello', On 1/15/08, iu2 wrote: > Hi, > > I'm trying to write data to both a file and the console, so I did: > > class File_and_console(file): > def write(self, s): > file.write(self, s) > print s, > > >>> f = File_and_console('1.txt', 'w') > >>> f.write('hello') > hello > >>> print >>f, 'world' > >>> > > the 'write' method works, but 'print >>' doesn't, it writes only to > the file. It doesn't actually call File_and_console.write > > Why? How can I fix it? > Thanks > iu2 > -- > http://mail.python.org/mailman/listinfo/python-list > From paul.sijben at xs4all.nl Fri Jan 11 04:44:36 2008 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Fri, 11 Jan 2008 10:44:36 +0100 Subject: encrypting python modules Message-ID: <47873a78$0$85785$e4fe514c@news.xs4all.nl> Hello, this question has come by repeatedly in several guises over the past years but has never been solved in this forum as far as I have been able to Google. However since so many people are asking the question, I hope someone has made a solution and is willing to share it. The problem: I have a client-server app written in python. I want to make sure that the client is not: 1) destabilized by users accidentally or on purpose dropping python files in the path (after which calling the helpdesk will not be useful) 2) extended with "new features" without me knowing about it (again resulting in calls to my helpdesk...) 3) trivially decompiled. Added issue, I want the client to be able to update itself when I have fixed bugs or created new functionality. I know that I can not stop a dedicated hacker deconstructing my code. Since all clients need to go through the server I am not afraid of "freeloaders". I am now considering overriding import with some code that will only import modules signed and crypted by me. However I can not imagine that I would be the first one planning to do this. So is there a solution like this available somewhere? Paul Sijben From hvora at usc.edu Fri Jan 4 23:10:11 2008 From: hvora at usc.edu (Hita Vora) Date: Fri, 04 Jan 2008 20:10:11 -0800 Subject: do - loop Message-ID: I have a dataset which has about 3000 subjects in it. I take each subject and perform 3 to 4 geoprocessing tasks on it. Currently I have a model where I manually feed in each subject's ID and then the rest of the process is automated. I would like to automate the process such that it would automatically select another subject after the process has been completed on a specfic subject. ie to repeat the same process on each of the IDs. Any help such as a dummy code would be greatly appreciated. Thanks. Hita From gherzig at fmed.uba.ar Wed Jan 30 09:16:40 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Wed, 30 Jan 2008 11:16:40 -0300 Subject: Removing Pubic Hair Methods In-Reply-To: References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> Message-ID: <47A086C8.6010509@fmed.uba.ar> Sion Arrowsmith wrote: >Marc 'BlackJack' Rintsch wrote: > > >>On Tue, 29 Jan 2008 11:48:38 -0800, Tobiah wrote: >> >> >>>class genital: >>> def pubic_hair(self): >>> pass >>> def remove(self): >>> del(self.pubic_hair) >>> >>> >>I think `pubic_hair` is an attribute instead of a method. >> >>Oh, and ``del`` is a statement and not a function. So the way you wrote >>it with parentheses is a bit misleading. >> >> > >And who's going to want to call genital().remove() anyway? > > > I will use genital().extend(), thats for shure ^^ From ganeshborse at gmail.com Thu Jan 3 23:23:41 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 3 Jan 2008 20:23:41 -0800 (PST) Subject: PyObject_CallObject code dump after calling 4 times References: <938001bf-33d2-4071-9b08-f7bb041505b1@s19g2000prg.googlegroups.com> Message-ID: <0d763f52-6845-4822-807a-130c9c46c327@i12g2000prf.googlegroups.com> On Jan 3, 8:49?pm, grbgooglefan wrote: > On Jan 3, 8:02?pm, Phil Thompson > wrote: > > > > > > > On Thursday 03 January 2008, grbgooglefan wrote: > > > > I have a following C++ code which uses PyObject_CallObject to evaluate > > > expressions dynamically. This code sets the input parameters for the > > > function also dynamically. After calling this function 4 times (with > > > these shown values), PyObject_CallObject ?causes application to crash > > > in frame_dealloc. > > > 1) Can some one please help me understand why is this crash happening > > > in frame_dealloc & how to solve it? > > > 2) Is there anything wrong I am doing about incrementing or > > > decrementing the reference counts of the object passed to > > > PyObject_CallObject? > > > Yes. > > > > 3) Is it because of the big value (2299265.500000) I am trying to > > > convert from double to float using PyFloat_FromDouble? > > > > //========================= code reduced for readability > > > =============== > > > switch(ndtyp){ > > > ? ? ?case(INT_T): > > > ? ? ? ? ?{ > > > ? ? ? ? ?printf("PyInt_FromLong val %d, var %s > > > \n",inputVar.nionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > > ? ? ? ? ?val = PyInt_FromLong(inputVar.nionum); > > > ? ? ? ? ?break; > > > ? ? ? ? ?} > > > ? ? ? case(LONG_T): > > > ? ? ? ? ?{ > > > ? ? ? ? ?printf("PyLong_FromLong val %ld, var %s > > > \n",inputVar.lionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > > ? ? ? ? ?val = PyLong_FromLong(inputVar.lionum); > > > ? ? ? ? ?break; > > > ? ? ? ? ?} > > > ? ? ? case(FLOAT_T): > > > ? ? ? ? ?{ > > > ? ? ? ? ?printf("PyFloat_FromDouble val %f, var %s > > > \n",inputVar.fionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > > ? ? ? ? ?val = PyFloat_FromDouble(inputVar.fionum); > > > ? ? ? ? ?break; > > > ? ? ? ? ?} > > > ? ? ? case(DOUBLE_T): > > > ? ? ? ? ?{ > > > ? ? ? ? ?printf("PyFloat_FromDouble val %f, var %s > > > \n",inputVar.dionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > > ? ? ? ? ?val = PyFloat_FromDouble(inputVar.dionum); > > > ? ? ? ? ?break; > > > ? ? ? ? ?} > > > ? ? ? ?case(STRING_T): > > > ? ? ? ? ?{ > > > ? ? ? ? ?printf("PyString_FromString val %s, var %s > > > \n",inputVar.ioString,pEvalFunc->pExprVarsArray[nCtr].szVarName); > > > ? ? ? ? ?val = PyString_FromString(inputVar.ioString); > > > ? ? ? ? ?break; > > > ? ? ? ? ?} > > > ? ? ? ?default: > > > ? ? ? ? ?printf("Unknown data type [%d] for %s\n",ndtyp,pEvalFunc- > > > > >pExprVarsArray[nCtr].szVarName); > > > > } > > > if(!val){ > > > ? ?ret = -1; > > > ? ?printf("Failed to convert %d %s to PyObject\n",ndtyp,pEvalFunc- > > > > >pExprVarsArray[nCtr].szVarName); fflush(stdout); > > > > ? ?Py_XDECREF(pTuple); > > > ? ?break; > > > } > > > ? PyTuple_SetItem(pTuple, nCtr, val); > > > ? Py_XDECREF(val); > > > Don't do this - PyTuple_SetItem() steals a reference to val. > > > > } > > > // all variables are set, call Python function > > > Py_XINCREF(pTuple); > > > Why do this? > > > > ? PyObject *pResult = PyObject_CallObject(pEvalFunc- > > > > >pPyEvalFunction,pTuple); > > > > Py_XDECREF(pTuple); > > > Why do this? > > > > if(PyErr_Occurred()){ > > > ?PyErr_Print(); > > > } else { > > > ? ? ? char* plevel = NULL; > > > ? ? ? if(NULL != (plevel = PyString_AsString(pResult))){ > > > ? ? ? ? ret = 0; > > > ? ? ? ? sprintf(szEvalResult,"%s",plevel); > > > ? ? ? } > > > } > > > Py_XDECREF(pResult); > > > pTuple will now have the same number of references as when you started the > > above code, so you may want to Py_DECREF() it. > > > Phil- Hide quoted text - > > > - Show quoted text - > > Thanks for all the responses. > These help me. > I could simulate this crash in my small test program & I think (I > could be wrong also) it is because of extraneous Py_XDECREF of > "PyObject *val" which I am using to convert variables to tuple. > When I change the code to simple do like this, it works fine. > ? ? ? ? ? ? PyTuple_SetItem(pytuple,0,PyLong_FromLong(size)); > ? ? ? ? ? ? PyTuple_SetItem(pytuple,1,PyLong_FromLong(maxvol)); > ? ? ? ? ? ? PyTuple_SetItem(pytuple,2,PyFloat_FromDouble(adv));- Hide quoted text - > > - Show quoted text - Now my new code looks like this. Do you think this is correct way to handle ref counts? Do you forsee any issues of memory leaks, etc. here? // ================================================================================ switch(ndtyp){ case(INT_T): //printf("PyInt_FromLong val %d, var %s \n",inputVar.nionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); PyTuple_SetItem(pTuple,nCtr,PyInt_FromLong(inputVar.nionum)); break; case(LONG_T): //printf("PyLong_FromLong val %ld, var %s \n",inputVar.lionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); PyTuple_SetItem(pTuple,nCtr,PyLong_FromLong(inputVar.lionum)); break; case(FLOAT_T): //printf("PyFloat_FromDouble val %f, var %s \n",inputVar.fionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); PyTuple_SetItem(pTuple,nCtr,PyFloat_FromDouble(inputVar.fionum)); break; case(DOUBLE_T): //printf("PyFloat_FromDouble val %f, var %s \n",inputVar.dionum,pEvalFunc->pExprVarsArray[nCtr].szVarName); PyTuple_SetItem(pTuple,nCtr,PyFloat_FromDouble(inputVar.dionum)); break; case(STRING_T): //printf("PyString_FromString val %s, var %s \n",inputVar.ioString,pEvalFunc->pExprVarsArray[nCtr].szVarName); PyTuple_SetItem(pTuple,nCtr,PyString_FromString(inputVar.ioString)); break; default: printf("Unknown data type [%d] for %s \n",ndtyp,pEvalFunc->pExprVarsArray[nCtr].szVarName); bUnknownDataType = true; break; } if(bUnknownDataType){ // got an unknown data type for a variable ret = -1; break; } } // all variables are set, call Python function if(ret == 0){ PyObject *pResult = PyObject_CallObject(pEvalFunc- >pPyEvalFunction,pTuple); if(PyErr_Occurred()){ ret = -1; printf("error occured in PyObject_CallObject\n"); PyErr_Print(); } else { char* plevel = NULL; if(NULL != (plevel = PyString_AsString(pResult))){ ret = 0; strncpy(szEvalResult,plevel,strlen(plevel)); printf("Final result %s\n",szEvalResult); } else { printf("PyObject_CallObject returned NULL\n"); ret = -1; } } Py_XDECREF(pResult); Py_XDECREF(pTuple); // ================================================================================ From arkanes at gmail.com Thu Jan 31 14:36:59 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 31 Jan 2008 13:36:59 -0600 Subject: Python for mobiles In-Reply-To: <1201807007.31585.20.camel@smilochik-lin> References: <03e0ad28-e72c-4582-8518-b5cb07d408df@e10g2000prf.googlegroups.com> <1201807007.31585.20.camel@smilochik-lin> Message-ID: <4866bea60801311136y3bff85fbwaef52c4ee9f6762b@mail.gmail.com> On Jan 31, 2008 1:16 PM, Shawn Milochik wrote: > > A better solution would surely be to get a Nokia S60 'phone, for which > there is a native Python implementation. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > > > Steve: > > Do you know if the Nokia E60i phone has this capability? Also, is wxPython supported? > Or are you just knowledgeable about the S60? > wxPython is not, but there are bindings for the S60s native gui provided. You can find out it your phone is supported a pys60.sf.net. From fredrik at pythonware.com Wed Jan 9 14:05:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 20:05:39 +0100 Subject: problem of converting a list to dict In-Reply-To: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> Message-ID: Louis.Soninhu at gmail.com wrote: > I have a list like this > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] > > I'd like to remove the first and the last item as they are irrevalent, > and convert it to the dict: > {'tom':'boss','mike':'manager','paul':'employee'} > > I tried this but it didn't work: > > mydict={} > for i in mylist[1:-1]: > a=i.split('=') > mydict[a[0]]=a[1] > > and I got this: > File "srch", line 19, in > grab("a/tags1") > File "srch", line 15, in grab > mydict[mylist[0]]=mylist[1] > IndexError: list index out of range > > Anyone could shed me a light on this? works for me, with the mylist example you provided. to see what's going on on your machine, try printing "a" after the split, but before you use it to populate the dictionary. From tarundevnani at gmail.com Thu Jan 24 22:31:47 2008 From: tarundevnani at gmail.com (tarun) Date: Fri, 25 Jan 2008 09:01:47 +0530 Subject: [wxPython-users] Issue with docking wx.listctrl window In-Reply-To: <4798D1B1.7020908@alldunn.com> References: <4798D1B1.7020908@alldunn.com> Message-ID: Thanks a lot Robin. I tried using self.log and instead of self.log.list. *Code is attached.* But this gives me a panel and listctrl in it. The extra blank space around the listctrl in window1 is something that I don't need. Please help. Regards, Tarun Devnani On Jan 24, 2008 11:28 PM, Robin Dunn wrote: > tarun wrote: > > Hello All, > > > > I'm trying to create a Frame with AuiManager. The code is attached. > > > > *Problem:* > > - I want 2 windows to be docked in the frame. One is a text control and > > other is a list control. > > - The text control gets docked, but on trying to dock the list control, > > all the tabs dis-appear. > > The tabs appear only when the list control window is kept floating. > > > > In the attached code the list control window is kept floating. This can > > be docked > > To see the issue with docking, comment line 33 and un-comment line 35 in > > the attached file and then try to execute, the issue would be clearly > > visible. On un-docking the window1, the tabs again appear.. > > > > *Please let me the solution to this ASAP* > > > The main problem is that you are putting the listctrl on a panel, but > you are telling AUI to manage the listctrl, not the panel. If I > understand correctly then your other problems stem from that as well. > Try passing self.log to AddPane, instead of self.log.list. > > > -- > Robin Dunn > Software Craftsman > http://wxPython.org Java give you jitters? Relax > with wxPython! > > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Docking.py URL: From steve at REMOVE-THIS-cybersource.com.au Mon Jan 21 17:17:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 22:17:11 -0000 Subject: When is min(a, b) != min(b, a)? References: <13p9h86e9aoa43e@corp.supernews.com> Message-ID: <13pa6f7q3ftckc9@corp.supernews.com> On Mon, 21 Jan 2008 18:00:05 +0000, Pete Forman wrote: > If NaNs in your data are important then you must take care in explicit > and implicit comparisons to consider unordered results. And even if they're not important, beware of bugs from failing to consider unordered results due to unexpected NaNs. -- Steven From steven at REMOVE.THIS.cybersource.com.au Mon Jan 14 22:14:19 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 15 Jan 2008 03:14:19 -0000 Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> <7xsl105fvv.fsf@ruckus.brouhaha.com> <13onli9dk7mu926@corp.supernews.com> <7xhchgatin.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 14 Jan 2008 15:15:28 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> map = {'a': Aclass, 'b': Bclass, 'c': Cclass} class_ = map.get(astring, >> default=Zclass) >> >> The result I want is the class, not the result of calling the class >> (which would be an instance). If I wanted the other semantics, I'd be >> using defaultdict instead. > > I used default as a keyward arg name indicating the presence of a > callable. I probably should have called it defaultfunc or something. > > x = d.get('a', f) # --> default value is f x = d.get('a', > defaultfunc=f) # --> default value is result of f() . So you're talking about proposed *added* behaviour, rather than *replacing* the current behaviour? Sorry if I misunderstood you in the first place. -- Steven From mikez302 at gmail.com Mon Jan 14 12:06:18 2008 From: mikez302 at gmail.com (mikez302) Date: Mon, 14 Jan 2008 09:06:18 -0800 (PST) Subject: IDLE won't start in Python 2.5 for Windows References: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> <13ogqhlds0tbsac@corp.supernews.com> <57a7e4a2-0acc-4439-9bd6-d96862ffc22e@j78g2000hsd.googlegroups.com> <13oi9lg6onn6s72@corp.supernews.com> <13ojc0i3ii1etcb@corp.supernews.com> Message-ID: I was able to start IDLE from the command line, and reset my keyboard shortcuts. It works fine now. In case this happens again, where would I find the config file? From musiccomposition at gmail.com Tue Jan 22 22:54:42 2008 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 22 Jan 2008 19:54:42 -0800 (PST) Subject: Cleanup when a object dies Message-ID: <601f19ce-ac60-4145-9e99-6eacb8ea74e2@e6g2000prf.googlegroups.com> I writing writing a class to allow settings (options, preferences) to written file in a cross platform manner. I'm unsure how to go a about syncing the data to disk. Of course, it's horribly inefficient to write the data every time something changes a value, however I don't see how I can do it on deletion. I've read that __del__ methods should be avoided. So am I just going to have to force the client of my object to call sync when they're done? From siona at chiark.greenend.org.uk Wed Jan 30 08:24:26 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Jan 2008 13:24:26 +0000 (GMT) Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: >On Tue, 29 Jan 2008 11:48:38 -0800, Tobiah wrote: >> class genital: >> def pubic_hair(self): >> pass >> def remove(self): >> del(self.pubic_hair) >I think `pubic_hair` is an attribute instead of a method. > >Oh, and ``del`` is a statement and not a function. So the way you wrote >it with parentheses is a bit misleading. And who's going to want to call genital().remove() anyway? -- \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 tenax.raccoon at gmail.com Wed Jan 23 12:11:58 2008 From: tenax.raccoon at gmail.com (Jason) Date: Wed, 23 Jan 2008 09:11:58 -0800 (PST) Subject: application error in python References: <75de8afc-4295-40b5-b9b7-af19ef5264e6@t1g2000pra.googlegroups.com> Message-ID: <70c55d41-1feb-49bf-8f3e-4cb538c2f0de@e6g2000prf.googlegroups.com> On Jan 23, 4:29 am, abhishek wrote: > hello group i am working on a project where most of the code has been > written in c++ but the web component is written in python. Initially > we have been using python2.4 and vs.net2003 but recently we decided to > move ahead with python2.5 and vs.net2005. > > the problem that has been haunting me for while now is when i am > trying to access a few functions in c++ through python by > building .pyd extension, python.exe crashes saying an application > error has occured > > any clues why this happened as everythiing was working well > in .net2003 and python2.4 > > thanks abhishek It could be that Python 2.5 is still built and linked against version 7.1 of the Microsoft C run-time. VS 2005 links against version 8.0 of the Microsoft C run-time. The two versions of the DLL are incompatible, and will cause crashes if memory is allocated from one DLL and then freed with the other. File handles also opened with one C run-time DLL cannot be used with the other version either. Unfortunately, there's no really good fix for this. Microsoft made their libraries and C run-time incompatible between versions of Visual Studio. Rather than force all Python developers to switch to VS 2005, the Python core developers stayed with the previous compiler. If you absolutely must be able to pass file handles and memory with VS 2005 DLLs, you must recompile Python with VS 2005. You will also need to recompile all DLL libraries, such as wxPython, LXML, and the PIL. Pure Python modules and libraries will be unaffected. The easiest solution, however, is to use Python 2.5 and Visual Studio 2003. --Jason From HoustonJuliet at yahoo.com Sat Jan 26 19:52:39 2008 From: HoustonJuliet at yahoo.com (HoustonJuliet) Date: Sat, 26 Jan 2008 16:52:39 -0800 (PST) Subject: do design patterns still apply with Python? In-Reply-To: <120eok46fkf0j2b@corp.supernews.com> References: <8SINf.1718$No6.40137@news.tufts.edu> <120eok46fkf0j2b@corp.supernews.com> Message-ID: <15114746.post@talk.nabble.com> I am a fan of these people: Goldie Hawn Kate Hudson Oliver Reed Robert Conrad Vic Morrow Bill Bixby Grant Edwards wrote: > > On 2006-03-02, John Salerno wrote: > >> Since Python does so many things different, especially compared to >> compiled and statically typed languages, do most of the basic design >> patterns still apply when writing Python code? > > Definitely. Especially plaid, paisley, and a nice medium > houndstooth check. But please, not all at the same time. > > -- > Grant Edwards grante Yow! Maybe we could > paint > at GOLDIE HAWN a rich > PRUSSIAN > visi.com BLUE -- > -- > http://mail.python.org/mailman/listinfo/python-list > > :drunk: -- View this message in context: http://www.nabble.com/do-design-patterns-still-apply-with-Python--tp3210321p15114746.html Sent from the Python - python-list mailing list archive at Nabble.com. From ricaraoz at gmail.com Thu Jan 31 18:55:54 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 31 Jan 2008 20:55:54 -0300 Subject: REALLY simple xml reader In-Reply-To: <60dsbrF1qj28sU1@mid.uni-berlin.de> References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> Message-ID: <47A2600A.2090707@bigfoot.com> Diez B. Roggisch wrote: > Ricardo Ar?oz schrieb: >> Diez B. Roggisch wrote: >>> Ricardo Ar?oz schrieb: >>>> Thanks Ivan, it seems a elegant API, and easy to use. >>>> I tried to play a little with it but unfortunately could not get it off >>>> the ground. I kept getting >>>>>>> root = et.fromstring(doc) >>>> Traceback (most recent call last): >>>> File "", line 1, in >>>> File "E:\Python25\lib\xml\etree\ElementTree.py", line 963, in XML >>>> parser.feed(text) >>>> File "E:\Python25\lib\xml\etree\ElementTree.py", line 1245, in feed >>>> self._parser.Parse(data, 0) >>>> ExpatError: XML or text declaration not at start of entity: line 2, column 0 >>> That's a problem in your XML not being XML. Has nothing to do with >>> element-tree - as one sees from the error-message "ExpatError". If you >>> show it to us, we might see why. >>> >> Sure, >> >> doc = """ >> > > It's not allowed to have a newline before the > > Put it on the line above, and things will work. > > Diez Worked ok. Thanks a lot to you all, I'm not using it right now but I've had a taste and now know where to look and how to start. Cheers From cokofreedom at gmail.com Fri Jan 11 04:25:13 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 11 Jan 2008 01:25:13 -0800 (PST) Subject: python recursive function References: Message-ID: <9633edcf-b9e6-42d3-9444-1b26b6e46d63@v29g2000hsf.googlegroups.com> > Stylistically I prefer 'if not n % 5', looks neater. > As for your assignment, the hardest task will be creating an effective > method of ensuring you recurse through all possibilities. I was chatting to a friend about the 'if not n % 5' and while I am happy to use it saying that when 5 % 5 is False because it returns 0...for this case just feels wrong to me. I understand the reason to keep it this way...but still...having to use not all the time is just annoying. From misterwang at gmail.com Tue Jan 15 11:22:23 2008 From: misterwang at gmail.com (Peter Wang) Date: Tue, 15 Jan 2008 08:22:23 -0800 (PST) Subject: jpype with JFreeChart, anyone interested to help? References: Message-ID: <51378fac-791b-4ccc-97c8-7e911304b54f@v4g2000hsf.googlegroups.com> On Jan 14, 8:25 pm, oyster wrote: > Thanx > However I knew Chaco and matplotlib, and I use matplotlib during my > school days. And as I have pointed out, they are for "plot", but not > "chart". If you don't know the difference between plot and chart, you > can have a look at athttp://www.jfree.org/jfreechart,http://www.rmchart.com > Yes, it is true we can use plot lib to draw chart, but that is tedious. What are the chart types that are missing? Or do you find that the handling of categorical data is generally lacking? Charting and plotting are quite related, and I think you might get better traction trying to add the exact chart and axis types that you need to an existing package rather than starting yet another plotting package for Python. :) -Peter From boblatest at yahoo.com Wed Jan 9 15:07:10 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Jan 2008 20:07:10 GMT Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <5ujp0tF1ehvg2U1@mid.dfncis.de> Message-ID: <5uknreF1il028U3@mid.uni-berlin.de> Sion Arrowsmith wrote: > Robert Latest wrote: >> BTW, where can I find all methods of the built-in types? >>Section 3.6 only talks about strings and mentions the list append() method >>only in an example. Am I too stupid to read the manual, or is this an >>omission? > > 3.6 talks about features common to all "sequence" types. Strings > are discussed specifically in 3.6.1 ("String Methods"). Lists are > similarly discussed in 3.6.4 ("Mutable Sequence Types"). OK, the latter then. Too stupid. Thanks ;-) robert From subopt at gmail.com Tue Jan 29 10:00:31 2008 From: subopt at gmail.com (subopt inTheVicinityOf geemail.com) Date: Tue, 29 Jan 2008 07:00:31 -0800 (PST) Subject: Trouble loading dll via ctypes Message-ID: <68615d61-3e71-4a39-8783-52ff0db97b48@i12g2000prf.googlegroups.com> I'm trying to load a dll via ctypes by doing this: cdll.LoadLibrary('/path/to/mylib.so') But i'm getting this: /path/to/mylib.so: cannot open shared object file: No such file or directory What am i doing wrong? The dll in question is in a directory mounted via NSF, but no part of the path/filename is a symlink. When i try code from the docs: cdll.LoadLibrary('libc.so.6') ,then all is fine. I've also tried to set my LD_LIBRARY_PATH before starting Python, checking it via os.environ, then doing the cdll.LoadLibrary(...), but that fails with the same complaint. What am i doing wrong? tia, Eric From paul at boddie.org.uk Tue Jan 15 06:40:54 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 15 Jan 2008 03:40:54 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <4785d960$0$22237$426a74cc@news.free.fr> <478733a9$0$18055$426a34cc@news.free.fr> <47877a9c$0$2437$426a34cc@news.free.fr> <877iiga0hb.fsf@mulj.homelinux.net> Message-ID: On 15 Jan, 08:33, "Jaimy Azle" wrote: > > perhaps in the future another sillly point could be added also, Java has > Jython, while Python doesn't have some thing like PyJava or... perhaps Py-va > (Python based Java Language). You could compile Java to CPython bytecode or, in the case of a little experiment I did some time ago, translate Java bytecode to CPython bytecode: the CPython virtual machine operates at a higher level and can support the Java instructions fairly easily, whereas a fair amount of work is required to support CPython instructions on the Java virtual machine. I found that the biggest obstacle was probably treating Java packages like Python packages - something which admittedly isn't completely necessary, but which would make the thing more usable at the prompt. Ultimately, I had little need for Java- based software and thus wasn't motivated into continuing the work, although Python 2.5 and beyond do provide some conveniences which might make some aspects of the implementation more bearable. Given that other languages (eg. Logix [2], various Lisp dialects) have been implemented for CPython, I think your point could be better formulated. Paul [1] http://www.boddie.org.uk/python/javaclass.html [2] http://www.livelogix.net/logix/ From sjmachin at lexicon.net Wed Jan 9 14:45:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 9 Jan 2008 11:45:43 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> Message-ID: <3a9ff586-007e-40c6-9568-d83bc7ce6f7d@d4g2000prg.googlegroups.com> On Jan 10, 5:56 am, Louis.Soni... at gmail.com wrote: > Hi pals > > I have a list like this > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] > > I'd like to remove the first and the last item as they are irrevalent, > and convert it to the dict: > {'tom':'boss','mike':'manager','paul':'employee'} > > I tried this but it didn't work: > > mydict={} > for i in mylist[1:-1]: > a=i.split('=') # this will disect each item of mylist into a 2-item No it doesn't; it dissects i into a 2-item list if i is a string containing exactly one '='. DON'T rely on "knowing" that the first and last entries are the only irrelevant ones. Do some checking. Conditions to check for: (1) len(a) == 2 (2) a[0] is empty or not what you expect (a person's name) (3) a[1] is empty or not what you expect (a job title) (consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = ' boss') (4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...] From kyosohma at gmail.com Fri Jan 4 16:57:26 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 4 Jan 2008 13:57:26 -0800 (PST) Subject: Skill Resume Achievements, What Good Goes Here? References: <724e4836-d895-4210-972d-dd8f861902df@l1g2000hsa.googlegroups.com> Message-ID: On Jan 4, 3:06 pm, apatheticagnostic wrote: > On Jan 2, 11:31 am, kyoso... at gmail.com wrote: > > > > > On Jan 2, 9:59 am, vbgunz wrote: > > > > I spent some time working on a skill resume, the kind of resume > > > college students put together and realized, I am not in college and > > > everything I learned was self-taught. Of course I would like some real > > > world achievements but don't consider throw-away code an achievement > > > and am failing to really see any. I don't even wish to entertain the > > > thought of lying about anything. > > > > What are some achievements an employer may be looking for in someone > > > willing to start at ground level, entry level, intern, etc? What are > > > some real world achievements every n00b will need under his/her belt > > > in order to be taken seriously? > > > Internships are always a good thing to have. If you've contributed to > > open source projects, I'd put that on there. If you're applying for > > some kind of programming job, they'll probably want to see some of > > your code, know what home-brewed projects you've done and how long > > they took to complete, issues you ran into, etc. > > > That might get you started anyway. > > > Mike > > As someone else who's self-educated and curious about this, would > listing canonical comp-sci books that you've gone through on your own > and understood be a reasonable thing to mention? For example, SICP, > PLAI, etc? I'm not sure...I went through a ton of interviews and was never asked about what books I'd read. I did get questions about group projects / assignments and a couple companies wanted to know what I programs I created on my own. Mike From DustanGroups at gmail.com Sun Jan 6 07:51:32 2008 From: DustanGroups at gmail.com (Dustan) Date: Sun, 6 Jan 2008 04:51:32 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <33417662-8246-4950-9b86-265aa1c63c69@c23g2000hsa.googlegroups.com> Message-ID: <24f46b58-330b-435c-8e57-8e18f1ce471e@d70g2000hsb.googlegroups.com> On Jan 5, 4:16 am, c... at mailinator.com wrote: > The warning "The group you are posting to is a Usenet group. Messages > posted to this group will make your email address visible to anyone on > the Internet." means a person, but not a bot, may see my email > address, so it is safe to use my real address next time... Wrong. A bot may be able to read and scan all messages sent through Usenet. From steve at REMOVE-THIS-cybersource.com.au Sun Jan 27 20:47:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 28 Jan 2008 01:47:18 -0000 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net> <60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> Message-ID: <13pqd16n4o3rufe@corp.supernews.com> On Sun, 27 Jan 2008 19:13:27 -0500, Terry Reedy wrote: [snip] > class Test(object): > @autoassign > def __init__(self, _foo, _bar, baz): > print 'baz =', baz [snip] > I think this version, with this name convention, is nice enough to > possibly go in the stdlib if there were an appropriate place for it. > Not sure where though. If there were a classtools module.... -1/2 I don't like the name convention. _name already has a perfectly good convention: it's a private name, don't mess with it. That includes in function/method signatures. With your convention, _foo is public. I suppose you could write __foo for a private name, and ___foo for a *really* private name, relying on the decorator to strip one of the underscores. But counting all those underscores is a PITA, and what happens if you don't actually want that private name set as an instance attribute? As nice as this feature would be, and I vote +2 on the functionality, I wonder whether the amount of line noise in method definitions now will be approaching Perlish levels? We've got default values, type annotations (in Python3), *args and **kwargs, _ private names, and now we want to add auto-assignment. If we do get syntax support, I vote +1 on &foo, +1/2 on @foo, -1 on .foo and -1 on self.foo. (It's explicit, but it's long...). -- Steven From john.m.roach at gmail.com Wed Jan 9 14:30:45 2008 From: john.m.roach at gmail.com (John) Date: Wed, 9 Jan 2008 11:30:45 -0800 (PST) Subject: printing dots in simple program while waiting References: Message-ID: On Jan 9, 12:14 pm, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of Martin Marcher > > Sent: Wednesday, January 09, 2008 11:57 AM > > To: python-l... at python.org > > Subject: Re: printing dots in simple program while waiting > > > John wrote: > > > > import time > > > s = '.' > > > print 'working', # Note the "," at the end of the line > > > while True: > > > print s > > > time.sleep(1) > > > see my comment in the code above... > > > if that's what you mean > > Bah. The trailing command may prevent the newline, but it appends a > space whether you want it or not.[1] Use sys.stdout.write('.') instead. > > import sys > > print "wussy nanny state, tax 'n spend my spaces, liberal comma:" > for i in range(1, 10): > print '.', > print > print "manly neo-con I know what's Right so keep your government out of > my strings! print:" > for i in range(1, 10): > sys.stdout.write('.') > > [1] Which has to be _the_ most annoying feature of Python. *grrr* > > ***** > > 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 Thanks for all of the help. This is what ended up working: import time import sys s = '.' sys.stdout.write( 'working' ) while True: sys.stdout.write( s ) sys.stdout.flush() time.sleep(0.5) From suyashjape at gmail.com Fri Jan 11 01:25:06 2008 From: suyashjape at gmail.com (suyash jape) Date: Fri, 11 Jan 2008 11:55:06 +0530 Subject: How to POSTcall and retrieve result page Message-ID: <16314edc0801102225s502b8929oc802c66d4f0bedb1@mail.gmail.com> Hi all i want to access a web page through python script, fillup the necessary fields, and press submit button (which does POST call) and retrieve the result page and retrieve some values from it. Here is the script i have written till now. >import urllib2 > # create array of name/value pairs > self.params = urllib.urlencode({'seqname': 'BioSequence', 'sequence': 'ATACATTATCCAAACATAAAAAGCATGGCTT'}) > > # send http-post > request = urllib.urlopen("http://www.hydrazome.metazome.net/search.php", params) > > # read back each line of reply > line = request.read() >print line This script fills up the correct values in the search.php page.But i am not sure if it is doing the POST (submit call). Beacause in 'line' varialble, i am getting the search.php page.Not the result page which is blast_results.php. How to retrieve the result page? Thanks Suyash -------------- next part -------------- An HTML attachment was scrubbed... URL: From aisaac at american.edu Wed Jan 23 11:57:05 2008 From: aisaac at american.edu (Alan G Isaac) Date: Wed, 23 Jan 2008 11:57:05 -0500 Subject: pairs from a list In-Reply-To: References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> Message-ID: <24SdnaCXzLZC7AranZ2dnUVZ_v2pnZ2d@rcn.net> Steven D'Aprano wrote: > In fact, "fastest" isn't even a meaningful attribute. Does it mean: > > * the worst-case is fastest > * the best-case is fastest > * the average-case is fastest > * fastest on typical data > * all of the above I confess that it did not occur to me that there might be an interesting distinction among these cases for the question of how to get sequential pairs from a list. How would one draw these distinctions in this case? Thanks, Alan Isaac PS Just for context, the sequential pairs were needed in a simulation, but my question was primarily prompted by my surprise that the approaches I looked at differed as much as they did. From lists at cheimes.de Sat Jan 26 12:39:45 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 26 Jan 2008 18:39:45 +0100 Subject: Portably killing/signalling another process not supported? In-Reply-To: <479b6c58$0$36354$742ec2ed@news.sonic.net> References: <479b6c58$0$36354$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > There doesn't seem to be any way to portably kill another process > in Python. "os.kill" is Mac/Unix only. The "signal" module only lets > you send signals to the current process. And the "subprocess" module > doesn't have a "kill" function. > > Subprocess objects really should have a portable "interrupt" or > "kill" function. They already have "poll" and "wait", which have > to be implemented differently for different systems; that's the > logical place for "kill". > > Yes, there are nonportable workarounds > (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462) > but no portable solution. We are looking for somebody to implement a portable and cross platform implementation of kill() and send_signal() for the subprocess module. Are you interested in working on a patch for Python 2.6 and 3.0? From hardcoded.software at gmail.com Thu Jan 24 10:20:23 2008 From: hardcoded.software at gmail.com (Virgil Dupras) Date: Thu, 24 Jan 2008 07:20:23 -0800 (PST) Subject: Test driven development References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> Message-ID: <53bae618-0a57-470e-b698-3f936ef7c0e7@s12g2000prg.googlegroups.com> On Jan 24, 7:37?am, ajcpp... at gmail.com wrote: > Hi > > Sorry if this is a bit off topic but as unit testing is such a > cornerstone of python development I thought a few of you may be able > to share your knowledge/experiences. > > I like the concept of TDD but find it difficult to put into practice > most of the time. I think this primarily because I tend to like top- > down development and functional/object decomposition and TDD feels > more like a bottom-up approach. > > So my question is when approaching a project that you want to employ > test driven development on how and where do you start? And also if > anyone uses top-down design with TDD I would be interested in how you > do it (does it involve lots of mock objects/ is the first test you > write the last one to pass)? > > Thanks > > Andy I know what you mean by top-down vs. bottom-up and I used to have the same dilemma, but now I would tend to agree with Albert. Your issue with top-down or bottom-up is not relevant in TDD. The only thing that is relevant is to reach your current milestone as soon as possible, without caring about what you're going to do in the milestone after that. Not so long ago, I took the "bottom-up" approach to TDD, which was a mistake because it leads to over-engineering (the end result is not so bad since it's over-engineering that has good test coverage :) ) Roy: While mocking is good to have tests well organized (instead of having a huge pile of tests at the highest level), "over- mocking" (mocking everything, early) leads to, I think, a design that is too rigid. What if a new spec reveals that the current design of a large subset of your classes has to be re-done? All your mocking and the test below them, they all have to be "brought up" to the highest level of tests so you can re-organize your code. Since doing this is a lot of work, and usually messing with tests is a lot more dangerous than messing with the code itself, you would tend to stay with your old design, even if it's not the optimal design for the task you need to do. Virgil From jared.grubb at gmail.com Thu Jan 31 22:10:02 2008 From: jared.grubb at gmail.com (Jared Grubb) Date: Thu, 31 Jan 2008 19:10:02 -0800 Subject: char string 2 hex string Message-ID: <925822270801311910q2450c19ayd347e696cc040cc4@mail.gmail.com> You could also do: "".join(['%02x' % ord(c) for c in 'AAA']) On 31 Jan 2008, at 14:09, Paul Rubin wrote: Antonio Chay writes: "AAA" should be "414141" 'AAA'.encode('hex') -- http://mail.python.org/mailman/listinfo/python-list On 31 Jan 2008, at 14:05, Antonio Chay wrote: Hello! I need to transform a string from a file into a hexadecimal representation, for example: "AAA" should be "414141" With perl I do this with: unpack("H*","AAA") And with python I got this: "".join([str(hex(ord(x)))[2:] for x in "AAA"]) But seems a little "weird" for me. Is there another way? Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From digisatori at gmail.com Thu Jan 31 02:49:46 2008 From: digisatori at gmail.com (digisatori at gmail.com) Date: Wed, 30 Jan 2008 23:49:46 -0800 (PST) Subject: list traversal and remove Message-ID: I supposed the below code will print seven 2 and generate the list li without 2. Strangely it only print four 2. If you change the number of 2 in the list, the results are all beyond expectation. I know the other way to achieve the expected goal, but why this is happening? Could somebody enlight me? li= [2,2,2,2,2,2,2,3,4,5,6,7,8,9] for x in li: if x == 2: print x li.remove(x) From arnodel at googlemail.com Mon Jan 21 02:21:04 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 20 Jan 2008 23:21:04 -0800 (PST) Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> <7xhch8cc7o.fsf@ruckus.brouhaha.com> Message-ID: On Jan 21, 3:19?am, Terry Jones wrote: > Here's a solution that doesn't use any copying of lists in for recursion. > It also eliminates a bunch of trivially equivalent solutions. The countdown > function is 37 lines of non-comment code. ?Sample (RPN) output below. > > Terry [snip code] > This produces: [...] > Target 234, numbers = (100, 9, 7, 6, 3, 1) > ? ? ? ? (6, 1, 'add', 100, 'mul', 7, 'sub', 9, 'add', 3, 'div') > ? ? ? ? (100, 1, 'sub', 3, 'div', 7, 'mul', 6, 'sub', 9, 'add') > ? ? ? ? (7, 6, 'mul', 3, 'mul', 100, 'sub', 9, 'mul', 1, 'mul') > ? ? ? ? (100, 7, 'sub', 3, 'div', 6, 'sub', 1, 'add', 9, 'mul') > ? ? ? ? (7, 6, 'mul', 3, 'mul', 1, 'sub', 100, 'add', 9, 'add') > ? ? ? ? (6, 9, 'sub', 7, 'mul', 1, 'sub', 100, 'add', 3, 'mul') > ? ? ? ? (100, 9, 'sub', 7, 'sub', 6, 'sub', 3, 'mul', 1, 'mul') > ? ? ? ? (100, 7, 'mul', 3, 'mul', 6, 'add', 9, 'div', 1, 'mul') > ? ? ? ? (100, 1, 'sub', 7, 'mul', 9, 'sub', 3, 'div', 6, 'add') > ? ? ? ? (100, 7, 'sub', 3, 'div', 1, 'sub', 9, 'add', 6, 'mul') > ? ? ? ? (7, 3, 'mul', 6, 'sub', 9, 'mul', 1, 'sub', 100, 'add') > ? ? ? ? (100, 7, 'mul', 6, 'sub', 1, 'sub', 9, 'add', 3, 'div') > ? ? ? ? (100, 9, 'add', 7, 'add', 1, 'add', 3, 'div', 6, 'mul') > ? ? ? ? (100, 9, 'sub', 7, 'div', 6, 'mul', 3, 'mul', 1, 'mul') In countdown you are not required to use all numbers to reach the target. This means you are missing solutions, e.g. (1, 3, 6, 'mul', 'add', 7 , 'add', 9, 'mul') After a quick glance at your code it seems to me that you can only have solutions of the type: (num, num, op, num, op, num, op, num, op, num, op) this omits many possible solutions (see the one above). -- Arnaud From fredrik at pythonware.com Wed Jan 9 12:19:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 18:19:57 +0100 Subject: asynchronous timer events - how to? In-Reply-To: <4784fd96$0$22305$ba620e4c@news.skynet.be> References: <4784fd96$0$22305$ba620e4c@news.skynet.be> Message-ID: Helmut Jarausch wrote: > I'm using a web server (Karrigell) which is based on the asyncore module. > I'd like to be able to checkpoint some data (e.g. pickled dictionaries) to disk > from time to time. > For that I would need to setup a timer which calls a Python object/function when > its time interval has expired. While this function is running I need access to > the variables of the server. the usual way to do that with asyncore is to add an outer control loop that calls asyncore.loop with a count argument (or poll directly), and checks a "task queue" at regular intervals. but in your case, it's probably easier to set up a cron job that does a "wget" against your server with a "secret" URL, and have the server do the checkpointing whenever that URL is fetched. From David.Reksten at sweco.no Wed Jan 30 09:47:42 2008 From: David.Reksten at sweco.no (David.Reksten at sweco.no) Date: Wed, 30 Jan 2008 15:47:42 +0100 Subject: SV: Unicode literals to latin-1 In-Reply-To: <2f3cbea4-861d-4076-913e-61ef5d81d738@b2g2000hsg.googlegroups.com> References: <60avf7F1ps52dU3@mid.uni-berlin.de> <2f3cbea4-861d-4076-913e-61ef5d81d738@b2g2000hsg.googlegroups.com> Message-ID: <7C90895B4B6EE44AAF5F16CB1F48427162C41CE48B@srv-mail-02.nettverk.int> On 30. januar 2008 14:31, Gabriel Genellina wrote: >On 30 ene, 07:54, wrote: >> On 30. januar 2008 10:48, Marc 'BlackJack' Rintsch wrote: >> >> >On Wed, 30 Jan 2008 09:57:55 +0100, David.Reksten wrote: >> >> >> How can I convert a string read from a database containing unicode >> >> literals, such as "Fr\u00f8ya" to the latin-1 equivalent, "Fr?ya"? > >> >In [388]: 'Fr\u00f8ya'.decode('unicode-escape') >> >Out[388]: u'Fr\xf8ya' >> >> 'unicode-escape' did the trick! Thank you! > >A unicode-escaped string looks very strange in a database... I'd >revise the way things are stored and retrieved. I agree. I'm currently using the trick above to fix it. .david From __peter__ at web.de Wed Jan 9 05:56:46 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 9 Jan 2008 11:56:46 +0100 Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: cesco wrote: > say I have a string like the following: s1 = 'hi_cat_bye_dog' > and I want to replace the even '_' with ':' and the odd '_' with ',' so > that I get a new string like the following: s2 = 'hi:cat,bye:dog' >>> import re >>> from itertools import cycle >>> re.sub("_", lambda m, c=cycle(":,").next: c(), "hi_cat_bye_dog") 'hi:cat,bye:dog' > Is there a common recipe to accomplish that? I can't come up with any > solution... There are many. If you want to learn Python don't be afraid to write it in a long-winded way (with loops and helper functions) first. Peter From lists at cheimes.de Thu Jan 17 01:03:03 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 17 Jan 2008 07:03:03 +0100 Subject: assigning values in python and perl In-Reply-To: <2d37f441-c01f-439b-9897-35b7e4dfa77b@h11g2000prf.googlegroups.com> References: <2d37f441-c01f-439b-9897-35b7e4dfa77b@h11g2000prf.googlegroups.com> Message-ID: <478EEF97.2070807@cheimes.de> George Sakkis wrote: > Python's parameter passing is like passing a pointer in C/C++. [snip] It's not (I repeat NOT) like passing a pointer in C. Please read http://effbot.org/zone/call-by-object.htm Christian From dannox at gmail.com Fri Jan 25 19:13:19 2008 From: dannox at gmail.com (whatazor) Date: Fri, 25 Jan 2008 16:13:19 -0800 (PST) Subject: python and multithreading problem Message-ID: <3a1379f5-f5f5-4af1-903c-8b1f52eb9ed7@k2g2000hse.googlegroups.com> Hi all, I made an application that use multithreading (indifferently importing thread or threading module) , but when I call some wrapped modules (with swig) from my application they run like there is only a single thread (and my application gui ,made with wxPython, freezes). If I use other modules not wrapped, but created for test that multithread works, and gui is not freezing are ok. Modules that wrap DLL are not my product but are created by another developer with VS.NET, and the only thing I can think is that they're builded without multithreaded compiler option. Can it be another cause for this behaviour, can this explanation be correct? maybe also swig have a multithreading option. thank you in advance w From sjmachin at lexicon.net Wed Jan 23 14:03:14 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 Jan 2008 11:03:14 -0800 (PST) Subject: csv to xls using python 2.1.3 References: <18238cac-3ca7-4cff-9710-e9a4337bb27b@j78g2000hsd.googlegroups.com> Message-ID: On Jan 24, 1:58 am, LizzyLiz wrote: > Perfect! Thanks :-) > > LizzyLiz You have an interesting notion of perfection, which may change after some experience with the proposed solution. Note that sticking with Python 2.1 precludes your using the Python csv module as you first proposed, and is shutting you out of an enormous lot of new functionality. Are you inextricably bound to 2.1? From bperry.volatile at gmail.com Tue Jan 15 16:17:28 2008 From: bperry.volatile at gmail.com (Brandon Perry) Date: Tue, 15 Jan 2008 15:17:28 -0600 Subject: Compile with GLib-1.2 instead of 2.4 In-Reply-To: <1200430429.6386.2.camel@bperry-laptop> References: <1200430429.6386.2.camel@bperry-laptop> Message-ID: <1200431848.6386.4.camel@bperry-laptop> Sorry, I know what arg to use with ./configure. With --with-libc=STRING, do I put the version I want, or the path to my GLib 1.2 files? On Tue, 2008-01-15 at 14:53 -0600, Brandon Perry wrote: > Hi, I am having to compile a standalone python because the webserver I > use doesn't allow access to /usr/lib/python. I tried compiling on my > lappy and uploading it, but the webserver does not have GLib-2.4. What > arguments would I have to include in order for it to compile with > GLib-1.2 instead of/and GLib2.4? > > Thanks, Brandon From David.Reksten at sweco.no Wed Jan 30 04:40:36 2008 From: David.Reksten at sweco.no (David.Reksten at sweco.no) Date: Wed, 30 Jan 2008 10:40:36 +0100 Subject: SV: Unicode literals to latin-1 In-Reply-To: References: Message-ID: <7C90895B4B6EE44AAF5F16CB1F48427162C41CE46B@srv-mail-02.nettverk.int> On 30. januar 2008 10:21, Berteun Damman wrote: >On Wed, 30 Jan 2008 09:57:55 +0100, > wrote: >> How can I convert a string read from a database containing unicode >> literals, such as "Fr\u00f8ya" to the latin-1 equivalent, "Fr????ya"? >> >> I have tried variations around >> "Fr\u00f8ya".decode('latin-1') >> but to no avail. > >Assuming you use Unicode-strings, the following should work: > u"Fr\u00f8ya".encode('latin-1') I'm afraid that the string read from the database is a non-unicode string, thus me not using u"..." above. But it may contain unicode literals from the (Python-based) system that populated the table, and I'd like to get them back to proper unicode strings again, so that I can display them correctly to the user. >That is, for some string s, s.decode('encoding') converts the >non-unicode string s with encoding to a unicode string u. Whereas >for some unicode string u, u.encode('encoding') converts the unicode >string u into a non-unicode string with the specified encoding. > >You can use s.encode() on a non-unicode string, but it will first try to >decode it (which might give an DecodeError if there are non-ASCII >characters present) and it will then encode it. Any suggestions on how that would look, given the example above? .david From ryan at ryankaskel.com Wed Jan 23 13:50:02 2008 From: ryan at ryankaskel.com (ryan k) Date: Wed, 23 Jan 2008 10:50:02 -0800 (PST) Subject: Stripping whitespace Message-ID: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> Hello. I have a string like 'LNAME PASTA ZONE'. I want to create a list of those words and basically replace all the whitespace between them with one space so i could just do lala.split(). Thank you! Ryan Kaskel From fredrik at pythonware.com Fri Jan 4 04:25:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 04 Jan 2008 10:25:54 +0100 Subject: linecache and glob In-Reply-To: <3682a1dd-a3a6-436f-87a0-37feaef65ccc@h11g2000prf.googlegroups.com> References: <0e16ca26-9e34-4f97-83de-9ddc3693d085@i12g2000prf.googlegroups.com> <0a62d553-7fe9-41c0-84dc-a1f3749b46f8@e23g2000prf.googlegroups.com> <3682a1dd-a3a6-436f-87a0-37feaef65ccc@h11g2000prf.googlegroups.com> Message-ID: jo3c wrote: > i have a 2000 files with header and data > i need to get the date information from the header > then insert it into my database > i am doing it in batch so i use glob.glob('/mydata/*/*/*.txt') > to get the date on line 4 in the txt file i use > linecache.getline('/mydata/myfile.txt/, 4) > > but if i use > linecache.getline('glob.glob('/mydata/*/*/*.txt', 4) won't work glob.glob returns a list of filenames, so you need to call getline once for each file in the list. but using linecache is absolutely the wrong tool for this; it's designed for *repeated* access to arbitrary lines in a file, so it keeps all the data in memory. that is, all the lines, for all 2000 files. if the files are small, and you want to keep the code short, it's easier to just grab the file's content and using indexing on the resulting list: for filename in glob.glob('/mydata/*/*/*.txt'): line = list(open(filename))[4-1] ... do something with line ... (note that line numbers usually start with 1, but Python's list indexing starts at 0). if the files might be large, use something like this instead: for filename in glob.glob('/mydata/*/*/*.txt'): f = open(filename) # skip first three lines f.readline(); f.readline(); f.readline() # grab the line we want line = f.readline() ... do something with line ... From bkasterm at gmail.com Tue Jan 29 21:23:56 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Tue, 29 Jan 2008 18:23:56 -0800 (PST) Subject: Gmail imap search does not get all messages. Message-ID: <60cd1edc-761c-4e68-b110-65df54f3c6b3@l32g2000hse.googlegroups.com> 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 Scott.Daniels at Acm.Org Sun Jan 6 13:52:35 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 06 Jan 2008 10:52:35 -0800 Subject: how to use bool In-Reply-To: References: <05c5df8b-15c4-47e6-8c14-72c57a84a0ea@y5g2000hsf.googlegroups.com> <2c516040-0193-4de3-bf7d-b61e739cdc2d@l57g2000hsa.googlegroups.com> Message-ID: <13o28j16l831pbe@corp.supernews.com> jimgardener at gmail.com wrote: > ...if another method in the same class calls this method but wants to > pass the error to a gui code which calls it,,can i do like this > > def callingmethode(self): > try: > mymethod() > except MyError,myerr: > raise myerr > > so that I can handle the error in a gui code that calls > callingmethode() > > class MyGUI: > def guimethode(self): > someinst=SomeClass() > try: > someinst.callingmethode() > except MyError,myer: > self.dealwithMyError(myer) > > is this kind of raising exception the correct way?I am getting syntax > error at > except MyError,myerr: > raise myerr > Almost. The callingmethode code above behaves like: def callingmethode(self): mymethod() except that your code hides the traceback information. If you need to do something locally (other than passing along the exception), use either: def callingmethode(self): try: mymethod() finally: cleanup_stuff() or (if you have some exception-specific code to do): def callingmethode(self): try: mymethod() except MyError,myerr: stuff_only_for_exceptional_cases() raise # Note that this keeps the original traceback. --Scott David Daniels Scott.Daniels at Acm.Org From martin at marcher.name Sat Jan 12 15:34:32 2008 From: martin at marcher.name (Martin Marcher) Date: Sat, 12 Jan 2008 21:34:32 +0100 Subject: sqlite3 is it in the python default distro? Message-ID: Hello, I can see that sqlite is in the standard lib documentation: http://docs.python.org/lib/module-sqlite3.html however debian and ubuntu (and gentoo according to the packages info) seem _not_ to include it. Now 2 question arise: a) Is sqlite included in the python default distribution b) In real life can I consider (on linux) that an installation of python includes the sqlite stuff? thanks martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 22 06:48:02 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 22 Jan 2008 12:48:02 +0100 Subject: what's this instance? In-Reply-To: References: <4795b32d$0$16941$426a74cc@news.free.fr> Message-ID: <4795d7a5$0$25895$426a74cc@news.free.fr> J. Peng a ?crit : > Bruno Desthuilliers ??: >> J. Peng a ?crit : >>> def safe_float(object): >>> try: >>> retval = float(object) >>> except (ValueError, TypeError), oops: >>> retval = str(oops) >>> return retval >>> The code above works well. >> For which definition of "works well" ? >> > > I got it from Core Python Programming book I bought.You may ask it to > Westley Chun.:) Ok: Mr Chun, if you here us ?-) From stanc at al.com.au Thu Jan 31 19:01:40 2008 From: stanc at al.com.au (Astan Chee) Date: Fri, 01 Feb 2008 11:01:40 +1100 Subject: wxEVT_SCROLL_ENDSCROLL In-Reply-To: <151424.10138.qm@web35309.mail.mud.yahoo.com> References: <151424.10138.qm@web35309.mail.mud.yahoo.com> Message-ID: <47A26164.30109@al.com.au> try wx.EVT_SCROLL_ENDSCROLL ? Jack Holt wrote: > Hello, > > I got the following error: > > Traceback (most recent call last): > File "vplayer.py", line 15, in ? > File "config.pyo", line 3, in ? > File "wx\__init__.pyo", line 44, in ? > File "wx\_core.pyo", line 3592, in ? > AttributeError: 'module' object has no attribute > 'wxEVT_SCROLL_ENDSCROLL' > > > I never had that error before... until I messed up > with the python package > (I had to reinstall Active Python + py2exe + > wxpython). I can run my app > from the SVN with no problem. I get the error from the > compiled version - > made with py2exe. > > Line 3 in config.py points to: Import wx > > > > Help!! > > Thanks, > -Dan > > > > ____________________________________________________________________________________ > Looking for last minute shopping deals? > Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping > Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. From petr.jakes.tpc at gmail.com Tue Jan 1 23:11:12 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Tue, 1 Jan 2008 20:11:12 -0800 (PST) Subject: Newbie: Why doesn't this work References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> <13nldkj6ecl4j31@corp.supernews.com> Message-ID: Steven, thanks for a nice explanation. I am trying to experiment a little bit with new-style class and I am confused why following example always returns 0 (zero). I was expecting will return values from 0 to 9 and finaly an Exception. class GenExample(object): def getInfo(self): for no in range(10): yield no myNo=property(getInfo) gen=GenExample() print gen.myNo.next() print gen.myNo.next() . . print gen.myNo.next() -- Petr Jakes From arnodel at googlemail.com Tue Jan 22 13:55:55 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 22 Jan 2008 10:55:55 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Jan 22, 6:34?pm, Paddy wrote: [...] > Hi George, > You need to 'get it right' first. Micro optimizations for speed > without thought of the wider context is a bad habit to form and a time > waster. > If the routine is all that needs to be delivered and it does not > perform at an acceptable speed then find out what is acceptable and > optimise towards that goal. My questions were set to get posters to > think more about the need for speed optimizations and where they > should be applied, (if at all). > > A bit of forethought might justify leaving the routine alone, or > optimising for readability instead. But it's fun! Some-of-us-can't-help-it'ly yours -- Arnaud From hniksic at xemacs.org Fri Jan 4 10:05:58 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 04 Jan 2008 16:05:58 +0100 Subject: Details about pythons set implementation References: Message-ID: <87bq818wbt.fsf@mulj.homelinux.net> Achim Domma writes: > I'm interested in details about how sets are implemented in python. > They seem to be quite fast and I found some remarks who state, that > the implementation is highly optimized. I need to implemented sets > in C/C++ and need a starting point on how to do it right. Could > somebody give me a starting point? You can simply look at the implementation, Objects/setobject.c in the Python source code. Most that it's mostly copy-paste from the dict implementation (dictobject.c) and that both are quite involved and optimized for the use by Python. They're not general implementation of sets from use in C. The "highly optimized" remarks should be understood in the context of Python, not in the context of other C and C++ set libraries. I don't know how well Python sets compare to other set libraries, but I doubt that it's much faster than the median (which "highly optimized" could be understood to imply). BTW if you're using C++, why not simply use std::set? If you need it called from C, you can wrap the needed methods in a C-accessible API. From nick at craig-wood.com Fri Jan 4 09:30:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 04 Jan 2008 08:30:05 -0600 Subject: Why python says "unexpected parameter 'mini.py'" for my code? References: Message-ID: oyster wrote: > The following is my pure-python wxwidgets test. It is hardly pure python since it depends on wxWindows and ctypes... > It runs and give a frame, but soon python comes up to say > "unexpected parameter > 'mini.py'" and I have to close it. > I cannot find the reason. Can somebody give me a hint to let it work > well? Thanks I tried it but it doesn't work at all on linux. I suggest you use wxPython and stop re-inventing the wheel! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ajaksu at gmail.com Sun Jan 27 17:58:23 2008 From: ajaksu at gmail.com (ajaksu) Date: Sun, 27 Jan 2008 14:58:23 -0800 (PST) Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> <92e093d4-e094-481c-84b3-82a677bbe70d@v17g2000hsa.googlegroups.com> Message-ID: <7d1d4b80-3d54-4bf7-8393-3fb2cf97f674@v67g2000hse.googlegroups.com> This message got huge :/ Sorry for being so cryptic and unhelpful. I now believe that you're incurring in a (quite deep) misunderstanding and wish to make things clear for both of us :) On Jan 27, 6:58 am, o... at thepond.com wrote: > On Fri, 25 Jan 2008 17:44:07 -0800 (PST), ajaksu > wrote: > > > > >On Jan 25, 11:36 pm, ajaksu wrote: > >> On Jan 25, 11:10 pm, o... at thepond.com wrote: > >[...] > > >Gaah, is this what's going on? > > >ajaksu at Belkar:~$ cat error.txt > >This is not assembler... > > >ajaksu at Belkar:~$ ndisasm error.txt > >00000000 54 push sp > >00000001 686973 push word 0x7369 > >00000004 206973 and [bx+di+0x73],ch > >00000007 206E6F and [bp+0x6f],ch > >0000000A 7420 jz 0x2c > >0000000C 61 popa > >0000000D 7373 jnc 0x82 > >0000000F 656D gs insw > >00000011 626C65 bound bp,[si+0x65] > >00000014 722E jc 0x44 > >00000016 2E db 0x2E > >00000017 2E db 0x2E > >00000018 0A db 0x0A > > >:/ > > not sure what you're saying. Sure looks like assembler to me. Take the > '54 push sp'. The 54 is an assembler opcode for push and the sp is > the stack pointer, on which it is operating. What I did above was: 1- create a file called "error.txt" that contains the string "This is not assembler..." 2- show the contents of the file ("cat" being the relevant command) 3- run the NetWideDisassembler (ndisasm) on error.txt 4- watch as it "disassembled" the text file (in fact, "assembling" the code above reconstructs part of the string!) 5- conclude that you were misguided by this behavior of disassemblers, for AFAIK .pyc files contain Python "opcodes" (bytecode), that in no way I can think of could be parsed by a generic disassembler 6- form a belief that you were trying to understand meaningless "assembler" like the above (that would have no bearing on what Python does!) Now, it seems that we're in flaming mode and that is unfortunate, because I do believe in your expertise. In part, because my father was a systems analyst for IBM mainframes and knows (a huge) lot about informatics. However, I've seen him, due to simple misunderstandings like this, building a complex scenario to explain his troubles with MSWord. I believe this is what's happening here, so I suggest that we take a step back and stop calling names. Given that you're in the uncomfortable place of the "troll assigned by votes" outsider in this issue, let me expose some relevant data. The people you're pissed off with (and vice-versa) are very competent and knowledgeable Python (and other languages) programmers, very kind to newcomers and notably helpful (as you might find out lurking in this newsgroup or reading the archives). They spend time and energy helping people to solve problems and understand the language. Seriously, they know about assembler (a lot more than I do) and how Python works. And they know and respect each other. Now, your attitude and faith in your own assumptions (of which, "the .pyc contains assembler" in special) was both rude and upsetting. This doesn't mean that you're not an assembler expert (I believe you are). But it seemed like you were trying to teach us how Python works, and that was considered offensive, specially due to your words. OTOH, my responses were cryptic, unhelpful and smell of "mob thinking". While Steven D'Aprano and others showed a lot more of patience and willingness to help. So please forgive me and please PAY ATTENTION to those trying to HELP and make things clearer to you. As a simple example of my own e Dunning-Kruger effect, I was sure I'd get errors on trying to "assemble" the output of the disassembling, but it does roundtrip part of the string and I was baffled. I'd guess you know why, I have no idea. The 0x74 finding was also curious, you are indeed getting part of the binary format of bytecode, but (AFAICT) you won't find real assembler there. In summary, you can show us what you know and put your knowledge (instead of what you got wrong and how you upset people) in focus. Try to set things right. Believe me, this here community packs an uncommon amount of greatness and openness. HTH, Daniel From sour.craig at gmail.com Fri Jan 11 11:31:24 2008 From: sour.craig at gmail.com (Craig Ward) Date: Fri, 11 Jan 2008 11:31:24 -0500 Subject: Fwd: newbie question regarding int(input(:)) - sorry for the spam Message-ID: <275866c0801110831sbe97615ic96af03c3473f2d1@mail.gmail.com> sorry for the spam Here is the complete message! I am trying to write a menu script that will execute bash scripts. Everything is fine until the script executes and I want to see if there are any more options to run before quitting. Example: ================================================= def menu(opt1 = "something", opt2 = "something else"): print "1)", opt1 "" print "2)", opt2"" def anythingelse(opt 3 = "final check"): menu() print "3)", opt3"" menu() choice = int(input(":")) if choice == 1 command anythingelse() elif choice == 2 command 2 anythingelse() else choice ==3 command 3 quit ======================================= My newbie problem is that although the menu repeats there is no chance to have a second input and I can't put the int(input(":") in the function because I get the error 'int' is not callable plus my choice variable is not defined. can someone please enlighten me? :-) ---------- Forwarded message ---------- From: Craig Ward Date: Jan 11, 2008 11:21 AM Subject: newbie question regarding int(input(:)) To: python-list at python.org Hi experts! I am trying to write a menu script that will execute bash scripts. Everything is fine until the script executes and I want to see if there are any more options to run before quitting. Example: def menu(opt1 = "something", opt2 = "something else"): -- Computers are like air conditioners. They stop working when you open Windows. -- Computers are like air conditioners. They stop working when you open Windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Jan 8 10:45:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 Jan 2008 16:45:01 +0100 Subject: stupid/style/list question In-Reply-To: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> References: <89836bd5-eb16-486c-81ed-1d5387b333cd@c23g2000hsa.googlegroups.com> Message-ID: Giampaolo Rodola' wrote: > To flush a list it is better doing "del mylist[:]" or "mylist = []"? > Is there a preferred way? If yes, why? The latter creates a new list object, the former modifies an existing list in place. The latter is shorter, reads better, and is probably a bit faster in most cases. The former should be used when it's important to clear a specific list object (e.g. if there are multiple references to the list). From emin.shopper at gmail.com Thu Jan 3 17:09:03 2008 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Thu, 3 Jan 2008 17:09:03 -0500 Subject: choosing random dynamic port number Message-ID: <32e43bb70801031409o5d1dcd2at5a159339cd43ae52@mail.gmail.com> Dear Experts, Is there a good way to choose/assign random dynamic port numbers in python? I had in mind something like the following, but if multiple programs are generating random port numbers, is there a way to check if a given port number is already taken? def GenerateDynamicPortNumber(): "Generate a random dynamic port number and return it." # port numbers between 49152 to 65535 are dynamic port numbers return 49152 + random.randrange(15000) -------------- next part -------------- An HTML attachment was scrubbed... URL: From cokofreedom at gmail.com Fri Jan 11 04:06:16 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 11 Jan 2008 01:06:16 -0800 (PST) Subject: python recursive function References: Message-ID: <33eeba3f-701c-40a3-bb71-fb3fd94b877e@e6g2000prf.googlegroups.com> On Jan 11, 9:46 am, Gary Herron wrote: > Tom_chicollegeboy wrote: > > here is what I have to do: > > > This question involves a game with teddy bears. The game starts when I > > give you some bears. You then start giving me back some bears, but you > > must follow these rules (where n is the number of bears that you > > have): > > This sounds very much like a homework assignment, and so should probably > not be answered here. (Neither should it have been asked here.) If, > in your attempt to write this program, you have some questions about > Python, then I encourage to ask those questions here. > > Gary Herron > > > If n is even, then you may give back exactly n/2 bears. (Hint: To test > > whether n is even, use the expression ((n % 2) == 0).) > > If n is divisible by 3 or 4, then you may multiply the last two digits > > of n and give back this many bears. (By the way, the last digit of n > > is n%10, and the next-to-last digit is (n%100)/10; this rule may not > > be used if either of the last two digits is 0.) > > > If n is divisible by 5, then you may give back exactly 42 bears. > > The goal of the game for you is to end up with EXACTLY 42 bears. > > > For example, suppose that you start with 250 bears. Then you could > > make these moves: > > > Start with 250 bears. > > Since 250 is divisible by 5, you may return 42 of the bears, leaving > > you with 208 bears. > > Since 208 is even, you may return half of the bears, leaving you with > > 104 bears. > > Since 104 is even, you may return half of the bears, leaving you with > > 52 bears. > > Since 52 is divisible by 4, you may multiply the last two digits > > (resulting in 10) and return these 10 bears. This leaves you with 42 > > bears. > > You have reached the goal! > > Now, you are to write a program that, if I give you n bears, returns > > true if it is at all possible for you to win the game. Your program > > must use recursion to check all possible ways in which you can apply > > the rules. > > > Usage: > > >>>> bears(42) > > > True > > >>>> bears(250) > > > True > > >>>> bears(50) > > > False > > >>>> bears(84) > > > True > > >>>> bears(41) > > > False > > > As you see my program must use recursion. > > > I came up with this idea but I am not sure if its right or are there > > any minor errors that I can easily fix: > > > def bears (n): > > if n==42: > > return True > > if n%5==0: > > bears(n-42) > > if n%2==0: > > bears(n/2) > > if n%3==0 or n%4==0: > > one = (n%10) > > two = ((n%100)/10) > > if one!=0 and two!=0: > > bears(n-(one*two)) > > return False > > > If a game hits 42 it should return True, otherwise False. If program > > never hits 42 and return True, then it returns False. I figured out > > base case, but I still get False when I enter bears(250). Any help > > would be very appreciated! Note that for ; if one!=0 and two!=0: you can use if one and two: which is my pythonic. Also in your example with 52, shouldn't it divide by even first? Obviously this must not happen, thus maybe you should run a check that when you are returning a new value it does not go below 42? Frankly this looks like a terrible way to use recursion. From fredrik at pythonware.com Sat Jan 12 14:35:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Jan 2008 20:35:58 +0100 Subject: IDLE won't start in Python 2.5 for Windows In-Reply-To: <57a7e4a2-0acc-4439-9bd6-d96862ffc22e@j78g2000hsd.googlegroups.com> References: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> <13ogqhlds0tbsac@corp.supernews.com> <57a7e4a2-0acc-4439-9bd6-d96862ffc22e@j78g2000hsd.googlegroups.com> Message-ID: mikez302 wrote: > I opened a command window in my Python25 folder and tried typing > pythonw. I just got another command prompt as if the program ran but > didn't do anything. It looked like this: > > C:\Python25>pythonw > > C:\Python25> "pythonw" is the console-less version of the Python runtime, so that's expected. Try using "python" instead. From sjmachin at lexicon.net Sun Jan 27 16:50:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 27 Jan 2008 13:50:15 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> Message-ID: On Jan 28, 7:47 am, "Mark Tolonen" wrote: > >"John Machin" wrote in message > >news:eeb3a05f-c122-4b8c-95d8-d13741263374 at h11g2000prf.googlegroups.com... > >On Jan 27, 9:17 pm, glacier wrote: > >> On 1?24?, ??3?29?, "Gabriel Genellina" > >> wrote: > > >*IF* the file is well-formed GBK, then the codec will not mess up when > >decoding it to Unicode. The usual cause of mess is a combination of a > >human and a text editor :-) > > SAX uses the expat parser. From the pyexpat module docs: > > Expat doesn't support as many encodings as Python does, and its repertoire > of encodings can't be extended; it supports UTF-8, UTF-16, ISO-8859-1 > (Latin1), and ASCII. If encoding is given it will override the implicit or > explicit encoding of the document. > > --Mark Thank you for pointing out where that list of encodings had been cunningly concealed. However the relevance of dropping it in as an apparent response to my answer to the OP's question about decoding possibly butchered GBK strings is .... what? In any case, it seems to support other 8-bit encodings e.g. iso-8859-2 and koi8-r ... C:\junk>type gbksax.py import xml.sax, xml.sax.saxutils import cStringIO unistr = u''.join(unichr(0x4E00+i) + unichr(ord('W')+i) for i in range(4)) print 'unistr=%r' % unistr gbkstr = unistr.encode('gbk') print 'gbkstr=%r' % gbkstr unistr2 = gbkstr.decode('gbk') assert unistr2 == unistr print "latin1 FF -> utf8 = %r" % '\xff'.decode('iso-8859-1').encode('utf8') print "latin2 FF -> utf8 = %r" % '\xff'.decode('iso-8859-2').encode('utf8') print "koi8r FF -> utf8 = %r" % '\xff'.decode('koi8-r').encode('utf8') xml_template = """%s""" asciidoc = xml_template % ('ascii', 'The quick brown fox etc') utf8doc = xml_template % ('utf-8', unistr.encode('utf8')) latin1doc = xml_template % ('iso-8859-1', 'nil illegitimati carborundum' + '\xff') latin2doc = xml_template % ('iso-8859-2', 'duo secundus' + '\xff') koi8rdoc = xml_template % ('koi8-r', 'Moskva' + '\xff') gbkdoc = xml_template % ('gbk', gbkstr) for doc in (asciidoc, utf8doc, latin1doc, latin2doc, koi8rdoc, gbkdoc): f = cStringIO.StringIO() handler = xml.sax.saxutils.XMLGenerator(f, encoding='utf8') xml.sax.parseString(doc, handler) result = f.getvalue() f.close print repr(result[result.find(''):]) C:\junk>gbksax.py unistr=u'\u4e00W\u4e01X\u4e02Y\u4e03Z' gbkstr='\xd2\xbbW\xb6\xa1X\x81 at Y\xc6\xdfZ' latin1 FF -> utf8 = '\xc3\xbf' latin2 FF -> utf8 = '\xcb\x99' koi8r FF -> utf8 = '\xd0\xaa' 'The quick brown fox etc' '\xe4\xb8\x80W\xe4\xb8\x81X\xe4\xb8\x82Y\xe4\xb8\x83Z' 'nil illegitimati carborundum\xc3\xbf' 'duo secundus\xcb\x99' 'Moskva\xd0\xaa' Traceback (most recent call last): File "C:\junk\gbksax.py", line 27, in xml.sax.parseString(doc, handler) File "C:\Python25\lib\xml\sax\__init__.py", line 49, in parseString parser.parse(inpsrc) 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 xml.sax._exceptions.SAXParseException: :1:30: unknown encoding C:\junk> From kay.schluehr at gmx.net Mon Jan 28 10:02:25 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 28 Jan 2008 07:02:25 -0800 (PST) Subject: optional static typing for Python References: Message-ID: <6ddadeeb-6ca6-4456-a0d8-ba80fd8d1d17@v46g2000hsv.googlegroups.com> On 27 Jan., 23:19, "Russ P." wrote: > A while back I came across a tentative proposal from way back in 2000 > for optional static typing in Python: > > http://www.python.org/~guido/static-typing > > Two motivations were given: > > -- faster code > -- better compile-time error detection > > I'd like to suggest a third, which could help extend Python into the > safety-critical domain: > > -- facilitates automated source-code analysis > > There has been much heated debate in the past about whether Python is > appropriate for safety-critical software. Some argue that, with > thorough testing, Python code can be as reliable as code in any > language. Well, maybe. But then, a famous computer scientist once > remarked that, > > "Program testing can be used to show the presence of bugs, but never > to show their absence!" --Edsger Dijkstra > > The next step beyond extensive testing is automated, "static" analysis > of source-code ("static" in the sense of analyzing it without actually > running it). For example, Spark Ada is a subset of Ada with > programming by contract, and in some cases it can formally prove the > correctness of a program by static analysis. > > Then there is Java Pathfinder (http://javapathfinder.sourceforge.net), > an "explicit state software model checker." The developers of JPF > wanted > to use it on a prototype safety-critical application that I wrote in > Python, but JPF only works on Java code. We considered somehow using > Jython and Jythonc, but neither did the trick. So they ended up having > someone manually convert my Python code to Java! (The problem is that > my code was still in flux, and the Java and Python versions have now > diverged.) > > In any case, optional static typing in Python would help tremendously > here. The hardest part of automated conversion of Python to a > statically typed language is the problem of type inference. If the > types are explicitly declared, that problem obviously goes away. > Explicit typing would also greatly facilitate the development of a > "Python Pathfinder," so the conversion would perhaps not even be > necessary in the first place. > > Note also that, while "static" type checking would be ideal, > "explicit" typing would be a major step in the right direction and > would probably be much easier to implement. That is, provide a syntax > to explicitly declare types, then just check them at run time. A > relatively simple pre-processor could be implemented to convert the > explicit type declarations into "isinstance" checks or some such > thing. (A pre-processor command-line argument could be provided to > disable the type checks for more efficient production runs if > desired.) > > I noticed that Guido has expressed further interest in static typing > three or four years ago on his blog. Does anyone know the current > status of this project? Thanks. It has been withdrawn in its original version. What's left is annotation syntax and the __annotation__ dict ( I don't know what the latter is good for but maybe some purpose emerges once a complete signature object is provided? ). So there has not been much work spent on hybrid type systems, static analysis and type directed native compilation. I did some work on type feedback and created a Python dialect called TPython a while ago based on Python 3.0 but supporting more syntax to add also local type annotations and an 'A of T' construct for type parametricity. The main purpose of TPython was to provide an interface for 3rd party tools used for refactoring, type checking, compilation, documentation etc. without separating annotations from Python code but build them in place. This project is unpublished and on hold because it is part of EasyExtend 2.0 and I reworked EE to incorporate a brand new parser generator called Trail that involved quite some research from my side. EasyExtend 3 is intended to be released in Q2. Regards From bignose+hates-spam at benfinney.id.au Tue Jan 1 23:17:54 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 02 Jan 2008 15:17:54 +1100 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> <87r6h1b2kx.fsf@benfinney.id.au> <87bq85rp2d.fsf@physik.rwth-aachen.de> Message-ID: <87abnoc13h.fsf@benfinney.id.au> Torsten Bronger writes: > [...] the width of a tab is nowhere defined. It really is a matter > of the editor's settings. RFC 678 "Standard File Formats" : Horizontal Tab Moves the printer to the next horizontal tab stop. The conventional stops for horizontal tabs are every eight characters, that is character positions 9, 17, 25, ... within the logical page. Note that it is difficult to enforce these conventions and it is therefore recommended that horizontal tabs not be used in document files. > I, for example, dislike too wide indenting. I use four columns in > Python and two in Delphi. However, there are Python projects using > eight spaces for each indentation level. How many columns to indent source code is an orthogonal question to how wide an ASCII TAB (U+0009) should be rendered. The former question is open to matters of style; the latter at least is standardised, even given the caveats about enforcement. > If all Python code used tabs, eveybody could use their own > preferences, for both reading and writing code, and interoperability > would be maintained nevertheless. Interoperability isn't the only criterion though. On the contrary, source code is primarily for reading by programmers, and only incidentally for reading by the compiler. -- \ "I hate it when my foot falls asleep during the day, because | `\ that means it's gonna be up all night." -- Steven Wright | _o__) | Ben Finney From msj at infoserv.dk Tue Jan 29 09:21:46 2008 From: msj at infoserv.dk (Martin Skou) Date: Tue, 29 Jan 2008 15:21:46 +0100 Subject: Executing other python code In-Reply-To: References: <2667f9ae-6ba5-4b86-9b32-9f110d6cf5cd@s19g2000prg.googlegroups.com> Message-ID: <479f3618$0$2088$edfadb0f@dtext02.news.tele.dk> Over-simplified yes, but it will work! Python is beautiful :-) From steveo at syslang.net Mon Jan 28 13:06:16 2008 From: steveo at syslang.net (Steven W. Orr) Date: Mon, 28 Jan 2008 13:06:16 -0500 (EST) Subject: Question on importing wxPython Message-ID: python-2.3.5 wx-2.6 I just bought the wxPython In Action book and I see that all the examples say to import wx All of our pre-existing code was horribly doing a from wxPython import * I changed all the code so that it was doing an import wx and found that everything was broken. In particular, references to wxNewId would fail. 634 > python Python 2.3.5 (#2, May 4 2005, 08:51:39) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import wx >>> wx.wxNewId Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'wxNewId' >>> In fact, the *only* way to get it was to go back to import wxPython and then refer to it as wxPython.wx.wxNewId Is my system broken or am I missing something? i.e., should I be able to say import wx? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From lists at cheimes.de Wed Jan 23 02:51:13 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 23 Jan 2008 08:51:13 +0100 Subject: bags? 2.5.x? In-Reply-To: References: Message-ID: Dan Stromberg wrote: > Is there a particular reason why bags didn't go into 2.5.x or 3000? > > I keep wanting something like them - especially bags with something akin > to set union, intersection and difference. Ask yourself the following questions: * Is the feature useful for the broad mass? * Has the feature been implemented and contributed for Python? * Is the code well written, tested and documented? * Is the code mature and used by lots of people? Can you answer every question with yes? Christian From yuxi at ece.gatech.edu Sat Jan 19 08:57:24 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Sat, 19 Jan 2008 08:57:24 -0500 Subject: Core Python Programming . . . In-Reply-To: <0005f532-409b-4c4e-8483-b2e32bbc724a@q77g2000hsh.googlegroups.com> References: <7xir1q29j5.fsf@ruckus.brouhaha.com> <0005f532-409b-4c4e-8483-b2e32bbc724a@q77g2000hsh.googlegroups.com> Message-ID: FireNWater wrote: > I guess I'm not fully up to speed on what constitutes an IP address. > Does the term 'octet' refer to an 8-bit (xFF) number? Yes, it somewhat archaic though. It's used when "byte" is ambiguous. On some ancient (by computing standards) computers, the size of a byte may be as small as 6 bits or as big as 9. For the purposes of this question, I think it's safe to assume an IP address is just a 32-bit number. And you need to extract each group of 8-bits and print those out with dots between them. From ckimyt at gmail.com Fri Jan 4 08:45:22 2008 From: ckimyt at gmail.com (Mike) Date: Fri, 4 Jan 2008 05:45:22 -0800 (PST) Subject: Strange varargs issue Message-ID: I'm not sure if this is a bug or if I'm just not understanding something correctly. I'm running the following (broken.py) on ActivePython 2.5.1.1, based on Python 2.5.1 (r251:54863 5/1/2007) as "python broken.py foo" (on Windows, of course): #!/bin/env python import sys class foobar(object): def func(arg): print 'foobar.func: %r' % arg __f = foobar() def caller(a): print 'caller: %r' % a __f.func(a) def main(): rest = sys.argv[1:] print 'main: %r' % rest caller(*rest) if __name__ == '__main__': main() ...and the result of running this ("python broken.py foo") is: main: ['foo'] caller: 'foo' Traceback (most recent call last): File "broken.py", line 21, in main() File "broken.py", line 18, in main caller(*rest) File "broken.py", line 13, in caller __f.func(a) TypeError: func() takes exactly 1 argument (2 given) How can this possibly be? The "caller" print statement obviously shows "a" is singular. Thanks in advance for any and all insight... Mike From ajaksu at gmail.com Sat Jan 5 11:57:35 2008 From: ajaksu at gmail.com (ajaksu) Date: Sat, 5 Jan 2008 08:57:35 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> Message-ID: <2ab22f95-d132-4e3c-8b68-bcbcee64e2ef@j78g2000hsd.googlegroups.com> Hi there :) On Jan 5, 2:14 pm, c... at mailinator.com wrote: > On Jan 5, 5:07 pm, c... at mailinator.com wrote: > > > Hello, Paul and Arnaud. > > While I think about your answers: do you think there is any way to > > avoid shuffle? > > It may take unnecessary long on a long list most of whose elements > > have the property. I've been thinking about this one before you asked and only got a bad solution: you don't need to shuffle the list if you can construct a random list of indexes to loop through, but my timings show that I can't do that faster than "shuffle(range(x))" for worst cases (i.e., iterate thru the whole list) :) The rather good news is that shuffling a list of arbitrary objects is pretty fast (as compared to a list of integers). OTOH, if you do know that the chances are high enough, you can try choosing items randomly without substitution (adapted from random.py's sample): from random import random def randpickuntil(lst, prop=bool): selected = set() for i in xrange(len(lst)): j = int(random() * n) while j in selected: j = int(random() * n) if prop(lst[j]): return lst[j] selected_add(j) > Umm... > You provide nice answers in the case many elements are picked from the > same list. > Any ideas for the case when the picker is called many times on a > program, but never twice with the same list? If the lists share items, a cache could help a lot. Otherwise, you'd benefit more from finding a good way to test the property (could you give a hint on what it is?). How do objects acquire that property, is it a sum of independent factors? HTH, Daniel From devraj at gmail.com Thu Jan 10 21:44:34 2008 From: devraj at gmail.com (Devraj) Date: Thu, 10 Jan 2008 18:44:34 -0800 (PST) Subject: open excel file while it is being used. References: Message-ID: <3305cad1-a17b-4b95-98ce-04ac2e420dfb@s19g2000prg.googlegroups.com> Hi Barry, Obviously what you are trying to do is detect file locks. I am not exactly sure how to do this in Python but from previous system administration jobs here are some scenarios that you might want to watch out for. - I know for one that if you are accessing the file on a Samba share, file locking with OpenOffice or Excel have strange things happen to them - I am also aware that the same thing works different if the files are shared from a Windows server and accessed on a Linux machine, and depends on the version of Samba/Linux kernel you are running On Jan 11, 7:38 am, barry.z... at gmail.com wrote: > Hi, > > I have a python program that constantly updates an excel spreadsheet. > I would like to be able to view its updates while using excel to edit > other excel files. Below are the test codes I have: > > -------------------------------------------------------------------------------------- > from time import sleep > import win32com.client as w32c > > def test(): > w32c.pythoncom.CoInitialize() > print w32c.pythoncom._GetInterfaceCount() > app1 = w32c.Dispatch("Excel.Application") > #app1.Visible=False > #app1.Interactive = False > wb=app1.Workbooks.Open("c:\\temp\\Book1.xls") > > sleep(3) > sh=wb.Sheets("Sheet1") > sh.Cells(2,1).Value = "Hello, world!" > sh = None > > wb.Save() > wb = None > app1 = None > w32c.pythoncom.CoUninitialize() > print w32c.pythoncom._GetInterfaceCount() > ------------------------------------------------------------------------------------- > > If the user just looks at the file then it's fine, but if the user > double clicks one cell, which will have a cursor flashing in the cell, > then it will lead to a crash of the program with error: "Call was > rejected by callee." I can make the program keep trying to access the > file, but if the user doesn't make the flashing cursor disappear, the > program will wait forever! > > I know excel has the fuction such that when a user is accessing a file > and other users open that file, it will prompt for options of opening > it as read-only or sending notification. I have been trying to > implement that in the program, but don't know how. > > So, any suggestion will be greatly appreciated! > > - Barry From mobiledreamers at gmail.com Mon Jan 14 01:49:39 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Sun, 13 Jan 2008 22:49:39 -0800 Subject: Recieving emails in python In-Reply-To: References: Message-ID: ok i dont want to write an mta i want to use another mta to recieve emails on say - python at mygrouplist.com so can i start reading the emails to python from that mta How to set this up to read messages from the mta sending out email we are using sendmail so we ll continue using that for now thanks It depends. If you're trying to write a MTA, think about looking at and stealing parts of mailmain and smtpd.py Mailman: http://www.gnu.org/software/mailman/index.html Smtpd:http://barry.warsaw.us/software/Code/smtpd.py If you're going to use someone else as a MTA then just use IMAP or POP to get the mail out, there are IMAP and POP libraries imap: http://docs.python.org/lib/module-imaplib.html pop: http://docs.python.org/lib/module-poplib.html Else, if you're writing this all from scratch, whip out the RFC and start hacking: http://info.internet.isi.edu/in-notes/rfc/files/rfc821.txt --Michael On 1/13/08, mobiledreamers at gmail.com wrote: > > I m trying to create something simple a mailing list similar to yahoo > groups > I m stumbling at the part where the python recieves messages via say > python at yahoogroups.com > > how to make python recieve emails and process it > after that it is straight forward processing in python inserting in db etc > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Sun Jan 6 22:55:44 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 Jan 2008 03:55:44 -0000 Subject: Should HTML entity translation accept "&"? References: <47817BDC.7020707@animats.com> <87tzlqo2a4.fsf@benfinney.id.au> Message-ID: On Mon, 07 Jan 2008 12:25:07 +1100, Ben Finney wrote: > John Nagle writes: > >> For our own purposes, I rewrote "htmldecode" to require a sequence >> ending in ";", which means some bogus HTML escapes won't be recognized, >> but correct HTML will be processed correctly. What's general opinion of >> this behavior? Too strict, or OK? > > I think it's fine. In the face of ambiguity (and deviation from the > published standards), refuse the temptation to guess. That's good advice for a library function. But... > More specifically, I don't see any reason to contort your code to > understand some non-entity sequence that would be flagged as invalid by > HTML validator tools. ... it is questionable advice for a program which is designed to make sense of invalid HTML. Like it or not, real-world applications sometimes have to work with bad data. I think we can all agree that the world would have been better off if the major browsers had followed your advice, but given that they do not, and thus leave open the opportunity for websites to exist with invalid HTML, John is left in the painful position of having to write code that has to make sense of invalid HTML. I think only John can really answer his own question. What are the consequences of false positives versus false negatives? If it raises an exception, can he shunt the code to another function and use some heuristics to make sense of it, or is it "game over, another site can't be analyzed"? -- Steven From sjmachin at lexicon.net Wed Jan 9 14:53:32 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 9 Jan 2008 11:53:32 -0800 (PST) Subject: printing dots in simple program while waiting References: Message-ID: On Jan 10, 6:30 am, John wrote: > On Jan 9, 12:14 pm, "Reedick, Andrew" wrote: > > > > > > -----Original Message----- > > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > > list-bounces+jr9445=att.... at python.org] On Behalf Of Martin Marcher > > > Sent: Wednesday, January 09, 2008 11:57 AM > > > To: python-l... at python.org > > > Subject: Re: printing dots in simple program while waiting > > > > John wrote: > > > > > import time > > > > s = '.' > > > > print 'working', # Note the "," at the end of the line > > > > while True: > > > > print s > > > > time.sleep(1) > > > > see my comment in the code above... > > > > if that's what you mean > > > Bah. The trailing command may prevent the newline, but it appends a > > space whether you want it or not.[1] Use sys.stdout.write('.') instead. > > > import sys > > > print "wussy nanny state, tax 'n spend my spaces, liberal comma:" > > for i in range(1, 10): > > print '.', > > print > > print "manly neo-con I know what's Right so keep your government out of > > my strings! print:" > > for i in range(1, 10): > > sys.stdout.write('.') > > > [1] Which has to be _the_ most annoying feature of Python. *grrr* > > > ***** > > > 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 > > Thanks for all of the help. This is what ended up working: > > import time > import sys > > s = '.' > sys.stdout.write( 'working' ) > while True: > sys.stdout.write( s ) > sys.stdout.flush() > time.sleep(0.5) For your next trick, write a "spinner" using |/-\ in succession :-) From leon at pasde.spam.fr Tue Jan 1 10:21:51 2008 From: leon at pasde.spam.fr (Leon) Date: Tue, 01 Jan 2008 16:21:51 +0100 Subject: TK 8.5 References: Message-ID: > We are planing to use Tcl/Tk 8.5 for Python 2.6 and 3.0. The topic is > currently being discussed but nothing has been decided yet. Great news! I hope you'll decide to use Tcl/Tk 8.5 ! I'm sure I'm not the only one !!! On this page : http://www.python.org/dev/peps/pep-0361/ We can read : "the initial 2.6 target is for April 2008" Great ! But I found nothing about Tk 8.5 ? Leon From joejacob21 at gmail.com Thu Jan 24 06:25:06 2008 From: joejacob21 at gmail.com (joe jacob) Date: Thu, 24 Jan 2008 03:25:06 -0800 (PST) Subject: Designing website Message-ID: <248758f0-6d8b-4e91-9c3c-a6a0314bebcb@q77g2000hsh.googlegroups.com> Hi All, I am planning to design a website using windows, apache, mysql, python. But I came to know that python cgi is very slow. I came across mod_python also but no good documentation are available for learning mod_python. Suggest me a good solution for this as I don't know other languages like PHP; I prefer python. From mitko at qlogic.com Fri Jan 11 18:54:16 2008 From: mitko at qlogic.com (Mitko Haralanov) Date: Fri, 11 Jan 2008 15:54:16 -0800 Subject: Import and execfile() In-Reply-To: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> References: <7a2f3d08-70d6-476b-9108-c96efe5c33cd@j20g2000hsi.googlegroups.com> Message-ID: <20080111155416.7a008755@opal.mv.qlogic.com> On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis wrote: > # trying to set the configuration: > CFG = {} > execfile('path/to/some_config.py', CFG) > > Traceback (most recent call last): > ... > ImportError: No module named master_config > > > I understand why this fails but I'm not sure how to tell execfile() to > set the path accordingly. Any ideas ? This might be overly simplistic but you could have a load_config function which takes the path to the config file and the variable where to load the config as arguments. In the load_config function, you could get the directory part of the config file path, appending it to sys.path, load the config, and then remove the newly added directory from sys.path. -- Mitko Haralanov From hinds.ja at gmail.com Wed Jan 2 16:01:23 2008 From: hinds.ja at gmail.com (hinds.ja at gmail.com) Date: Wed, 2 Jan 2008 13:01:23 -0800 (PST) Subject: Insert to a clob field using cx_Oracle via a stored procedure Message-ID: <87860f02-9c78-4248-8d30-c13c91a59f00@i29g2000prf.googlegroups.com> Hello, Does anyone have experience using cx_Oracle to call a stored procedure that inserts to a clob field? We have done this successfully via straight SQL, but we are at a loss on how to do the same insert using a stored procedure call. Any assistance would be much appreciated. Thanks. Jason From steve at REMOVE-THIS-cybersource.com.au Mon Jan 28 03:09:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 28 Jan 2008 08:09:45 -0000 Subject: Using a dict as if it were a module namespace References: <13podkpqqvef674@corp.supernews.com> Message-ID: <13pr3e9bqgt3t81@corp.supernews.com> On Sun, 27 Jan 2008 10:04:06 -0500, Ross Ridge wrote: > I think this is the way to go as it follows the principle of "say what > you mean." You can however simplify it, and repeat yourself less, by > using the extended call syntax: > > expr = "myfunc(**test)" > setup = """from __main__ import myfunc, test""" Ah, also good thinking! I'd have to modify it, because the tests carry other information which shouldn't be passed to the test function, but that's a simple modification. Thanks to all who replied. -- Steven From bronger at physik.rwth-aachen.de Mon Jan 28 06:54:12 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 28 Jan 2008 12:54:12 +0100 Subject: optional static typing for Python References: <479da584$0$25625$426a74cc@news.free.fr> <69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com> Message-ID: <87d4rm88t7.fsf@physik.rwth-aachen.de> Hall?chen! Russ P. writes: > On Jan 28, 1:51 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Russ P. a ?crit :> A while back I came across a tentative proposal from way > back in 2000 >> > for optional static typing in Python: >> >> (snip) >> >>> In any case, optional static typing in Python would help >>> tremendously here. The hardest part of automated conversion of >>> Python to a statically typed language is the problem of type >>> inference. If the types are explicitly declared, that problem >>> obviously goes away. >> >> (snip) >> >>> Note also that, while "static" type checking would be ideal, >>> "explicit" typing would be a major step in the right direction >> >> Lord have mercy(tm). > > What is that supposed to mean? So you haven't understood him. Then why is this rant following? Anyway, I can only speak for myself: I have the concern that any (albeit optional) declaring of types in Python leads to people thinking that their code is more valuable with such declarations. Mostly you know which type is to be expected after all. As a result, you see such declarations everywhere, whether helpful or not. Maybe eventually tools such as pylint will even give a percentage how many parameters are annotated, and people try to maximize this value. Ugh. Then, Python is not as useful anymore because readability falls drastically. Moreover, there is a Fortran saying: "One person's constant is another person's variable." The same applies to types in Python. Pythons is one way, Ada another way; there is no silver bullet. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From jitender001001 at gmail.com Thu Jan 17 23:12:00 2008 From: jitender001001 at gmail.com (jitender001001 at gmail.com) Date: Thu, 17 Jan 2008 20:12:00 -0800 (PST) Subject: plz help how to print python variable using os.system() References: <78444c3a-17dc-4912-aac7-39253648d86f@u10g2000prn.googlegroups.com> Message-ID: <0d32c730-9fa6-492f-ac92-af4f83f55331@e23g2000prf.googlegroups.com> Thanks Lutz....... From gagsl-py2 at yahoo.com.ar Wed Jan 23 17:06:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 20:06:51 -0200 Subject: get the size of a dynamically changing file fast ? References: <198fd91f-912b-4f56-a840-af96225125a7@c23g2000hsa.googlegroups.com> <197576d1-ab36-45f2-9648-3cfab6d3a814@j20g2000hsi.googlegroups.com> <4797849A.3040002@gmail.com> Message-ID: En Wed, 23 Jan 2008 16:16:58 -0200, Stef Mientki escribi?: >>> Yes, that's a small disadavantage of using a "high-level" language, >>> where there's no flush available, and you assume it'll done >>> automatically ;-) >> >> Uhm, there is a flush method for Python's files. From "http:// >> > I was talking about a "high-level" language, in which the sending > program was written, > (Delphi, not about Python ;-) In Delphi, flush(filevar) does work. Or are you using a TFileStream or similar? -- Gabriel Genellina From alex.holkner at gmail.com Thu Jan 17 08:42:20 2008 From: alex.holkner at gmail.com (Alex Holkner) Date: Fri, 18 Jan 2008 00:42:20 +1100 Subject: ANN: pyglet 1.0 Message-ID: The first stable/production version of pyglet has been released. http://www.pyglet.org --- pyglet provides an object-oriented programming interface for developing games and other visually-rich applications for Windows, Mac OS X and Linux. Some of the features of pyglet are: * No external dependencies or installation requirements. For most application and game requirements, pyglet needs nothing else besides Python, simplifying distribution and installation. * Take advantage of multiple windows and multi-monitor desktops. pyglet allows you to use as many windows as you need, and is fully aware of multi-monitor setups for use with fullscreen games. * Load images, sound, music and video in almost any format. pyglet can optionally use AVbin to play back audio formats such as MP3, OGG/Vorbis and WMA, and video formats such as DivX, MPEG-2, H.264, WMV and Xvid. pyglet is provided under the BSD open-source license, allowing you to use it for both commercial and other open-source projects with very little restriction. Cheers Alex. From deets at nospam.web.de Mon Jan 28 13:48:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jan 2008 19:48:04 +0100 Subject: post variable In-Reply-To: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> References: <2b4a4378-7b9c-4762-9641-075d0fdc70f6@s19g2000prg.googlegroups.com> Message-ID: <606mbbF1p1kafU1@mid.uni-berlin.de> pavloutefkros at gmail.com schrieb: > sorry for creating a new post but this is totally different from the > previous one. > > Here is the problem (which is very hard to explain, so i will use a > paradigm): i submit a form and the post variable is being sent to the > page test.py. then the test.py retrieves the POST and print it to the > page. now everything is great except one thing. > > lets say i submitted the form and went to test.py and the output was > correct, then, while i'm on test.py if i reload the page, the POST > variable IS STILL THERE. > > so the output is always the POST retrieven at first. So the page keeps > on printing the POST variable retrieven at first even thought i might > have reloaded the page 1000 times. Is there any way to "empty" the > POST variable, so that at reload nothing would be the same? > > ps: so many "so" and wacky explanation, noone would understand :(. If you are reloading a page, the variables that were sent to it are re-send by the browser. I fail to see where the problem is. Reloading means reloading. Diez From spaceoutlet at gmail.com Sat Jan 26 05:26:37 2008 From: spaceoutlet at gmail.com (Alex K) Date: Sat, 26 Jan 2008 11:26:37 +0100 Subject: paging in python shell In-Reply-To: <857659.95304.qm@web32813.mail.mud.yahoo.com> References: <857659.95304.qm@web32813.mail.mud.yahoo.com> Message-ID: That seems interesting but it's not quite what I want to do. To take an example I would like to be able to do something similar to the mysql shell when its pager is set to less. Displayhook is called whenever an expression is being evaluated. I'd like to call 'less' on the ouput of a statement. Alex On 26/01/2008, gagsl-py2 at yahoo.com.ar wrote: > > --- Alex K escribi?: > > > Thank you for this interesting tip. However I'm not > > sure to know how > > to use it. It seems pydoc.pager('text') just pages > > the text passed in. > > How do I actually make the python shell use a > > different pager? > > I'm unsure of what you want. Do you want the print > statement, inside the Python interpreter, to page its > output? Write a function to page the output the way > you like, and assign it to sys.displayhook (see > http://docs.python.org/lib/module-sys.html#l2h-5124 ) > > -- > Gabriel Genellina > > > Tarjeta de cr?dito Yahoo! de Banco Supervielle. > Solicit? tu nueva Tarjeta de cr?dito. De tu PC directo a tu casa. www.tuprimeratarjeta.com.ar > -- > http://mail.python.org/mailman/listinfo/python-list > From namesagame-usenet at yahoo.com Wed Jan 2 22:12:47 2008 From: namesagame-usenet at yahoo.com (gamename) Date: Wed, 2 Jan 2008 19:12:47 -0800 (PST) Subject: Cloning Environments Message-ID: Hi, I have several machines running Linux (mostly fedora6) and Windows (mostly XP). I'm thinking of using easy_install to create as uniform an environment as possible for all of them. Cloning the environment, to put it another way. Is there a good example somewhere showing how to do this? I'm new to easy_install and relatively new to python. TIA, -T From inFocus at sl.com Tue Jan 22 20:45:22 2008 From: inFocus at sl.com (inFocus at sl.com) Date: Tue, 22 Jan 2008 20:45:22 -0500 Subject: Extract value from a attribute in a string Message-ID: Hello, I am looking for some help in reading a large text tile and extracting a value from an attribute? so I would need to find name=foo and extract just the value foo which can be at any location in the string. The attribute name will be in almost each line. Thank you for any suggestions. From doug.farrell at gmail.com Thu Jan 17 15:25:43 2008 From: doug.farrell at gmail.com (writeson) Date: Thu, 17 Jan 2008 12:25:43 -0800 (PST) Subject: handlers.SocketHandler and exceptions References: <02de2e9c-331d-45c0-afaa-578ddad55664@j78g2000hsd.googlegroups.com> Message-ID: On Jan 17, 2:45 pm, Vinay Sajip wrote: Vinay, Again, thanks for your very timely help! I was just editing the handlers.py code, and didn't really understand how that was going to work, and of course it didn't. I was just about to write to you again, and voila, you'd already responded with what I needed to know. I would have been floundering around for quite awhile before I'd have found (if ever) the change you mentioned to __init__.py. I made the changes and my logging server is working as I expected! Exceptions are being placed in the log file, complete with their tracebacks. Again, thanks very much for your help, greatly appreciated! Doug From paul at boddie.org.uk Fri Jan 18 17:54:05 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 18 Jan 2008 14:54:05 -0800 (PST) Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. References: <478FAC5A.50206@animats.com> <478ff1e6$0$85790$e4fe514c@news.xs4all.nl> <479046a5$0$36403$742ec2ed@news.sonic.net> Message-ID: <3b14e57b-9461-4e1c-9bde-fdde99f87617@z17g2000hsg.googlegroups.com> On 18 Jan, 07:32, John Nagle wrote: > > "Processing" is useful, but it uses named pipes and sockets, > not ordinary pipes. Also, it has C code, so all the usual build > and version problems apply. The pprocess module uses pickles over sockets, mostly because the asynchronous aspects of the communication only appear to work reliably with sockets. See here for the code: http://www.python.org/pypi/pprocess Unlike your approach, pprocess employs the fork system call. In another project of mine - jailtools - I use some of the pprocess functionality with the subprocess module: http://www.python.org/pypi/jailtools I seem to recall that a few things are necessary when dealing with subprocesses, especially those which employ the python executable: running in unbuffered mode is one of those things. Paul From bignose+hates-spam at benfinney.id.au Wed Jan 16 03:11:53 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jan 2008 19:11:53 +1100 Subject: no pass-values calling? References: <13or6esikdrqa33@corp.supernews.com> <873asyclo0.fsf@benfinney.id.au> Message-ID: <87y7aqb35i.fsf@benfinney.id.au> Christian Heimes writes: > Ben Finney wrote: > > The term "reference" is fine, since that's exactly how it works. > > One gets at an object via some reference, be it a name or some > > access into a container object. When an object has no more > > references to itself, it becomes a candidate for garbage > > collection. And so on. > > Thanks you, but I know exactly how Python works. I'm actually > developing CPython and PythonDotNET. Uh, okay. I didn't ask for you to flash your credentials, but if that is significant to you, be my guest. > Anyway your message doesn't help a newbie and it gives most > certainly the wrong impression. You are using words that have a > different meaning in other languages. If you explain Python w/o the > words variable, pointer, reference or call-by-value you have a much > better chance to explain it right. Trust me :) I've done my share of explaining of Python to people, and found "reference" to be exactly the right term to help the newbie understand what's happening and what they should expect. I agree with you on "variable", "pointer", and "call-by-value". Those don't describe how Python works, and thus only confuse the matter. Thus I avoid them, and correct newbies who appear to be getting confused because of those existing concepts. -- \ "I don't accept the currently fashionable assertion that any | `\ view is automatically as worthy of respect as any equal and | _o__) opposite view." -- Douglas Adams | Ben Finney From asmodai at in-nomine.org Sat Jan 12 06:37:59 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 12 Jan 2008 12:37:59 +0100 Subject: where do my python files go in linux? In-Reply-To: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> Message-ID: <20080112113759.GJ75977@nexus.in-nomine.org> -On [20080112 12:03], Jorgen Bodde (jorgen.maillist at gmail.com) wrote: >app.py calls a lot of modules in {dir}/app. Horst says the python file >goes in /usr/bin/app.py which is ok with me, but I have multiple >python files, and I decided to use an app.sh script to call my python >files. In the /usr/bin I do not see subdirs so I assume that is not >really desirable. Personally I'd be loathe to put app.py in /usr/bin. This directory is normally reserved for OS-specific binaries. For personal/system-extended stuff I'd use /usr/local/bin or whatever your system mandates. (But hey, that's the typical mentality difference between the BSD and Linux world it seems, so do with it what you want.) >Question 2. Should I use *.pyc rather then *.py files to speed up >executing as the user cannot write to /usr/bin or any other dir in the >system and everytime my app runs it will recompile it .pyc will help execution time so it might be nice to have those in place. Normally you'd split up the bulk of the code into a module which gets installed into site-packages and a piece of stand-alone front-end code which imports the module and executes whatever you need to do and gets installed into a typical PATH directory. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ ...fools rush in where Angels fear to tread. From lists at cheimes.de Wed Jan 23 14:44:26 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 23 Jan 2008 20:44:26 +0100 Subject: When is min(a, b) != min(b, a)? In-Reply-To: <13p9hdmh7c08abe@corp.supernews.com> References: <13p9hdmh7c08abe@corp.supernews.com> Message-ID: Grant Edwards wrote: > In many applications (e.g. process control) propogating NaN > values are way too useful to avoid. Avoiding NaN would make a > lot of code far more complicated than would using them. NaNs are very useful for experienced power users but they are very confusing for newbies or developers without a numerical background. It's very easy to create an inf or nan in Python: inf = 1E+5000 ninf = -inf nan = inf * 0. 1E5000 creates a nan because it is *much* bigger than DBL_MAX (around 1E+308). In fact it is even larger than LDBL_MAX (around 1E+4932). Christian From martin at v.loewis.de Thu Jan 17 15:26:59 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 Jan 2008 21:26:59 +0100 Subject: -fno-strict-aliasing turned off when cross compiling In-Reply-To: <8d3d3114-0e23-4506-be43-e980613a0e93@q39g2000hsf.googlegroups.com> References: <66c2d5b4-c84f-47d9-aa4a-1cca3ae594b2@q39g2000hsf.googlegroups.com> <478ee01b$0$4589$9b622d9e@news.freenet.de> <8d3d3114-0e23-4506-be43-e980613a0e93@q39g2000hsf.googlegroups.com> Message-ID: <478FBA13.20806@v.loewis.de> > This makes some sense. Thank you. As for this: > > def detect_modules(self): > # Ensure that /usr/local is always used > add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') > add_dir_to_list(self.compiler.include_dirs, '/usr/local/ > include') > > it looks like a recipe for a disaster when cross compiling: > cc1: warning: include location "/usr/local/include" is unsafe for > cross-compilation Yes, Python doesn't really support cross-compilation. So you are on your own. Of course, in true cross-compilation, you won't get a chance to run setup.py, since python will only run on the target system, not on the host system, therefore setup.py won't even start, and it doesn't matter that it won't support cross-compilation. Regards, Martin From kyosohma at gmail.com Wed Jan 30 13:33:41 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 30 Jan 2008 10:33:41 -0800 (PST) Subject: event handling References: Message-ID: <3fb69345-56e7-43e7-927b-82c7312e86f5@n20g2000hsh.googlegroups.com> On Jan 30, 11:16 am, Peter Nemeth wrote: > Hi , > > I am working on a stellar spectral analysis pipeline in Python. My OS is > Suse 10.0, and i use Python 2.5 . I have found difficulties with keyboard > event handling. My code communicates with the user through an xterm window > and shows graphs in a Gnuplot window. At a certain point i start an > infinite loop in order to select multiple spectral regions by mouse-clicks > over the Gnuplot graph. I would like to terminate this loop by a single > keystroke, but i can not get it done. I use 'thread' to run this process > in the background waiting for a keystroke. I don't want to use tkinter, > widgets or pygame because those require a popup surface to work in and i > already have the gnuplot window. > > I tried a C like getch() function, but that pauses the code waiting for > key press instead of scanning the event queue. > > Is there any other means for general event handling in Python? > > Any help would be greatly appreciated. > > Sincerely, > Peter I would use wxPython, but since you seem against that, here's what I found using Google-fu: http://www.freenetpages.co.uk/hp/alan.gauld/tutevent.htm It sounds very similar to what you are doing and it shows how to do it in both Windows and Linux. Threads are annoying buggers. You'll probably want to have one thread catching key-presses and storing them in a file or "file-like" object and have your other thread read from it periodically. I'm not sure that the link above mentions that. Hope that helps! Mike From antroy at gmail.com Fri Jan 4 03:50:25 2008 From: antroy at gmail.com (Ant) Date: Fri, 4 Jan 2008 00:50:25 -0800 (PST) Subject: Jython: Honourable mention on Charles Nutter's blog. Message-ID: <284737ca-7626-4f65-a780-638377d3b3d6@e25g2000prg.googlegroups.com> Hi all, The Jython team got an honourable mention on the Headius blog this morning. Apparently they have got Django working with the latest builds of Jython: http://headius.blogspot.com/2008/01/jythons-back-baby.html So congratulations! -- Ant. From paddy3118 at googlemail.com Wed Jan 9 16:40:44 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 9 Jan 2008 13:40:44 -0800 (PST) Subject: alternating string replace: Extended input (Long). References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <3dc4aed2-ae92-418f-b86d-2b7f0d2abd73@y5g2000hsf.googlegroups.com> On Jan 9, 9:29 pm, Paddy wrote: > On Jan 9, 8:56 pm, Fredrik Lundh wrote: > > > Donald 'Paddy' McCarthy wrote: > > > I created some more test strings and ran posters solutions against them. > > > the point being? > > > > > To see how they act against 'corner cases' and > an exercise for me in trying to create corner cases. (I'm in to > functional testing at the mo'). > > - Paddy. ... Then there is seeing how multiple interpretations of a real world (i.e. limited), spec. act on an extended dataset. The limited spec comes up all the time in the design and verification of digital circuits. Then again, I was also waiting on someone and it passed the time amiably :-) - Paddy. From aaron.watters at gmail.com Tue Jan 1 19:19:30 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 1 Jan 2008 16:19:30 -0800 (PST) Subject: cloud computing (and python)? References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> Message-ID: <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> On Jan 1, 5:05 pm, Steven D'Aprano wrote: > On Tue, 01 Jan 2008 13:55:10 -0800, PatrickMinnesota wrote: > > The idea is that your data and applications are on the net, rather than > > your local hard drive. > > Or, to put it another way, your data and applications are controlled by > another company rather than you. > > Not that I wish to be cynical or anything like that. > > -- > Steven I see. So cloud computing is java dickless^H^H^H^H^H^Hskless workstations warmed over but less flexible? I'm having trouble understanding why people would want to buy in to this. For example at the amazon site I see things like "it might take a couple minutes to load your image..." Are they joking? hmmm. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=try+not+to+allocate+too+many+objects+okay From sjmachin at lexicon.net Sun Jan 13 04:54:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 13 Jan 2008 01:54:33 -0800 (PST) Subject: Elementary string-formatting References: Message-ID: <7d17fa05-67c5-4acb-91b6-c53fdf70ae27@q77g2000hsh.googlegroups.com> On Jan 13, 8:43 pm, Odysseus wrote: > In article > , > Roberto Bonvallet wrote: > > > Put this at the beginning of your program: > > > from __future__ import division > > > This forces all divisions to yield floating points values: > > Thanks for the tip. May I assume the div operator will still behave as > usual? div operator? The integer division operator is // >>> from __future__ import division >>> 1 / 3 0.33333333333333331 >>> 1 // 3 0 >>> 22 / 7 3.1428571428571428 >>> 22 // 7 3 >>> 22 div 7 File "", line 1 22 div 7 ^ SyntaxError: invalid syntax >>> From spaceoutlet at gmail.com Mon Jan 7 09:46:32 2008 From: spaceoutlet at gmail.com (Alex K) Date: Mon, 7 Jan 2008 15:46:32 +0100 Subject: introspection question In-Reply-To: References: Message-ID: Nice thank you. But anyway to make it look pretty? On 07/01/2008, Peter Otten <__peter__ at web.de> wrote: > Alex K wrote: > > > What would be the simplest way of enumerating all methods and members > > (including inherited) of a given object? Thank you. > > inspect.getmembers() > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From jzgoda at o2.usun.pl Sat Jan 5 06:41:54 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sat, 05 Jan 2008 12:41:54 +0100 Subject: Question on os.tempnam() vulnerability In-Reply-To: <13nt81gftkfa32d@corp.supernews.com> References: <13nt81gftkfa32d@corp.supernews.com> Message-ID: Grant Edwards pisze: >> you get a name instead of a file, so someone else can create that file >> after you've called tempnam/tmpnam, but before you've actually gotten >> around to create the file yourself. which means that anyone on the >> machine might be able to mess with your application's data. >> >> use the functions marked as "safe" in the tempfile module instead. > > Under Windows, is there a "safe" way to create a temp file that > has a name that can be passed to a program which will then open > it? I never figured out a way to do that and had to fall back > on the "unsafe" tmpnam method. I think it's all impossible to get only file name and feel safe. You have to have both file name and a file object opened exclusively for you. Any other way you'll get a possible race condition. -- Jarek Zgoda http://zgodowie.org/ From george.sakkis at gmail.com Mon Jan 14 14:37:15 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 14 Jan 2008 11:37:15 -0800 (PST) Subject: SyntaxError: 'import *' not allowed with 'from .' Message-ID: <9ac37212-7521-454d-a35f-afd6f7ec24f6@m34g2000hsf.googlegroups.com> Unless I missed it, PEP 328 doesn't mention anything about this. What's the reason for not allowing "from .relative.module import *' ? George From bruno.desthuilliers at gmail.com Tue Jan 15 14:14:31 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 15 Jan 2008 11:14:31 -0800 (PST) Subject: Benchmark [was Re: common problem - elegant solution sought] References: <5v3gg1F1kkla5U1@mid.dfncis.de> <478ccc9e$0$29264$ba620e4c@news.skynet.be> <7xbq7ngdge.fsf@ruckus.brouhaha.com> Message-ID: <2007a710-3a9c-40f2-aab2-24d60432454c@e23g2000prf.googlegroups.com> On Jan 15, 6:18 pm, Paul Rubin wrote: > Helmut Jarausch writes: > > def del_by_key(L,key) : > > for pos, (k,d) in enumerate(L): > > if k == key : > > del L[pos] > > break > > This looks very dangerous, mutating L while iterating over it. This would indeed be dangerous *without* the break statement !-) From papilonv at gmail.com Mon Jan 21 04:38:15 2008 From: papilonv at gmail.com (Vikas Jadhav) Date: Mon, 21 Jan 2008 15:08:15 +0530 Subject: Fwd: Help! - Invoke setup.py file In-Reply-To: <7856b4e60801190232j3b1a18b5n3630ddf77aed9ee0@mail.gmail.com> References: <7856b4e60801190232j3b1a18b5n3630ddf77aed9ee0@mail.gmail.com> Message-ID: <7856b4e60801210138w5e71a977w473db4bea0cba43c@mail.gmail.com> Hi, Please look into the query mentioned in below email. Cheers, Vikas ---------- Forwarded message ---------- From: Vikas Jadhav Date: Jan 19, 2008 4:02 PM Subject: Help! - Invoke setup.py file To: python-list at python.org Hi, We have setup of SVGMath* 0.3.2 (Converter- Mathml 2.0 coding to SVG). The setup folder contains setup.py file but we are not able to initiate this file. Kindly help us, resolution to this query will be appreciated. Python version: Installed on PC- 2.5.1 and OS- Windows 2000. * *SVGMath* is a *command*-line utility to convert MathML expressions to SVG, written entirely in Python. Note: Attached file contains SVGMath installation components. Cheers, Vikas -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: SVGMath-0.3.2.zip Type: application/zip Size: 77473 bytes Desc: not available URL: From terry at jon.es Thu Jan 17 21:45:23 2008 From: terry at jon.es (Terry Jones) Date: Fri, 18 Jan 2008 03:45:23 +0100 Subject: Some Berkeley DB questions (being maintained? queries?) In-Reply-To: Your message at 04:29:05 on Thursday, 17 January 2008 References: <0ba30836-8e2d-4061-94ea-ccddb24bc290@s19g2000prg.googlegroups.com> <003601c85904$904150c0$0401a8c0@T60> Message-ID: <18320.4803.331705.315917@terry.local> >>>>> "Brian" == Brian Smith writes: Brian> HerbAsher at googlemail.com wrote: >> 2. Are there good python libraries for bdb available, that >> are being maintained? Brian> I would like to know the answer to this question too--if you have Brian> used the pybsddb/bsddb.db module, please share your experience. I used it a little in mid-2006. I ran into one issue that I resolved by looking at the C source and fiddling with the Python interface. I sent mail to the people mentioned in the bsddb README file. One (Barry Warsaw) answered to say he hadn't looked at the code in a couple of years and was probably not the person to contact. >> 4. What are good, stable alternatives? >From memory, the Chandler project also has an interface to BSD DB, but I don't remember any details at all. I'm also interested in any ongoing or planned work on the Python interface. Terry From paddy3118 at googlemail.com Mon Jan 7 22:16:10 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 7 Jan 2008 19:16:10 -0800 (PST) Subject: TIOBE declares Python as programming language of 2007! References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> Message-ID: <325e6baa-db24-4636-83e2-f66b2c7c00a5@e10g2000prf.googlegroups.com> On Jan 7, 10:55 am, monkeyda... at mailinator.com wrote: > Seehttp://www.tiobe.com/index.htm?tiobe_index. > > Marc ohloh "Monthly Commits by Language" also shows Python open-source work being healthy: http://tinyurl.com/2wcadu If you remove C/C++ the other languages can be more easily compared. (C/C++ I see as the bedrock language of open-source): http://tinyurl.com/2u76d9 - Paddy. From aekidens at yahoo.es Fri Jan 11 16:31:05 2008 From: aekidens at yahoo.es (Gabriel) Date: Fri, 11 Jan 2008 22:31:05 +0100 Subject: Graphics Module Message-ID: Hi all ! I'm developing a math program that shows graphics of functions. I would hear suggestions about the way of drawing 2D . Thanks a lot for your answers. - Gabriel - From Matthew_WARREN at bnpparibas.com Mon Jan 28 10:10:54 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Mon, 28 Jan 2008 15:10:54 +0000 Subject: validate string is valid maths Message-ID: Hi pythoners. I am generating strings of length n, randomly from the symbols +-/*0123456789 What would be the 'sensible' way of transforming the string, for example changing '3++++++8' into 3+8 or '3++--*-9' into '3+-9' such that eval(string) will always return a number? in cases where multiple symbols conflict in meaning (as '3++--*-9' the earliest valid symbols in the sequence should be preserved so for example, '3++*/-9' = 3+-9 '45--/**/+7' = 45-+7 '55/-**+-6**' = 55/-6 ...that is, unless there is a canonical method for doing this that does something else instead.. this sounds like homework. It's not. I like making problems up and it's a slow work day. So, as an aside, there is no real reason I want to do this, nor other problem to solve, nor other background to what I'm trying to achieve ;) other than twiddling with python. 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 mail at timgolden.me.uk Mon Jan 28 05:36:42 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 28 Jan 2008 10:36:42 +0000 Subject: starting programs from python script on windows In-Reply-To: References: Message-ID: <479DB03A.9060801@timgolden.me.uk> Benedict Verheyen wrote: > i want to automate starting programs on my windows machine and i want > to do it with windows. > This is a sample script: > > from subprocess import Popen, PIPE > import time > > print " Starting app 1" > time.sleep(1) > try: > p1 = Popen(["C:\Program Files\Microsoft > Office\OFFICE11\OUTLOOK.EXE"], stdout=PIPE) > except Exception, e: > print "Error on startup app 1 %s " % str(e) > > print " Starting app 2" > time.sleep(1) > > try: > p2 = Popen(["C:\Windows\system32\cmd.exe"], stdout=PIPE) > except Exception, e: > print "Error on startup app 2 %s " % str(e) > > It start it from a batch file: > SET PYTHONPATH=C:\Python25 > > rem - path to script to execute > %PYTHONPATH%\python.exe C:\login.py > > This is the result: > > C:\>C:\Python25\python.exe C:\login.py > Starting app 1 > Starting app 2 > Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. > Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. > Het proces heeft geprobeerd naar een niet-bestaande sluis te schrijven. > > 1. I get an error message saying the process has tried to write to a non > existing pipe. > > 2. Order of execution isn't respected: it prints the 2 messages and then > it tries to start the programs. Outlook is started but the command > prompt not. > > Anyway, if it works, i would like to start using python to drive the > startup scripts of the users on the system. > > How can i use python to start several programs as i would otherwise do > manually and keep the order i want? [Takes a big, deep breath] OK. You've got a few misunderstandings in there. Nothing too major, but it's worth sorting them out. 1) If you just want to kick off a program and that's it, say as part of some kind of startup process, then you can just use the subprocess.call convenience function. The business with stdout=PIPE is for communicating with (usually console-based) programs which read and write to the console. 2) The optional PYTHONPATH env var is used *internally* to Python as one way of determining the path to search for Python modules *after you've got Python running*. To run Python itself, you either need to ensure the python.exe is already in the standard PATH env var, or look for it in its conventional place: c:\python25\python.exe. (Or make some other arrangement according to local convention etc.) There was a thread here recently about using Python as part of a login script -- which is what I think you're doing here. I think, because of the uncertain interaction between the Workstation in effect when you're logging in as opposed to the Workstation which owns the user's desktop, you might do better to have some technique for adding to the [Startup] entry on the Start Menu if all you want to do is to start programs. All that said, here's some sample code which just kicks off a batch of programs. Note that I'm use os.startfile because that will use ShellExecute which honours app path shortcuts, making common things like MS Office apps much easier. You could equivalently use subprocess.call but then you either have to hardcode application paths or use FindExectable against an arbitrary associated doc to find the right place. import os programs = [ "outlook.exe", "cmd.exe", "winword.exe", "c:/temp/helpfile.pdf" ] for program in programs: os.startfile (program) The last entry -- helpfile.pdf -- is to illustrate that os.startfile can "start" documents as well as executable programs. TJG From steven at REMOVE.THIS.cybersource.com.au Thu Jan 10 04:03:46 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 10 Jan 2008 09:03:46 -0000 Subject: How to get memory size/usage of python object References: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> <257fa40e-5a6d-4e1d-aefd-9439a182391c@f47g2000hsd.googlegroups.com> Message-ID: On Thu, 10 Jan 2008 00:14:42 -0800, Santiago Romero wrote: >> Would you care to precisely define "REAL size" first? Consider: >> >> >>> atuple = (1, 2) >> >>> mylist = [(0, 0), atuple] >> >> Should sizeof(mylist) include sizeof(atuple) ? > > No, I'm talking about "simple" lists, without REFERENCES to another > objects into it. > > I mean: > > lists = [ 0, 1, 2, 3, 4, (1,2), 3] That list has 7 references to other objects. One of those objects has 2 references to objects. In total, depending on implementation, there could be as many as 9 objects referenced by that list, or as few as 6 objects (both references to 3 could be to the same object). In the current CPython implementation, that list will have 7 references to 6 objects. Including indirect references, there will be 9 references to 6 objects. (Or so I understand.) > or > > array = [ [0,0,0,0,0,0,0], [1,1,1,1,2,1,2], ... ] Ignoring the '...', there will be a total of 16 references to 5 objects in the current CPython implementation. Other Pythons (Jython, IronPython, PyPy, ...) may be different. > Maybe I can "pickle" the object to disk and see the filesize ... :-? That would measure something very different. Possibly you want something like this heuristic: def sizeof(obj): """APPROXIMATE memory taken by some Python objects in the current 32-bit CPython implementation. Excludes the space used by items in containers; does not take into account overhead of memory allocation from the operating system, or over-allocation by lists and dicts. """ T = type(obj) if T is int: kind = "fixed" container = False size = 4 elif T is list or T is tuple: kind = "variable" container = True size = 4*len(obj) elif T is dict: kind = "variable" container = True size = 144 if len(obj) > 8: size += 12*(len(obj)-8) elif T is str: kind = "variable" container = False size = len(obj) + 1 else: raise TypeError("don't know about this kind of object") if kind == "fixed": overhead = 8 else: # "variable" overhead = 12 if container: garbage_collector = 8 else: garbage_collector = 0 malloc = 8 # in most cases size = size + overhead + garbage_collector + malloc # Round to nearest multiple of 8 bytes x = size % 8 if x != 0: size += 8-x size = (size + 8) return size See: http://mail.python.org/pipermail/python-list/2002-March/135223.html to get you started. -- Steven. From attn.steven.kuo at gmail.com Thu Jan 31 18:24:15 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 31 Jan 2008 15:24:15 -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> <7xzlula8z4.fsf@ruckus.brouhaha.com> Message-ID: On Jan 31, 3:09 pm, Paul Rubin wrote: > "attn.steven.... at gmail.com" writes: > > mysets = [set(range(x[2],x[1])) for x in mylist] > > This is pretty horrible, each set can be arbitrarily large, > i.e. if x[2] and x[1] are 0 and 1000000, you get a set with > a million elements. True... Any lighter-weight implementation of sets out there? That is, one that would defer use of resources until actually needed -- somewhat akin to the distinction between range and xrange, and so on. xset? -- Regards, Steven From asmodai at in-nomine.org Tue Jan 8 03:18:18 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 09:18:18 +0100 Subject: web service between python and c# In-Reply-To: <12f6e713-392e-4fda-8354-51a8337d77dc@l6g2000prm.googlegroups.com> References: <12f6e713-392e-4fda-8354-51a8337d77dc@l6g2000prm.googlegroups.com> Message-ID: <20080108081818.GC75977@nexus.in-nomine.org> -On [20080108 07:24], abhishek (guptaabhishek1983 at gmail.com) wrote: >but have no idea on how to interface it with c# client. Totally depends on what exactly you need to accomplish. Some solutions can just use SOAP or REST. Others need full-fledged XML-RPC or other similar solutions. Some just use a serialization format like JSON. So what exactly are you trying to do? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ And every word upon your spiralling cross is but a misled sun, a bitter loss... From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Jan 12 04:22:43 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 12 Jan 2008 10:22:43 +0100 Subject: [Kamaelia] TCPClient: How to sense connection failure? References: <5uq49vF1jkgcoU1@mid.individual.net> Message-ID: <5urf73F1j3iqgU1@mid.individual.net> Hendrik van Rooyen wrote: > Not sure about Kamelia, but I have found that when a FIN comes > along, a socket.recv() gives back an empty string, just like EOF > on a file. That Python socket interface can detect it I'm absolutely sure -- Twisted handles it. I even pdb'ed Kamaelia and control flow ended at a different point in case of connection closing -- but yielded control to the scheduler immediately and never continued. > Below is what I use - a sort of netstring, synced on a tilde, with > human readable length implementation and escaping of tildes and > the escape character. Thank you (though I hope I won't have to mess with socket functions ;) ). > I hope the tabs survive the journey Looks like they morphed to spaces. Regards, Bj?rn -- BOFH excuse #77: Typo in the code From PatrickMinnesota at gmail.com Tue Jan 1 17:04:10 2008 From: PatrickMinnesota at gmail.com (PatrickMinnesota) Date: Tue, 1 Jan 2008 14:04:10 -0800 (PST) Subject: cloud computing (and python)? References: Message-ID: <2d4cea90-a09a-422d-ac26-cce8bbbc9a60@x69g2000hsx.googlegroups.com> On Jan 1, 3:26 pm, Aaron Watters wrote: > So, in between skiing runs I noticed > a Business Week cover story on > "cloud computing". The article had > lots of interesting information in it like > about how somebody's mom used to > be an airline stewardess and the > interior decor of various office spaces. > It was a truly excellent piece of > journalism. > > However it gave me no idea what > "cloud computing" is and how it > could be used to solve a computational > problem. > > Could anyone on this list > which usually has highly informed > readers give me a clue at some > level of technical detail what cloud > computing is about and how it could > be used. Bonus points if you mention > Python in the response! > > An actual example would be great, > if it's not web scraping and searching. > > - Aaron Watters > > ==http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=snow Oh, and I forgot to mention Python for points. Python combined with a framework like Django is used with Amazon's cloud services in various applications. www.Pownce.com is an example. From gherron at islandtraining.com Sat Jan 12 23:32:57 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 12 Jan 2008 20:32:57 -0800 Subject: Elementary string-formatting In-Reply-To: References: Message-ID: <47899479.7010404@islandtraining.com> Odysseus wrote: > Hello, group: I've just begun some introductory tutorials in Python. > Taking off from the "word play" exercise at > > > > I've written a mini-program to tabulate the number of characters in each > word in a file. Once the data have been collected in a list, the output > is produced by a while loop that steps through it by incrementing an > index "i", saying > > print '%2u %6u %4.2f' % \ > (i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0]) > Using 4.2 is the problem. The first digit (your 4) give the total number of characters to use for the number. Your numbers require at least 5 characters, two digits, one decimal point, and two more digits. So try 5.2, or 6.2 or 7.2 or higher if your numbers can grow into the hundreds or thousands or higher. If you want to try one of the floating point formats, then your first number must be large enough to account for digits (before and after) the decimal point, the 'E', and any digits in the exponent, as well as signs for both the number and the exponent. Gary Herron > My problem is with the last entry in each line, which isn't getting > padded: > > 1 0 0.00 > 2 85 0.07 > 3 908 0.80 > 4 3686 3.24 > 5 8258 7.26 > 6 14374 12.63 > 7 21727 19.09 > 8 26447 23.24 > 9 16658 14.64 > 10 9199 8.08 > 11 5296 4.65 > 12 3166 2.78 > 13 1960 1.72 > 14 1023 0.90 > 15 557 0.49 > 16 261 0.23 > 17 132 0.12 > 18 48 0.04 > 19 16 0.01 > 20 5 0.00 > 21 3 0.00 > > I've tried varying the number before the decimal in the formatting > string; "F", "g", and "G" conversions instead of "f"; and a couple of > other permutations (including replacing the arithmetical expression in > the tuple with a variable, defined on the previous line), but I can't > seem to get the decimal points to line up. I'm sure I'm missing > something obvious, but I'd appreciate a tip -- thanks in advance! > > FWIW I'm running > > Python 2.3.5 (#1, Oct 5 2005, 11:07:27) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin > > from the Terminal on Mac OS X v10.4.11. > > P.S. Is there a preferable technique for forcing floating-point division > of two integers to that used above, multiplying by "100.0" first? What > about if I just wanted a ratio: is "float(n / m)" better than "1.0 * n / > m"? > > From lasses_weil at klapptsowieso.net Mon Jan 14 09:37:20 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 14 Jan 2008 15:37:20 +0100 Subject: __init__ explanation please In-Reply-To: References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> Message-ID: <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> Jeroen Ruigrok van der Werven wrote: > To restate it more correctly: __init__ is akin to a constructor. > No. See Hrvoje Niksic's reply (and Ben Finney's to which it was a reply). __init__() /initializes/ an instance (automatically after creation). It is called, /after/ the instance has been constructed via the __new__() method. __new__() actually /constructs/ a new instance. > I am not entirely sure I fully understand __new__'s semantics though. Create a new (blank) instance of a class and return it. That's all there is to it. > I must not be understanding something and __new__'s documentation there is not > that clear to me, to be honest. > It is somewhat confusing at first. But just bear in mind: 99 out of 100 times, you don't need to override __new__(). When you need it, you'll know. /W From bignose+hates-spam at benfinney.id.au Tue Jan 1 19:53:37 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 02 Jan 2008 11:53:37 +1100 Subject: Catching external program exceptions References: <25qdnZuc2dn0WOfanZ2dnUVZ_gWdnZ2d@wideopenwest.com> Message-ID: <87ejd1avzi.fsf@benfinney.id.au> Marty writes: > I need to catch exceptions thrown by programs started by the os.system > function, as indicated by a non-zero return code (e.g. the mount > utility). That's not an exception. It's referred to as an "exit status" or (often) some short form or variation of that term. Python can make available the exit status value of an external process, but isn't going to interpret them to the point of raising exceptions that you can catch. The exit status is always available to the parent process, but the *meaning* of any given value of that status is highly dependent on the program that was running. If you want to respond to particular values, you'll have to do so by explicitly testing the exit status against values to which you've assigned meaning -- hopefully meanings documented in the manual page for the program which generates the exit status. > For example, if I get the following results in a bash > shell: > > $mount test > mount: can't find /home/marty/test in /etc/fstab or /etc/mtab > > then I want to catch the same exception What's happening isn't an exception. It's a message being emitted to an output stream (likely the stderr stream of the mount process, though some programs will put error messages on stdout), followed by an exit of that process. The parent of that process will receive an exit status from the process when it terminates; it will also (on Unix-like systems) receive a separate value indicating the OS signal that caused the process to exit. Python's 'os.system' function makes both these values available as the return value of the function. > from the corresponding os.system() call, i.e. "os.system('mount > test')", but it doesn't work as expected: > > > >>> import os, sys > >>> try: os.system('mount test') > ... except: print 'error' > ... > mount: can't find /home/marty/test in /etc/fstab or /etc/mtab > 256 > >>> The statement within the 'try' block executes the 'os.system()' call; since you're running inside the interpreter, the return value from that function is displayed. The return value, as documented in the 'os.system' documentation, encodes both the signal number (the low 8 bits, in this case (256 & 0x0F) == 0) and, since the signal number is zero ("no signal received") the exit status value (the high 8 bits, in this case (256 >> 8) == 1). No exception is being raised, so the 'try' block completes successfully and the 'except' block is not invoked. So, instead of testing for an exception, you should instead be testing the exit status code returned by the 'os.system' call. First, read the documentation for the command you're running:: $ man mount [...] Unfortunately the 'mount(8)' manual page doesn't (on my system) mention possible values for the exit status. So, you'll just have to deduce it, or go with the common convention of "zero status == success, non-zero status == error". MountFailedError = OSError import os return_value = os.system('mount test') signal_number = (return_value & 0x0F) if not signal_number: exit_status = (return_value >> 8) if exit_status: raise MountFailedError("Oh no!") Why isn't this standardised? Because the process-call interface is inconsistent between operating systems, and there's even less consistency in the implementations of the programs that return these values. The Zen of Python says: "In the face of ambiguity, refuse the temptation to guess." Thus, Python can do little more than present the values it received from the process call; anything further would be guessing. -- \ "I bought some batteries, but they weren't included; so I had | `\ to buy them again." -- Steven Wright | _o__) | Ben Finney From deets at nospam.web.de Fri Jan 11 13:36:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jan 2008 19:36:19 +0100 Subject: Converting a bidimensional list in a bidimensional array In-Reply-To: <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> <005679e9-c355-4e0a-872c-e0dae3181fd0@x69g2000hsx.googlegroups.com> <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> Message-ID: <5upr93F1j6u7aU1@mid.uni-berlin.de> Santiago Romero schrieb: >>> - Speed Performance: Do you think that changing from list to Array() >>> would improve speed? I'm going to do lots of tilemap[y][x] checks (I >>> mean, player jumping around the screen, checking if it's falling over >>> a non-zero tile, and so). > >> First of all: if you have enough memory to use a python list, then I >> suggest you to use a list. >> >> Often python lists are faster than array.array (maybe because python >> lists actually contain pyobjects). > > > My problem is that, in my game, each screen is 30x20, and I have > about 100 screens, so my tilemap contains 32*20*100 = 60000 python > objects (integers). > > If each integer-python-object takes 16 bytes, this makes 60000 * 16 = > almost 1MB of memory just for the tilemaps... > > Using array of type H (16 bits per item = 2 bytes), my maps take just > 60000*2 = 120KB of memory. > > After that, I just will access tilemap data for reading (i.e. value > = tilemap.GetTile(x,y)) ... > > Do you think I should still go with lists instead of an H-type array? With these requirements, there is no need to jump through hoops to try and save memeroy. You even can load levels from disk while the player moves through the world. Seriously - even a decade old machine would have had enough ram for this. And nowadays .5GB to 2GB are the minimum. Don't waste time you could spend designing a nice game on saving memory.... Diez From deets at nospam.web.de Mon Jan 7 08:12:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 Jan 2008 14:12:24 +0100 Subject: TIOBE declares Python as programming language of 2007! In-Reply-To: <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> References: <5746755e-3330-4f84-b5d2-255b34582225@i72g2000hsd.googlegroups.com> <8820e3d1-cccb-4bac-b177-fbec967ab5d5@c4g2000hsg.googlegroups.com> Message-ID: <5uempsF1gt5cbU1@mid.uni-berlin.de> Berco Beute schrieb: > Cool! We knew it would happen one day :) > What could be the reason? Python 3? Jython 2.2? Java's loss of > sexiness? I'd say Java was never sexy, but dressed up in expensive lingerie by marketing maniacs... Diez From jpeng at block.duxieweb.com Tue Jan 22 04:25:52 2008 From: jpeng at block.duxieweb.com (J. Peng) Date: Tue, 22 Jan 2008 17:25:52 +0800 Subject: what's this instance? In-Reply-To: <4795b32d$0$16941$426a74cc@news.free.fr> References: <4795b32d$0$16941$426a74cc@news.free.fr> Message-ID: <4795B6A0.9010809@block.duxieweb.com> Bruno Desthuilliers ??: > J. Peng a ?crit : >> def safe_float(object): >> try: >> retval = float(object) >> except (ValueError, TypeError), oops: >> retval = str(oops) >> return retval > >> The code above works well. > > For which definition of "works well" ? > I got it from Core Python Programming book I bought.You may ask it to Westley Chun.:) From kay.schluehr at gmx.net Tue Jan 29 16:33:08 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 29 Jan 2008 13:33:08 -0800 (PST) Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> <479e0225$0$36389$742ec2ed@news.sonic.net> Message-ID: <70c4064a-a65d-4fd5-b39c-38e6a3fb567b@i7g2000prf.googlegroups.com> On 29 Jan., 17:00, "Chris Mellon" wrote: > Given the difficulty of statically analyzing Python, and the > limitations you need to add for either static typing or type inference > to be practical, I think that the real future for faster Python code > is JIT, not static optimizations. Python has a JIT right now - so why do you think it's Pythons "real future"? From detlev at die-offenbachs.de Sat Jan 12 08:34:35 2008 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 12 Jan 2008 14:34:35 +0100 Subject: eric4 request for contribution Message-ID: Hi, I am in the progress of writing a refactoring plugin for eric4 using the rope refactoring library. Unfortunately, this library does not contain a nice icon to be shown in an About Rope dialog. Is there anybody around, who could contribute such an icon. Maybe it could look like the Python snake but instead of the snake a rope is shown. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From jimis at gmx.net Thu Jan 10 12:17:47 2008 From: jimis at gmx.net (Dimitrios Apostolou) Date: Thu, 10 Jan 2008 19:17:47 +0200 (EET) Subject: urllib2 rate limiting Message-ID: Hello list, I want to limit the download speed when using urllib2. In particular, having several parallel downloads, I want to make sure that their total speed doesn't exceed a maximum value. I can't find a simple way to achieve this. After researching a can try some things but I'm stuck on the details: 1) Can I overload some method in _socket.py to achieve this, and perhaps make this generic enough to work even with other libraries than urllib2? 2) There is the urllib.urlretrieve() function which accepts a reporthook parameter. Perhaps I can have reporthook to increment a global counter and sleep as necessary when a threshold is reached. However there is not something similar in urllib2. Isn't urllib2 supposed to be a superset of urllib in functionality? Why there is no reporthook parameter in any of urllib2's functions? Moreover, even the existing way reporthook can be used doesn't seem so right: reporthook(blocknum, bs, size) is always called with bs=8K even for the last block, and sometimes (blocknum*bs > size) is possible, if the server sends wrong Content-Lentgth HTTP headers. 3) Perhaps I can use filehandle.read(1024) and manually read as many chunks of data as I need. However I think this would generally be inefficient and I'm not sure how it would work because of internal buffering of urllib2. So how do you think I can achieve rate limiting in urllib2? Thanks in advance, Dimitris P.S. And something simpler: How can I disallow urllib2 to follow redirections to foreign hosts? From arnodel at googlemail.com Mon Jan 21 06:33:28 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 21 Jan 2008 03:33:28 -0800 (PST) Subject: Default attribute values pattern References: <4794697f$0$16980$426a74cc@news.free.fr> <41f8394c-342c-42dc-9bf2-a737b572aff9@c4g2000hsg.googlegroups.com> Message-ID: <2b478c87-238d-43b7-a414-8dc609395752@e25g2000prg.googlegroups.com> On Jan 21, 10:09?am, cokofree... at gmail.com wrote: > > Grab(argdict, key, default) is argdict.pop(key, default) > > "pop() raises a KeyError when no default value is given and the key is > not found." And it doesn't if a default is provided, which is always the case in the uses of Grab(...), so it seems the right tool for the job. > > def grab(kw, key, default=None): > > ? ?try: > > ? ? ?return kw.pop(key) > > ? ?except KeyError: > > ? ? ?return default > > So Bruno's technique seems to me to be the correct one as it catches > the KeyError. If you really really want to write a grab function (IMHO pop is good enough): def grab(kw, key, default=None): return kw.pop(key, default) -- Arnaud From tjreedy at udel.edu Sat Jan 26 02:32:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jan 2008 02:32:48 -0500 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com><8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com><479A58F9.4090805@gmx.net> <8d04436f0801251519g482a697dn625223b6d46e8f2c@mail.gmail.com> Message-ID: "Henry Baxter" wrote in message news:8d04436f0801251519g482a697dn625223b6d46e8f2c at mail.gmail.com... | Thanks Hexamorph and Neal. Somehow I didn't make the connection with using | 'index', but I'm all sorted out now :) | | On Jan 25, 2008 1:47 PM, Hexamorph wrote: | | > Henry Baxter wrote: | > > Oops, gmail has keyboard shortcuts apparently, to continue: | > > | > > def maxi(l): | > > m = max(l) | > > for i, v in enumerate(l): | > > if m == v: | > > return i | > > | > | > What's about l.index(max(l)) ? Both of these methods scan the list twice. The two given by RH and SDD do so just once. Both of those will give the index of the of the last maximum value. If you want the index of the first max value (you did not specify ;-), write an explicit loop. From travis.jensen at gmail.com Fri Jan 18 13:53:23 2008 From: travis.jensen at gmail.com (Travis Jensen) Date: Fri, 18 Jan 2008 11:53:23 -0700 Subject: array and list In-Reply-To: <010888f2-7755-4ec1-9f56-be8a43097a1f@i12g2000prf.googlegroups.com> References: <24f854eb-93a8-414d-a518-842bb2d185fb@s13g2000prd.googlegroups.com> <010888f2-7755-4ec1-9f56-be8a43097a1f@i12g2000prf.googlegroups.com> Message-ID: <4C920483-DD98-4DB2-9E6B-21879D82E2B8@gmail.com> On Jan 18, 2008, at 2:48 AM, bearophileHUGS at lycos.com wrote: > J. Peng>why perl call it array and python call it list?< > > Unfortunate naming, I'd say. Calling list a dynamic array is silly, > despite all the things you may say about abstract data types having > the correct methods, etc. I wouldn't call it unfortunate. The list semantics follow LISP's semantics far more closely than C's array semantics. I would hazard to guess that they are called lists because that is what every functional language calls them and this aspect of python was modeled after functional languages. tj Travis Jensen travis.jensen at gmail.com http://softwaremaven.innerbrane.com/ You should read my blog; it is more interesting than my signiature. From donn.ingle at gmail.com Fri Jan 25 09:33:47 2008 From: donn.ingle at gmail.com (Donn) Date: Fri, 25 Jan 2008 16:33:47 +0200 Subject: piping into a python script In-Reply-To: References: <200801241903.20082.donn.ingle@gmail.com> Message-ID: <200801251633.47201.donn.ingle@gmail.com> Andrew, Thanks for your tips. I managed to get a working script going. I am sure there will be stdin 'issues' to come, but I hope not. If anyone wants to have a look, it's on the cheese shop at: http://pypi.python.org/pypi/fui \d -- "You know, I've gone to a lot of psychics, and they've told me a lot of different things, but not one of them has ever told me 'You are an undercover policewoman here to arrest me.'" -- New York City undercover policewoman Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ From stefan.behnel-n05pAM at web.de Wed Jan 23 09:12:23 2008 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 Jan 2008 15:12:23 +0100 Subject: Problem with processing XML In-Reply-To: <6c291c78-7a11-4d6f-be15-c916017ccf60@s13g2000prd.googlegroups.com> References: <13pbudgks88rcf3@corp.supernews.com> <47971EFF.8070701@web.de> <6c291c78-7a11-4d6f-be15-c916017ccf60@s13g2000prd.googlegroups.com> Message-ID: <47974B47.5000509@web.de> Hi, Paul Boddie wrote: > I'm not disputing the benefits of the ElementTree approach, but one > has to recall that the DOM is probably the most widely used XML API > out there (being the one most client-side developers are using) and > together with the other standards (XPath and so on) isn't as bad as > most people like to make out. I didn't deny that it works in general. However, it does not fit into the standard ways things work in Python. > Furthermore, I don't think it does > Python much good to have people "acting all Ruby on Rails" and telling > people to throw out everything they ever did in order to suck up the > benefits, regardless of the magnitude of those benefits; it comes > across as saying that "your experience counts for nothing compared to > our superior skills". Not exactly the best way to keep people around. I would have formulated it a bit different from my experience, which usually is: people complain on the list that they can't manage to get X to work for them. Others tell them: "don't use X, use Y", implicitly suggesting that you may have to learn it, but it will help you get your problem done in a way that you can /understand/ (i.e. that will fix your code for you, by enabling you to fix it yourself). >From my experience, this works in most (although admittedly not all) cases. But in any case, this reduction of complexity is an important step towards making people ask less questions. > As I noted in my chronology, the kind of attitude projected by various > people in the Python community at various times (and probably still > perpetuated in the Ruby community) is that stuff originating from the > W3C is bad The W3C is good in defining standards for portability and interoperability. APIs rarely fall into that bag. They should be language specific as they are made for use in a programming language, and therefore must match the way this language works. However, programming languages themselves are sometimes made for interoperability, and this is definitely true for XSLT and XQuery. I am a big fan of domain specific languages, because they (usually) are great in what they are designed for, and nothing more. > like the DOM stuff, if the support for standardised/ > recognised technologies is perceived as deficient, and given the point > above about glossing over what people themselves bring with them to > solve a particular problem, then people are quite likely to gloss over > Python than hear anyone's sermon about how great Python's other XML > technologies are. It's not about "other XML technologies", it's only about making the standard XML technologies accessible and usable. It's about designing interfaces in a way that matches the tool people are using anyway, which in this case is Python. Stefan From paddy3118 at googlemail.com Tue Jan 29 13:00:33 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 29 Jan 2008 10:00:33 -0800 (PST) Subject: Python noob SOS (any [former?] Perlheads out there?) References: Message-ID: <4786a797-dedf-45bc-960a-9d1a20b0de5d@l1g2000hsa.googlegroups.com> On Jan 29, 4:39 pm, kj wrote: > It's not the Python syntax that I'm having problems with, but rather > with larger scale issues such as the structuring of packages, > techniques for code reuse, test suites, the structure of > distributions,... Python and Perl seem to come from different > galaxies altogether... Maybe if someone could point Kynn at a suitable project where he could look at the complete repository and see how its successfully done? It would need I guess to employ: * Setuptools * modules/package(s) * Doctest/unit tests And not be too large I guess. Anyone wish to put forward their project? - Paddy. - Paddy. From mensanator at aol.com Mon Jan 21 19:02:34 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 21 Jan 2008 16:02:34 -0800 (PST) Subject: Max Long References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> Message-ID: On Jan 21, 5:36?pm, Gary Herron wrote: > tjhn... at gmail.com wrote: > > How can I figure out the largest long available? ?I was hoping for > > something like sys.maxint, but I didn't see it. ?Also, can someone > > point me to where I can (concisely) read about size of such types > > (int, float, long). > > There is no explicit (defined) limit. ?The amount of available address > space forms a practical limit. But not the only limitation: >>> import collatz_functions as cf >>> for k in xrange(1,20): a = cf.Type12MH(k,1) print 'number of digits in generation %2d:' % (k),cf.gmpy.numdigits(a) number of digits in generation 1: 2 number of digits in generation 2: 9 number of digits in generation 3: 74 number of digits in generation 4: 659 number of digits in generation 5: 5926 number of digits in generation 6: 53328 number of digits in generation 7: 479940 number of digits in generation 8: 4319453 number of digits in generation 9: 38875064 number of digits in generation 10: 349875565 Traceback (most recent call last): File "", line 2, in a = cf.Type12MH(k,1) File "C:\Program Files\PyGTK\Python\lib\collatz_functions.py", line 745, in Type12MH return TWO**(SIX*a - ONE) - ONE ValueError: mpz.pow outrageous exponent The power function can't do exponents that have 32 or more bits even if the memory can hold the resulting number. > > Gary Herron From lists at cheimes.de Tue Jan 29 06:46:15 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 29 Jan 2008 12:46:15 +0100 Subject: refcount In-Reply-To: References: Message-ID: Simon Pickles wrote: > Hi, > > Is is possible to access the refcount for an object? > > Ideally, I am looking to see if I have a refcount of 1 before calling del Help on built-in function getrefcount in module sys: getrefcount(...) getrefcount(object) -> integer Return the reference count of object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount(). Christian From cjw at sympatico.ca Tue Jan 8 13:01:02 2008 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 08 Jan 2008 13:01:02 -0500 Subject: I'm searching for Python style guidelines In-Reply-To: References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: Martin Vilcans wrote: > On 1/7/08, Guilherme Polo wrote: >> 2008/1/7, MartinRinehart at gmail.com : >>> Anything written somewhere that's thorough? Any code body that should >>> serve as a reference? >> PEP 8 >> http://www.python.org/dev/peps/pep-0008/ > > The problem with PEP 8 is that even code in the standard libraries > doesn't follow the recommendations regarding the naming of functions > for example. The recommendation is to_separate_words_with_underscore, > but some code uses lowerCamelCase instead. > > I tended to dislike the underscore convention, but after forcing > myself to use it for a while I'm starting to appreciate its beauty. I've come to like lowerCamelCase and a tab of 2. A tab of 4 wastes more space than is needed for the occasional heavy indenting. Colin W. From gregcorradini at gmail.com Tue Jan 29 11:27:13 2008 From: gregcorradini at gmail.com (Greg Corradini) Date: Tue, 29 Jan 2008 08:27:13 -0800 (PST) Subject: Mx.ODBC insert error Message-ID: <15163149.post@talk.nabble.com> Hello, I've never gotten this traceback error before using mx.ODBC. Any ideas about resolving this issue? The statement and the error it generates are listed below. curse.execute("Insert into FHWA_StandSamp_2008(LRS_ID_NEW) values('0402000010') where LRS_ID = '0403700010'") Traceback (most recent call last): File "", line 1, in ? curse.execute("Insert into FHWA_StandSamp_2008(LRS_ID_NEW) values ('0402000010') where LRS_ID = '0403700010'") ProgrammingError: ('37000', -3516, '[Microsoft][ODBC Microsoft Access Driver] Missing semicolon (;) at end of SQL statement.', 4612) Thanks Greg -- View this message in context: http://www.nabble.com/Mx.ODBC-insert-error-tp15163149p15163149.html Sent from the Python - python-list mailing list archive at Nabble.com. From rong.xian at gmail.com Sun Jan 27 08:50:53 2008 From: rong.xian at gmail.com (glacier) Date: Sun, 27 Jan 2008 05:50:53 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> <87abmv7pch.fsf@benfinney.id.au> <2b5d38cd-73e1-4b79-bd32-25be9a275549@s19g2000prg.googlegroups.com> Message-ID: On 1?27?, ??7?20?, John Machin wrote: > On Jan 27, 9:17 pm, glacier wrote: > > > > > > > On 1?24?, ??3?29?, "Gabriel Genellina" wrote: > > > > En Thu, 24 Jan 2008 04:52:22 -0200, glacier escribi?: > > > > > According to your reply, what will happen if I try to decode a long > > > > string seperately. > > > > I mean: > > > > ###################################### > > > > a='???'*100000 > > > > s1 = u'' > > > > cur = 0 > > > > while cur < len(a): > > > > d = min(len(a)-i,1023) > > > > s1 += a[cur:cur+d].decode('mbcs') > > > > cur += d > > > > ###################################### > > > > > May the code above produce any bogus characters in s1? > > > > Don't do that. You might be splitting the input string at a point that is > > > not a character boundary. You won't get bogus output, decode will raise a > > > UnicodeDecodeError instead. > > > You can control how errors are handled, see http://docs.python.org/lib/string-methods.html#l2h-237 > > > > -- > > > Gabriel Genellina > > > Thanks Gabriel, > > > I guess I understand what will happen if I didn't split the string at > > the character's boundry. > > I'm not sure if the decode method will miss split the boundry. > > Can you tell me then ? > > > Thanks a lot. > > *IF* the file is well-formed GBK, then the codec will not mess up when > decoding it to Unicode. The usual cause of mess is a combination of a > human and a text editor :-)- ??????? - > > - ??????? - I guess firstly, I should check if the file I used to test is well- formed GBK..:) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 23 08:12:50 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 23 Jan 2008 14:12:50 +0100 Subject: Max Long References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> <5vkog7F1m4dhvU1@mid.individual.net> Message-ID: <5vosqiF1nc20jU1@mid.individual.net> tjhnson at gmail.com wrote: > Indeed, as the docs pointed out. I guess I was confused by > > "If pylong is greater than ULONG_MAX, an OverflowError is raised." > > at http://docs.python.org/api/longObjects.html. Take care -- this is about "unsigned long" data type of C, not a Python "long" instance. Regards, Bj?rn -- BOFH excuse #75: There isn't any problem From gagsl-py2 at yahoo.com.ar Tue Jan 22 00:34:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 Jan 2008 03:34:30 -0200 Subject: newbie question: On installation of additional packages to Python References: Message-ID: En Tue, 22 Jan 2008 00:36:34 -0200, Nasser Abbasi escribi?: > I am running on windowz. I have downloaded and installed 2.5.1 Python. > > my question is on installing additional packages. > > What is the easiest way to do that? I read about python 'eggs' (like jar > files for Java), and easyInstall script, and such. Once you have setuptools installed, it's as easy as executing: easy_install packagename The alternative is to find and download the package yourself, unzip in a temporary directory, and execute: setup.py install For most packages that's all that is required. > Is there some automated way to install Python packages? a > manual/document I > could read that describes step by step how to do that? Browsing the > documentation, there does not seem to be something specific there (other > than saying download this tar file and install it). > > I like how one can install additional packages in 'R' . In 'R' one can do > all that from the user interface for R by a pull-down menu, then one > selects > a mirror site, then one can see all the packages available, then select > the > package to download, and the rest is done automatically. (The package is > downloaded, installed, etc...) That's mainly what easy_install does, plus dependency checking. -- Gabriel Genellina From petr.jakes.tpc at gmail.com Fri Jan 4 12:50:16 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Fri, 4 Jan 2008 09:50:16 -0800 (PST) Subject: Pivot Table/Groupby/Sum question References: <148c3214-77b9-47b0-a680-ffb85dd3efcd@e6g2000prf.googlegroups.com> <63a5a87e-3385-4ef0-80a3-cd1a01eeeac3@w38g2000hsf.googlegroups.com> <276d150b-6b2a-4973-8569-bd8cad6df948@s19g2000prg.googlegroups.com> <018c37d5-67c0-4995-88e3-86f701580c26@e23g2000prf.googlegroups.com> <5d6721cc-1912-4adc-9e47-0afa21c51c89@21g2000hsj.googlegroups.com> <17de023b-8dfd-4478-8271-96e21968d489@s8g2000prg.googlegroups.com> <39fd9ee5-d874-4cea-a7bb-64ab62594332@m34g2000hsf.googlegroups.com> <14a5ef8d-41c8-4164-8a5b-f992c7d12990@u10g2000prn.googlegroups.com> <84ab8796-cef2-4e02-bd91-c5226e2b283b@u10g2000prn.googlegroups.com> Message-ID: <55d47b0b-3655-45f9-9e19-088d67157758@d21g2000prf.googlegroups.com> On Jan 4, 4:55 pm, patrick.wa... at gmail.com wrote: > Petr thanks so much for your input. I'll try to learnSQL, especially > if I'll do a lot of database work. > > I tried to do it John's way as en exercise and I'm happy to say I > understand a lot more. Basically I didn't realize I could nest > dictionaries like db = {country:{genre:{sub_genre:3}}} and call them > like db[country][genre][sub_genre]. The Python Cookbook was quite > helpful to figure out why items needed to be added the way they did. > Also using the structure of the dictionary was a conceptually easier > solution than what I found onhttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334695. > > So, now I need to work on writing it to Excel. I'll update with the > final code. > Hi, good to know you have succeded. I think it is matter of taste which way to go (dictionary or database). My feelig is: for data use database! If you are trying to work with data, you will need it sooner or later anyway. Again: database is made for data! :-) Writing your data to excel? Just save your numbers separated by commas in the file with the extension csv (my_data.csv) and you can open it directly in Excel. Good luck :-) Petr From 42flicks at gmail.com Thu Jan 31 00:07:40 2008 From: 42flicks at gmail.com (Mike D) Date: Thu, 31 Jan 2008 18:07:40 +1300 Subject: Design question - Sharing of single object by multiple processes Message-ID: <2b54d4370801302107v5d65607ey5f18d7d7bd8adaf3@mail.gmail.com> Hello, I've just picked up the Python language and am really enjoying it. I've just signed up to this mailing list and I'm looking forward to taking part in some discussions. My first post is a question I've been pondering for the last couple of days: For relatively static data (such as a list), is it possible to load a single instance and have many python processes access it? I want to have an object in memory. This object will be loaded on application start up and will contain a list of objects. These will be obtained from (most likely) the file system. My reasoning is: I want to prevent a file system or database fetch each time as it seems unnecessary. Is this possible? In Java I'm pretty sure this could implemented with an object factory and static methods. My understanding is that python invokes a separate process for each request however. If possible, what would be a good way of providing a new structure as it is updated. If anyone could give me some advice or point me in the correct direction I'd really appreciate it. Thanks in advance, Mike. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Tue Jan 15 05:06:18 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 15 Jan 2008 02:06:18 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <13od12b23hfv772@corp.supernews.com> <5b035c91-72eb-4d88-b19b-e89470865c5b@i7g2000prf.googlegroups.com> <13ogbfasbcici1c@corp.supernews.com> <389f20bb-ccbf-43bd-b38b-e359a3f62c3a@f47g2000hsd.googlegroups.com> Message-ID: Paul Boddie: > what is everyone with any degree of > concern about Python's performance doing to improve the situation? They are probably developing systems like Cython and ShedSkin, and hoping to see Psyco improved again to manage itertools better (and maybe 64 bit CPUs too). > Sure, C (or actually C++) seems to win the shootout [1], Beside C++ being the faster (not C anymore), there are other ways to "win" the Shootout, like using less RAM, writing shorter code, etc. If you change the way you measure you can see that FreePascal, Ruby and D too "win" the Shootout :-) (the first as the one using less memory, the second one as the one with shorter programs, and the third one as "faster && with shorter programs"). > but there are > plenty of language implementations between g++ and CPython to suggest > that the old choice of extension modules written in C vs. other code > written in Python doesn't provide a complete map of the opportunities. I think in few years it may become feasible to use Pyd to write extensions in D for CPython :-) Bye, bearophile From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 12:04:34 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 18:04:34 +0100 Subject: Unknown cause to error (new to python) In-Reply-To: References: <478e10bd$0$27280$426a34cc@news.free.fr> Message-ID: <478e38f7$0$27530$426a34cc@news.free.fr> Brandon Perry a ?crit : (top-post corrected) >> >> On Wed, 2008-01-16 at 15:12 +0100, Bruno Desthuilliers wrote: >>> Brandon Perry a ?crit : (snip context) >>>> but I am getting some weird errors. >>>> >>>> File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", >>>> line 41, in ? >>>> File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", line 71, in ? >>>> File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", line 4, in ? >>>> File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", line 4, in ? >>>> File "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", line 15, in ? >>> >>> Sorry but my crystal ball is broken. Please post the *whole* traceback. >>> > Sorry, this is all I can get. :-( > > This isn't my webserver, so the only error logs I get are what they give > me. I guess I will just have to keep working at it. Then looks like you're in for hard time. Trying to solve a problem without any relevant information is not rationaly possible. Perhaps you should try voodoo ? > Thanks for looking at it though, Brandon Sorry, can't help much here. From hniksic at xemacs.org Fri Jan 11 12:11:51 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 11 Jan 2008 18:11:51 +0100 Subject: Learning Python via a little word frequency program References: <205c99df-2550-47b0-9c82-020b99ed3122@l1g2000hsa.googlegroups.com> <7x63y0ins2.fsf@ruckus.brouhaha.com> Message-ID: <87abncs2w8.fsf@mulj.homelinux.net> Mike Meyer writes: > On 11 Jan 2008 03:50:53 -0800 Paul Rubin <"http://phr.cx"@NOSPAM.invalid> wrote: > >> rent writes: >> > keys = freq.keys() >> > keys.sort(key = freq.get, reverse = True) >> > for k in keys: >> > print "%-10s: %d" % (k, freq[k]) >> >> I prefer (untested): >> >> def snd((x,y)): return y # I wish this was built-in > > What's wrong with operator.itemgetter? > >> sorted_freq = sorted(freq.iteritems(), key=snd, reverse=True) > > (still untested) > > from operator import itemgetter > sorted_freq = sorted(freq.iteritems(), key=itemgetter(2), reverse=True) It should be itemgetter(1). See how easy it is to get it wrong? :-) (Okay, this was too easy a shot to miss out on; I actually like itemgetter.) From bj_666 at gmx.net Wed Jan 9 14:08:15 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Jan 2008 19:08:15 GMT Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> Message-ID: <5ukkcvF1hs5vpU1@mid.uni-berlin.de> On Wed, 09 Jan 2008 10:56:36 -0800, Louis.Soninhu wrote: > Hi pals > > I have a list like this > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] > > I'd like to remove the first and the last item as they are irrevalent, > and convert it to the dict: > {'tom':'boss','mike':'manager','paul':'employee'} > > I tried this but it didn't work: > > mydict={} > for i in mylist[1:-1]: > a=i.split('=') # this will disect each item of mylist into a 2-item > list > mydict[a[0]]=a[1] > > and I got this: > File "srch", line 19, in > grab("a/tags1") > File "srch", line 15, in grab > mydict[mylist[0]]=mylist[1] > IndexError: list index out of range > > Anyone could shed me a light on this? The real list you used had at least one string without a '=' in it. The list given above doesn't raise that exception: In [102]: mylist=['','tom=boss','mike=manager','paul=employee','meaningless'] In [103]: mydict={} In [104]: for i in mylist[1:-1]: .....: a=i.split('=') .....: mydict[a[0]]=a[1] .....: In [105]: mydict Out[105]: {'mike': 'manager', 'paul': 'employee', 'tom': 'boss'} Ciao, Marc 'BlackJack' Rintsch From http Tue Jan 22 08:24:34 2008 From: http (Paul Rubin) Date: 22 Jan 2008 05:24:34 -0800 Subject: Question on sort() key function References: <5vlopgF1mv4ekU1@mid.dfncis.de> <7xve5mfdmr.fsf@ruckus.brouhaha.com> <5vlqbjF1kl9cjU1@mid.dfncis.de> Message-ID: <7xy7airo19.fsf@ruckus.brouhaha.com> Robert Latest writes: > > flist.sort(key=lambda f: f.mod_date.toordinal) > > It doesn't throw an error any more, but neither does it sort the list. This, > however, works: Oh, I didn't realize that toordinal was a callable, given your earlier sample. You want: flist.sort(key=lambda f: f.mod_date.toordinal() ) From http Sun Jan 20 18:24:27 2008 From: http (Paul Rubin) Date: 20 Jan 2008 15:24:27 -0800 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> <5de6aa5a-767f-4eb7-8bcb-89bc5f83d04b@e4g2000hsg.googlegroups.com> Message-ID: <7xhch8cc7o.fsf@ruckus.brouhaha.com> dg.google.groups at thesamovar.net writes: > Unfortunately I realise I stated the problem imprecisely. You're only > allowed to use each number once (otherwise there's a trivial solution > for every problem, i.e. x/x + x/x + x/x + ... + x/x repeated y times > for target y given any source number x). Trying your program on 234 > from [100,9,7,6,3,1] gives you 9*9*3-9 using the 9 three times. Here's an inefficient solution, that doesn't find 234 but finds 253. If you see a double post, it's because I posted something similar a little while ago but cancelled it since it had a bug. I'm not sure this one is correct either ;-). from operator import * def countdown(nums, trace='', ops=[add,mul,sub,div]): n0,n1s = nums[0], nums[1:] if not n1s: yield n0, str(n0) return for f in ops: for r,t in countdown(n1s, trace, [add, mul, sub]): if f != div or r != 0 and n0 % r == 0: yield f(n0, r), '%s(%s,%s)'% (f.__name__, n0, t) def find_repr(target, nums): # print all representations of target from nums for x,t in countdown(nums): if x == target: print x,t find_repr(253, [100,9,7,6,3,1]) From bignose+hates-spam at benfinney.id.au Thu Jan 24 00:41:02 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 24 Jan 2008 16:41:02 +1100 Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> <87ejc77r3c.fsf@benfinney.id.au> Message-ID: <87abmv7pch.fsf@benfinney.id.au> Ben Finney writes: > glacier writes: > > > I use chinese charactors as an example here. > > > > >>>s1='???' > > >>>repr(s1) > > "'\\xc4\\xe3\\xba\\xc3\\xc2\\xf0'" > > >>>b1=s1.decode('GBK') > > > > My first question is : what strategy does 'decode' use to tell the > > way to seperate the words. I mean since s1 is an multi-bytes-char > > string, how did it determine to seperate the string every 2bytes > > or 1byte? > > The codec you specified ("GBK") is, like any character-encoding > codec, a precise mapping between characters and bytes. It's almost > certainly not aware of "words", only character-to-byte mappings. To be clear, I should point out that I didn't mean to imply static tabular mappings only. The mappings in a character encoding are often more complex and algorithmic. That doesn't make them any less precise, of course; and the core point is that a character-mapping codec is *only* about getting between characters and bytes, nothing else. -- \ "He who laughs last, thinks slowest." -- Anonymous | `\ | _o__) | Ben Finney From christopher.saunter at durham.ac.uk Fri Jan 25 09:24:56 2008 From: christopher.saunter at durham.ac.uk (c d saunter) Date: Fri, 25 Jan 2008 14:24:56 +0000 (UTC) Subject: Windows AVIFile problems References: Message-ID: Thomas Heller (theller at ctypes.org) wrote: : c d saunter schrieb: : > Hi All, : > : The dll is not corrupt. It is the 16-bit dll, possibly present for legacy : 16-bit support. Thomas, Thanks, that explains a lot. Regards, Chris Saunter From huayang.xia at gmail.com Thu Jan 24 17:17:09 2008 From: huayang.xia at gmail.com (Huayang Xia) Date: Thu, 24 Jan 2008 14:17:09 -0800 (PST) Subject: PyPerforce: How to open file for editing Message-ID: I'm completely new to pyperforce. I want to open a file (check out a file) for editing. How can I do it from PyPerforce? Another thing is how can I add files to my created label? Thanks in advance. From sjmachin at lexicon.net Thu Jan 31 14:48:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 31 Jan 2008 11:48:36 -0800 (PST) Subject: PIL linux err References: Message-ID: On Feb 1, 5:41 am, dzizes wrote: > Hi, > > I'm trying to run simple .py on linux, which is using PIL. Below error > message which I receive: > > File "/usr/lib/python2.4/site-packages/PIL/Image.py", line 960, in > histogram > self.load() > File "/usr/lib/python2.4/site-packages/PIL/ImageFile.py", line 180, in > load > d = Image._getdecoder(self.mode, d, a, self.decoderconfig) > File "/usr/lib/python2.4/site-packages/PIL/Image.py", line 375, in > _getdecoder > raise IOError("decoder %s not available" % decoder_name) > IOError: decoder jpeg not available > > Do you know what might be the problem? Is your googler broken? See: http://effbot.org/zone/pil-decoder-jpeg-not-available.htm From paddy3118 at googlemail.com Mon Jan 7 02:33:06 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 6 Jan 2008 23:33:06 -0800 (PST) Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> Message-ID: <91f8a1dd-248c-40c3-a70a-6f0caefb6c4a@s8g2000prg.googlegroups.com> On Jan 5, 11:07 pm, bearophileH... at lycos.com wrote: > Paddy: > > > Not really, it seems to me to be going the exact opposite way with > > languages with automatic type conversions being seen as not suited for > > larger programs. > > In Java you can add the number 1 to a string, and have it > automatically converted to string before the string join... What do > you think of that feature? > > Bye, > bearophile Hi Bearophile, Unfortunately, (fortunately?), I don't know enough Java. I can just get by reading correct Java programs so could not really comment. If Java is flexible enough to allow the '+' operator to be defined between strings and integers and left it to the programmer to define the result then that would be a good thing, but having the language automatically define conversions between unrelated types would break strong typing which I have read that Java enjoys. http://en.wikipedia.org/wiki/Type_system#Strong_and_weak_typing - Paddy. From peng.kyo at gmail.com Thu Jan 17 01:11:57 2008 From: peng.kyo at gmail.com (J. Peng) Date: Thu, 17 Jan 2008 14:11:57 +0800 Subject: assigning values in python and perl In-Reply-To: References: <18c1e5f20801161934m69ff44edo1e35f5381f7d2928@mail.gmail.com> Message-ID: <18c1e5f20801162211u661efa36u582eea623449c5d4@mail.gmail.com> On Jan 17, 2008 1:54 PM, Mel wrote: > > test(a) (along with def test(x)) takes the object named 'a' in the > current namespace and binds it with the name 'x' in function test's > local namespace. So, inside test, the name 'x' starts by referring to > the list that contains [1,2,3]. But the only use test makes of the > name 'x' is to re-bind it to a new list [4,5,6]. Exiting test, the > local namespace is thrown away. > Hi, Yes I know it pretty well now, but thanks for the pointer. What I asked is that, if we re-write that code with perl or C, we'll get different results. From fredrik at pythonware.com Thu Jan 10 16:54:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jan 2008 22:54:16 +0100 Subject: Newbie question on Classes In-Reply-To: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> References: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> Message-ID: Adrian Wood wrote: > I can call man.state() and then woman.state() or Person.state(man) and > Person.state(woman) to print the status of each. This takes time and > space however, and becomes unmanageable if we start talking about a > large number of objects, and unworkable if there is an unknown number. > What I'm after is a way to call the status of every instance of Man, > without knowing their exact names or number. > > I've gone through the relevant parts of the online docs, tried to find > information elsewhere online, and looked for code samples, but the > ionformation either isn't there, or just isn't clicking with me. I've > tried tracking the names of each object in a list, and even creating > each object within a list, but don't seem to be able to find the right > syntax to make it all work. For a start, how about: class Person: ... your class ... persons = [] man = Person() persons.add(man) woman = Person() persons.add(woman) for p in persons: print p, p.state() Once you've gotten this to work, you can, if you want, look into moving the list maintenance into the class itself (i.e. let the __init__ function add the person to the list, and provide a destroy method that removes it from the list). And once you've gotten that to work, you can look at the "weakref" module for more elegant ways to handle destruction. But one step at a time... From tjreedy at udel.edu Sun Jan 27 19:26:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jan 2008 19:26:46 -0500 Subject: explicit protocols and duck typing References: <5e28034f-a20f-4aa7-b299-9c9132ef2566@c4g2000hsg.googlegroups.com> Message-ID: wrote in message news:5e28034f-a20f-4aa7-b299-9c9132ef2566 at c4g2000hsg.googlegroups.com... | Hi all, | | As I understand it, the idea behind duck typing is that you just take | an object and if it has the methods you want to use you use it | assuming it to be the right type of object. I'm interested in | extending this idea a bit, but I feel the sort of thing I have in mind | has already been thought of. So for example, in the program I'm | writing a 'state variable' specifier can be either an integer or a | string (the string name is mapped to an integer by another function | getvarindex(name)). Why a function rather than a dict 'varindex'? The valid strings are then varindex.keys(). You might want a build_varindex() func though. |In this case, I can't do duck typing by seeing if | the object has a method or not, because both of the types are built in | types. builtin types have methods same as user types. It is not clear from your description why there should be any restriction on state-variable specifier other than hashable since any set of hashable objects can be easily mapped to range(len() with a dict. Whether you merely document the rules or write code to enforce them should partly depends on who suffers when they are broken. tjr From jeff at jmcneil.net Thu Jan 24 12:49:19 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 24 Jan 2008 12:49:19 -0500 Subject: Duplicating a variable In-Reply-To: References: Message-ID: <82d28c40801240949h4545636xbaa2751086939d32@mail.gmail.com> Have a look at the copy module if you have a somewhat "complex" object graph to duplicate. Remember, you're essentially just creating another reference to a singular list object with simple assignment (a = b). >>> a = [1,2,3,4, ['5a', '5b', '5c', ['6a', '6b','6c']], 7,8] >>> b = a >>> a [1, 2, 3, 4, ['5a', '5b', '5c', ['6a', '6b', '6c']], 7, 8] >>> a[4][1] = None >>> a [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> b [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> import copy >>> d = copy.deepcopy(a) >>> d [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> a [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> a[4][1] = "Something" >>> a [1, 2, 3, 4, ['5a', 'Something', '5c', ['6a', '6b', '6c']], 7, 8] >>> b [1, 2, 3, 4, ['5a', 'Something', '5c', ['6a', '6b', '6c']], 7, 8] >>> d [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> Thanks, Jeff On 1/24/08, hnessenospam at yahoo.com wrote: > > I have run into a bit of a subtle problem. How do I go about > duplicating a variable (particularly a list of lists) in python. I > was surprised when simple assignment didn't work. For example, let y = > [1,2,3] > > >>> x = y > >>> x[2] = 5 > >>> y > [1,2,5] > > It seems that simply assigning x to y allows further modification of y > via x. (I'm new to python and I'm sure this is obvious to experienced > users). So my question, how do I go about duplicating a variable > which I can then manipulate independently? > > Thanks, > > -Hans > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Fri Jan 25 11:23:40 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 25 Jan 2008 10:23:40 -0600 Subject: Automatically Writing a Dictionary In-Reply-To: <8CA2D8436C5B761-E80-5C4@FWM-D40.sysops.aol.com> References: <8CA2C0BF25FCAA6-1374-117B@WEBMAIL-DC15.sysops.aol.com> <47979785.502@tim.thechases.com> <8CA2D8436C5B761-E80-5C4@FWM-D40.sysops.aol.com> Message-ID: <479A0D0C.1040703@tim.thechases.com> >> d = dict(line.split(',').rstrip('\n')? > > Thanks. That worked except for the rstrip. So I did this: Sorry...I got the order wrong on them (that's what I get for editing after copy&pasting). They should be swapped: d = dict(line.rstrip('\n').split(',')) to strip off the newline before you split it. -tkc From news at neither-nor.net Wed Jan 23 09:43:47 2008 From: news at neither-nor.net (Kristian Domke) Date: Wed, 23 Jan 2008 15:43:47 +0100 Subject: twisted: problem with sftp-client Message-ID: Hello Folks, I don't know, if it is ok to post large portions of code, but I have really no idea where the problem lies, so I don't have much of a choice. I am programming a tool, which in the end shall connect to an sftp-server, take the list of files in a specified directory, searches for some special names and mailes them to different persons. I am only at the start at the moment. As orientation I use the cftp.py programm from twisted.conch with some alterations because of not having userinteraction. At its current state the programm should do nothing but getting the listing of files from a server. It works fine with the cfto.py, so the server is ok. But while the cftp.py script gets 'files' as an exceptions.EOFError exeption in the StdioClient._cbReadFile at the end of the listing, I just get another list and run into wall (aka Traceback): > 2008/01/23 16:14 +0200 [SSHChannel session (0) on SSHService > ssh-connection on SimpleTransport,client] Unhandled Error > Traceback (most recent call last): > File "/usr/lib/python2.5/site-packages/twisted/python/log.py", > line 48, in callWithLogger > return callWithContext({"system": lp}, func, *args, **kw) > File "/usr/lib/python2.5/site-packages/twisted/python/log.py", > line 33, in callWithContext > return context.call({ILogContext: newCtx}, func, *args, > **kw) > File > "/usr/lib/python2.5/site-packages/twisted/python/context.py", line 59, > in callWithContext > return self.currentContext().callWithContext(ctx, func, > *args, **kw) > File > "/usr/lib/python2.5/site-packages/twisted/python/context.py", line 37, > in callWithContext > return func(*args,**kw) > --- --- > File > "/usr/lib/python2.5/site-packages/twisted/conch/ssh/filetransfer.py", > line 52, in dataReceived > f(data) > File > "/usr/lib/python2.5/site-packages/twisted/conch/ssh/filetransfer.py", > line 694, in packet_STATUS > msg, data = getNS(data) > File > "/usr/lib/python2.5/site-packages/twisted/conch/ssh/common.py", line > 39, in getNS > l, = struct.unpack('!L',s[c:c+4]) > File "struct.py", line 87, in unpack > return o.unpack(s) > struct.error: unpack requires a string argument of length 4 I have no Idea, and hope here is someone who can help me. Kristian ---------------------------------------- from twisted.internet import reactor, defer, protocol from twisted.conch.ssh import connection, filetransfer, keys, userauth from twisted.conch.ssh import channel, transport, common from twisted.conch.client import options, default, connect from twisted.python import log, failure import sys, time publicKey = 'some public key' privateKey ='''some private key''' USER = 'sftpuser' def run(): opts = options.ConchOptions() opts['host'] = 'localhost' opts['user'] = USER opts['port'] = 22 log.startLogging(sys.stdout) log.msg('logging started') protocol.ClientCreator(reactor, SimpleTransport).connectTCP(opts['host'], opts['port']) reactor.run() # start the event loop def doConnect(options): host = options['host'] user = options['user'] port = options['port'] conn = SSHConnection vhk = default.verifyHostKey uao = UserAuthClient(user, conn) d = connect.connect(host, port, options, vhk, uao) d.addErrback(_ebExit) return d def _ebExit(f): if hasattr(f.value, 'value'): s =f.value.value else: s = str(f) log.msg( s ) try: reactor.stop() except: pass def _cleanExit(): try: reactor.stop() except: pass class SimpleTransport(transport.SSHClientTransport): def verifyHostKey(self, hostKey, fingerprint): log.msg('host key fingerprint: %s' % fingerprint) return defer.succeed(1) def connectionSecure(self): self.requestService( UserAuthClient(USER, SSHConnection())) class UserAuthClient(userauth.SSHUserAuthClient): """Simple User Authentication Client""" def getPassword(self, prompt = None): return # this says we won't do password authentication def getPublicKey(self): return keys.getPublicKeyString(data = publicKey) def getPrivateKey(self): return defer.succeed(keys.getPrivateKeyObject(data = privateKey)) class SSHConnection(connection.SSHConnection): def serviceStarted(self): log.msg('Service started') self.openChannel(SSHSession(conn = self)) class SSHSession(channel.SSHChannel): name = 'session' def channelOpen(self, irgnoreData): log.msg('session %s is open' % self.id) request = 'subsystem' d = self.conn.sendRequest(self, request, common.NS('sftp'), wantReply=1) d.addCallback(self._cbSubsystem) d.addErrback(_ebExit) return d def _cbSubsystem(self, result): log.msg('Establishing Subsystem') self.client = SFTPClient() self.client.makeConnection(self) self.dataReceived = self.client.dataReceived def openFailed(self, reason): log.err('Opening Session failed: %s' % reason) _cleanExit() class SFTPClient(filetransfer.FileTransferClient): def __init__(self): filetransfer.FileTransferClient.__init__(self) self.currentDirectory = '' def connectionMade(self): log.msg('Connection with SFTPClient established') self.realPath('').addCallback(self._cbSetCurDir).addErrback(_cleanExit) def _cbSetCurDir(self, path): self.currentDirectory = path log.msg('currentDirectory set to %s.' % path) #self.cmd_MKDIR('test') self.cmd_LS(self.currentDirectory) def cmd_MKDIR(self, path): return self.makeDirectory(path, {}).addCallback(self._ignore) def cmd_LS(self, path): log.msg('List Stucture of %s' % path) d = self.openDirectory(path) d.addCallback(self._cbOpenList) def _cbOpenList(self, directory): files = [] log.msg('direc.:%s' % str(directory)) log.msg('direc.:%s' % type(directory)) log.msg('direc.:%s' % str(directory.parent)) log.msg('direc.:%s' % type(directory.parent)) d = directory.read() d.addCallback(self._cbReadFile, files, directory) d.addErrback(self._ebRaeadFile, files, directory) def _ebReadFile(self, files, l, directory): log.msg('**errback!**') self._cbReadFile(files, l, directory) def _cbReadFile(self, files, l, directory): log.msg('ReadFile called') log.msg('direc.:%s' % type(files)) if not isinstance(files, failure.Failure): log.msg('if not') l.extend(files) d = directory.read() #d.addCallback(self._ignore) d.addBoth(self._cbReadFile, l, directory) return d else: log.msg('else') reason = files reason.trap(EOFError) directory.close() return l def _ignore(self, *args): pass if __name__ == "__main__": run() From fredrik at pythonware.com Tue Jan 8 07:16:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 Jan 2008 13:16:42 +0100 Subject: Open a List of Files In-Reply-To: References: Message-ID: BJ Swope wrote: > the code looks ok. please define "not working". > > Yep, defining "not working" is always helpful! :) > > I want to have all 3 files open at the same time. I will write to each > of the files later in my script but just the last file is open for writing. to keep more than one file open, you need more than one variable, or a variable that can hold more than one object. if the number of files may vary, put the file objects in a list. if the number of files is constant, you might as well just use three variables and call open three times; e.g. def getfilename(name): return os.path.join(Host_Path, name) messages_file = open(getfilename("messages"), "w") recipients_file = open(getfilename("recipients"), "w") viruses_file = open(getfilename("viruses"), "w") From bearophileHUGS at lycos.com Fri Jan 11 12:50:46 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 11 Jan 2008 09:50:46 -0800 (PST) Subject: Converting a bidimensional list in a bidimensional array References: <13c40542-208c-48eb-a48e-62966a6ca0bc@s12g2000prg.googlegroups.com> <13o9kupahavp952@corp.supernews.com> <2e29293f-4fd2-4cea-b330-93e8968438b4@m77g2000hsc.googlegroups.com> <005679e9-c355-4e0a-872c-e0dae3181fd0@x69g2000hsx.googlegroups.com> <3ae88ff6-38d5-4fde-800d-c22e73f89c5f@i3g2000hsf.googlegroups.com> Message-ID: <054ea1c0-2b68-44cf-b7c6-f8e0d1a97a62@i72g2000hsd.googlegroups.com> Santiago Romero: > If each integer-python-object takes 16 bytes, this makes 60000 * 16 = > almost 1MB of memory just for the tilemaps... > Using array of type H (16 bits per item = 2 bytes), my maps take just > 60000*2 = 120KB of memory. > Do you think I should still go with lists instead of an H-type array? 1 MB or RAM may be small enough nowdays, so you may use lists. If not, then the array.array solution can be good. You may even store just the rows of your images as arrays, so you can use the usual syntax [][]. Another alternative is to use some external numerical lib, it's quite useful if you use pygame, to blit, process images, store and process bitmaps, etc. Bye, bearophile From bill.wws at gmail.com Thu Jan 17 10:38:57 2008 From: bill.wws at gmail.com (bill.wu) Date: Thu, 17 Jan 2008 07:38:57 -0800 (PST) Subject: the tutor list has been strangely silent for a few days. Anyone know what has happened? Message-ID: <2a3fed86-fc50-4d43-88af-38ea155fc09c@e4g2000hsg.googlegroups.com> the tutor list has been strangely silent for a few days. Anyone know what has happened? why? From princismo at gmail.com Mon Jan 21 11:15:02 2008 From: princismo at gmail.com (=?Big5?B?w0P4rw==?=) Date: Mon, 21 Jan 2008 08:15:02 -0800 (PST) Subject: How to solve "TypeError: list indices must be integers". Message-ID: <3f3ca8c6-b57c-43ff-bf80-11768e1a0f94@s8g2000prg.googlegroups.com> This is more details about my problem, which I running my py script for my project. Programming in pythoncard that we can develop a GUI based application easily. I was assigned dialog.colorDialog(self) return value to a result object, but I suspect that result.color is the attribute of the result object that can assign to a string variable. There is a error prompt from python console "TypeError: list indices must be integers". Have any suggestion to solve this problem? When I print result.color, it is print out something like (255,0,0). How to covert result.color into a string? How to convert a string to result.color type? adrian From yuxi at gatech.edu Thu Jan 17 11:31:50 2008 From: yuxi at gatech.edu (Yu-Xi Lim) Date: Thu, 17 Jan 2008 11:31:50 -0500 Subject: How to create graphs an embed them in GUI? In-Reply-To: References: Message-ID: Heiko Niedermeyer wrote: > Sorry for the fuzzy subject... > > Currently I'm writing a little programm to extract some chemical > information out of a text file, and then present it in a pleasant way. > The Extraction works so far, so now the presentation will be next. > If the GUI is only for the graph, try matplotlib. It should do the graphs/charts you require. If necessary, you can combine matplotlib with another GUI toolkit for a full GUI. This might be useful if you want to display menus and dialogs to load the text files, etc. 3D is a different matter. I'd personally go with Python bindings for VTK, but be warned that the learning curve is very steep and the online docs are quite sparse (you're encouraged to buy the book, which is probably the main source of income for the VTK devs). From devraj at gmail.com Thu Jan 10 21:37:59 2008 From: devraj at gmail.com (Devraj) Date: Thu, 10 Jan 2008 18:37:59 -0800 (PST) Subject: Detecting OS platform in Python Message-ID: Hi everyone, My Python program needs reliably detect which Operating System its being run on, infact it even needs to know which distribution of say Linux its running on. The reason being its a GTK application that needs to adapt itself to be a Hildon application if run on devices like the N800. I have been searching around for an answer to this, and did find some messages on a lists that suggested the use of sys.platform to detect platform, with counter posts saying that it didn't work on Windows etc. Can anyone please shed some light on this? Thanks a lot. From fuzzyman at gmail.com Wed Jan 23 16:47:37 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Wed, 23 Jan 2008 13:47:37 -0800 (PST) Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? References: Message-ID: ios... at gmail.com wrote: > Hi, I am looking for a HTML parser who can parse a given page into > a DOM tree, and can reconstruct the exact original html sources. > Strictly speaking, I should be allowed to retrieve the original > sources at each internal nodes of the DOM tree. > I have tried Beautiful Soup who is really nice when dealing with > those god damned ill-formed documents, but it's a pity for me to find > that this guy cannot retrieve original sources due to its great tidy > job. > Since Beautiful Soup, like most of the other HTML parsers in > python, is a subclass of sgmllib.SGMLParser to some extent, I have > investigated the source code of sgmllib.SGMLParser, see if there is > anything I can do to tell Beautiful Soup where he can find every tag > segment from HTML source, but this will be a time-consuming job. > so... any ideas? > A while ago I had a similar need, but my solution may not solve your problem. I wanted to rewrite URLs contained in links and images etc, but not modify any of the rest of the HTML. I created an HTML parser (based on sgmllib) with callbacks as it encounters tags and attributes etc. It is easy to process a stream without 'damaging' the beautiful orginal structure of crap HTML - but it doesn't provide a DOM. http://www.voidspace.org.uk/python/recipebook.shtml#scraper All the best, Michael Foord http://www.manning.com/foord > > cheers > kai liu From ptmcg at austin.rr.com Wed Jan 30 20:01:42 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 30 Jan 2008 17:01:42 -0800 (PST) Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! References: Message-ID: <8713cbea-7e82-4713-b411-b62f49b40f79@b2g2000hsg.googlegroups.com> On Jan 30, 6:40?pm, "Blubaugh, David A." wrote: > I do not understand why no one has answered the following question: > > Has anybody worked with Gene Expression Programming???? ? > > David Blubaugh > Sorry, I was too busy reading the posts about the pubic hair. And did you really wait only 1/2 an hour before going ballistic that NOBODY ANSWERED YOUR QUESTION????!!!!!!!!!!!!!! Take a pill. -- Paul From lists at cheimes.de Mon Jan 28 12:08:50 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 28 Jan 2008 18:08:50 +0100 Subject: Get Available Functions In-Reply-To: <479E0A7A.9080305@tim.thechases.com> References: <020501c861ca$d604dc70$820e9550$@rawlins@thinkbluemedia.co.uk> <479E0A7A.9080305@tim.thechases.com> Message-ID: Tim Chase wrote: > I've had a couple cases where the underlying module was written > in C (mod_python in particular...don't know if it still has this > problem) where dir() wouldn't actually tell you about the object, > but for most cases, dir() will get you pointed in the right > dir-ection. :) dir(), inspect and help() can't retrieve the method signature from a C function (builtin_function_or_method type). Christian From apatheticagnostic at gmail.com Fri Jan 4 16:06:02 2008 From: apatheticagnostic at gmail.com (apatheticagnostic) Date: Fri, 4 Jan 2008 13:06:02 -0800 (PST) Subject: Skill Resume Achievements, What Good Goes Here? References: Message-ID: <724e4836-d895-4210-972d-dd8f861902df@l1g2000hsa.googlegroups.com> On Jan 2, 11:31 am, kyoso... at gmail.com wrote: > On Jan 2, 9:59 am, vbgunz wrote: > > > I spent some time working on a skill resume, the kind of resume > > college students put together and realized, I am not in college and > > everything I learned was self-taught. Of course I would like some real > > world achievements but don't consider throw-away code an achievement > > and am failing to really see any. I don't even wish to entertain the > > thought of lying about anything. > > > What are some achievements an employer may be looking for in someone > > willing to start at ground level, entry level, intern, etc? What are > > some real world achievements every n00b will need under his/her belt > > in order to be taken seriously? > > Internships are always a good thing to have. If you've contributed to > open source projects, I'd put that on there. If you're applying for > some kind of programming job, they'll probably want to see some of > your code, know what home-brewed projects you've done and how long > they took to complete, issues you ran into, etc. > > That might get you started anyway. > > Mike As someone else who's self-educated and curious about this, would listing canonical comp-sci books that you've gone through on your own and understood be a reasonable thing to mention? For example, SICP, PLAI, etc? From jarausch at skynet.be Thu Jan 31 14:51:23 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Thu, 31 Jan 2008 20:51:23 +0100 Subject: helper function in a class' namespace Message-ID: <47a226bb$0$2982$ba620e4c@news.skynet.be> Hi, the following code works fine def Helper(M) : return 'H>'+M class A(object): def __init__(self,Msg) : print Helper(Msg) B=A('ZZ') but the Helper function is in the module's namespace. I'd like to put it into class A's namespace. Note, the Helper function doesn't need access to any instance attributes. The first variant class A(object): def Helper(M) : return 'H>'+M def __init__(self,Msg) : print Helper(Msg) doesn't work since Python is looking for a global function Helper (why?) The alternative class A(object): def Helper(M) : return 'H>'+M def __init__(self,Msg) : print A.Helper(Msg) doesn't work either since now the first argument to A.Helper must be 'A'. So, isn't it possible to have a helper function in the namespace of a class without (the overhead of) passing a 'self' or a 'cls' parameter? Probably I'm hurt by my C++ history. Many thanks for your help, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From lists.gnarlodious at gmail.com Tue Jan 8 00:27:40 2008 From: lists.gnarlodious at gmail.com (Gnarlodious) Date: Mon, 7 Jan 2008 22:27:40 -0700 Subject: mod-python on Mac OSX 10.5 Message-ID: <4782fe18$0$26015$88260bb3@free.teranews.com> I am trying to install mod_python on OSX 10.5, Intel version. sudo apachectl configtest tells me this: httpd: Syntax error on line 114 of /private/etc/apache2/httpd.conf: Cannot load /usr/libexec/apache2/mod_python.so into server: dlopen(/usr/libexec/apache2/mod_python.so, 10): no suitable image found. Did find:\n\t/usr/libexec/apache2/mod_python.so: mach-o, but wrong architecture I attempted to follow instructions found on these pages but it didn't work: Can anyone tell me what is causing this error? -- Gnarlie http://Gnarlodious.com/ -- Posted via a free Usenet account from http://www.teranews.com From mccredie at gmail.com Thu Jan 10 23:58:51 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 10 Jan 2008 20:58:51 -0800 (PST) Subject: for loop without variable References: <3b3bfd5c-7425-42df-8ca0-f6ad2a7fca33@q39g2000hsf.googlegroups.com> <87fxx6p1nr.fsf@mulj.homelinux.net> Message-ID: <71343659-f8df-475b-813c-973fa82948e8@m77g2000hsc.googlegroups.com> On Jan 10, 10:36 pm, Marty wrote: > Hrvoje Niksic wrote: > > Mike Meyer writes: > > >> It sounds to me like your counter variable actually has meaning, > > > It depends how the code is written. In the example such as: > > > for meaningless_variable in xrange(number_of_attempts): > > ... > > > the loop variable really has no meaning. Rewriting this code only to > > appease pylint is exactly that, it has nothing with making the code > > more readable. > > >> you've hidden that meaning by giving it the meaningless name "i". If > >> you give it a meaningful name, then there's an obvious way to do it > >> (which you listed yourself): > > >> while retries_left: > > [...] > > > This loop contains more code and hence more opportunities for > > introducing bugs. For example, if you use "continue" anywhere in the > > loop, you will do one retry too much. > > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) > > This caused me to wonder why Python does not have a "foreach" statement (and > also why has it not come up in this thread)? I realize the topic has probably > been beaten to death in earlier thread(s), but does anyone have the short answer? Pythons `for' essentially is foreach. The code below does the same thing as what you have posted does. Actually, I've found that if you find yourself ever doing range(len(data_in)) in python, it is time to take a second look. data_out = [] for x in data_in: data_out.append([]) `range' is just a function that returns a list. Matt From ajaksu at gmail.com Sat Jan 5 12:23:13 2008 From: ajaksu at gmail.com (ajaksu) Date: Sat, 5 Jan 2008 09:23:13 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <48ce2eef-cee9-4398-9a62-a0ccf8391458@i29g2000prf.googlegroups.com> <0086a2fc-0492-429b-9ec8-68ace739856f@s12g2000prg.googlegroups.com> <2ab22f95-d132-4e3c-8b68-bcbcee64e2ef@j78g2000hsd.googlegroups.com> Message-ID: <52aaba7c-6c39-49e3-a3a6-9c346fe9a8d8@e10g2000prf.googlegroups.com> > OTOH, if you do know that the chances are high enough, you can try > choosing items randomly without substitution (adapted from random.py's > sample): Sorry, this works: def randpickuntil(lst, prop=bool): selected = set() n = len(lst) for i in xrange(n): j = int(random() * n) while j in selected: j = int(random() * n) if prop(lst[j]): return lst[j] selected.add(j) Gotta say it's much faster on average than shuffle for moderately to highly probable tests, but might become pathological (i.e. run for minutes) for very large lists in which prop(x) is False for all. From ganeshborse at gmail.com Thu Jan 31 05:44:25 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Thu, 31 Jan 2008 02:44:25 -0800 (PST) Subject: Import of cStringIO failing with "undefined symbol: PyObject_SelfIter" on python-2.3.3-88.9 References: <13cb45c0-5b5d-4151-9797-d851ed3ad544@i7g2000prf.googlegroups.com> Message-ID: <8a39673c-528a-4512-a3ca-89ece8b7cf5f@l32g2000hse.googlegroups.com> On Jan 10, 6:07?pm, grbgooglefan wrote: > I am importing cStringIO module in my PythonC++ embedded program. > > The import is failing with the following error: > ImportError: /usr/lib/python2.3/lib-dynload/cStringIO.so: undefined > symbol:PyObject_SelfIter > > I have python-2.3.3-88.9.x86 installed on my machine. > Why is this error coming? how can I resolve this undefined symbol? > Do I need to import anything before this? Workaround to avoid this problem is in another post named "PyImport_ImportModule("cStringIO") failure with undefined symbol Options". From nytrokiss at gmail.com Wed Jan 23 14:10:46 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 23 Jan 2008 20:10:46 +0100 Subject: Stripping whitespace In-Reply-To: <5vphe6F1njt09U1@mid.uni-berlin.de> References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> <5vphe6F1njt09U1@mid.uni-berlin.de> Message-ID: <8a6b8e350801231110n55dfcdaft5ff670c09b0155ef@mail.gmail.com> Using the split method is the easiest! On 23 Jan 2008 19:04:38 GMT, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jan 2008 10:50:02 -0800, ryan k wrote: > > > Hello. I have a string like 'LNAME > > PASTA ZONE'. I want to create a list of those words and > > basically replace all the whitespace between them with one space so i > > could just do lala.split(). Thank you! > > You *can* just do ``lala.split()``: > > In [97]: lala = 'LNAME PASTA ZONE' > > In [98]: lala.split() > Out[98]: ['LNAME', 'PASTA', 'ZONE'] > > Ciao, > Marc 'BlackJack' Rintsch > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com From pavlovevidence at gmail.com Fri Jan 18 14:59:56 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 18 Jan 2008 11:59:56 -0800 (PST) Subject: Using "pickle" for interprocess communication - some notes and things that ought to be documented. References: <478FAC5A.50206@animats.com> Message-ID: <008e67da-7ad7-4cc5-a9d0-405d89297217@v29g2000hsf.googlegroups.com> On Jan 17, 2:28 pm, John Nagle wrote: > It's possible to use "pickle" for interprocess communication over > pipes, but it's not straightforward. > > First, "pickle" output is self-delimiting. > Each dump ends with ".", and, importantly, "load" doesn't read > any characters after the "." So "pickle" can be used repeatedly > on the same pipe, and one can do repeated message-passing this way. This > is a useful, but undocumented, feature. > > It almost works. > > Pickle's "dump" function doesn't flush output after dumping, so > there's still some data left to be written. The sender has to > flush the underlying output stream after each call to "dump", > or the receiver will stall. The "dump" function probably ought to flush > its output file. But... you can also write multiple pickles to the same file. Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import cPickle >>> f = open('xxx.pkl','wb') >>> cPickle.dump(1,f) >>> cPickle.dump('hello, world',f) >>> cPickle.dump([1,2,3,4],f) >>> f.close() >>> f = open('xxx.pkl','rb') >>> cPickle.load(f) 1 >>> cPickle.load(f) 'hello, world' >>> cPickle.load(f) [1, 2, 3, 4] An automatic flush would be very undesirable there. Best to let those worrying about IPC to flush the output file themselves: which they ought to be doing regardless (either by explicitly flushing or using an unbuffered stream). > It's also necessary to call Pickle's "clear_memo" before each "dump" > call, since objects might change between successive "dump" calls. > "Unpickle" doesn't have a "clear_memo" function. It should, because > if you keep reusing the "Unpickle" object, the memo dictionary > fills up with old objects which can't be garbage collected. > This creates a memory leak in long-running programs. This is all good to know. I agree that this is a good use case for a clear_memo on a pickle unloader. > Then, on Windows, there's a CR LF problem. This can be fixed by > launching the subprocess with > > proc = subprocess.Popen(launchargs, > stdin=subprocess.PIPE, stdout=subprocess.PIPE, > universal_newlines=True) > > Failure to do this produces the useful error message "Insecure string pickle". > Binary "pickle" protocol modes won't work at all in this situation; "universal > newline" translation is compatible, not transparent. On Unix/Linux, this > just works, but the code isn't portable. I would think a better solution would be to use the -u switch to launch the subprocess, or the PYTHONUNBUFFERED environment variable if you want to invoke the Python script directly. It opens up stdin and stdout in binary, unbuffered mode. Using "univeral newlines" in a non-text format seems like it's not a good idea. For text-format pickles it'd be the right thing, of course. > Incidentally, in the subprocess, it's useful to do > > sys.stdout = sys.stderr > > after setting up the Pickle objects. This prevents any stray print statements > from interfering with the structured Pickle output. Nice idea. > Then there's end of file detection. When "load" reaches an end of > file, it properly raises EOFError. So it's OK to do "load" after > "load" until EOFerror is raised. > > "pickle" and "cPickle" seem to be interchangeable in this application, > so that works. > > It's a useful way to talk to a subprocess, but you need to know all the > issues above to make it work. Thanks: this was an informative post Carl Banks From steve at REMOVE-THIS-cybersource.com.au Fri Jan 4 17:15:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 04 Jan 2008 22:15:01 -0000 Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: <13ntbv51tqcm7c@corp.supernews.com> On Fri, 04 Jan 2008 09:29:50 -0800, bukzor wrote: > Why cant you implement < for complex numbers? Maybe I'm being naive, but > isn't this the normal definition? > a + bi < c + di iff sqrt(a**2 + b**2) < sqrt(c**2, d**2) No, it is not. Ordered comparisons are not defined for complex numbers. Which is bigger, 4+2j or 2+4j? > How do you implement a set without sorting? With a hash table. Or if you are willing to limit yourself to sets of small integers, you can implement it using bit flipping. E.g. 5 is an element of the set if bit 5 is on. > Are you expecting better than O(log n)? Sure. -- Steven From gherron at islandtraining.com Mon Jan 14 03:44:35 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 14 Jan 2008 00:44:35 -0800 Subject: NotImplimentedError In-Reply-To: <882739.52486.qm@web63705.mail.re1.yahoo.com> References: <882739.52486.qm@web63705.mail.re1.yahoo.com> Message-ID: <478B20F3.7010208@islandtraining.com> hakim ouaras wrote: > Hi, > > I am begining with python, I want to know what is the utility and how > to use the expression "NotImplementedError". > > Thak you for your answers > Hakim > > ------------------------------------------------------------------------ > Never miss a thing. Make Yahoo your homepage. > It's meant to be used to mark a procedure that you intend to write, but have not yet done so. The procedure you have not yet written "raises" that exception to indicate that it is not yet implemented and should not be called: def DoSomething(some, args): """ This procedure will do ... great things someday. """ raise NotImplementedError Then *if* the writer of the application that will call it forgets that's it not yet implemented, and mistakenly tries to call it, an error will be raised. It's not so useful in a small application, or a single person project, but it does become useful if several people are writing different parts (say a library and an application) at the same time. Gary Herron From mlindo at gmail.com Tue Jan 15 16:48:32 2008 From: mlindo at gmail.com (Moises Alberto Lindo Gutarra) Date: Tue, 15 Jan 2008 16:48:32 -0500 Subject: Running Multiple Versions In-Reply-To: <795bedbb-e21e-49b8-856d-bce83a5fced3@f10g2000hsf.googlegroups.com> References: <795bedbb-e21e-49b8-856d-bce83a5fced3@f10g2000hsf.googlegroups.com> Message-ID: <5db591c00801151348g7a100796u7f75bb50ef640aae@mail.gmail.com> that is correct, you can work several version of python in same machine. When you execute some script you only need redirect %PATH% and %PYTHONPATH% 2008/1/15, noel at webeok.org : > Hi, > > We are windows shop with some unix servers as well. We run 2.4.1 and > want to begin migrating to 2.5.1. I am looking for information > dealing with having more than one version of python on a server at one > time. I believe this is called side-by-side and all that is needed to > select a version on a windows box is to set the path to the desired > version of python prior to launching the script. > > Does this sound correct? > > Is there doc online that describes this? > > For windows, has anyone come up with a way to have the script launch > the correct version at load time - similar to the she-bang method used > in unix? > > Thanks > > Noel > -- > http://mail.python.org/mailman/listinfo/python-list > -- Atentamente, Mois?s Alberto Lindo Gutarra Asesor - Desarrollador Java / Open Source From tjreedy at udel.edu Sun Jan 27 19:13:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jan 2008 19:13:27 -0500 Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <479cca7e$0$9108$9b4e6d93@newsspool2.arcor-online.net><60411eF1ors2pU1@mid.uni-berlin.de> <479cd1f0$0$25377$9b4e6d93@newsspool4.arcor-online.net> <7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com> Message-ID: "Andr?" wrote in message news:7dcc86da-6ed7-48ec-9a9e-ada5574ae06e at v17g2000hsa.googlegroups.com... If one goes back to the original idea instead, the decision of using automatic assignment should depend on the signature of the __init__ function. Here's an implementation (using "_" instead of "." as it would lead to a syntax error): from functools import * from inspect import * def autoassign(_init_): @wraps(_init_) def _autoassign(self, *args, **kwargs): argnames, _, _, _ = getargspec(_init_) for name, value in zip(argnames[1:], args): if name.startswith("_"): setattr(self, name[1:], value) _init_(self, *args, **kwargs) return _autoassign class Test(object): @autoassign def __init__(self, _foo, _bar, baz): print 'baz =', baz t = Test(1, 2, 3) print t.foo print t.bar print t.baz #== the output is baz = 3 1 2 Traceback (most recent call last): File "/Users/andre/CrunchySVN/branches/andre/src/tools_2k.py", line 24, in exec_code exec code in local_dict File "User's code", line 23, in AttributeError: 'Test' object has no attribute 'baz' ================================= I think this version, with this name convention, is nice enough to possibly go in the stdlib if there were an appropriate place for it. Not sure where though. If there were a classtools module.... tjr From S.Mientki-nospam at mailbox.kun.nl Wed Jan 23 10:12:32 2008 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 23 Jan 2008 16:12:32 +0100 Subject: A GUI framework for running simulations In-Reply-To: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com> References: <1e394f08-b670-4dbd-b7e9-fd607abd4e59@j78g2000hsd.googlegroups.com> Message-ID: <657f0$47975960$83aef404$1819@news1.tudelft.nl> ram.rachum at gmail.com wrote: > Hello! I am currently working on writing a simulation engine for > special relativity physics. I'm writing it in Python, of course. I'm > doing fine with the engine, but I want a GUI framework in which I > could use it conveniently, and test different setups on it. I'm not so > strong with GUI programming. I looked at Tkinter, I looked at > WxPython, I looked at PythonCard. It all looks pretty daunting. > > My question is, does there exist a GUI package that is intended > specifically for simulations? I saw a program called Golly, which is a > simulation for Conway's Game of Life. Its GUI had most of the features > I needed. For example, you can load a setup, there are "play" and > "stop" buttons, you can change a setup and save it, etc. > > So does anyone know of a general GUI framework for running > simulations? although quit premature, PyLab_Works might be of interest, see some demos here (watch the demo at the bottom first): http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_animations_screenshots.html (you can contact me offline if PyLab_Works looks interesting to you). cheers, Stef Mientki From sjmachin at lexicon.net Sat Jan 12 20:46:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 12 Jan 2008 17:46:02 -0800 (PST) Subject: Is unicode.lower() locale-independent? References: <871w8ni60t.fsf@physik.rwth-aachen.de> <8b781e43-c3c0-4113-a9a1-7351fb377d0d@i3g2000hsf.googlegroups.com> Message-ID: On Jan 13, 9:49 am, Carl Banks wrote: > On Sat, 12 Jan 2008 13:51:18 -0800, John Machin wrote: > > On Jan 12, 11:26 pm, Torsten Bronger > > wrote: > >> Hall?chen! > > >> Fredrik Lundh writes: > >> > Robert Kern wrote: > > >> >>> However it appears from your bug ticket that you have a much > >> >>> narrower problem (case-shifting a small known list of English words > >> >>> like VOID) and can work around it by writing your own > >> >>> locale-independent casing functions. Do you still need to find out > >> >>> whether Python unicode casings are locale-dependent? > > >> >> I would still like to know. There are other places where .lower() is > >> >> used in numpy, not to mention the rest of my code. > > >> > "lower" uses the informative case mappings provided by the Unicode > >> > character database; see > > >> > http://www.unicode.org/Public/4.1.0/ucd/UCD.html > > >> > afaik, changing the locale has no influence whatsoever on Python's > >> > Unicode subsystem. > > >> Slightly off-topic because it's not part of the Unicode subsystem, but > >> I was once irritated that the none-breaking space (codepoint xa0 I > >> think) was included into string.whitespace. I cannot reproduce it on > >> my current system anymore, but I was pretty sure it occured with a > >> fr_FR.UTF-8 locale. Is this possible? And who is to blame, or must my > >> program cope with such things? > > > The NO-BREAK SPACE is treated as whitespace in the Python unicode > > subsystem. As for str objects, the default "C" locale doesn't know it > > exists; otherwise AFAIK if the character set for the locale has it, it > > will be treated as whitespace. > > > You were irritated because non-break SPACE was included in > > string.whiteSPACE? Surely not! It seems eminently logical to me. > > To me it seems the point of a non-breaking space is to have something > that's printed as whitespace but not treated as it. To me it seems the point of a no-break space is that it's treated as a space in all respects except that it doesn't "break". > > > Perhaps > > you were irritated because str.split() ignored the "no-break"? If like > > me you had been faced with removing trailing spaces from text columns in > > databases, you surely would have been delighted that str.rstrip() > > removed the trailing-padding-for-nicer-layout no-break spaces that the > > users had copy/pasted from some clown's website :-) > > > What was the *real* cause of your irritation? > > If you want to use str.split() to split words, you will foil the user who > wants to not break at a certain point. Which was exactly my point -- but this would happen only rarely or not at all in my universe (names, addresses, product descriptions, etc in databases). > > Your use of rstrip() is a lot more specialized, if you ask me. Not very specialised at all in my universe -- a standard transformation that one normally applies to database text is to remove all leading and trailing whitespace, and compress runs of 1 or more whitespace characters to a single normal space. Your comment seems to imply that trailing non-break spaces are significant and should be preserved ... From mani.sabri at gmail.com Mon Jan 28 13:29:35 2008 From: mani.sabri at gmail.com (mani) Date: Mon, 28 Jan 2008 10:29:35 -0800 (PST) Subject: Embeding python with mingw on win32 and python 2.4.4 Message-ID: <563a8060-8d79-4bc8-8306-9a5d77bfae5e@i72g2000hsd.googlegroups.com> Hi I'm bringing up an old story once more! I'm on win32 (winxp sp2) python 2.4.4. mingw gcc version is 3.4.5. msys is in c:\msys. mingw is in c:\mingw and python is in c:\pyton24. there are also python24.lib and libpython24.a in c:\python24\libs. when I try to compile this sample code [1] from msys prompt with command [2] in msys shell I get the results [3]. this subject was discussed a few times over these years and I tried everything in the posts and forums that I found and google could translate with no success. I realy need your suggestion! Regards, Mani [1] Sample code: #include int main(int argc, char *argv[]) { Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } [2] Command: $ g++ -I/c/python24/include -I/c/MinGW/include -L/c/python24/libs -L/ c/ mingw/lib -lpython24 -shared -mwin32 -o p1 p1.o [3] Results: p1.o:p1.cpp:(.text+0x2b): undefined reference to `_imp__Py_Initialize' p1.o:p1.cpp:(.text+0x39): undefined reference to `_imp__PyRun_SimpleString' p1.o:p1.cpp:(.text+0x40): undefined reference to `_imp__Py_Finalize' collect2: ld returned 1 exit status From smriti.sebastuan at gmail.com Wed Jan 9 12:13:09 2008 From: smriti.sebastuan at gmail.com (smriti Sebastian) Date: Wed, 9 Jan 2008 22:43:09 +0530 Subject: centre of mass of protein Message-ID: <22c5c6390801090913w6667560cv809a2e5fc8ad7e5b@mail.gmail.com> hi all, Is there any script or module in python where we can find the centre of mass of protein? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Jan 7 16:32:22 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jan 2008 08:32:22 +1100 Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <87ve65mie1.fsf@benfinney.id.au> MartinRinehart at gmail.com writes: > The best thing about Python is _______. The best thing about Python is its elegance. -- \ "Like the creators of sitcoms or junk food or package tours, | `\ Java's designers were consciously designing a product for | _o__) people not as smart as them." -- Paul Graham | Ben Finney From piet at cs.uu.nl Tue Jan 8 03:48:39 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 08 Jan 2008 09:48:39 +0100 Subject: dictionary/hash and '1' versus 1 References: <7a9c25c20801031638j706eed4iebf6a77a3119b70f@mail.gmail.com> <7fcfb973-5fa4-43a4-96ab-2a20868cfb70@l6g2000prm.googlegroups.com> <8dfa1350-2200-42c4-8cef-22e224778c48@r60g2000hsc.googlegroups.com> <5uen3rF1f2vjrU1@mid.uni-berlin.de> Message-ID: >>>>> "Diez B. Roggisch" (DBR) wrote: >DBR> So you can also do >DBR> "" + some_object >DBR> However, >DBR> some_object + "" >DBR> or >DBR> 1 + "" >DBR> don't work - the operator is only overloaded on the left argument. There is no problem with 1+"" neither with new Integer(1)+"" in Java. Nor any other object on the left hand side. The + operator is not tied to the left hand side as in C++. if either side is a string and the other side has a toString method it is OK. This is special-cased in the compiler. It is defined in the language definition, not in the library definition. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From oweston at earthlink.net Mon Jan 28 08:42:26 2008 From: oweston at earthlink.net (wes) Date: Mon, 28 Jan 2008 05:42:26 -0800 Subject: Python Genetic Algorithm In-Reply-To: References: Message-ID: <13prmt7khp1gg42@corp.supernews.com> Max, def GeneticNextGen(self): numsets = len(self.WtSets) numwts = len(self.WtSets[0].Lis) self.WtSets.sort(CompByCurrentFitness) index_lis = [] K = 100.0 N = float(numwts) #if RISE(slope) is too high, concentration occurs too fast and #you lose many quickly RISE = -0.01*K RUN = N - 1.0 m = RISE/RUN for i in range( numsets ): x = float(i) numin = int(m * x + K) for k in range(numin): index_lis.append( i ) new_wtset_list = WtSetListClass() while len(new_wtset_list.WtSets) < numsets: #split in a number of placeses splitPoints = [] #empty list of places where dna's are crossed numSplitPoints = random.randint( 2, 4 ) #number of places to cross at(not to hot & not to cold) while len(splitPoints) < numSplitPoints: #get required num of points at random split_pt = random.randint( 0, numwts - 1 ) if split_pt not in splitPoints: splitPoints.append(split_pt) i1 = random.choice( index_lis ) #get two old weight sets at random from a biased list while( 1 ): i2 = random.choice( index_lis ) if i2 <> i1: break wts1 = self.WtSets[ i1 ] wts2 = self.WtSets[ i2 ] list1 = wts1.Lis[0:] #just size new weight sets list2 = wts1.Lis[0:] flip = False #copy into new weight sets from old alternating the for k in range(len(wts1.Lis)): # the source on 2 to 4 flip points if k in splitPoints: flip = not flip if flip: list1[k] = wts2.Lis[k] list2[k] = wts1.Lis[k] else: list1[k] = wts1.Lis[k] list2[k] = wts2.Lis[k] split_pt1 = random.choice(splitPoints) #capture a place to mutate at low probabilty x = random.randint( 0, 1000 ) #.1 % of time mutate at boundry if x == 5: list1[ split_pt1 ] = RandomFloat(LOWWT,HIGHWT) list2[ split_pt1 ] = RandomFloat(LOWWT,HIGHWT) wt = WtSetClass( list1 ) wt.FoldParentFitnesses( wts1,wts2 ) new_wtset_list.WtSets.append( wt ) if len(new_wtset_list.WtSets) < numsets: wt = WtSetClass( list2 ) wt.FoldParentFitnesses( wts1,wts2 ) new_wtset_list.WtSets.append( wt ) x = random.randint(0,10000) if x == 5: new_wtset_list.RandomizeRandomWt() #0.01% of time made an entire new random wt self.WtSets = new_wtset_list.WtSets From roy at panix.com Mon Jan 28 23:01:51 2008 From: roy at panix.com (Roy Smith) Date: Mon, 28 Jan 2008 23:01:51 -0500 Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com> Message-ID: In article , "Terry Reedy" wrote: > "Paddy" wrote in message > news:4dc87a25-1d90-4b66-8fa4-d0d41f48344e at i29g2000prf.googlegroups.com... > |I would value the opinion of fellow Pythoneers who have also > | contributed to Wikipedia, on the issue of "Is Python Standardized". > > Depends entirely on the operative meaning of standardized. Formal > standards body? Obviously no. > > Specified in a standard-setting document? Yes. In fact, in someways, > Python is better standardized that C, for instance, in that the Python > standard usefully standardizes some things that the C standard leaved > unstandardized as 'implementation defined'. > > Example 1. Order of evaluation of function arguments. Python: left to > right. C: undefined (and unstandardized), I believe. > > Example 2: Strings for Infinity and Not-A-Number. Python: will standardize > in 2.6 to hide the variation in C implementations (or is Microsoft just > non-compliant here?). But, surely Python has plenty of "implementation defined" aspects. Especially in the libraries. Especially those parts of the libraries which are thin layers on top of operating system services (os and socket come to mind as two highly variable areas). From python.list at tim.thechases.com Mon Jan 28 11:55:38 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 28 Jan 2008 10:55:38 -0600 Subject: referer url In-Reply-To: <0e7fb40e-809c-4979-bbb8-0cd9a7e816c2@t1g2000pra.googlegroups.com> References: <0e7fb40e-809c-4979-bbb8-0cd9a7e816c2@t1g2000pra.googlegroups.com> Message-ID: <479E090A.9020907@tim.thechases.com> > I was wondering, if there is a way to retrieve the referer url with > python (web-based). > I tried this: > > import os > print os.getenv('HTTP_REFERER') > > but it's not working, even thought other http variables do function, > this one is always a None. This could be for any number of reasons, inter alia: 1) you don't specify the environment in which your python code is running. this may not get stashed in the os.getenv(). In Django, it's stashed in request.META.HTTP_REFERER; in CGI, it should be in your os.getenv(); in WebStack, the trans parameter has get_headers()/get_header_values() methods you can use to extract the referer; and in other frameworks, they may toss them elsewhere. 2) the browser is configured to protect the privacy of the browser, and not send a Referer header 3) your server may not be configured to include the HTTP_REFERER environment variable (improbable, but possible) 4) your user(s) are coming from a book-marked link where there is no Referer to be sent -tkc From python.list at tim.thechases.com Thu Jan 3 09:05:07 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 03 Jan 2008 08:05:07 -0600 Subject: reassign to builtin possible !? In-Reply-To: References: <01d59239-9ced-427d-8820-80d6875acc1f@l1g2000hsa.googlegroups.com> <5u450fF1gldn9U2@mid.uni-berlin.de> Message-ID: <477CEB93.8000706@tim.thechases.com> >> But you can't alter the values for True/False globally with this. > > Are you sure ? what about the following example ? > Is this also shadowing ? > >>>> import __builtin__ >>>> __builtin__.True = False >>>> __builtin__.True > False It doesn't seem to screw things up globally >>> import __builtin__ >>> t = __builtin__.True >>> __builtin__.True = False >>> __builtin__.False = t >>> True False >>> False True >>> 1 == 1 True >>> import os >>> os.path.isdir('.') True >>> #if they were globally redefined, this would be False >>> #you'd have to actually reference __builtin__.True My thought would be if you do something as daft as redefining/shadowing True and False, you get the headaches that ensue. Fortunately, since Python is explicit, you can trace back through the code and see where the inanity occurred. Additionally, any scoping rules mean that programmer stupidity can't leak too badly outside the scope of the block containing the stupidity. It's the old "DIHWIDT! WDDT!" ("Doctor, it hurts when I do this!", "well don't do that!") syndrome. -tkc From python.list at tim.thechases.com Wed Jan 2 16:42:47 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 02 Jan 2008 15:42:47 -0600 Subject: database query - logic question In-Reply-To: <6A85AD3923D6C348AF108B4A8F459EA201BEFD3B@CIXMX1.compxnet.com> References: <6A85AD3923D6C348AF108B4A8F459EA201BEFD3B@CIXMX1.compxnet.com> Message-ID: <477C0557.6070808@tim.thechases.com> Israel Carr wrote: > Thanks for anyone who takes the time to read this. If I posted to the > wrong list, I apologize and you can disregard. > > I need help with a script to pull data from a postgres database. I'm ok > with the database connection just not sure how to parse the data to get > the results I need. > > I'm running Python 2.4.4. For what it's worth, once I can get my logic > correct I'll be publishing the reports mentioned below via zope for web > clients. > > Here is a small sample of the records in the table: > > name date time status > machine1 01/01/2008 13:00:00 system ok > machine1 01/01/2008 13:05:00 system ok > machine1 01/01/2008 13:10:00 status1 > machine1 01/01/2008 13:10:30 status1 > machine1 01/01/2008 13:11:00 system ok > machine1 01/01/2008 13:16:30 status2 > machine1 01/01/2008 13:17:00 status2 > machine1 01/01/2008 13:17:30 status2 > machine1 01/01/2008 13:18:00 status2 > machine1 01/01/2008 13:18:30 status2 > machine1 01/01/2008 13:19:00 system ok > machine1 01/01/2008 13:24:00 status2 > machine1 01/01/2008 13:24:30 status2 > machine1 01/01/2008 13:25:00 system ok > > I need to report from this data. > The detail report needs to be something like: > machine1 01/01/2008 13:10:00 status1 00:01:30 > machine1 01/01/2008 13:16:30 status2 00:02:30 > machine1 01/01/2008 13:24:00 status2 00:01:00 Well, just for fun of the SQL challenge, I tossed together the following (using sqlite3) SELECT name, Min(ts) as ts, next_ts, status FROM ( SELECT *, ( SELECT ts FROM test WHERE test.name = t.name AND test.ts > t.ts AND test.status = 'system ok' ORDER BY test.ts ASC LIMIT 1) AS next_ts FROM test t WHERE status <> 'system ok' ) with_next GROUP BY name, status, next_ts where my table has "name", "ts" (a timestamp field combo of your "date" and "time" fields, and for sqlite, formatting in "YYYY-MM-DD mm:ss" format) which yields rows with the machine name, the non "system ok" status, the timestamp of the initial event, and the timestamp of the subsequent "system ok" stamp. There's a bit of an underdefined case where you have more than one non-OK status before OK gets reset: 00:10 status1 00:20 status1 00:30 status2 00:40 status ok If this can't happen, it should work fine. If the above can happen, you'll get odd overlaps in your reporting. Since I couldn't find an Interval data type in sqlite, you'd just have to take the "ts" and "next_ts" columns and subtract them to get the interval you want. > and the summary needs to be > machine1 01/01/2008 total 'status1' time = 00:01:30 > machine1 01/01/2008 total 'status2' time = 00:03:30 > _____ > machine1 01/01/2008 total 'non-OK' time = 00:05:00 #this is the > sum of status1 and status2 times While the below doesn't track the changing of the machine, you can follow the basic framework given here. I threw in a couple helper functions to normalize whatever data types ("normalize_status()" and "make_timestamp()") NO_TIME = datetime.datetime(datetime.MINYEAR, 1, 1) OK = 'system ok' normalize_status = lambda s: s.lower() def log(s): print s print '=' * len(s) def make_timestamp(date, time): d = datetime.datetime(*(int(s) for s in date.split('-') + time.split(':'))) return d status_tally = {} last_status = OK last_ts = NO_TIME log('Intervals (your first request)') for i, (machine, date, time, status) in enumerate(fetchall()): ts = make_timestamp(date, time) status = normalize_status(status) if status == OK and last_status <> OK: interval = ts - last_ts print machine, last_status, last_ts, interval if last_status in status_tally: status_tally[last_status] += interval else: status_tally[last_status] = interval last_status = status elif status <> OK and last_status == OK: last_ts = ts last_status = status log('Summary (your 2nd request)') for k,v in status_tally.iteritems(): print k, v log('Grand Total (your 3rd request)') print sum(status_tally.values(), datetime.timedelta(0)) Thanks for the mental exercise. :) -tkc From qgallet at gmail.com Thu Jan 17 07:32:53 2008 From: qgallet at gmail.com (Quentin Gallet-Gilles) Date: Thu, 17 Jan 2008 13:32:53 +0100 Subject: Loop in a loop? In-Reply-To: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: <8b943f2b0801170432o5016ef9i20eedf80a50e3479@mail.gmail.com> Hi, I'd consider using zip : >>> array1 = ['one','two','three','four'] >>> array2 = ['a','b','c','d'] >>> zip(array1, array2) [('one', 'a'), ('two', 'b'), ('three', 'c'), ('four', 'd')] >>> for one, two in zip(array1, array2): ... print one, two ... one a two b three c four d >>> HTH, Quentin On Jan 17, 2008 1:21 PM, Sacred Heart wrote: > Hi, > I'm new to Python and have come across a problem I don't know how to > solve, enter com.lang.python :) > > I'm writing some small apps to learn the language, and I like it a lot > so far. > > My problem I've stumbled upon is that I don't know how to do what I > want. I want to do a loop in a loop. I think. > > I've got two arrays with some random stuff in, like this. > > array1 = ['one','two','three','four'] > array2 = ['a','b','c','d'] > > I want to loop through array1 and add elements from array2 at the end, > so it looks like this: > > one a > two b > three c > four c > > I'm stuck. I know how to loop through the arrays separatly and print > them, but both at the same time? Hmmm. > > A push in the right direction, anyone? > > R, > SH > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vlastimil.brom at gmail.com Tue Jan 1 12:14:22 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 1 Jan 2008 18:14:22 +0100 Subject: WXPython - Using inline images In-Reply-To: <2adc542f0712310615na782e58vc9710c4bfab1edf4@mail.gmail.com> References: <2adc542f0712310615na782e58vc9710c4bfab1edf4@mail.gmail.com> Message-ID: <9fdb569a0801010914s6a3abf97xcfd3416d056f2c33@mail.gmail.com> 2007/12/31, Sick Monkey : ... Is there anyway WXPython can just use the inline image without having to create a physical copy? I know this can be done in TKinter using inline gifs, but was wondering if anyone knew of a clever way to do this in WXPython? ... I think, you can use a stream and wx.ImageFromStream for that see the wxPython Demo ...\demo\images.py for some examples. Greetings, Vlasta -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Jan 8 08:44:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 08 Jan 2008 14:44:52 +0100 Subject: use fileinput to read a specific line In-Reply-To: <13o6tldft8suj83@corp.supernews.com> References: <6f2db44c-2641-47cb-ab24-4177ccc96d6e@m77g2000hsc.googlegroups.com> <13o637afk4mql0c@corp.supernews.com> <36e49a53-8e56-4847-a792-5032ea204a8e@l6g2000prm.googlegroups.com> <13o6tldft8suj83@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > Python guarantees[1] that files will be closed, but doesn't specify when > they will be closed. I understand that Jython doesn't automatically close > files until the program terminates, so even if you could rely on the ref > counter to close the files in CPython, it won't be safe to do so in > Jython. From what I can tell, Java's GC automatically closes file streams, so Jython will behave pretty much like CPython in most cases. I sure haven't been able to make Jython run out by file handles by opening tons of files and discarding the file objects without closing them. Has anyone? From ncoghlan at gmail.com Tue Jan 1 00:06:53 2008 From: ncoghlan at gmail.com (NickC) Date: Mon, 31 Dec 2007 21:06:53 -0800 (PST) Subject: getting n items at a time from a generator References: <5657aa68-cbc4-4285-86e8-91ddd317260d@q77g2000hsh.googlegroups.com> <05e5f3ef-9930-4ad5-af88-2f08594568aa@j20g2000hsi.googlegroups.com> Message-ID: On Dec 27 2007, 11:31 pm, Kugutsumen wrote: > On Dec 27, 7:24 pm, Terry Jones wrote: > > > > > >>>>> "Kugutsumen" == Kugutsumen writes: > > > Kugutsumen> On Dec 27, 7:07 pm, Paul Hankin wrote: > > > >> On Dec 27, 11:34 am, Kugutsumen wrote: > > > >> > I am relatively new the python language and I am afraid to be missing > > >> > some clever construct or built-in way equivalent to my 'chunk' > > >> > generator below. > > > Kugutsumen> Thanks, I am going to take a look at itertools. I prefer the > > Kugutsumen> list version since I need to buffer that chunk in memory at > > Kugutsumen> this point. > > > Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.) p705 > > > def chop(iterable, length=2): > > return izip(*(iter(iterable),) * length) > > > Terry > > [snip code] > > > Try this instead: > > > import itertools > > > def chunk(iterator, size): > > # I prefer the argument order to be the reverse of yours. > > while True: > > chunk = list(itertools.islice(iterator, size)) > > if chunk: yield chunk > > else: break > > Steven, I really like your version since I've managed to understand it > in one pass. > Paul's version works but is too obscure to read for me :) > > Thanks a lot again. To work with an arbitrary iterable, it needs an extra line at the start to ensure the iterator items are consumed correctly each time around the loop. It may also be better to ensure the final item is the same length as the other items - if that isn't the case (you want to know where the data really ends) then leave out the parts relating to adding the padding object. import itertools def chunk(iterable, size, pad=None): iterator = iter(iterable) padding = [pad] while True: chunk = list(itertools.islice(iterator, size)) if chunk: yield chunk + (padding*(size-len(chunk))) else: break Cheers, Nick. From S.Mientki-nospam at mailbox.kun.nl Thu Jan 17 11:19:56 2008 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 17 Jan 2008 17:19:56 +0100 Subject: How to create graphs an embed them in GUI? In-Reply-To: References: Message-ID: <5967b$478f802b$83aef404$8664@news1.tudelft.nl> Heiko Niedermeyer wrote: > Sorry for the fuzzy subject... > > Currently I'm writing a little programm to extract some chemical > information out of a text file, and then present it in a pleasant way. > The Extraction works so far, so now the presentation will be next. > > As I'm learning Python from scratch, I don't care wether to use (=learn) > TKinter or PyQt or whatever, I just need some advice, which suits my > needs best. > It would be nice to have the programm working under win and linux > (shouldn't be a big Problem) and my requirements concerning the standard > elements should be met by almost every framework. > My problem is, that I want to add graph (simple, line connected X,Y- > scatter plots) and if possible the 3D representation of atoms in a > molecule (-> coloured spheres in space). > I think it would take me years to program those by myself, so I would ne > ready to use packages, if available. > Long story short: Are there packages that could do this, and does it > matter which GUI I want to embed them in? I think "Vision" (formerly Viper)is exactly what you are looking for. If not look at VTK. cheers, Stef > > best wishes From deets at nospam.web.de Wed Jan 16 14:28:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jan 2008 20:28:47 +0100 Subject: Interesting Thread Gotcha In-Reply-To: References: <5v6oc6F1l2sfqU1@mid.uni-berlin.de> <57dd69d6-469b-479c-968b-e78c6d842308@t1g2000pra.googlegroups.com> <5v70v9F1kmtinU1@mid.uni-berlin.de> Message-ID: <5v747jF1lc8buU1@mid.uni-berlin.de> Dan schrieb: > On Jan 16, 1:33 pm, "Diez B. Roggisch" wrote: >> Dan schrieb: >> >> >> >>> On Jan 16, 11:06 am, "Diez B. Roggisch" wrote: >>>> Hendrik van Rooyen wrote: >>>>> "Dan" wrote: >>>>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) >>>>>> Needs to be >>>>>>>>> keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) >>>>>> Commas are important! >>>>>> -Dan >>>>> Absolutely! - well spotted! >>>>> As the first correct respondent, you win the freedom to spend a week in >>>>> Naboomspruit at your own expense. >>>>> It would have been nice, however, to have gotten something like: >>>>> TypeError - This routine needs a tuple. >>>>> instead of the silent in line calling of the routine in question, >>>>> while failing actually to start a new thread. >>>> You can't prevent the silent inline-calling - otherwise, how would you do >>>> this: >>>> def compute_thread_target(): >>>> def target(): >>>> pass >>>> return target >>>> thread.start_new_thread(compute_thread_target()) >>>> Of course start_new_thread could throw an error if it got nothing callable >>>> as first argument. No idea why it doesn't. >>>> Diez >>> Of course, in his case, having start_new_thread throw an error >>> wouldn't have helped, since he went into an infinite loop while >>> evaluating the parameters for start_new_thread. >>> Would it be possible to have pychecker (or some such) warn that there >>> is an insufficient parameter count to start_new_thread? I guess that >>> would require knowing the type of thread. . . >> What has this to do with the second argument? It's perfectly legal to >> have a function as thread-target that takes no arguments at all, so >> enforcing a second argument wouldn't be helpful - all it would do is to >> force all developers that don't need an argument tuple to pass the empty >> tuple. So there was no insufficient argument count. >> >> And none of these would solve the underlying problem that in python >> expressions are evaluated eagerly. Changing that would mean that you end >> up with a totally new language. >> >> the only thing that could help to a certain extend would be static >> types. Which we don't want here :) >> >> Diez > > It doesn't seem to be legal in my version of python (or the doc): > >>>> import thread >>>> def bat(): > print "hello" > > >>>> thread.start_new_thread(bat) > > Traceback (most recent call last): > File "", line 1, in > thread.start_new_thread(bat) > TypeError: start_new_thread expected at least 2 arguments, got 1 >>>> thread.start_new_thread(bat, ()) > 2256hello Ah, I thought it was optional, as in the threading.Thread(target=..., args=....)-version. Sorry for not looking that up. Then you'd might stand a chance that pychecker can find such a situation - but of course not on a general level, as in the above - that would only work with type-annotations. Diez From software at ginstrom.com Thu Jan 31 01:45:42 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Thu, 31 Jan 2008 15:45:42 +0900 Subject: Has Anyone Worked with Gene Expression Programming??????????????????????????? In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F38021A5D9F@AWMAIL04.belcan.com> Message-ID: <003d01c863d4$e6631990$0203a8c0@MOUSE> > On Behalf Of Daniel Fetchinson > Actually, it turns out I might say I'm a world known expert > of Gene Expression Programming. > The only thing is that some higher powers are preventing me > from telling you about it. > I'm really sorry, I hope you understand. Please don't ask > questions. It's not safe to know too much about this stuff. > One day, my son, you'll understand. You'll understand. The first rule of Gene Expression Programming is - you do not talk about Gene Expression Programming. Regards, Ryan Ginstrom From cokofreedom at gmail.com Mon Jan 21 02:59:38 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Sun, 20 Jan 2008 23:59:38 -0800 (PST) Subject: Bug in __init__? References: <88580064-3590-471e-8036-a631dd5a38b4@i3g2000hsf.googlegroups.com> Message-ID: <50ed76e4-f865-4821-935f-310c96b0ecb9@e23g2000prf.googlegroups.com> Is there no way of adding a possible warning message (that obviously could be turned off) to warn users of possible problems linked to using mutable types as parameters? Seems to me this could save users a few minutes/hours of headaches and headscratching. (The biggest issue affecting new programmers these days!) From nytrokiss at gmail.com Fri Jan 11 08:37:05 2008 From: nytrokiss at gmail.com (James Matthews) Date: Fri, 11 Jan 2008 14:37:05 +0100 Subject: HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? In-Reply-To: <47872936.9070603@islandtraining.com> References: <7243c2ac-fa22-4b5b-bd8c-34235123ab69@t1g2000pra.googlegroups.com> <47872936.9070603@islandtraining.com> Message-ID: <8a6b8e350801110537j6ba0fddew8571aa71b0b7e5af@mail.gmail.com> Ahh it's good to know that you "love" pointers like everyone else! On Jan 11, 2008 9:30 AM, Gary Herron wrote: > abhishek wrote: > > Hi group any idea on HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS?? > > > > > > Thank you > > > POINTERS? Heaps? Huh? Ummm, let me think -- those terms *do* sound > vaguely familiar -- from sometime in the deep dark primitive past. > Perhaps from back in my (shudder) C/C++ days -- ya, that's it. > Thankfully, this is Python and the modern era -- we don't use no > stinking POINTERS here. > > Seriously, this group deals with Python. There are no pointers in > Python. Now please, what did you *really* mean to ask? > > Gary Herron > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com From hat at se-162.se.wtb.tue.nl Fri Jan 11 07:18:29 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 11 Jan 2008 13:18:29 +0100 Subject: reading a specific column from file References: Message-ID: On 2008-01-11, cesco wrote: > Hi, > > I have a file containing four columns of data separated by tabs (\t) > and I'd like to read a specific column from it (say the third). Is > there any simple way to do this in Python? > > I've found quite interesting the linecache module but unfortunately > that is (to my knowledge) only working on lines, not columns. > > Any suggestion? the csv module may do what you want. From nikbaer at gmail.com Tue Jan 29 13:56:18 2008 From: nikbaer at gmail.com (nik) Date: Tue, 29 Jan 2008 10:56:18 -0800 (PST) Subject: ISO with timezone References: <4f079ee5-3c0d-4c15-902a-678f0cd7528d@q39g2000hsf.googlegroups.com> Message-ID: Thanks, that does help and now I have: >>> from datetime import datetime, tzinfo, timedelta >>> import time >>> class TZ(tzinfo): ... def utcoffset(self,dt): return timedelta(seconds=time.timezone) ... >>> print datetime(2008,2,29,15,30,11,tzinfo=TZ()).isoformat() 2008-02-29T15:30:11+8:00 But what I want to know now it how to get the actual time into the expression instead of typing the 2008,2,29,15.... So something like: >>> print datetime(time.gmtime(),tzinfo=TZ()).isoformat(), but that doesn't work. I realize that I could do: >>> t = time.gmtime() >>> print datetime(t[0],t[1],t[2],t[3],t[4],t[5],tzinfo=TZ()).isoformat() but I imagine there might be a cleaner way of doing this. Thanks, Nik On Jan 28, 9:10 pm, "Nicholas F. Fabry" wrote: > Hello, nik. > > On Jan 28, 2008, at 21:03, nik wrote: > > > > > Hi, > > > How does one express the time in ISO format with the timezone > > designator? > > > what I want is YYYY-MM-DDThh:mm:ss.sTZD > > >> From the documentation I see: > >>>> from datetime import tzinfo, timedelta, datetime > >>>> class TZ(tzinfo): > > ... def utcoffset(self, dt): return timedelta(minutes=-399) > > ... > >>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') > > '2002-12-25 00:00:00-06:39' > > > and I've also figured out: > >>>> datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3] > > '2008-01-23T11:22:54.130' > > > But can't figure out how to fit them together. > > There is nothing there to 'fit together' - in the first example given, > the datetime object has no time component specified, so it fills in > default vaules of zero. The following should make this clear: > > >>> your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ()) > >>> print your_time > 2008-02-29 15:30:11-05:00 > >>> print your_time.isoformat('T') > 2008-02-29T15:30:11-05:00 > > If you wish to append the NAME of the tzinfo object instead of its > offset, that requires a bit more playing around (along with a properly > defined tzinfo object - check out dateutil or pytz for a concrete > implementation of tzinfo subclasses (i.e. timezones)), but the > following would work: > > >>> print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z') > 2008-02-29T15:30:11 EST > > For details on how the .strftime method works, see Python Standard > Library, Section 14.2. > > I hope this helps! > > Nick Fabry > > > Thank you, > > Nik > > -- > >http://mail.python.org/mailman/listinfo/python-list > From jd1987 at borozo.com Wed Jan 30 02:54:53 2008 From: jd1987 at borozo.com (Joe Demeny) Date: Wed, 30 Jan 2008 02:54:53 -0500 Subject: Form to mail script Message-ID: <200801300254.55107.jd1987@borozo.com> I am looking for a python web form to mail script for a public web site - could you recommend one? -- Joe Demeny From tezzspaceman at gmail.com Wed Jan 23 01:41:33 2008 From: tezzspaceman at gmail.com (TezZ Da Sp@cE MaN) Date: Wed, 23 Jan 2008 12:11:33 +0530 Subject: UNSUBSCRIBE In-Reply-To: <5vme8iF1mqjl6U1@mid.uni-berlin.de> References: <5vme8iF1mqjl6U1@mid.uni-berlin.de> Message-ID: <006801c85d8b$020776a0$061663e0$@com> -----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 Diez B. Roggisch Sent: 22 January 2008 20:22 To: python-list at python.org Subject: Re: isgenerator(...) - anywhere to be found? Jean-Paul Calderone wrote: > On Tue, 22 Jan 2008 15:15:43 +0100, "Diez B. Roggisch" > wrote: >>Jean-Paul Calderone wrote: >> >>> On Tue, 22 Jan 2008 14:20:35 +0100, "Diez B. Roggisch" >>> wrote: >>>>For a simple greenlet/tasklet/microthreading experiment I found myself >>>>in the need to ask the question >>>> >>>> [snip] >>> >>> Why do you need a special case for generators? If you just pass the >>> object in question to iter(), instead, then you'll either get back >>> something that you can iterate over, or you'll get an exception for >>> things that aren't iterable. >> >>Because - as I said - I'm working on a micro-thread thingy, where the >>scheduler needs to push returned generators to a stack and execute them. >>Using send(), which rules out iter() anyway. > > Sorry, I still don't understand. Why is a generator different from any > other iterator? Because you can use send(value) on it for example. Which you can't with every other iterator. And that you can utizilize to create a little framework of co-routines or however you like to call it that will yield values when they want, or generators if they have nested co-routines the scheduler needs to keep track of and invoke after another. I'm currently at work and can't show you the code - I don't claim that my current approach is the shizzle, but so far it serves my purposes - and I need a isgenerator() Diez -- http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Thu Jan 3 10:56:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 16:56:45 +0100 Subject: how to use bool In-Reply-To: References: Message-ID: jimgardener at gmail.com wrote: > hi, i have some code where i set a bool type variable and if the value > is false i would like to return from the method with an error msg.. > being a beginner I wd like some help here > > class myclass: > ......... > def mymethod(self): > success=True > msg="all validation OK" > success=validateSthing() > if(success==False): > msg="sthing failed" > return (success,msg) > > dosomeprocessing() > ..... > success=validateSthingelse() > if(success==False): > msg="sthingelse failed" > return (success,msg) > domoreprocessing() > .... > return(success,msg) > > i would like to know if this way of doing this is OK..I have need of > many kinds of validations in this ..is there a better way of doing > this ? to test boolean values, it's usually better to use plain "if" or "if not" statements: if success: ... handle success here ... if not success: ... handle failure here ... to report failures, use exceptions (the raise and try/except statements). see the tutorial for more on this topic. From alainpoint at yahoo.fr Mon Jan 7 08:41:12 2008 From: alainpoint at yahoo.fr (alain) Date: Mon, 7 Jan 2008 05:41:12 -0800 (PST) Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: <08f0c528-0619-432a-80a1-569cd9183e09@s12g2000prg.googlegroups.com> On Jan 7, 2:09?pm, MartinRineh... at gmail.com wrote: > I'm a Java guy who's been doing Python for a month now and I'm > convinced that > > 1) a multi-paradigm language is inherently better than a mono-paradigm > language > > 2) Python writes like a talented figure skater skates. > > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is _______. > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > "grace" but I'm not sure I've done enough to choose. Paraphrasing Steve Jobs but in this context: PYTHON = a bycycle for the mind Best regards Alain From duncan.booth at invalid.invalid Mon Jan 21 05:36:45 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jan 2008 10:36:45 GMT Subject: problem with 'global' References: Message-ID: Mel wrote: > oyster wrote: >> why the following 2 prg give different results? a.py is ok, but b.py >> is 'undefiend a' >> I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC >> v.1310 32 bit (Intel)] on win32 >> #a.py >> def run(): >> if 1==2: # note, it always False >> global a >> a=1 >> >> run() >> a >> >> #b.py >> def run(): >> a=1 >> >> run() >> a > > The docs seem to be in > but don't look all that helpful. Why are you reading Python 2.4 docs? Try http://docs.python.org/ref/global.html The first sentence (which hasn't changed since 2.4) describing the global statement seems clear enough to me: "The global statement is a declaration which holds for the entire current code block." From mario at ruggier.org Wed Jan 2 13:28:36 2008 From: mario at ruggier.org (mario) Date: Wed, 2 Jan 2008 10:28:36 -0800 (PST) Subject: unicode(s, enc).encode(enc) == s ? References: <5e49e7e6-f2b3-4c9f-9dec-e5f01f12d59a@e4g2000hsg.googlegroups.com> <4773f0de$0$15825$9b622d9e@news.freenet.de> <7cb20641-ab33-4818-a911-80c684cb9792@q77g2000hsh.googlegroups.com> <4775AC6B.8070109@v.loewis.de> Message-ID: <1310677e-51ec-49f2-9709-196dcc4e1ac9@e4g2000hsg.googlegroups.com> Thanks a lot Martin and Marc for the really great explanations! I was wondering if it would be reasonable to imagine a utility that will determine whether, for a given encoding, two byte strings would be equivalent. But I think such a utility will require *extensive* knowledge about many bizarrities of many encodings -- and has little chance of being pretty! In any case, it goes well beyond the situation that triggered my original question in the first place, that basically was to provide a reasonable check on whether round-tripping a string is successful -- this is in the context of a small utility to guess an encoding and to use it to decode a byte string. This utility module was triggered by one that Skip Montanaro had written some time ago, but I wanted to add and combine several ideas and techniques (and support for my usage scenarios) for guessing a string's encoding in one convenient place. I provide a write-up and the code for it here: http://gizmojo.org/code/decodeh/ I will be very interested in any remarks any of you may have! Best regards, mario From maxerickson at gmail.com Fri Jan 25 18:57:30 2008 From: maxerickson at gmail.com (Max Erickson) Date: Fri, 25 Jan 2008 23:57:30 +0000 (UTC) Subject: a newbie regex question References: <4227b8d4-c2c7-4395-97a3-5aadcec94b7d@p69g2000hsa.googlegroups.com> <880dece00801250545t124745cck6f9be1b887ec57b5@mail.gmail.com> Message-ID: "Dotan Cohen" wrote: > Maybe you mean: > for match in re.finditer(r'\([A-Z].+[a-z])\', contents): > Note the last backslash was in the wrong place. The location of the backslash in the orignal reply is correct, it is there to escape the closing paren, which is a special character: >>> import re >>> s='Abcd\nabc (Ab), (ab)' >>> re.findall(r'\([A-Z].+[a-z]\)', s) ['(Ab), (ab)'] Putting the backslash at the end of the string like you indicated results in a syntax error, as it escapes the closing single quote of the raw string literal: >>> re.findall(r'\([A-Z].+[a-z])\', s) SyntaxError: EOL while scanning single-quoted string >>> max From danielatdaveschool at gmail.com Wed Jan 16 00:19:03 2008 From: danielatdaveschool at gmail.com (danielatdaveschool at gmail.com) Date: Tue, 15 Jan 2008 21:19:03 -0800 (PST) Subject: Image to browser References: <8c014bd1-7040-4ba3-9206-e1567c4a391a@n20g2000hsh.googlegroups.com> Message-ID: On Jan 16, 12:16 am, danielatdavesch... at gmail.com wrote: > Hi, noob here > > Im using mod_python and apache2 using psp for output of page, i open a > file and resize it with the following code > > <% > import Image, util > > fields = util.FieldStorage(req) > filename = fields.getlist('src')[0] > > path = '/var/www/content/' + filename > size = 128, 128 > > im = Image.open(path) > print im.resize(size, Image.ANTIALIAS) > %> > > so for one, I dont think print does much with psp as far as i can > tell, i cant even do a print 'hello world', it has to be a > req.write('hello world'), but i cant req.write the im.resize. The > manual for im.resize states that its return can go ahead and be > streamed via http but I get a blank page when im expecting to see > image characters dumped to my screen. Python doesn't throw up any > errors. Im not sure where else to look or what to do. > > Thanks for any help, > Daniel its worth noting that ive tried using print "Content-Type: image/jpeg\n" before the print im.resize and still no luck From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 30 04:08:04 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 30 Jan 2008 10:08:04 +0100 Subject: Web Interface Recommendations In-Reply-To: References: <45040839-8b1f-40af-9ef5-1be274c6e95f@z17g2000hsg.googlegroups.com> <80d6ce9f-6c8b-412d-a261-cfe480bd0c3b@e10g2000prf.googlegroups.com> Message-ID: <47a03e68$0$5443$426a34cc@news.free.fr> PurpleServerMonkey a ?crit : (snip) > Out of the major frameworks is there one that stands out as being > particularly well suited for what I'm trying to do? > > Django and CherryPy are on the short list so I'll give them a detailed > look although Pylons does sound rather interesting as well. I guess you'll have to try them out to find the one that best match your needs and personal preferences. Mostly: - CherryPy is more of a web application server than a framework per-se: it's it's own HTTP server - which might or not be a good thing -, and only deals with the "controler" part of the MVC triad. - Django is by now a mostly mature MVC framework, with more than a couple years of production use on quite a lot of sites and applications, good documentation and a somewhat large and active community. OTHO, it's a very opiniated (and somewhat monolithic) framework, with most parts of the stack (ORM, forms validation, template system etc) built specifically for this framework (which was probably the sensible thing to do by the time), so it's perhaps the less flexible of the three. - Pylons is IMHO very promising: wsgi from bottom to top, very flexible, good default components choice (paste / Routes / SQLAlchemy / Mako / FormEncode) but let you swap what you want in and out, and FWIW I've seen so far a very sound architecture. FWIW, next Turbogears major version will switch from CherryPy to Pylons. OTHO, it's still far from being as mature and documented as Django. My 2 cents... From kyosohma at gmail.com Fri Jan 4 16:58:49 2008 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 4 Jan 2008 13:58:49 -0800 (PST) Subject: Skill Resume Achievements, What Good Goes Here? References: <724e4836-d895-4210-972d-dd8f861902df@l1g2000hsa.googlegroups.com> Message-ID: <7c505881-f8ff-4ef9-8b08-7160791233c4@k39g2000hsf.googlegroups.com> On Jan 4, 3:06 pm, apatheticagnostic wrote: > On Jan 2, 11:31 am, kyoso... at gmail.com wrote: > > > > > On Jan 2, 9:59 am, vbgunz wrote: > > > > I spent some time working on a skill resume, the kind of resume > > > college students put together and realized, I am not in college and > > > everything I learned was self-taught. Of course I would like some real > > > world achievements but don't consider throw-away code an achievement > > > and am failing to really see any. I don't even wish to entertain the > > > thought of lying about anything. > > > > What are some achievements an employer may be looking for in someone > > > willing to start at ground level, entry level, intern, etc? What are > > > some real world achievements every n00b will need under his/her belt > > > in order to be taken seriously? > > > Internships are always a good thing to have. If you've contributed to > > open source projects, I'd put that on there. If you're applying for > > some kind of programming job, they'll probably want to see some of > > your code, know what home-brewed projects you've done and how long > > they took to complete, issues you ran into, etc. > > > That might get you started anyway. > > > Mike > > As someone else who's self-educated and curious about this, would > listing canonical comp-sci books that you've gone through on your own > and understood be a reasonable thing to mention? For example, SICP, > PLAI, etc? I should mention that it's certainly not hopeless. My boss is self- taught and so is our webmaster...you'll probably just have to start somewhere low on the ladder. Such as small businesses like computer repair shops or local ISPs where you can show your stuff. Mike From george.sakkis at gmail.com Tue Jan 22 21:32:22 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 22 Jan 2008 18:32:22 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> Message-ID: On Jan 22, 1:34 pm, Paddy wrote: > On Jan 22, 5:34 am, George Sakkis wrote: > > > > > On Jan 22, 12:15 am, Paddy wrote: > > > > On Jan 22, 3:20 am, Alan Isaac wrote:> I want to generate sequential pairs from a list. > > > <> > > > > What is the fastest way? (Ignore the import time.) > > > > 1) How fast is the method you have? > > > 2) How much faster does it need to be for your application? > > > 3) Are their any other bottlenecks in your application? > > > 4) Is this the routine whose smallest % speed-up would give the > > > largest overall speed up of your application? > > > I believe the "what is the fastest way" question for such small well- > > defined tasks is worth asking on its own, regardless of whether it > > makes a difference in the application (or even if there is no > > application to begin with). > > Hi George, > You need to 'get it right' first. For such trivial problems, getting it right alone isn't a particularly high expectation. > Micro optimizations for speed > without thought of the wider context is a bad habit to form and a time > waster. The OP didn't mention anything about the context; for all we know, this might be a homework problem or the body of a tight inner loop. There is this tendency on c.l.py to assume that every optimization question is about a tiny subproblem of a 100 KLOC application. Without further context, we just don't know. > If the routine is all that needs to be delivered and it does not > perform at an acceptable speed then find out what is acceptable > and optimise towards that goal. My questions were set to get > posters to think more about the need for speed optimizations and > where they should be applied, (if at all). I don't agree with this logic in general. Just because one can solve a problem by throwing a quick and dirty hack with quadratic complexity that happens to do well enough on current typical input, it doesn't mean he shouldn't spend ten or thirty minutes more to write a proper linear time solution, all else being equal or at least comparable (elegance, conciseness, readability, etc.). Of course it's a tradeoff; spending a week to save a few milliseconds on average is usually a waste for most applications, but being a lazy keyboard banger writing the first thing that pops into mind is not that good either. George From paul at boddie.org.uk Tue Jan 22 11:48:40 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 22 Jan 2008 08:48:40 -0800 (PST) Subject: Problem with processing XML References: <13pbudgks88rcf3@corp.supernews.com> Message-ID: On 22 Jan, 15:11, John Carlyle-Clarke wrote: > > I wrote some code that works on my Linux box using xml.dom.minidom, but > it will not run on the windows box that I really need it on. Python > 2.5.1 on both. > > On the windows machine, it's a clean install of the Python .msi from > python.org. The linux box is Ubuntu 7.10, which has some Python XML > packages installed which can't easily be removed (namely python-libxml2 > and python-xml). I don't think you're straying into libxml2 or PyXML territory here... > I have boiled the code down to its simplest form which shows the problem:- > > import xml.dom.minidom > import sys > > input_file = sys.argv[1]; > output_file = sys.argv[2]; > > doc = xml.dom.minidom.parse(input_file) > file = open(output_file, "w") On Windows, shouldn't this be the following...? file = open(output_file, "wb") > doc.writexml(file) > > The error is:- > > $ python test2.py input2.xml output.xml > Traceback (most recent call last): > File "test2.py", line 9, in > doc.writexml(file) > File "c:\Python25\lib\xml\dom\minidom.py", line 1744, in writexml > node.writexml(writer, indent, addindent, newl) > File "c:\Python25\lib\xml\dom\minidom.py", line 814, in writexml > node.writexml(writer,indent+addindent,addindent,newl) > File "c:\Python25\lib\xml\dom\minidom.py", line 809, in writexml > _write_data(writer, attrs[a_name].value) > File "c:\Python25\lib\xml\dom\minidom.py", line 299, in _write_data > data = data.replace("&", "&").replace("<", "<") > AttributeError: 'NoneType' object has no attribute 'replace' > > As I said, this code runs fine on the Ubuntu box. If I could work out > why the code runs on this box, that would help because then I call set > up the windows box the same way. If I encountered the same issue, I'd have to inspect the goings-on inside minidom, possibly using judicious trace statements in the minidom.py file. Either way, the above looks like an attribute node produces a value of None rather than any kind of character string. > The input file contains an block which is what actually > causes the problem. If you remove that node and subnodes, it works > fine. For a while at least, you can view the input file at > http://rafb.net/p/5R1JlW12.html The horror! ;-) > Someone suggested that I should try xml.etree.ElementTree, however > writing the same type of simple code to import and then write the file > mangles the xsd:schema stuff because ElementTree does not understand > namespaces. I'll leave this to others: I don't use ElementTree. > By the way, is pyxml a live project or not? Should it still be used? > It's odd that if you go to http://www.python.org/and click the link > "Using python for..." XML, it leads you to http://pyxml.sourceforge.net/topics/ > > If you then follow the download links to > http://sourceforge.net/project/showfiles.php?group_id=6473 you see that > the latest file is 2004, and there are no versions for newer pythons. > It also says "PyXML is no longer maintained". Shouldn't the link be > removed from python.org? The XML situation in Python's standard library is controversial and can be probably inaccurately summarised by the following chronology: 1. XML is born, various efforts start up (see the qp_xml and xmllib modules). 2. Various people organise themselves, contributing software to the PyXML project (4Suite, xmlproc). 3. The XML backlash begins: we should all apparently be using stuff like YAML (but don't worry if you haven't heard of it). 4. ElementTree is released, people tell you that you shouldn't be using SAX or DOM any more, "pull" parsers are all the rage (although proponents overlook the presence of xml.dom.pulldom in the Python standard library). 5. ElementTree enters the standard library as xml.etree; PyXML falls into apparent disuse (see remarks about SAX and DOM above). I think I looked seriously at wrapping libxml2 (with libxml2dom [1]) when I experienced issues with both PyXML and 4Suite when used together with mod_python, since each project used its own Expat libraries and the resulting mis-linked software produced very bizarre results. Moreover, only cDomlette from 4Suite seemed remotely fast, and yet did not seem to be an adequate replacement for the usual PyXML functionality. People will, of course, tell you that you shouldn't use a DOM for anything and that the "consensus" is to use ElementTree or lxml (see above), but I can't help feeling that this has a damaging effect on the XML situation for Python: some newcomers would actually benefit from the traditional APIs, may already be familiar with them from other contexts, and may consider Python lacking if the support for them is in apparent decay. It requires a degree of motivation to actually attempt to maintain software providing such APIs (which was my solution to the problem), but if someone isn't totally bound to Python then they might easily start looking at other languages and tools in order to get the job done. Meanwhile, here are some resources: http://wiki.python.org/moin/PythonXml Paul [1] http://www.python.org/pypi/libxml2dom From paddy3118 at googlemail.com Mon Jan 28 01:40:27 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 27 Jan 2008 22:40:27 -0800 (PST) Subject: optional static typing for Python References: <0e963ca7-2525-4c74-817f-ed67a48aedf5@i3g2000hsf.googlegroups.com> <7xbq76pva9.fsf@ruckus.brouhaha.com> <7x1w82xymd.fsf@ruckus.brouhaha.com> Message-ID: On Jan 28, 6:17 am, Paul Rubin wrote: > Paddy writes: > > Given the complexity of current microprocessors i'm guessing that > > their previous testing methods would be too good to just junk in > > totality because the FDIV bug was not found. Similarly if they were > > not using formal methods then it makes sense to add it too your > > arsenal; and unfortunately it takes a mistake like that to allow > > different methods to be explored and incorporated. > > Fair enough. My main issue was against the notion that random testing > is the only thing necessary. Sorry Paul if I may have given that impression, its just that when you bring in random testing to a design that until then had only directed tests you can see the bug rate jump up! Think of a hysteresis curve that has gone flat with current testing methods as not many new bugs are being found; add a new test methodology - random testing and you get a new hysteresis curve added as bugs found jump up again. We eventually ship the chip and get awarded by one of our large customers for quality - which happened - so thats why I put it forward. - Paddy. From max at alcyone.com Tue Jan 1 23:40:16 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 Jan 2008 20:40:16 -0800 Subject: os.tmpfile() In-Reply-To: References: Message-ID: jyoung79 at kc.rr.com wrote: > Can anyone elaborate on how 'os.tmpfile()' works? I was thinking it would create some sort of temporary file I could quickly add text too and then when I was finished would automatically get rid of it. Here's my questions: ... > Can you actually 'write' to this file? And if so, do you have to 'close()' it when you're done with it? Thanks for your help with this... I'm still learning Python and haven't been able to find out much about this in the documentation or on-line. It's a file. You read strings from it and write strings to it. It isn't a string itself. Given that what you're trying to do doesn't make any sense, it's hard to know where to begin to identify what's confusing you. -- 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 And though the odds say improbable / What do they know -- Stevie Wonder From gherzig at fmed.uba.ar Mon Jan 28 10:26:32 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Mon, 28 Jan 2008 12:26:32 -0300 Subject: sharing objects between classes Message-ID: <479DF428.4070902@fmed.uba.ar> Hi all. Im wondering the way to share a database connection between some classes: So far, i came up with a simple class schema, where each class means each different relation, i mean i have the follow classes class Database(object): ## make the connection self.conn = make_conn(....) class Table(object): def get_fields: .... And at this point i dont know how to use the Database.conn attribute, since the get_fields method will perform a query over the given database. At first, i just define the Table class as a inner class of Database, but if i try a class Database(object): ## make the connection def __init__(self): self.conn = sql_connect(....) self.table = Table('foo') class Table(object): ## inner class def get_fields(self, name): .... I get a "NameError: global name 'Table' is not defined". So, which would the right pattern to use here? Using a global module? I dont know why, but i dont like that idea too much. Any comments will be appreciated! Thanks! Gerardo From gagsl-py2 at yahoo.com.ar Tue Jan 22 22:13:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Jan 2008 01:13:31 -0200 Subject: Extract value from a attribute in a string References: Message-ID: En Tue, 22 Jan 2008 23:45:22 -0200, escribi?: > I am looking for some help in reading a large text tile and extracting > a value from an attribute? so I would need to find name=foo and > extract just the value foo which can be at any location in the string. > The attribute name will be in almost each line. In this case a regular expression may be the right tool. See http://docs.python.org/lib/module-re.html py> import re py> text = """ok name=foo ... in this line name=bar but ... here you get name = another thing ... is this what you want?""" py> for match in re.finditer(r"name\s*=\s*(\S+)", text): ... print match.group(1) ... foo bar another -- Gabriel Genellina From greg.johnston at gmail.com Wed Jan 23 10:41:47 2008 From: greg.johnston at gmail.com (Greg Johnston) Date: Wed, 23 Jan 2008 07:41:47 -0800 (PST) Subject: PyGTK, Glade, and ComboBoxEntry.append_text() References: <4066a33f-6293-48e3-a48c-66af699d0eb9@i29g2000prf.googlegroups.com> Message-ID: <03d13e0b-9cf4-47e1-95c4-082ffd6dc76d@e4g2000hsg.googlegroups.com> On Jan 21, 5:44?pm, Greg Johnston wrote: > Hey all, > > I'm a relative newbie to Python (switched over from Scheme fairly > recently) but I've been usingPyGTKand Glade to create an interface, > which is a combo I'm very impressed with. > > There is, however, one thing I've been wondering about. It doesn't > seem possible to modifyComboBoxEntrychoice options on the fly--at > least with append_text(), etc--because they were not created with > gtk.combo_box_entry_new_text(). Basically, I'm wondering if there's > any way around this. > > Thank you, > Greg Johnston P.S. If anyone reads this later wondering how to do it, all you need to do is "prime" the ComboBoxEntry with a blank entry in Glade. You can then use append_text(), insert_text(), etc. on the object, as well as remove_text(0) to get rid of your blank entry. From rtw at freenet.co.uk Thu Jan 3 11:48:24 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Thu, 03 Jan 2008 10:48:24 -0600 Subject: Who's to blame? References: <92dfc2fc-0677-43c0-b34f-4f240fa40205@e4g2000hsg.googlegroups.com> Message-ID: Nicola Musatti wrote in news:92dfc2fc-0677-43c0-b34f-4f240fa40205 @e4g2000hsg.googlegroups.com in comp.lang.python: Note there is a wxpython mailinglist/newsgroup: news:gmane.comp.python.wxpython [snip] > problem lies in the fact that apparently ShowModal() does not return > when either the Yes or the No buttons are pressed. Curiously, if you > change the Yes and No buttons with the OK and Cancel ones that are > currently commented everything works as expected. This is because the wx.Dialog class has handlers for the wxID_OK and wxID_CANCEL button identifiers, IIRC in windows the MS supplied dialog procedure behaves this way. > > As the sbs_test_xrc.py file below is automatically generated by > wxPython 2.8.6.1's XRCed tool from a XRC file which in turn is > generated by wxFormBuilder (http://wxformbuilder.org/), I really cant > figure out to whom I should report this problem, assuming I'm not > missing some obvious mistake of mine, that is. > class MainFrame(sbs_test_xrc.xrcMainFrame): > def __init__(self, parent): > sbs_test_xrc.xrcMainFrame.__init__(self, parent) > self.button.Bind(wx.EVT_BUTTON, self.OnButton) First you can make the dialog a member, you are showing and hiding it so there is no need to create a new one every time OnButton is fired. self.dialog = sbs_test_xrc.xrcDialog(self) # now replace the defaults of ID_OK and ID_CANCEL # self.dialog.SetAffirmativeId( wxID_YES ) self.dialog.SetEscapeId( wxID_NO ) Alternativly you could derive from xrcDialog as you are with xrcMainFrame and do the above in the derived classes __init__. > def OnButton(self, event=None): > d = sbs_test_xrc.xrcDialog(self) > ## if d.ShowModal() == wx.ID_OK: > if d.ShowModal() == wx.ID_YES: > self.Close() > http://www.wxpython.org/docs/api/wx.Dialog-class.html Rob. -- http://www.victim-prime.dsl.pipex.com/ From anne.nospam01 at wangnick.de Mon Jan 7 17:29:51 2008 From: anne.nospam01 at wangnick.de (anne.nospam01 at wangnick.de) Date: Mon, 7 Jan 2008 14:29:51 -0800 (PST) Subject: What is the encoding of __file__? References: <736ae822-54a9-4ee6-91fe-92c2c6eb43db@21g2000hsj.googlegroups.com> <4782A255.8070604@v.loewis.de> Message-ID: On 7 Jan., 23:06, "Martin v. L?wis" wrote: > > can someone quickly tell me what the encoding of __file__ is? I can't > > find it in the documentation. > > > BTW, I'm using Python 2.5.1 on WIndows XP and Vista. > > It's platform-specific - the same encoding that is used for file names > (i.e. sys.getfilesystemencoding()). On Windows, it will be "mbcs", which > in turn is installation-specific - on Western European/US installations, > it's "windows-1252". Thanks, I'll then use sys.getfilesystemencoding() to decode _file__ and re-encode into utf-8, which is the default encoding of all strings in our software, as we deal a bit with Chinese terms. Windows-1252 on my box. I just created a directory containing Chinese characters (on Vista), and whoa, files opened with IDLE are empty, import doesn't find modules in that directory. Of course Windows-1252 can't encode these ... But I understand that Python 3 will clean this up? Kind regards, Sebastian From bladedpenguin at gmail.com Sat Jan 26 00:17:01 2008 From: bladedpenguin at gmail.com (Tim Rau) Date: Fri, 25 Jan 2008 21:17:01 -0800 (PST) Subject: How can I use the up and down, left and right arrow keys to control a Python Pgm References: Message-ID: On Jan 25, 10:48 pm, "jitrowia" wrote: > I was wondering what kind of python code I would need to enable me to > use the up and down, left and right arrow keys to control software > programming decisions within a Python Program. > > Any direction and advice would be greatly appreciated, > > Thank You, > Rodney "software programming decisions" is awfully vague. COuld oyu narrow down exactly what you want to do? From brkict at gmail.com Thu Jan 31 10:16:47 2008 From: brkict at gmail.com (glomde) Date: Thu, 31 Jan 2008 07:16:47 -0800 (PST) Subject: Bug/Patch: Problem with xml/__init__.py when using freeze.py Message-ID: <36e7c2d1-27f0-47c6-9527-14eb3353b0db@f47g2000hsd.googlegroups.com> Hi, I tried to do freeze.py for my script that uses ElementTree. But got the this error: File "/usr/lib/python2.5/xml/__init__.py", line 45, in _xmlplus.__path__.extend(__path__) AttributeError: 'str' object has no attribute 'extend' The reason seems that _xmlplus.__path__ is a string after freeze.py. I fixed it by changing the import to: try: _xmlplus.__path__.extend(__path__) sys.modules[__name__] = _xmlplus except AttributeError: pass This might not be the correct solution but it works for me. I do not really now how the __path__ variable works in a freezed environment. Best regards /T From konrad at isg.cs.uni-magdeburg.de Wed Jan 30 03:21:28 2008 From: konrad at isg.cs.uni-magdeburg.de (=?ISO-8859-1?Q?Konrad_M=FChler?=) Date: Wed, 30 Jan 2008 09:21:28 +0100 Subject: Removing hidden files and folders with python ... Message-ID: Hi, I try to delete a whole directory-tree using shutil.rmtree(...) But there are always the hidden files and folders (e.g. from the svn .svn) left. How can I delete -all- files and folders (also the hidden) with python? Many Thanks Konrad From nikolaskaralis at gmail.com Wed Jan 2 09:22:21 2008 From: nikolaskaralis at gmail.com (Nikolas Karalis) Date: Wed, 2 Jan 2008 16:22:21 +0200 Subject: cloud computing (and python)? In-Reply-To: <3693eb2d-9034-4f30-8d8f-84376bc6d521@e25g2000prg.googlegroups.com> References: <9c8776d0-6d32-44e6-a79a-82cd90877620@i12g2000prf.googlegroups.com> <13nle9g72fbtfce@corp.supernews.com> <90729745-badf-41bd-ad87-eac67e3733da@t1g2000pra.googlegroups.com> <7yBej.30029$CN4.18224@news-server.bigpond.net.au> <3693eb2d-9034-4f30-8d8f-84376bc6d521@e25g2000prg.googlegroups.com> Message-ID: <85b2e0230801020622x244ea444h2273572dd336e1ee@mail.gmail.com> I read a few things about this on the web, and i still don't get the difference between cloud computing and grid computing... It looks like the same. Nikolas On Jan 2, 2008 3:46 AM, PatrickMinnesota wrote: > On Jan 1, 7:12 pm, Neil Hodgson wrote: > > Cloud computing is mostly about scalability. You do not need to be > > concerned so much about low level infrastructure details such as > > purchasing servers, configuring and maintaining them, hiring space in > > data centres, linking up data centres, etc. It converts a lot of fixed > > costs into lower recurring costs so makes it easier for a start up with > > limited capital to start operating. > > > > There are Python libraries for accessing some of the cloud computing > > services and you can also host Python application code on some services > > that allow code execution. This includes services that can run arbitrary > > code on virtual machines such as EC2 and more restricted computational > > services like Hadoop which can run Jython. > > > > Neil > > I would say that cloud computing to an implementor or company > providing cloud > computing is all about scalability and stuff like S3 and EC3. There > are > other options for this BTW. > > But to the end user, it's about having your data and applications on a > disk > served by a network and server that is somewhere out there on the net > and > accessible from anywhere that you have connectivity. You might travel > with > a laptop, but generally, when in Hong Kong, you'll be screwed if a > chunk of > data is sitting on a disk inside a desktop in your home office and > isn't on > your laptop. With the 'cloud' concept, it wouldn't matter where you > are, > as long as you have a connection to the internet, you can run the apps > and > access the data. > > Issues: and yes, they are big, who has control over the data, is it > being > backed up and protected, and is your private data being mined without > your approval. Oh, > and what happens if you use Zoho's system and they go out of > business? > -- > http://mail.python.org/mailman/listinfo/python-list > -- Nikolas Karalis Applied Mathematics and Physics Undergraduate National Technical University of Athens, Greece http://users.ntua.gr/ge04042 -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at marcher.name Mon Jan 7 15:54:55 2008 From: martin at marcher.name (Martin Marcher) Date: Mon, 07 Jan 2008 21:54:55 +0100 Subject: Python's great, in a word References: <499211c2-c771-4b56-9444-87ede5c86653@q39g2000hsf.googlegroups.com> Message-ID: On Monday 07 January 2008 21:25 Dustan wrote: > On Jan 7, 11:40 am, Martin Marcher wrote: >> it's pythonicness. > > "it is pythonicness"??? not all here are native english speakers, but thanks for the correction. I'll try to keep it in mind. -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From fredrik at pythonware.com Wed Jan 9 05:12:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 09 Jan 2008 11:12:31 +0100 Subject: "Canonical" way of deleting elements from lists In-Reply-To: <5ujkbaF1e11ksU1@mid.dfncis.de> References: <5ujkbaF1e11ksU1@mid.dfncis.de> Message-ID: Robert Latest wrote: >>From a list of strings I want to delete all empty ones. This works: > > while '' in keywords: keywords.remove('') > > However, to a long-term C programmer this looks like an awkward way of > accomplishing a simple goal, because the list will have to be re-evaluated > in each iteration. you're using a quadratic algorihm ("in" is a linear search, and remove has to move everything around for each call), and you're worried about the time it takes Python to fetch a variable? > Is there a way to just walk the list once and throw out unwanted > elements as one goes along? creating a new list is always almost the right way to do things like this. in this specific case, filter() or list comprehensions are good choices: keywords = filter(None, keywords) # get "true" items only keywords = [k for k in keywords if k] also see: http://effbot.org/zone/python-list.htm#modifying From gowricp at gmail.com Sun Jan 13 18:44:12 2008 From: gowricp at gmail.com (Gowri) Date: Sun, 13 Jan 2008 15:44:12 -0800 (PST) Subject: converting JSON to string References: <9afa232c-793e-4972-b667-2f3958820234@v29g2000hsf.googlegroups.com> <13og5g06rvrtefa@corp.supernews.com> Message-ID: <4f5b1f7a-923a-4d68-ab6d-5e019590f02d@k2g2000hse.googlegroups.com> On Jan 12, 2:58 am, Jeroen Ruigrok van der Werven wrote: > -On [20080112 08:38], Gowri (gowr... at gmail.com) wrote: > > >Actually, I have one other problem after all this. I see that if I try > >to construct JSON output as above, it is of the form > >[{'isbn': u'1-56592-724-9', 'title': u'The Cathedral & the Bazaar'}, > >{'isbn': u'1-56592-051-1', 'title': u'Making TeX Work'}] > >The extra 'u' seems to causing syntax error in JavaScript which is not > >able to parse this response string. Any idea how I can fix this? > > JSON does not support Unicode in the sense of allowing raw Unicode codepoints. > Instead JSON uses a \uNNNN scheme to encode Unicode characters (a bit flawed > to limit it to four hexadecimal digits though, it leaves the whole CJK Unified > Ideographs Extension B out of scope.). > > I use simplejson along with lxml/ElementTree for my JSON<>XML needs. > > -- > Jeroen Ruigrok van der Werven / asmodai > ????? ?????? ??? ?? ??????http://www.in-nomine.org/|http://www.rangaku.org/ > Any road leads to the end of the world... Thanks Jeroen. That helped a lot :) From sevengeon at gmail.com Wed Jan 2 07:39:43 2008 From: sevengeon at gmail.com (Geon.) Date: Wed, 2 Jan 2008 04:39:43 -0800 (PST) Subject: how to get playtime ( playback time ) of movie files? Message-ID: <7ab948ea-0ea9-47ab-80ff-73a95a4d958d@d21g2000prf.googlegroups.com> hi.. i want get playtime of movie files ( avi , mpeg , wav , mov etc... ) how to get ?? please help me .. From rasky at develer.com Sun Jan 27 15:15:55 2008 From: rasky at develer.com (Giovanni Bajo) Date: Sun, 27 Jan 2008 20:15:55 GMT Subject: strftime return value encoding (mbcs, locale, etc.) Message-ID: <%D5nj.2630$Xg7.935@tornado.fastwebnet.it> Hello, I am trying to find a good way to portably get the output of strftime() and put it onto a dialog (I'm using PyQt, but it doesn't really matter). The problem is that I need to decode the byte stream returned by strftime () into Unicode. This old bug: http://mail.python.org/pipermail/python-bugs-list/2003- November/020983.html (last comment) mentions that it is "byte string in the locale's encoding". The comment also suggests to use "mbcs" in Windows (which, AFAIK, it's sort of an "alias" encoding for the current Windows codepage), and to find out the exact encoding using locale.getpreferredencoding(). Thus, I was hoping that something like: strftime("%#c", localtime()).decode(locale.getpreferredencoding()) would work... but alas I was reported this exception: LookupError: unknown encoding: cp932 So: what is the correct code to achieve this? Will something like this work: data = strftime("%#c", localtime()) if os.name == "nt": data = data.decode("mbcs") else: data = dada.decode(locale.getpreferredencoding()) Is this the correct way of doing it? (Yes, it sucks). Shouldn't Python automatically alias whatever is returned by locale.getpreferredencoding() to "mbcs", so that my original code works portably? Thanks in advance! -- Giovanni Bajo From stanc at al.com.au Thu Jan 3 02:18:50 2008 From: stanc at al.com.au (Astan Chee) Date: Thu, 03 Jan 2008 18:18:50 +1100 Subject: sending commands in body of HTTP with urllib2 Message-ID: <477C8C5A.7000901@al.com.au> Hi, Im trying to implement the logic from http://www.hypothetic.org/docs/msn/general/http_connections.php to a simple python code using urllib2 and some parts of urllib. Im behind a http proxy that requires authentication that is why Im using urllib2. Im asking for help on how to send commands in a body of a HTTP before requesting for response. What am I doing wrong? I only get the response from the server but my commands never seem to be acknowledged or properly handled. Below is my code: import urllib2 import base64 import urllib USER='user' PASS='pass' proxy_info = {'host' : "proxy.com.au",'port' : 8080} # build a new opener that uses a proxy requiring authorization proxy_support = urllib2.ProxyHandler({"http" : \ "http://%(host)s:%(port)d" % proxy_info}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) user_pass = base64.encodestring('%s:%s' % (urllib.unquote(USER),urllib.unquote(PASS))) authheader = "Basic %s" % user_pass opener.addheaders = [('Accept-Language','en-us'), ('Accept-Encoding','gzip, deflate'), ('Host','gateway.messenger.hotmail.com'), ('Proxy-Connection','Keep-Alive'), ('Connection','Keep-Alive'), ('Pragma','no-cache'), ('Content-Type','application/x-msn-messenger'), ('User-agent','MSMSGS'), ('Accept','*/*'), ('Proxy-authorization',authheader)] # install it urllib2.install_opener(opener) # use it url = 'http://gateway.messenger.hotmail.com/gateway/gateway.dll?Action=open&Server=NS&IP=messenger.hotmail.com' values = 'VER 5 MSNP8 CVR0' f = urllib2.urlopen(url,values) print f.headers print f.read() Thanks for any help! From ioscas at gmail.com Wed Jan 23 08:20:32 2008 From: ioscas at gmail.com (kliu) Date: Wed, 23 Jan 2008 05:20:32 -0800 (PST) Subject: Is there a HTML parser who can reconstruct the original html EXACTLY? References: Message-ID: On Jan 23, 7:39 pm, "A.T.Hofkamp" wrote: > On 2008-01-23, ios... at gmail.com wrote: > > > Hi, I am looking for a HTML parser who can parse a given page into > > a DOM tree, and can reconstruct the exact original html sources. > > Why not keep a copy of the original data instead? > > That would be VERY MUCH SIMPLER than trying to reconstruct a parsed tree back > to original source text. > > sincerely, > Albert Thank u for your reply. but what I really need is the mapping between each DOM nodes and the corresponding original source segment. From meesters at uni-mainz.de Mon Jan 28 13:30:01 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Mon, 28 Jan 2008 19:30:01 +0100 Subject: extending Python - passing nested lists References: <8d3fbe29-f188-4a5b-b249-ba01a3d00320@1g2000hsl.googlegroups.com> Message-ID: Mark Dickinson wrote: > Well, it's pretty clear: you misspelt "length" as "lenght". :) Well, that's not it ;-). (Damn copy & paste plague ...) > > PySequence_Fast doesn't return an array: it returns a PyObject---in > this case, a PyObject corresponding to a Python tuple. That's it. Thanks. Think I just need a different approach. I got completely on the wrong track here. Thanks Christian From dickinsm at gmail.com Mon Jan 28 13:20:33 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 28 Jan 2008 10:20:33 -0800 (PST) Subject: extending Python - passing nested lists References: Message-ID: <8d3fbe29-f188-4a5b-b249-ba01a3d00320@1g2000hsl.googlegroups.com> On Jan 28, 10:10 am, Christian Meesters wrote: > Hi, > > I would like to write a C-extension function for an application of mine. For > this I need to pass a nested list (like: [[a, b, c], [d, e, f], ...], where > all letters are floats) to the C-function. Now, with the code I have the > compiler is complaining: "subscripted value is neither array nor pointer". > Can somebody tell me what's wrong? Well, it's pretty clear: you misspelt "length" as "lenght". :) PySequence_Fast doesn't return an array: it returns a PyObject---in this case, a PyObject corresponding to a Python tuple. As the compiler says, a PyObject is neither an array nor a pointer, so when you write dummy_list[i] the compiler doesn't know what you mean. You probably want to use PySequence_Fast_GET_ITEM. See the documentation at http://docs.python.org/api/sequence.html#l2h-333 Mark From tjreedy at udel.edu Sun Jan 27 20:01:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jan 2008 20:01:17 -0500 Subject: Python Genetic Algorithm References: Message-ID: "Max" wrote in message news:caf75b0d-7ed3-421a-93f8-6f7d90a98923 at p69g2000hsa.googlegroups.com... | In GAs, you operate on a Population of solutions. Each Individual from | the Population is a potential solution to the problem you're | optimizing, and Individuals have what's called a chromosome - a | specification of what it contains. For example, common chromosomes are | bit strings, lists of ints/floats, permutations...etc. I'm stuck on | how to implement the different chromosomes. I have a Population class, | which is going to contain a list of Individuals. Each individual will | be of a certain chromosome. I envision the chromosomes as subclasses | of an abstract Individual class, perhaps all in the same module. I'm | just having trouble envisioning how this would be coded at the | population level. Presumably, when a population is created, a | parameter to its __init__ would be the chromosome type, but I don't | know how to take that in Python and use it to specify a certain class. | | I'm doing something similar with my crossover methods, by specifying | them as functions in a module called Crossover, importing that, and | defining | | crossover_function = getattr(Crossover, "%s_crossover" % xover) | | Where xover is a parameter defining the type of crossover to be used. | I'm hoping there's some similar trick to accomplish what I want to do | with chromosomes - or maybe I'm going about this completely the wrong | way, trying to get Python to do something it's not made for. Any help/ | feedback would be wonderful. 'Python genetic algorithm' returns 25000 hits with Google. But here is what I would do without looking at them. Start with the Individual base class and common methods, some virtual (not implemented). An example of a virtual method would be the crossover(self,other) method, since its implementation depends on the concrete chromosome implementation. Make subclasses with concrete chromosome types (initialized in .__init__). For each, implement the methods that depend on that type. In particular, the mutate(self, args) and crossover(self,other, args) methods. For the Population class, give __init__ an 'individual' parameter and store it as an attribute. If you want, check that it 'issubclass(Individual)'. To add members to the population, call the stored subclass. To operate on the population, write Population methods. There should not depend on the particular chromosome implementations. To operate on the members within the Population methods, call their Individual methods. b = a.mutate(args); c = a.crossover(b, args). I see two ways to deal with scoring the fitness of individuals within a Population instance. Once is to write a particular fitness function, pass it to the Population init to save as an attribute, and then call as needed. The other is to subclass an Individual subclass, give it that funtion fitness method, and pass that subsubclass to Population. The difference is between having Population methods calling self.fitness(some_member) versus some_member.fitness(). I hope this is helpful for getting started. Terry Jan Reedy From JAMoore84 at gmail.com Thu Jan 24 11:44:31 2008 From: JAMoore84 at gmail.com (JAMoore84 at gmail.com) Date: Thu, 24 Jan 2008 08:44:31 -0800 (PST) Subject: Beginner Pyserial Question Message-ID: <93223c7c-c891-424c-bc4f-00d61592663a@l32g2000hse.googlegroups.com> Hi Guys, I have a project where I'd like to save GPS data that is streamed to a Sony Vaio over bluetooth. I can monitor the data stream over Hyper Terminal, but I'd like to use python to capture it as well. I've installed Python 2.5, pyserial 2.2 and the appropriate pywin program (pywin32-210.win32-py2.5.exe). My problem comes when I try to open a serial port. After importing "serial", I issue the following statement: >>> GPS = serial.Serial(0) Traceback (most recent call last): File "", line 1, in GPS = serial.Serial(0) File "C:\Python25\lib\site-packages\serial\serialutil.py", line 156, in __init__ self.open() File "C:\Python25\lib\site-packages\serial\serialwin32.py", line 55, in open raise SerialException("could not open port: %s" % msg) SerialException: could not open port: (2, 'CreateFile', 'The system cannot find the file specified.') I'm not sure where the source of the problem is. I was wondering if someone could recognize what might be be. the Vaio is running XP SP2. Thanks! From george.maggessy at gmail.com Tue Jan 8 01:21:53 2008 From: george.maggessy at gmail.com (George Maggessy) Date: Mon, 7 Jan 2008 22:21:53 -0800 (PST) Subject: Pet Store Message-ID: <964259c9-2a6f-4a9e-8878-762de20c3b53@v46g2000hsv.googlegroups.com> Hi there, I'm an experience Java developer trying to learn Python. I just finished the Python tutorial on python.org and I'm currently reading the "Learning Python" book. However, if I could find something like a simple web app with some best practices, such as those famous "Java Pet Store" apps, I think that would help me to fill up some gaps in my learning process. Does anybody know any app like that? Cheers, George From matiassurdi at gmail.com Thu Jan 3 11:43:46 2008 From: matiassurdi at gmail.com (Matias Surdi) Date: Thu, 03 Jan 2008 17:43:46 +0100 Subject: Adding a HTTP header to a SOAPpy request Message-ID: Hi, Could anybody tell me which is the easier way to do a SOAP call to a web service wich requires an http header to be present? I can't figure it out. Thanks a lot Some code I'm using: import SOAPpy s = SOAPpy.SOAPProxy("http://10.3.5.128:10560/SERVICES",namespace="http://ws.mysite.com") s.some_method() Thanks a lot. From stanc at al.com.au Thu Jan 3 03:42:51 2008 From: stanc at al.com.au (Astan Chee) Date: Thu, 03 Jan 2008 19:42:51 +1100 Subject: sending commands in body of HTTP with urllib2 In-Reply-To: <477C8C5A.7000901@al.com.au> References: <477C8C5A.7000901@al.com.au> Message-ID: <477CA00B.6010001@al.com.au> Astan Chee wrote: > Hi, > Im trying to implement the logic from > http://www.hypothetic.org/docs/msn/general/http_connections.php to a > simple python code using urllib2 and some parts of urllib. Im behind a > http proxy that requires authentication that is why Im using urllib2. Im > asking for help on how to send commands in a body of a HTTP before > requesting for response. What am I doing wrong? I only get the response > from the server but my commands never seem to be acknowledged or > properly handled. > I've tried a httplib implementation for it, and now it keeps giving me an Error 400 (bad request) / Invalid header name as a response. What am I doing wrong? is the server depreciated? or not working like the document describes it? Thanks again for any help. Below is my code import httplib import base64 import urllib USER='user' PASS='pass' url = 'http://gateway.messenger.hotmail.com/gateway/gateway.dll?Action=open&Server=NS&IP=messenger.hotmail.com' values = 'VER 5 MSNP8 CVR0\r\n' user_pass = base64.encodestring('%s:%s' % (urllib.unquote(USER),urllib.unquote(PASS))) authheader = "Basic %s" % user_pass proxy_authorization='Proxy-authorization: Basic '+user_pass+'\r\n' conn = httplib.HTTPConnection("proxy.com.au", 8080) conn.connect() conn.putrequest("POST", url) conn.putheader('Accept','*/*') conn.putheader('Accept-Language','en-us') conn.putheader('Accept-Encoding','gzip, deflate') conn.putheader('User-agent','MSMSGS') conn.putheader('Host','gateway.messenger.hotmail.com') conn.putheader('Proxy-Connection','Keep-Alive') conn.putheader('Pragma','no-cache') conn.putheader('Content-Type','application/x-msn-messenger') conn.putheader('content-length',str(len(values))) conn.putheader('Proxy-authorization',authheader) conn.endheaders() conn.send(values) r = conn.getresponse() print r.status, r.reason print r.msg print r.read() From steve at holdenweb.com Wed Jan 30 21:51:53 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Jan 2008 21:51:53 -0500 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <13q2960err4db28@corp.supernews.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> <13q2960err4db28@corp.supernews.com> Message-ID: <47A137C9.507@holdenweb.com> Grant Edwards wrote: > On 2008-01-31, Daniel Fetchinson wrote: >>> I do not understand why no one has answered the following question: >>> >>> Has anybody worked with Gene Expression Programming???? >> Hmmmmm, maybe because nobody did? Just a thought. It can also be that >> everyone worked with it but everyone is part of a big conspiracy not >> to answer any of your emails just to make you act weird. > > That's it then, now we're going to have to kill you... > Look guys, I thought we'd agreed that the PSU was no longer to be From python.list at tim.thechases.com Tue Jan 8 21:41:20 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 08 Jan 2008 20:41:20 -0600 Subject: Open a List of Files In-Reply-To: References: <874pdomrrd.fsf@mulj.homelinux.net> Message-ID: <47843450.8070508@tim.thechases.com> > I decided that I was just trying to be "too smooth by 1/2" so I fell back to > > messages = open(os.path.join(host_path,'messages.txt'), 'wb') > deliveries = open(os.path.join(host_path,'deliveries.txt'), 'wb') > actions = open(os.path.join(host_path,'actions.txt'), 'wb') > parts = open(os.path.join(host_path,'parts.txt'), 'wb') > recipients = open(os.path.join(host_path,'recipients.txt'), 'wb') > viruses = open(os.path.join(host_path,'viruses.txt'), 'wb') > esp_scores = open(os.path.join(host_path,'esp_scores.txt'), 'wb') Another way to write this which reduces some of the code would be filenames = ['messages', 'deliveries', 'actions', 'parts', 'recipients', 'viruses', 'esp_scores'] (messages, deliveries, actions, parts, recipients, viruses, esp_scores) = [ open(os.path.join(host_path, '%s.txt' % fn), 'wb') for fn in filenames ] It becomes even more clear if you make an intermediate "opener" function such as binwriter = lambda fname: open( os.path.join(host_path, '%s.txt' % fname), 'wb') (messages, deliveries, actions, parts, recipients, viruses, esp_scores) = [ binwriter(fn) for fn in filenames] This makes it easier to change intended functionality in one place, rather than updating each line. Additionally, it's easy to add a new entry (just add the filename in the filename list, and the variable-name in the assignment tuple). It also makes it clear that each one is getting the same treatment (that there's not some outlier making you study matters carefully to figure out that there isn't). -tkc From joe at incomps.com Tue Jan 8 15:02:40 2008 From: joe at incomps.com (Joseph Bernhardt) Date: Tue, 8 Jan 2008 13:02:40 -0700 Subject: ZSI and .NET Message-ID: <000c01c85231$6cd3bcb0$467b3610$@com> I am successfully using ZSI to create a web service for our internal use. A request containing a username and password will respond with user information. Sample Request: Jough joughspassword Response for Sample Request: my at email.com 28 my at otheremail.com Unfortunately, when I try to complete the request via C#, an exception will be thrown when the response is deserialized: {"The specified type was not recognized: name='string', namespace='http://www.w3.org/2001/XMLSchema', at ."} I realize that my problem is mainly .NET based, but since it has to do with datatypes I thought someone from here may be able to help me. The python code is a simple CGI dispatched function. Let me know if you need to see it, or the wsdl. Thanks! Jough -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Jan 14 18:34:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 10:34:45 +1100 Subject: NotImplimentedError References: <882739.52486.qm@web63705.mail.re1.yahoo.com> <874pdgf2wo.fsf@benfinney.id.au> Message-ID: <87ejckdlre.fsf@benfinney.id.au> Ben Finney writes: > I think of NotImplemented as equivalent to None Not "equivalent"; rather "comparable in usage". -- \ "[W]e are still the first generation of users, and for all that | `\ we may have invented the net, we still don't really get it." | _o__) -- Douglas Adams | Ben Finney From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 29 10:35:52 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 29 Jan 2008 16:35:52 +0100 Subject: Terse Syntax through External Methods In-Reply-To: References: <5vu9gaF1no9i1U1@mid.uni-berlin.de> Message-ID: <479f47d1$0$13485$426a74cc@news.free.fr> Jens a ?crit : > On Jan 25, 3:19 pm, "Diez B. Roggisch" wrote: >> Jens schrieb: >> >> >> >>> Hello Everyone >>> I'm newbie to Zope and i have a few questions regarding external >>> methods. (snip) >>> This doesn't work because because the method doesn't have access to >>> the environment. >> If it has to be an External method, you can't access such a context >> AFAIK. IIRC, that's what the 'self' argument is for. Now I don't know if it will solve the OP's problem with dtml (which I avoid like pest). >> But then you can create a python script that _has_ this context, >> and passese it to the external method. Not the nicest solution, but >> should work. >> > > Like I said i'm a newbie. I though the deal with Zope was that i > couldn't really do inline scripting (for security reasons) > like in php but had to use these external methods. how does one go > about creating a "normal" python script exactly and > how do I invoke it's functionality? Zope (well... Zope2.x) has an object type named "Script (Python)". What you can do with them is restricted (for security reasons) but is obviously enough for what you want here. And really, you should *not* use dtml unless you have no other choice at all. Anyway: Zope is a world in itself, and most pythoneers don't use it. The Zope experts are mostly on the Zope's mailing list, so that's where you should post such questions. HTH From steven at REMOVE.THIS.cybersource.com.au Mon Jan 21 22:50:50 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 22 Jan 2008 03:50:50 -0000 Subject: read files References: Message-ID: On Tue, 22 Jan 2008 11:00:53 +0800, J. Peng wrote: > first I know this is the correct method to read and print a file: > > fd = open("/etc/sysctl.conf") > done=0 > while not done: > line = fd.readline() > if line == '': > done = 1 > else: > print line, > > fd.close() The evolution of a Python program. # Solution 2: fd = open("/etc/sysctl.conf") done = False while not done: line = fd.readline() if line: print line, else: done = True fd.close() # Solution 3: fd = open("/etc/sysctl.conf") while True: line = fd.readline() if line: print line, else: break fd.close() # Solution 4: fd = open("/etc/sysctl.conf") lines = fd.readlines() for line in lines: print line, fd.close() # Solution 5: fd = open("/etc/sysctl.conf", "r") for line in fd.readlines(): print line, fd.close() # Solution 6: for line in open("/etc/sysctl.conf").readlines(): print line, # garbage collector will close the file (eventually) # Solution 7: fd = open("/etc/sysctl.conf", "r") line = fd.readline() while line: print line, line = fd.readline() fd.close() # Solution 8: fd = open("/etc/sysctl.conf", "r") for line in fd: print line, fd.close() # Solution 9: for line in open("/etc/sysctl.conf"): print line, # Solution 10: # (the paranoid developer) try: fd = open("/etc/sysctl.conf", "r") except IOError, e: log_error(e) # defined elsewhere print "Can't open file, please try another." else: try: for line in fd: print line, except Exception, e: log_error(e) print "Reading file was interrupted by an unexpected error." try: fd.close() except IOError, e: # Can't close a file??? That's BAD news. log_error(e) raise e -- Steven From Louis.Soninhu at gmail.com Wed Jan 9 14:16:35 2008 From: Louis.Soninhu at gmail.com (Louis.Soninhu at gmail.com) Date: Wed, 9 Jan 2008 11:16:35 -0800 (PST) Subject: problem of converting a list to dict References: <99c05fff-c690-4173-8e41-424a12692188@n20g2000hsh.googlegroups.com> <5ukkcvF1hs5vpU1@mid.uni-berlin.de> Message-ID: <83555c97-bdc1-45e0-a2b2-d8a68e3b0df8@s19g2000prg.googlegroups.com> that's very strange... the list I give here is almost same as the real list, except for the length. Thanks Marc, I'll go check what's wrong elsewhere From Scott.Daniels at Acm.Org Thu Jan 10 00:55:46 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 09 Jan 2008 21:55:46 -0800 Subject: Collecting Rich Data Structures for students In-Reply-To: References: Message-ID: <13obci92687ms70@corp.supernews.com> kirby.urner at gmail.com wrote: > Some of us over on edu-sig, one of the community actives, > have been brainstorming around this Rich Data Structures > idea, by which we mean Python data structures already > populated with non-trivial data about various topics such > as: periodic table (proton, neutron counts); Monty Python > skit titles; some set of cities (lat, long coordinates); types > of sushi. Look into the "Stanford GraphBase" at: http://www-cs-faculty.stanford.edu/~knuth/sgb.html A great source of some data with some interesting related exercises. Also, a few screen-scraping programs that suck _current_ information from some sources should also delight; the students have a shot at getting ahead of the teacher. --Scott David Daniels Scott.Daniels at Acm.Org From bronger at physik.rwth-aachen.de Tue Jan 1 10:27:08 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 01 Jan 2008 16:27:08 +0100 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> <13ndq2ca87epk79@corp.supernews.com> <87prwodcjn.fsf@benfinney.id.au> <13ngchr5qkcvp94@corp.supernews.com> <87bq87d4s4.fsf@benfinney.id.au> <13nklhfs3v71v5b@corp.supernews.com> Message-ID: <87r6h1sh0z.fsf@physik.rwth-aachen.de> Hall?chen! Steven D'Aprano writes: > [...] > > Ah, and now we're getting somewhere! It's not so much that tabs > are intrinsically harmful (as people like Thorsten keep > insisting), but that in a world supposedly dominated by people who > indent with spaces, using tabs might lead to inconsiderate > programmers ignoring your project's coding standards and inserting > spaces into your code base. > > Yes, I can see that is a problem. I believe it is best solved by > refusing contributions from such inconsiderate programmers. After > all, if they're going to ignore your project's code standards in > one aspect, they're invariably going to ignore others as well. No, you cannot have both tabs and spaces. The whole community must settle on a single method. I cannot adjust my editor's settings to the respective SVN tree I'm looking at, nor can I incorporate other project's code into mine if the indentation method is not the same. Of course, there is no intrinsic benefit from spaces but it is the method that has won. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From userprogoogle-139 at yahoo.co.uk Wed Jan 9 04:59:43 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Wed, 9 Jan 2008 01:59:43 -0800 (PST) Subject: Multi form CGI examples? Message-ID: <9443f999-ab6f-4ba6-aba9-bddf6ffb82d3@q77g2000hsh.googlegroups.com> Hi, I have been looking online for some examples of how to create multi form CGI scripts using Python. I have come across a few but am still a little confused - being new to CGI on Python. Can anyone provide me with some pointers to useful tutorials or advice on the best way to go about it? I think I have mastered the basic elements of parsing and processing single forms so it is really a matter of architecture and examples more than anything else. For example should I write everything in one file or split it up over several, also should I use HTML files or hard code the HTML in the script? As for the actual forms, there will probably be three of them. Each will have some elements which are required. Other aspects include the ability to upload files and check whether the person is logged in (probably via cookies although the people who operate the site have yet to get back to me). These are all kind of newbie questions when it comes to CGI, but not being a web developer tips and advice are appreciated. I would rather avoid costly mistakes! Thanks in advance. Kind regards, rod From mail at timgolden.me.uk Sun Jan 13 10:28:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 13 Jan 2008 15:28:39 +0000 Subject: How to get user home directory on Windows In-Reply-To: References: <0bb27916-5416-47b2-b58c-1eb82ccb6d3e@k2g2000hse.googlegroups.com> Message-ID: <478A2E27.8060109@timgolden.me.uk> thebjorn wrote: > On Jan 12, 6:50 pm, "Giampaolo Rodola'" wrote: >> Update. >> I found a way for getting the home directory of the user but it >> requires to validate the user by providing username+password: >> >> def get_homedir(username, password): >> token = win32security.LogonUser( >> username, >> None, >> password, >> win32security.LOGON32_LOGON_NETWORK, >> win32security.LOGON32_PROVIDER_DEFAULT >> ) >> return win32profile.GetUserProfileDirectory(token) >> >> What I'd like to do is avoiding the requirement of the password, the >> same way as if I would on UNIX where it would be enough just using the >> pwd module: >> >> >>> import pwd >> >>> pwd.getpwnam('user').pw_dir >> '/home/user' > > Check out http://msdn2.microsoft.com/en-us/library/bb762181(VS.85).aspx > for some of the complexities of special directories on Windows. Part of the problem here is that is the OP is asking for the "home dir" of a user, but there is no such thing under Windows. Or, rather, there are several such things. The code he posts above will get the path to what will be the user's %USERPROFILE% env var when he logs on. (Which is certainly one of the definitions of "home dir"). But he wants that path *without* having to log them in. The page you refer to (and other similar suggestions of using the os.expanduser function which essentially does the same thing for you) assume you're already logged in as the user in question. I've posted a (WMI-based) solution [1] on the python-win32 list where the OP copied his question. You could do the same just with win32security and _winreg. (Left as an exercise... etc.) Haven't yet heard back from the OP as to whether that's given him what he wants or not. TJG [1] http://mail.python.org/pipermail/python-win32/2008-January/006656.html From bg_ie at yahoo.com Thu Jan 24 10:44:42 2008 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Thu, 24 Jan 2008 07:44:42 -0800 (PST) Subject: Connecting to Sql Server from Python Message-ID: <56f14ea0-defb-445b-b957-7f379a000add@x69g2000hsx.googlegroups.com> Hi, I have an sql server from which I'd like to read and write to. The connection string is as follows - "Data Source=localhost\SQLExpress;Initial Catalog=Test;Integrated Security=True;Pooling=False" Other properties as they appear in Visual Studio 2005 include - Data Provider: .NET Framework Data Provider for SQL Server State: Open Type: Microsoft SQL Server So my question is, how might I connect to my Test Catalog and update data within its tables via perl, Thanks, Barry. From brkict at gmail.com Tue Jan 22 07:14:01 2008 From: brkict at gmail.com (glomde) Date: Tue, 22 Jan 2008 04:14:01 -0800 (PST) Subject: possible to overide setattr in local scope? Message-ID: <9dac9675-992e-4dc5-b085-06f0811939ca@1g2000hsl.googlegroups.com> In a class it is poosible to override setattr, so that you can decide how you should handle setting of variables. Is this possible to do outside of an class on module level. mysetattr(obj, var, value): print "Hello" So that test = 5 would print Hello From Scott.Daniels at Acm.Org Thu Jan 24 22:30:50 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 24 Jan 2008 19:30:50 -0800 Subject: Ignore exceptions In-Reply-To: <244a3456-84d3-4328-b30a-59fae999bada@u10g2000prn.googlegroups.com> References: <8448fdcb-3ee5-4173-a841-0e844e54d9ba@e4g2000hsg.googlegroups.com> <244a3456-84d3-4328-b30a-59fae999bada@u10g2000prn.googlegroups.com> Message-ID: <13pillknr66de4d@corp.supernews.com> Roger Miller wrote: > On Jan 24, 11:30 am, Jonathan Gardner > wrote: >> .... > >> A few sample good uses of try/except blocks: >> (1) Do something else if an expected exception occurs. >> (2) Show a friendly error message when an exception occurs over ... > I'd add (3) Clean-up handlers. These don't actually handle the > problem, they just free resources, close files, etc. before re- > raising the exception for someone else to worry about. Ah, but typically these are try/finally blocks. Many can be dealt with by context mangers in 2.5 or later -- see with_statement. --Scott David Daniels Scott.Daniels at Acm.Org From sevenbark at gmail.com Mon Jan 28 00:12:47 2008 From: sevenbark at gmail.com (sevenbark) Date: Sun, 27 Jan 2008 23:12:47 -0600 Subject: raw_input(), STRANGE behaviour References: <6894a107-525e-4600-842f-f647c95d5c6a@q39g2000hsf.googlegroups.com> Message-ID: On Sat, 26 Jan 2008 04:23:36 -0800 (PST), Dox33 wrote: >WHERE IS THE SECOND LINE? >It is in the file stderr_catch.txt!!! > >**** See the problem? >Please Tell me? Why is the prompt produced by raw_input() printed to >the error channel? It should be stdout, just as the print statement >does. Isn't this the norm in Unix shells also? In bash the "read" command prints the prompt on stderr and the "select" command prints both the menu and prompt on stderr. sb From parvini_navid at yahoo.com Tue Jan 1 03:58:17 2008 From: parvini_navid at yahoo.com (Navid Parvini) Date: Tue, 1 Jan 2008 00:58:17 -0800 (PST) Subject: File Info Message-ID: <692822.86973.qm@web54501.mail.re2.yahoo.com> Dear All, Would you please tell me if there is another function instead of stat that gives the same information ( such as the size of the file) but faster? Thank you in advance. Navid --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Thu Jan 24 10:07:47 2008 From: roy at panix.com (Roy Smith) Date: Thu, 24 Jan 2008 10:07:47 -0500 Subject: Test driven development References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> Message-ID: In article <7b0188a3-f6f6-483c-8f41-2dd9b9522268 at v67g2000hse.googlegroups.com>, ajcppmod at gmail.com wrote: > So my question is when approaching a project that you want to employ > test driven development on how and where do you start? And also if > anyone uses top-down design with TDD I would be interested in how you > do it (does it involve lots of mock objects/ is the first test you > write the last one to pass)? I've been a big fan of TDD for a few years. I don't always use it. When working with legacy code, sometimes the pain of getting things into a test harness exceeds the effort I'm able or willing to put into it right now. The other times I don't use it is when I'm "just doing some simple little thing" (which inevitably grows into something bigger than originally anticipated). In all cases, I often find that code I ended up writing is less well documented, less well tested, and more buggy. You've hit the nail on the head with the top-down, bottom-up issue. TDD (at least in my mind) encourages bottom-up design, because it forces you to have working code on day one. This is not always good. So, the key (as you pointed out) to mixing TDD with top-down, is to use mock objects a lot. But, this is a good thing; it forces you to write classes which can be tested in isolation. This no only makes for better tested code, but often leads to cleaner design. Now, to drag this thread back to something apropos to Python, the good news is that Python makes it easy to work with mock objects. Often, all you need to do is "import myTestingFoo as Foo" and it all just works. Since functions and classes are first-class objects, it's easy to pass them around. Since Python uses duck typing, you don't have to make sure your test class inherets from anything in particular. It all just works. From __peter__ at web.de Thu Jan 17 12:40:30 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jan 2008 18:40:30 +0100 Subject: Interesting Thread Gotcha References: <5v6hj5F1k6gi5U1@mid.individual.net> Message-ID: Hendrik van Rooyen wrote: > "Bjoern Schliessmann" wrote: > > Hendrik van Rooyen wrote: >> Absolutely! - well spotted! > > This is no threading problem at all; not even a syntax problem. If > you don't know exactly what start_new_thread and kbd_driver > functions do it's impossible to tell if your code does what is > intended. > >> It would have been nice, however, to have gotten something like: >> >> TypeError - This routine needs a tuple. >> >> instead of the silent in line calling of the routine in question, >> while failing actually to start a new thread. > > Exactly which part of the code should give you this warning? > > I am obviously missing something. > > My understanding is that, to start a new thread, one does: > > NewThreadID = thread.start_new_thread(NameOfRoutineToStart, > (ArgumentToCall_it_with,secondArg,Etc)) > > This calls start_new_thread with the name and the arguments to pass. > > If one omits the comma, then start_new_thread is surely stilled called, > but with an argument that is now a call to the routine in question, which > somehow causes the problem. > > So start_new_thread is the code that that is executed, with a bad set of > arguments - one thing, (a call to a routine) instead of two things - > a routine and a tuple of arguments. > > Everywhere else in Python if you give a routine the incorrect number of > arguments, you get an exception. Why not here? Python always evaluates the function's arguments first. The check for the correct number of arguments is part of the call and therefore done afterwards: >>> def f(x): print x ... >>> f(f(1), f(2), f(3)) 1 2 3 Traceback (most recent call last): File "", line 1, in TypeError: f() takes exactly 1 argument (3 given) So if one of the arguments takes forever to calculate you will never see the TypeError: >>> def g(x): ... print x ... import time ... while 1: time.sleep(1) ... >>> f(f(1), g(2), f(3)) 1 2 Traceback (most recent call last): File "", line 1, in File "", line 4, in g KeyboardInterrupt # I hit Ctrl-C Peter From ggpolo at gmail.com Wed Jan 16 12:38:49 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 16 Jan 2008 15:38:49 -0200 Subject: paramiko In-Reply-To: <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> Message-ID: 2008/1/16, Tarun Kapoor : > # now, connect and use paramiko Transport to negotiate SSH2 across > the connection > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((hostname, port)) > > t = paramiko.Transport(sock) > t.start_client() > key = t.get_remote_server_key() > > event = threading.Event() > t.auth_password(username=username, password=password, event=event) > event.wait() > > if not t.is_authenticated(): > print "not authenticated" > > output: > not authenticated > This is a different problem I guess, now you are usin get_remote_server_key. And why are you creating event after calling start_client without specifying it ? > > > > On Jan 16, 11:11 am, "Guilherme Polo" wrote: > > 2008/1/16, Tarun Kapoor : > > > > > > > > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > > > the remote server using an SFTP client I have just to make sure that > > > username and password are working.. This is the code. > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > > > connection > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > > sock.connect((hostname, port)) > > > > > t = paramiko.Transport(sock) > > > > > event = threading.Event() > > > > > t.start_client(event) > > > > > event.wait(15) > > > > > if not t.is_active(): > > > > > print 'SSH negotiation failed.' > > > > > sys.exit(1) > > > > > else: > > > > > print "SSH negotiation sucessful" > > > > > event.clear() > > > > > t.auth_password(username=username, password=password,event=event) > > > > > if not t.is_authenticated(): > > > > > print "not authenticated" > > > > > output: > > > > > SSH negotiation successful > > > > > not authenticated > > > > > Tarun > > > > > Waterstone Capital Management > > > > > 2 Carlson Parkway, Suite 260 > > > > > Plymouth, MN 55447 > > > > > Direct: 952-697-4123 > > > > > Cell: 612-205-2587 > > > Disclaimer This e-mail and any attachments is confidential and intended > > > solely for the use of the individual(s) to whom it is addressed. Any views > > > or opinions presented are solely those of the author and do not necessarily > > > represent those of Waterstone Capital Management, L.P and affiliates. If you > > > are not the intended recipient, be advised that you have received this > > > e-mail in error and that any use, dissemination, printing, forwarding or > > > copying of this email is strictly prohibited. Please contact the sender if > > > you have received this e-mail in error. You should also be aware that > > > e-mails are susceptible to interference and you should not assume that the > > > contents of this e-mail originated from the sender above or that they have > > > been accurately reproduced in their original form. Waterstone Capital > > > Management, L.P. and affiliates accepts no responsibility for information, > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > > > please verify the authenticity with the sender. > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > > You are missing an event.wait() after t.auth_password. > > Also, why are you passing this magic value "15" to event.wait() ? That > > parameter is passed to class _Verbose to indicate if debug messages > > should be displayed or not, so typical values would be 0/1 or > > False/True. > > > > -- > > -- Guilherme H. Polo Goncalves > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From asmodai at in-nomine.org Tue Jan 8 07:25:00 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 8 Jan 2008 13:25:00 +0100 Subject: Look for a string on a file and get its line number In-Reply-To: <47836440$0$27202$9b4e6d93@newsspool1.arcor-online.net> References: <164e475c-285e-48a1-b415-9f9d05d1a186@s12g2000prg.googlegroups.com> <47836440$0$27202$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <20080108122500.GK75977@nexus.in-nomine.org> -On [20080108 12:59], Wildemar Wildenburger (lasses_weil at klapptsowieso.net) wrote: >Style note: >May I suggest enumerate (I find the explicit counting somewhat clunky) >and maybe turning it into a generator (I like generators): Sure, I still have a lot to discover myself with Python. I'll study your examples, thanks. :) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ A conclusion is simply the place where you got tired of thinking... From gagsl-py2 at yahoo.com.ar Mon Jan 21 14:08:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Jan 2008 17:08:46 -0200 Subject: problem with 'global' References: Message-ID: En Mon, 21 Jan 2008 11:44:54 -0200, Mel escribi?: > Duncan Booth wrote: >> >> The first sentence (which hasn't changed since 2.4) describing the >> global >> statement seems clear enough to me: "The global statement is a >> declaration >> which holds for the entire current code block." > > I don't think that would stop the OP from thinking the global > statement had to be executed. In the code example, it seems to have > been stuck in a > > if 1==2: global a > > and it still worked. The future statement is another example, even worse: if 0: from __future__ import with_statement with open("xxx") as f: print f All import statements are executable, only this special form is not. That "global" and "__future__" are directives and not executable statements, is confusing. -- Gabriel Genellina From sickcodemonkey at gmail.com Thu Jan 31 21:00:44 2008 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 31 Jan 2008 21:00:44 -0500 Subject: CDA conversion Message-ID: <2adc542f0801311800q3251acebta0494befa2be2470@mail.gmail.com> Good evening. I am trying to write an application in Python that will allow a person to insert a CD into their computer and this python script will convert the music to mp3. NOTE: I have already google'd this, and nothing really pops out at me. I found tons of applications that does this, but I am trying to write this myself (as a little project). Does anyone know a good site that I can find some pointers on getting started? The machine that this will run on is running Linux and has Python 2.5. Any help is greatly appreciated. ~~~~~~~~~~~~~~~~~ .dave Filize.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Jan 7 08:33:04 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 7 Jan 2008 14:33:04 +0100 Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: MartinRinehart wrote: > Anything written somewhere that's thorough? Any code body that should > serve as a reference? http://www.python.org/dev/peps/pep-0008/ From asmodai at in-nomine.org Mon Jan 7 04:00:35 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 7 Jan 2008 10:00:35 +0100 Subject: do - loop In-Reply-To: References: Message-ID: <20080107090035.GA82115@nexus.in-nomine.org> -On [20080107 09:51], Hita Vora (hvora at usc.edu) wrote: >I have a dataset which has about 3000 subjects in it. I take each subject >and perform 3 to 4 geoprocessing tasks on it. Currently I have a model where >I manually feed in each subject's ID and then the rest of the process is >automated. I would like to automate the process such that it would >automatically select another subject after the process has been completed on >a specfic subject. ie to repeat the same process on each of the IDs. Well, hopefully I understood you correctly, but if we assume that the dataset is a simple list you can iterate over it as thus: for subject in dataset: do_geoprocessing(subject) Dictionaries and other datatypes have similar means to construct an iterator. Is this a bit what you want to achieve? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Vae victis! From MartinRinehart at gmail.com Sat Jan 5 05:40:48 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Sat, 5 Jan 2008 02:40:48 -0800 (PST) Subject: Basic inheritance question References: Message-ID: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> Jeroen Ruigrok van der Werven wrote: > Shouldn't this be: > > self.startLoc = start > self.stopLoc = stop Thanks! Of course it should. Old Java habits die slowly. From cwitts at gmail.com Fri Jan 18 06:21:16 2008 From: cwitts at gmail.com (Chris) Date: Fri, 18 Jan 2008 03:21:16 -0800 (PST) Subject: Filtering two files with uncommon column References: <45b01339-250d-4693-95d6-73bb97d8e6d2@e4g2000hsg.googlegroups.com> <5084371c-dba0-4d11-be95-a01d1b439de6@s12g2000prg.googlegroups.com> Message-ID: <90f75e10-1f30-4c2b-8424-8e621366723f@e10g2000prf.googlegroups.com> On Jan 18, 12:08 pm, Madhur wrote: > On Jan 18, 2:37 pm, Chris wrote: > > > > > On Jan 18, 11:23 am, Madhur wrote: > > > > I would like to know the best way of generating filter of two files > > > based upon the following condition > > > > I have two files. Contents of the first file is > > > > File 1 > > > abc def hij > > > asd sss lmn > > > hig pqr mno > > > > File 2 > > > > jih def asd > > > poi iuu wer > > > wer pqr jjj > > > > I would like have the output as > > > Output > > > > File1 > > > asd sss lmn > > > File2 > > > poi iuu wer > > > > Basically I want to compare the two files based on second column. If > > > the second > > > column matches on both the files do not print anything, else if there > > > is no matc > > > h in for the second column for first file in second file then print it > > > under Fil > > > e1 header, else if there is no match for the second column for second > > > file in fi > > > rst file print it under File2 header. > > > > Thankyou > > > Madhur > > > file1 = open('file1.txt','rb') > > file2 = open('file2.txt','rb') > > > file1_line = file1.next() > > file2_line = file2.next() > > > while file1_line and file2_line: > > try: > > f1_col2 = file1_line.split(' ')[1] > > except IndexError: > > print 'Not enough delimiters in line.' > > try: > > f2_col2 = file2_line.split(' ')[2] > > except IndexError: > > print 'Not enough delimiters in line.' > > > if f1_col2 != f2_col2: > > outfile_data_to_relevant_files() > > > file1_line = file1.next() > > file2_line = file2.next() > > > HTH > > Chris > > If the files2 is unordered, then the above logic does not work. How to > takle it? Take a look at *nix's sort command, it can also sort based on a key From ajaksu at gmail.com Fri Jan 25 20:36:06 2008 From: ajaksu at gmail.com (ajaksu) Date: Fri, 25 Jan 2008 17:36:06 -0800 (PST) Subject: translating Python to Assembler References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> <13pdiaqsdicf9eb@corp.supernews.com> <5vosafF1nn9odU2@mid.individual.net> Message-ID: On Jan 25, 11:10 pm, o... at thepond.com wrote: > Once a python py file is compiled into a pyc file, I can disassemble > it into assembler. Assembler is nothing but codes, which are > combinations of 1's and 0's. You can't read a pyc file in a hex > editor, but you can read it in a disassembler. It doesn't make a lot > of sense to me right now, but if I was trying to trace through it with > a debugger, the debugger would disassemble it into assembler, not > python. Please, tell me you're kidding... From aahz at pythoncraft.com Thu Jan 31 11:18:21 2008 From: aahz at pythoncraft.com (Aahz) Date: Thu, 31 Jan 2008 08:18:21 -0800 Subject: DEADLINE Feb 4: OSCON 2008 Call for Proposals Message-ID: <20080131161821.GA4232@panix.com> The O'Reilly Open Source Convention (OSCON) is accepting proposals for tutorials and presentations. The submission period ends Feb 4. OSCON 2008 will be in Portland, Oregon July 21-25. For more information and to submit a proposal, see http://conferences.oreilly.com/oscon/ -- 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 workitharder at gmail.com Tue Jan 1 11:47:11 2008 From: workitharder at gmail.com (bukzor) Date: Tue, 1 Jan 2008 08:47:11 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <601e4a81-a69a-4576-a276-41d82a256482@e50g2000hsh.googlegroups.com> <13nganfbu52dnff@corp.supernews.com> <13nh4uvkq9cmo81@corp.supernews.com> Message-ID: <5db44c52-7900-463d-9e9d-053c439cb85a@d21g2000prf.googlegroups.com> On Dec 30 2007, 11:01 pm, Steven D'Aprano wrote: > On Sun, 30 Dec 2007 20:00:14 -0800, bukzor wrote: > > I think you struck at the heart of the matter earlier when you noted > > that this is the simplest way to declare a static variable in python. > > Using the 'global' keyword is the other way, and is much more explicit, > > and much more widely used. I also see this as the main use of the > > 'notlocal' keyword to be introduced in py3k (it also fixes the example > > given by Istvan above). > > There doesn't appear to be any reference to a "notlocal" keyword in > Python 3 that I can find. Have I missed something? It sounds like an > April Fool's gag to me. Do you have a reference to a PEP or other > official announcement? > > -- > Steven I got it slightly wrong. It's 'nonlocal': http://www.python.org/dev/peps/pep-3104/ --Buck From bj_666 at gmx.net Mon Jan 28 12:38:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Jan 2008 17:38:34 GMT Subject: optional static typing for Python References: <37e31514-fad2-4186-87f4-8cf5ed74299f@v17g2000hsa.googlegroups.com> <9aec1b73-79f5-467b-a544-889107caa3b2@q77g2000hsh.googlegroups.com> <479e0225$0$36389$742ec2ed@news.sonic.net> Message-ID: <606i8qF1p0rptU2@mid.uni-berlin.de> On Mon, 28 Jan 2008 08:31:43 -0800, John Nagle wrote: > Unenforced static typing is somewhat pointless. If that > goes in, it should be enforced by implementations. Luckily we don't get static typing. We get annotations which *can* be used for type hints, checked by additional code. Can be used for other things as well. Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Fri Jan 25 11:26:49 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Jan 2008 16:26:49 GMT Subject: is possible to get order of keyword parameters ? References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> Message-ID: <5vugu9F1oe0goU4@mid.uni-berlin.de> On Fri, 25 Jan 2008 05:49:40 -0800, rndblnch wrote: > def f(**kwargs): > > return result > > such as : > f(x=12, y=24) == ['x', 'y'] > f(y=24, x=12) == ['y', 'x'] > > what i need is to get the order of the keyword parameters inside the > function. > any hints ? Impossible. Dictionaries are unordered. Ciao, Marc 'BlackJack' Rintsch From rocco.rossi at gmail.com Sun Jan 6 17:59:57 2008 From: rocco.rossi at gmail.com (rocco.rossi at gmail.com) Date: Sun, 6 Jan 2008 14:59:57 -0800 (PST) Subject: Noob question Message-ID: <17e045f1-7891-4afc-a98b-42dffdc45dd4@41g2000hsy.googlegroups.com> Tinkering with Python I find myself often writing scripts and then experimenting with the interactive interpreter, which is really a cool way to learn a language. However, when, after loading a module with import or from module import * and using it, I make a change to the module file, the changes are not effective after re-importing that same module, and I have to exit the interpreter and restart all over. Isn't there some way to avoid this annoying process? Thank you. From dickinsm at gmail.com Mon Jan 21 11:14:31 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 21 Jan 2008 08:14:31 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: Message-ID: On Jan 21, 9:55?am, Jason wrote: > display. ?On windows, "float('nan')" will cause an exception, as there > are no valid string representations of NAN that can be converted to > the special floating point value. ?Also, if you manage to create a nan > under Windows, it displays as "1.#QNAN". I believe this will be fixed in Python 2.6 :) Mark From steve at holdenweb.com Thu Jan 31 19:38:29 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 Jan 2008 19:38:29 -0500 Subject: psycopg2 In-Reply-To: References: Message-ID: Andre' John wrote: > Hi > > I am trying to do this for a Postgresql database: > > conn = psycopg2.connect('host=localhost') > cur = conn.cursor() > cur.execute("SELECT * FROM names WHERE name=%s", ['S']) > > , which doesn't work, and neither does > > cur.execute("SELECT * FROM names WHERE name='%s'", ['S']) > > or > > cur.execute("SELECT * FROM names WHERE name='S'") > > work. I'm more inclined to believe the first two than the third, but I suppose if you are telling the truth (House: "Patients always lie") then I am guessing you have defined your table's "names" columns to be an array type. I haven't worked with those (since they don't confirm to the strict relational model I prefer to work with), but I am guessing you might try cur.execute("SELECT * FROM names WHERE name='%s'", (['S'], )) as this provides the necessary tuple as the second argument to execute, and the on;y element of the tuple is a list of a single element. > It always returns: > > Traceback (most recent call last): > > File "", line 1, in > > psycopg2.ProgrammingError: array value must start with ?{? or > dimension information > > > Though, when doing > > cur.execute("SELECT * FROM names") > > it works. > I am totally helpless here. Does anyone have an idea? > If my suggestion doesn't work, you should probably let us know more about the structure of your table. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bruno.desthuilliers at gmail.com Wed Jan 9 18:02:57 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 9 Jan 2008 15:02:57 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> Message-ID: <76bc64cc-541c-434f-aac5-96d1a2d231ee@c23g2000hsa.googlegroups.com> On 9 jan, 21:46, "dongie.ag... at gmail.com" wrote: > Thanks for the clarification. > > Though I was hoping someone could give me a definitive answer. Sorry - but I'm definitively not the right person on this... > I was > quite excited about this project initially, but seeing the actual > execute times was a big downer. Seeing that the original laser marker > by GRL Vienna is done in Processing which from what I know is built on > Java, I was hoping that Python would be up to a similar task. Java's declarative static typing allow agressive just-in-time optimizations - which is not the case in Python due to it's higly dynamic nature[1]. You may want to have a look at psyco (a JIT compiler) or to look for other angles (if there's any - IIRC the example you're talking about already uses at least PIL for image processing and something like scipy or numpy for intensive math ops). If none of the two above answers fits your needs, and no Python Guru comes with a better answer, then I'm afraid you'll have to go for a language with a faster implementation. Python is quite faster nowadays than it used to be, and is usually fast enough for most day-to-day programming tasks (a, but it's still not as highly optimized as some Lisp implementations (to compare to another highly [1] you can read more on this on the pypy website, and specially here IIRC: http://codespeak.net/pypy/dist/pypy/doc/dynamic-language-translation.html) From mgi820 at motorola.com Wed Jan 16 12:12:56 2008 From: mgi820 at motorola.com (Gary Duzan) Date: Wed, 16 Jan 2008 17:12:56 +0000 (UTC) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <60b75f24-d33a-476e-932d-11dfb9880562@v4g2000hsf.googlegroups.com> Message-ID: In article <60b75f24-d33a-476e-932d-11dfb9880562 at v4g2000hsf.googlegroups.com>, Paul Boddie wrote: > >I think the benefits of running Java on CPython are significantly less >than those had by running Python on the Java VM (or another VM). >Firstly, who wants to write statically typed code which then runs on a >virtual machine that can't take advantage of the type declarations? I know it was a rhetorical question, but I wanted to point out that this is exactly what happens with Java Generics. They didn't want to update the type system in the JVM, so all the generic types get thrown out by the compiler in favor of non-generic types, and casts are inserted as necessary. Practicality wins over Purity again. Gary Duzan Motorola HNM From gherron at islandtraining.com Mon Jan 21 18:36:19 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 21 Jan 2008 15:36:19 -0800 Subject: Max Long In-Reply-To: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> References: <3def6a2d-a182-4eb2-a85c-a2948192e7ed@e10g2000prf.googlegroups.com> Message-ID: <47952C73.6080907@islandtraining.com> tjhnson at gmail.com wrote: > How can I figure out the largest long available? I was hoping for > something like sys.maxint, but I didn't see it. Also, can someone > point me to where I can (concisely) read about size of such types > (int, float, long). > There is no explicit (defined) limit. The amount of available address space forms a practical limit. Gary Herron From workitharder at gmail.com Sun Jan 6 18:38:49 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 6 Jan 2008 15:38:49 -0800 (PST) Subject: how to use bool References: <05c5df8b-15c4-47e6-8c14-72c57a84a0ea@y5g2000hsf.googlegroups.com> <2c516040-0193-4de3-bf7d-b61e739cdc2d@l57g2000hsa.googlegroups.com> Message-ID: <5b9f8f01-8e3b-413b-827b-122f86ff8962@i29g2000prf.googlegroups.com> On Jan 6, 8:56 am, jimgarde... at gmail.com wrote: > some more doubts in this area,,forgive the ignorance of a beginner > > i have > > class MyError(Exception): > def __init__(self,msg) > self.msg=msg > > now my method that can raise this is > > class SomeClass: > ........... > def mymethod(self): > if (somecondition): > raise MyError("somecondn failed") > > if another method in the same class calls this method but wants to > pass the error to a gui code which calls it,,can i do like this > > def callingmethode(self): > try: > mymethod() > except MyError,myerr: > raise myerr > > so that I can handle the error in a gui code that calls > callingmethode() > > class MyGUI: > def guimethode(self): > someinst=SomeClass() > try: > someinst.callingmethode() > except MyError,myer: > self.dealwithMyError(myer) > > is this kind of raising exception the correct way?I am getting syntax > error at > except MyError,myerr: > raise myerr It's unnecessary to catch the exception and raise it again. The default action for an uncaught exception it to raise it higher. Also this class doesn't make much sense: > class MyError(Exception): > def __init__(self,msg) > self.msg=msg This doesn't call the super class's init function. You'd want to do something like this: > class MyError(Exception): > def __init__(self,msg) > self.msg=msg > Exception.___init__(self) Also, the first argument to the Exception constructor is a text message, so you could just do this: > class MyError(Exception): > def __init__(self,msg) > Exception.___init__(self, msg) This is exactly the default constructor, so you could write it this way: > class MyError(Exception): > pass or as a one-liner: > class MyError(Exception): pass When you want to access the message out of the exception, you can use 'e.message' or 'str(e)'. If you want to print the exception's message, just do 'print e'. Besides that, your code looks good. Might want to read the exceptions chapter of the documentation: http://docs.python.org/tut/node10.html --Bukzor From hniksic at xemacs.org Wed Jan 9 05:52:13 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 09 Jan 2008 11:52:13 +0100 Subject: "Canonical" way of deleting elements from lists References: <5ujkbaF1e11ksU1@mid.dfncis.de> <87ejcri96v.fsf@mulj.homelinux.net> Message-ID: <87abnfi84i.fsf@mulj.homelinux.net> Hrvoje Niksic writes: > If you're looking for a quick (no quadratic behavior) and convenient > way to do it, you can do it like this: > > keywords = [s for s in keywords if s != ''] It now occurred to me that a good compromise between convenience and efficiency that retains the same list is: keywords[:] = (s for s in keywords if s) From jd at commandprompt.com Mon Jan 7 14:21:01 2008 From: jd at commandprompt.com (jd at commandprompt.com) Date: Mon, 7 Jan 2008 11:21:01 -0800 (PST) Subject: PostgreSQL Conference East: Call for Papers Message-ID: <407c0907-4584-42d0-a717-843860120083@d70g2000hsb.googlegroups.com> PostgreSQL Conference East is being held on the weekend of March 29th and 30th, 2008 in College Park, Maryland. The conference will have a series of talks, mini-tutorials and tutorials and we are now accepting submissions! If you are a third pary vendor, PostgreSQL developer, PostgreSQL consultant, DBA, or just a user who really does cool stuff, you need to submit a talk, or tutorial. Do you know how to get that last 20 transactions per second out of an array using adaptive readahead? Maybe you know more about Autovacuum than you ever care to admit? Perhaps, you have recently deployed PostgreSQL and saved a company 300k over the next closest competitor... Now is your time to share, learn and participate in the community! Submit your talk at: http://www.postgresqlconference.org/talk_submission/ . PostgreSQL Conference East is part of the PostgreSQL Community Conference series. All proceeds from the conferences are donations to PostgreSQL via the non-profit Software in the Public Interest a U.S. 501c3. Sincerely, Joshua D. Drake From brad at 16systems.com Sat Jan 19 16:54:07 2008 From: brad at 16systems.com (Brad) Date: Sat, 19 Jan 2008 16:54:07 -0500 Subject: Python 3000 and import __hello__ Message-ID: Just playing around with Python3000 a2 release on Windows XP 32-bit x86. import __hello__ doesn't print 'hello world...' as it does on 2.5 The import doesn't fail or generate errors... just no output. Perhaps this is by design? Brad From donn.ingle at gmail.com Fri Jan 25 09:42:21 2008 From: donn.ingle at gmail.com (Donn Ingle) Date: Fri, 25 Jan 2008 16:42:21 +0200 Subject: piping into a python script References: <5vrovvF1njt09U6@mid.uni-berlin.de> Message-ID: Nick Craig-Wood wrote: > This iterates over the lines of all files listed in sys.argv[1:], > defaulting to sys.stdin if the list is empty. If a filename is '-', it > is also replaced by sys.stdin. To specify an alternative list of > filenames, pass it as the first argument to input(). A single file > name is also allowed. Yeah it has been discussed. It seems the one problem with it is that it opens each file. I only want the filenames. Anyway, this has more-or-less been solved now. Thanks, \d From hat at se-162.se.wtb.tue.nl Thu Jan 24 09:51:55 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 24 Jan 2008 15:51:55 +0100 Subject: Test driven development References: <7b0188a3-f6f6-483c-8f41-2dd9b9522268@v67g2000hse.googlegroups.com> Message-ID: On 2008-01-24, ajcppmod at gmail.com wrote: > I like the concept of TDD but find it difficult to put into practice > most of the time. I think this primarily because I tend to like top- > down development and functional/object decomposition and TDD feels > more like a bottom-up approach. It is not bottom-up imho. The main difference imho is in abstract, far-away goals versus running code for a small concrete sub-set of functionality in the short-term. How you provide that "running code for a small concrete sub-set of functionality in the short-term" is not defined by the approach. > So my question is when approaching a project that you want to employ > test driven development on how and where do you start? And also if 1. Define a small step of extended functionality that you can finish by the end of the week. 2. Write tests that should run after implementing the functionality. 3. Write code that make the tests work. 4. goto 1. > anyone uses top-down design with TDD I would be interested in how you > do it (does it involve lots of mock objects/ is the first test you > write the last one to pass)? No, with TTD there is only one goal, namely increasing the percentage of passed tests to 100%. (which you then break again by doing steps 1 and 2, and fix again in step 3) TTD is about DESIGNing for WHAT YOU NEED TODAY, not for what you might need tomorrow. You may want to do a small top-down design (and next week another slightly larger one, and another slightly larger one in 2 weeks, etc), but you should NOT DESIGN FOR MORE FUNCTIONALITY THAN WHAT YOU NEED for all tests to pass. Sincerely, Albert PS The above is purely from a TTD perspective. I personally do not really think you can SOLVE ALL PROBLEMS in the most efficient way using TTD. On the other hand, the concrete, short-term approach does produce running code fast for the implemented sub-set of functionality, which may be nice in a project. From gagsl-py2 at yahoo.com.ar Tue Jan 29 15:07:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jan 2008 18:07:01 -0200 Subject: runscript module, where are the docs... References: <1fbdde0d-ae09-4b6a-8f08-0713de94cc0b@j78g2000hsd.googlegroups.com> Message-ID: En Tue, 29 Jan 2008 13:48:58 -0200, glomde escribi?: > I am going through some code and found > import runscript > > BUT I cant find and information about this module. I searched Google > did a grep in > the /usr/lib/python directory. > > What is the purpose of this module and where can I find information > about it. Or the source. It doesn't appear to be a standard module, look around the place where you found it. -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jan 31 17:09:55 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 31 Jan 2008 23:09:55 +0100 Subject: Naive idiom questions References: Message-ID: <60ev9jF1qdpctU1@mid.individual.net> Terran Melconian wrote: > * Why are there no real mutable strings available? > > I found MutableString in UserString, but further research > indicates that it is horribly inefficient and actually just > wraps immutable strings for the implementation. Did you measure such impact on your application? Also see http://www.skymind.com/~ocrow/python_string/ > I want to be able to accumulate a string with +=, not by going > through an intermediate list and then doing ''.join(), because > I think the latter is ugly. >>> yummy = "ham" >>> yummy += "eggs" >>> yummy 'hameggs' > There are also times when I'd like to use the string as a > modifiable buffer. Use a list instead. When done with modifications you may concatenate its contents to a string using "".join(my_list). > * What's the best way to initialize a list of lists? > [...] > l=[[None]*5 for i in range(5)] > > I don't particularly like it, though. It bothers me to have > to explain list comprehensions, which are a moderately > advanced feature conceptually, just to initialize an array. Look at "lower level" HLLs. In C++, you'd have to use int my_array[5][5]; for (int i=0; i<5; ++i) for (int j=0; j<5; j++) my_array[i][j] = -1; Personally, I like list comprehensions much better. Regards, Bj?rn -- BOFH excuse #254: Interference from lunar radiation From bj_666 at gmx.net Wed Jan 30 17:03:52 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jan 2008 22:03:52 GMT Subject: Removing Pubic Hair Methods References: <479f7759$0$25985$88260bb3@free.teranews.com> <60b9e7F1ps52dU4@mid.uni-berlin.de> <47a089d9$0$5950$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <60cai8F1qgh3aU1@mid.uni-berlin.de> On Wed, 30 Jan 2008 15:29:45 +0100, Wildemar Wildenburger wrote: > Gerardo Herzig wrote: >> I will use genital().extend(), thats for shure ^^ > > Well, you never go wrong with apply(genital(), females), do you? `apply()` is deprecated. And ``genital(*females)`` looks a bit odd. :-) Ciao, Marc 'BlackJack' Rintsch From yantao at telus.com Sun Jan 27 00:37:48 2008 From: yantao at telus.com (Peter Pei) Date: Sun, 27 Jan 2008 05:37:48 GMT Subject: how to make format operator % work with unicode as expected In-Reply-To: References: <13po55nc0q0s06@corp.supernews.com> Message-ID: I just sorted posts by from, and figured out that you are kind of PSF guy... However that does not make you qualified, I care whether you are capable not whether you have the time to spend for PSF. Adios! ========================================== "Peter Pei" wrote in message news:YHUmj.43649$fj2.28192 at edtnps82... > You didn't understand my question, but thanks any way. > > Yes, it is true that %s already support unicode, and I did not contradict > that. But it counts the number of bytes instead of characters, and makes > things like %-20s out of alignment. If you don't understand my assertion, > please don't argue back and I am only interested in answers from those who > are qualified. > ============================================================== > > "Steven D'Aprano" wrote in message > news:13po55nc0q0s06 at corp.supernews.com... >> On Sun, 27 Jan 2008 04:06:45 +0000, Peter Pei wrote: >> >>> I probably should mention that what I want is to make all parts of the >>> string aligned, and look like table. I am not looking for other ways to >>> make it table-alike, but only interested in making % work with unicode >>> -counting characters not bytes... >> >> % already works with unicode. Just give it unicode arguments: >> >> >>>>> print u"x y z %s 1 2 3" % u"Les mis?rables" >> x y z Les mis?rables 1 2 3 >> >> >> -- >> Steven > From deets at nospam.web.de Mon Jan 28 16:35:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jan 2008 22:35:52 +0100 Subject: PYS file In-Reply-To: References: Message-ID: <60705vF1pl66cU1@mid.uni-berlin.de> Gabriel Genellina schrieb: > On 28 ene, 13:05, azrael wrote: > >> A I Understood correctly, pyc files are compiled py scripts. Is it >> possible to decomplite them. >> I guess it's possible, but how hard is it. > > You want to get back the Python source? Look for the "decompyle" > package. The last published release works for version 2.3; there is a > paid service for newer versions (you send the .pyc, they give back > the .py) > > At least you may use the dis module to disassemble the compiled .pyc > into the correspoding VM instructions - if you are happy reading > that... From other posts of the OP I'd rather think that he's after copy/IP-protection. So the answer is: if your code contains algorithms worth stealing (which in 99.99% isn't the case, objectively) or the program as whole is worth being hacked because of public interest combined with high prices (SPSS, photoshop), IT WILL BE. Even if it has been under-water-mouth-coded in assembler. Diez From bj_666 at gmx.net Wed Jan 23 14:04:38 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Jan 2008 19:04:38 GMT Subject: Stripping whitespace References: <9d7fb924-08b2-410a-a792-4ec10c46955d@d70g2000hsb.googlegroups.com> Message-ID: <5vphe6F1njt09U1@mid.uni-berlin.de> On Wed, 23 Jan 2008 10:50:02 -0800, ryan k wrote: > Hello. I have a string like 'LNAME > PASTA ZONE'. I want to create a list of those words and > basically replace all the whitespace between them with one space so i > could just do lala.split(). Thank you! You *can* just do ``lala.split()``: In [97]: lala = 'LNAME PASTA ZONE' In [98]: lala.split() Out[98]: ['LNAME', 'PASTA', 'ZONE'] Ciao, Marc 'BlackJack' Rintsch From attn.steven.kuo at gmail.com Thu Jan 31 17:58:42 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 31 Jan 2008 14:58:42 -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> Message-ID: On Jan 31, 2:48 pm, "attn.steven.... at gmail.com" wrote: > On Jan 31, 8:12 am, erikcw wrote: > > One way would be to use sets and check for intersection: > > for idx, s in enumerate(mysets): > for next_idx, next_s in enumerate(mysets[idx+1:]): > if s.intersection(next_s): > print "mylist[%d] and mylist[%d] intersect" % ( > idx, idx + next_idx + 1 ) > Um, that would have been more helpful if I hadn't forgotten to preface that with: mylist = [(55, 58, 52), (20, 22, 18), (17, 21, 13), (60, 63, 57),] mysets = [set(range(x[2],x[1])) for x in mylist] -- Cheers, Steven From cokofreedom at gmail.com Tue Jan 15 05:50:17 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 15 Jan 2008 02:50:17 -0800 (PST) Subject: common problem - elegant solution sought References: <5v3gg1F1kkla5U1@mid.dfncis.de> Message-ID: <5fcec3dc-f223-4617-acad-69d33e225c23@f47g2000hsd.googlegroups.com> > I have a list of tuples (Unique_ID,Date) both of which are strings. > I want to delete the tuple (element) with a given Unique_ID, but > I don't known the corresponding Date. > > My straight forward solution is a bit lengthy, e.g. > > L=[("a","070501"),("b","080115"),("c","071231")] Do they have to be tuples? Seems to me if you are using a Unique_ID that a dictionary would be perfect. Indeed when you are looking to delete an entry you can simply look for the Unique_ID in the dictionary and it will be a very fast look up. if key in "my_dictionary": However, if you must use a list of tuples, your current method is very inefficient. Why not use the del within the if Key == "b":? I cannot provide extremely elegant solutions with your current system, but I can tell you with a large enough list your way is going to take a very long time since you will iterate over the whole list sequentially to find an entry... From mikez302 at gmail.com Sat Jan 12 14:21:39 2008 From: mikez302 at gmail.com (mikez302) Date: Sat, 12 Jan 2008 11:21:39 -0800 (PST) Subject: IDLE won't start in Python 2.5 for Windows References: <5eab7ca5-f3b9-4559-acf7-b3d6d69067ad@z17g2000hsg.googlegroups.com> <13ogqhlds0tbsac@corp.supernews.com> Message-ID: <57a7e4a2-0acc-4439-9bd6-d96862ffc22e@j78g2000hsd.googlegroups.com> I opened a command window in my Python25 folder and tried typing pythonw. I just got another command prompt as if the program ran but didn't do anything. It looked like this: C:\Python25>pythonw C:\Python25> From arnodel at googlemail.com Sat Jan 19 07:07:58 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 19 Jan 2008 04:07:58 -0800 (PST) Subject: Is this a bug, or is it me? References: Message-ID: <150b3c8f-56cb-4759-b674-ed07abeda450@e6g2000prf.googlegroups.com> On Jan 17, 3:55?pm, Peter Otten <__pete... at web.de> wrote: > Here is a simpler example: > > >>> class A: > > ... ? ? a = 42 > ... ? ? list(a for _ in "a") > ... > Traceback (most recent call last): > ? File "", line 1, in > ? File "", line 3, in A > ? File "", line 3, in > NameError: global name 'a' is not defined [...] > So it seems that Python gets puzzled by the extra scope introduced by the > genexp, i. e. you are seeing an obscure variant of the following > (expected) behaviour: > > >>> class B: > > ... ? ? a = 42 > ... ? ? def f(): a > ... ? ? f() > ... > Traceback (most recent call last): > ? File "", line 1, in > ? File "", line 4, in B > ? File "", line 3, in f > NameError: global name 'a' is not defined This is exactly the problem: class A: a = 42 list(a for _ in "a") is in fact compiled as: class A: a = 42 def _genexpr(): for _ in "a": yield a list(_genexpr()) Except that the _genexpr function is not bound to any name, just left on the stack for list to pick up next. This can be checked using the dis module. Trying it yields exactly the same error: >>> class A(object): ... a = 42 ... def _genexpr(): ... for _ in "a": ... yield a ... list(_genexpr()) ... Traceback (most recent call last): File "", line 1, in File "", line 6, in A File "", line 5, in _genexpr NameError: global name 'a' is not defined > I think you should file a bug report, though making the genexp recognizing > the class scope probably isn't worth the effort. It isn't necessary to do that to fix the problem. I think that the semantics of genexprs concerning free variables are confusing (and this is a good example!). I suggested a change on python-ideas a while ago that would solve this particular issue. In short, all free variables inside a generator expression could be bound at the creation of the expression, not when it is evaluated. So for example ((c, f(x)) for x in L) would be the equivalent of what one could currently write as. (lambda _c, _f: ((c, f(x) for x in L))(c, f) so your example would compile to: class A: a = 42 def _genexpr(_a): for _ in "a": yield _a list(_genexpr(a)) Which would behave as the OP expected (and I think as it is reasonable to expect if one doesn't know about how genexprs are implemented). Other reasons why I think this is desirable are exposed (maybe not very convincingly) in this post to python-ideas. http://mail.python.org/pipermail/python-ideas/2007-December/001260.html -- Arnaud From morse at edoug.org Wed Jan 9 15:48:13 2008 From: morse at edoug.org (Doug Morse) Date: Wed, 9 Jan 2008 20:48:13 +0000 (UTC) Subject: ISO books of official Python docs References: Message-ID: Several of the O'Reilly & Assoc. books -- such as Python in a Nutshell, The Python Standard Library, etc -- are in large part reproductions of the official docs and references. So, while not exactly what you asked for, the ORA books might be a viable alternative if what you want isn't available. On Wed, 9 Jan 2008 19:55:10 +0000 (UTC), kj wrote: > > > > Is it possible to buy the official Python docs in book form? If > so, I'd very much appreciate the name(s) and author(s) of the > book(s). > > TIA! > > kynnjo From aahz at pythoncraft.com Sat Jan 12 23:58:21 2008 From: aahz at pythoncraft.com (Aahz) Date: Sat, 12 Jan 2008 20:58:21 -0800 Subject: OSCON 2008 Call for Proposals Message-ID: <20080113045821.GA4328@panix.com> The O'Reilly Open Source Convention (OSCON) is accepting proposals for tutorials and presentations. The submission period ends Feb 4. OSCON 2008 will be in Portland, Oregon July 21-25. For more information and to submit a proposal, see http://conferences.oreilly.com/oscon/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jan 22 04:30:59 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 22 Jan 2008 10:30:59 +0100 Subject: Bug in __init__? In-Reply-To: References: Message-ID: <4795b788$0$11545$426a34cc@news.free.fr> Bart Ogryczak a ?crit : > On 2008-01-18, citizen Zbigniew Braniecki testified: (snip usual default mutable list arg problem) >> class A(): >> >> def add (self, el): >> self.lst.extend(el) >> >> def __init__ (self, val=[]): >> print val >> self.lst = val > > What you want probably is: > def __init__ (self, val=None): > if(val == None): Better to use an identity test here - there's only one instance of the None object, and identity test is faster than equality test (one function call faster IIRC !-). Also, the parens are totallu useless. if val is None: > self.lst = [] > else: > from copy import copy > ### see also deepcopy > self.lst = copy(val) What makes you think the OP wants a copy ? From steven at REMOVE.THIS.cybersource.com.au Sun Jan 6 22:57:52 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 Jan 2008 03:57:52 -0000 Subject: Delete lines containing a specific word References: <13o2tapcc2d066e@corp.supernews.com> Message-ID: On Mon, 07 Jan 2008 00:42:01 +0000, Grant Edwards wrote: >> If you want to delete them, you still have to do the rest of the job >> yourself. > > Nonsense. > > How is this not doing what the OP asks? > > grep -v pattern infile >outfile; mv outfile infile It isn't deleting lines. As abstractions go, it comes pretty close, but just try it on a disk with insufficient free space for the temporary outfile and watch it break. -- Steven From barry.zhao at gmail.com Thu Jan 10 15:38:50 2008 From: barry.zhao at gmail.com (barry.zhao at gmail.com) Date: Thu, 10 Jan 2008 12:38:50 -0800 (PST) Subject: open excel file while it is being used. Message-ID: Hi, I have a python program that constantly updates an excel spreadsheet. I would like to be able to view its updates while using excel to edit other excel files. Below are the test codes I have: -------------------------------------------------------------------------------------- from time import sleep import win32com.client as w32c def test(): w32c.pythoncom.CoInitialize() print w32c.pythoncom._GetInterfaceCount() app1 = w32c.Dispatch("Excel.Application") #app1.Visible=False #app1.Interactive = False wb=app1.Workbooks.Open("c:\\temp\\Book1.xls") sleep(3) sh=wb.Sheets("Sheet1") sh.Cells(2,1).Value = "Hello, world!" sh = None wb.Save() wb = None app1 = None w32c.pythoncom.CoUninitialize() print w32c.pythoncom._GetInterfaceCount() ------------------------------------------------------------------------------------- If the user just looks at the file then it's fine, but if the user double clicks one cell, which will have a cursor flashing in the cell, then it will lead to a crash of the program with error: "Call was rejected by callee." I can make the program keep trying to access the file, but if the user doesn't make the flashing cursor disappear, the program will wait forever! I know excel has the fuction such that when a user is accessing a file and other users open that file, it will prompt for options of opening it as read-only or sending notification. I have been trying to implement that in the program, but don't know how. So, any suggestion will be greatly appreciated! - Barry From magicalnepal at gmail.com Thu Jan 17 00:07:45 2008 From: magicalnepal at gmail.com (magicalnepal at gmail.com) Date: Wed, 16 Jan 2008 21:07:45 -0800 (PST) Subject: Thinking of your next holiday Message-ID: <52a96c2d-6d99-4635-8d3f-781ed1ef6445@s12g2000prg.googlegroups.com> Are you planning for vacation, holiday? We would like you to spare your valuable time! Visit our website www.magical-nepal.com for information on Nepal, Tibet and Bhutan. Thanking you in advance visiting and look forward to assist you. Regards, Rath Nepal Tours and Travels P O Box 10691, 2nd Floor Mountain Plaza Tel: 977-1-4268948, 4258141, 4264512 Fax: 977-1-4264512 E-mail: sales at magical-nepal.com website: www.magical-nepal.com From bdesth.quelquechose at free.quelquepart.fr Sun Jan 6 14:46:21 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 06 Jan 2008 20:46:21 +0100 Subject: Basic inheritance question In-Reply-To: <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> References: <7f7930b0-2b67-46df-97c5-b08db4d4071e@e6g2000prf.googlegroups.com> <8e0118eb-4ae6-4231-bc15-5e339697dad7@v4g2000hsf.googlegroups.com> Message-ID: <4781300a$0$17701$426a74cc@news.free.fr> Lie a ?crit : > On Jan 5, 5:40 pm, MartinRineh... at gmail.com wrote: > >>Jeroen Ruigrok van der Werven wrote: >> >> >>>Shouldn't this be: >> >>>self.startLoc = start >>>self.stopLoc = stop >> >>Thanks! Of course it should. Old Java habits die slowly. > > > No, seriously it isn't Java habits only, most other languages wouldn't > need explicit calling of class name. Where is the "explicit calling of class name" exactly ? From steven at REMOVE.THIS.cybersource.com.au Thu Jan 3 21:47:06 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 04 Jan 2008 02:47:06 -0000 Subject: dictionary/hash and '1' versus 1 References: Message-ID: On Thu, 03 Jan 2008 16:56:00 -0600, Reedick, Andrew wrote: > The problem occurred because a method used to generate keys was > returning a string instead of a number without an explicit conversion > taking place. And since I was using hash.get(i, default_value) to avoid > having to pair every key lookup with a hash.has_key(), no exception was > thrown when the key wasn't found. # How to fix this broken function without modifying the source? def foo(arg): """Returns a string instead of a number.""" return "1" # oops I meant 1 _foo = foo # save a reference to original broken function foo = lambda *args, **kwargs: int(_foo(*args, **kwargs)) # and patch it And now you can use foo(arg) confident that it will always return an int like you expect. Modifications of this technique should be obvious. -- Steven From caca at mailinator.com Sat Jan 5 05:16:19 2008 From: caca at mailinator.com (caca at mailinator.com) Date: Sat, 5 Jan 2008 02:16:19 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> <33417662-8246-4950-9b86-265aa1c63c69@c23g2000hsa.googlegroups.com> Message-ID: > Caching might help. > > If random_pick is called several times with the same list(s) then > cache the result of > [property(i) for i in a_list] against a_list. > > If random_pick is called several times with list(s) with multiple > instances of list items then cache > property(i) against i for i in a_list . > > You could do both. > > You might investigate wether property(i) could be implemented using a > faster algorithm, maybe table lookup, or interpolation from initial > table lookup. > > - Paddy. Thanks, Paddy. Those are interesting general comments for the general problem. By the way, I noticed two things: I forgot to write randint in the third approach: > > a=globalRNG.randint(1,len(a_list)) The warning "The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet." means a person, but not a bot, may see my email address, so it is safe to use my real address next time... From henry.baxter at gmail.com Sat Jan 12 03:49:40 2008 From: henry.baxter at gmail.com (Henry Baxter) Date: Sat, 12 Jan 2008 00:49:40 -0800 Subject: ctypes, GetWindowLongPtr In-Reply-To: References: <8d04436f0801111814p31b3a98brd9fb5eed48860505@mail.gmail.com> Message-ID: <8d04436f0801120049q2f19536cpddbeabb1cfd15d8f@mail.gmail.com> David, Quick reply :) That pointed me in the right direction. The documentation I was reading indicated the use of GetWindowLongPtr, but at compile time (if one were writing C/C++ code) which particular version (Long/64, or 32 bit) is chosen. That's where I was getting mixed up - thanks! Henry On Jan 11, 2008 9:33 PM, David Wahler wrote: > On Jan 11, 2008 9:14 PM, Henry Baxter wrote: > > Hello, > > > > I have been happily using ctypes for a while to do win32 programming. I > use the Microsoft documentation to understand the function, then call it > with the help of ctypes. > > > > The problem is that the docs says user32.dll has GetWindowLongPtr, but > ctypes can't find it using windll.user32.GetWindowLongPtrA or > windll.user32.GetWindowLongPtrW or windll.user32.GetWindowLongPtr. Errors > look like this: > > > > Traceback (most recent call last): > > File "Z:\experiments\windowsapp3.py", line 106, in > > GetWindowLongPtr = windll.user32.GetWindowLongPtrA > > File "C:\Python25\lib\ctypes\__init__.py", line 353, in __getattr__ > > func = self.__getitem__(name) > > File "C:\Python25\lib\ctypes\__init__.py", line 358, in __getitem__ > > func = self._FuncPtr((name_or_ordinal, self)) > > AttributeError: function 'GetWindowLongPtrA' not found > > > > I have the same problem with the SetWindowLongPtr function. > > > > I can use plenty of other functions (GetParent, CreateWindowExA, > DefWindowProcA, and etc) but not these ones. > > > > > > I don't understand what goes on with ctypes under the hood really, so my > troubleshooting abilities at this point are quite lacking! I would > appreciate any help you could offer. > > > > > > Thanks! > > I don't have a copy of the official Win32 headers handy, but the MinGW > version of winuser.h contains this section of code: > > WINUSERAPI LONG WINAPI GetWindowLongA(HWND,int); > WINUSERAPI LONG WINAPI GetWindowLongW(HWND,int); > #ifdef _WIN64 > WINUSERAPI LONG_PTR WINAPI GetWindowLongPtrA(HWND,int); > WINUSERAPI LONG_PTR WINAPI GetWindowLongPtrW(HWND,int); > #else > #define GetWindowLongPtrA GetWindowLongA > #define GetWindowLongPtrW GetWindowLongW > #endif > > which I would take to mean you need to use GetWindowLong on 32-bit > windows, and GetWindowLongPtr on 64-bit windows. > > -- David > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Mon Jan 28 09:36:15 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 28 Jan 2008 06:36:15 -0800 (PST) Subject: wx.EVT_RIGHT_UP strangeness? References: Message-ID: <03340347-329f-493c-8027-1736b38e589a@s12g2000prg.googlegroups.com> On Jan 26, 1:30 pm, sigpo... at hotmail.com wrote: > I am playing with wxPython 2.8.7.1 on OS X 10.4.11 with MacPython 2.5 > > When running the demo program, the ShapeWindow demo does not close the > window > on right click. It turns out that the wx.EVT_RIGHT_UP does not fire. > > I discovered that one way to get it to fire is to bind the > wx.EVT_RIGHT_DOWN event also. > > Thus adding the following two lines solves the problem: > > in __init__ add: self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) > > secondly add: def OnRightDown(self, evt): pass > > Everything then works ok. > > My question is: Is this how it is supposed to work, and if not, am I > the only one with > this problem? It works for me without any changes. I right-click the snake image and it disappears. I'm on Windows XP, Python 2.4/2.5 with wxPython 2.8.7.1 What OS and wxPython version are you using? You may want to post to the wxPython user's group too. They can tell you if it is an OS dependent bug or not: http://wxpython.org/maillist.php Mike From boblatest at yahoo.com Tue Jan 22 04:56:55 2008 From: boblatest at yahoo.com (Robert Latest) Date: 22 Jan 2008 09:56:55 GMT Subject: Question on sort() key function References: <5vlopgF1mv4ekU1@mid.dfncis.de> <7xve5mfdmr.fsf@ruckus.brouhaha.com> <5vlqbjF1kl9cjU1@mid.dfncis.de> Message-ID: <5vlsv7F1n3d1bU1@mid.dfncis.de> Peter Otten wrote: > Robert Latest wrote: > >> Paul Rubin wrote: >>> The attribute is on instances of File, not on the class itself. See >>> if this works: >>> >>> flist.sort(key=lambda f: f.mod_date.toordinal) >> >> It doesn't throw an error any more, but neither does it sort the list. This, >> however, works: >> >> ---------------------- >> def by_date(f1, f2): >> return f1.mod_date.toordinal() - f2.mod_date.toordinal() >> >> flist.sort(by_date) >> ---------------------- >> >> So I'm sticking with it, although I sort of liked the key approach. >> >> robert > > This should work then: > > def date_key(f): > return f.mod_date.toordinal() > flist.sort(key=date_key) > > This can also be written as > > flist.sort(key=lambda f: f.mod_date.toordinal()) Well, that's almost Paul's (non-working) suggestion above, but it works because of the parentheses after toordinal. Beats me how both versions can be valid, anyway. To me it's all greek. I grew up with C function pointers, and they always work. robert From jeffober at gmail.com Thu Jan 17 14:26:53 2008 From: jeffober at gmail.com (Jeff) Date: Thu, 17 Jan 2008 11:26:53 -0800 (PST) Subject: how django discovers changed sources References: <18udndZmKMfMNhLanZ2dnUVZ_rzinZ2d@comcast.com> Message-ID: That is the behavior of the development server. When you are writing your application, you don't want to have to manually restart the server every time you change a file. On apache it obviously doesn't do that. From bperry.volatile at gmail.com Wed Jan 16 08:37:27 2008 From: bperry.volatile at gmail.com (Brandon Perry) Date: Wed, 16 Jan 2008 07:37:27 -0600 Subject: Unknown cause to error (new to python) Message-ID: <1200490647.5903.3.camel@bperry-laptop> Hi, I am having to compile a standalone version of python for the web server I use (they don't allow access to /usr/bin/python). I posted earlier about a GLib error, but I have fixed that now. I am very close to getting this to work, but I am getting some weird errors. File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", line 41, in ? File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", line 71, in ? File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", line 4, in ? File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", line 4, in ? File "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", line 15, in ? I am using 2.2 for compatibility purposes. Thanks, Brandon From jr9445 at ATT.COM Fri Jan 11 16:28:50 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 11 Jan 2008 15:28:50 -0600 Subject: Newbie question on Classes In-Reply-To: <2a7ff558-a688-4b6f-ba05-126d7b533cac@e10g2000prf.googlegroups.com> References: <25e4147e0801101346m61895072x22b8c44746ed0b44@mail.gmail.com> <2a7ff558-a688-4b6f-ba05-126d7b533cac@e10g2000prf.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 John Machin > Sent: Friday, January 11, 2008 4:08 PM > To: python-list at python.org > Subject: Re: Newbie question on Classes > > On Jan 11, 9:27 am, "Reedick, Andrew" wrote: > > > -----Original Message----- > > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > > list-bounces+jr9445=att.... at python.org] On Behalf Of Adrian Wood > > > Sent: Thursday, January 10, 2008 4:47 PM > > > To: python-l... at python.org > > > Subject: Newbie question on Classes > > > > > > How about searching the garbage collector? > > Not a good idea, because gc is an implementation artifact and in fact > is specific to the C Python implementation; you won't find it in e.g. > Iron Python or Jython. > a) I forgot the ';-)' and/or tag. b) It was junk code. A cleaner loop would be (which I figured out 5 minutes after posting =P ): for i in gc.get_objects(): if isinstance(i, Person): print i.__class__, "%x" % id(i), i.SomeMethod() c) It's good to know about GC being CPython only. d) You forgot to mention the problem that some of the objects could be 'deleted' but not garbage collected yet. e) Most importantly, anyone who is using the garbage collector as their object manager isn't into proper coding practices in the first place. From mark.e.tolonen at mailinator.com Sun Jan 13 13:51:59 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Sun, 13 Jan 2008 10:51:59 -0800 Subject: Exceptions - How do you make it work like built-in exceptions? References: <7888e20f-0775-46c4-a6e2-3fc3825c5145@e23g2000prf.googlegroups.com> Message-ID: "Lie" wrote in message news:7888e20f-0775-46c4-a6e2-3fc3825c5145 at e23g2000prf.googlegroups.com... >A built-in exceptions, when raised, would print traceback that points > out the offending code, like this: > > Traceback (most recent call last): > File "F:\dir\code.py", line 43, in > a = 1/0 <<<--- > ZeroDivisionError: integer division or modulo by zero > > a user-made exception, when raised, would print traceback that points > out the code that raises the exception > > Traceback (most recent call last): > File "F:\dir\code.py", line 48, in > raise SomeException('Some Exception Message') <<<--- > SomeException: Some Exception Message > > which is generally of little use (yeah, it's possible to trace the > code from the line number, but sometimes it might not be that easy, > cause the line number is (again) the line number for the raising code > instead of the offending code) > > The sample exception was generated from this code: > #### > class SomeException(Exception): > pass > > try: > a = 1/0 > except: > raise SomeException('Some Exception Message') > #### > > Is it possible to make the user-made exception points out the > offending code? The raise statement *was* the offending (unhandled exception) code. The ZeroDivisionError was handled by your except clause. You can override the traceback your exception will use with the three-expression form of the raise statement (See Section 6.9 "The raise statement" in the Python Reference Manual) by passing the traceback of the original exception: ###### CODE ##### import sys class SomeException(Exception): pass try: a=1/0 except: org_type,org_value,org_traceback = sys.exc_info() raise SomeException,'had some problems with this code',org_traceback ###### OUTPUT ###### Traceback (most recent call last): File "exc.py", line 7, in a=1/0 SomeException: had some problems with this code --Mark From sgeiger at ncee.net Thu Jan 10 22:36:31 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Thu, 10 Jan 2008 21:36:31 -0600 Subject: getting n items at a time from a generator In-Reply-To: <7x7iihcbsg.fsf@ruckus.brouhaha.com> References: <7x7iihcbsg.fsf@ruckus.brouhaha.com> Message-ID: <4786E43F.2000402@ncee.net> Paul Rubin wrote: > Tim Roberts writes: > >> I have to say that I have found this to be a surprisingly common need as >> well. Would this be an appropriate construct to add to itertools? >> > > I'm in favor. > I am ecstatic about the idea of getting n items at a time from a generator! This would eliminate the use of less elegant functions to do this sort of thing which I would do even more frequently if it were easier. Is it possible that this syntax for generator expressions could be adopted? >>> sentence = 'this is a senTence WiTH' >>> generator = (word.capitalize() for word in sentence.split()) >>> print generator.next(3,'PadValue') ('This','Is','A') >>> print generator.next(3,'PadValue') ('Sentence','With','PadValue') >>> generator.next(3,'PadValue') Traceback (most recent call last): File "", line 1, in StopIteration >>> While on the topic of generators: Something else I have longed for is assignment within a while loop. (I realize this might be more controversial and might have been avoided on purpose, but I wasn't around for that discussion.) >>> sentence = 'this is a senTence WiTH' >>> generator = (word.capitalize() for word in sentence.split()) >>> while a,b,c = generator.next(3,'PadValue'): ... print a,b,c ... This Is A Sentence With PadValue >>> -- 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 tjreedy at udel.edu Wed Jan 16 15:16:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Jan 2008 15:16:40 -0500 Subject: module naming conventions References: <7f39199a-3334-4bcc-a424-5102f042ed01@1g2000hsl.googlegroups.com><87zlv8dnya.fsf@benfinney.id.au><6a53a14a-8f7c-4b6b-986f-48c7698f679f@v29g2000hsf.googlegroups.com><8763xwdj9c.fsf@benfinney.id.au> <478d113a$0$26041$88260bb3@free.teranews.com> Message-ID: "Tobiah" wrote in message news:478d113a$0$26041$88260bb3 at free.teranews.com... | | > Release your package as free software on the Cheeseshop | > . If the name you want is already | > taken, pick one that will help users distinguish yours from the | > existing one. | > | | I like this idea. I developed a library with a name that got | a couple of obscure software related hits on Google. I checked | sourceforge, and found that the name was available, so I stuck | my flag in the dirt. | | It was a python module, so I suppose I will have to look into | the cheeseshop. Is that as open as sourceforge, or is it only | for mature, sophisticated modules? Look at the cheeseshop page, but I would say that 'mature' and 'sophisticated' are too high a bar. 'Potentially useful and not-known-to-be-buggy' should be more like it. From albert at spenarnc.xs4all.nl Tue Jan 22 12:49:51 2008 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 22 Jan 2008 17:49:51 GMT Subject: Beginners question about debugging (import) Message-ID: I'm starting with Python. First with some interactive things, working through the tutorial, then with definitions in a file called sudoku.py. Of course I make lots of mistakes, so I have to include that file time and again. I discovered (the hard way) that the second time you invoke from sudoku.py import * nothing happens. There is reload. But it only seems to work with import sudoku Now I find myself typing ``sudoku.'' all the time: x=sudoku.sudoku() y=sudoku.create_set_of_sets() sudoku.symbols Is there a more convenient way? (This is a howto question, rather difficult to get answered from the documentation.) Groetjes Albert ~ -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- like all pyramid schemes -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From pavloutefkros at gmail.com Mon Jan 28 12:06:58 2008 From: pavloutefkros at gmail.com (pavloutefkros at gmail.com) Date: Mon, 28 Jan 2008 09:06:58 -0800 (PST) Subject: referer url References: <0e7fb40e-809c-4979-bbb8-0cd9a7e816c2@t1g2000pra.googlegroups.com> Message-ID: Thanks for the reply. 1) CGI so i'm doing it right. 2) this is impossible as i'm doing the exact same thing with another language and it utterly works. 3) the same as above 4) no.. this gets nerve breaking! From sjmachin at lexicon.net Mon Jan 21 04:23:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jan 2008 01:23:34 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <13p8803epubo92b@corp.supernews.com> <14dc1431-909b-4702-a695-846a683ef345@q77g2000hsh.googlegroups.com> Message-ID: <2a12db76-70c3-4ffe-94dc-b5595201f05f@f47g2000hsd.googlegroups.com> On Jan 21, 8:12 pm, pythonewbie wrote: > On 21 jan, 09:53, pythonewbie wrote: > > > > > On 21 jan, 05:31, Dennis Lee Bieber wrote: > > > > On Sun, 20 Jan 2008 13:58:13 -0800 (PST), pythonewbie > > > declaimed the following in comp.lang.python: > > > > > I just would like to know if I would ALWAYS find the install directory > > > > in sys.path[6] and site-packages directory in sys.path[7] on any Win32 > > > > platform and sys.path[2] and site-packages directory in sys.path[6] on > > > > any Linux platform. > > > > Unlikely... > > > > >>> sys.path[6] > > > > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg'>>> sys.path[2] > > > > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg'>>> sys.path > > > > ['', 'E:\\Python24\\lib\\site-packages\\pyopengl-3.0.0a5-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg', > > > 'E:\\Python24\\lib\\site-packages\\sqlobject-0.7.6-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\celementtree-1.0.5_20051216-py2.4-win32.egg', > > > 'E:\\Python24\\lib\\site-packages\\configobj-4.4.0-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\ruledispatch-0.5a0.dev_r2306-py2.4-win32.egg', > > > 'E:\\Python24\\lib\\site-packages\\formencode-0.7.1-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\pastescript-1.3.4-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\elementtree-1.2.6_20050316-py2.4-win32.egg', > > > 'E:\\Python24\\lib\\site-packages\\simplejson-1.7.1-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\cherrypy-2.2.1-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\turbocheetah-0.9.5-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\turbojson-1.0-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\pyprotocols-1.0a0dev_r2302-py2.4-win32.egg', > > > 'E:\\Python24\\lib\\site-packages\\pastedeploy-1.3-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\paste-1.3-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\cheetah-2.0rc8-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\setuptools-0.6c6-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\turbogears-1.0.3.2-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\turbokid-1.0.2-py2.4.egg', > > > 'E:\\Python24\\lib\\site-packages\\kid-0.9.6-py2.4.egg', > > > 'e:\\python24\\lib\\site-packages\\scipy', > > > 'C:\\WINDOWS\\system32\\python24.zip', 'e:\\UserData\\Dennis Lee > > > Bieber\\My Documents', 'E:\\Python24\\DLLs', 'E:\\Python24\\lib', > > > 'E:\\Python24\\lib\\plat-win', 'E:\\Python24\\lib\\lib-tk', > > > 'E:\\Python24\\Lib\\site-packages\\pythonwin', 'E:\\Python24', > > > 'E:\\Python24\\lib\\site-packages', > > > 'E:\\Python24\\lib\\site-packages\\Numeric', > > > 'E:\\Python24\\lib\\site-packages\\PIL', > > > 'E:\\Python24\\lib\\site-packages\\win32', > > > 'E:\\Python24\\lib\\site-packages\\win32\\lib', > > > 'E:\\Python24\\lib\\site-packages\\wx-2.8-msw-unicode'] > > > > >>> os.environ["PATH"] > > > > 'E:\\Python24\\;C:\\GNAT\\bin;C:\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\PROGRA~1\\MySQL\\MySQL > > > Server 5.0\\bin;C:\\Program Files\\SciTE;C:\\Program > > > Files\\Java\\jre1.6.0_03\\bin;C:\\Program > > > Files\\Java\\jdk1.6.0_03\\bin;C:\\Program Files\\Common > > > Files\\Adobe\\AGL;C:\\MSSQL7\\BINN;c:\\PROGRA~1\\sdb\\programs\\bin;c:\\PROGRA~1\\sdb\\programs\\pgm;C:\\Tcl\\bin;C:\\Program > > > Files\\Common Files\\Roxio Shared\\DLLShared\\;C:\\Program Files\\Common > > > Files\\Roxio Shared\\9.0\\DLLShared\\;e:\\Python24\\Scripts;c:\\Regina' > > > > -- > > > 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/ > > > OK Denis Lee, I see now. I appreciate your clear and simple to > > understand reply. > > > All posts on this topic, have been appreciated a lot... Thanks to all > > helpers. > > > Cheers > > Hi John Machin, > > Your code : > > >>> import sys, re > >>> for p in sys.path: > > ... m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p) > ... if m: > ... print m.group(1, 0) > ... break > ... else: > ... raise Exception('Huh?') > ... > > Does not work on my PC : Traceback (most recent call last): > File "/home/eproust/john-machin_recup_rep_site-packages.py", line 9, > in > raise Exception('Huh?') > Exception: Huh? My palantir is in the workshop, so you'll have to tell me what's in sys.path on your machine. > > Even if I remove all code below the else: part of the script... Uh-huh. From sjmachin at lexicon.net Sun Jan 27 02:56:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 26 Jan 2008 23:56:31 -0800 (PST) Subject: how to make format operator % work with unicode as expected References: Message-ID: On Jan 27, 3:06 pm, "Peter Pei" wrote: > I probably should mention that what I want is to make all parts of the > string aligned, and look like table. I am not looking for other ways to make > it table-alike, but only interested in making % work with unicode -counting > characters not bytes... Can you show some *code* that demonstrates the alleged problem? E.g. len("" % some_unicode) != expected_len Reading this may help: http://www.chiark.greenend.org.uk/~sgtatham/bugs.html From Russ.Paielli at gmail.com Sun Jan 27 21:50:56 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jan 2008 18:50:56 -0800 (PST) Subject: py3k feature proposal: field auto-assignment in constructors References: <0ebb27f8-eada-489f-b656-99a98c4df143@s8g2000prg.googlegroups.com> <87d4rm93l1.fsf@benfinney.id.au> <479d2c23$0$25372$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Jan 27, 5:13 pm, Wildemar Wildenburger wrote: > Ben Finney wrote: > > "Andr?" writes: > > >> Personally, I like the idea you suggest, with the modification that I > >> would use "." instead of "@", as in > > >> class Server(object): > >> def __init__(self, .host, .port, .protocol, .bufsize, .timeout): > >> pass > > > -1. > > > That leading dot is too easy to miss when looking over the code. > > class Server(object): > def __init__(self, self.host, self.port, > self.protocol, self.bufsize, self.timeout): > pass > > ? > > /W That makes sense to me. Come to think of it, why restrict this convention to the constructor? Or am I just opening a can of worms? From robert.kern at gmail.com Sun Jan 13 22:15:16 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 13 Jan 2008 21:15:16 -0600 Subject: Slicing wrapped numpy arrays In-Reply-To: References: Message-ID: Martin Manns wrote: > On Sun, 13 Jan 2008 16:03:16 -0600 > Robert Kern wrote: > >> Martin Manns wrote: >>> Hi, >>> >>> I have created a class that wraps a numpy array of custom objects. I >>> would like to be able to slice respective objects (without copying >>> the array if possible). >>> >>> I have browsed the doc and found some hints at __getitem__. >>> However, I still do not grasp how to do it. How do I implement >>> __getitem__ correctly? >>> mymap[10:20,15:20,:] # This line should work afterwards >> The first thing you should do is simply implement a very basic, >> nonfunctional version just to see what objects come in: >> >> In [1]: class Sliceable(object): >> ...: def __getitem__(self, arg): >> ...: print arg >> ...: > > I did that and got here: > >> (slice(None, None, 2), slice(10, None, 10)) > > However, I still do not see how I get a Map object that employs a > slice of the array without creating a new Map object. That's because creating a new Map object is the right thing to do. Instead of making Map.__init__() generate the map array from the dimensions, it should just take a preconstructed map array. You can use a @classmethod or just a factory function to provide an alternate constructor which builds a Map from the dimensions. When designing classes, I usually try to do as little computation as possible in an __init__(). Doing a lot of stuff there limits the ways you can build the object later. For some classes, this doesn't matter a whole lot, but for data structures that can be sliced and concatenated or otherwise transformed, you really want that flexibility. -- 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 paddy3118 at googlemail.com Sat Jan 26 02:59:57 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 25 Jan 2008 23:59:57 -0800 (PST) Subject: finding child cpu usage of a running child References: Message-ID: On Jan 26, 5:43 am, Karthik Gurusamy wrote: > Hi, > > Wondering if there is a way to measure a child process's cpu usage > (sys and user) when the child is still running. I see os.times() > working fine in my system (Linux 2.6.9-42.7.ELsmp), but it gives valid > data only after the child has exited. When the child is alive, > os.times() data for child is zero for both child-sys and child-user > cpu. > > My script (process P1) launches child process P2 (using > popen2.Popen3). P2 is a long running process (big compilation). Every > minute or so, from P1, I want to measure how much cpu P2 has consumed > and based on that I can make some estimate on the completion time of > P2 (I have a rough idea how much total cpu P2 needs to complete). > > I understand it may be too expensive to update this information to the > parent process when any of the child/grand-child completes; but > wondering if any there is any way to get this info; the expensive > operations is on-demand only when the request is made. > > Thanks, > Karthik I had a similar requirement in December and found: http://lilypond.org/~janneke/software/ proc-time.c and proc-time.py poll /proc/.... files whilst command is running to get stats. Enjoy, - Paddy. From bj_666 at gmx.net Tue Jan 22 03:08:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Jan 2008 08:08:19 GMT Subject: what's this instance? References: Message-ID: <5vlmjjF1n19plU2@mid.uni-berlin.de> On Tue, 22 Jan 2008 15:36:49 +0800, J. Peng wrote: > def safe_float(object): > try: > retval = float(object) > except (ValueError, TypeError), oops: > retval = str(oops) > return retval > > x=safe_float([1,2,3,4]) > print x > > > The code above works well.But what's the instance of "oops"? where is it > coming from? I'm totally confused on it.thanks. `oops` is bound to the `ValueError` or `TypError` object if `float()` raises such an exception. Ciao, Marc 'BlackJack' Rintsch From gefafwisp at gmail.com Wed Jan 30 13:19:13 2008 From: gefafwisp at gmail.com (gefafwisp at gmail.com) Date: Wed, 30 Jan 2008 10:19:13 -0800 (PST) Subject: Updating documents in PyLucene Message-ID: Hi all, The way that Lucene (and by extension, PyLucene) seems to work is that updates to documents are implemented by the user as a document addition (of the new version) and subsequent deletion (of the old version). My problem is that I'd like to update a number of documents which have their Store flag set to NO - they're indexed, but not stored. I don't have the original text content of these documents available anywhere else - is there any way for me to get this un-stored indexed data from the old document into the new? Also posting to comp.lang.java.programmer. Thanks, James From ndbecker2 at gmail.com Fri Jan 25 16:47:22 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 25 Jan 2008 16:47:22 -0500 Subject: Index of maximum element in list References: <8d04436f0801251337p78f88900l877603cf6b785ef9@mail.gmail.com> <8d04436f0801251339u13a2d0bgf7b675e81898a47c@mail.gmail.com> Message-ID: Henry Baxter wrote: > Oops, gmail has keyboard shortcuts apparently, to continue: > > def maxi(l): > m = max(l) > for i, v in enumerate(l): > if m == v: > return i > > But it seems like something that should be built in - or at least I should > be able to write a lambda function for it, but I'm not sure how to do that > either...Suggestions are very much welcome! > I really think this is a good candidate for a builtin. I suggest: max2 (x): """ return (minvalue,minindex)""" This allows efficient usage in all cases, including iterators (not just sequences). From steven.bethard at gmail.com Fri Jan 25 15:05:06 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 25 Jan 2008 13:05:06 -0700 Subject: is possible to get order of keyword parameters ? In-Reply-To: <5b6e2bc6-8136-4e3a-8bf2-bb6d689d6110@s8g2000prg.googlegroups.com> References: <5a247397-1b15-4701-bbb3-60b2f11d0c28@i12g2000prf.googlegroups.com> <5b6e2bc6-8136-4e3a-8bf2-bb6d689d6110@s8g2000prg.googlegroups.com> Message-ID: rndblnch wrote: > my goal is to implement a kind of named tuple. > idealy, it should behave like this: > p = Point(x=12, y=13) > print p.x, p.y > but what requires to keep track of the order is the unpacking: > x, y = p > i can't figure out how to produce an iterable that returns the values > in the right order. > relying on a "natural" order of the key names is not possible: x, and > y are alphabetically sorted but the following example should also > work: > size = Point(width=23, height=45) > w, h = size There are a couple of recipes for named tuples: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261 The latter of these will be in Python 2.6. Using that recipe, and your example, you would write:: Point = namedtuple('Point', 'x y') p = Point(x=12, y=13) x, y = p Point = namedtuple('Point', 'width', 'height') size = Point(width=23, height=45) w, h = size STeVe From dickinsm at gmail.com Sat Jan 12 11:34:02 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 12 Jan 2008 08:34:02 -0800 (PST) Subject: Compiling fails on Mac OS X 10.5 References: <352080fd-ace1-46d4-82b1-94937b851a38@k2g2000hse.googlegroups.com> Message-ID: On Jan 12, 9:41?am, mc wrote: > Hi! > I'm trying to compile on my Macbook with OS X 10.5. I have all updates > and Xcode 3.0 installed. > > I checked python out with: svn checkouthttp://svn.python.org/projects/python/branches/py3k > After that I did "./configure" in the ?created "py3k" dir. Everything > went fine. But make fails with the following error message: > ranlib libpython3.0.a > gcc ?-u _PyMac_Error -o python.exe \ > ? ? ? ? ? ? ? ? ? ? ? ? Modules/python.o \ > ? ? ? ? ? ? ? ? ? ? ? ? libpython3.0.a -ldl > make: *** [sharedmods] Error 1 > > I tried checking out many times. I also tried de 3.0a2 release,gives > me the same error. I've heard others have compiled it successfully on > Leopard so I wonder what causes the problems on my system. Could you post the rest of the ./configure and compilation output? make might be rereporting an error that occurred further up. I don't see anything related on the Python bug tracker. It might be worth posting a bug report at bugs.python.org Mark From sjmachin at lexicon.net Thu Jan 24 16:53:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 24 Jan 2008 13:53:53 -0800 (PST) Subject: Sorting Large File (Code/Performance) References: <85bddf27-6d38-4dce-a7e7-412d15703c37@i3g2000hsf.googlegroups.com> <908f8427-005f-4425-95a8-2db82c6efc5a@e6g2000prf.googlegroups.com> Message-ID: On Jan 25, 8:26 am, Ira.Ko... at gmail.com wrote: > I need to isolate all lines that start with two characters (zz to be > particular) What does "isolate" mean to you? What does this have to do with sorting? What do you actually want to do with (a) the lines starting with "zz" (b) the other lines? What percentage of the lines start with "zz"? When looking at the GnuWin32 collection: (a) "Unicode" is not relevant to your sort problem. (b) grab yourself a wc and a grep while you're there -- they will help with "how many lines" and "what percentage of lines" questions. From svenn.bjerkem at googlemail.com Wed Jan 9 08:56:31 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Wed, 9 Jan 2008 05:56:31 -0800 (PST) Subject: executing newgrp from python in current shell possible? Message-ID: Hi, as a user on a linux system I am member of the groups "users" and "design" with users as my default group. To controll the accessibility of some parts of the file system, creation of files and directories in those parts must be done with group "design". This is currently done manually with "newgrp design" on the command line before doing anything else. I have been looking for a way to execute this command as a part of a script, but it seems that the changes are only valid in the context of the script and when the script exits, the current shell still have the original "users" group setting. It looks like the command spawns a new command line in the context of the current xterm as I get back to my old command line when exiting (instead of the xterm dissapearing) A possible alternative could be to have the python script launch a new shell, but I still have the problem to set the group id for that new shell (lack of python knowledge). I am happy for any advice. Maybe it is simply not possible to do this kind of operation from a script in python on linux. -- kind regards, Svenn From arnodel at googlemail.com Tue Jan 22 02:11:23 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 21 Jan 2008 23:11:23 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> Message-ID: On Jan 22, 3:20?am, Alan Isaac wrote: > I want to generate sequential pairs from a list. > Here is a way:: > > ? ? from itertools import izip, islice > ? ? for x12 in izip(islice(x,0,None,2),islice(x,1,None,2)): > ? ? ? ? print x12 > > (Of course the print statement is just illustrative.) > What is the fastest way? (Ignore the import time.) > > Thanks, > Alan Isaac Don't know the fastest, but here's a very concise way: from itertools import izip def ipairs(seq): it = iter(seq) return izip(it, it) >>> list(pairs(xrange(10))) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] >>> list(pairs('hello')) [('h', 'e'), ('l', 'l')] -- Arnaud From rphenry at home.com Sat Jan 12 13:09:50 2008 From: rphenry at home.com (Richard Henry) Date: Sat, 12 Jan 2008 10:09:50 -0800 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> <4788de48$0$26887$ecde5a14@news.coretel.net> Message-ID: "radiosrfun" wrote in message news:4788de48$0$26887$ecde5a14 at news.coretel.net... > "default" wrote in message > news:91hho3tr56dpsfqsav4lnr8sl944bbrviv at 4ax.com... > > On Sat, 12 Jan 2008 02:01:09 -0500, "radiosrfun" > > wrote: > > > >>I WISH - that the President and Congress of this country would shut off > >>ALL > >>foreign aid. > > > > Ditto that. > > > > Israel is the chief beneficiary of our foreign aid largesse. Some 8 > > billion dollars annually. What doesn't find its way into politicians > > pockets goes to pay for a military that is winning us a lot of new > > friends in the Arab world. > > > > We pay Egypt ~ 2 billion a year in extortion to keep them from > > attacking Israel. > > > > The actually amount Israel receives is not really known to the public. > > The official numbers read something like 3 billion in aid, and another > > 5 billion in guaranteed loans - which are turned into grants year > > after year. This is money we borrow so there's an additional interest > > burden. > > > > Actually when you talk about shutting off "foreign aid" you may be > > making thermate's point for him. > > -- > > Well - the first cup of coffee hasn't exactly kicked in yet - but I believe > I know what you're saying and if correct - you may have a point there. According to the US Govt for 2006: Israel: $2.6B Egypt $1.8B Iraq: $9.8B Afghanistan $3.7B http://qesdb.usaid.gov/gbk/ From dickinsm at gmail.com Mon Jan 28 09:40:23 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 28 Jan 2008 06:40:23 -0800 (PST) Subject: When is min(a, b) != min(b, a)? References: <13pi8fiiqgljdb5@corp.supernews.com> <13pjgrj540qt98a@corp.supernews.com> Message-ID: <15b62428-a10f-46bb-bf4c-3f37474adc6f@c23g2000hsa.googlegroups.com> On Jan 28, 6:50 am, Antoon Pardon wrote: > My personal preference would be that python would allow people the > choice, with the default being that any operation that resulted > in a non numeric result would throw an exception. > > People who somehow made it clear they know how to work with inf, and > NaN results, would get silent NaN where no exceptions would be thrown. I also think this would be the ideal situation. Getting there would require a lot of thought, planning, a PEP or two, and some hard work and tricky coding to deal with all the different ways that the C compiler, libm and hardware might try to mess things up. Right now I don't have time for this :-( Anyone else? > > Putting aside sorting and max/min, what is the use-case for having > > comparisons with NaN succeed? What benefit will it give you? > > I guess the same benefit it gives to those that have operations with > NaN succeed. If 3 * NaN should succeed and all sort of other stuff, > why suddenly make an exception for 3 < NaN. Right. This is especially true when the result of the comparison is treated as number (i.e. 0 or 1) rather than as a boolean, and goes back into the calculation in some way. On the other hand, there are certainly situations where you want a comparison with a NaN to raise an exception. I guess this is why IEEE-754r provides two sets of comparison operators: signaling and non-signaling. Mark From jayabarathi2007 at gmail.com Fri Jan 25 01:18:23 2008 From: jayabarathi2007 at gmail.com (Barathi) Date: Thu, 24 Jan 2008 22:18:23 -0800 (PST) Subject: Method for intracardiac therapy using sensor for heart wall thickness Message-ID: Method for intracardiac therapy using sensor for heart wall thickness Localization of muscle gene ..... rotating and reciprocating piston metering pumps, peristaltic pumps or any ... http://www.freewebs.com/boreqwe/ http://indianfriendfinder.com/go/g931378-pmem http://bigchurch.com/go/g931377-pmem From fredrik at pythonware.com Thu Jan 3 10:16:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 03 Jan 2008 16:16:42 +0100 Subject: problem with global var In-Reply-To: <3448388f0801030638sd285c7dh78b9ea9f7b911139@mail.gmail.com> References: <3448388f0801030638sd285c7dh78b9ea9f7b911139@mail.gmail.com> Message-ID: Bruno Ferreira wrote: > When I execute the program _without_ the lines 10 and 11: > > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > > it runs perfectly. > > But if I execute the program _with_ those lines, this exception is thrown: > > bruno at ts:~$ python topsquid.py > Traceback (most recent call last): > File "topsquid.py", line 20, in > add_sorted (linefields) > File "topsquid.py", line 6, in add_sorted > if int(list[4]) > int(topsquid[i][4]): > UnboundLocalError: local variable 'topsquid' referenced before assignment Python uses static analysis to determine if a variable is local to a function; somewhat simplified, if you assign to the variable inside the function, *all* uses of that variable inside the function will be considered local. for the full story, see: http://docs.python.org/ref/naming.html to fix this, you can insert a "global" declaration at the top of the def add_sorted (list): global topsquid # mark topsquid as global in this function ... in this case, you can also avoid the local assignment by modifying the list in place; if len(topsquid) > 50: topsquid[:] = topsquid[0:50] or, as a one-liner: del topsquid[50:] From meesters at uni-mainz.de Tue Jan 29 08:22:36 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Tue, 29 Jan 2008 14:22:36 +0100 Subject: extending Python - passing nested lists References: <3ddeaf07-3f4b-4d68-a176-9205fa4d234b@k39g2000hsf.googlegroups.com> Message-ID: Thanks. Point is that all such approaches would require lots(!) of calls to the Python API - a way by which I won't gain the desired speed. I've tried pyrex and the corresponding C-file is so convoluted with dummy variables, incrementing & decrementing references, and other stuff, that I want to try to write a C-function myself. My goal is not to avoid PyObjects* and the corresponding reference handling - apart from the head and end of the function. (I could use ctypes instead, but that again would obfuscate the API of my package a bit.) Christian From jarausch at skynet.be Wed Jan 30 11:21:56 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 30 Jan 2008 17:21:56 +0100 Subject: Trouble loading dll via ctypes In-Reply-To: <68615d61-3e71-4a39-8783-52ff0db97b48@i12g2000prf.googlegroups.com> References: <68615d61-3e71-4a39-8783-52ff0db97b48@i12g2000prf.googlegroups.com> Message-ID: <47a0a425$0$2941$ba620e4c@news.skynet.be> subopt inTheVicinityOf geemail.com wrote: > I'm trying to load a dll via ctypes by doing this: > > cdll.LoadLibrary('/path/to/mylib.so') > > But i'm getting this: > > /path/to/mylib.so: cannot open shared object file: No such file or > directory What am i doing wrong? > > The dll in question is in a directory mounted via NSF, but no part of > the path/filename is a symlink. When i try code from the docs: > > cdll.LoadLibrary('libc.so.6') > > ,then all is fine. > > I've also tried to set my LD_LIBRARY_PATH before starting Python, > checking it via os.environ, then doing the cdll.LoadLibrary(...), but > that fails with the same complaint. What am i doing wrong? > I vaguely remember you need execute permissions for a dynamic library to load. Permissions on an NFS mounted directory are different, especial for user 'root'. Check if can execute some executable in that NFS path. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From kyosohma at gmail.com Tue Jan 22 15:48:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 22 Jan 2008 12:48:03 -0800 (PST) Subject: Processing XML that's embedded in HTML References: Message-ID: <6886f9c5-43ce-44c2-a272-35587d59a0ec@d70g2000hsb.googlegroups.com> On Jan 22, 11:32 am, Paul Boddie wrote: > > The rest of the document is html, javascript div tags, etc. I need the > > information only from the row where the Relationship tag = Owner and > > the Priority tag = 1. The rest I can ignore. When I tried parsing it > > with minidom, I get an ExpatError: mismatched tag: line 1, column 357 > > so I think the HTML is probably malformed. > > Or that it isn't well-formed XML, at least. I probably should have posted that I got the error on the first line of the file, which is why I think it's the HTML. But I wouldn't be surprised if it was the XML that's behaving badly. > > > I looked at BeautifulSoup, but it seems to separate its HTML > > processing from its XML processing. Can someone give me some pointers? > > With libxml2dom [1] I'd do something like this: > > import libxml2dom > d = libxml2dom.parse(filename, html=1) > # or: d = parseURI(uri, html=1) > rows = d.xpath("//XML/BoundData/Row") > # or: rows = d.xpath("//XML[@id="grdRegistrationInquiryCustomers"]/ > BoundData/Row") > > Even though the document is interpreted as HTML, you should get a DOM > containing the elements as libxml2 interprets them. > > > I am currently using Python 2.5 on Windows XP. I will be using > > Internet Explorer 6 since the document will not display correctly in > > Firefox. > > That shouldn't be much of a surprise, it must be said: it isn't XHTML, > where you might be able to extend the document via XML, so the whole > document has to be "proper" HTML. > > Paul > > [1]http://www.python.org/pypi/libxml2dom I must have tried this module quite a while ago since I already have it installed. I see you're the author of the module, so you can probably tell me what's what. When I do the above, I get an empty list either way. See my code below: import libxml2dom d = libxml2dom.parse(filename, html=1) rows = d.xpath('//XML[@id="grdRegistrationInquiryCustomers"]/BoundData/ Row') # rows = d.xpath("//XML/BoundData/Row") print rows I'm not sure what is wrong here...but I got lxml to create a tree from by doing the following: from lxml import etree from StringIO import StringIO parser = etree.HTMLParser() tree = etree.parse(filename, parser) xml_string = etree.tostring(tree) context = etree.iterparse(StringIO(xml_string)) However, when I iterate over the contents of "context", I can't figure out how to nab the row's contents: for action, elem in context: if action == 'end' and elem.tag == 'relationship': # do something...but what!? # this if statement probably isn't even right Thanks for the quick response, though! Any other ideas? Mike From mail at timgolden.me.uk Thu Jan 17 06:18:26 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 17 Jan 2008 11:18:26 +0000 Subject: Opening/Running files through python In-Reply-To: <239efd0e-5ac8-485c-b316-aa52b0a2c316@i72g2000hsd.googlegroups.com> References: <239efd0e-5ac8-485c-b316-aa52b0a2c316@i72g2000hsd.googlegroups.com> Message-ID: <478F3982.7040602@timgolden.me.uk> Ionis wrote: > Hey guys, hope you can help me here. > > I am running in windows and I am trying to open a file via python. I > want the file (a text file) to open up in the users default text > editor. I'm not wanting to read a file, I just want to open it. Is > there a way? import os os.startfile ("blah.txt") From jzgoda at o2.usun.pl Sun Jan 27 18:08:32 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 28 Jan 2008 00:08:32 +0100 Subject: optional static typing for Python In-Reply-To: References: Message-ID: Russ P. pisze: >>> I noticed that Guido has expressed further interest in static typing >>> three or four years ago on his blog. Does anyone know the current >>> status of this project? Thanks. >> I thought it was april fools joke? > > On January 21, 2000? Which calendar do you use? Static typing in Python is usual theme of april fools jokes. -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From mwm-keyword-python.b4bdba at mired.org Fri Jan 11 18:29:56 2008 From: mwm-keyword-python.b4bdba at mired.org (Mike Meyer) Date: Fri, 11 Jan 2008 18:29:56 -0500 Subject: Newbie Q: modifying SQL statements In-Reply-To: <20080111231141.GA24213@neptune.faber.nom> References: <20080111013206.GA18259@neptune.faber.nom> <20080110225352.2c112555@bhuda.mired.org> <20080111231141.GA24213@neptune.faber.nom> Message-ID: <20080111182956.64466688@bhuda.mired.org> On Fri, 11 Jan 2008 18:11:41 -0500 "Faber J. Fedor" wrote: > On 10/01/08 22:53 -0500, Mike Meyer wrote: > > Personally, I think it would be more pythonic to not try and use two > > different APIs to walk the list of jobs (... One Way To Do it): > > > > def __call__(self, where=None): > > q = "select * from %s" % (self.name,) + ("" if not where else (" where %s" % where)) > > Does this '("" if not where...' syntax actually work? I couldn't get it to > compile and I couldn't find any examples of such syntax (but you can't > expect googling for 'if not' to be too successful). Yes. >>> def test(name, where): ... return "select * from %s" % (name,) + ("" if not where else (" where %s" % where)) ... >>> test('mine', 'x = 3') 'select * from mine where x = 3' >>> test('mine', None) 'select * from mine' >>> test('yours', 'barfle is not NULL') 'select * from yours where barfle is not NULL' It is a 2.5 feature, though. I converted all my clients to 2.5.1, shortly after it was available, and haven't used anything older since. Sorry 'bout that. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From steve at REMOVE-THIS-cybersource.com.au Mon Jan 14 16:27:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 14 Jan 2008 21:27:21 -0000 Subject: encrypting python modules References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <13og1dbe4qcfs2b@corp.supernews.com> <478b220e$0$85788$e4fe514c@news.xs4all.nl> <13omgn69naf1se8@corp.supernews.com> <5v13toF1kbqonU1@mid.dfncis.de> Message-ID: <13onktp123l2c0e@corp.supernews.com> On Mon, 14 Jan 2008 12:46:48 +0000, Robert Latest wrote: > And, contrary to the advice I gave elsethread, unfortunately it's > impossible to just drop uncooperative customers when you develop GPL > software ;-) Just because you are writing GPLed code doesn't mean you are permanently linked to anyone you have supplied code to. You can send their emails straight to /dev/null. You don't have to give them any support, only the source code. And if you do give them support, the GPL doesn't limit what your hourly rates are: you are free to charge them one million dollars per hour, payable in advance in blocks of fifteen hours. If they don't like it, they can always fork the code, or find another person to support it, or simply stop being dicks. -- Steven From bbtestingbb at gmail.com Thu Jan 24 00:49:15 2008 From: bbtestingbb at gmail.com (bbtestingbb at gmail.com) Date: Wed, 23 Jan 2008 21:49:15 -0800 (PST) Subject: Some questions about decode/encode References: <1723019e-a335-4882-8476-cba68d142746@s13g2000prd.googlegroups.com> Message-ID: <54c22550-a2fc-4eac-b80d-20936b209b99@y5g2000hsf.googlegroups.com> On Jan 23, 8:49 pm, glacier wrote: > I use chinese charactors as an example here. > > >>>s1='???' > >>>repr(s1) > > "'\\xc4\\xe3\\xba\\xc3\\xc2\\xf0'" > > >>>b1=s1.decode('GBK') > > My first question is : what strategy does 'decode' use to tell the way > to seperate the words. decode() uses the GBK strategy you specified to determine what constitutes a character in your string. > My second question is: is there any one who has tested very long mbcs > decode? I tried to decode a long(20+MB) xml yesterday, which turns out > to be very strange and cause SAX fail to parse the decoded string. > However, I use another text editor to convert the file to utf-8 and > SAX will parse the content successfully. > > I'm not sure if some special byte array or too long text caused this > problem. Or maybe thats a BUG of python 2.5? That's probably to vague of a description to determine why SAX isn't doing what you expect it to. From aarfaee at cs.ucsd.edu Sat Jan 19 23:35:33 2008 From: aarfaee at cs.ucsd.edu (Arash Arfaee) Date: Sat, 19 Jan 2008 20:35:33 -0800 Subject: psyco problem on mac wingide Message-ID: <266557d0801192035i2fcb8a8dk268209f1d63ffbc7@mail.gmail.com> Hello All, I have no problem using psyco on python shell on my new Mac, however I cannot import it from WingIDE. I copied psyco directory into mac python folder. Does wingide installs another python shell? Thanks, Arash From rw at smsnet.pl Thu Jan 10 15:42:44 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 10 Jan 2008 21:42:44 +0100 Subject: urllib2 rate limiting References: <87ejcpo7r8.fsf@merkury.smsnet.pl> Message-ID: <87abndo1iz.fsf@merkury.smsnet.pl> Dimitrios Apostolou writes: > On Thu, 10 Jan 2008, Rob Wolfe wrote: > >> Dimitrios Apostolou writes: >> >>> P.S. And something simpler: How can I disallow urllib2 to follow >>> redirections to foreign hosts? >> >> You need to subclass `urllib2.HTTPRedirectHandler`, override >> `http_error_301` and `http_error_302` methods and throw >> `urllib2.HTTPError` exception. > > Thanks! I think for my case it's better to override redirect_request > method, and return a Request only in case the redirection goes to the > same site. Just another question, because I can't find in the docs the > meaning of (req, fp, code, msg, hdrs) parameters. To read the URL I > get redirected to (the 'Location:' HTTP header?), should I check the > hdrs parameter or there is a better way? Well, according to the documentation there is no better way. But I looked into the source code of `urllib2` and it seems that `redirect_request` method takes one more parameter `newurl`, what is probably what you're looking for. ;) Regards, Rob From tjreedy at udel.edu Tue Jan 22 22:40:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jan 2008 22:40:43 -0500 Subject: possible to overide setattr in local scope? References: <9dac9675-992e-4dc5-b085-06f0811939ca@1g2000hsl.googlegroups.com> Message-ID: "glomde" wrote in message news:9dac9675-992e-4dc5-b085-06f0811939ca at 1g2000hsl.googlegroups.com... | In a class it is poosible to override setattr, so that you can decide | how you should | handle setting of variables. | | Is this possible to do outside of an class on module level. | | mysetattr(obj, var, value): | print "Hello" | | So that | | test = 5 | | | would print | Hello An assignment at module level amounts to setting an attribute of an instance of the builtin (C coded) module type, which you cannot change. Even if you can subclass that type (I don't know), there is no way to get the (stock) interpreter to use instances of your module subclass instead. From george.sakkis at gmail.com Mon Jan 21 23:54:28 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 21 Jan 2008 20:54:28 -0800 (PST) Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> Message-ID: On Jan 21, 10:20 pm, Alan Isaac wrote: > I want to generate sequential pairs from a list. > Here is a way:: > > from itertools import izip, islice > for x12 in izip(islice(x,0,None,2),islice(x,1,None,2)): > print x12 > > (Of course the print statement is just illustrative.) > What is the fastest way? (Ignore the import time.) Look up the timeit module and test yourself the various alternatives; that's the most reliable way to tell for sure. George From jarausch at igpm.rwth-aachen.de Wed Jan 23 06:21:23 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 23 Jan 2008 12:21:23 +0100 Subject: Removing objects In-Reply-To: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> Message-ID: <5vom9lF1mlfisU1@mid.dfncis.de> bladedpenguin at gmail.com wrote: > I am writing a game, and it must keep a list of objects. I've been > representing this as a list, but I need an object to be able to remove > itself. It doesn't know it's own index. If I tried to make each object > keep track of it's own index, it would be invalidated when any object > with a lower index was deleted. The error was that when I called > list.remove(self), it just removed the first thing in hte list with > the same type as what I wanted, rather than the object I wanted. The > objects have no identifying charachteristics, other than thier > location in memory > > So my question: How do I look something up in a list by it's location > in memory? does python even support pointers? > > Is there a better way? You could use a doubly linked list. The class 'deque' from collections is such a list but I don't known how to delete a specific element without this ugly (expensive?) rotate method. Here is my solution in pure Python #!/usr/bin/python import re class Queue(object): __slots__= 'Head', 'Tail', '__iter__','NNd' def __init__(self): self.Head= None self.Tail= None self.NNd= None def append(self,N): if self.Head == None: self.Head= N self.Tail= self N._enqueue_after(self.Tail) self.Tail= N def dequeue(self,N): Father, Son= N._dequeue() if self.Tail == N: self.Tail= Father if self.Head == N: self.Head= Son if self.Head == None: self.Tail= None def enqueue_after(self,N,Father): N._enqueue_after(Father) if self.Tail == Father: self.Tail= N def enqueue_before(self,N,Son): N._enqueue_before(Son) if self.Head == Son: self.Head= N def __iter__(self): next= self.Head # allows to dequeue the current element in a loop while True: current= next if current == None: raise StopIteration next= current._next() yield current class Node(object): # partially application specific __slots__= 'next', 'NNd','PNd','key','data' def __init__(self,Key,Data,P=None,N=None): # P = Previous N = Next if P != None: P.NNd= self if N != None: N.PNd= self self.PNd= P self.NNd= N self.key= Key self.data= Data def _enqueue_after(self,Father): self.NNd= Father.NNd self.PNd= Father Father.NNd= self def _enqueue_before(self,Son): self.NNd= Son self.PNd= Son.PNd Son.PNd= self def _dequeue(self): if self.PNd != None: self.PNd.NNd= self.NNd if self.NNd != None: self.NNd.PNd= self.PNd Father= self.PNd Son= self.NNd self.PNd= self.NNd= None return Father,Son def _next(self): return self.NNd def __str__(self): # highly application specific return '(%s:%s)' % (self.key,self.data) # some tests MyQ= Queue() MyQ.append( Node('HJ','3949') ) print MyQ.Head,MyQ.Tail,MyQ.Head.key MyQ.append( Node('CJ','10149') ) print MyQ.Head,MyQ.Tail,MyQ.Head.key N= MyQ.Head print "queue: ",N.key,"->" N= N.NNd print "next: ",N.key,"->" N= N.NNd if N != None: print "next: ",N.key,"->" else: print "no next:" for N in MyQ: print "loop->",N print N.key,N.data MyQ.dequeue(MyQ.Tail) print "--- after dequeue" print "Head: ",MyQ.Head," Tail: ",MyQ.Tail for N in MyQ: print "loop2->",N print N.key,N.data MyQ.dequeue(MyQ.Tail) print "after second dequeue" print "Head: ",MyQ.Head," Tail: ",MyQ.Tail for N in MyQ: print "loop3->",N print N.key,N.data ENJOY, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From jimgardener at gmail.com Wed Jan 9 00:35:35 2008 From: jimgardener at gmail.com (jimgardener) Date: Tue, 8 Jan 2008 21:35:35 -0800 (PST) Subject: copy a numpy array References: <0cc33c4e-bb6b-4f80-8b4d-d702dc7789ec@v29g2000hsf.googlegroups.com> Message-ID: <2af4702f-a29e-4d7b-85e8-78cd7dc9f36a@f3g2000hsg.googlegroups.com> thanx guys for the replies need a little clarification srcarray=array([1.2,2.3,3.4,4.5,5.6]) destarray=array(srcarray,copy=False) then srcarray[2]=99.9 will cause the change to be reflected in both src and dest. doesn't that mean data is shared between both arrays? but if i do destarray=array(srcarray) or destarray=srcarray.copy() then the change in one array will not affect the other,meaning no data sharing ...want to know if my understanding is right jim From http Thu Jan 31 10:59:03 2008 From: http (Paul Rubin) Date: 31 Jan 2008 07:59:03 -0800 Subject: Sine Wave Curve Fit Question References: <7eOdnXVrB-fQFD3anZ2dnUVZ8hednZ2d@giganews.com> <47a0c8b5$0$2994$ba620e4c@news.skynet.be> <47A1EE83.6050105@skynet.be> Message-ID: <7x8x26t29k.fsf@ruckus.brouhaha.com> Helmut Jarausch writes: > You're right: standard Python's math library missing the function arctan2. It's math.atan2 . From Luke.Visinoni at gmail.com Tue Jan 15 19:03:06 2008 From: Luke.Visinoni at gmail.com (Luke) Date: Tue, 15 Jan 2008 16:03:06 -0800 (PST) Subject: Data mapper - need to map an dictionary of values to a model References: <838669b3-db7b-4397-afba-565dd3df4d0a@i29g2000prf.googlegroups.com> <2d59f289-2def-43a8-93b7-f326b8f12066@z17g2000hsg.googlegroups.com> Message-ID: <88c59b87-a1e6-4e19-ba0f-402ecf0d7f7b@s19g2000prg.googlegroups.com> On Jan 15, 3:53 pm, George Sakkis wrote: > On Jan 14, 7:56 pm, Luke wrote: > > > > > I am writing an order management console. I need to create an import > > system that is easy to extend. For now, I want to accept an dictionary > > of values and map them to my data model. The thing is, I need to do > > things to certain columns: > > > - I need to filter some of the values (data comes in as YYYY-MM- > > DDTHH:MM:SS-(TIMEZONE-OFFSET) and it needs to map to Order.date as a > > YYYY-MM-DD field) > > - I need to map parts of an input column to more than one model param > > (for instance if I get a full name for input--like "John Smith"--I > > need a function to break it apart and map it to > > Order.shipping_first_name and Order.shipping_last_name) > > - Sometimes I need to do it the other way too... I need to map > > multiple input columns to one model param (If I get a shipping fee, a > > shipping tax, and a shipping discount, I need them added together and > > mapped to Order.shipping_fee) > > > I have begun this process, but I'm finding it difficult to come up > > with a good system that is extensible and easy to understand. I won't > > always be the one writing the importers, so I'd like it to be pretty > > straight-forward. Any ideas? > > > Oh, I should also mention that many times the data will map to several > > different models. For instance, the importer I'm writing first would > > map to 3 different models (Order, OrderItem, and OrderCharge) > > > I am not looking for anybody to write any code for me. I'm simply > > asking for inspiration. What design patterns would you use here? Why? > > The specific transformations you describe are simple to be coded > directly but unless you constrain the set of possible transformations > that can take place, I don't see how can this be generalized in any > useful way. It just seems too open-ended. > > The only pattern I can see here is breaking down the overall > transformation to independent steps, just like the three you > described. Given some way to specify each separate transformation, > their combination can be factored out. To illustrate, here's a trivial > example (with dicts for both input and output): > > class MultiTransformer(object): > def __init__(self, *tranformers): > self._tranformers = tranformers > > def __call__(self, input): > output = {} > for t in self._tranformers: > output.update(t(input)) > return output > > date_tranformer = lambda input: {'date' : input['date'][:10]} > name_tranformer = lambda input: dict( > zip(('first_name', 'last_name'), > input['name'])) > fee_tranformer = lambda input: {'fee' : sum([input['fee'], > input['tax'], > input['discount']])} > tranformer = MultiTransformer(date_tranformer, > name_tranformer, > fee_tranformer) > print tranformer(dict(date='2007-12-22 03:18:99-EST', > name='John Smith', > fee=30450.99, > tax=459.15, > discount=985)) > # output > #{'date': '2007-12-22', 'fee': 31895.140000000003, > 'first_name': #'J', 'last_name': 'o'} > > You can see that the MultiTransformer doesn't buy you much by itself; > it just allows dividing the overall task to smaller bits that can be > documented, tested and reused separately. For anything more > sophisticated, you have to constrain what are the possible > transformations that can happen. I did something similar for > transforming CSV input rows (http://pypi.python.org/pypi/csvutils/) so > that it's easy to specify 1-to-{0,1} transformations but not 1-to-many > or many-to-1. > > HTH, > George thank you that is very helpful. I will ponder that for a while :) From dieter at handshake.de Thu Jan 24 13:30:43 2008 From: dieter at handshake.de (Dieter Maurer) Date: 24 Jan 2008 19:30:43 +0100 Subject: pythonic backtrace with gdb In-Reply-To: References: Message-ID: Hynek Hanke writes on Wed, 23 Jan 2008 14:30:22 +0100: > ... > I've also tried to use the backtrace script here > http://mashebali.com/?Python_GDB_macros:The_Macros:Backtrace > But I get a different error: > (gdb) pbt > Invalid type combination in ordering comparison. > > I'm using GDB version 6.6.90. I expect that your GDB version is too new and has introduced some safety checks (which now break). It will probably help when you add explicite type casts to "long" around the comparisons in the definition of "pbt". Dieter From jerryji1976 at gmail.com Mon Jan 14 16:20:12 2008 From: jerryji1976 at gmail.com (jerryji) Date: Mon, 14 Jan 2008 13:20:12 -0800 (PST) Subject: hide object property from dir() function? Message-ID: Hi, Sorry for this newbie question, I was puzzled why the existing property of an object is not shown in the dir() function output. "v" is an lxml Element object variable -- In [44]: v Out[44]: In [45]: dir(v) Out[45]: ['__copy__', '__deepcopy__', '__reduce__', 'append', 'clear', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'keys', 'makeelement', 'remove', 'set'] dir() output doesn't contain the ".tag", which does exist -- In [46]: v.tag Out[46]: 'documentProperties' what is the rule governing the display of a property from dir()? Many thanks in advance! Jerry From mobiledreamers at gmail.com Tue Jan 8 22:32:33 2008 From: mobiledreamers at gmail.com (Mark) Date: Tue, 08 Jan 2008 19:32:33 -0800 Subject: Pyflakes pre-commit hook in subversion Message-ID: <47844051.7090401@gmail.com> An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Mon Jan 14 16:38:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 14 Jan 2008 21:38:17 -0000 Subject: short path evaluation, why is f() called here: dict(a=1).get('a', f()) References: <67cf6b0f-69ae-47d9-ae4b-7c4a5011dbcd@e25g2000prg.googlegroups.com> <0643d2e4-ba3d-4752-9604-87dcac0ff2d3@t1g2000pra.googlegroups.com> <7xsl105fvv.fsf@ruckus.brouhaha.com> Message-ID: <13onli9dk7mu926@corp.supernews.com> On Mon, 14 Jan 2008 12:08:52 -0800, Paul Rubin wrote: > aspineux writes: >> Yes, I missed 'get' and 'setdefault' are functions :-) Then why not >> some new semantic >> >> d.get('a', f()) --> d['a', f()] >> d.setdefault('a', f()) --> d['a'=f()] >> >> Is is a good idea enough to change the python semantic ? Or simply is >> it a good idea ? > > Changing python semantics for something like this is nuts. Allowing > passing a callable (sort of like re.sub allows) makes a certain amount > of sense: > > d.get('a', default=f) But how can Python determine when you want the result to be *the callable* and when you want it to be *the result of calling the callable*? Functions and other callables are first-class objects, and it is quite reasonable to have something like this: map = {'a': Aclass, 'b': Bclass, 'c': Cclass} class_ = map.get(astring, default=Zclass) The result I want is the class, not the result of calling the class (which would be an instance). If I wanted the other semantics, I'd be using defaultdict instead. -- Steven From bignose+hates-spam at benfinney.id.au Mon Jan 14 19:28:47 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jan 2008 11:28:47 +1100 Subject: module naming conventions References: <7f39199a-3334-4bcc-a424-5102f042ed01@1g2000hsl.googlegroups.com> <87zlv8dnya.fsf@benfinney.id.au> <6a53a14a-8f7c-4b6b-986f-48c7698f679f@v29g2000hsf.googlegroups.com> Message-ID: <8763xwdj9c.fsf@benfinney.id.au> grackle writes: > I do use packages. I mentioned the Java naming conventions because > they were my first thought for solving the problem of name clashes, > and they work well in some non-Java languages. They don't apply well > to Python, since every top-level module has a unique identity that > can only be specified on one source path. If two libraries use the > same top-level module name, they can't be used together in the same > program without modifying their source code. What do you mean by "top-level module", and "the same top-level name"? Do you mean "the same fully-qualified name"? If two modules are in separate places in the hierarchy, they will have different fully-qualified names. ===== $ find foo/ -name '*.py' foo/__init__.py foo/spam.py foo/bar/__init__.py foo/bar/spam.py foo/baz/__init__.py foo/baz/spam.py ===== ===== eggs.py ===== import foo.spam import foo.bar.spam import foo.baz.spam # ... ===== > mycompany_mymodulename was just the first solution I thought of that > seemed practical. The mycompany_ prefix protects me from name clashes > with useful modules I might acquire from elsewhere. Ah, I see; you're referring to a worldwide package namespace, enforced by the language. AFAIK there's no such thing in Python. > Of course, the best convention is probably the predominant one, and > that's my question: What is the standard way of naming Python > packages? Release your package as free software on the Cheeseshop . If the name you want is already taken, pick one that will help users distinguish yours from the existing one. -- \ "If you do not trust the source do not use this program." | `\ ?Microsoft Vista security dialogue | _o__) | Ben Finney From Programus at gmail.com Wed Jan 23 22:01:05 2008 From: Programus at gmail.com (programus) Date: Wed, 23 Jan 2008 19:01:05 -0800 (PST) Subject: Removing objects References: <20a06a46-d7ca-44dd-8ae7-3c6bceb70fc1@q77g2000hsh.googlegroups.com> Message-ID: <92564557-f044-4117-8dc4-f88b79ff4d4a@s19g2000prg.googlegroups.com> On Jan 23, 2:59 pm, bladedpeng... at gmail.com wrote: > I am writing a game, and it must keep a list of objects. I've been > representing this as a list, but I need an object to be able to remove > itself. It doesn't know it's own index. If I tried to make each object > keep track of it's own index, it would be invalidated when any object > with a lower index was deleted. The error was that when I called > list.remove(self), it just removed the first thing in hte list with > the same type as what I wanted, rather than the object I wanted. The > objects have no identifying charachteristics, other than thier > location in memory > > So my question: How do I look something up in a list by it's location > in memory? does python even support pointers? > > Is there a better way? How about using pygame.sprite? ( http://www.pygame.org/docs/ref/sprite.html ) The class pygame.sprite.Sprite has a kill() function, which can remove itself from all groups that contains it. (A group is just like a list. Just see pygame.sprite.Group) And here is a short tutorial about this. http://www.pygame.org/docs/tut/SpriteIntro.html From bronger at physik.rwth-aachen.de Sat Jan 12 07:26:42 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 12 Jan 2008 13:26:42 +0100 Subject: Is unicode.lower() locale-independent? References: Message-ID: <871w8ni60t.fsf@physik.rwth-aachen.de> Hall?chen! Fredrik Lundh writes: > Robert Kern wrote: > >>> However it appears from your bug ticket that you have a much >>> narrower problem (case-shifting a small known list of English >>> words like VOID) and can work around it by writing your own >>> locale-independent casing functions. Do you still need to find >>> out whether Python unicode casings are locale-dependent? >> >> I would still like to know. There are other places where .lower() >> is used in numpy, not to mention the rest of my code. > > "lower" uses the informative case mappings provided by the Unicode > character database; see > > http://www.unicode.org/Public/4.1.0/ucd/UCD.html > > afaik, changing the locale has no influence whatsoever on Python's > Unicode subsystem. Slightly off-topic because it's not part of the Unicode subsystem, but I was once irritated that the none-breaking space (codepoint xa0 I think) was included into string.whitespace. I cannot reproduce it on my current system anymore, but I was pretty sure it occured with a fr_FR.UTF-8 locale. Is this possible? And who is to blame, or must my program cope with such things? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From gagsl-py2 at yahoo.com.ar Wed Jan 30 09:27:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jan 2008 06:27:29 -0800 (PST) Subject: Module/package hierarchy and its separation from file structure References: <874pd49qjl.fsf@benfinney.id.au> <0a285e6e-a3a9-4be9-ae59-4cb7547ffa3a@q21g2000hsa.googlegroups.com> <13q10njnbffkceb@corp.supernews.com> Message-ID: <0c1095b9-3e36-4151-93b8-24f8cd9fbee3@v17g2000hsa.googlegroups.com> On 30 ene, 12:00, Steven D'Aprano wrote: > I call that a bug in the inspect module. In fact, looking at the source > for the findsource() function, I can see no fewer than two bugs, just in > the way it handles classes: > > (1) it assumes that the only way to create a class is with a class > statement, which is wrong; and > > (2) it assumes that the first occurrence of "class " must be the > correct definition, which is also wrong. Yes, it's broken. But I'm afraid that's the only available thing to do. Python stores filename and line number information in code objects (only). If you have a reference to any code object (a method, a function, a traceback...) inspect can use it to retrieve that information. Once a class is defined, there is no code object attached to it. (The class statement is executed when the module is loaded and initialized, but that code object is discarded afterwards because it's not required anymore). If you *know* that a certain method is defined in a class, you can use it to find the real module. But in general, there is nothing to start with. I'm eagerly waiting for someone to come and say I'm wrong... -- Gabriel Genellina From larudwer at freenet.de Mon Jan 7 15:51:53 2008 From: larudwer at freenet.de (Ruediger) Date: Mon, 07 Jan 2008 21:51:53 +0100 Subject: Killing worker threads References: <8a6b8e350801060548m6f39594che1207cc5bc4b6487@mail.gmail.com> Message-ID: maybe following recipe from activestate may be usefull. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 http://sebulba.wikispaces.com/recipe+thread2 From boblatest at yahoo.com Mon Jan 14 07:46:48 2008 From: boblatest at yahoo.com (Robert Latest) Date: 14 Jan 2008 12:46:48 GMT Subject: encrypting python modules References: <47873a78$0$85785$e4fe514c@news.xs4all.nl> <13og1dbe4qcfs2b@corp.supernews.com> <478b220e$0$85788$e4fe514c@news.xs4all.nl> <13omgn69naf1se8@corp.supernews.com> Message-ID: <5v13toF1kbqonU1@mid.dfncis.de> Steven D'Aprano wrote: > No, it's a serious question. You distribute Python code, and you're > worried that your users will modify the source code and then neglect to > mention it when they report bugs which they introduced. > > Before you build an elephant-proof fence around your house, it is quite > reasonable to ask whether or not there are actually elephants in your > neighbourhood. Depending on where you are, there are probably plenty. Recently I started hacking around in a GPLed Python app (GRAMPS, if anybody cares). This program has a built-in bug report feature which makes it easy to email bugs with associated stack trace etc. to the developers. Unfortunately the bug report window also automatically popped up even when stuff went wrong within my own broken code. For such a case it would be good if a software could somehow detect modifications of itself and its associated modules. And, contrary to the advice I gave elsethread, unfortunately it's impossible to just drop uncooperative customers when you develop GPL software ;-) robert From kyosohma at gmail.com Sat Jan 5 10:07:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 5 Jan 2008 09:07:13 -0600 Subject: Tabnanny errors when Migrating Python 2.4 code to 2.5 Message-ID: >> I'm using Windows XP, using IDLE (which was mentioned already) > in the context of editing/displaying code, not executing it. Does the > problem occur before or after you edit a file with IDLE? Actually, neither. I'm not editing the code. I open it in IDLE in 2.5 and attempt to run it through the Run menu "Run Module" menu item or by pressing F5. It immediately fails with a tabnanny error. If I run it from 2.4's IDLE, it works. >> and I >> downloaded the 2.5.1 exe/msi file from python.org to install it. > What you downloaded doesn't answer the question about how you > installed it. Do you still have your 2.4 installation? Yes, I use both 2.4 and 2.5 as I migrate from one to the other. I've attached a file that causes it consistently. On two systems with both 2.4 and 2.5 installed, it fails on line 206 when run from the IDLE included with 2.5. >> I have yet to find a simple one which exhibits the issue to post. It >> seems to happen to my complex files, not the simple ones. > So chop up a complex file ... > Have you inspected the failing files using a text editor that can > display tabs and spaces (e.g. PythonWin, TextPad)? I just used Notepad++ to inspect the file and it does indeed have tabs at line 206 rather than spaces. I take it that Python 2.5 is more sensitive to that than is 2.4? I program almost exclusively in IDLE as I'd read that this can happen in some text editors, but it seemed implied that it didn't if you used IDLE. At least, that's what I got from various Python books and the website: http://www.python.org/idle/doc/idlemain.html Anyway, thanks for the help. Mike -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: scrubber.py URL: From hexamorph at gmx.net Thu Jan 24 12:53:22 2008 From: hexamorph at gmx.net (Hexamorph) Date: Thu, 24 Jan 2008 18:53:22 +0100 Subject: piping into a python script In-Reply-To: References: Message-ID: <4798D092.9000308@gmx.net> Donn Ingle wrote: > Paddy wrote: >> fileinput is set to process each file a line at a time unfortunately. > Wow. So there seems to be no solution to my OP. I'm amazed, I would have > thought a simple list of strings, one from stdin and one from the args, > would be easy to get. > > I *really* don't want to open each file, that would be insane. > > Perhaps I shall have to forgo the stdin stuff then, after all. > Hi! I'm not sure if I completely get what you want, but what's about this: #!/usr/bin/python import sys filelist = [] with_stdin=0 if len(sys.argv) > 1: for file in sys.argv[1:]: if file == "-": with_stdin=1 continue filelist.append(file) else: with_stdin=1 if with_stdin: for file in sys.stdin: filelist.append(file) for file in filelist: print "Processing file: %s" % file It's a bit clumsy, but seems to do what I guess you want. HTH From steve at REMOVE-THIS-cybersource.com.au Wed Jan 23 17:00:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Jan 2008 22:00:16 -0000 Subject: pairs from a list References: <4idlj.14026$k15.6829@trnddc06> <6ba85a53-885f-47c1-9189-bfc0cd638579@i29g2000prf.googlegroups.com> <3f0163e5-6c5f-41b4-a67c-54a4a9244ba8@s12g2000prg.googlegroups.com> <24SdnaCXzLZC7AranZ2dnUVZ_v2pnZ2d@rcn.net> Message-ID: <13pfe7g5j8ek665@corp.supernews.com> On Wed, 23 Jan 2008 11:57:05 -0500, Alan G Isaac wrote: > Steven D'Aprano wrote: >> In fact, "fastest" isn't even a meaningful attribute. Does it mean: >> >> * the worst-case is fastest >> * the best-case is fastest >> * the average-case is fastest >> * fastest on typical data >> * all of the above > > > I confess that it did not occur to me that there might be an interesting > distinction among these cases for the question of how to get sequential > pairs from a list. How would one draw these distinctions in this case? Well, in this *specific* case I don't think they're terribly interesting because your problem is so simple. Best-case will, presumably, occur when the list is empty. Worst-case will occur if somebody passes a non- terminating iterator to your code (although that depends on the nature of your solution and how you are using it). But in the broader context of optimizing, these distinctions are very important. For example, Quicksort is very fast on randomly ordered data, but terribly slow on data which is already sorted: about as slow as Bubblesort. Mergesort's best-case isn't as fast as Quicksort's best-case, but it's worst-case behaviour is much, much better. And both Quicksort and Mergesort are complex enough that a simpler, slower algorithm like Shell Sort will be significantly faster for small data sets. But I'm sure you already know all this, I'm just mentioning it for the benefit of anybody else reading who still thinks that a generic "what's the fastest way" type question is meaningful. -- Steven From paddy3118 at googlemail.com Thu Jan 24 10:46:24 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 24 Jan 2008 07:46:24 -0800 (PST) Subject: piping into a python script References: <5vrovvF1njt09U6@mid.uni-berlin.de> Message-ID: <77bf0ea2-5e7d-4cd0-8692-319b85a97d65@v17g2000hsa.googlegroups.com> On Jan 24, 3:25 pm, Marc 'BlackJack' Rintsch wrote: > On Thu, 24 Jan 2008 17:17:25 +0200, Donn Ingle wrote: > > Given these two examples: > > 1. > > ./fui.py *.py > > 2. > > ls *.py | ./fui.py > > > How can I capture a list of the arguments? > > I need to get all the strings (file or dir names) passed via the normal > > command line and any that may come from a pipe. > > > There is a third case: > > 3. > > ls *.jpg | ./fui.py *.png > > Where I would be gathering strings from two places. > > > I am trying to write a command-line friendly tool that can be used in > > traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. > > > I have tried: > > 1. pipedIn = sys.stdin.readlines() > > Works fine for example 2, but example 1 goes into a 'wait for input' mode > > and that's no good. Is there a way to tell when no input is coming from a > > pipe at all? > > Usually Linux tools that can get the data from command line or files treat > a single - as file name special with the meaning of: read from stdin. > > So the interface if `fui.py` would be: > > 1. ./fui.py *.a > 2. ls *.a | ./fui.py - > 3. ls *.a | ./fui.py *.b - > > Ciao, > Marc 'BlackJack' Rintsch If X.a X.b Y.a Y.b are all files whose contents are to be processed then To process all files: ./fui.py *.a *.b Or: ./fui.py `ls *.a *.b` To process one file from a pipe unix usually does: cat X.a | ./fui.py - To get the filenames from stdin would usually need a command line switch telling fui.py to read a file *list* from stdin. For verilog simulators for example you have the -f switch that says insert further command line arguments from the file name in the next argument, so you could do: ls *.a | ./fui.py -f - *.b For equivalent functionality to my first example. - Paddy. From jura.grozni at gmail.com Mon Jan 21 18:34:52 2008 From: jura.grozni at gmail.com (azrael) Date: Mon, 21 Jan 2008 15:34:52 -0800 (PST) Subject: constructor question References: <758a6b15-9c4d-4c14-82ed-d76be2be0192@21g2000hsj.googlegroups.com> Message-ID: <11dc48f6-74e2-44cf-946c-dfd648264e4b@v46g2000hsv.googlegroups.com> 5 days ago I looked at it and didn't take a notice. thnx, this helped On Jan 22, 12:10?am, TeroV wrote: > azrael wrote: > > lets supose i have a object > > >>>> class a: > >>>> ? __init__(self,b): > >>>> ? ? ? ?self.b=b > > >>>> object=a(2) > > > how can I bind the object with "print". I supose that this should be > > possible with a constructor. but I don't know how. > > >>>> print a > > 2 > > > Something like this > > > Thnx > > Is it that you want to print an object, and customize what is printed? > __str__ method is what you need, seehttp://docs.python.org/ref/customization.html > > -- > Tero From casey at rodarmor.com Thu Jan 17 03:58:38 2008 From: casey at rodarmor.com (Casey Rodarmor) Date: Thu, 17 Jan 2008 00:58:38 -0800 Subject: Stop tab-completing empty lines! Message-ID: Hi everybody, I have the following in my python startup file: import readline, rlcompleter readline.parse_and_bind("tab: complete") This lets me tab complete identifiers in the interpreter beautifully, but there's a tiny problem... If I'm sitting at the beginning of a blank line and just want a tab, it tries to tab complete, which kind of a pain. -=SIMULATED PYTHON PROMPT=- >>> def mega_awesome_function(cool_stuff, **some_sweet_kwargs): ... X (The X is where I press tab and get super annoyed) I could just rebind the key, but i like tab ;-) Any suggestions? Best regards, Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Mon Jan 14 10:15:19 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 14 Jan 2008 16:15:19 +0100 Subject: __init__ explanation please References: <47895d25$0$30708$4c368faf@roadrunner.com> <20080113104641.GN75977@nexus.in-nomine.org> <478b73a2$0$25384$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <87myr8v3p4.fsf@mulj.homelinux.net> Wildemar Wildenburger writes: > Jeroen Ruigrok van der Werven wrote: >> To restate it more correctly: __init__ is akin to a constructor. >> > No. See Hrvoje Niksic's reply (and Ben Finney's to which it was a > reply). > > __init__() /initializes/ an instance (automatically after > creation). It is called, /after/ the instance has been constructed I don't understand the purpose of this "correction". After all, __init__ *is* the closest equivalent to what other languages would call a constructor. Take C++ and Java, the two most popular OO languages in existence. Their constructors also "initialize" an instance -- the actual allocation is left to the caller (new or stack in C++) or to the garbage collector. They even share with Python the convention of not returning the constructed value, they operate purely on side effect, just like Python's __init__. And yet, no one says that they are somehow not constructors because of that. Wikipedia calls the constructor "a special method used in object oriented programming which puts the object's members into a valid state." Again, exactly what __init__ does. From rw at smsnet.pl Tue Jan 29 14:27:08 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 29 Jan 2008 20:27:08 +0100 Subject: Telnet Program References: <777d417c-6016-4a44-8d5e-8de6bf604e9a@e6g2000prf.googlegroups.com> Message-ID: <87zluo77qr.fsf@merkury.smsnet.pl> "paul.zorn at gmail.com" writes: > I am having some issues writing a telnet program, using telnetlib. I > am not sure if it is the telnet on the connections end or it is my > program. > > A little background, when I log in straight from the Linux Command > prompt. The only thing I get is a blinking cursor. Then I type in my > command 'FOO' enter then screen on the very next line returns 'OK', > Then automatically puts the blinking cursor on the next line. Then > when I want to quit the telnet session I hit CTRL+Z that takes me to > telnet> then i type quit. > > My Program currently looks like it connects. Because the last string > that I get back that is not blank says: "Logged in successfully". > > So my problem is that when I issue the command through tn.write("FOO > \n"). Then do a tn.read_until('OK\n', 10). It gets returned nothing. I > have also added tn.read_until('OK\n', 10).splitlines(). That is also > returned blank. > > I have tried various different newlines \n \r \r\n. All the > documentation for telnet program that I am logging into says, use > Carriage Return after each command. Nothing seems to get back the > data. I am not sure if the Python telnet is looking for more of true > command line like telnet>. Have you tried: tn.set_debuglevel(1) ? HTH, Rob From Moshe.Ben-Eliezer at audiocodes.com Mon Jan 14 02:57:21 2008 From: Moshe.Ben-Eliezer at audiocodes.com (Moshe Ben-Eliezer) Date: Mon, 14 Jan 2008 09:57:21 +0200 Subject: Return name of caller function? Message-ID: Hello there, Did someone help you with this problem? I would like to know the solution as well. Do you know how to do in on C (CPP) environment ? Thanks anyway. BR. Moshe. ________________________________ This email and any files transmitted with it are confidential material. They are intended solely for the use of the designated individual or entity to whom they are addressed. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, use, distribution or copying of this communication is strictly prohibited and may be unlawful. If you have received this email in error please immediately notify the sender and delete or destroy any copy of this message -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.hankin at gmail.com Sat Jan 5 06:21:37 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 5 Jan 2008 03:21:37 -0800 (PST) Subject: fastest method to choose a random element References: <55e58046-d94f-4252-8d43-8b46fd3ae8dd@e6g2000prf.googlegroups.com> Message-ID: <3aee60d1-47fe-4904-b648-0c8d5826850a@d21g2000prf.googlegroups.com> On Jan 4, 7:55?pm, c... at mailinator.com wrote: > ? Hello, > ? This is a question for the best method (in terms of performance > only) to choose a random element from a list among those that satisfy > a certain property. > > ? This is the setting: I need to pick from a list a random element > that satisfies a given property. All or none of the elements may have > the property. Most of the time, many of the elements will satisfy the > property, and the property is a bit expensive to evaluate. Chance of > having the property are uniform among elements. Here's some code that uses a cached random sorting of the list. It assumes you'll want more than one random element. It never calls 'prop' on the same element twice, and it's O(n) even when the elements that pass 'prop' are sparse. I hope this is useful to you! import random class RandomPicker(object): def __init__(self, seq, prop=lambda x:True): seq = list(seq) random.shuffle(seq) # Store with the item whether we've computed prop on it already. self.random_list = [(x, False) for x in seq] self.prop = prop def pick(self): for i, (x, p) in enumerate(self.random_list): if p or self.prop(x): if not p: # Record the fact that self.prop passed. self.random_list[i] = (x, True) # Chop off the items that prop failed on. self.random_list = self.random_list[i:] r = self.random_list # Instead of shuffling the whole list again, just insert # x back in the list randomly. Since the remaining elements # are randomly sorted already, this is ok. n = random.randint(0, len(r) - 1) r[0], r[n] = r[n], r[0] return x # Nothing in the list passes the 'prop' test. return None # Example: pick 100 odd integers from 0 to 1000. a = RandomPicker(xrange(1000), lambda x: x % 2 == 1) print [a.pick() for i in xrange(100)] -- Paul Hankin From rowen at cesmail.net Wed Jan 23 15:45:27 2008 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 23 Jan 2008 12:45:27 -0800 Subject: When is min(a, b) != min(b, a)? References: <13p9hdmh7c08abe@corp.supernews.com> Message-ID: In article , Christian Heimes wrote: > Grant Edwards wrote: > > In many applications (e.g. process control) propogating NaN > > values are way too useful to avoid. Avoiding NaN would make a > > lot of code far more complicated than would using them. > > NaNs are very useful for experienced power users but they are very > confusing for newbies or developers without a numerical background. > > It's very easy to create an inf or nan in Python: > > inf = 1E+5000 > ninf = -inf > nan = inf * 0. > > 1E5000 creates a nan because it is *much* bigger than DBL_MAX (around > 1E+308). In fact it is even larger than LDBL_MAX (around 1E+4932). Isn't it safer to use float("inf"), float("-inf") and float("nan") to create the necessary items? -- Russell From rtw at freenet.co.uk Sun Jan 6 11:07:34 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sun, 06 Jan 2008 10:07:34 -0600 Subject: Cost of "unicode(s)" where s is Unicode References: <4780fb68$0$36341$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote in news:4780fb68$0$36341$742ec2ed at news.sonic.net in comp.lang.python: > Does > > text = unicode(text) > > make a copy of a Unicode string, or is that essentially a > free operation if the input is already Unicode? > > John Nagle > http://docs.python.org/lib/built-in-funcs.html#l2h-78 ... More precisely, if object is a Unicode string or subclass it will return that Unicode string without any additional decoding applied. ... Rob. -- http://www.victim-prime.dsl.pipex.com/ From python.list at tim.thechases.com Wed Jan 23 11:15:15 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 23 Jan 2008 10:15:15 -0600 Subject: Python CGI script and CSS style sheet In-Reply-To: References: Message-ID: <47976813.5090309@tim.thechases.com> > I'm working with a Python CGI script that I am trying to use with an > external CSS (Cascading Style Sheet) and it is not reading it from the > web server. The script runs fine minus the CSS formatting. Does > anyone know if this will work within a Python CGI? It seems that line > 18 is not being read properly. One more thing. I tested this style > sheet with pure html code (no python script) and everything works > great. > > Listed below is a modified example. > > ++++++++++ > > 1 #!/usr/bin/python > 2 > 3 import cgi > 4 > 5 print "Content-type: text/html\n" The answer is "it depends". Mostly on the configuration of your web-server. Assuming you're serving out of a cgi-bin/ directory, you'd be referencing http://example.com/cgi-bin/foo.py If your webserver (apache, lighttpd, whatever) has been configured for this directory to return contents of non-executable items, your above code will reference http://example.com/cgi-bin/central.css and so you may be able to just drop the CSS file in that directory. However, I'm fairly certain that Apache can be (and often is) configured to mark folders like this as "execute only, no file-reading". If so, you'll likely get some sort of Denied message back if you fetch the CSS file via HTTP. A better way might be to reference the CSS file as "/media/central.css" 12 and then put it in a media folder which doesn't have the execute-only/no-read permission set. Another (less attractive) alternative is to have your CGI sniff the incoming request, so you can have both http://example.com/cgi-bin/foo.py http://example.com/cgi-bin/foo.py?file=css using the 'file' GET parameter to return the CSS file instead of your content. I'd consider this ugly unless deploy-anywhere is needed, in which case it's not so bad because the deployment is just the one .py file (and optionally an external CSS file that it reads and dumps). -tkc From dirk.collins at verizon.net Wed Jan 30 22:55:19 2008 From: dirk.collins at verizon.net (Dirk Collins) Date: Thu, 31 Jan 2008 03:55:19 GMT Subject: Why the HELL has nobody answered my question!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! References: Message-ID: "Blubaugh, David A." wrote: > I do not understand why no one has answered the following question: > Has anybody worked with Gene Expression Programming???? Not me, and I'm not expecting too. In addition, I'm not actually trying to figure out if anyone else is working with Gene Expression Programming because: 1) I'm busy at the moment trying to improve my python for other reasons... and... 2) I'm not sure whether Gene Expression Programming is a good idea. Re, Dirk From arnodel at googlemail.com Fri Jan 4 12:37:41 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 4 Jan 2008 09:37:41 -0800 (PST) Subject: Details about pythons set implementation References: <87bq818wbt.fsf@mulj.homelinux.net> Message-ID: <7018ca69-d20e-43eb-9c36-bda177ebe7cf@e4g2000hsg.googlegroups.com> On Jan 4, 5:08?pm, Sion Arrowsmith wrote: [...] > But the real killer is that requirement for a std::set is that > T::operator< exists. Which means, for instance, that you can't > have a set of complex numbers.... This is really OT but IIRC, std::set is actually std::set< T, std::less > So make your own less_complex() function (for example, use lexicographic order), std::set should give you a set of complex numbers (sorry if some syntax is incorrect I haven't done any C++ for a while :) -- Arnaud From arnodel at googlemail.com Sun Jan 27 11:14:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 27 Jan 2008 16:14:19 +0000 Subject: Python self-evaluating strings Message-ID: <1BEEBF03-1A38-4745-B08B-DCA3106D1CC5@gmail.com> Hi all, An earlier post today got me thinking about "quines" (programs that output themselves) in Python. I tried to find some on the web but didn't find many ([1]). In particular I didn't find any that corresponded to my instinctive (LISP-induced, probably) criterion: def self_evaluating(s): "Return True if string s evaluates to itself" return s == eval(s) Here is the result of my efforts so far: 1. Starting from the classic idea (lambda x:x%x)('lambda x:x%x') I got the following v=(lambda x:x%('"''""'+x+'"''""'))("""(lambda x:x%%('"''""'+x+'"''""')) (%s)""") 2. (Given that if s is a nonempty string, s*2 is a longer string). Starting from the idea "%s %s" % (("%s %s",)*2) I got the following u="\"%s\" %% ((r\"%s\",)*2)" % ((r"\"%s\" %% ((r\"%s\",)*2)",)*2) Most of my problems in creating these 2 was with finding a suitable way of quoting strings that propagates well. Both u and v are one- liners. I'm hoping for no funky line wrapping here. Note: I'm not quoting the string as it makes no difference since they evaluate to themselves:) I'd like to know if anyone on the list has indulged in this time- bending/mind-wasting activity before. If so, it would be nice to create a list of such expressions. Quining's-better-than-ironing'ly yours -- Arnaud [1] http://www.nyx.net/~gthompso/self_pyth.txt From deets at nospam.web.de Sat Jan 12 08:18:32 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 12 Jan 2008 14:18:32 +0100 Subject: upload file and estimation time In-Reply-To: References: Message-ID: <5urt1aF1ivnefU1@mid.uni-berlin.de> whatazor schrieb: > Hi all, > unseccsefully, I try to analyze this problem. If I can only work on > the client size, how can I create a module that calculate the upload > time of a file, so the time for finish it? i can start with ftp > protocol and after extend this logic for my requirements. All you need to to is to - count the number of bytes to transfer, U - count the bytes already transfered, u - measure the time since the upload, t Then the ETA is eta = (u / t) * (U - u) Using the ftp-lib, you best pass a file-wrapper that overload the read-method to accumulate the read bytes to yield u. Diez From berlin.brown at gmail.com Tue Jan 15 20:33:36 2008 From: berlin.brown at gmail.com (BerlinBrown) Date: Tue, 15 Jan 2008 17:33:36 -0800 (PST) Subject: Is str/unicode.encode supposed to work? with replace/ignore Message-ID: With this code, ignore/replace still generate an error # Encode to simple ascii format. field.full_content = field.full_content.encode('ascii', 'replace') Error: [0/1] 'ascii' codec can't decode byte 0xe2 in position 14317: ordinal not in ran ge(128) The document in question; is a wikipedia document. I believe they use latin-1 unicode or something similar. I thought replace and ignore were supposed to replace and ignore? From karthik3186 at gmail.com Thu Jan 17 03:41:33 2008 From: karthik3186 at gmail.com (Karthik) Date: Thu, 17 Jan 2008 14:11:33 +0530 Subject: Replace stop words (remove words from a string) In-Reply-To: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> References: <3501a850-f351-437b-8817-ec49ecf006cf@m34g2000hsb.googlegroups.com> Message-ID: <01be01c858e4$c6b8b280$542a1780$@com> How about - for s in stoplist: string.replace(mystr, s, "") Hope this should work. -----Original Message----- From: python-list-bounces+karthik3186=gmail.com at python.org [mailto:python-list-bounces+karthik3186=gmail.com at python.org] On Behalf Of BerlinBrown Sent: Thursday, January 17, 2008 1:55 PM To: python-list at python.org Subject: Replace stop words (remove words from a string) if I have an array of "stop" words, and I want to replace those values with something else; in a string, how would I go about doing this. I have this code that splits the string and then does a difference but I think there is an easier approach: E.g. mystr = kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjkkkkjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsldf sd; if I have an array stop_list = [ "[BAD]", "[BAD2]" ] I want to replace the values in that list with a zero length string. I had this before, but I don't want to use this approach; I don't want to use the split. line_list = line.lower().split() res = list(set(keywords_list).difference(set(ENTITY_IGNORE_LIST))) -- http://mail.python.org/mailman/listinfo/python-list From ss.datics at gmail.com Fri Jan 25 17:21:07 2008 From: ss.datics at gmail.com (DATICS2008) Date: Fri, 25 Jan 2008 14:21:07 -0800 (PST) Subject: CFP: DATICS 2008 - Design, Analysis and Tools for Integrated Circuits and Systems Message-ID: <1b41b443-5d1a-466f-b904-b48ff2769adf@v46g2000hsv.googlegroups.com> Apologies for any multiple copies received. We would appreciate it if you could distribute the following call for papers to any relevant mailing lists you know of. CALL FOR PAPERS =========================================================== Special Session: Design, Analysis and Tools for Integrated Circuits and Systems DATICS 2008 July 22-24, 2008 (Crete Island, Greece) http://digilander.libero.it/systemcfl/datics =========================================================== Aims and Scope -------------------------- The main target of the Special Session: DATICS 2008 of the WSEAS CSCC multi-conference (http://www.wseas.org/conferences/2008/greece/icc/) is to bring together software/hardware engineering researchers, computer scientists, practitioners and people from industry to exchange theories, ideas, techniques and experiences related to all areas of design, analysis and tools for integrated circuits (e.g. digital, analog and mixed-signal circuits) and systems (e.g. real-time, hybrid and embedded systems). The special session also focuses on the field of formal methods and low power design methodologies for integrated circuits. Topics ---------- Topics of interest include, but are not limited to, the following: * digital, analog, mixed-signal designs and test * RF design and test * design-for-testability and built-in self test methodologies * reconfigurable system design * high-level synthesis * EDA tools for design, testing and verification * low power design methodologies * network and system on-a-chip * application-specific SoCs * specification languages: SystemC, SystemVerilog and UML * all areas of modelling, simulation and verification * formal methods and formalisms (e.g. process algebras, petri-nets, automaton theory and BDDs) * real-time, hybrid and embedded systems * software engineering (including real-time Java, real-time UML and performance metrics) Industrial Collaborators: ----------------------------------- DATICS 2008 is partnered with: * CEOL: Centre for Efficiency-Oriented Languages "Towards improved software timing", University College Cork, Ireland ( http://www.ceol.ucc.ie) * International Software and Productivity Engineering Institute, USA (http://www.intspei.com ) * Intelligent Support Ltd., United Kingdom (http://www.isupport- ltd.co.uk) * Solari, Hong Kong ( http://www.solari-hk.com) * Minteos, Italy (http://www.minteos.com) * M.O.S.T., Italy (http://www.most.it) Technical Program Committee: ---------------------------------------------- * Prof. Vladimir Hahanov, Kharkov National University of Radio Electronics, Ukraine * Prof. Paolo Prinetto, Politecnico di Torino, Italy * Prof. Alberto Macii, Politecnico di Torino, Italy * Prof. Joongho Choi, University of Seoul, South Korea * Prof. Wei Li, Fudan University, China * Prof. Michel Schellekens, University College Cork, Ireland * Prof. Franco Fummi, University of Verona, Italy * Prof. Jun-Dong Cho, Sung Kyun Kwan University, South Korea * Dr. Emanuel Popovici, University College Cork, Ireland * Dr. Jong-Kug Seon, Telemetrics Lab., LG Industrial Systems Co. Ltd., South Korea * Dr. Umberto Rossi, STMicroelectronics, Italy * Dr. Graziano Pravadelli, University of Verona, Italy * Dr. Vladimir Pavlov, International Software and Productivity Engineering Institute, USA * Dr. Jinfeng Huang, Philips & LiteOn Digital Solutions Netherlands, Advanced Research Centre, The Netherlands * Dr. Thierry Vallee, Georgia Southern University, Statesboro, Georgia, USA * Dr. Menouer Boubekeur, University College Cork, Ireland * Dr. Ana Sokolova, University of Salzburg, Austria * Dr. Sergio Almerares, STMicroelectronics, Italy * Ajay Patel (Director), Intelligent Support Ltd, United Kingdom * Monica Donno (Director), Minteos, Italy * Alessandro Carlo (Manager), Research and Development Centre of FIAT, Italy * Yui Fai Lam (Manager), Microsystems Packaging Institute, Hong Kong University of Science and Technology, Hong Kong Important Dates --------------------------- March 31, 2008: Deadline for submission of completed papers May 1, 2008: Notification of acceptance/rejection to authors Please visit our web-site for further information on the hosting conference of DATICS, submission guidelines, proceedings and publications and international technical reviewers. Best regards, General Chair of DATICS: Dr. K.L. Man (University College Cork, Ireland) and Organising Committee Chair: Miss Maria O'Keeffe (University College Cork, Ireland) From bearophileHUGS at lycos.com Wed Jan 30 08:24:18 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jan 2008 05:24:18 -0800 (PST) Subject: comparing two lists, ndiff performance References: Message-ID: <421f51b9-868d-4e6a-aaf8-2df0802e4467@y5g2000hsf.googlegroups.com> Zbigniew Braniecki: > Is there a way to speed it up? Any easier way? Faster method? This problem is a bit messy. Maybe it's better to sidestep the problem, and not use a list, and create an object that wraps the list, so it always keeps an updated record of what changes are done... but you have to notify it if you change the objects it contains. Bye, bearophile From ctrachte at gmail.com Fri Jan 4 20:30:42 2008 From: ctrachte at gmail.com (infixum) Date: Fri, 4 Jan 2008 17:30:42 -0800 (PST) Subject: vim newb - indenting python comments Message-ID: I'm just starting to use vim. It has helped me do a lot of repetitive editing of Python files. One problem I have is that the >> indent in normal mode doesn't work when a line starts with the # character. Any idea what I'm doing wrong? Thanks in advance for your help. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jan 25 17:46:19 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 25 Jan 2008 23:46:19 +0100 Subject: Puzzled by behaviour of class with empty constructor References: <99b8e2ac-1c72-430a-9172-a809e169f96a@i12g2000prf.googlegroups.com> Message-ID: <5vv75rF1nt2o7U1@mid.individual.net> dbaston at gmail.com wrote: > print x.ends,y.ends,z.ends > ############# > Running the following code outputs: >>>> [(0, 2)] [(0, 2)] [(0, 2)] > > Can anyone explain this? Yes. You bound a single list to the name "ends" inside the class. This name is shared by all instances. If you want the instances to each have separate lists, delete the "ends" definition from class declaration and insert "self.ends = []" into __init__. I also suggest you to have a look at the tutorial. Regards, Bj?rn -- BOFH excuse #49: Bogon emissions From sjmachin at lexicon.net Sun Jan 20 19:23:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jan 2008 16:23:46 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> Message-ID: <930da860-87d7-4a37-89cf-5a21aa3c1bd1@e6g2000prf.googlegroups.com> On Jan 21, 11:00 am, pythonewbie wrote: > On 21 jan, 00:09, John Machin wrote: > > > > > On Jan 21, 8:58 am, pythonewbie wrote: > > > > I just would like to know if I would ALWAYS find the install directory > > > in sys.path[6] and site-packages directory in sys.path[7] on any Win32 > > > platform and sys.path[2] and site-packages directory in sys.path[6] on > > > any Linux platform. > > > > If the reply is : "YES you can be sure of it !" > > > No, you can't be sure of any such thing. In general in computing > > assuming a fixed position in a variable-length list is a nonsense. > > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > > (Intel)] on win32 > > Type "help", "copyright", "credits" or "license" for more information.>>> import sys > > >>> from pprint import pprint as pp > > >>> pp([(x, p) for x, p in enumerate(sys.path)]) > > > [(0, ''), > > (1, 'c:\\python25\\lib\\site-packages\\setuptools-0.6c3-py2.5.egg'), > > (2, 'C:\\WINDOWS\\system32\\python25.zip'), > > (3, 'c:\\python25\\DLLs'), > > (4, 'c:\\python25\\lib'), > > (5, 'c:\\python25\\lib\\plat-win'), > > (6, 'c:\\python25\\lib\\lib-tk'), > > (7, 'c:\\python25'), > > (8, 'c:\\python25\\lib\\site-packages'), > > (9, 'c:\\python25\\lib\\site-packages\\win32'), > > (10, 'c:\\python25\\lib\\site-packages\\win32\\lib'), > > (11, 'c:\\python25\\lib\\site-packages\\Pythonwin')] > > > Something like this might be more reliable: > > > >>> import sys, re > > >>> for p in sys.path: > > > ... m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p) > > ... if m: > > ... print m.group(1, 0) > > ... break > > ... else: > > ... raise Exception('Huh?') > > ... > > ('c:\\python25', 'c:\\python25\\lib\\site-packages') > > > > All would be great for me and I would be ready to create a script to > > > detect with a reliable manner the installation dir. et site-packages > > > dir. for all my Linux/Win32 Python apps. > > > You mentioned Python versions back to 2.1 earlier. However you > > evidently haven't bothered to start up Python 2.1 and look at > > sys.path: > > > C:\junk>\python21\python > > Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on > > win32 > > Type "copyright", "credits" or "license" for more information.>>> import sys; sys.path > > > ['', 'C:\\junk', 'C:\\python21\\DLLs', 'C:\\python21\\lib', 'C:\ > > \python21\\lib\\ > > plat-win', 'C:\\python21\\lib\\lib-tk', 'C:\\python21'] > > > Before you rush out and re-invent the wheel, have a look at this: > > >http://www.python.org/community/sigs/current/distutils-sig/ > > > You may like to re-ask your questions on the distutils mailing list. > > > HTH, > > John > > Hi John, > > Thanks for your help and suggestions. > > Your code is very interesting for the newbie that I am. > > But I have not understood your two last suggestions... > > As a newbie, I have asked usenet for help in order to get a easy/ > convenient way to get the site-packages directory, and the best reply > I obtained, was to use the function > distutils.sysconfig.get_python_lib(). > > This function is a really good way to avoid to re-invent the wheel to > get what I wanted ! > I am talking about your underlying goal "My goal is to verify if an/ several extension(s) are installed and to automatically install the missing ones on Linux or Win32." ... you may well find that there is at least one wheel for "automatically install". From hat at se-162.se.wtb.tue.nl Thu Jan 31 08:56:55 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 31 Jan 2008 14:56:55 +0100 Subject: Python noob SOS (any [former?] Perlheads out there?) References: <6099ab30-390d-4b38-bc8e-81ecb52e03a6@e25g2000prg.googlegroups.com> Message-ID: On 2008-01-30, grflanagan wrote: > On Jan 29, 5:39 pm, kj wrote: > For command line options I get a long way with this: > > [code python] > def _getargs(): > allargs = sys.argv[1:] > args = [] > kwargs = {} > key = None > while allargs: > arg = allargs.pop(0) > if arg.startswith('--'): > key, arg = arg.split('=', 1) > key = key[2:] > elif arg.startswith('-'): > key = arg[1:] > if not allargs or allargs[0].startswith('-'): > allargs.insert(0, 'yes') > continue > if key is None: > args.append(arg) > else: > kwargs[key] = arg > key = None > return args, kwargs > > ARGS, KWARGS = _getargs() > [/code] Have a look at getopt (old) or optparse (newer) packages in the Python library instead. Sincerely, Albert From aisaac at american.edu Wed Jan 23 14:33:18 2008 From: aisaac at american.edu (Alan G Isaac) Date: Wed, 23 Jan 2008 14:33:18 -0500 Subject: Python printing! In-Reply-To: References: Message-ID: SMALLp wrote: > Hy. How to use printer in python. http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html From andre.roberge at gmail.com Sat Jan 12 15:50:54 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sat, 12 Jan 2008 12:50:54 -0800 (PST) Subject: Great Python books for the beginner References: <1a4d8dae-4722-4a10-a638-ac1b2d85227a@i72g2000hsd.googlegroups.com> Message-ID: <306d22c4-b578-4df4-b01b-7a4d55070823@1g2000hsl.googlegroups.com> On Jan 12, 4:04 pm, Landon wrote: > One thing I wonder about is the examples these books use to teach the > concepts. I found myself really attached to K&R because the end of > section projects were utilities that I would find be able to find > useful in day to day work such as a version of wc and a program that > would take collapse all consecutive whitespace in a document into one > space. I could just use the projects from K&R, but I imagine a Python > book would have a better selection that highlight Python's abilities. > > On another note, I would prefer to have a paper book so I don't have > to keep switching back and forth between documents on my computer. You don't need to switch back and forth ... if you use Crunchy! http://code.google.com/p/crunchy To see it in action, http://showmedo.com/videos/video?name=1430000&fromSeriesID=143 (the third video in that series shows how to quickly get started using the official Python tutorial). Andr? From http Sat Jan 12 14:28:05 2008 From: http (Paul Rubin) Date: 12 Jan 2008 11:28:05 -0800 Subject: removeall() in list References: <7xlk6ww058.fsf@ruckus.brouhaha.com> <2bc707d7-717d-4d6d-b5df-e26f534f8d06@f47g2000hsd.googlegroups.com> <7xsl147xl9.fsf@ruckus.brouhaha.com> <567164de-6a62-4469-a63f-b656ef2570dc@f47g2000hsd.googlegroups.com> <7xd4s7c45n.fsf@ruckus.brouhaha.com> <7xmyrbby04.fsf@ruckus.brouhaha.com> <7109ac74-b5a5-4e76-aea5-f520c001b962@f47g2000hsd.googlegroups.com> <354c74f6-6e56-4e41-a686-56239aa4cea9@f47g2000hsd.googlegroups.com> <7x8x2uj3yb.fsf@ruckus.brouhaha.com> <0ad68aa8-735d-4cf0-b17a-d1f2be6af652@f47g2000hsd.googlegroups.com> <7x1w8mj27a.fsf@ruckus.brouhaha.com> Message-ID: <7x7iie3ku2.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > Will you engage with me over e-mail to discuss the Locker > implementation I'm developing? Aaron I really can't, sorry. I'm finding it hard enough to follow over the newsgroup. If you just have a single one of these lists, it's probably simplest to do what Frederik Lundh suggested. The other stuff we've discussed is mostly about how to organize having a lot of them. From martyb1 at earthlink.net Tue Jan 1 17:57:44 2008 From: martyb1 at earthlink.net (Marty) Date: Tue, 01 Jan 2008 17:57:44 -0500 Subject: Catching external program exceptions Message-ID: <25qdnZuc2dn0WOfanZ2dnUVZ_gWdnZ2d@wideopenwest.com> I need to catch exceptions thrown by programs started by the os.system function, as indicated by a non-zero return code (e.g. the mount utility). For example, if I get the following results in a bash shell: $mount test mount: can't find /home/marty/test in /etc/fstab or /etc/mtab then I want to catch the same exception from the corresponding os.system() call, i.e. "os.system('mount test')", but it doesn't work as expected: >>> import os, sys >>> try: os.system('mount test') ... except: print 'error' ... mount: can't find /home/marty/test in /etc/fstab or /etc/mtab 256 >>> I get the same results with popon, popen2, popen3, etc. Apparently these also work only when the program does not generate an exception. Is there any way to catch the return code. or if not, a workaround? From martin at v.loewis.de Thu Jan 17 15:35:38 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 Jan 2008 21:35:38 +0100 Subject: Hebrew in idle ans eclipse (Windows) In-Reply-To: <86ea4c94-f4b3-4bc3-9b2a-bc9b5c182264@i12g2000prf.googlegroups.com> References: <478ee0c0$0$4589$9b622d9e@news.freenet.de> <86ea4c94-f4b3-4bc3-9b2a-bc9b5c182264@i12g2000prf.googlegroups.com> Message-ID: <478FBC1A.4080201@v.loewis.de> > import pymssql > > con = > pymssql.connect(host='192.168.13.122',user='sa',password='',database='tempdb') > cur = con.cursor() > cur.execute('select firstname, lastname from [users]') > lines = cur.fetchall() > > print lines > > or > > print lines[0] > > 'lines' is a list containing tuples of 2 values, for firstname and > lastname. The names are Hebrew and their code looks different when I'm > runnig it from IDLE than when running it from Windows shell or > eclipse, as I described in my first post. Ok. Please understand that there are different ways to represent characters as bytes; these different ways are called "encodings". Please also understand that you have to make a choice of encoding every time you represent characters as bytes: if you read it from a database, and if you print it to a file or to the terminal. Please further understand that interpreting bytes in an encoding different from the one they were meant for results in a phenomenon called "moji-bake" (from Japanese, "ghost characters"). You get some text, but it makes no sense (or individual characters are incorrect). So you need to find out a) what the encoding is that your data have in MySQL b) what the encoding is that is used when printing in IDLE c) what the encoding is that is used when printing into a terminal window. b) and c) are different on Windows; the b) encoding is called the "ANSI code page", and c) is called the "OEM code page". What the specific choice is depends on your specific Windows version and local system settings. As for a: that's a choice somebody made when the database was created; I don't know how to figure out what encoding MySQL uses. In principle, rather than doing print lines[0] you should do print lines[0].decode("").encode("") when printing to the console. Furtenately, you can also write this as print lines[0].decode("") as Python will figure out the console encoding by itself, but it can't figure out the MySQL encoding (or atleast doesn't, the way you use MySQL). Regards, Martin From steve at REMOVE-THIS-cybersource.com.au Fri Jan 11 22:03:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jan 2008 03:03:06 -0000 Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <47852dd8$0$27994$426a74cc@news.free.fr> <13oattm5ijqvf58@corp.supernews.com> <4785d960$0$22237$426a74cc@news.free.fr> <13od12b23hfv772@corp.supernews.com> <5b035c91-72eb-4d88-b19b-e89470865c5b@i7g2000prf.googlegroups.com> Message-ID: <13ogbfasbcici1c@corp.supernews.com> On Fri, 11 Jan 2008 09:52:17 -0800, Paul Boddie wrote: > These days, I seriously doubt that anyone uses the term "interpreted" to > mean "parses the source text and works out what to do, over and over > again as the program runs". Given the way that people seem to use "interpreted" as a pejorative and a synonym for "slow", I don't doubt it one bit. Especially in management, where they might be making technical judgments on the basis of half- remembered Comp Sci 101 lessons from fifteen years earlier and vague buzzword-laden articles in trade magazines. -- Steven From MartinRinehart at gmail.com Mon Jan 7 11:06:24 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Mon, 7 Jan 2008 08:06:24 -0800 (PST) Subject: I'm searching for Python style guidelines References: <698e593e-5fef-4e37-a289-d23435ba89c9@l6g2000prm.googlegroups.com> Message-ID: Thank you both. Stupid me, went to Python.org and found Style Guidelines and thought that was the last word. Oh well. PEP 8 reminds me a lot of Sun's Java conventions, in ways I wish it didn't. The overall structure seems like a random list of topics and it omits a lot. For Java I went from Sun to other conventions to try to compile a meta-convention ( http://www.MartinRinehart.com/articles/code-conventions.html ). Here's just one of my questions: foo = [ 'some item, quite long', 'more items, all demanding there own line as they are not short', ... Where would you put the closing ']'? From dongie.agnir at gmail.com Thu Jan 10 08:05:53 2008 From: dongie.agnir at gmail.com (dongie.agnir at gmail.com) Date: Thu, 10 Jan 2008 05:05:53 -0800 (PST) Subject: Python too slow? References: <5a0af669-9460-4348-aacd-7a47d4f8114d@k2g2000hse.googlegroups.com> <8f99cb7e-5664-4ebb-b3fc-dd32124ea5f4@m77g2000hsc.googlegroups.com> Message-ID: On Jan 10, 3:00 am, Ant wrote: > On Jan 10, 12:04 pm, "dongie.ag... at gmail.com" > wrote: > > > For the most part, I agree with you, which is why I chose Python in > > the first place. I like quick development. Unfortunately, this is > > one of those cases where execution time is a factor. Who knows, maybe > > someone who's done camera vision with Python will come in and say it's > > just the algorithm in the example that needs work (I'm crossing my > > fingers that that's the case). > > It would probably be worth reposting your question with a different > subject line. Something along the lines of "Image/Video processing > performance in Python", and explaining what you actually want to > achieve. "Python too slow?" doesn't give enough information - clearly > Python is fast enough for many many tasks, since it is so widely used. > It also sounds like a troll - so many people who would actually be > able to assist you (such as the PIL, pygame and numpy/scipy > communities) may have ignored this thread. > > Cheers, > > -- > Ant. Thanks for the advice. I'll do that now. From gagsl-py2 at yahoo.com.ar Sun Jan 20 15:26:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 20 Jan 2008 18:26:14 -0200 Subject: Just for fun: Countdown numbers game solver References: <36a8f0a6-2a2b-4578-b04b-b3ab05be94a0@d21g2000prf.googlegroups.com> Message-ID: En Sun, 20 Jan 2008 18:06:57 -0200, escribi?: > Nice challenge! I came up with something like this: A nice solution too! -- Gabriel Genellina From jorgen.maillist at gmail.com Sat Jan 12 10:13:08 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Sat, 12 Jan 2008 16:13:08 +0100 Subject: where do my python files go in linux? In-Reply-To: <20080112113759.GJ75977@nexus.in-nomine.org> References: <11e49df10801120302g607aa983he999a1f473d79fc8@mail.gmail.com> <20080112113759.GJ75977@nexus.in-nomine.org> Message-ID: <11e49df10801120713w39992532tdbc97721e7ed845b@mail.gmail.com> Hi Jeroen, Thanks for the advice. > Personally I'd be loathe to put app.py in /usr/bin. This directory is normally > reserved for OS-specific binaries. For personal/system-extended stuff I'd use > /usr/local/bin or whatever your system mandates. (But hey, that's the typical > mentality difference between the BSD and Linux world it seems, so do with it > what you want.) I thought about that too. I just wonder why /usr/local/bin is always empty and every .deb I install from a source (if it's from Ubuntu or not) installs files in /usr/bin .. So I looked further and noticed that most python files do reside in /usr/share/{appname} > Normally you'd split up the bulk of the code into a module which gets > installed into site-packages and a piece of stand-alone front-end code which > imports the module and executes whatever you need to do and gets installed > into a typical PATH directory. I would agree but it is not a site package I am trying to distribute, but a wxPython application. I would not think my app belongs in the python site packages dir. Thanks a lot for the input! - Jorgen From asmodai at in-nomine.org Mon Jan 7 06:01:04 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 7 Jan 2008 12:01:04 +0100 Subject: python syntax In-Reply-To: <633886.19582.qm@web45510.mail.sp1.yahoo.com> References: <633886.19582.qm@web45510.mail.sp1.yahoo.com> Message-ID: <20080107110104.GD82115@nexus.in-nomine.org> -On [20080107 11:46], mpho raborife (mraborife at yahoo.com) wrote: >os.system("HCopy -T 1 -C" 'os.path.join(conf_dir, "/hcopy.conf")' "-S" >'os.path.join(list_dir, "hcopy_list.txt")') I would guess you would want this: os.system("HCopy -T 1 -C" + os.path.join(conf_dir, "/hcopy.conf") + "-S" + os.path.join(list_dir, "hcopy_list.txt")) But I'd personally not use such a contracted syntax, it makes detecting failure on any of the three function calls difficult. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ If I promise you the Moon and the Stars, would you believe it..? From deets at nospam.web.de Wed Jan 2 07:46:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Jan 2008 13:46:23 +0100 Subject: wxpython application ( problem ? ) References: <40fb61de-6a10-46ac-9edf-28f412bce3b5@e6g2000prf.googlegroups.com> <5u1asvF1fgr5bU2@mid.uni-berlin.de> <7cb975f6-e9a6-4527-bd84-2041aede197f@j20g2000hsi.googlegroups.com> Message-ID: <5u1fcvF1fqkc0U1@mid.uni-berlin.de> vedrandekovic at gmail.com wrote: > On 2 sij, 12:29, Marc 'BlackJack' Rintsch wrote: >> On Wed, 02 Jan 2008 03:24:56 -0800, vedrandekovic wrote: >> > Here is sample of my simple script with wxpython and modules: >> > subprocess,threading, directpython....... >> >> Are you accessing the GUI from threads? >> >> Ciao, >> Marc 'BlackJack' Rintsch > > > Hi again, > > yes, so what's the problem? It is the problem. It is usually not allowed to manipulate GUI-objects from any thread except the main-thread that runs the event-loop. All GUI-toolkits have guidelines how to cope with that, e.g. custom events in Qt3, or timers. This message indicates that WX has similar means: http://osdir.com/ml/python.matplotlib.general/2005-03/msg00208.html Diez From mail at timgolden.me.uk Wed Jan 23 04:55:08 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Jan 2008 09:55:08 +0000 Subject: what's wrong with the wmi.Terminate() method? In-Reply-To: References: Message-ID: <47970EFC.90206@timgolden.me.uk> thunder54007 at gmail.com wrote: [... snip same problem as reported to python-win32 ...] See my reply on python-win32. TJG From steve at REMOVE-THIS-cybersource.com.au Mon Jan 21 08:58:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Jan 2008 13:58:48 -0000 Subject: Sorting a list depending of the indexes of another sorted list References: <7d798282-fb67-4261-8836-196f39e88fb1@n20g2000hsh.googlegroups.com> Message-ID: <13p998o7mskm7e0@corp.supernews.com> On Mon, 21 Jan 2008 09:53:10 +0100, Peter Otten wrote: > Santiago Romero wrote: > >> I'm trying to sort both lists so that they end like this: >> >> preferences = [10, 20, 30] >> hosts = [ "mx1.domain.com", "mx2.domain.com", "anotherhost.domain.com" >> ] >> >> I want to sort hosts list depending on the numeric order of >> "preferences". > > The following relies on undocumented (I hope) behaviour: What bit are you suggesting is undocumented? >>>> preferences = [10, 30, 20] >>>> hosts = [ "mx1.domain.com", "anotherhost.domain.com", >... "mx2.domain.com"] >>>> hosts.sort(key=lambda x, p=iter(preferences).next: p()) >>>> preferences.sort() >>>> hosts > ['mx1.domain.com', 'mx2.domain.com', 'anotherhost.domain.com'] >>>> preferences > [10, 20, 30] Now if you wanted to claim it was opaque and confusing, I'd agree with you :-) Here's a function that uses the Decorate-Sort-Undecorate technique to sort one list by the contents of another: from sys import maxint _indices = xrange(maxint) def sorterDSU(alist, blist): """Return a copy of alist sorted by the contents of blist.""" assert len(alist) == len(blist) decorated = zip(blist, _indices, alist) decorated.sort() return [avalue for (bvalue, i, avalue) in decorated] Here's another version: def sorter(alist, blist): assert len(alist) == len(blist) table = sorted(range(len(alist)), key=blist.__getitem__) return [alist[i] for i in table] >>> alist = "John Eric Michael Graham Terry-J Terry-G".split() >>> blist = [5, 0, 4, 1, 3, 2] >>> sorter(alist, blist) ['Eric', 'Graham', 'Terry-G', 'Terry-J', 'Michael', 'John'] -- Steven From gavinlusby at googlemail.com Wed Jan 23 12:21:08 2008 From: gavinlusby at googlemail.com (Gavin Lusby) Date: Wed, 23 Jan 2008 17:21:08 -0000 Subject: Checking the existence of parsed variables Message-ID: <000001c85de4$59c3f400$0adea8c0@bp1.ad.bp.com> Hello all, I am regularly writing programs that parses ever changing lists of variables. The method I do it is by loading it in to a dictionary of the form: d['variable_name']=variable_value So when it comes to a method that uses a required set of variables I have to make tens of the following statements if d.has_key('swr'): swr = float(d['swr']) else: print 'ERROR: COREYTAB variable swr not specified'; iErr += 1 When I thought a pythonic way of doing it would be to use a variable variable.(sorry that sounds ridiculous) but it would work like this: _start_code_________________________________________________________________ ___ # make all input parameters equal the string of themselves type = 'type'; tabnum = 'tabnum'; coreyw = 'coreyw'; coreyow = 'coreyow' swc = 'swc'; swr = 'swr'; kro_swc = 'kro_swc'; krw_swr = 'krw_swr' coreyg = 'coreyg'; coreygo = 'coreygo'; sgi = 'sgi'; sgc = 'sgc' sgr = 'sgr'; kro_sgc = 'kro_sgc'; krg_swc = 'krg_swc' # error check parameters existence and if there, over-write their info # if there are integer values, then must remember to re-typecast them later for var in (type, tabnum, coreyw, coreyow, swc, swr, kro_swc, krw_swr, coreyg, coreygo, sgi, sgc, sgr, kro_sgc, krg_swc): if d.has_key(var): if isnumeric(d[var]): var = float(d[var]) else: var = d[var] else: print 'ERROR: getcorey() parameter '+str(var)+' not specified' iErr += 1 _end_code___________________________________________________________________ ___ Since this doesn't work, any other ideas out there? Many thanks in advance, Gavin -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Jan 17 10:55:56 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Jan 2008 16:55:56 +0100 Subject: Is this a bug, or is it me? References: Message-ID: cptnwillard wrote: > Hello all, > For some reason, the following does not work : > > > class C: > TYPES = [None] > DICT = {} > for Type in TYPES: > DICT.update((E,Type) for E in [1]) > >>>> NameError: global name 'Type' is not defined > > > What do you think? Is this a bug? Here is a simpler example: >>> class A: ... a = 42 ... list(a for _ in "a") ... Traceback (most recent call last): File "", line 1, in File "", line 3, in A File "", line 3, in NameError: global name 'a' is not defined The equivalent code using a list comprehension instead of the generator expression works without complaint: >>> class A: ... a = 42 ... [a for _ in "a"] ... >>> So it seems that Python gets puzzled by the extra scope introduced by the genexp, i. e. you are seeing an obscure variant of the following (expected) behaviour: >>> class B: ... a = 42 ... def f(): a ... f() ... Traceback (most recent call last): File "", line 1, in File "", line 4, in B File "", line 3, in f NameError: global name 'a' is not defined I think you should file a bug report, though making the genexp recognizing the class scope probably isn't worth the effort. Peter From nytrokiss at gmail.com Tue Jan 22 15:05:26 2008 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 22 Jan 2008 21:05:26 +0100 Subject: question In-Reply-To: <6760762.631391201031899339.JavaMail.root@hrndva-web18-z01> References: <6760762.631391201031899339.JavaMail.root@hrndva-web18-z01> Message-ID: <8a6b8e350801221205s723a6330te59e48389957a086@mail.gmail.com> Since you aren't familyer with classes i will keep this within the scope of functions... If you have code like this def a(): def b(): a+=1 Then you can only call function b when you are within function a James On Jan 22, 2008 8:58 PM, wrote: > I'm still learning Python and was wanting to get some thoughts on this. I apologize if this sounds ridiculous... I'm mainly asking it to gain some knowledge of what works better. The main question I have is if I had a lot of lists to choose from, what's the best way to write the code so I'm not wasting a lot of memory? I've attempted to list a few examples below to hopefully be a little clearer about my question. > > Lets say I was going to be pulling different data, depending on what the user entered. I was thinking I could create a function which contained various functions inside: > > def albumInfo(theBand): > def Rush(): > return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > > def Enchant(): > return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > > ... > > The only problem with the code above though is that I don't know how to call it, especially since if the user is entering a string, how would I convert that string into a function name? For example, if the user entered 'Rush', how would I call the appropriate function --> albumInfo(Rush()) > > But if I could somehow make that code work, is it a good way to do it? I'm assuming if the user entered 'Rush' that only the list in the Rush() function would be stored, ignoring the other functions inside the albumInfo() function? > > I then thought maybe just using a simple if/else statement might work like so: > > def albumInfo(theBand): > if theBand == 'Rush': > return ['Rush', 'Fly By Night', 'Caress of Steel', '2112', 'A Farewell to Kings', 'Hemispheres'] > elif theBand == 'Enchant': > return ['A Blueprint of the World', 'Wounded', 'Time Lost'] > ... > > Does anyone think this would be more efficient? > > I'm not familiar with how 'classes' work yet (still reading through my 'Core Python' book) but was curious if using a 'class' would be better suited for something like this? Since the user could possibly choose from 100 or more choices, I'd like to come up with something that's efficient as well as easy to read in the code. If anyone has time I'd love to hear your thoughts. > > Thanks. > > Jay > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com From rschroev_nospam_ml at fastmail.fm Thu Jan 17 13:14:38 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 17 Jan 2008 18:14:38 GMT Subject: Loop in a loop? In-Reply-To: References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: Sacred Heart schreef: > On Jan 17, 1:35 pm, cokofree... at gmail.com wrote: >> for i in zip(array1, array2): >> print i >> >> Although I take it you meant four d, the issue with this method is >> that once you hit the end of one array the rest of the other one is >> ignored. > > Yes, small typo there. > > Okey, so if my array1 is has 4 elements, and array2 has 6, it won't > loop trough the last 2 in array2? How do I make it do that? One solution is with map() instead if zip(). map() with None as the first argument works much like zip(), but it keeps looping if one of the lists is exhausted. When that happens, it uses None for those values: words = ['zero', 'one', 'two', 'three'] numbers = [0, 1, 2, 3, 4, 5, 6] for word, number in map(None, words, numbers): print word, number zero 0 one 1 two 2 three 3 None 4 None 5 None 6 -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From aahz at pythoncraft.com Sun Jan 6 12:53:21 2008 From: aahz at pythoncraft.com (Aahz) Date: 6 Jan 2008 09:53:21 -0800 Subject: Cost of "unicode(s)" where s is Unicode References: <4780fb68$0$36341$742ec2ed@news.sonic.net> <70b9f250-a7b5-423e-8395-d0c4215d2564@d70g2000hsb.googlegroups.com> Message-ID: In article <70b9f250-a7b5-423e-8395-d0c4215d2564 at d70g2000hsb.googlegroups.com>, JKPeck wrote: > >>>> u = u"abc" >>>> uu = unicode(u) >>>> u is uu >True >>>> s = "abc" >>>> ss = unicode(s) >>>> s is ss >False You uuencode Unicode? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Sorry, couldn't resist the alliteration From martin at marcher.name Tue Jan 8 05:04:33 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 08 Jan 2008 11:04:33 +0100 Subject: use fileinput to read a specific line References: Message-ID: jo3c wrote: > i need to read line 4 from a header file http://docs.python.org/lib/module-linecache.html ~/2delete $ cat data.txt L1 L2 L3 L4 ~/2delete $ python Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import linecache >>> linecache.getline("data.txt", 2) 'L2\n' >>> linecache.getline("data.txt", 5) '' >>> linecache.getline("data.txt", 1) 'L1\n' >>> -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From asmodai at in-nomine.org Sun Jan 13 05:46:41 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sun, 13 Jan 2008 11:46:41 +0100 Subject: __init__ explanation please In-Reply-To: <47895d25$0$30708$4c368faf@roadrunner.com> References: <47895d25$0$30708$4c368faf@roadrunner.com> Message-ID: <20080113104641.GN75977@nexus.in-nomine.org> -On [20080113 01:41], Erik Lind (elind at spamcop.net) wrote: >I'm new to Python, and OOP. I've read most of Mark Lutz's book and more >online and can write simple modules, but I still don't get when __init__ >needs to be used as opposed to creating a class instance by assignment. I personally tend to see __init__ or __new__ as equivalent to what other languages call a constructor. (And I am sure some people might disagree with that. ;)) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ The riddle master himself lost the key to his own riddles one day, and found it again at the bottom of his heart. From pydecker at gmail.com Thu Jan 24 18:12:28 2008 From: pydecker at gmail.com (Peter Decker) Date: Thu, 24 Jan 2008 17:12:28 -0600 Subject: Testing whether something is of type Exception In-Reply-To: <47991a8a$0$36353$742ec2ed@news.sonic.net> References: <47991a8a$0$36353$742ec2ed@news.sonic.net> Message-ID: On Jan 24, 2008 5:14 PM, John Nagle wrote: > How can I tell whether an object is of type Exception? > At least in Python 2.4, "Exception" is an old-style class, and > the "type" of Exception objects is "instance". > > Clearly "repr" knows; it returns: > isinstance(x, Exception) -- # p.d. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 16 09:11:31 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 Jan 2008 15:11:31 +0100 Subject: anti-spam policy for c.l.py? In-Reply-To: References: <08ed32c4-6230-4b14-9c31-4b94e0231cf2@c4g2000hsg.googlegroups.com> <478dee4e$0$28424$426a34cc@news.free.fr> Message-ID: <478e1068$0$27280$426a34cc@news.free.fr> Jeroen Ruigrok van der Werven a ?crit : > -On [20080116 12:51], Bruno Desthuilliers (bruno.42.desthuilliers at wtf.websiteburo.oops.com) wrote: >> Apart from checking posts headers and complaining about the relevant >> ISPs, there's not much you can do AFAIK. This is usenet, not a mailing-list. > > It is both actually. python-list at python.org is linked to comp.lang.python due > to a news gateway. Yes, I know - but the OP explicitely mentionned c.l.py (re-read the title), not the ML. From petr.jakes.tpc at gmail.com Fri Jan 25 14:43:40 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Fri, 25 Jan 2008 11:43:40 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application Message-ID: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> Hi, I am working with the Python 2.5 running on the command line version of Linux Ubuntu 7.04. This means NO X-windows, NO GTK/Gnome, NO computer mouse, on my machine (AMD Geode 500MHz CPU, VGA output). I would like to write some really light weighted GU interface. My concept is to have just few user screens (about 10) controlled via 4 or 5 HW buttons connected to the GPIO pins they are available on the motherboard (the HW design and the SW concept of reading this buttons is already solved). After some googling, I have found below mentioned can be usable, but first, I would like to ask here for your opinions/experiences/advices. Best regards Petr Jakes http://www.libsdl.org/ http://pyfltk.sourceforge.net/ http://www.pygame.org/news.html http://pyui.sourceforge.net/ http://pyglet.org/ From eproust at gmail.com Mon Jan 21 05:38:14 2008 From: eproust at gmail.com (pythonewbie) Date: Mon, 21 Jan 2008 02:38:14 -0800 (PST) Subject: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt References: <5vhjgcF1lr6bnU1@mid.uni-berlin.de> <5vhnheF1meri9U1@mid.uni-berlin.de> <92b30d4a-53b9-45ae-b900-7c8e793d43dd@q77g2000hsh.googlegroups.com> <5vi1r8F1mjs0rU1@mid.uni-berlin.de> <5360e13d-215d-4d3e-9930-daa6cddd996a@f10g2000hsf.googlegroups.com> <5vj79dF1m2nmlU1@mid.uni-berlin.de> Message-ID: <677d61a1-16be-40ae-8332-a5ff45ff8905@j78g2000hsd.googlegroups.com> On 21 jan, 10:34, "Diez B. Roggisch" wrote: > pythonewbie > > > > > Because the solution using distutils.sysconfig.get_python_lib() is > > very smart ! > > Depending on your goal. You said > > """ > My goal is to verify if an/several extension(s) are installed and to > automatically install the missing ones on Linux or Win32. > """ > > This goal can't be reached with only the site-packages - because I can > install packages somewhere else (matter of factly, this happens on debian > for example, they've split the install-dirs and created a bunch of dirs > under /usr/share) > > So having a method that gives you the installation root doesn't help much > here. > > Diez Diez, I repeat I am a newbie, so please don't be angry against me, if I say something stupid or if I propose a method not efficient. An easy way to get the absolute path of site-packages seems very useful to me, in order to check anything (all extensions available and not provided by sys.path, etc.) related to the files on the filesystem, if necessary. For the automatic installation of missing extensions (using admin rights), I think that it is not difficult to do it on both platforms... From siona at chiark.greenend.org.uk Wed Jan 9 12:16:21 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Jan 2008 17:16:21 +0000 (GMT) Subject: How to get memory size/usage of python object References: <935adc19-2391-4909-a675-cdad11479abb@p69g2000hsa.googlegroups.com> Message-ID: Santiago Romero wrote: > Is there a way to check the REAL size in memory of a python object? > > Something like > >> print sizeof(mylist) > [ ... ] Would you care to precisely define "REAL size" first? Consider: >>> atuple = (1, 2) >>> mylist = [(0, 0), atuple] Should sizeof(mylist) include sizeof(atuple) ? >>> del atuple What about now, when mylist has the only reference to the (1, 2) object that also used to be referred to as atuple? -- \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 jarausch at igpm.rwth-aachen.de Fri Jan 25 04:12:02 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Fri, 25 Jan 2008 10:12:02 +0100 Subject: global/local variables In-Reply-To: <4d161c89-7e33-4ddc-851f-bc9beb537229@q21g2000hsa.googlegroups.com> References: <13pia51grjfo2ed@corp.supernews.com> <4d161c89-7e33-4ddc-851f-bc9beb537229@q21g2000hsa.googlegroups.com> Message-ID: <5vtnf3F1nen4hU1@mid.dfncis.de> Tim Rau wrote: > I'm sorry: I forgot to say what my problem was. Python seems to think > that nextID is a local, and complains that it can't find it. THis is > not the full text of the function, just the level that is causing > errors. the lack of : on the if is a transcription error. > Traceback (most recent call last): > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > \sandbox.py", line 248, in > thing.step() > File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox > \sandbox.py", line 112, in step > allThings[len(allThings)-1].id = nextID > UnboundLocalError: local variable 'nextID' referenced before > assignment But in the next line in the same function you say nextID+= 1 Since there is an assignment to nextID in the same function without a global statement, you tell Python, that nextID is a local variable. Note: Assignment (anywhere in a function) is a local definition unless there is a global statement in this function > I want to know why it says 'local variable' it never had a problem > when just allThings was in there. > > as for the objection to global variable: If I didn't make them global, > I'd make them part of a singleton class called gameVars that would get > passed everywhere. It's unlikely that they'll get mixed in with > anyhting else, as they fulfill a unique function. Also, I think it's > more convenient, and I am, after all, my own employer when it comes to > programming. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From radiosrfun at radiosrfun.com Sat Jan 12 10:35:38 2008 From: radiosrfun at radiosrfun.com (radiosrfun) Date: Sat, 12 Jan 2008 10:35:38 -0500 Subject: *** AMERICAN BASTARDS DESERVE TO BE RAPED *** References: <58ogo3pmecob8al6hvnb67rts0jo7j4qf1@4ax.com> <478865b1$0$26840$ecde5a14@news.coretel.net> <91hho3tr56dpsfqsav4lnr8sl944bbrviv@4ax.com> Message-ID: <4788de48$0$26887$ecde5a14@news.coretel.net> "default" wrote in message news:91hho3tr56dpsfqsav4lnr8sl944bbrviv at 4ax.com... > On Sat, 12 Jan 2008 02:01:09 -0500, "radiosrfun" > wrote: > >>I WISH - that the President and Congress of this country would shut off >>ALL >>foreign aid. > > Ditto that. > > Israel is the chief beneficiary of our foreign aid largesse. Some 8 > billion dollars annually. What doesn't find its way into politicians > pockets goes to pay for a military that is winning us a lot of new > friends in the Arab world. > > We pay Egypt ~ 2 billion a year in extortion to keep them from > attacking Israel. > > The actually amount Israel receives is not really known to the public. > The official numbers read something like 3 billion in aid, and another > 5 billion in guaranteed loans - which are turned into grants year > after year. This is money we borrow so there's an additional interest > burden. > > Actually when you talk about shutting off "foreign aid" you may be > making thermate's point for him. > -- Well - the first cup of coffee hasn't exactly kicked in yet - but I believe I know what you're saying and if correct - you may have a point there. From theller at ctypes.org Fri Jan 4 09:12:09 2008 From: theller at ctypes.org (Thomas Heller) Date: Fri, 04 Jan 2008 15:12:09 +0100 Subject: pydepend (checking dependencies like jdepend) ? In-Reply-To: <3E7E58237D756A4D85E7A36CB8C953ED01E24A@exchange2003.dspace.de> References: <1969e240-9e80-4df1-b085-7956dfa4f7ae@t1g2000pra.googlegroups.com> <71a1c5ae-2051-44ff-998e-a342fa88ffab@e25g2000prg.googlegroups.com> <3E7E58237D756A4D85E7A36CB8C953ED01E24A@exchange2003.dspace.de> Message-ID: Stefan Schukat schrieb: > No, py2exe does not display such information but has an algorithm to > collect such information. > Perhaps this is a starting point for you. If py2exe is run with the -x flag, it does display a cross-reference in a browser window. Thomas From wim at fixnum.org Wed Jan 23 03:36:33 2008 From: wim at fixnum.org (Wim Vander Schelden) Date: Wed, 23 Jan 2008 09:36:33 +0100 Subject: translating Python to Assembler In-Reply-To: References: <6qqcp39mpdl0i9s9vmtkm81cicv8av0i6t@4ax.com> Message-ID: On 1/23/08, Christian Heimes wrote: > > Wim Vander Schelden wrote: > > Python modules and scripts are normally not even compiled, if they have > > been, > > its probably just the Python interpreter packaged with the scripts and > > resources. > > No, that is not correct. Python code is compiled to Python byte code and > execute inside a virtual machine just like Java or C#. It's even > possible to write code with Python assembly and compile the Python > assembly into byte code. > > You most certainly meant: Python code is not compiled into machine code. I didn't know that python uses a VM, I thought it still used an interpretter! You learn something new everyday :) Thanks, Wim -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Wed Jan 23 19:48:42 2008 From: aahz at pythoncraft.com (Aahz) Date: Wed, 23 Jan 2008 16:48:42 -0800 Subject: REMINDER: OSCON 2008 Call for Proposals Message-ID: <20080124004842.GA14395@panix.com> The O'Reilly Open Source Convention (OSCON) is accepting proposals for tutorials and presentations. The submission period ends Feb 4. OSCON 2008 will be in Portland, Oregon July 21-25. For more information and to submit a proposal, see http://conferences.oreilly.com/oscon/ -- 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 see.signature at no.spam Wed Jan 30 11:07:35 2008 From: see.signature at no.spam (Eric Brunel) Date: Wed, 30 Jan 2008 17:07:35 +0100 Subject: Tkinter - incremental input ? References: <60b922F1pnj4bU1@mid.dfncis.de> Message-ID: On Wed, 30 Jan 2008 13:32:00 +0100, Helmut Jarausch wrote: [snip] > While I can bind '' to a callback, I haven't figured out how > to get (and later on set) the cursor within the Entry widget. > In other words I need to know at which character position the last > character was entered. You can get the position of the insertion point with entry.index('insert'), and set it via entry.icursor(index). If you want to do this as the user types, take care to bind to KeyRelease; this way, the character corresponding to the key has already been entered in the entry. BTW, you may also want to automatically select the part that the user hasn't actually typed. This can be done with entry.selection_clear(), then entry.selection_range(start_position, end_position). HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From ckimyt at gmail.com Mon Jan 7 08:21:42 2008 From: ckimyt at gmail.com (Mike) Date: Mon, 7 Jan 2008 05:21:42 -0800 (PST) Subject: How to refer to the current module? Message-ID: I want to do something like the following (let's pretend that this is in file 'driver.py'): #!/bin/env python import sys def foo(): print 'foo' def bar(arg): print 'bar with %r' % arg def main(): getattr(driver, sys.argv[1])(*sys.argv[2:]) if __name__=='__main__': main() Essentially what I'm trying to get at here is dynamic function redirection, like a generic dispatch script. I could call this as python driver.py foo or python driver.py bar 15 and at any time later I can add new functions to driver.py without having to update a dispatch dict or what-have-you. The problem is, 'driver' doesn't exist in main() line 1. If I 'import driver' from the command line, then getattr(driver, ...) works, but it's not bound here. Is there any way around this? Can I somehow scope the 'current module' and give getattr(...) an object that will (at run time) have the appropriate bindings? Thanks in advance for all advice! Mike From ptmcg at austin.rr.com Mon Jan 7 18:15:47 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 7 Jan 2008 15:15:47 -0800 (PST) Subject: Open source English dictionary to use programmatically w/ python References: Message-ID: <43c9e776-b406-4e3e-9ef3-e6d7e574be3c@l6g2000prm.googlegroups.com> On Jan 7, 5:10?pm, dgoldsmith_89 wrote: > > Sorry for my ignorance: I can query an Access DB w/ standard SQL > queries (and this is how I would access it w/ Python)? > > DG If you are running on a Mac, just use sqlite, it's built-in to Python as of v2.5 and you will find more help, documentation, and fellow Python+sqlite users than you will Python+Access. -- Paul From bignose+hates-spam at benfinney.id.au Tue Jan 29 04:37:49 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 29 Jan 2008 20:37:49 +1100 Subject: optional static typing for Python References: <479da584$0$25625$426a74cc@news.free.fr> <69007512-0cd2-47ef-aa4f-65c174326b8c@i29g2000prf.googlegroups.com> Message-ID: <87lk69dlaq.fsf@benfinney.id.au> "Russ P." writes: > I would just like to thank you for reminding me about what losers > hang out perpetually on sites like this one, thinking they are in > some kind of real "community." Being reminded of that will help > prevent me from becoming such a loser myself. No, I didn't say that > all the "regulars" here are losers, but you most certainly are. We're a community largely because we don't tolerate this level of content-free insult. Please find a different forum for this stuff. -- \ "We spend the first twelve months of our children's lives | `\ teaching them to walk and talk and the next twelve years | _o__) telling them to sit down and shut up." -- Phyllis Diller | Ben Finney From mr.cerutti at gmail.com Tue Jan 1 18:54:54 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Tue, 1 Jan 2008 18:54:54 -0500 Subject: pyparsing question In-Reply-To: <8df809a0-1950-4250-a968-2d366f64cdb4@d21g2000prf.googlegroups.com> References: <8df809a0-1950-4250-a968-2d366f64cdb4@d21g2000prf.googlegroups.com> Message-ID: <51302a8c0801011554p16951e8fp1805ad6c3d65621a@mail.gmail.com> On Jan 1, 2008 6:32 PM, hubritic wrote: > I am trying to parse data that looks like this: > > IDENTIFIER TIMESTAMP T C RESOURCE_NAME DESCRIPTION > 2BFA76F6 1208230607 T S SYSPROC SYSTEM > SHUTDOWN BY USER > A6D1BD62 1215230807 I > H Firmware Event > > My problem is that sometimes there is a RESOURCE_NAME and sometimes > not, so I wind up with "Firmware" as my RESOURCE_NAME and "Event" as > my DESCRIPTION. The formating seems to use a set number of spaces. > > The data I have has a fixed number of characters per field, so I could > split it up that way, but wouldn't that defeat the purpose of using a > parser? I am determined to become proficient with pyparsing so I am > using it even when it could be considered overkill; thus, it has gone > past mere utility now, this is a matter of principle! If your data is really in fixed-size columns, then pyparsing is the wrong tool. There's no standard Python tool for reading and writing fixed-length field "flatfile" data files, but it's pretty simple to use named slices to get at the data. identifier = slice(0, 8) timestamp = slice(8, 18) t = slice(18, 21) c = slice(21, 24) resource_name = slice(24, 35) description = slice(35) for line in file: line = line.rstrip("\n") print "id:", line[identifier] print "timestamp:", line[timestamp] ...etc... -- Neil Cerutti -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Wed Jan 9 07:19:52 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 9 Jan 2008 04:19:52 -0800 (PST) Subject: alternating string replace References: <753518eb-693c-4985-9e5f-24906143e98c@s19g2000prg.googlegroups.com> Message-ID: <2a90b41a-2e82-465a-8b97-50ead52dca5b@x69g2000hsx.googlegroups.com> My version, uses a re.sub, plus a function used as an object with a one bit state: from re import sub def repl(o): repl.n = not repl.n return ":" if repl.n else "," repl.n = False print sub("_", repl, "hi_cat_bye_dog_foo_bar_red") Bye, bearophile From ggpolo at gmail.com Wed Jan 16 15:28:07 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 16 Jan 2008 18:28:07 -0200 Subject: paramiko In-Reply-To: <3019696f-cf50-43e2-8534-2ef4ae4de5d9@y5g2000hsf.googlegroups.com> References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> <8142ea9b-7f31-4be5-82c9-487ba60a2755@j78g2000hsd.googlegroups.com> <8ceaad4c-c725-4093-a204-ab09162d4629@c23g2000hsa.googlegroups.com> <685fabb3-c9e8-47ac-84f2-405b831bccad@v4g2000hsf.googlegroups.com> <3019696f-cf50-43e2-8534-2ef4ae4de5d9@y5g2000hsf.googlegroups.com> Message-ID: 2008/1/16, Tarun Kapoor : > On Jan 16, 1:56 pm, "Guilherme Polo" wrote: > > 2008/1/16, Tarun Kapoor : > > > > > > > > > On Jan 16, 12:22 pm, "Guilherme Polo" wrote: > > > > 2008/1/16, Tarun Kapoor : > > > > > > > On Jan 16, 11:38 am, "Guilherme Polo" wrote: > > > > > > 2008/1/16, Tarun Kapoor : > > > > > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across > > > > > > > the connection > > > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > > > > sock.connect((hostname, port)) > > > > > > > > > t = paramiko.Transport(sock) > > > > > > > t.start_client() > > > > > > > key = t.get_remote_server_key() > > > > > > > > > event = threading.Event() > > > > > > > t.auth_password(username=username, password=password, event=event) > > > > > > > event.wait() > > > > > > > > > if not t.is_authenticated(): > > > > > > > print "not authenticated" > > > > > > > > > output: > > > > > > > not authenticated > > > > > > > > This is a different problem I guess, now you are usin get_remote_server_key. > > > > > > And why are you creating event after calling start_client without > > > > > > specifying it ? > > > > > > > > > On Jan 16, 11:11 am, "Guilherme Polo" wrote: > > > > > > > > 2008/1/16, Tarun Kapoor : > > > > > > > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > > > > > > > > > the remote server using an SFTP client I have just to make sure that > > > > > > > > > username and password are working.. This is the code. > > > > > > > > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > > > > > > > > > connection > > > > > > > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > > > > > > > > sock.connect((hostname, port)) > > > > > > > > > > > t = paramiko.Transport(sock) > > > > > > > > > > > event = threading.Event() > > > > > > > > > > > t.start_client(event) > > > > > > > > > > > event.wait(15) > > > > > > > > > > > if not t.is_active(): > > > > > > > > > > > print 'SSH negotiation failed.' > > > > > > > > > > > sys.exit(1) > > > > > > > > > > > else: > > > > > > > > > > > print "SSH negotiation sucessful" > > > > > > > > > > > event.clear() > > > > > > > > > > > t.auth_password(username=username, password=password,event=event) > > > > > > > > > > > if not t.is_authenticated(): > > > > > > > > > > > print "not authenticated" > > > > > > > > > > > output: > > > > > > > > > > > SSH negotiation successful > > > > > > > > > > > not authenticated > > > > > > > > > > > Tarun > > > > > > > > > > > Waterstone Capital Management > > > > > > > > > > > 2 Carlson Parkway, Suite 260 > > > > > > > > > > > Plymouth, MN 55447 > > > > > > > > > > > Direct: 952-697-4123 > > > > > > > > > > > Cell: 612-205-2587 > > > > > > > > > Disclaimer This e-mail and any attachments is confidential and intended > > > > > > > > > solely for the use of the individual(s) to whom it is addressed. Any views > > > > > > > > > or opinions presented are solely those of the author and do not necessarily > > > > > > > > > represent those of Waterstone Capital Management, L.P and affiliates. If you > > > > > > > > > are not the intended recipient, be advised that you have received this > > > > > > > > > e-mail in error and that any use, dissemination, printing, forwarding or > > > > > > > > > copying of this email is strictly prohibited. Please contact the sender if > > > > > > > > > you have received this e-mail in error. You should also be aware that > > > > > > > > > e-mails are susceptible to interference and you should not assume that the > > > > > > > > > contents of this e-mail originated from the sender above or that they have > > > > > > > > > been accurately reproduced in their original form. Waterstone Capital > > > > > > > > > Management, L.P. and affiliates accepts no responsibility for information, > > > > > > > > > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > > > > > > > > > please verify the authenticity with the sender. > > > > > > > > > -- > > > > > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > You are missing an event.wait() after t.auth_password. > > > > > > > > Also, why are you passing this magic value "15" to event.wait() ? That > > > > > > > > parameter is passed to class _Verbose to indicate if debug messages > > > > > > > > should be displayed or not, so typical values would be 0/1 or > > > > > > > > False/True. > > > > > > > > > > -- > > > > > > > > -- Guilherme H. Polo Goncalves > > > > > > > > > -- > > > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > > > -- > > > > > > -- Guilherme H. Polo Goncalves > > > > > > > ok here is the problem... I don't know what is the correct way... The > > > > > only demos i have from the paramiko library use a hostkeyfile. since i > > > > > don't have that i thought i would use the get_remote_key to get the > > > > > key and then connect it using the code in the demo.. But clearly > > > > > nothing is working...I should not HAVE to use the key since i should > > > > > be able to authenticate using the password... > > > > > > > Can you please suggest the right way to go ? > > > > > > You don't need to use key to authenticate using username and password, > > > > indeed. And you don't. Your first email was almost correct, you just > > > > needed to add event.wait() after t.auth_password. It worked here after > > > > doing that change. You can check out my version: > > > > > > import sys > > > > import socket > > > > import paramiko > > > > import threading > > > > > > if len(sys.argv) != 4: > > > > print "%s hostname user password" % sys.argv[0] > > > > sys.exit(1) > > > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > sock.connect((sys.argv[1], 22)) > > > > > > t = paramiko.Transport(sock) > > > > event = threading.Event() > > > > t.start_client(event) > > > > > > event.wait() > > > > > > if not t.is_active(): > > > > print 'SSH negotiation failed.' > > > > sys.exit(1) > > > > else: > > > > print "SSH negotiation sucessful" > > > > > > event.clear() > > > > t.auth_password(username=sys.argv[2], password=sys.argv[3], event=event) > > > > event.wait() > > > > if not t.is_authenticated(): > > > > print "Authentication failed." > > > > else: > > > > print "Authenticated!" > > > > > > t.close() > > > > > > > Thanks for your time ! > > > > > -- > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > > > > -- Guilherme H. Polo Goncalves > > > > > ok i tried the exact same code and here is the output > > > SSH negotiation sucessful > > > Authentication failed. > > > > > I am positive that the username and paddword are correct. ! > > > > I believe paramiko supports only ssh2, so be sure to check if your > > server is not running ssh1. > > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > > -- > > -- Guilherme H. Polo Goncalves > > > The server is running SSH2. > Can you think of any other ideas to troubleshoot ? > > -- > http://mail.python.org/mailman/listinfo/python-list > Take a look at ssh server log would be my next idea. -- -- Guilherme H. Polo Goncalves From bj_666 at gmx.net Tue Jan 22 05:04:54 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Jan 2008 10:04:54 GMT Subject: Question on sort() key function References: <5vlopgF1mv4ekU1@mid.dfncis.de> <7xve5mfdmr.fsf@ruckus.brouhaha.com> <5vlqbjF1kl9cjU1@mid.dfncis.de> <5vlsv7F1n3d1bU1@mid.dfncis.de> Message-ID: <5vlte5F1n19plU3@mid.uni-berlin.de> On Tue, 22 Jan 2008 09:56:55 +0000, Robert Latest wrote: > Peter Otten wrote: >> Robert Latest wrote: >> >> This should work then: >> >> def date_key(f): >> return f.mod_date.toordinal() >> flist.sort(key=date_key) >> >> This can also be written as >> >> flist.sort(key=lambda f: f.mod_date.toordinal()) > > Well, that's almost Paul's (non-working) suggestion above, but it works > because of the parentheses after toordinal. Beats me how both versions can > be valid, anyway. > > To me it's all greek. I grew up with C function pointers, and they > always work. > > robert Suppose `func` is a C function pointer, then foo = func; and foo = func(); have different meanings. It's just the same in Python. First is the function itself, second *calls* the function. Ciao, Marc 'BlackJack' Rintsch From cokofreedom at gmail.com Thu Jan 17 07:35:18 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 17 Jan 2008 04:35:18 -0800 (PST) Subject: Loop in a loop? References: <02e45be1-db8a-438b-a981-d96c53ec9b0e@v17g2000hsa.googlegroups.com> Message-ID: On Jan 17, 1:21 pm, Sacred Heart wrote: > Hi, > I'm new to Python and have come across a problem I don't know how to > solve, enter com.lang.python :) > > I'm writing some small apps to learn the language, and I like it a lot > so far. > > My problem I've stumbled upon is that I don't know how to do what I > want. I want to do a loop in a loop. I think. > > I've got two arrays with some random stuff in, like this. > > array1 = ['one','two','three','four'] > array2 = ['a','b','c','d'] > > I want to loop through array1 and add elements from array2 at the end, > so it looks like this: > > one a > two b > three c > four c > > I'm stuck. I know how to loop through the arrays separatly and print > them, but both at the same time? Hmmm. > > A push in the right direction, anyone? > > R, > SH for i in zip(array1, array2): print i Although I take it you meant four d, the issue with this method is that once you hit the end of one array the rest of the other one is ignored. From ivanlan9 at gmail.com Thu Jan 24 18:58:05 2008 From: ivanlan9 at gmail.com (Ivan Van Laningham) Date: Thu, 24 Jan 2008 16:58:05 -0700 Subject: Problem with Tkinter scrollbar callback In-Reply-To: References: Message-ID: Hi All-- That helps. Doing a get() on the scrollbar before a set(0.0,0.0) returns a 4-tuple: (0.0, 0.0, 0.0, 0.0) ! I did the set(0.0,0.0) and now the callback gets the correct number of arguments. However, I'm still getting the weird behaviour when clicking the arrowheads--and the heads are all I want. They act like they've been set to a keybounce timeout of about a millisecond. ... The arrow click increments the number of cells in a table row (effectively), and it shoots up from 5 to 26 columns almost instantly (that's the internal max I set). Metta, Ivan On Jan 24, 2008 4:27 PM, Russell E. Owen wrote: > In article , > > "Ivan Van Laningham" wrote: > > > Hi All-- > > I'm having two problems with the scrollbar callback on linux systems > > (Fedora 7, Suse 10.1,2 and 3 all exhibit the issues). > > > > Problem one: on Windows, the callback is called with the arguments as > > specified in the doc: "scroll", "1" or "-1", "units". When I run the > > identical code on linux, the callback is invoked with only one > > argument, "1" or "-1". Here's a small program which demos the > > problem: > > > > ========begin============ > > #!/usr/bin/env python > > > > from Tkinter import * > > import sys > > > > def die(event): > > sys.exit(0) > > def sDoit(*args): > > for i in args: > > print "scrollbar:",i, type(i) > > root=Tk() > > f=Frame(root) > > f.pack(expand=1,fill=BOTH) > > button=Button(f,width=25) > > button["text"]="Quit" > > button.bind("
this is in a table, woo-hoo!